[Scummvm-git-logs] scummvm master -> 515d592a48e77def684f0286c028a2201f59b068

dreammaster dreammaster at scummvm.org
Sun Feb 7 00:39:48 UTC 2021


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

Summary:
0faeeb8087 AGS: Skeleton engine
df58db6659 AGS: Added std class implementations and allegro stubs
a60d290a08 AGS: Initial addition of engine/ and shared/ folders
bd6a58d1a1 AGS: Adding ScummVM comment headers
90ec822f76 AGS: Cleaning up header file guard defines
8f6391bb5b COMMON: Added WeakPtr class, refactored SharedPtr
8026e4bb30 AGS: Run astyle formatting
76a2e90366 AGS: Wrapping headers in an AGS3 namespace
d8e471b03c AGS: Changing Common namespace to Shared
a7a9ca0543 AGS: Adding AGS3 namespace to cpp files
6c8789264d AGS: Added shared/util/ folder
b177fe1445 AGS: Added shared/script/
d43369f309 AGS: Adding shared/gui/ folder
b12ea53326 AGS: Added shared/gfx/ and support code
fdcfe8362f AGS: Move allegro from stubs/ to lib/
f4544dff7a AGS: Added shared/ac/ folder
6b8f864134 AGS: Added shared/core/ folder
216657c3ab AGS: Added shared/debugging/ folder
197b2ef34d AGS: Adding shared/game/ folder
9a78e04039 AGS: Beginnings of engine/ inclusion
d8cb72494c AGS: Added engine/gui/ folder
68b3eb52d4 AGS: Added engine/game/ folder
6ce1206bbd AGS: Added engine/font/ folder
ee48881da4 AGS: Added engine/platform/ folder
65a2cf6687 AGS: Added engine/plugin/ folder
c16efc3a1d AGS: Adding engine/script/ folder
3a8ce07088 AGS: gcc compilation fixes
76618e6d38 AGS: Added engine/gfx/ folder
969f4b507c AGS: Warning fixes
3b2728cd52 AGS: Fix some const loss warnings
32eb934454 AGS: Added engine/device/ folder
9dda780dc6 AGS: Added engine/debugging/ folder
ed3476151a AGS: gcc warning fixes
c7793a82fb AGS: std::set implementation now derives from Common::SortedArray
ba9bf10d50 AGS: Added engine/ac/dynobj/ folder
5448c99840 AGS: Added engine/ac/statobj/ folder
fe46be9223 AGS: Added engine/ac/ folder
14b1344aa0 AGS: Warning fixes
12dc2c220f AGS: Added shared/font/ folder
77cdd07d6f AGS: Added engine/media/audio/ folder
a4fd46ecc8 AGS: Added engine/media/video/ folder
69b6cfab29 AGS: Move std/ folder into lib/
cb88fc7a92 AGS: Added platform driver
2a2f3585ef AGS: Added lib/hq2x/ folder
c51cc1dd76 AGS: Add missing files from engine/ac/ to project
94a4ef6e7f AGS: Added shared/game/main_game_file.cpp to project
fcce2aa02d AGS: Added shared/util/stdio_compat.cpp to project
cc8bbe896e AGS: Add in missing code to project
f07fc5d7b8 AGS: Added stubs for DUH player
712ef7ed06 AGS: Adding DUMBFILE methods to project
b5ce4bc97a AGS: Add missing dll stub methods to project
37148c0f19 AGS: Added color blending methods
ceaae27126 AGS: Adding missing methods
04ed871098 AGS: Added missing allegro gfx methods
cf26917b29 AGS: Further adding missing code
536bb13032 AGS: Add further missing lib/ code
1192e1c353 AGS: Add overall main code
8c72948dee AGS: Fix global objects crashing ScummVM on startup
c9351d3a8d AGS: Remove mistake settings from configure.engine
75183a5a03 AGS: gcc compilation fixes
739c02d5c0 AGS: Fix a bunch of warnings about const loss
2df8106340 AGS: Further gcc warning fixes
24ff2a9753 AGS: Add detection for Black Cauldron Remake
7efe9249f8 AGS: Further const loss warning fixes
1b86461eda AGS: Fix const warnings in macro expansions
bb23db380f AGS: Get game filename from detection entry
1f78ef4eb7 AGS: Add tests as an optional sub-engine
2aaf78cf52 AGS: Remove directory logic from startup
255ec51653 AGS: Fix directory/file exists methods
01967d483c AGS: Fix specifying game filename
599b724cfd AGS: Fix opening game filename
071f076665 AGS: Fix tyring to read config file when not present
f4dad65589 AGS: Fix ustrsize stub
e22019dcf4 AGS: Create ScummVM SYSTEM_DRIVER
95703bb526 AGS: Change sound method stubs from errors to warnings
2f8cbfcfef AGS: Set up digi driver detection
89eed25fd0 AGS: Further fixes for audio init
c0913b7ed7 AGS: Properly load fonts via asset manager
377a0ffe7b AGS: Fixes for setup of screen resolutions
00e29a1382 AGS: Fix creating and clearing bitmaps
7d4ef226f9 AGS: Implement glGetIntegerv method
9701be90f2 AGS: Implement load_pcx method
cf969752fe AGS: Allow paletted bitmaps in create_bitmap_ex method
447072fcf2 AGS: Initialize screen with the needed resolution
519004004a AGS: Fix returning GetColorDepth for paletted surfaces
0fabbbed93 AGS: Switch to using software graphics driver
ea07ed59e5 AGS: Rename software graphics driver to ScummVM
8924e8819a AGS: Adding ScummVM graphics init code
f54c799a97 AGS: Fix writing initial save state
da6096e169 AGS: Implement draw_trans_sprite method
137263a6be AGS: Fixes to WaitForNextFrame
7089339362 AGS: Implemented keyboard/mouse event handlers
1cb82fde8c AGS: Palette fixes
2014c3db16 AGS: Another fix for getting bitmap color depths
7463b87bbd AGS: Implemented Allegro PACKFILE
3e190f6c5c AGS: Remove deprecated MIDI_DRIVER
338d08a0cb AGS: Implemented ScummVM MIDI music player
ab7146ed2e AGS: Fix shutdown crash in set_gfx_mode
b2ec154bca AGS: Added detection for AGDI KQ2
edb16471d0 AGS: Added detection for A Tale of Two Kingdoms
e0ddb50c59 AGS: Added framework for implementing AGS plugin DLLs in code
72eec8f220 AGS: Add script method stubs for AgsCreditZ
5a8c96982a AGS: Set ManagedSurface palette when blitting to screen
27775a43d1 AGS: Reimplement std::map from scratch
d2abe022bb AGS: Set palette if needed for other blitting methods
4e675ea29e AGS: Implement clipping methods, fixing rendering of text dialogs
b61dd2c633 AGS: Hook up ScummVM window close to exit game
618e89c704 AGS: Fix free after delete in PosixLibrary unload
732f5bac91 AGS: Disable save_config_file
3155da5ed4 AGS: Allow graceful exit after call to quit
522312989c AGS: Set the transparent color on all created surfaces
527d73e0e6 AGS: Handle sprite transparency for cursors
5aa27892c6 AGS: Implementing drawing code used by pathfinder
f8b95a5d34 AGS: Fix closing ScummVM window on title screen
765f9cbfee AGS: Fix cursor palette intensity
02ddc563fd AGS: Added engine methods for load/save game
1de35ad633 AGS: Adding saveilfe support to FileStream
b71eb2de1f AGS: Fixing keys - upper/lowercase, function keys, etc
6767689c06 AGS: Simplifying passing of script method params to DLL class
0cf3a48ae4 AGS: Saves now has dummy path for clarity, added MetaEngine listSaves
6f7c777a21 AGS: Sound cleanup and hookup to ScummVM decoders
ce606cd25c AGS: Remove deprecated audio classes
aa21b7f735 AGS: Change some TODO warnings to comments
1416b86022 AGS: Implement select_palette & unselect_palette
2447e8b06f AGS: Corrections to saving games
cf99f28036 AGS: Show fatal errors in a GUI message dialog
26adb0b229 AGS: Fix for writing audio to savegames
406d7c5110 AGS: Don't allow audio streams to free cached sound data
e173527290 AGS: gcc compilation fixes
ae7efc5002 AGS: Properly handle transparent pixels in item z order
9b893f1602 AGS: Add AGS credits section
4a9d59e8a9 AGS: Don't show GUI message on exit
e0d73e9dc8 AGS: Implement horizontally flipped sprite draw
6da17f421b AGS: Matching keycodes to Allegro in original
c2e502f771 AGS: Fix assert on ClearRect with invalid coordinates
35497da624 AGS: Fix unreachable code warnings
7097d33268 AGS: Fix some overflow warnings
3d84af6aeb AGS: Fix more unreachable code warnings
cf9bbb2bb2 AGS: Beginnings of new Globals class
daaa9ab6c6 AGS: Mark engine with 16bit requirement
e2469a8cfa AGS: Move globals from ags.cpp to Globals
f432dc29c2 AGS: Move quit globals into Globals
4b40b09ce0 AGS: Move mouse globals to Globals
ec02e1a118 AGS: Move debugger globals to Globals
94add31198 AGS: Fix spurious bool comparisons
2732f63a84 AGS: Use empty() rather than size() == 0
2bbf6d1110 AGS: Compilation fix when tests are enabled
7717131014 AGS: Fix games that write to files in the game folder
5c97a54273 AGS: Implement bitmap saving code needed by KQ2
9d2c67f738 AGS: Fix black box & gfx issues in ATOTK
9ef8af4427 AGS: Implemented Theora video player
a9c456c778 AGS: Add some more detection entries
dbf63c63db AGS: Add override keyword
05e1af053b AGS: Use ScummVM endian macros
712c151498 AGS: Fix ReadDialogs for some AGS versions on 64 bit systems
e0d5aab805 AGS: Remove redundant virtual keywords when override is present
911c54c7e2 AGS: Match the 32-bit PixelFormat to decoded bitmaps
982a708f0f AGS: Move plugins/ folder into AGS3 namespace
03c7491e18 AGS: Fix compilation of VS 64-bit builds
ef4d87b28a AGS: Allow plugins onEvent 64-bit pointers
440a14e565 AGS: Tentative draw_lit_sprite implementation
57e6e684c9 AGS: Fix compilation when theoradec is disabled
304ba31e4b AGS: Fix out of bound crossfade volume
e9dd4d963f AGS: Change game folder consts from String to const char *
2d128fffcd AGS: Fix mapping folder macros like $
ecf601dbb3 AGS: Framework for specifying a specific plugin version a game needs
58acb3579e AGS: Initial import of unmodified other plugins source
8dcf692ce5 AGS: Added AGSFlashlight plugin
8659371368 AGS: Fix volume range in SOUNDCLIP::get_volume
372284a67e AGS: Fix game data parser for versions between 2.6 and 2.7.1
e5b3b38dad AGS: Added AGSBlend plugin
f46df1bb90 AGS: Added AGSPalRender plugin
17341f6133 AGS: Added AGSParallax plugin
64224bb59d AGS: Make AGSParallax plugin endian safe
c6824e1caf AGS: Added AGSSnowRain plugin
08caa53082 AGS: Made AGSSnowRain endian safe
b1b1e067f9 AGS: Change AGSParallax plugin to use save serializer
a11cab9a50 AGS: Added AGSSpriteFont plugin
8bc249b99f AGS: gcc compilation fixes
d6b8c21557 AGS: Merged engine/plugin/ into plugins/ folder
57a1cd9580 AGS: Added AGSCredits 1.1 SetCredits method
0bad8f3969 AGS: Implementing AGSCreditz ScrollCredits
be2206d879 AGS: Hook up loading savegames from launcher
e2878645b5 AGS: Added savegame thumbnails
f41fdec782 AGS: Implement GMM saving & loading
3813c6db5e AGS: Cleanup of transparency color in Allegro stubs
420cee48a5 GRAPHICS: Allow ManagedSurface blitting to ignore transparency
81d891ebb0 GRAPHICS: ManagedSurface transBlitFrom ignore alpha matching transColor
8e192f5ce9 AGS: Fix rendering of player in KQ2+
8ec4829dcb AGS: Added fallback detector
a94af81188 AGS: Added tool to scan folders and build detection entries
175735f727 AGS: Fixes for game scanner tool
81af425224 AGS: Added all games from agsarchives.com to detection table
ef8a01baee AGS: Fix compiler warnings
f646ceb889 AGS: Add listing of some pre-2.5 games to game scanner
8a5a0e30cd AGS: In progress adding pre-2.5 AGS game detection entries
5023339db9 AGS: More pre 2.5 detection entries
85cba02c60 AGS: Further groupings for detection table
6efe97aaf9 AGS: Cleanup of demo detection entries
46fdf3bf50 AGS: Savegame screenshots now exclude in-game save dialogs
5e8e40ddc6 AGS: Cleanup of qfg2 vga detection entries
47b2538384 AGS: Added AGS contributors to credits.pl
88fbbbad64 AGS: Minor detection table cleanups
9c74ac0f97 AGS: Show md5 when AGS game found in fallbackDetect
211e5d7e90 AGS: Further separate methods in  two AgsCreditz classes
9ea3e804c8 AGS: Implemented AGSCreditz overall script methods
a24e8b175a AGS: Methods to read/write arrays that have safe save/load methods
0c2adad99d AGS: Further cleaning up read/write structure arrays
6fa72f4b49 AGS: Fix savegame magic number to match standalone savegames
298a266c37 AGS: Starting to add AgsCreditz 2.0 support methods
f1830f63d7 AGS: SHow GUI error dialog for unsupported games
0589f9a817 GRAPHICS: Support 24-bit surfaces as dest for blitFrom
6a5bb2c48f AGS: Fix starting up early 2.5 paletted games
de985f566e AGS: Remove unused local
515d592a48 AGS: Fix std::unordered_map insert to ignore duplicates


Commit: 0faeeb80879dc5026de17074a0c09889ad6ac18c
    https://github.com/scummvm/scummvm/commit/0faeeb80879dc5026de17074a0c09889ad6ac18c
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Skeleton engine

Based on AGS 3.5.0.27

Changed paths:
  A engines/ags/ags.cpp
  A engines/ags/ags.h
  A engines/ags/configure.engine
  A engines/ags/detection.cpp
  A engines/ags/detection.h
  A engines/ags/detection_tables.h
  A engines/ags/metaengine.cpp
  A engines/ags/metaengine.h
  A engines/ags/module.mk


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
new file mode 100644
index 0000000000..133e2ec915
--- /dev/null
+++ b/engines/ags/ags.cpp
@@ -0,0 +1,59 @@
+/* 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 "ags/ags.h"
+#include "ags/detection.h"
+#include "common/scummsys.h"
+#include "common/config-manager.h"
+#include "common/debug-channels.h"
+#include "common/events.h"
+#include "common/file.h"
+
+namespace AGS {
+
+AGSEngine *g_vm;
+
+/*------------------------------------------------------------------*/
+
+AGSEngine::AGSEngine(OSystem *syst, const AGSGameDescription *gameDesc) : Engine(syst),
+		_gameDescription(gameDesc), _randomSource("AGS") {
+	g_vm = this;
+	DebugMan.addDebugChannel(kDebugPath, "Path", "Pathfinding debug level");
+	DebugMan.addDebugChannel(kDebugGraphics, "Graphics", "Graphics debug level");
+}
+
+AGSEngine::~AGSEngine() {
+}
+
+uint32 AGSEngine::getFeatures() const {
+	return _gameDescription->desc.flags;
+}
+
+Common::Error AGSEngine::run() {
+	return Common::kNoError;
+}
+
+SaveStateList AGSEngine::listSaves() const {
+	return getMetaEngine().listSaves(_targetName.c_str());
+}
+
+} // namespace AGS
diff --git a/engines/ags/ags.h b/engines/ags/ags.h
new file mode 100644
index 0000000000..fce049973e
--- /dev/null
+++ b/engines/ags/ags.h
@@ -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.
+ *
+ */
+
+#ifndef AGS_AGS_H
+#define AGS_AGS_H
+
+#include "common/scummsys.h"
+#include "common/system.h"
+#include "common/error.h"
+#include "common/random.h"
+#include "common/hash-str.h"
+#include "common/util.h"
+#include "engines/engine.h"
+#include "engines/savestate.h"
+#include "graphics/surface.h"
+
+namespace AGS {
+
+#define SCREEN_WIDTH 320
+#define SCREEN_HEIGHT 200
+
+enum AGSDebugChannels {
+	kDebugPath     = 1 << 0,
+	kDebugGraphics = 1 << 1
+};
+
+struct AGSGameDescription;
+
+class AGSEngine : public Engine {
+private:
+	const AGSGameDescription *_gameDescription;
+	Common::RandomSource _randomSource;
+protected:
+	// Engine APIs
+	virtual Common::Error run();
+public:
+	AGSEngine(OSystem *syst, const AGSGameDescription *gameDesc);
+	virtual ~AGSEngine();
+	void GUIError(const Common::String &msg);
+
+	void set_window_title(const char *str) {
+		// No implementation
+	}
+
+	uint32 getFeatures() const;
+
+	/**
+	 * Returns the current list of savegames
+	 */
+	SaveStateList listSaves() const;
+
+	/**
+	 * Gets a random number
+	 */
+	uint32 getRandomNumber(uint maxNum) {
+		return _randomSource.getRandomNumber(maxNum);
+	}
+
+	/**
+	 * Sets the random number seed
+	 */
+	void setRandomNumberSeed(uint32 seed) {
+		_randomSource.setSeed(seed);
+	}
+};
+
+extern AGSEngine *g_vm;
+
+} // namespace AGS
+
+#endif
diff --git a/engines/ags/configure.engine b/engines/ags/configure.engine
new file mode 100644
index 0000000000..55cba93bb4
--- /dev/null
+++ b/engines/ags/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 ags "Adventure Game Studio" no "" "" "cxx11"
diff --git a/engines/ags/detection.cpp b/engines/ags/detection.cpp
new file mode 100644
index 0000000000..898cc29fb7
--- /dev/null
+++ b/engines/ags/detection.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 "base/plugins.h"
+#include "ags/detection.h"
+#include "ags/detection_tables.h"
+
+AGSMetaEngineDetection::AGSMetaEngineDetection() : AdvancedMetaEngineDetection(AGS::GAME_DESCRIPTIONS,
+	sizeof(AGS::AGSGameDescription), AGS::AGS_GAMES) {
+	static const char *const DIRECTORY_GLOBS[2] = { "usecode", 0 };
+	_maxScanDepth = 2;
+	_directoryGlobs = DIRECTORY_GLOBS;
+}
+
+REGISTER_PLUGIN_STATIC(AGS_DETECTION, PLUGIN_TYPE_ENGINE_DETECTION, AGSMetaEngineDetection);
diff --git a/engines/ags/detection.h b/engines/ags/detection.h
new file mode 100644
index 0000000000..f916f2f2a1
--- /dev/null
+++ b/engines/ags/detection.h
@@ -0,0 +1,54 @@
+/* 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 AGS_DETECTION_H
+#define AGS_DETECTION_H
+
+#include "engines/advancedDetector.h"
+
+namespace AGS {
+
+struct AGSGameDescription {
+	ADGameDescription desc;
+};
+
+} // namespace AGS
+
+class AGSMetaEngineDetection : public AdvancedMetaEngineDetection {
+public:
+	AGSMetaEngineDetection();
+	~AGSMetaEngineDetection() override {}
+
+	virtual const char *getEngineId() const {
+		return "ags";
+	}
+
+	virtual const char *getName() const {
+		return "Adventure Game Studio";
+	}
+
+	virtual const char *getOriginalCopyright() const {
+		return "";
+	}
+};
+
+#endif
diff --git a/engines/ags/detection_tables.h b/engines/ags/detection_tables.h
new file mode 100644
index 0000000000..29a04e180b
--- /dev/null
+++ b/engines/ags/detection_tables.h
@@ -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.
+ *
+ */
+
+namespace AGS {
+
+static const PlainGameDescriptor AGS_GAMES[] = {
+	{ "ags", "Adventure Game Studio Game" },
+	{ 0, 0 }
+};
+
+static const AGSGameDescription GAME_DESCRIPTIONS[] = {
+	{ AD_TABLE_END_MARKER }
+};
+
+} // namespace AGS
diff --git a/engines/ags/metaengine.cpp b/engines/ags/metaengine.cpp
new file mode 100644
index 0000000000..bb737c24f0
--- /dev/null
+++ b/engines/ags/metaengine.cpp
@@ -0,0 +1,42 @@
+/* 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 "ags/metaengine.h"
+#include "ags/detection.h"
+#include "ags/ags.h"
+
+const char *AGSMetaEngine::getName() const {
+	return "ags";
+}
+
+Common::Error AGSMetaEngine::createInstance(OSystem *syst, Engine **engine, const ADGameDescription *desc) const {
+	const AGS::AGSGameDescription *gd = (const AGS::AGSGameDescription *)desc;
+
+	*engine = new AGS::AGSEngine(syst, gd);
+	return Common::kNoError;
+}
+
+#if PLUGIN_ENABLED_DYNAMIC(AGS)
+REGISTER_PLUGIN_DYNAMIC(AGS, PLUGIN_TYPE_ENGINE, AGSMetaEngine);
+#else
+REGISTER_PLUGIN_STATIC(AGS, PLUGIN_TYPE_ENGINE, AGSMetaEngine);
+#endif
diff --git a/engines/ags/metaengine.h b/engines/ags/metaengine.h
new file mode 100644
index 0000000000..b8a6cd8c84
--- /dev/null
+++ b/engines/ags/metaengine.h
@@ -0,0 +1,37 @@
+/* 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 AGS_METAENGINE_H
+#define AGS_METAENGINE_H
+
+#include "engines/advancedDetector.h"
+
+#define MAX_SAVES 99
+
+class AGSMetaEngine : public AdvancedMetaEngine {
+public:
+	const char *getName() const override;
+
+	virtual Common::Error createInstance(OSystem *syst, Engine **engine, const ADGameDescription *desc) const;
+};
+
+#endif
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
new file mode 100644
index 0000000000..92457bcd17
--- /dev/null
+++ b/engines/ags/module.mk
@@ -0,0 +1,17 @@
+MODULE := engines/ags
+
+MODULE_OBJS = \
+	ags.o \
+	metaengine.o
+
+
+# This module can be built as a plugin
+ifeq ($(ENABLE_AGS), DYNAMIC_PLUGIN)
+PLUGIN := 1
+endif
+
+# Include common rules
+include $(srcdir)/rules.mk
+
+# Detection objects
+DETECT_OBJS += $(MODULE)/detection.o


Commit: df58db66597f921f2778b0759746a175f2218edf
    https://github.com/scummvm/scummvm/commit/df58db66597f921f2778b0759746a175f2218edf
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added std class implementations and allegro stubs

Changed paths:
  A engines/ags/std/array.h
  A engines/ags/std/chrono.h
  A engines/ags/std/functional.h
  A engines/ags/std/limits.h
  A engines/ags/std/list.h
  A engines/ags/std/map.h
  A engines/ags/std/memory.h
  A engines/ags/std/mutex.h
  A engines/ags/std/set.h
  A engines/ags/std/thread.h
  A engines/ags/std/type_traits.h
  A engines/ags/std/utility.h
  A engines/ags/std/vector.h
  A engines/ags/std/xutility.h
  A engines/ags/stubs/allegro.cpp
  A engines/ags/stubs/allegro.h
  A engines/ags/stubs/allegro/alconfig.h
  A engines/ags/stubs/allegro/base.h
  A engines/ags/stubs/allegro/color.cpp
  A engines/ags/stubs/allegro/color.h
  A engines/ags/stubs/allegro/config.cpp
  A engines/ags/stubs/allegro/config.h
  A engines/ags/stubs/allegro/digi.cpp
  A engines/ags/stubs/allegro/digi.h
  A engines/ags/stubs/allegro/error.cpp
  A engines/ags/stubs/allegro/error.h
  A engines/ags/stubs/allegro/file.cpp
  A engines/ags/stubs/allegro/file.h
  A engines/ags/stubs/allegro/fixed.cpp
  A engines/ags/stubs/allegro/fixed.h
  A engines/ags/stubs/allegro/gfx.cpp
  A engines/ags/stubs/allegro/gfx.h
  A engines/ags/stubs/allegro/keyboard.cpp
  A engines/ags/stubs/allegro/keyboard.h
  A engines/ags/stubs/allegro/midi.cpp
  A engines/ags/stubs/allegro/midi.h
  A engines/ags/stubs/allegro/mouse.cpp
  A engines/ags/stubs/allegro/mouse.h
  A engines/ags/stubs/allegro/sound.cpp
  A engines/ags/stubs/allegro/sound.h
  A engines/ags/stubs/allegro/system.cpp
  A engines/ags/stubs/allegro/system.h
  A engines/ags/stubs/allegro/unicode.cpp
  A engines/ags/stubs/allegro/unicode.h
    engines/ags/module.mk


diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 92457bcd17..5256e3b69e 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -2,7 +2,21 @@ MODULE := engines/ags
 
 MODULE_OBJS = \
 	ags.o \
-	metaengine.o
+	metaengine.o \
+	stubs/allegro.o \
+	stubs/allegro/color.o \
+	stubs/allegro/config.o \
+	stubs/allegro/digi.o \
+	stubs/allegro/error.o \
+	stubs/allegro/file.o \
+	stubs/allegro/fixed.o \
+	stubs/allegro/gfx.o \
+	stubs/allegro/keyboard.o \
+	stubs/allegro/midi.o \
+	stubs/allegro/mouse.o \
+	stubs/allegro/sound.o \
+	stubs/allegro/system.o \
+	stubs/allegro/unicode.o
 
 
 # This module can be built as a plugin
diff --git a/engines/ags/std/array.h b/engines/ags/std/array.h
new file mode 100644
index 0000000000..4505a669f6
--- /dev/null
+++ b/engines/ags/std/array.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 AGS_STD_ARRAY_H
+#define AGS_STD_ARRAY_H
+
+#include "common/array.h"
+
+namespace AGS3 {
+namespace std {
+
+template<class T>
+class array : public Common::Array<T> {
+public:
+	array() : Common::Array<T>() {
+	}
+	array(size_t size) : Common::Array<T>() {
+		Common::Array<T>::resize(size);
+	}
+};
+
+} // namespace std
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/std/chrono.h b/engines/ags/std/chrono.h
new file mode 100644
index 0000000000..5bbb2b03fd
--- /dev/null
+++ b/engines/ags/std/chrono.h
@@ -0,0 +1,85 @@
+/* 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 AGS_STD_CHRONO_H
+#define AGS_STD_CHRONO_H
+
+#include "common/system.h"
+
+namespace AGS3 {
+namespace std {
+
+namespace chrono {
+
+typedef uint32 milliseconds;
+
+struct system_clock {
+};
+
+
+struct steady_clock { // wraps QueryPerformanceCounter
+	using rep = uint32;
+	using period = milliseconds;
+	using duration = milliseconds;
+	using time_point = uint32;
+	static constexpr bool is_steady = true;
+
+	static time_point now() { // get current time
+		return g_system->getMillis();
+	}
+};
+
+using high_resolution_clock = steady_clock;
+
+class duration {
+private:
+	uint32 _value;
+public:
+	duration() : _value(0) {
+	}
+	duration(uint32 value) : _value(value) {
+	}
+
+	size_t count() const {
+		// durations for ScummVM are hardcoded to be in milliseconds
+		return 1000;
+	}
+
+	operator milliseconds() const {
+		return _value;
+	}
+};
+
+template<class T>
+duration duration_cast(T param);
+
+template<milliseconds>
+duration duration_cast(milliseconds param) {
+	return duration(param);
+}
+
+} // namespace chrono
+
+} // namespace std
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/std/functional.h b/engines/ags/std/functional.h
new file mode 100644
index 0000000000..e83b997020
--- /dev/null
+++ b/engines/ags/std/functional.h
@@ -0,0 +1,45 @@
+/* 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 AGS_STD_FUNCTIONAL_H
+#define AGS_STD_FUNCTIONAL_H
+
+namespace AGS3 {
+namespace std {
+
+template <class _Arg, class _Result>
+struct unary_function { // base class for unary functions
+	using argument_type = _Arg;
+	using result_type = _Result;
+};
+
+template <class _Arg1, class _Arg2, class _Result>
+struct binary_function { // base class for binary functions
+	using first_argument_type = _Arg1;
+	using second_argument_type = _Arg2;
+	using result_type = _Result;
+};
+
+} // namespace std
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/std/limits.h b/engines/ags/std/limits.h
new file mode 100644
index 0000000000..31e6cf6ad9
--- /dev/null
+++ b/engines/ags/std/limits.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.
+ *
+ */
+
+#include <cmath>
+
+#ifndef AGS_STD_LIMITS_H
+#define AGS_STD_LIMITS_H
+
+namespace AGS3 {
+namespace std {
+
+class _Num_base {
+};
+
+template <class _Ty>
+class numeric_limits : public _Num_base {
+};
+
+template <>
+class numeric_limits<float> {
+public:
+	static constexpr float quiet_NaN() {
+		return NAN;
+	}
+};
+
+} // namespace std
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/std/list.h b/engines/ags/std/list.h
new file mode 100644
index 0000000000..5694dfc64a
--- /dev/null
+++ b/engines/ags/std/list.h
@@ -0,0 +1,77 @@
+/* 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 AGS_STD_LIST_H
+#define AGS_STD_LIST_H
+
+#include "common/list.h"
+
+namespace AGS3 {
+namespace std {
+
+template<class T>
+class list : public Common::List<T> {
+public:
+	struct reverse_iterator {
+	private:
+		typename Common::List<T>::iterator _it;
+	public:
+		reverse_iterator(typename Common::List<T>::iterator it) : _it(it) {
+		}
+		reverse_iterator() {
+		}
+
+		T operator*() const {
+			return *_it;
+		}
+
+		reverse_iterator &operator++() {
+			--_it;
+			return *this;
+		}
+
+		bool operator==(const reverse_iterator &rhs) {
+			return _it == rhs._it;
+		}
+		bool operator!=(const reverse_iterator &rhs) {
+			return _it != rhs._it;
+		}
+	};
+public:
+	typename Common::List<T>::iterator insert(typename Common::List<T>::iterator pos,
+		const T &element) {
+		Common::List<T>::insert(pos, element);
+		return pos;
+	}
+
+	reverse_iterator rbegin() {
+		return reverse_iterator(Common::List<T>::reverse_begin());
+	}
+	reverse_iterator rend() {
+		return reverse_iterator(Common::List<T>::end());
+	}
+};
+
+} // namespace std
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/std/map.h b/engines/ags/std/map.h
new file mode 100644
index 0000000000..5899948db3
--- /dev/null
+++ b/engines/ags/std/map.h
@@ -0,0 +1,53 @@
+/* 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 AGS_STD_MAP_H
+#define AGS_STD_MAP_H
+
+#include "common/hashmap.h"
+#include "ags/std/utility.h"
+
+namespace AGS3 {
+namespace std {
+
+template<class Key, class Val, class HashFunc = Common::Hash<Key>,
+class EqualFunc = Common::EqualTo<Key> >
+class map : public Common::HashMap<Key, Val, HashFunc, EqualFunc> {
+public:
+	void insert(pair<Key, Val> elem) {
+		this->operator[](elem.first) = elem.second;
+	}
+};
+
+template<class Key, class Val, class HashFunc = Common::Hash<Key>,
+	class EqualFunc = Common::EqualTo<Key> >
+class unordered_map : public Common::HashMap<Key, Val, HashFunc, EqualFunc> {
+public:
+	void insert(pair<Key, Val> elem) {
+		this->operator[](elem.first) = elem.second;
+	}
+};
+
+} // namespace std
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/std/memory.h b/engines/ags/std/memory.h
new file mode 100644
index 0000000000..c33d945d76
--- /dev/null
+++ b/engines/ags/std/memory.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 AGS_STD_MEMORY_H
+#define AGS_STD_MEMORY_H
+
+#include "common/ptr.h"
+#include "common/textconsole.h"
+
+namespace AGS3 {
+namespace std {
+
+template<class T>
+using shared_ptr = Common::SharedPtr<T>;
+
+template<class T>
+using weak_ptr = Common::WeakPtr<T>;
+
+template<typename T, class DL = Common::DefaultDeleter<T> >
+using unique_ptr = Common::ScopedPtr<T, DL>;
+
+} // namespace std
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/std/mutex.h b/engines/ags/std/mutex.h
new file mode 100644
index 0000000000..4a3352d8f1
--- /dev/null
+++ b/engines/ags/std/mutex.h
@@ -0,0 +1,37 @@
+/* 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 AGS_STD_MUTEX_H
+#define AGS_STD_MUTEX_H
+
+#include "common/mutex.h"
+
+namespace AGS3 {
+namespace std {
+
+class recursive_mutex : public Common::Mutex {
+};
+
+} // namespace std
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/std/set.h b/engines/ags/std/set.h
new file mode 100644
index 0000000000..30b39c0421
--- /dev/null
+++ b/engines/ags/std/set.h
@@ -0,0 +1,123 @@
+/* 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 AGS_STD_SET_H
+#define AGS_STD_SET_H
+
+namespace AGS3 {
+namespace std {
+
+template<class T>
+class set {
+	struct Comparitor {
+		bool operator()(const T &a, const T &b) const {
+			return a == b;
+		}
+	};
+
+	class Items : public Common::Array<T> {
+	public:
+		void swap(Items &arr) {
+			SWAP(this->_capacity, arr._capacity);
+			SWAP(this->_size, arr._size);
+			SWAP(this->_storage, arr._storage);
+		}
+	};
+private:
+	Items _items;
+	Comparitor _comparitor;
+public:
+	typedef T *iterator;
+	typedef const T *const_iterator;
+
+	iterator begin() { return _items.begin(); }
+	iterator end() { return _items.end(); }
+	const_iterator begin() const { return _items.begin(); }
+	const_iterator end() const { return _items.end(); }
+
+	/**
+	 * Clear the set
+	 */
+	void clear() {
+		_items.clear();
+	}
+
+	/**
+	 * Inserts a new item
+	 */
+	void insert(T val) {
+		_items.push_back(val);
+		Common::sort(begin(), end(), _comparitor);
+	}
+
+	/**
+	 * Inserts a range of items
+	 */
+	void insert(iterator first, iterator last) {
+		for (; first != last; ++first)
+			_items.push_back(*first);
+		Common::sort(begin(), end(), _comparitor);
+	}
+
+	/**
+	 * Swaps a set
+	 */
+	void swap(set<T> &arr) {
+		_items.swap(arr);
+	}
+
+	/**
+	 * Find an item
+	 */
+	iterator find(const T item) {
+		iterator it = begin();
+		for (; it != end() && *it != item; ++it) {}
+		return it;
+	}
+	const_iterator find(const T item) const {
+		const_iterator it = begin();
+		for (; it != end() && *it != item; ++it) {
+		}
+		return it;
+	}
+	bool empty() const {
+		return _items.empty();
+	}
+
+	/**
+	 * Returns the number of matching entries
+	 */
+	size_t count(const T item) const {
+		size_t total = 0;
+		for (const_iterator it = begin(); it != end(); ++it) {
+			if (*it == item)
+				++total;
+		}
+
+		return total;
+	}
+};
+
+} // namespace std
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/std/thread.h b/engines/ags/std/thread.h
new file mode 100644
index 0000000000..46be465c51
--- /dev/null
+++ b/engines/ags/std/thread.h
@@ -0,0 +1,61 @@
+/* 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 AGS_STD_THREAD_H
+#define AGS_STD_THREAD_H
+
+#include "common/textconsole.h"
+
+namespace AGS3 {
+namespace std {
+
+class thread {
+public:
+	template <class _Fn, class... _Args>
+	explicit thread(_Fn &&_Fx, _Args &&... _Ax) {
+		warning("TODO: thread::constructor");
+	}
+
+	thread() {
+		warning("TODO: thread::constructor");
+	}
+
+	void join() {
+		warning("TODO: thread::join");
+	}
+	bool joinable() const {
+		warning("TODO: thread::joinable");
+		return true;
+	}
+};
+
+class this_thread {
+public:
+	static void yield() {
+		warning("TODO: this_thread::yield");
+	}
+};
+
+} // namespace std
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/std/type_traits.h b/engines/ags/std/type_traits.h
new file mode 100644
index 0000000000..564a663ce6
--- /dev/null
+++ b/engines/ags/std/type_traits.h
@@ -0,0 +1,51 @@
+/* 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 AGS_STD_TYPE_TRAITS_H
+#define AGS_STD_TYPE_TRAITS_H
+
+namespace AGS3 {
+namespace std {
+
+// STRUCT TEMPLATE remove_extent
+template <class _Ty>
+struct remove_extent { // remove array extent
+	using type = _Ty;
+};
+
+template <class _Ty, size_t _Ix>
+struct remove_extent<_Ty[_Ix]> {
+	using type = _Ty;
+};
+
+template <class _Ty>
+struct remove_extent<_Ty[]> {
+	using type = _Ty;
+};
+
+template <class _Ty>
+using remove_extent_t = typename remove_extent<_Ty>::type;
+
+} // namespace std
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/std/utility.h b/engines/ags/std/utility.h
new file mode 100644
index 0000000000..241a332a98
--- /dev/null
+++ b/engines/ags/std/utility.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 AGS_STD_UTILITY_H
+#define AGS_STD_UTILITY_H
+
+namespace AGS3 {
+namespace std {
+
+template<class T1, class T2>
+struct pair {
+	T1 first;
+	T2 second;
+
+	pair() {
+	}
+	pair(T1 first_, T2 second_) : first(first_), second(second_) {
+	}
+};
+
+template< class T1, class T2 >
+pair<T1, T2> make_pair(T1 first, T2 second) {
+	return pair<T1, T2>(first, second);
+}
+
+} // namespace std
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/std/vector.h b/engines/ags/std/vector.h
new file mode 100644
index 0000000000..745fb20bd6
--- /dev/null
+++ b/engines/ags/std/vector.h
@@ -0,0 +1,173 @@
+/* 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 AGS_STD_VECTOR_H
+#define AGS_STD_VECTOR_H
+
+#include "common/array.h"
+
+namespace AGS3 {
+namespace std {
+
+template<class T>
+class vector : public Common::Array<T> {
+public:
+	struct reverse_iterator {
+	private:
+		vector<T> *_owner;
+		int _index;
+	public:
+		reverse_iterator(vector<T> *owner, int index) : _owner(owner), _index(index) {
+		}
+		reverse_iterator() : _owner(0), _index(-1) {
+		}
+
+		T &operator*() {
+			return (*_owner)[_index];
+		}
+
+		reverse_iterator &operator++() {
+			--_index;
+			return *this;
+		}
+
+		bool operator==(const reverse_iterator &rhs) {
+			return _owner == rhs._owner && _index == rhs._index;
+		}
+		bool operator!=(const reverse_iterator &rhs) {
+			return !operator==(rhs);
+		}
+	};
+
+	struct const_reverse_iterator {
+	private:
+		const vector<T> *_owner;
+		int _index;
+	public:
+		const_reverse_iterator(const vector<T> *owner, int index) : _owner(owner), _index(index) {
+		}
+		const_reverse_iterator() : _owner(0), _index(-1) {
+		}
+
+		const T operator*() const {
+			return (*_owner)[_index];
+		}
+
+		const_reverse_iterator &operator++() {
+			--_index;
+			return *this;
+		}
+
+		bool operator==(const const_reverse_iterator &rhs) {
+			return _owner == rhs._owner && _index == rhs._index;
+		}
+		bool operator!=(const const_reverse_iterator &rhs) {
+			return !operator==(rhs);
+		}
+	};
+public:
+	typedef T reference;
+	typedef const T const_reference;
+
+	vector() : Common::Array<T>() {
+	}
+	vector(size_t newSize) : Common::Array<T>() {
+		Common::Array<T>::resize(newSize);
+	}
+	vector(size_t newSize, const T elem) {
+		resize(newSize, elem);
+	}
+
+	typename Common::Array<T>::iterator erase(typename Common::Array<T>::iterator pos) {
+		return Common::Array<T>::erase(pos);
+	}
+
+	typename Common::Array<T>::iterator erase(typename Common::Array<T>::iterator first,
+		typename Common::Array<T>::iterator last) {
+		Common::copy(last, this->_storage + this->_size, first);
+
+		int count = (last - first);
+		this->_size -= count;
+
+		// We also need to destroy the objects beyond the new size
+		for (uint idx = this->_size; idx < (this->_size + count); ++idx)
+			this->_storage[idx].~T();
+
+		return first;
+	}
+
+	void swap(vector &arr) {
+		SWAP(this->_capacity, arr._capacity);
+		SWAP(this->_size, arr._size);
+		SWAP(this->_storage, arr._storage);
+	}
+
+	/**
+	 * Rotates the array so that the item pointed to by the iterator becomes
+	 * the first item, and the predeceding item becomes the last one
+	 */
+	void rotate(Common::Array<T>::iterator &it) {
+		if (it != Common::Array<T>::end()) {
+			size_t count = it - Common::Array<T>::begin();
+			for (size_t ctr = 0; ctr < count; ++ctr) {
+				Common::Array<T>::push_back(Common::Array<T>::front());
+				Common::Array<T>::remove_at(0);
+			}
+		}
+	}
+
+	reverse_iterator rbegin() {
+		return reverse_iterator(this, (int)Common::Array<T>::size() - 1);
+	}
+	reverse_iterator rend() {
+		return reverse_iterator(this, -1);
+	}
+	const_reverse_iterator rbegin() const {
+		return const_reverse_iterator(this, (int)Common::Array<T>::size() - 1);
+	}
+	const_reverse_iterator rend() const {
+		return const_reverse_iterator(this, -1);
+	}
+
+	void pop_front() {
+		Common::Array<T>::remove_at(0);
+	}
+
+	void resize(size_t newSize) {
+		Common::Array<T>::resize(newSize);
+	}
+	void resize(size_t newSize, const T elem) {
+		size_t oldSize = Common::Array<T>::size();
+		resize(newSize);
+		for (size_t idx = oldSize; idx < newSize; ++idx)
+			this->operator[](idx) = elem;
+	}
+
+	T at(size_t index) const {
+		return (*this)[index];
+	}
+};
+
+} // namespace std
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/std/xutility.h b/engines/ags/std/xutility.h
new file mode 100644
index 0000000000..ac5627fbdb
--- /dev/null
+++ b/engines/ags/std/xutility.h
@@ -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.
+ *
+ */
+
+#ifndef AGS_STD_XUTILITY_H
+#define AGS_STD_XUTILITY_H
+
+#include "common/algorithm.h"
+
+namespace AGS3 {
+namespace std {
+
+} // namespace std
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/stubs/allegro.cpp b/engines/ags/stubs/allegro.cpp
new file mode 100644
index 0000000000..44f7099b30
--- /dev/null
+++ b/engines/ags/stubs/allegro.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 "ags/stubs/allegro.h"
+
+namespace AGS3 {
+
+int install_allegro() {
+	return 0;
+}
+
+void allegro_exit() {
+}
+
+} // namespace AGS3
diff --git a/engines/ags/stubs/allegro.h b/engines/ags/stubs/allegro.h
new file mode 100644
index 0000000000..6d3aed6b22
--- /dev/null
+++ b/engines/ags/stubs/allegro.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 AGS_STUBS_ALLEGRO_H
+#define AGS_STUBS_ALLEGRO_H
+
+#include "ags/stubs/allegro/alconfig.h"
+#include "ags/stubs/allegro/base.h"
+#include "ags/stubs/allegro/color.h"
+#include "ags/stubs/allegro/config.h"
+#include "ags/stubs/allegro/digi.h"
+#include "ags/stubs/allegro/error.h"
+#include "ags/stubs/allegro/file.h"
+#include "ags/stubs/allegro/fixed.h"
+#include "ags/stubs/allegro/gfx.h"
+#include "ags/stubs/allegro/keyboard.h"
+#include "ags/stubs/allegro/midi.h"
+#include "ags/stubs/allegro/mouse.h"
+#include "ags/stubs/allegro/sound.h"
+#include "ags/stubs/allegro/system.h"
+#include "ags/stubs/allegro/unicode.h"
+
+namespace AGS3 {
+
+extern int install_allegro();
+extern void allegro_exit();
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/stubs/allegro/alconfig.h b/engines/ags/stubs/allegro/alconfig.h
new file mode 100644
index 0000000000..88a154b8ea
--- /dev/null
+++ b/engines/ags/stubs/allegro/alconfig.h
@@ -0,0 +1,79 @@
+/* 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 AGS_STUBS_ALLEGRO_ALCONFIG_H
+#define AGS_STUBS_ALLEGRO_ALCONFIG_H
+
+namespace AGS3 {
+
+
+#ifndef INLINE
+#define INLINE
+#endif
+
+#ifndef RET_VOLATILE
+#define RET_VOLATILE   volatile
+#endif
+
+#ifndef ZERO_SIZE_ARRAY
+#define ZERO_SIZE_ARRAY(type, name)             type name[]
+#endif
+
+#ifndef AL_CONST
+#define AL_CONST
+#endif
+
+#ifndef AL_VAR
+#define AL_VAR(type, name)                      extern type name
+#endif
+
+#ifndef AL_ARRAY
+#define AL_ARRAY(type, name)                    extern type name[]
+#endif
+
+#ifndef AL_FUNC
+#define AL_FUNC(type, name, args)               type name args
+#endif
+
+#ifndef AL_PRINTFUNC
+#define AL_PRINTFUNC(type, name, args, a, b)    AL_FUNC(type, name, args)
+#endif
+
+#ifndef AL_METHOD
+#define AL_METHOD(type, name, args)             type (*name) args
+#endif
+
+#ifndef AL_FUNCPTR
+#define AL_FUNCPTR(type, name, args)            extern type (*name) args
+#endif
+
+#ifndef AL_FUNCPTRARRAY
+#define AL_FUNCPTRARRAY(type, name, args)       extern type (*name[]) args
+#endif
+
+#ifndef AL_INLINE
+#define AL_INLINE(type, name, args, code)       type name args;
+#endif
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/stubs/allegro/base.h b/engines/ags/stubs/allegro/base.h
new file mode 100644
index 0000000000..cc08b5b518
--- /dev/null
+++ b/engines/ags/stubs/allegro/base.h
@@ -0,0 +1,60 @@
+/* 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 AGS_STUBS_ALLEGRO_BASE_H
+#define AGS_STUBS_ALLEGRO_BASE_H
+
+#include "common/scummsys.h"
+#include "common/algorithm.h"
+
+namespace AGS3 {
+
+#define ALLEGRO_VERSION          4
+#define ALLEGRO_SUB_VERSION      4
+#define ALLEGRO_WIP_VERSION      2
+#define ALLEGRO_VERSION_STR      "4.4.2"
+#define ALLEGRO_DATE_STR         "2011"
+#define ALLEGRO_DATE             20110519    /* yyyymmdd */
+
+/* Returns the median of x, y, z */
+#define MID(x,y,z)   ((x) > (y) ? ((y) > (z) ? (y) : ((x) > (z) ?    \
+                       (z) : (x))) : ((y) > (z) ? ((z) > (x) ? (z) : \
+                       (x)): (y)))
+
+#define AL_ID MKTAG
+
+extern int *allegro_errno;
+
+/**
+ * info about a hardware driver
+ */
+struct _DRIVER_INFO {
+	int id;                          /* integer ID */
+	void *driver;                    /* the driver structure */
+	int autodetect;                  /* set to allow autodetection */
+};
+
+#define AL_FUNC(type, name, args)               type name args
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/stubs/allegro/color.cpp b/engines/ags/stubs/allegro/color.cpp
new file mode 100644
index 0000000000..a69500e387
--- /dev/null
+++ b/engines/ags/stubs/allegro/color.cpp
@@ -0,0 +1,68 @@
+/* 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 "ags/stubs/allegro/color.h"
+#include "common/textconsole.h"
+#include "common/system.h"
+#include "graphics/palette.h"
+
+namespace AGS3 {
+
+int _rgb_r_shift_15 = 0;
+int _rgb_g_shift_15 = 0;
+int _rgb_b_shift_15 = 0;
+int _rgb_r_shift_16 = 0;
+int _rgb_g_shift_16 = 0;
+int _rgb_b_shift_16 = 0;
+int _rgb_r_shift_24 = 0;
+int _rgb_g_shift_24 = 0;
+int _rgb_b_shift_24 = 0;
+int _rgb_r_shift_32 = 0;
+int _rgb_g_shift_32 = 0;
+int _rgb_b_shift_32 = 0;
+int _rgb_a_shift_32 = 0;
+
+int bestfit_color(const PALETTE pal, int r, int g, int b) {
+	error("TODO: bestfit_color");
+}
+
+void set_color(int idx, const RGB *p) {
+	g_system->getPaletteManager()->setPalette((const byte *)p, idx, 1);
+}
+
+void set_palette(const PALETTE p) {
+
+}
+
+void set_palette_range(const PALETTE p, int from, int to, int retracesync) {
+	byte palette[256 * 3];
+	byte *destP = palette;
+	for (int i = 0; i < 256; ++i, destP += 3) {
+		destP[0] = p->r;
+		destP[1] = p->g;
+		destP[2] = p->b;
+	}
+
+	g_system->getPaletteManager()->setPalette(&palette[from], from, to - from + 1);
+}
+
+} // namespace AGS3
diff --git a/engines/ags/stubs/allegro/color.h b/engines/ags/stubs/allegro/color.h
new file mode 100644
index 0000000000..0785bd23cd
--- /dev/null
+++ b/engines/ags/stubs/allegro/color.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 AGS_STUBS_ALLEGRO_COLOR_H
+#define AGS_STUBS_ALLEGRO_COLOR_H
+
+#include "common/scummsys.h"
+#include "ags/stubs/allegro/alconfig.h"
+
+namespace AGS3 {
+
+#include "common/pack-start.h"	// START STRUCT PACKING
+
+struct color {
+	byte r, g, b;
+} PACKED_STRUCT;
+
+typedef color RGB;
+typedef color PALETTE[256];
+
+#include "common/pack-end.h"	// END STRUCT PACKING
+
+//define RGB(r,g,b)          ((COLORREF)(((BYTE)(r)|((WORD)((BYTE)(g))<<8))|(((DWORD)(BYTE)(b))<<16)))
+
+extern int bestfit_color(const PALETTE pal, int r, int g, int b);
+
+extern int _rgb_r_shift_15;
+extern int _rgb_g_shift_15;
+extern int _rgb_b_shift_15;
+extern int _rgb_r_shift_16;
+extern int _rgb_g_shift_16;
+extern int _rgb_b_shift_16;
+extern int _rgb_r_shift_24;
+extern int _rgb_g_shift_24;
+extern int _rgb_b_shift_24;
+extern int _rgb_r_shift_32;
+extern int _rgb_g_shift_32;
+extern int _rgb_b_shift_32;
+extern int _rgb_a_shift_32;
+
+AL_FUNC(void, set_color, (int idx, AL_CONST RGB *p));
+AL_FUNC(void, set_palette, (AL_CONST PALETTE p));
+AL_FUNC(void, set_palette_range, (AL_CONST PALETTE p, int from, int to, int retracesync));
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/stubs/allegro/config.cpp b/engines/ags/stubs/allegro/config.cpp
new file mode 100644
index 0000000000..537f86e439
--- /dev/null
+++ b/engines/ags/stubs/allegro/config.cpp
@@ -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.
+ *
+ */
+
+#include "ags/stubs/allegro/config.h"
+#include "common/textconsole.h"
+
+namespace AGS3 {
+
+void override_config_data(const char *data, int length) {
+	// No implementation
+}
+
+} // namespace AGS3
diff --git a/engines/ags/stubs/allegro/config.h b/engines/ags/stubs/allegro/config.h
new file mode 100644
index 0000000000..5695ea0eda
--- /dev/null
+++ b/engines/ags/stubs/allegro/config.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 AGS_STUBS_ALLEGRO_CONFIG_H
+#define AGS_STUBS_ALLEGRO_CONFIG_H
+
+namespace AGS3 {
+
+extern void override_config_data(const char *data, int length);
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/stubs/allegro/digi.cpp b/engines/ags/stubs/allegro/digi.cpp
new file mode 100644
index 0000000000..07ba5ecfda
--- /dev/null
+++ b/engines/ags/stubs/allegro/digi.cpp
@@ -0,0 +1,40 @@
+/* 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 "ags/stubs/allegro/digi.h"
+
+namespace AGS3 {
+
+DIGI_DRIVER *digi_driver;
+
+DIGI_DRIVER *digi_input_driver;
+
+int digi_card;
+
+int digi_input_card;
+
+
+int detect_digi_driver(int driver_id) {
+	return 0;
+}
+
+} // namespace AGS3
diff --git a/engines/ags/stubs/allegro/digi.h b/engines/ags/stubs/allegro/digi.h
new file mode 100644
index 0000000000..78f41cadee
--- /dev/null
+++ b/engines/ags/stubs/allegro/digi.h
@@ -0,0 +1,145 @@
+/* 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 AGS_STUBS_ALLEGRO_DIGI_H
+#define AGS_STUBS_ALLEGRO_DIGI_H
+
+#include "common/scummsys.h"
+#include "ags/stubs/allegro/base.h"
+#include "ags/stubs/allegro/alconfig.h"
+
+namespace AGS3 {
+
+
+#define DIGI_VOICES           64       /* Theoretical maximums: */
+/* actual drivers may not be */
+/* able to handle this many */
+
+/* a sample */
+struct SAMPLE {
+	int bits;                           /* 8 or 16 */
+	int stereo;                         /* sample type flag */
+	int freq;                           /* sample frequency */
+	int priority;                       /* 0-255 */
+	unsigned long len;                  /* length (in samples) */
+	unsigned long loop_start;           /* loop start position */
+	unsigned long loop_end;             /* loop finish position */
+	unsigned long param;                /* for internal use by the driver */
+	void *data;                         /* sample data */
+};
+
+
+#define DIGI_AUTODETECT       -1       /* for passing to install_sound() */
+#define DIGI_NONE             0
+
+/* driver for playing digital sfx */
+struct DIGI_DRIVER {
+	int  id;                            /* driver ID code */
+	AL_CONST char *name;                /* driver name */
+	AL_CONST char *desc;                /* description string */
+	AL_CONST char *ascii_name;          /* ASCII format name string */
+	int  voices;                        /* available voices */
+	int  basevoice;                     /* voice number offset */
+	int  max_voices;                    /* maximum voices we can support */
+	int  def_voices;                    /* default number of voices to use */
+
+	/* setup routines */
+	AL_METHOD(int, detect, (int input));
+	AL_METHOD(int, init, (int input, int voices));
+	AL_METHOD(void, exit, (int input));
+	AL_METHOD(int, set_mixer_volume, (int volume));
+	AL_METHOD(int, get_mixer_volume, (void));
+
+	/* for use by the audiostream functions */
+	AL_METHOD(void *, lock_voice, (int voice, int start, int end));
+	AL_METHOD(void, unlock_voice, (int voice));
+	AL_METHOD(int, buffer_size, (void));
+
+	/* voice control functions */
+	AL_METHOD(void, init_voice, (int voice, AL_CONST SAMPLE *sample));
+	AL_METHOD(void, release_voice, (int voice));
+	AL_METHOD(void, start_voice, (int voice));
+	AL_METHOD(void, stop_voice, (int voice));
+	AL_METHOD(void, loop_voice, (int voice, int playmode));
+
+	/* position control functions */
+	AL_METHOD(int, get_position, (int voice));
+	AL_METHOD(void, set_position, (int voice, int position));
+
+	/* volume control functions */
+	AL_METHOD(int, get_volume, (int voice));
+	AL_METHOD(void, set_volume, (int voice, int volume));
+	AL_METHOD(void, ramp_volume, (int voice, int tyme, int endvol));
+	AL_METHOD(void, stop_volume_ramp, (int voice));
+
+	/* pitch control functions */
+	AL_METHOD(int, get_frequency, (int voice));
+	AL_METHOD(void, set_frequency, (int voice, int frequency));
+	AL_METHOD(void, sweep_frequency, (int voice, int tyme, int endfreq));
+	AL_METHOD(void, stop_frequency_sweep, (int voice));
+
+	/* pan control functions */
+	AL_METHOD(int, get_pan, (int voice));
+	AL_METHOD(void, set_pan, (int voice, int pan));
+	AL_METHOD(void, sweep_pan, (int voice, int tyme, int endpan));
+	AL_METHOD(void, stop_pan_sweep, (int voice));
+
+	/* effect control functions */
+	AL_METHOD(void, set_echo, (int voice, int strength, int delay));
+	AL_METHOD(void, set_tremolo, (int voice, int rate, int depth));
+	AL_METHOD(void, set_vibrato, (int voice, int rate, int depth));
+
+	/* input functions */
+	int rec_cap_bits;
+	int rec_cap_stereo;
+	AL_METHOD(int, rec_cap_rate, (int bits, int stereo));
+	AL_METHOD(int, rec_cap_parm, (int rate, int bits, int stereo));
+	AL_METHOD(int, rec_source, (int source));
+	AL_METHOD(int, rec_start, (int rate, int bits, int stereo));
+	AL_METHOD(void, rec_stop, (void));
+	AL_METHOD(int, rec_read, (void *buf));
+};
+
+AL_ARRAY(_DRIVER_INFO, _digi_driver_list);
+
+/* macros for constructing the driver lists */
+#define BEGIN_DIGI_DRIVER_LIST                                 \
+   _DRIVER_INFO _digi_driver_list[] =                          \
+   {
+
+#define END_DIGI_DRIVER_LIST                                   \
+      {  0,                nullptr,             0     }        \
+   };
+
+AL_VAR(DIGI_DRIVER *, digi_driver);
+
+AL_VAR(DIGI_DRIVER *, digi_input_driver);
+
+AL_VAR(int, digi_card);
+
+AL_VAR(int, digi_input_card);
+
+AL_FUNC(int, detect_digi_driver, (int driver_id));
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/stubs/allegro/error.cpp b/engines/ags/stubs/allegro/error.cpp
new file mode 100644
index 0000000000..b25496e834
--- /dev/null
+++ b/engines/ags/stubs/allegro/error.cpp
@@ -0,0 +1,28 @@
+/* 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 AGS3 {
+
+static int allegro_error;
+extern int *allegro_errno = &allegro_error;
+
+} // namespace AGS3
diff --git a/engines/ags/stubs/allegro/error.h b/engines/ags/stubs/allegro/error.h
new file mode 100644
index 0000000000..46d3e03fde
--- /dev/null
+++ b/engines/ags/stubs/allegro/error.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 AGS_STUBS_ALLEGRO_ERROR_H
+#define AGS_STUBS_ALLEGRO_ERROR_H
+
+#include "common/scummsys.h"
+
+namespace AGS3 {
+
+
+
+// Error codes
+#define EPERM           1
+#define ENOENT          2
+#define ESRCH           3
+#define EINTR           4
+#define EIO             5
+#define ENXIO           6
+#define E2BIG           7
+#define ENOEXEC         8
+#define EBADF           9
+#define ECHILD          10
+#define EAGAIN          11
+#define ENOMEM          12
+#define EACCES          13
+#define EFAULT          14
+#define EBUSY           16
+#define EEXIST          17
+#define EXDEV           18
+#define ENODEV          19
+#define ENOTDIR         20
+#define EISDIR          21
+#define ENFILE          23
+#define EMFILE          24
+#define ENOTTY          25
+#define EFBIG           27
+#define ENOSPC          28
+#define ESPIPE          29
+#define EROFS           30
+#define EMLINK          31
+#define EPIPE           32
+#define EDOM            33
+#define EDEADLK         36
+#define ENAMETOOLONG    38
+#define ENOLCK          39
+#define ENOSYS          40
+#define ENOTEMPTY       41
+
+// Error codes used in the Secure CRT functions
+#ifndef RC_INVOKED
+#define _SECURECRT_ERRCODE_VALUES_DEFINED
+#define EINVAL          22
+#define ERANGE          34
+#define EILSEQ          42
+#define STRUNCATE       80
+#endif
+
+extern int *allegro_errno;
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/stubs/allegro/file.cpp b/engines/ags/stubs/allegro/file.cpp
new file mode 100644
index 0000000000..ad121f296b
--- /dev/null
+++ b/engines/ags/stubs/allegro/file.cpp
@@ -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.
+ *
+ */
+
+#include "ags/stubs/allegro/file.h"
+#include "common/str.h"
+
+namespace AGS3 {
+
+char *fix_filename_case(char *path) {
+	return path;
+}
+
+char *fix_filename_slashes(char *path) {
+	return path;
+}
+
+char *append_filename(char *dest, const char *path, const char *filename, int size) {
+	strncpy(dest, path, size);
+	strncat(dest, filename, size);
+	return dest;
+}
+
+char *canonicalize_filename(char *dest, const char *filename, int size) {
+	strncpy(dest, filename, size);
+	return dest;
+}
+
+char *make_relative_filename(char *dest, const char *path, const char *filename, int size) {
+	strncpy(dest, filename, size);
+	return dest;
+}
+
+int is_relative_filename(const char *filename) {
+	Common::String fname(filename);
+	return !fname.contains('/') && !fname.contains('\\') ? 0 : -1;
+}
+
+} // namespace AGS3
diff --git a/engines/ags/stubs/allegro/file.h b/engines/ags/stubs/allegro/file.h
new file mode 100644
index 0000000000..083e8d1db3
--- /dev/null
+++ b/engines/ags/stubs/allegro/file.h
@@ -0,0 +1,42 @@
+/* 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 AGS_STUBS_ALLEGRO_FILE_H
+#define AGS_STUBS_ALLEGRO_FILE_H
+
+namespace AGS3 {
+
+struct PACKFILE {
+	// TODO: PACKFILE handling
+	int dummy;
+};
+
+extern char *fix_filename_case(char *path);
+extern char *fix_filename_slashes(char *path);
+extern char *append_filename(char *dest, const char *path, const char *filename, int size);
+extern char *canonicalize_filename(char *dest, const char *filename, int size);
+extern char *make_relative_filename(char *dest, const char *path, const char *filename, int size);
+extern int is_relative_filename(const char *filename);
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/stubs/allegro/fixed.cpp b/engines/ags/stubs/allegro/fixed.cpp
new file mode 100644
index 0000000000..a6923e58ec
--- /dev/null
+++ b/engines/ags/stubs/allegro/fixed.cpp
@@ -0,0 +1,178 @@
+/* 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 "ags/stubs/allegro/fixed.h"
+#include "ags/stubs/allegro/error.h"
+
+namespace AGS3 {
+
+fixed fixtorad_r;
+fixed radtofix_r;
+
+fixed ftofix(double x) {
+   if (x > 32767.0) {
+      *allegro_errno = ERANGE;
+      return 0x7FFFFFFF;
+   }
+
+   if (x < -32767.0) {
+      *allegro_errno = ERANGE;
+      return (fixed)-0x7FFFFFFF;
+   }
+
+   return (fixed)(x * 65536.0 + (x < 0 ? -0.5 : 0.5));
+}
+
+double fixtof(fixed x) {
+   return (double)x / 65536.0;
+}
+
+fixed fixadd(fixed x, fixed y) {
+   fixed result = x + y;
+
+   if (result >= 0) {
+      if ((x < 0) && (y < 0)) {
+         *allegro_errno = ERANGE;
+         return (fixed)-0x7FFFFFFF;
+      }
+      else
+         return result;
+   }
+   else {
+      if ((x > 0) && (y > 0)) {
+         *allegro_errno = ERANGE;
+         return 0x7FFFFFFF;
+      }
+      else
+         return result;
+   }
+}
+
+fixed fixsub(fixed x, fixed y) {
+   fixed result = x - y;
+
+   if (result >= 0) {
+      if ((x < 0) && (y > 0)) {
+         *allegro_errno = ERANGE;
+         return (fixed)-0x7FFFFFFF;
+      }
+      else
+         return result;
+   }
+   else {
+      if ((x > 0) && (y < 0)) {
+         *allegro_errno = ERANGE;
+         return 0x7FFFFFFF;
+      }
+      else
+         return result;
+   }
+}
+
+fixed fixmul(fixed x, fixed y) {
+	int64 lx = x;
+	int64 ly = y;
+	int64 lres = (lx * ly);
+
+	if (lres > 0x7FFFFFFF0000LL) {
+		*allegro_errno = ERANGE;
+		return 0x7FFFFFFF;
+	} else if (lres < -0x7FFFFFFF0000LL) {
+		*allegro_errno = ERANGE;
+		return 0x80000000;
+	} else {
+		int res = lres >> 16;
+		return res;
+	}
+}
+
+fixed fixdiv(fixed x, fixed y) {
+	if (y == 0) {
+		*allegro_errno = ERANGE;
+		return (fixed)(x < 0) ? -0x7FFFFFFF : 0x7FFFFFFF;
+	} else
+		return ftofix(fixtof(x) / fixtof(y));
+}
+
+int fixfloor(fixed x) {
+	/* (x >> 16) is not portable */
+	if (x >= 0)
+		return (x >> 16);
+	else
+		return ~((~x) >> 16);
+}
+
+
+int fixceil(fixed x) {
+	if (x > 0x7FFF0000) {
+		*allegro_errno = ERANGE;
+		return 0x7FFF;
+	}
+
+	return fixfloor(x + 0xFFFF);
+}
+
+fixed itofix(int x) {
+	return x << 16;
+}
+
+
+int fixtoi(fixed x) {
+	return fixfloor(x) + ((x & 0x8000) >> 15);
+}
+
+
+fixed fixcos(fixed x) {
+	return _cos_tbl[((x + 0x4000) >> 15) & 0x1FF];
+}
+
+
+fixed fixsin(fixed x) {
+	return _cos_tbl[((x - 0x400000 + 0x4000) >> 15) & 0x1FF];
+}
+
+
+fixed fixtan(fixed x) {
+	return _tan_tbl[((x + 0x4000) >> 15) & 0xFF];
+}
+
+
+fixed fixacos(fixed x) {
+	if ((x < -65536) || (x > 65536)) {
+		*allegro_errno = EDOM;
+		return 0;
+	}
+
+	return _acos_tbl[(x + 65536 + 127) >> 8];
+}
+
+
+fixed fixasin(fixed x) {
+	if ((x < -65536) || (x > 65536)) {
+		*allegro_errno = EDOM;
+		return 0;
+	}
+
+	return 0x00400000 - _acos_tbl[(x + 65536 + 127) >> 8];
+}
+
+} // namespace AGS3
diff --git a/engines/ags/stubs/allegro/fixed.h b/engines/ags/stubs/allegro/fixed.h
new file mode 100644
index 0000000000..45acd42c99
--- /dev/null
+++ b/engines/ags/stubs/allegro/fixed.h
@@ -0,0 +1,63 @@
+/* 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 AGS_STUBS_ALLEGRO_FIXED_H
+#define AGS_STUBS_ALLEGRO_FIXED_H
+
+#include "common/scummsys.h"
+
+namespace AGS3 {
+
+typedef uint32 fixed;
+
+extern fixed fixtorad_r;
+extern fixed radtofix_r;
+extern fixed _cos_tbl[];
+extern fixed _tan_tbl[];
+extern fixed _acos_tbl[];
+
+extern fixed ftofix(double x);
+extern double fixtof(fixed x);
+extern fixed fixadd(fixed x, fixed y);
+extern fixed fixsub(fixed x, fixed y);
+extern fixed fixmul(fixed x, fixed y);
+extern fixed fixdiv(fixed x, fixed y);
+extern int fixfloor(fixed x);
+extern int fixceil(fixed x);
+extern fixed itofix(int x);
+extern int fixtoi(fixed x);
+extern fixed fixcos(fixed x);
+extern fixed fixsin(fixed x);
+extern fixed fixtan(fixed x);
+extern fixed fixacos(fixed x);
+extern fixed fixasin(fixed x);
+
+#if 0
+extern fixed fixsqrt(fixed x);
+extern fixed fixhypot(fixed x, fixed y);
+extern fixed fixatan(fixed x);
+extern fixed fixatan2(fixed y, fixed x);
+#endif
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/stubs/allegro/gfx.cpp b/engines/ags/stubs/allegro/gfx.cpp
new file mode 100644
index 0000000000..799e42a07d
--- /dev/null
+++ b/engines/ags/stubs/allegro/gfx.cpp
@@ -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.
+ *
+ */
+
+#include "ags/stubs/allegro/gfx.h"
+#include "common/textconsole.h"
+
+namespace AGS3 {
+
+int color_conversion;
+
+void set_color_conversion(int mode) {
+	color_conversion = mode;
+}
+
+int get_color_conversion() {
+	return color_conversion;
+}
+
+int set_gfx_mode(int card, int w, int h, int v_w, int v_h) {
+	error("TODO: set_gfx_mode");
+}
+
+
+} // namespace AGS3
diff --git a/engines/ags/stubs/allegro/gfx.h b/engines/ags/stubs/allegro/gfx.h
new file mode 100644
index 0000000000..a3e15eaa8c
--- /dev/null
+++ b/engines/ags/stubs/allegro/gfx.h
@@ -0,0 +1,176 @@
+/* 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 AGS_STUBS_ALLEGRO_GRAPHICS_H
+#define AGS_STUBS_ALLEGRO_GRAPHICS_H
+
+#include "graphics/managed_surface.h"
+#include "ags/stubs/allegro/base.h"
+
+namespace AGS3 {
+
+#define GFX_TEXT                       -1
+#define GFX_AUTODETECT                 0
+#define GFX_AUTODETECT_FULLSCREEN      1
+#define GFX_AUTODETECT_WINDOWED        2
+#define GFX_SAFE                       AL_ID('S','A','F','E')
+#define GFX_NONE                       AL_ID('N','O','N','E')
+
+/* drawing modes for draw_sprite_ex() */
+#define DRAW_SPRITE_NORMAL 0
+#define DRAW_SPRITE_LIT 1
+#define DRAW_SPRITE_TRANS 2
+
+/* flipping modes for draw_sprite_ex() */
+#define DRAW_SPRITE_NO_FLIP 0x0
+#define DRAW_SPRITE_H_FLIP  0x1
+#define DRAW_SPRITE_V_FLIP  0x2
+#define DRAW_SPRITE_VH_FLIP 0x3
+
+/* Blender mode defines, for the gfx_driver->set_blender_mode() function */
+#define blender_mode_none            0
+#define blender_mode_trans           1
+#define blender_mode_add             2
+#define blender_mode_burn            3
+#define blender_mode_color           4
+#define blender_mode_difference      5
+#define blender_mode_dissolve        6
+#define blender_mode_dodge           7
+#define blender_mode_hue             8
+#define blender_mode_invert          9
+#define blender_mode_luminance      10
+#define blender_mode_multiply       11
+#define blender_mode_saturation     12
+#define blender_mode_screen         13
+#define blender_mode_alpha          14
+
+
+#define SCREEN_W     (gfx_driver ? gfx_driver->w : 0)
+#define SCREEN_H     (gfx_driver ? gfx_driver->h : 0)
+
+#define VIRTUAL_W    (screen ? screen->w : 0)
+#define VIRTUAL_H    (screen ? screen->h : 0)
+
+#define COLORCONV_NONE              0
+
+#define COLORCONV_8_TO_15           1
+#define COLORCONV_8_TO_16           2
+#define COLORCONV_8_TO_24           4
+#define COLORCONV_8_TO_32           8
+
+#define COLORCONV_15_TO_8           0x10
+#define COLORCONV_15_TO_16          0x20
+#define COLORCONV_15_TO_24          0x40
+#define COLORCONV_15_TO_32          0x80
+
+#define COLORCONV_16_TO_8           0x100
+#define COLORCONV_16_TO_15          0x200
+#define COLORCONV_16_TO_24          0x400
+#define COLORCONV_16_TO_32          0x800
+
+#define COLORCONV_24_TO_8           0x1000
+#define COLORCONV_24_TO_15          0x2000
+#define COLORCONV_24_TO_16          0x4000
+#define COLORCONV_24_TO_32          0x8000
+
+#define COLORCONV_32_TO_8           0x10000
+#define COLORCONV_32_TO_15          0x20000
+#define COLORCONV_32_TO_16          0x40000
+#define COLORCONV_32_TO_24          0x80000
+
+#define COLORCONV_32A_TO_8          0x100000
+#define COLORCONV_32A_TO_15         0x200000
+#define COLORCONV_32A_TO_16         0x400000
+#define COLORCONV_32A_TO_24         0x800000
+
+#define COLORCONV_DITHER_PAL        0x1000000
+#define COLORCONV_DITHER_HI         0x2000000
+#define COLORCONV_KEEP_TRANS        0x4000000
+
+#define COLORCONV_DITHER            (COLORCONV_DITHER_PAL |          \
+                                     COLORCONV_DITHER_HI)
+
+#define COLORCONV_EXPAND_256        (COLORCONV_8_TO_15 |             \
+                                     COLORCONV_8_TO_16 |             \
+                                     COLORCONV_8_TO_24 |             \
+                                     COLORCONV_8_TO_32)
+
+#define COLORCONV_REDUCE_TO_256     (COLORCONV_15_TO_8 |             \
+                                     COLORCONV_16_TO_8 |             \
+                                     COLORCONV_24_TO_8 |             \
+                                     COLORCONV_32_TO_8 |             \
+                                     COLORCONV_32A_TO_8)
+
+#define COLORCONV_EXPAND_15_TO_16    COLORCONV_15_TO_16
+
+#define COLORCONV_REDUCE_16_TO_15    COLORCONV_16_TO_15
+
+#define COLORCONV_EXPAND_HI_TO_TRUE (COLORCONV_15_TO_24 |            \
+                                     COLORCONV_15_TO_32 |            \
+                                     COLORCONV_16_TO_24 |            \
+                                     COLORCONV_16_TO_32)
+
+#define COLORCONV_REDUCE_TRUE_TO_HI (COLORCONV_24_TO_15 |            \
+                                     COLORCONV_24_TO_16 |            \
+                                     COLORCONV_32_TO_15 |            \
+                                     COLORCONV_32_TO_16)
+
+#define COLORCONV_24_EQUALS_32      (COLORCONV_24_TO_32 |            \
+                                     COLORCONV_32_TO_24)
+
+#define COLORCONV_TOTAL             (COLORCONV_EXPAND_256 |          \
+                                     COLORCONV_REDUCE_TO_256 |       \
+                                     COLORCONV_EXPAND_15_TO_16 |     \
+                                     COLORCONV_REDUCE_16_TO_15 |     \
+                                     COLORCONV_EXPAND_HI_TO_TRUE |   \
+                                     COLORCONV_REDUCE_TRUE_TO_HI |   \
+                                     COLORCONV_24_EQUALS_32 |        \
+                                     COLORCONV_32A_TO_15 |           \
+                                     COLORCONV_32A_TO_16 |           \
+                                     COLORCONV_32A_TO_24)
+
+#define COLORCONV_PARTIAL           (COLORCONV_EXPAND_15_TO_16 |     \
+                                     COLORCONV_REDUCE_16_TO_15 |     \
+                                     COLORCONV_24_EQUALS_32)
+
+#define COLORCONV_MOST              (COLORCONV_EXPAND_15_TO_16 |     \
+                                     COLORCONV_REDUCE_16_TO_15 |     \
+                                     COLORCONV_EXPAND_HI_TO_TRUE |   \
+                                     COLORCONV_REDUCE_TRUE_TO_HI |   \
+                                     COLORCONV_24_EQUALS_32)
+
+#define COLORCONV_KEEP_ALPHA        (COLORCONV_TOTAL                 \
+                                     & ~(COLORCONV_32A_TO_8 |        \
+                                         COLORCONV_32A_TO_15 |       \
+                                         COLORCONV_32A_TO_16 |       \
+                                         COLORCONV_32A_TO_24))
+
+class BITMAP : public Graphics::ManagedSurface {
+};
+
+AL_FUNC(void, set_color_conversion, (int mode));
+AL_FUNC(int, get_color_conversion, ());
+AL_FUNC(int, set_gfx_mode, (int card, int w, int h, int v_w, int v_h));
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/stubs/allegro/keyboard.cpp b/engines/ags/stubs/allegro/keyboard.cpp
new file mode 100644
index 0000000000..ba014a85f5
--- /dev/null
+++ b/engines/ags/stubs/allegro/keyboard.cpp
@@ -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.
+ *
+ */
+
+#include "ags/stubs/allegro/keyboard.h"
+#include "common/algorithm.h"
+#include "common/textconsole.h"
+
+namespace AGS3 {
+
+bool key[Common::KEYCODE_LAST];
+
+int install_keyboard() {
+	Common::fill(&key[0], &key[Common::KEYCODE_LAST], false);
+	return 0;
+}
+
+void remove_keyboard() {
+}
+
+} // namespace AGS3
diff --git a/engines/ags/stubs/allegro/keyboard.h b/engines/ags/stubs/allegro/keyboard.h
new file mode 100644
index 0000000000..8f8d0da14f
--- /dev/null
+++ b/engines/ags/stubs/allegro/keyboard.h
@@ -0,0 +1,105 @@
+/* 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 AGS_STUBS_ALLEGRO_KEYBOARD_H
+#define AGS_STUBS_ALLEGRO_KEYBOARD_H
+
+#include "common/keyboard.h"
+
+namespace AGS3 {
+
+#define KB_SHIFT_FLAG Common::KBD_SHIFT
+#define KB_CTRL_FLAG Common::KBD_CTRL
+#define KB_ALT_FLAG Common::KBD_ALT
+
+#define KEY_F9 Common::KEYCODE_F9
+#define KEY_LCONTROL Common::KEYCODE_LCTRL
+#define KEY_RCONTROL Common::KEYCODE_RCTRL
+
+#define __allegro_KEY_LSHIFT Common::KEYCODE_LSHIFT
+#define __allegro_KEY_RSHIFT Common::KEYCODE_RSHIFT
+#define __allegro_KEY_LCONTROL Common::KEYCODE_LCTRL
+#define __allegro_KEY_RCONTROL Common::KEYCODE_RCTRL
+#define __allegro_KEY_ALT Common::KEYCODE_LALT
+
+#define __allegro_KEY_F1 Common::KEYCODE_F1
+#define __allegro_KEY_F2 Common::KEYCODE_F2
+#define __allegro_KEY_F3 Common::KEYCODE_F3
+#define __allegro_KEY_F4 Common::KEYCODE_F4
+#define __allegro_KEY_F5 Common::KEYCODE_F5
+#define __allegro_KEY_F6 Common::KEYCODE_F6
+#define __allegro_KEY_F7 Common::KEYCODE_F7
+#define __allegro_KEY_F8 Common::KEYCODE_F8
+#define __allegro_KEY_F9 Common::KEYCODE_F9
+#define __allegro_KEY_F10 Common::KEYCODE_F10
+#define __allegro_KEY_F11 Common::KEYCODE_F11
+#define __allegro_KEY_F12 Common::KEYCODE_F12
+
+#define __allegro_KEY_HOME Common::KEYCODE_HOME
+#define __allegro_KEY_UP Common::KEYCODE_UP
+#define __allegro_KEY_PGUP Common::KEYCODE_PAGEUP
+#define __allegro_KEY_LEFT Common::KEYCODE_LEFT
+#define __allegro_KEY_RIGHT Common::KEYCODE_RIGHT
+#define __allegro_KEY_END Common::KEYCODE_END
+#define __allegro_KEY_DOWN Common::KEYCODE_DOWN
+#define __allegro_KEY_PGDN Common::KEYCODE_PAGEDOWN
+#define __allegro_KEY_INSERT Common::KEYCODE_INSERT
+#define __allegro_KEY_DEL Common::KEYCODE_DELETE
+
+#define __allegro_KEY_0_PAD Common::KEYCODE_KP0
+#define __allegro_KEY_1_PAD Common::KEYCODE_KP1
+#define __allegro_KEY_2_PAD Common::KEYCODE_KP2
+#define __allegro_KEY_3_PAD Common::KEYCODE_KP3
+#define __allegro_KEY_4_PAD Common::KEYCODE_KP4
+#define __allegro_KEY_5_PAD Common::KEYCODE_KP5
+#define __allegro_KEY_6_PAD Common::KEYCODE_KP6
+#define __allegro_KEY_7_PAD Common::KEYCODE_KP7
+#define __allegro_KEY_8_PAD Common::KEYCODE_KP8
+#define __allegro_KEY_9_PAD Common::KEYCODE_KP9
+#define __allegro_KEY_DEL_PAD Common::KEYCODE_KP_PERIOD
+
+#define __allegro_KEY_PRTSCR Common::KEYCODE_PRINT
+#define __allegro_KEY_PAUSE Common::KEYCODE_PAUSE
+#define __allegro_KEY_ABNT_C1 94
+#define __allegro_KEY_YEN 95
+#define __allegro_KEY_KANA 96
+#define __allegro_KEY_CONVERT 97
+#define __allegro_KEY_NOCONVERT 98
+#define __allegro_KEY_CIRCUMFLEX 100
+#define __allegro_KEY_KANJI 102
+#define __allegro_KEY_ALTGR 120
+#define __allegro_KEY_LWIN Common::KEYCODE_LMETA
+#define __allegro_KEY_RWIN Common::KEYCODE_RMETA
+#define __allegro_KEY_MENU 123
+#define __allegro_KEY_SCRLOCK Common::KEYCODE_SCROLLOCK
+#define __allegro_KEY_NUMLOCK Common::KEYCODE_NUMLOCK
+#define __allegro_KEY_CAPSLOCK Common::KEYCODE_CAPSLOCK
+
+
+extern bool key[Common::KEYCODE_LAST];
+
+extern int install_keyboard();
+extern void remove_keyboard();
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/stubs/allegro/midi.cpp b/engines/ags/stubs/allegro/midi.cpp
new file mode 100644
index 0000000000..d0bab80254
--- /dev/null
+++ b/engines/ags/stubs/allegro/midi.cpp
@@ -0,0 +1,46 @@
+/* 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 "ags/stubs/allegro/midi.h"
+
+namespace AGS3 {
+
+MIDI_DRIVER *midi_driver;
+
+MIDI_DRIVER *midi_input_driver;
+
+int midi_card;
+
+int midi_input_card;
+
+volatile long midi_pos;       /* current position in the midi file, in beats */
+volatile long midi_time;      /* current position in the midi file, in seconds */
+
+long midi_loop_start;         /* where to loop back to at EOF */
+long midi_loop_end;           /* loop when we hit this position */
+
+
+int detect_midi_driver(int driver_id) {
+	return 0;
+}
+
+} // namespace AGS3
diff --git a/engines/ags/stubs/allegro/midi.h b/engines/ags/stubs/allegro/midi.h
new file mode 100644
index 0000000000..8925ac653b
--- /dev/null
+++ b/engines/ags/stubs/allegro/midi.h
@@ -0,0 +1,123 @@
+/* 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 AGS_STUBS_ALLEGRO_MIDI_H
+#define AGS_STUBS_ALLEGRO_MIDI_H
+
+#include "common/scummsys.h"
+#include "ags/stubs/allegro/base.h"
+#include "ags/stubs/allegro/alconfig.h"
+
+namespace AGS3 {
+
+/* Theoretical maximums: */
+#define MIDI_VOICES           64       /* actual drivers may not be */
+#define MIDI_TRACKS           32       /* able to handle this many */
+
+/* a midi file */
+struct MIDI {
+	int divisions;                      /* number of ticks per quarter note */
+	struct {
+		unsigned char *data;             /* MIDI message stream */
+		int len;                         /* length of the track data */
+	} track[MIDI_TRACKS];
+};
+
+
+#define MIDI_AUTODETECT       -1
+#define MIDI_NONE             0
+#define MIDI_DIGMID           AL_ID('D','I','G','I')
+
+/* driver for playing midi music */
+struct MIDI_DRIVER {
+	int  id;                            /* driver ID code */
+	AL_CONST char *name;                /* driver name */
+	AL_CONST char *desc;                /* description string */
+	AL_CONST char *ascii_name;          /* ASCII format name string */
+	int  voices;                        /* available voices */
+	int  basevoice;                     /* voice number offset */
+	int  max_voices;                    /* maximum voices we can support */
+	int  def_voices;                    /* default number of voices to use */
+	int  xmin, xmax;                    /* reserved voice range */
+
+	/* setup routines */
+	AL_METHOD(int, detect, (int input));
+	AL_METHOD(int, init, (int input, int voices));
+	AL_METHOD(void, exit, (int input));
+	AL_METHOD(int, set_mixer_volume, (int volume));
+	AL_METHOD(int, get_mixer_volume, (void));
+
+	/* raw MIDI output to MPU-401, etc. */
+	AL_METHOD(void, raw_midi, (int data));
+
+	/* dynamic patch loading routines */
+	AL_METHOD(int, load_patches, (AL_CONST char *patches, AL_CONST char *drums));
+	AL_METHOD(void, adjust_patches, (AL_CONST char *patches, AL_CONST char *drums));
+
+	/* note control functions */
+	AL_METHOD(void, key_on, (int inst, int note, int bend, int vol, int pan));
+	AL_METHOD(void, key_off, (int voice));
+	AL_METHOD(void, set_volume, (int voice, int vol));
+	AL_METHOD(void, set_pitch, (int voice, int note, int bend));
+	AL_METHOD(void, set_pan, (int voice, int pan));
+	AL_METHOD(void, set_vibrato, (int voice, int amount));
+};
+
+
+AL_VAR(MIDI_DRIVER, midi_digmid);
+
+AL_ARRAY(_DRIVER_INFO, _midi_driver_list);
+
+
+/* macros for constructing the driver lists */
+#define BEGIN_MIDI_DRIVER_LIST                                 \
+   _DRIVER_INFO _midi_driver_list[] =                          \
+   {
+
+#define END_MIDI_DRIVER_LIST                                   \
+      {  0,                NULL,                0     }        \
+   };
+
+#define MIDI_DRIVER_DIGMID                                     \
+      {  MIDI_DIGMID,      &midi_digmid,        TRUE  },
+
+
+AL_VAR(MIDI_DRIVER *, midi_driver);
+
+AL_VAR(MIDI_DRIVER *, midi_input_driver);
+
+AL_VAR(int, midi_card);
+
+AL_VAR(int, midi_input_card);
+
+AL_VAR(volatile long, midi_pos);       /* current position in the midi file, in beats */
+AL_VAR(volatile long, midi_time);      /* current position in the midi file, in seconds */
+
+AL_VAR(long, midi_loop_start);         /* where to loop back to at EOF */
+AL_VAR(long, midi_loop_end);           /* loop when we hit this position */
+
+
+AL_FUNC(int, detect_midi_driver, (int driver_id));
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/stubs/allegro/mouse.cpp b/engines/ags/stubs/allegro/mouse.cpp
new file mode 100644
index 0000000000..c8bad8476f
--- /dev/null
+++ b/engines/ags/stubs/allegro/mouse.cpp
@@ -0,0 +1,116 @@
+/* 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 "ags/stubs/allegro/mouse.h"
+#include "common/textconsole.h"
+
+namespace AGS3 {
+
+MOUSE_DRIVER mousedrv_none;
+MOUSE_DRIVER *mouse_driver;
+_DRIVER_INFO _mouse_driver_list[];
+
+BITMAP *mouse_sprite;
+int mouse_x_focus;
+int mouse_y_focus;
+
+volatile int mouse_x;
+volatile int mouse_y;
+volatile int mouse_z;
+volatile int mouse_w;
+volatile int mouse_b;
+volatile int mouse_pos;
+
+volatile int freeze_mouse_flag;
+
+int install_mouse() {
+	return 0;
+}
+
+void remove_mouse() {
+}
+
+int poll_mouse() {
+	return 0;
+}
+
+int mouse_needs_poll() {
+	return 0;
+}
+
+void enable_hardware_cursor() {
+}
+
+void disable_hardware_cursor() {
+}
+
+void show_mouse(BITMAP *bmp) {
+}
+
+void scare_mouse() {
+}
+
+void scare_mouse_area(int x, int y, int w, int h) {
+}
+
+void unscare_mouse() {
+}
+
+void position_mouse(int x, int y) {
+}
+
+void position_mouse_z(int z) {
+}
+
+void position_mouse_w(int w) {
+}
+
+void set_mouse_range(int x1, int y_1, int x2, int y2) {
+}
+
+void set_mouse_speed(int xspeed, int yspeed) {
+}
+
+void select_mouse_cursor(int cursor) {
+}
+
+void set_mouse_cursor_bitmap(int cursor, BITMAP *bmp) {
+}
+
+void set_mouse_sprite_focus(int x, int y) {
+}
+
+void get_mouse_mickeys(int *mickeyx, int *mickeyy) {
+}
+
+void set_mouse_sprite(BITMAP *sprite) {
+}
+
+int show_os_cursor(int cursor) {
+	return 0;
+}
+
+int mouse_on_screen() {
+	return 0;
+}
+
+} // namespace AGS3
diff --git a/engines/ags/stubs/allegro/mouse.h b/engines/ags/stubs/allegro/mouse.h
new file mode 100644
index 0000000000..33538fac92
--- /dev/null
+++ b/engines/ags/stubs/allegro/mouse.h
@@ -0,0 +1,120 @@
+/* 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 AGS_STUBS_ALLEGRO_MOUSE_H
+#define AGS_STUBS_ALLEGRO_MOUSE_H
+
+#include "common/events.h"
+#include "ags/stubs/allegro/base.h"
+#include "ags/stubs/allegro/alconfig.h"
+#include "ags/stubs/allegro/gfx.h"
+
+namespace AGS3 {
+
+#define MOUSEDRV_AUTODETECT  -1
+#define MOUSEDRV_NONE         0
+
+struct MOUSE_DRIVER {
+	int  id;
+	AL_CONST char *name;
+	AL_CONST char *desc;
+	AL_CONST char *ascii_name;
+	AL_METHOD(int, init, (void));
+	AL_METHOD(void, exit, (void));
+	AL_METHOD(void, poll, (void));
+	AL_METHOD(void, timer_poll, (void));
+	AL_METHOD(void, position, (int x, int y));
+	AL_METHOD(void, set_range, (int x1, int y_1, int x2, int y2));
+	AL_METHOD(void, set_speed, (int xspeed, int yspeed));
+	AL_METHOD(void, get_mickeys, (int *mickeyx, int *mickeyy));
+	AL_METHOD(int, analyse_data, (AL_CONST char *buffer, int size));
+	AL_METHOD(void, enable_hardware_cursor, (int mode));
+	AL_METHOD(int, select_system_cursor, (int cursor));
+};
+
+AL_VAR(MOUSE_DRIVER, mousedrv_none);
+AL_VAR(MOUSE_DRIVER *, mouse_driver);
+AL_ARRAY(_DRIVER_INFO, _mouse_driver_list);
+
+AL_FUNC(int, install_mouse, (void));
+AL_FUNC(void, remove_mouse, (void));
+
+AL_FUNC(int, poll_mouse, (void));
+AL_FUNC(int, mouse_needs_poll, (void));
+
+AL_FUNC(void, enable_hardware_cursor, (void));
+AL_FUNC(void, disable_hardware_cursor, (void));
+
+/* Mouse cursors */
+#define MOUSE_CURSOR_NONE        0
+#define MOUSE_CURSOR_ALLEGRO     1
+#define MOUSE_CURSOR_ARROW       2
+#define MOUSE_CURSOR_BUSY        3
+#define MOUSE_CURSOR_QUESTION    4
+#define MOUSE_CURSOR_EDIT        5
+#define AL_NUM_MOUSE_CURSORS        6
+
+AL_VAR(BITMAP *, mouse_sprite);
+AL_VAR(int, mouse_x_focus);
+AL_VAR(int, mouse_y_focus);
+
+AL_VAR(volatile int, mouse_x);
+AL_VAR(volatile int, mouse_y);
+AL_VAR(volatile int, mouse_z);
+AL_VAR(volatile int, mouse_w);
+AL_VAR(volatile int, mouse_b);
+AL_VAR(volatile int, mouse_pos);
+
+AL_VAR(volatile int, freeze_mouse_flag);
+
+#define MOUSE_FLAG_MOVE             1
+#define MOUSE_FLAG_LEFT_DOWN        2
+#define MOUSE_FLAG_LEFT_UP          4
+#define MOUSE_FLAG_RIGHT_DOWN       8
+#define MOUSE_FLAG_RIGHT_UP         16
+#define MOUSE_FLAG_MIDDLE_DOWN      32
+#define MOUSE_FLAG_MIDDLE_UP        64
+#define MOUSE_FLAG_MOVE_Z           128
+#define MOUSE_FLAG_MOVE_W           256
+
+AL_FUNCPTR(void, mouse_callback, (int flags));
+
+AL_FUNC(void, show_mouse, (BITMAP *bmp));
+AL_FUNC(void, scare_mouse, (void));
+AL_FUNC(void, scare_mouse_area, (int x, int y, int w, int h));
+AL_FUNC(void, unscare_mouse, (void));
+AL_FUNC(void, position_mouse, (int x, int y));
+AL_FUNC(void, position_mouse_z, (int z));
+AL_FUNC(void, position_mouse_w, (int w));
+AL_FUNC(void, set_mouse_range, (int x1, int y_1, int x2, int y2));
+AL_FUNC(void, set_mouse_speed, (int xspeed, int yspeed));
+AL_FUNC(void, select_mouse_cursor, (int cursor));
+AL_FUNC(void, set_mouse_cursor_bitmap, (int cursor, BITMAP *bmp));
+AL_FUNC(void, set_mouse_sprite_focus, (int x, int y));
+AL_FUNC(void, get_mouse_mickeys, (int *mickeyx, int *mickeyy));
+AL_FUNC(void, set_mouse_sprite, (BITMAP *sprite));
+AL_FUNC(int, show_os_cursor, (int cursor));
+AL_FUNC(int, mouse_on_screen, (void));
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/stubs/allegro/sound.cpp b/engines/ags/stubs/allegro/sound.cpp
new file mode 100644
index 0000000000..5eda1fe992
--- /dev/null
+++ b/engines/ags/stubs/allegro/sound.cpp
@@ -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.
+ *
+ */
+
+#include "ags/stubs/allegro/sound.h"
+#include "common/textconsole.h"
+
+namespace AGS3 {
+
+_DRIVER_INFO _digi_driver_list[] = {
+	{ 0, nullptr, 0     }
+};
+
+
+int install_sound(int digi, int midi, const char *cfg_path) {
+	// TODO: install_sound
+	return 0;
+}
+
+void remove_sound() {
+	// TODO: remove_sound
+}
+
+void reserve_voices(int digi_voices, int midi_voices) {
+	error("reserve_voices");
+}
+
+void set_volume_per_voice(int scale) {
+	error("set_volume_per_voice");
+
+}
+
+int install_sound_input(int digi, int midi) {
+	error("install_sound_input");
+}
+
+void remove_sound_input() {
+	error("remove_sound_input");
+}
+
+void set_volume(int digi_volume, int midi_volume) {
+	error("set_volume");
+}
+
+void set_hardware_volume(int digi_volume, int midi_volume) {
+	error("set_hardware_volume");
+}
+
+void get_volume(int *digi_volume, int *midi_volume) {
+	error("get_volume");
+}
+
+void get_hardware_volume(int *digi_volume, int *midi_volume) {
+	error("get_hardware_volume");
+}
+
+void set_mixer_quality(int quality) {
+	error("set_mixer_quality");
+}
+
+int get_mixer_quality() {
+	error("get_mixer_quality");
+}
+
+int get_mixer_frequency() {
+	error("get_mixer_frequency");
+}
+
+int get_mixer_bits() {
+	error("get_mixer_bits");
+}
+
+int get_mixer_channels() {
+	error("get_mixer_channels");
+}
+
+int get_mixer_voices() {
+	error("get_mixer_voices");
+}
+
+int get_mixer_buffer_length() {
+	error("get_mixer_buffer_length");
+}
+
+} // namespace AGS3
diff --git a/engines/ags/stubs/allegro/sound.h b/engines/ags/stubs/allegro/sound.h
new file mode 100644
index 0000000000..fa9f64097e
--- /dev/null
+++ b/engines/ags/stubs/allegro/sound.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 AGS_STUBS_ALLEGRO_SOUND_H
+#define AGS_STUBS_ALLEGRO_SOUND_H
+
+#include "common/scummsys.h"
+#include "ags/stubs/allegro/base.h"
+#include "ags/stubs/allegro/alconfig.h"
+
+namespace AGS3 {
+
+AL_FUNC(void, reserve_voices, (int digi_voices, int midi_voices));
+AL_FUNC(void, set_volume_per_voice, (int scale));
+
+AL_FUNC(int, install_sound, (int digi, int midi, AL_CONST char *cfg_path));
+AL_FUNC(void, remove_sound, (void));
+
+AL_FUNC(int, install_sound_input, (int digi, int midi));
+AL_FUNC(void, remove_sound_input, (void));
+
+AL_FUNC(void, set_volume, (int digi_volume, int midi_volume));
+AL_FUNC(void, set_hardware_volume, (int digi_volume, int midi_volume));
+
+AL_FUNC(void, get_volume, (int *digi_volume, int *midi_volume));
+AL_FUNC(void, get_hardware_volume, (int *digi_volume, int *midi_volume));
+
+AL_FUNC(void, set_mixer_quality, (int quality));
+AL_FUNC(int, get_mixer_quality, (void));
+AL_FUNC(int, get_mixer_frequency, (void));
+AL_FUNC(int, get_mixer_bits, (void));
+AL_FUNC(int, get_mixer_channels, (void));
+AL_FUNC(int, get_mixer_voices, (void));
+AL_FUNC(int, get_mixer_buffer_length, (void));
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/stubs/allegro/system.cpp b/engines/ags/stubs/allegro/system.cpp
new file mode 100644
index 0000000000..4767537379
--- /dev/null
+++ b/engines/ags/stubs/allegro/system.cpp
@@ -0,0 +1,65 @@
+/* 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 "ags/stubs/allegro/system.h"
+#include "common/system.h"
+
+namespace AGS3 {
+
+int color_depth;
+
+SYSTEM_DRIVER system_none;
+SYSTEM_DRIVER *system_driver;
+
+_DRIVER_INFO _system_driver_list[] = {
+//	{ SYSTEM_IOS, &system_none, true  },
+	{ SYSTEM_NONE, &system_none, false },
+	{ 0, nullptr , 0     }
+};
+
+
+void set_color_depth(int depth) {
+	color_depth = depth;
+}
+
+int get_color_depth() {
+	return color_depth;
+}
+
+int get_desktop_resolution(int *width, int *height) {
+	if (*width)
+		*width = g_system->getWidth();
+	if (*height)
+		*height = g_system->getHeight();
+
+	return 0;
+}
+
+void request_refresh_rate(int rate) {
+	// No implementation
+}
+
+void set_close_button_callback(void(*proc)()) {
+	// No implementation
+}
+
+} // namespace AGS3
diff --git a/engines/ags/stubs/allegro/system.h b/engines/ags/stubs/allegro/system.h
new file mode 100644
index 0000000000..0f67246006
--- /dev/null
+++ b/engines/ags/stubs/allegro/system.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 AGS_STUBS_ALLEGRO_SYSTEM_H
+#define AGS_STUBS_ALLEGRO_SYSTEM_H
+
+#include "ags/stubs/allegro/base.h"
+#include "ags/stubs/allegro/color.h"
+#include "ags/stubs/allegro/gfx.h"
+
+namespace AGS3 {
+
+#ifndef AL_METHOD
+#define AL_METHOD(type, name, args)             type (*name) args
+#endif
+
+#define SYSTEM_AUTODETECT  0
+#define SYSTEM_NONE        AL_ID('N','O','N','E')
+
+
+struct GFX_MODE {
+	int width, height, bpp;
+};
+
+struct GFX_MODE_LIST {
+	int num_modes;                /* number of gfx modes */
+	GFX_MODE *mode;               /* pointer to the actual mode list array */
+};
+
+struct SYSTEM_DRIVER {
+	int  id;
+	char *name;
+	char *desc;
+	char *ascii_name;
+	AL_METHOD(int, init, (void));
+	AL_METHOD(void, exit, (void));
+	AL_METHOD(void, get_executable_name, (char *output, int size));
+	AL_METHOD(int, find_resource, (char *dest, const char *resource, int size));
+	AL_METHOD(void, set_window_title, (const char *name));
+	AL_METHOD(int, set_close_button_callback, (AL_METHOD(void, proc, (void))));
+	AL_METHOD(void, message, (const char *msg));
+	AL_METHOD(void, assert, (const char *msg));
+	AL_METHOD(void, save_console_state, (void));
+	AL_METHOD(void, restore_console_state, (void));
+	AL_METHOD(BITMAP *, create_bitmap, (int color_depth, int width, int height));
+	AL_METHOD(void, created_bitmap, (BITMAP *bmp));
+	AL_METHOD(BITMAP *, create_sub_bitmap, (BITMAP *parent, int x, int y, int width, int height));
+	AL_METHOD(void, created_sub_bitmap, (BITMAP *bmp, BITMAP *parent));
+	AL_METHOD(int, destroy_bitmap, (BITMAP *bitmap));
+	AL_METHOD(void, read_hardware_palette, (void));
+	AL_METHOD(void, set_palette_range, (const RGB *p, int from, int to, int retracesync));
+	AL_METHOD(struct GFX_VTABLE *, get_vtable, (int color_depth));
+	AL_METHOD(int, set_display_switch_mode, (int mode));
+	AL_METHOD(void, display_switch_lock, (int lock, int foreground));
+	AL_METHOD(int, desktop_color_depth, (void));
+	AL_METHOD(int, get_desktop_resolution, (int *width, int *height));
+	AL_METHOD(void, get_gfx_safe_mode, (int *driver, struct GFX_MODE *mode));
+	AL_METHOD(void, yield_timeslice, (void));
+	AL_METHOD(void *, create_mutex, (void));
+	AL_METHOD(void, destroy_mutex, (void *handle));
+	AL_METHOD(void, lock_mutex, (void *handle));
+	AL_METHOD(void, unlock_mutex, (void *handle));
+	AL_METHOD(_DRIVER_INFO *, gfx_drivers, (void));
+	AL_METHOD(_DRIVER_INFO *, digi_drivers, (void));
+	AL_METHOD(_DRIVER_INFO *, midi_drivers, (void));
+	AL_METHOD(_DRIVER_INFO *, keyboard_drivers, (void));
+	AL_METHOD(_DRIVER_INFO *, mouse_drivers, (void));
+	AL_METHOD(_DRIVER_INFO *, joystick_drivers, (void));
+	AL_METHOD(_DRIVER_INFO *, timer_drivers, (void));
+};
+
+extern SYSTEM_DRIVER system_none;
+extern SYSTEM_DRIVER *system_driver;
+extern _DRIVER_INFO _system_driver_list[];
+
+extern void set_color_depth(int depth);
+extern int get_color_depth();
+extern int get_desktop_resolution(int *width, int *height);
+extern void request_refresh_rate(int rate);
+extern void set_close_button_callback(void(*proc)());
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/stubs/allegro/unicode.cpp b/engines/ags/stubs/allegro/unicode.cpp
new file mode 100644
index 0000000000..36372960e2
--- /dev/null
+++ b/engines/ags/stubs/allegro/unicode.cpp
@@ -0,0 +1,37 @@
+/* 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 "ags/stubs/allegro/unicode.h"
+#include "common/textconsole.h"
+
+namespace AGS3 {
+
+void set_uformat(int format) {
+	// TODO: implementation
+}
+
+size_t ustrsize(const char *s) {
+	error("TODO: ustrsize");
+}
+
+
+} // namespace AGS3
diff --git a/engines/ags/stubs/allegro/unicode.h b/engines/ags/stubs/allegro/unicode.h
new file mode 100644
index 0000000000..24e84d913a
--- /dev/null
+++ b/engines/ags/stubs/allegro/unicode.h
@@ -0,0 +1,41 @@
+/* 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 AGS_STUBS_ALLEGRO_UNICODE_H
+#define AGS_STUBS_ALLEGRO_UNICODE_H
+
+#include "ags/stubs/allegro/base.h"
+
+namespace AGS3 {
+
+#define U_ASCII         AL_ID('A','S','C','8')
+#define U_ASCII_CP      AL_ID('A','S','C','P')
+#define U_UNICODE       AL_ID('U','N','I','C')
+#define U_UTF8          AL_ID('U','T','F','8')
+#define U_CURRENT       AL_ID('c','u','r','.')
+
+extern void set_uformat(int format);
+extern size_t ustrsize(const char *s);
+
+} // namespace AGS3
+
+#endif


Commit: a60d290a08737b4543c86923fb13101a50f10bc2
    https://github.com/scummvm/scummvm/commit/a60d290a08737b4543c86923fb13101a50f10bc2
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Initial addition of engine/ and shared/ folders

Changed paths:
  A engines/ags/engine/ac/asset_helper.h
  A engines/ags/engine/ac/audiochannel.cpp
  A engines/ags/engine/ac/audiochannel.h
  A engines/ags/engine/ac/audioclip.cpp
  A engines/ags/engine/ac/audioclip.h
  A engines/ags/engine/ac/button.cpp
  A engines/ags/engine/ac/button.h
  A engines/ags/engine/ac/cdaudio.cpp
  A engines/ags/engine/ac/cdaudio.h
  A engines/ags/engine/ac/character.cpp
  A engines/ags/engine/ac/character.h
  A engines/ags/engine/ac/charactercache.h
  A engines/ags/engine/ac/characterextras.cpp
  A engines/ags/engine/ac/characterextras.h
  A engines/ags/engine/ac/characterinfo_engine.cpp
  A engines/ags/engine/ac/datetime.cpp
  A engines/ags/engine/ac/datetime.h
  A engines/ags/engine/ac/dialog.cpp
  A engines/ags/engine/ac/dialog.h
  A engines/ags/engine/ac/dialogoptionsrendering.cpp
  A engines/ags/engine/ac/dialogoptionsrendering.h
  A engines/ags/engine/ac/display.cpp
  A engines/ags/engine/ac/display.h
  A engines/ags/engine/ac/draw.cpp
  A engines/ags/engine/ac/draw.h
  A engines/ags/engine/ac/draw_software.cpp
  A engines/ags/engine/ac/draw_software.h
  A engines/ags/engine/ac/drawingsurface.cpp
  A engines/ags/engine/ac/drawingsurface.h
  A engines/ags/engine/ac/dynamicsprite.cpp
  A engines/ags/engine/ac/dynamicsprite.h
  A engines/ags/engine/ac/dynobj/all_dynamicclasses.h
  A engines/ags/engine/ac/dynobj/all_scriptclasses.h
  A engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp
  A engines/ags/engine/ac/dynobj/cc_agsdynamicobject.h
  A engines/ags/engine/ac/dynobj/cc_audiochannel.cpp
  A engines/ags/engine/ac/dynobj/cc_audiochannel.h
  A engines/ags/engine/ac/dynobj/cc_audioclip.cpp
  A engines/ags/engine/ac/dynobj/cc_audioclip.h
  A engines/ags/engine/ac/dynobj/cc_character.cpp
  A engines/ags/engine/ac/dynobj/cc_character.h
  A engines/ags/engine/ac/dynobj/cc_dialog.cpp
  A engines/ags/engine/ac/dynobj/cc_dialog.h
  A engines/ags/engine/ac/dynobj/cc_dynamicarray.cpp
  A engines/ags/engine/ac/dynobj/cc_dynamicarray.h
  A engines/ags/engine/ac/dynobj/cc_dynamicobject.cpp
  A engines/ags/engine/ac/dynobj/cc_dynamicobject.h
  A engines/ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h
  A engines/ags/engine/ac/dynobj/cc_gui.cpp
  A engines/ags/engine/ac/dynobj/cc_gui.h
  A engines/ags/engine/ac/dynobj/cc_guiobject.cpp
  A engines/ags/engine/ac/dynobj/cc_guiobject.h
  A engines/ags/engine/ac/dynobj/cc_hotspot.cpp
  A engines/ags/engine/ac/dynobj/cc_hotspot.h
  A engines/ags/engine/ac/dynobj/cc_inventory.cpp
  A engines/ags/engine/ac/dynobj/cc_inventory.h
  A engines/ags/engine/ac/dynobj/cc_object.cpp
  A engines/ags/engine/ac/dynobj/cc_object.h
  A engines/ags/engine/ac/dynobj/cc_region.cpp
  A engines/ags/engine/ac/dynobj/cc_region.h
  A engines/ags/engine/ac/dynobj/cc_serializer.cpp
  A engines/ags/engine/ac/dynobj/cc_serializer.h
  A engines/ags/engine/ac/dynobj/managedobjectpool.cpp
  A engines/ags/engine/ac/dynobj/managedobjectpool.h
  A engines/ags/engine/ac/dynobj/scriptaudiochannel.h
  A engines/ags/engine/ac/dynobj/scriptcamera.cpp
  A engines/ags/engine/ac/dynobj/scriptcamera.h
  A engines/ags/engine/ac/dynobj/scriptcontainers.h
  A engines/ags/engine/ac/dynobj/scriptdatetime.cpp
  A engines/ags/engine/ac/dynobj/scriptdatetime.h
  A engines/ags/engine/ac/dynobj/scriptdialog.h
  A engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.cpp
  A engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.h
  A engines/ags/engine/ac/dynobj/scriptdict.cpp
  A engines/ags/engine/ac/dynobj/scriptdict.h
  A engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp
  A engines/ags/engine/ac/dynobj/scriptdrawingsurface.h
  A engines/ags/engine/ac/dynobj/scriptdynamicsprite.cpp
  A engines/ags/engine/ac/dynobj/scriptdynamicsprite.h
  A engines/ags/engine/ac/dynobj/scriptfile.cpp
  A engines/ags/engine/ac/dynobj/scriptfile.h
  A engines/ags/engine/ac/dynobj/scriptgui.h
  A engines/ags/engine/ac/dynobj/scripthotspot.h
  A engines/ags/engine/ac/dynobj/scriptinvitem.h
  A engines/ags/engine/ac/dynobj/scriptmouse.h
  A engines/ags/engine/ac/dynobj/scriptobject.h
  A engines/ags/engine/ac/dynobj/scriptoverlay.cpp
  A engines/ags/engine/ac/dynobj/scriptoverlay.h
  A engines/ags/engine/ac/dynobj/scriptregion.h
  A engines/ags/engine/ac/dynobj/scriptset.cpp
  A engines/ags/engine/ac/dynobj/scriptset.h
  A engines/ags/engine/ac/dynobj/scriptstring.cpp
  A engines/ags/engine/ac/dynobj/scriptstring.h
  A engines/ags/engine/ac/dynobj/scriptsystem.h
  A engines/ags/engine/ac/dynobj/scriptuserobject.cpp
  A engines/ags/engine/ac/dynobj/scriptuserobject.h
  A engines/ags/engine/ac/dynobj/scriptviewframe.cpp
  A engines/ags/engine/ac/dynobj/scriptviewframe.h
  A engines/ags/engine/ac/dynobj/scriptviewport.cpp
  A engines/ags/engine/ac/dynobj/scriptviewport.h
  A engines/ags/engine/ac/event.cpp
  A engines/ags/engine/ac/event.h
  A engines/ags/engine/ac/file.cpp
  A engines/ags/engine/ac/file.h
  A engines/ags/engine/ac/game.cpp
  A engines/ags/engine/ac/game.h
  A engines/ags/engine/ac/gamesetup.cpp
  A engines/ags/engine/ac/gamesetup.h
  A engines/ags/engine/ac/gamestate.cpp
  A engines/ags/engine/ac/gamestate.h
  A engines/ags/engine/ac/global_api.cpp
  A engines/ags/engine/ac/global_audio.cpp
  A engines/ags/engine/ac/global_audio.h
  A engines/ags/engine/ac/global_button.cpp
  A engines/ags/engine/ac/global_button.h
  A engines/ags/engine/ac/global_character.cpp
  A engines/ags/engine/ac/global_character.h
  A engines/ags/engine/ac/global_datetime.cpp
  A engines/ags/engine/ac/global_datetime.h
  A engines/ags/engine/ac/global_debug.cpp
  A engines/ags/engine/ac/global_debug.h
  A engines/ags/engine/ac/global_dialog.cpp
  A engines/ags/engine/ac/global_dialog.h
  A engines/ags/engine/ac/global_display.cpp
  A engines/ags/engine/ac/global_display.h
  A engines/ags/engine/ac/global_drawingsurface.cpp
  A engines/ags/engine/ac/global_drawingsurface.h
  A engines/ags/engine/ac/global_dynamicsprite.cpp
  A engines/ags/engine/ac/global_dynamicsprite.h
  A engines/ags/engine/ac/global_file.cpp
  A engines/ags/engine/ac/global_file.h
  A engines/ags/engine/ac/global_game.cpp
  A engines/ags/engine/ac/global_game.h
  A engines/ags/engine/ac/global_gui.cpp
  A engines/ags/engine/ac/global_gui.h
  A engines/ags/engine/ac/global_hotspot.cpp
  A engines/ags/engine/ac/global_hotspot.h
  A engines/ags/engine/ac/global_inventoryitem.cpp
  A engines/ags/engine/ac/global_inventoryitem.h
  A engines/ags/engine/ac/global_invwindow.cpp
  A engines/ags/engine/ac/global_invwindow.h
  A engines/ags/engine/ac/global_label.cpp
  A engines/ags/engine/ac/global_label.h
  A engines/ags/engine/ac/global_listbox.cpp
  A engines/ags/engine/ac/global_listbox.h
  A engines/ags/engine/ac/global_mouse.cpp
  A engines/ags/engine/ac/global_mouse.h
  A engines/ags/engine/ac/global_object.cpp
  A engines/ags/engine/ac/global_object.h
  A engines/ags/engine/ac/global_overlay.cpp
  A engines/ags/engine/ac/global_overlay.h
  A engines/ags/engine/ac/global_palette.cpp
  A engines/ags/engine/ac/global_palette.h
  A engines/ags/engine/ac/global_parser.cpp
  A engines/ags/engine/ac/global_parser.h
  A engines/ags/engine/ac/global_plugin.h
  A engines/ags/engine/ac/global_record.cpp
  A engines/ags/engine/ac/global_record.h
  A engines/ags/engine/ac/global_region.cpp
  A engines/ags/engine/ac/global_region.h
  A engines/ags/engine/ac/global_room.cpp
  A engines/ags/engine/ac/global_room.h
  A engines/ags/engine/ac/global_screen.cpp
  A engines/ags/engine/ac/global_screen.h
  A engines/ags/engine/ac/global_slider.cpp
  A engines/ags/engine/ac/global_slider.h
  A engines/ags/engine/ac/global_string.cpp
  A engines/ags/engine/ac/global_string.h
  A engines/ags/engine/ac/global_textbox.cpp
  A engines/ags/engine/ac/global_textbox.h
  A engines/ags/engine/ac/global_timer.cpp
  A engines/ags/engine/ac/global_timer.h
  A engines/ags/engine/ac/global_translation.cpp
  A engines/ags/engine/ac/global_translation.h
  A engines/ags/engine/ac/global_video.cpp
  A engines/ags/engine/ac/global_video.h
  A engines/ags/engine/ac/global_viewframe.cpp
  A engines/ags/engine/ac/global_viewframe.h
  A engines/ags/engine/ac/global_viewport.cpp
  A engines/ags/engine/ac/global_viewport.h
  A engines/ags/engine/ac/global_walkablearea.cpp
  A engines/ags/engine/ac/global_walkablearea.h
  A engines/ags/engine/ac/global_walkbehind.cpp
  A engines/ags/engine/ac/global_walkbehind.h
  A engines/ags/engine/ac/gui.cpp
  A engines/ags/engine/ac/gui.h
  A engines/ags/engine/ac/guicontrol.cpp
  A engines/ags/engine/ac/guicontrol.h
  A engines/ags/engine/ac/guiinv.cpp
  A engines/ags/engine/ac/hotspot.cpp
  A engines/ags/engine/ac/hotspot.h
  A engines/ags/engine/ac/interfacebutton.cpp
  A engines/ags/engine/ac/interfaceelement.cpp
  A engines/ags/engine/ac/inventoryitem.cpp
  A engines/ags/engine/ac/inventoryitem.h
  A engines/ags/engine/ac/invwindow.cpp
  A engines/ags/engine/ac/invwindow.h
  A engines/ags/engine/ac/keycode.cpp
  A engines/ags/engine/ac/keycode.h
  A engines/ags/engine/ac/label.cpp
  A engines/ags/engine/ac/label.h
  A engines/ags/engine/ac/lipsync.h
  A engines/ags/engine/ac/listbox.cpp
  A engines/ags/engine/ac/listbox.h
  A engines/ags/engine/ac/math.cpp
  A engines/ags/engine/ac/math.h
  A engines/ags/engine/ac/mouse.cpp
  A engines/ags/engine/ac/mouse.h
  A engines/ags/engine/ac/movelist.cpp
  A engines/ags/engine/ac/movelist.h
  A engines/ags/engine/ac/object.cpp
  A engines/ags/engine/ac/object.h
  A engines/ags/engine/ac/objectcache.h
  A engines/ags/engine/ac/overlay.cpp
  A engines/ags/engine/ac/overlay.h
  A engines/ags/engine/ac/parser.cpp
  A engines/ags/engine/ac/parser.h
  A engines/ags/engine/ac/path_helper.h
  A engines/ags/engine/ac/properties.cpp
  A engines/ags/engine/ac/properties.h
  A engines/ags/engine/ac/region.cpp
  A engines/ags/engine/ac/region.h
  A engines/ags/engine/ac/richgamemedia.cpp
  A engines/ags/engine/ac/richgamemedia.h
  A engines/ags/engine/ac/room.cpp
  A engines/ags/engine/ac/room.h
  A engines/ags/engine/ac/roomobject.cpp
  A engines/ags/engine/ac/roomobject.h
  A engines/ags/engine/ac/roomstatus.cpp
  A engines/ags/engine/ac/roomstatus.h
  A engines/ags/engine/ac/route_finder.cpp
  A engines/ags/engine/ac/route_finder.h
  A engines/ags/engine/ac/route_finder_impl.cpp
  A engines/ags/engine/ac/route_finder_impl.h
  A engines/ags/engine/ac/route_finder_impl_legacy.cpp
  A engines/ags/engine/ac/route_finder_impl_legacy.h
  A engines/ags/engine/ac/route_finder_jps.inl
  A engines/ags/engine/ac/runtime_defines.h
  A engines/ags/engine/ac/screen.cpp
  A engines/ags/engine/ac/screen.h
  A engines/ags/engine/ac/screenoverlay.cpp
  A engines/ags/engine/ac/screenoverlay.h
  A engines/ags/engine/ac/scriptcontainers.cpp
  A engines/ags/engine/ac/slider.cpp
  A engines/ags/engine/ac/slider.h
  A engines/ags/engine/ac/speech.cpp
  A engines/ags/engine/ac/speech.h
  A engines/ags/engine/ac/sprite.cpp
  A engines/ags/engine/ac/sprite.h
  A engines/ags/engine/ac/spritecache_engine.cpp
  A engines/ags/engine/ac/spritelistentry.h
  A engines/ags/engine/ac/statobj/agsstaticobject.cpp
  A engines/ags/engine/ac/statobj/agsstaticobject.h
  A engines/ags/engine/ac/statobj/staticarray.cpp
  A engines/ags/engine/ac/statobj/staticarray.h
  A engines/ags/engine/ac/statobj/staticobject.h
  A engines/ags/engine/ac/string.cpp
  A engines/ags/engine/ac/string.h
  A engines/ags/engine/ac/sys_events.cpp
  A engines/ags/engine/ac/sys_events.h
  A engines/ags/engine/ac/system.cpp
  A engines/ags/engine/ac/system.h
  A engines/ags/engine/ac/textbox.cpp
  A engines/ags/engine/ac/textbox.h
  A engines/ags/engine/ac/timer.cpp
  A engines/ags/engine/ac/timer.h
  A engines/ags/engine/ac/topbarsettings.h
  A engines/ags/engine/ac/translation.cpp
  A engines/ags/engine/ac/translation.h
  A engines/ags/engine/ac/tree_map.cpp
  A engines/ags/engine/ac/tree_map.h
  A engines/ags/engine/ac/viewframe.cpp
  A engines/ags/engine/ac/viewframe.h
  A engines/ags/engine/ac/viewport_script.cpp
  A engines/ags/engine/ac/walkablearea.cpp
  A engines/ags/engine/ac/walkablearea.h
  A engines/ags/engine/ac/walkbehind.cpp
  A engines/ags/engine/ac/walkbehind.h
  A engines/ags/engine/debugging/agseditordebugger.h
  A engines/ags/engine/debugging/consoleoutputtarget.cpp
  A engines/ags/engine/debugging/consoleoutputtarget.h
  A engines/ags/engine/debugging/debug.cpp
  A engines/ags/engine/debugging/debug_log.h
  A engines/ags/engine/debugging/debugger.h
  A engines/ags/engine/debugging/dummyagsdebugger.h
  A engines/ags/engine/debugging/filebasedagsdebugger.cpp
  A engines/ags/engine/debugging/filebasedagsdebugger.h
  A engines/ags/engine/debugging/logfile.cpp
  A engines/ags/engine/debugging/logfile.h
  A engines/ags/engine/debugging/messagebuffer.cpp
  A engines/ags/engine/debugging/messagebuffer.h
  A engines/ags/engine/device/mousew32.cpp
  A engines/ags/engine/device/mousew32.h
  A engines/ags/engine/font/fonts_engine.cpp
  A engines/ags/engine/game/game_init.cpp
  A engines/ags/engine/game/game_init.h
  A engines/ags/engine/game/savegame.cpp
  A engines/ags/engine/game/savegame.h
  A engines/ags/engine/game/savegame_components.cpp
  A engines/ags/engine/game/savegame_components.h
  A engines/ags/engine/game/savegame_internal.h
  A engines/ags/engine/game/viewport.cpp
  A engines/ags/engine/game/viewport.h
  A engines/ags/engine/gfx/ali3dexception.h
  A engines/ags/engine/gfx/ali3dogl.cpp
  A engines/ags/engine/gfx/ali3dogl.h
  A engines/ags/engine/gfx/ali3dsw.cpp
  A engines/ags/engine/gfx/ali3dsw.h
  A engines/ags/engine/gfx/blender.cpp
  A engines/ags/engine/gfx/blender.h
  A engines/ags/engine/gfx/color_engine.cpp
  A engines/ags/engine/gfx/ddb.h
  A engines/ags/engine/gfx/gfx_util.cpp
  A engines/ags/engine/gfx/gfx_util.h
  A engines/ags/engine/gfx/gfxdefines.h
  A engines/ags/engine/gfx/gfxdriverbase.cpp
  A engines/ags/engine/gfx/gfxdriverbase.h
  A engines/ags/engine/gfx/gfxdriverfactory.cpp
  A engines/ags/engine/gfx/gfxdriverfactory.h
  A engines/ags/engine/gfx/gfxdriverfactorybase.h
  A engines/ags/engine/gfx/gfxfilter.h
  A engines/ags/engine/gfx/gfxfilter_aad3d.cpp
  A engines/ags/engine/gfx/gfxfilter_aad3d.h
  A engines/ags/engine/gfx/gfxfilter_aaogl.cpp
  A engines/ags/engine/gfx/gfxfilter_aaogl.h
  A engines/ags/engine/gfx/gfxfilter_allegro.cpp
  A engines/ags/engine/gfx/gfxfilter_allegro.h
  A engines/ags/engine/gfx/gfxfilter_d3d.cpp
  A engines/ags/engine/gfx/gfxfilter_d3d.h
  A engines/ags/engine/gfx/gfxfilter_hqx.cpp
  A engines/ags/engine/gfx/gfxfilter_hqx.h
  A engines/ags/engine/gfx/gfxfilter_ogl.cpp
  A engines/ags/engine/gfx/gfxfilter_ogl.h
  A engines/ags/engine/gfx/gfxfilter_scaling.cpp
  A engines/ags/engine/gfx/gfxfilter_scaling.h
  A engines/ags/engine/gfx/gfxmodelist.h
  A engines/ags/engine/gfx/graphicsdriver.h
  A engines/ags/engine/gfx/hq2x3x.h
  A engines/ags/engine/gfx/ogl_headers.h
  A engines/ags/engine/gui/animatingguibutton.cpp
  A engines/ags/engine/gui/animatingguibutton.h
  A engines/ags/engine/gui/cscidialog.cpp
  A engines/ags/engine/gui/cscidialog.h
  A engines/ags/engine/gui/gui_engine.cpp
  A engines/ags/engine/gui/guidialog.cpp
  A engines/ags/engine/gui/guidialog.h
  A engines/ags/engine/gui/guidialogdefines.h
  A engines/ags/engine/gui/guidialoginternaldefs.h
  A engines/ags/engine/gui/mycontrols.h
  A engines/ags/engine/gui/mylabel.cpp
  A engines/ags/engine/gui/mylabel.h
  A engines/ags/engine/gui/mylistbox.cpp
  A engines/ags/engine/gui/mylistbox.h
  A engines/ags/engine/gui/mypushbutton.cpp
  A engines/ags/engine/gui/mypushbutton.h
  A engines/ags/engine/gui/mytextbox.cpp
  A engines/ags/engine/gui/mytextbox.h
  A engines/ags/engine/gui/newcontrol.cpp
  A engines/ags/engine/gui/newcontrol.h
  A engines/ags/engine/main/config.cpp
  A engines/ags/engine/main/config.h
  A engines/ags/engine/main/engine.cpp
  A engines/ags/engine/main/engine.h
  A engines/ags/engine/main/engine_setup.cpp
  A engines/ags/engine/main/engine_setup.h
  A engines/ags/engine/main/game_file.cpp
  A engines/ags/engine/main/game_file.h
  A engines/ags/engine/main/game_run.cpp
  A engines/ags/engine/main/game_run.h
  A engines/ags/engine/main/game_start.cpp
  A engines/ags/engine/main/game_start.h
  A engines/ags/engine/main/graphics_mode.cpp
  A engines/ags/engine/main/graphics_mode.h
  A engines/ags/engine/main/main.cpp
  A engines/ags/engine/main/main.h
  A engines/ags/engine/main/main_allegro.cpp
  A engines/ags/engine/main/main_allegro.h
  A engines/ags/engine/main/maindefines_ex.h
  A engines/ags/engine/main/mainheader.h
  A engines/ags/engine/main/quit.cpp
  A engines/ags/engine/main/quit.h
  A engines/ags/engine/main/update.cpp
  A engines/ags/engine/main/update.h
  A engines/ags/engine/media/audio/ambientsound.cpp
  A engines/ags/engine/media/audio/ambientsound.h
  A engines/ags/engine/media/audio/audio.cpp
  A engines/ags/engine/media/audio/audio.h
  A engines/ags/engine/media/audio/audio_system.h
  A engines/ags/engine/media/audio/audiodefines.h
  A engines/ags/engine/media/audio/audiointernaldefs.h
  A engines/ags/engine/media/audio/clip_mydumbmod.cpp
  A engines/ags/engine/media/audio/clip_mydumbmod.h
  A engines/ags/engine/media/audio/clip_myjgmod.cpp
  A engines/ags/engine/media/audio/clip_myjgmod.h
  A engines/ags/engine/media/audio/clip_mymidi.cpp
  A engines/ags/engine/media/audio/clip_mymidi.h
  A engines/ags/engine/media/audio/clip_mymp3.cpp
  A engines/ags/engine/media/audio/clip_mymp3.h
  A engines/ags/engine/media/audio/clip_myogg.cpp
  A engines/ags/engine/media/audio/clip_myogg.h
  A engines/ags/engine/media/audio/clip_mystaticmp3.cpp
  A engines/ags/engine/media/audio/clip_mystaticmp3.h
  A engines/ags/engine/media/audio/clip_mystaticogg.cpp
  A engines/ags/engine/media/audio/clip_mystaticogg.h
  A engines/ags/engine/media/audio/clip_mywave.cpp
  A engines/ags/engine/media/audio/clip_mywave.h
  A engines/ags/engine/media/audio/queuedaudioitem.cpp
  A engines/ags/engine/media/audio/queuedaudioitem.h
  A engines/ags/engine/media/audio/sound.cpp
  A engines/ags/engine/media/audio/sound.h
  A engines/ags/engine/media/audio/soundcache.cpp
  A engines/ags/engine/media/audio/soundcache.h
  A engines/ags/engine/media/audio/soundclip.cpp
  A engines/ags/engine/media/audio/soundclip.h
  A engines/ags/engine/media/video/VMR9Graph.h
  A engines/ags/engine/media/video/video.cpp
  A engines/ags/engine/media/video/video.h
  A engines/ags/engine/platform/android/acpland.cpp
  A engines/ags/engine/platform/base/agsplatformdriver.cpp
  A engines/ags/engine/platform/base/agsplatformdriver.h
  A engines/ags/engine/platform/ios/acplios.cpp
  A engines/ags/engine/platform/linux/acpllnx.cpp
  A engines/ags/engine/platform/linux/icon.xpm
  A engines/ags/engine/platform/osx/acplmac.cpp
  A engines/ags/engine/platform/osx/alplmac.mm
  A engines/ags/engine/platform/util/libc.c
  A engines/ags/engine/platform/util/pe.c
  A engines/ags/engine/platform/util/pe.h
  A engines/ags/engine/platform/windows/acplwin.cpp
  A engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
  A engines/ags/engine/platform/windows/gfx/ali3dd3d.h
  A engines/ags/engine/platform/windows/media/video/acwavi.cpp
  A engines/ags/engine/platform/windows/media/video/acwavi3d.cpp
  A engines/ags/engine/platform/windows/minidump.cpp
  A engines/ags/engine/platform/windows/setup/winsetup.cpp
  A engines/ags/engine/platform/windows/setup/winsetup.h
  A engines/ags/engine/platform/windows/win_ex_handling.cpp
  A engines/ags/engine/platform/windows/win_ex_handling.h
  A engines/ags/engine/platform/windows/winapi_exclusive.h
  A engines/ags/engine/plugin/agsplugin.cpp
  A engines/ags/engine/plugin/agsplugin.h
  A engines/ags/engine/plugin/global_plugin.cpp
  A engines/ags/engine/plugin/plugin_builtin.h
  A engines/ags/engine/plugin/plugin_engine.h
  A engines/ags/engine/plugin/pluginobjectreader.cpp
  A engines/ags/engine/plugin/pluginobjectreader.h
  A engines/ags/engine/resource/DefaultGDF.gdf.xml
  A engines/ags/engine/resource/game-1.ICO
  A engines/ags/engine/resource/resource.h
  A engines/ags/engine/resource/tintshader.fx
  A engines/ags/engine/resource/tintshader.fxo
  A engines/ags/engine/resource/tintshaderLegacy.fx
  A engines/ags/engine/resource/tintshaderLegacy.fxo
  A engines/ags/engine/resource/version.rc
  A engines/ags/engine/script/cc_error_engine.cpp
  A engines/ags/engine/script/cc_instance.cpp
  A engines/ags/engine/script/cc_instance.h
  A engines/ags/engine/script/executingscript.cpp
  A engines/ags/engine/script/executingscript.h
  A engines/ags/engine/script/exports.cpp
  A engines/ags/engine/script/exports.h
  A engines/ags/engine/script/nonblockingscriptfunction.h
  A engines/ags/engine/script/runtimescriptvalue.cpp
  A engines/ags/engine/script/runtimescriptvalue.h
  A engines/ags/engine/script/script.cpp
  A engines/ags/engine/script/script.h
  A engines/ags/engine/script/script_api.cpp
  A engines/ags/engine/script/script_api.h
  A engines/ags/engine/script/script_engine.cpp
  A engines/ags/engine/script/script_runtime.cpp
  A engines/ags/engine/script/script_runtime.h
  A engines/ags/engine/script/systemimports.cpp
  A engines/ags/engine/script/systemimports.h
  A engines/ags/engine/util/library.h
  A engines/ags/engine/util/library_dummy.h
  A engines/ags/engine/util/library_posix.h
  A engines/ags/engine/util/library_psp.h
  A engines/ags/engine/util/library_windows.h
  A engines/ags/engine/util/mutex.h
  A engines/ags/engine/util/mutex_base.h
  A engines/ags/engine/util/mutex_lock.h
  A engines/ags/engine/util/mutex_psp.h
  A engines/ags/engine/util/mutex_pthread.h
  A engines/ags/engine/util/mutex_std.h
  A engines/ags/engine/util/mutex_wii.h
  A engines/ags/engine/util/mutex_windows.h
  A engines/ags/engine/util/scaling.h
  A engines/ags/engine/util/thread.h
  A engines/ags/engine/util/thread_psp.h
  A engines/ags/engine/util/thread_pthread.h
  A engines/ags/engine/util/thread_std.h
  A engines/ags/engine/util/thread_wii.h
  A engines/ags/engine/util/thread_windows.h
  A engines/ags/shared/ac/audiocliptype.cpp
  A engines/ags/shared/ac/audiocliptype.h
  A engines/ags/shared/ac/characterinfo.cpp
  A engines/ags/shared/ac/characterinfo.h
  A engines/ags/shared/ac/common.cpp
  A engines/ags/shared/ac/common.h
  A engines/ags/shared/ac/common_defines.h
  A engines/ags/shared/ac/dialogtopic.cpp
  A engines/ags/shared/ac/dialogtopic.h
  A engines/ags/shared/ac/dynobj/scriptaudioclip.cpp
  A engines/ags/shared/ac/dynobj/scriptaudioclip.h
  A engines/ags/shared/ac/game_version.h
  A engines/ags/shared/ac/gamesetupstruct.cpp
  A engines/ags/shared/ac/gamesetupstruct.h
  A engines/ags/shared/ac/gamesetupstructbase.cpp
  A engines/ags/shared/ac/gamesetupstructbase.h
  A engines/ags/shared/ac/gamestructdefines.h
  A engines/ags/shared/ac/interfacebutton.h
  A engines/ags/shared/ac/interfaceelement.h
  A engines/ags/shared/ac/inventoryiteminfo.cpp
  A engines/ags/shared/ac/inventoryiteminfo.h
  A engines/ags/shared/ac/mousecursor.cpp
  A engines/ags/shared/ac/mousecursor.h
  A engines/ags/shared/ac/oldgamesetupstruct.h
  A engines/ags/shared/ac/spritecache.cpp
  A engines/ags/shared/ac/spritecache.h
  A engines/ags/shared/ac/view.cpp
  A engines/ags/shared/ac/view.h
  A engines/ags/shared/ac/wordsdictionary.cpp
  A engines/ags/shared/ac/wordsdictionary.h
  A engines/ags/shared/api/stream_api.h
  A engines/ags/shared/core/asset.cpp
  A engines/ags/shared/core/asset.h
  A engines/ags/shared/core/assetmanager.cpp
  A engines/ags/shared/core/assetmanager.h
  A engines/ags/shared/core/def_version.h
  A engines/ags/shared/core/platform.h
  A engines/ags/shared/core/types.h
  A engines/ags/shared/debugging/assert.h
  A engines/ags/shared/debugging/debugmanager.cpp
  A engines/ags/shared/debugging/debugmanager.h
  A engines/ags/shared/debugging/out.h
  A engines/ags/shared/debugging/outputhandler.h
  A engines/ags/shared/font/agsfontrenderer.h
  A engines/ags/shared/font/fonts.cpp
  A engines/ags/shared/font/fonts.h
  A engines/ags/shared/font/ttffontrenderer.cpp
  A engines/ags/shared/font/ttffontrenderer.h
  A engines/ags/shared/font/wfnfont.cpp
  A engines/ags/shared/font/wfnfont.h
  A engines/ags/shared/font/wfnfontrenderer.cpp
  A engines/ags/shared/font/wfnfontrenderer.h
  A engines/ags/shared/game/customproperties.cpp
  A engines/ags/shared/game/customproperties.h
  A engines/ags/shared/game/interactions.cpp
  A engines/ags/shared/game/interactions.h
  A engines/ags/shared/game/main_game_file.cpp
  A engines/ags/shared/game/main_game_file.h
  A engines/ags/shared/game/plugininfo.h
  A engines/ags/shared/game/room_file.cpp
  A engines/ags/shared/game/room_file.h
  A engines/ags/shared/game/room_file_deprecated.cpp
  A engines/ags/shared/game/room_version.h
  A engines/ags/shared/game/roomstruct.cpp
  A engines/ags/shared/game/roomstruct.h
  A engines/ags/shared/gfx/allegrobitmap.cpp
  A engines/ags/shared/gfx/allegrobitmap.h
  A engines/ags/shared/gfx/bitmap.cpp
  A engines/ags/shared/gfx/bitmap.h
  A engines/ags/shared/gfx/gfx_def.h
  A engines/ags/shared/gui/guibutton.cpp
  A engines/ags/shared/gui/guibutton.h
  A engines/ags/shared/gui/guidefines.h
  A engines/ags/shared/gui/guiinv.cpp
  A engines/ags/shared/gui/guiinv.h
  A engines/ags/shared/gui/guilabel.cpp
  A engines/ags/shared/gui/guilabel.h
  A engines/ags/shared/gui/guilistbox.cpp
  A engines/ags/shared/gui/guilistbox.h
  A engines/ags/shared/gui/guimain.cpp
  A engines/ags/shared/gui/guimain.h
  A engines/ags/shared/gui/guiobject.cpp
  A engines/ags/shared/gui/guiobject.h
  A engines/ags/shared/gui/guislider.cpp
  A engines/ags/shared/gui/guislider.h
  A engines/ags/shared/gui/guitextbox.cpp
  A engines/ags/shared/gui/guitextbox.h
  A engines/ags/shared/script/cc_error.cpp
  A engines/ags/shared/script/cc_error.h
  A engines/ags/shared/script/cc_options.cpp
  A engines/ags/shared/script/cc_options.h
  A engines/ags/shared/script/cc_script.cpp
  A engines/ags/shared/script/cc_script.h
  A engines/ags/shared/script/script_common.h
  A engines/ags/shared/util/alignedstream.cpp
  A engines/ags/shared/util/alignedstream.h
  A engines/ags/shared/util/bbop.h
  A engines/ags/shared/util/bufferedstream.cpp
  A engines/ags/shared/util/bufferedstream.h
  A engines/ags/shared/util/compress.cpp
  A engines/ags/shared/util/compress.h
  A engines/ags/shared/util/datastream.cpp
  A engines/ags/shared/util/datastream.h
  A engines/ags/shared/util/directory.cpp
  A engines/ags/shared/util/directory.h
  A engines/ags/shared/util/error.h
  A engines/ags/shared/util/file.cpp
  A engines/ags/shared/util/file.h
  A engines/ags/shared/util/filestream.cpp
  A engines/ags/shared/util/filestream.h
  A engines/ags/shared/util/geometry.cpp
  A engines/ags/shared/util/geometry.h
  A engines/ags/shared/util/ini_util.cpp
  A engines/ags/shared/util/ini_util.h
  A engines/ags/shared/util/inifile.cpp
  A engines/ags/shared/util/inifile.h
  A engines/ags/shared/util/lzw.cpp
  A engines/ags/shared/util/lzw.h
  A engines/ags/shared/util/math.h
  A engines/ags/shared/util/memory.h
  A engines/ags/shared/util/misc.cpp
  A engines/ags/shared/util/misc.h
  A engines/ags/shared/util/multifilelib.h
  A engines/ags/shared/util/mutifilelib.cpp
  A engines/ags/shared/util/path.cpp
  A engines/ags/shared/util/path.h
  A engines/ags/shared/util/proxystream.cpp
  A engines/ags/shared/util/proxystream.h
  A engines/ags/shared/util/stdio_compat.c
  A engines/ags/shared/util/stdio_compat.h
  A engines/ags/shared/util/stream.cpp
  A engines/ags/shared/util/stream.h
  A engines/ags/shared/util/string.cpp
  A engines/ags/shared/util/string.h
  A engines/ags/shared/util/string_compat.c
  A engines/ags/shared/util/string_compat.h
  A engines/ags/shared/util/string_types.h
  A engines/ags/shared/util/string_utils.cpp
  A engines/ags/shared/util/string_utils.h
  A engines/ags/shared/util/textreader.h
  A engines/ags/shared/util/textstreamreader.cpp
  A engines/ags/shared/util/textstreamreader.h
  A engines/ags/shared/util/textstreamwriter.cpp
  A engines/ags/shared/util/textstreamwriter.h
  A engines/ags/shared/util/textwriter.h
  A engines/ags/shared/util/version.cpp
  A engines/ags/shared/util/version.h
  A engines/ags/shared/util/wgt2allg.cpp
  A engines/ags/shared/util/wgt2allg.h


diff --git a/engines/ags/engine/ac/asset_helper.h b/engines/ags/engine/ac/asset_helper.h
new file mode 100644
index 0000000000..9c6c442166
--- /dev/null
+++ b/engines/ags/engine/ac/asset_helper.h
@@ -0,0 +1,67 @@
+//=============================================================================
+//
+// Adventure Game Studio (AGS)
+//
+// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
+// The full list of copyright holders can be found in the Copyright.txt
+// file, which is part of this source code distribution.
+//
+// The AGS source code is provided under the Artistic License 2.0.
+// A copy of this license can be found in the file License.txt and at
+// http://www.opensource.org/licenses/artistic-license-2.0.php
+//
+//=============================================================================
+//
+// Functions related to finding and opening game assets.
+//
+//=============================================================================
+#ifndef __AGS_EE_AC__ASSETHELPER_H
+#define __AGS_EE_AC__ASSETHELPER_H
+#include <memory>
+#include <utility>
+#include "util/string.h"
+
+namespace AGS { namespace Common {class Stream;}}
+using AGS::Common::Stream;
+using AGS::Common::String;
+
+// Looks for valid asset library everywhere and returns path, or empty string if failed
+String  find_assetlib(const String &filename);
+// Looks up for known valid asset library and returns path, or empty string if failed
+String  get_known_assetlib(const String &filename);
+// Looks for asset everywhere and returns opened stream, or NULL if failed
+Stream *find_open_asset(const String &filename);
+
+extern "C" {
+    struct PACKFILE; // Allegro 4's own stream type
+    struct DUMBFILE; // DUMB stream type
+}
+
+// AssetPath combines asset library and item names
+// TODO: implement support for registering multiple libraries at once for
+// the AssetManager, then we could remove assetlib parameter.
+typedef std::pair<String, String> AssetPath;
+
+// Returns the path to the audio asset, considering the given bundling type
+AssetPath get_audio_clip_assetpath(int bundling_type, const String &filename);
+// Returns the path to the voice-over asset
+AssetPath get_voice_over_assetpath(const String &filename);
+
+// Custom AGS PACKFILE user object
+// TODO: it is preferrable to let our Stream define custom readable window instead,
+// keeping this as simple as possible for now (we may require a stream classes overhaul).
+struct AGS_PACKFILE_OBJ
+{
+    std::unique_ptr<Stream> stream;
+    size_t asset_size = 0u;
+    size_t remains = 0u;
+};
+// Creates PACKFILE stream from AGS asset.
+// This function is supposed to be used only when you have to create Allegro
+// object, passing PACKFILE stream to constructor.
+PACKFILE *PackfileFromAsset(const AssetPath &path, size_t &asset_size);
+// Creates DUMBFILE stream from AGS asset. Used for creating DUMB objects
+DUMBFILE *DUMBfileFromAsset(const AssetPath &path, size_t &asset_size);
+bool DoesAssetExistInLib(const AssetPath &assetname);
+
+#endif // __AGS_EE_AC__ASSETHELPER_H
diff --git a/engines/ags/engine/ac/audiochannel.cpp b/engines/ags/engine/ac/audiochannel.cpp
new file mode 100644
index 0000000000..4ac75c4e7a
--- /dev/null
+++ b/engines/ags/engine/ac/audiochannel.cpp
@@ -0,0 +1,353 @@
+//=============================================================================
+//
+// Adventure Game Studio (AGS)
+//
+// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
+// The full list of copyright holders can be found in the Copyright.txt
+// file, which is part of this source code distribution.
+//
+// The AGS source code is provided under the Artistic License 2.0.
+// A copy of this license can be found in the file License.txt and at
+// http://www.opensource.org/licenses/artistic-license-2.0.php
+//
+//=============================================================================
+
+#include "ac/audiochannel.h"
+#include "ac/gamestate.h"
+#include "ac/global_audio.h"
+#include "ac/dynobj/cc_audioclip.h"
+#include "debug/debug_log.h"
+#include "game/roomstruct.h"
+#include "script/runtimescriptvalue.h"
+#include "media/audio/audio_system.h"
+
+using namespace AGS::Common;
+
+extern GameState play;
+extern RoomStruct thisroom;
+extern CCAudioClip ccDynamicAudioClip;
+
+int AudioChannel_GetID(ScriptAudioChannel *channel)
+{
+    return channel->id;
+}
+
+int AudioChannel_GetIsPlaying(ScriptAudioChannel *channel)
+{
+    if (play.fast_forward)
+    {
+        return 0;
+    }
+
+    return channel_is_playing(channel->id) ? 1 : 0;
+}
+
+int AudioChannel_GetPanning(ScriptAudioChannel *channel)
+{
+    AudioChannelsLock lock;
+    auto* ch = lock.GetChannelIfPlaying(channel->id);
+
+    if (ch)
+    {
+        return ch->panningAsPercentage;
+    }
+    return 0;
+}
+
+void AudioChannel_SetPanning(ScriptAudioChannel *channel, int newPanning)
+{
+    if ((newPanning < -100) || (newPanning > 100))
+        quitprintf("!AudioChannel.Panning: panning value must be between -100 and 100 (passed=%d)", newPanning);
+
+    AudioChannelsLock lock;
+    auto* ch = lock.GetChannelIfPlaying(channel->id);
+
+    if (ch)
+    {
+        ch->set_panning(((newPanning + 100) * 255) / 200);
+        ch->panningAsPercentage = newPanning;
+    }
+}
+
+ScriptAudioClip* AudioChannel_GetPlayingClip(ScriptAudioChannel *channel)
+{
+    AudioChannelsLock lock;
+    auto* ch = lock.GetChannelIfPlaying(channel->id);
+
+    if (ch)
+    {
+        return (ScriptAudioClip*)ch->sourceClip;
+    }
+    return nullptr;
+}
+
+int AudioChannel_GetPosition(ScriptAudioChannel *channel)
+{
+    AudioChannelsLock lock;
+    auto* ch = lock.GetChannelIfPlaying(channel->id);
+
+    if (ch)
+    {
+        if (play.fast_forward)
+            return 999999999;
+
+        return ch->get_pos();
+    }
+    return 0;
+}
+
+int AudioChannel_GetPositionMs(ScriptAudioChannel *channel)
+{
+    AudioChannelsLock lock;
+    auto* ch = lock.GetChannelIfPlaying(channel->id);
+
+    if (ch)
+    {
+        if (play.fast_forward)
+            return 999999999;
+
+        return ch->get_pos_ms();
+    }
+    return 0;
+}
+
+int AudioChannel_GetLengthMs(ScriptAudioChannel *channel)
+{
+    AudioChannelsLock lock;
+    auto* ch = lock.GetChannelIfPlaying(channel->id);
+
+    if (ch)
+    {
+        return ch->get_length_ms();
+    }
+    return 0;
+}
+
+int AudioChannel_GetVolume(ScriptAudioChannel *channel)
+{
+    AudioChannelsLock lock;
+    auto* ch = lock.GetChannelIfPlaying(channel->id);
+
+    if (ch)
+    {
+        return ch->get_volume();
+    }
+    return 0;
+}
+
+int AudioChannel_SetVolume(ScriptAudioChannel *channel, int newVolume)
+{
+    if ((newVolume < 0) || (newVolume > 100))
+        quitprintf("!AudioChannel.Volume: new value out of range (supplied: %d, range: 0..100)", newVolume);
+
+    AudioChannelsLock lock;
+    auto* ch = lock.GetChannelIfPlaying(channel->id);
+
+    if (ch)
+    {
+        ch->set_volume_percent(newVolume);
+    }
+    return 0;
+}
+
+int AudioChannel_GetSpeed(ScriptAudioChannel *channel)
+{
+    AudioChannelsLock lock;
+    auto* ch = lock.GetChannelIfPlaying(channel->id);
+
+    if (ch)
+    {
+        return ch->get_speed();
+    }
+    return 0;
+}
+
+void AudioChannel_SetSpeed(ScriptAudioChannel *channel, int new_speed)
+{
+    AudioChannelsLock lock;
+    auto* ch = lock.GetChannelIfPlaying(channel->id);
+
+    if (ch)
+    {
+        ch->set_speed(new_speed);
+    }
+}
+
+void AudioChannel_Stop(ScriptAudioChannel *channel)
+{
+    if (channel->id == SCHAN_SPEECH && play.IsNonBlockingVoiceSpeech())
+        stop_voice_nonblocking();
+    else
+        stop_or_fade_out_channel(channel->id, -1, nullptr);
+}
+
+void AudioChannel_Seek(ScriptAudioChannel *channel, int newPosition)
+{
+    if (newPosition < 0)
+        quitprintf("!AudioChannel.Seek: invalid seek position %d", newPosition);
+
+    AudioChannelsLock lock;
+    auto* ch = lock.GetChannelIfPlaying(channel->id);
+
+    if (ch)
+    {
+        ch->seek(newPosition);
+    }
+}
+
+void AudioChannel_SetRoomLocation(ScriptAudioChannel *channel, int xPos, int yPos)
+{
+    AudioChannelsLock lock;
+    auto* ch = lock.GetChannelIfPlaying(channel->id);
+
+    if (ch)
+    {
+        int maxDist = ((xPos > thisroom.Width / 2) ? xPos : (thisroom.Width - xPos)) - AMBIENCE_FULL_DIST;
+        ch->xSource = (xPos > 0) ? xPos : -1;
+        ch->ySource = yPos;
+        ch->maximumPossibleDistanceAway = maxDist;
+        if (xPos > 0)
+        {
+            update_directional_sound_vol();
+        }
+        else
+        {
+            ch->apply_directional_modifier(0);
+        }
+    }
+}
+
+//=============================================================================
+//
+// Script API Functions
+//
+//=============================================================================
+
+#include "debug/out.h"
+#include "script/script_api.h"
+#include "script/script_runtime.h"
+
+// int | ScriptAudioChannel *channel
+RuntimeScriptValue Sc_AudioChannel_GetID(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptAudioChannel, AudioChannel_GetID);
+}
+
+// int | ScriptAudioChannel *channel
+RuntimeScriptValue Sc_AudioChannel_GetIsPlaying(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptAudioChannel, AudioChannel_GetIsPlaying);
+}
+
+// int | ScriptAudioChannel *channel
+RuntimeScriptValue Sc_AudioChannel_GetPanning(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptAudioChannel, AudioChannel_GetPanning);
+}
+
+// void | ScriptAudioChannel *channel, int newPanning
+RuntimeScriptValue Sc_AudioChannel_SetPanning(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(ScriptAudioChannel, AudioChannel_SetPanning);
+}
+
+// ScriptAudioClip* | ScriptAudioChannel *channel
+RuntimeScriptValue Sc_AudioChannel_GetPlayingClip(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_OBJ(ScriptAudioChannel, ScriptAudioClip, ccDynamicAudioClip, AudioChannel_GetPlayingClip);
+}
+
+// int | ScriptAudioChannel *channel
+RuntimeScriptValue Sc_AudioChannel_GetPosition(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptAudioChannel, AudioChannel_GetPosition);
+}
+
+// int | ScriptAudioChannel *channel
+RuntimeScriptValue Sc_AudioChannel_GetPositionMs(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptAudioChannel, AudioChannel_GetPositionMs);
+}
+
+// int | ScriptAudioChannel *channel
+RuntimeScriptValue Sc_AudioChannel_GetLengthMs(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptAudioChannel, AudioChannel_GetLengthMs);
+}
+
+// int | ScriptAudioChannel *channel
+RuntimeScriptValue Sc_AudioChannel_GetVolume(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptAudioChannel, AudioChannel_GetVolume);
+}
+
+// int | ScriptAudioChannel *channel, int newVolume
+RuntimeScriptValue Sc_AudioChannel_SetVolume(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT_PINT(ScriptAudioChannel, AudioChannel_SetVolume);
+}
+
+// void | ScriptAudioChannel *channel
+RuntimeScriptValue Sc_AudioChannel_Stop(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID(ScriptAudioChannel, AudioChannel_Stop);
+}
+
+// void | ScriptAudioChannel *channel, int newPosition
+RuntimeScriptValue Sc_AudioChannel_Seek(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(ScriptAudioChannel, AudioChannel_Seek);
+}
+
+// void | ScriptAudioChannel *channel, int xPos, int yPos
+RuntimeScriptValue Sc_AudioChannel_SetRoomLocation(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT2(ScriptAudioChannel, AudioChannel_SetRoomLocation);
+}
+
+RuntimeScriptValue Sc_AudioChannel_GetSpeed(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptAudioChannel, AudioChannel_GetSpeed);
+}
+
+RuntimeScriptValue Sc_AudioChannel_SetSpeed(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(ScriptAudioChannel, AudioChannel_SetSpeed);
+}
+
+void RegisterAudioChannelAPI()
+{
+    ccAddExternalObjectFunction("AudioChannel::Seek^1",             Sc_AudioChannel_Seek);
+    ccAddExternalObjectFunction("AudioChannel::SetRoomLocation^2",  Sc_AudioChannel_SetRoomLocation);
+    ccAddExternalObjectFunction("AudioChannel::Stop^0",             Sc_AudioChannel_Stop);
+    ccAddExternalObjectFunction("AudioChannel::get_ID",             Sc_AudioChannel_GetID);
+    ccAddExternalObjectFunction("AudioChannel::get_IsPlaying",      Sc_AudioChannel_GetIsPlaying);
+    ccAddExternalObjectFunction("AudioChannel::get_LengthMs",       Sc_AudioChannel_GetLengthMs);
+    ccAddExternalObjectFunction("AudioChannel::get_Panning",        Sc_AudioChannel_GetPanning);
+    ccAddExternalObjectFunction("AudioChannel::set_Panning",        Sc_AudioChannel_SetPanning);
+    ccAddExternalObjectFunction("AudioChannel::get_PlayingClip",    Sc_AudioChannel_GetPlayingClip);
+    ccAddExternalObjectFunction("AudioChannel::get_Position",       Sc_AudioChannel_GetPosition);
+    ccAddExternalObjectFunction("AudioChannel::get_PositionMs",     Sc_AudioChannel_GetPositionMs);
+    ccAddExternalObjectFunction("AudioChannel::get_Volume",         Sc_AudioChannel_GetVolume);
+    ccAddExternalObjectFunction("AudioChannel::set_Volume",         Sc_AudioChannel_SetVolume);
+    ccAddExternalObjectFunction("AudioChannel::get_Speed",          Sc_AudioChannel_GetSpeed);
+    ccAddExternalObjectFunction("AudioChannel::set_Speed",          Sc_AudioChannel_SetSpeed);
+    // For compatibility with  Ahmet Kamil's (aka Gord10) custom engine
+    ccAddExternalObjectFunction("AudioChannel::SetSpeed^1",         Sc_AudioChannel_SetSpeed);
+
+    /* ----------------------- Registering unsafe exports for plugins -----------------------*/
+
+    ccAddExternalFunctionForPlugin("AudioChannel::Seek^1",             (void*)AudioChannel_Seek);
+    ccAddExternalFunctionForPlugin("AudioChannel::SetRoomLocation^2",  (void*)AudioChannel_SetRoomLocation);
+    ccAddExternalFunctionForPlugin("AudioChannel::Stop^0",             (void*)AudioChannel_Stop);
+    ccAddExternalFunctionForPlugin("AudioChannel::get_ID",             (void*)AudioChannel_GetID);
+    ccAddExternalFunctionForPlugin("AudioChannel::get_IsPlaying",      (void*)AudioChannel_GetIsPlaying);
+    ccAddExternalFunctionForPlugin("AudioChannel::get_LengthMs",       (void*)AudioChannel_GetLengthMs);
+    ccAddExternalFunctionForPlugin("AudioChannel::get_Panning",        (void*)AudioChannel_GetPanning);
+    ccAddExternalFunctionForPlugin("AudioChannel::set_Panning",        (void*)AudioChannel_SetPanning);
+    ccAddExternalFunctionForPlugin("AudioChannel::get_PlayingClip",    (void*)AudioChannel_GetPlayingClip);
+    ccAddExternalFunctionForPlugin("AudioChannel::get_Position",       (void*)AudioChannel_GetPosition);
+    ccAddExternalFunctionForPlugin("AudioChannel::get_PositionMs",     (void*)AudioChannel_GetPositionMs);
+    ccAddExternalFunctionForPlugin("AudioChannel::get_Volume",         (void*)AudioChannel_GetVolume);
+    ccAddExternalFunctionForPlugin("AudioChannel::set_Volume",         (void*)AudioChannel_SetVolume);
+}
diff --git a/engines/ags/engine/ac/audiochannel.h b/engines/ags/engine/ac/audiochannel.h
new file mode 100644
index 0000000000..de655725ad
--- /dev/null
+++ b/engines/ags/engine/ac/audiochannel.h
@@ -0,0 +1,38 @@
+//=============================================================================
+//
+// Adventure Game Studio (AGS)
+//
+// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
+// The full list of copyright holders can be found in the Copyright.txt
+// file, which is part of this source code distribution.
+//
+// The AGS source code is provided under the Artistic License 2.0.
+// A copy of this license can be found in the file License.txt and at
+// http://www.opensource.org/licenses/artistic-license-2.0.php
+//
+//=============================================================================
+//
+//
+//
+//=============================================================================
+#ifndef __AGS_EE_AC__AUDIOCHANNEL_H
+#define __AGS_EE_AC__AUDIOCHANNEL_H
+
+#include "ac/dynobj/scriptaudioclip.h"
+#include "ac/dynobj/scriptaudiochannel.h"
+
+int     AudioChannel_GetID(ScriptAudioChannel *channel);
+int     AudioChannel_GetIsPlaying(ScriptAudioChannel *channel);
+int     AudioChannel_GetPanning(ScriptAudioChannel *channel);
+void    AudioChannel_SetPanning(ScriptAudioChannel *channel, int newPanning);
+ScriptAudioClip* AudioChannel_GetPlayingClip(ScriptAudioChannel *channel);
+int     AudioChannel_GetPosition(ScriptAudioChannel *channel);
+int     AudioChannel_GetPositionMs(ScriptAudioChannel *channel);
+int     AudioChannel_GetLengthMs(ScriptAudioChannel *channel);
+int     AudioChannel_GetVolume(ScriptAudioChannel *channel);
+int     AudioChannel_SetVolume(ScriptAudioChannel *channel, int newVolume);
+void    AudioChannel_Stop(ScriptAudioChannel *channel);
+void    AudioChannel_Seek(ScriptAudioChannel *channel, int newPosition);
+void    AudioChannel_SetRoomLocation(ScriptAudioChannel *channel, int xPos, int yPos);
+
+#endif // __AGS_EE_AC__AUDIOCHANNEL_H
diff --git a/engines/ags/engine/ac/audioclip.cpp b/engines/ags/engine/ac/audioclip.cpp
new file mode 100644
index 0000000000..5489ee5a3b
--- /dev/null
+++ b/engines/ags/engine/ac/audioclip.cpp
@@ -0,0 +1,154 @@
+//=============================================================================
+//
+// Adventure Game Studio (AGS)
+//
+// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
+// The full list of copyright holders can be found in the Copyright.txt
+// file, which is part of this source code distribution.
+//
+// The AGS source code is provided under the Artistic License 2.0.
+// A copy of this license can be found in the file License.txt and at
+// http://www.opensource.org/licenses/artistic-license-2.0.php
+//
+//=============================================================================
+
+#include "ac/asset_helper.h"
+#include "ac/audioclip.h"
+#include "ac/audiochannel.h"
+#include "ac/gamesetupstruct.h"
+#include "script/runtimescriptvalue.h"
+#include "ac/dynobj/cc_audiochannel.h"
+#include "media/audio/audio_system.h"
+
+extern GameSetupStruct game;
+extern ScriptAudioChannel scrAudioChannel[MAX_SOUND_CHANNELS + 1];
+extern CCAudioChannel ccDynamicAudio;
+
+int AudioClip_GetID(ScriptAudioClip *clip)
+{
+    return clip->id;
+}
+
+int AudioClip_GetFileType(ScriptAudioClip *clip)
+{
+    return clip->fileType;
+}
+
+int AudioClip_GetType(ScriptAudioClip *clip)
+{
+    return clip->type;
+}
+int AudioClip_GetIsAvailable(ScriptAudioClip *clip)
+{
+    return DoesAssetExistInLib(get_audio_clip_assetpath(clip->bundlingType, clip->fileName)) ? 1 : 0;
+}
+
+void AudioClip_Stop(ScriptAudioClip *clip)
+{
+    AudioChannelsLock lock;
+    for (int i = 0; i < MAX_SOUND_CHANNELS; i++)
+    {
+        auto* ch = lock.GetChannelIfPlaying(i);
+        if ((ch != nullptr) && (ch->sourceClip == clip))
+        {
+            AudioChannel_Stop(&scrAudioChannel[i]);
+        }
+    }
+}
+
+ScriptAudioChannel* AudioClip_Play(ScriptAudioClip *clip, int priority, int repeat)
+{
+    ScriptAudioChannel *sc_ch = play_audio_clip(clip, priority, repeat, 0, false);
+    return sc_ch;
+}
+
+ScriptAudioChannel* AudioClip_PlayFrom(ScriptAudioClip *clip, int position, int priority, int repeat)
+{
+    ScriptAudioChannel *sc_ch = play_audio_clip(clip, priority, repeat, position, false);
+    return sc_ch;
+}
+
+ScriptAudioChannel* AudioClip_PlayQueued(ScriptAudioClip *clip, int priority, int repeat)
+{
+    ScriptAudioChannel *sc_ch = play_audio_clip(clip, priority, repeat, 0, true);
+    return sc_ch;
+}
+
+//=============================================================================
+//
+// Script API Functions
+//
+//=============================================================================
+
+#include "debug/out.h"
+#include "script/script_api.h"
+#include "script/script_runtime.h"
+
+RuntimeScriptValue Sc_AudioClip_GetID(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptAudioClip, AudioClip_GetID);
+}
+
+// int | ScriptAudioClip *clip
+RuntimeScriptValue Sc_AudioClip_GetFileType(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptAudioClip, AudioClip_GetFileType);
+}
+
+// int | ScriptAudioClip *clip
+RuntimeScriptValue Sc_AudioClip_GetType(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptAudioClip, AudioClip_GetType);
+}
+
+// int | ScriptAudioClip *clip
+RuntimeScriptValue Sc_AudioClip_GetIsAvailable(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptAudioClip, AudioClip_GetIsAvailable);
+}
+
+// void | ScriptAudioClip *clip
+RuntimeScriptValue Sc_AudioClip_Stop(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID(ScriptAudioClip, AudioClip_Stop);
+}
+
+// ScriptAudioChannel* | ScriptAudioClip *clip, int priority, int repeat
+RuntimeScriptValue Sc_AudioClip_Play(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_OBJ_PINT2(ScriptAudioClip, ScriptAudioChannel, ccDynamicAudio, AudioClip_Play);
+}
+
+// ScriptAudioChannel* | ScriptAudioClip *clip, int position, int priority, int repeat
+RuntimeScriptValue Sc_AudioClip_PlayFrom(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_OBJ_PINT3(ScriptAudioClip, ScriptAudioChannel, ccDynamicAudio, AudioClip_PlayFrom);
+}
+
+// ScriptAudioChannel* | ScriptAudioClip *clip, int priority, int repeat
+RuntimeScriptValue Sc_AudioClip_PlayQueued(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_OBJ_PINT2(ScriptAudioClip, ScriptAudioChannel, ccDynamicAudio, AudioClip_PlayQueued);
+}
+
+void RegisterAudioClipAPI()
+{
+    ccAddExternalObjectFunction("AudioClip::Play^2",            Sc_AudioClip_Play);
+    ccAddExternalObjectFunction("AudioClip::PlayFrom^3",        Sc_AudioClip_PlayFrom);
+    ccAddExternalObjectFunction("AudioClip::PlayQueued^2",      Sc_AudioClip_PlayQueued);
+    ccAddExternalObjectFunction("AudioClip::Stop^0",            Sc_AudioClip_Stop);
+    ccAddExternalObjectFunction("AudioClip::get_ID",            Sc_AudioClip_GetID);
+    ccAddExternalObjectFunction("AudioClip::get_FileType",      Sc_AudioClip_GetFileType);
+    ccAddExternalObjectFunction("AudioClip::get_IsAvailable",   Sc_AudioClip_GetIsAvailable);
+    ccAddExternalObjectFunction("AudioClip::get_Type",          Sc_AudioClip_GetType);
+
+    /* ----------------------- Registering unsafe exports for plugins -----------------------*/
+
+    ccAddExternalFunctionForPlugin("AudioClip::Play^2",            (void*)AudioClip_Play);
+    ccAddExternalFunctionForPlugin("AudioClip::PlayFrom^3",        (void*)AudioClip_PlayFrom);
+    ccAddExternalFunctionForPlugin("AudioClip::PlayQueued^2",      (void*)AudioClip_PlayQueued);
+    ccAddExternalFunctionForPlugin("AudioClip::Stop^0",            (void*)AudioClip_Stop);
+    ccAddExternalFunctionForPlugin("AudioClip::get_FileType",      (void*)AudioClip_GetFileType);
+    ccAddExternalFunctionForPlugin("AudioClip::get_IsAvailable",   (void*)AudioClip_GetIsAvailable);
+    ccAddExternalFunctionForPlugin("AudioClip::get_Type",          (void*)AudioClip_GetType);
+}
diff --git a/engines/ags/engine/ac/audioclip.h b/engines/ags/engine/ac/audioclip.h
new file mode 100644
index 0000000000..ffb4a100b5
--- /dev/null
+++ b/engines/ags/engine/ac/audioclip.h
@@ -0,0 +1,32 @@
+//=============================================================================
+//
+// Adventure Game Studio (AGS)
+//
+// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
+// The full list of copyright holders can be found in the Copyright.txt
+// file, which is part of this source code distribution.
+//
+// The AGS source code is provided under the Artistic License 2.0.
+// A copy of this license can be found in the file License.txt and at
+// http://www.opensource.org/licenses/artistic-license-2.0.php
+//
+//=============================================================================
+//
+//
+//
+//=============================================================================
+#ifndef __AGS_EE_AC__AUDIOCLIP_H
+#define __AGS_EE_AC__AUDIOCLIP_H
+
+#include "ac/dynobj/scriptaudioclip.h"
+#include "ac/dynobj/scriptaudiochannel.h"
+
+int     AudioClip_GetFileType(ScriptAudioClip *clip);
+int     AudioClip_GetType(ScriptAudioClip *clip);
+int     AudioClip_GetIsAvailable(ScriptAudioClip *clip);
+void    AudioClip_Stop(ScriptAudioClip *clip);
+ScriptAudioChannel* AudioClip_Play(ScriptAudioClip *clip, int priority, int repeat);
+ScriptAudioChannel* AudioClip_PlayFrom(ScriptAudioClip *clip, int position, int priority, int repeat);
+ScriptAudioChannel* AudioClip_PlayQueued(ScriptAudioClip *clip, int priority, int repeat);
+
+#endif // __AGS_EE_AC__AUDIOCLIP_H
diff --git a/engines/ags/engine/ac/button.cpp b/engines/ags/engine/ac/button.cpp
new file mode 100644
index 0000000000..ecbcb1b1bc
--- /dev/null
+++ b/engines/ags/engine/ac/button.cpp
@@ -0,0 +1,501 @@
+//=============================================================================
+//
+// Adventure Game Studio (AGS)
+//
+// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
+// The full list of copyright holders can be found in the Copyright.txt
+// file, which is part of this source code distribution.
+//
+// The AGS source code is provided under the Artistic License 2.0.
+// A copy of this license can be found in the file License.txt and at
+// http://www.opensource.org/licenses/artistic-license-2.0.php
+//
+//=============================================================================
+
+#include "ac/button.h"
+#include "ac/common.h"
+#include "ac/gui.h"
+#include "ac/view.h"
+#include "ac/gamesetupstruct.h"
+#include "ac/global_translation.h"
+#include "ac/string.h"
+#include "ac/viewframe.h"
+#include "debug/debug_log.h"
+#include "gui/animatingguibutton.h"
+#include "gui/guimain.h"
+
+using namespace AGS::Common;
+
+extern GameSetupStruct game;
+extern ViewStruct*views;
+
+// *** BUTTON FUNCTIONS
+
+AnimatingGUIButton animbuts[MAX_ANIMATING_BUTTONS];
+int numAnimButs;
+
+void Button_Animate(GUIButton *butt, int view, int loop, int speed, int repeat) {
+    int guin = butt->ParentId;
+    int objn = butt->Id;
+
+    if ((view < 1) || (view > game.numviews))
+        quit("!AnimateButton: invalid view specified");
+    view--;
+
+    if ((loop < 0) || (loop >= views[view].numLoops))
+        quit("!AnimateButton: invalid loop specified for view");
+
+    // if it's already animating, stop it
+    FindAndRemoveButtonAnimation(guin, objn);
+
+    if (numAnimButs >= MAX_ANIMATING_BUTTONS)
+        quit("!AnimateButton: too many animating GUI buttons at once");
+
+    int buttonId = guis[guin].GetControlID(objn);
+
+    guibuts[buttonId].PushedImage = 0;
+    guibuts[buttonId].MouseOverImage = 0;
+
+    animbuts[numAnimButs].ongui = guin;
+    animbuts[numAnimButs].onguibut = objn;
+    animbuts[numAnimButs].buttonid = buttonId;
+    animbuts[numAnimButs].view = view;
+    animbuts[numAnimButs].loop = loop;
+    animbuts[numAnimButs].speed = speed;
+    animbuts[numAnimButs].repeat = repeat;
+    animbuts[numAnimButs].frame = -1;
+    animbuts[numAnimButs].wait = 0;
+    numAnimButs++;
+    // launch into the first frame
+    if (UpdateAnimatingButton(numAnimButs - 1))
+    {
+        debug_script_warn("AnimateButton: no frames to animate");
+        StopButtonAnimation(numAnimButs - 1);
+    }
+}
+
+const char* Button_GetText_New(GUIButton *butt) {
+    return CreateNewScriptString(butt->GetText());
+}
+
+void Button_GetText(GUIButton *butt, char *buffer) {
+    strcpy(buffer, butt->GetText());
+}
+
+void Button_SetText(GUIButton *butt, const char *newtx) {
+    newtx = get_translation(newtx);
+
+    if (strcmp(butt->GetText(), newtx)) {
+        guis_need_update = 1;
+        butt->SetText(newtx);
+    }
+}
+
+void Button_SetFont(GUIButton *butt, int newFont) {
+    if ((newFont < 0) || (newFont >= game.numfonts))
+        quit("!Button.Font: invalid font number.");
+
+    if (butt->Font != newFont) {
+        butt->Font = newFont;
+        guis_need_update = 1;
+    }
+}
+
+int Button_GetFont(GUIButton *butt) {
+    return butt->Font;
+}
+
+int Button_GetClipImage(GUIButton *butt) {
+    return butt->IsClippingImage() ? 1 : 0;
+}
+
+void Button_SetClipImage(GUIButton *butt, int newval) {
+    if (butt->IsClippingImage() != (newval != 0))
+    {
+        butt->SetClipImage(newval != 0);
+        guis_need_update = 1;
+    }
+}
+
+int Button_GetGraphic(GUIButton *butt) {
+    // return currently displayed pic
+    if (butt->CurrentImage < 0)
+        return butt->Image;
+    return butt->CurrentImage;
+}
+
+int Button_GetMouseOverGraphic(GUIButton *butt) {
+    return butt->MouseOverImage;
+}
+
+void Button_SetMouseOverGraphic(GUIButton *guil, int slotn) {
+    debug_script_log("GUI %d Button %d mouseover set to slot %d", guil->ParentId, guil->Id, slotn);
+
+    if ((guil->IsMouseOver != 0) && (guil->IsPushed == 0))
+        guil->CurrentImage = slotn;
+    guil->MouseOverImage = slotn;
+
+    guis_need_update = 1;
+    FindAndRemoveButtonAnimation(guil->ParentId, guil->Id);
+}
+
+int Button_GetNormalGraphic(GUIButton *butt) {
+    return butt->Image;
+}
+
+void Button_SetNormalGraphic(GUIButton *guil, int slotn) {
+    debug_script_log("GUI %d Button %d normal set to slot %d", guil->ParentId, guil->Id, slotn);
+    // normal pic - update if mouse is not over, or if there's no MouseOverImage
+    if (((guil->IsMouseOver == 0) || (guil->MouseOverImage < 1)) && (guil->IsPushed == 0))
+        guil->CurrentImage = slotn;
+    guil->Image = slotn;
+    // update the clickable area to the same size as the graphic
+    guil->Width = game.SpriteInfos[slotn].Width;
+    guil->Height = game.SpriteInfos[slotn].Height;
+
+    guis_need_update = 1;
+    FindAndRemoveButtonAnimation(guil->ParentId, guil->Id);
+}
+
+int Button_GetPushedGraphic(GUIButton *butt) {
+    return butt->PushedImage;
+}
+
+void Button_SetPushedGraphic(GUIButton *guil, int slotn) {
+    debug_script_log("GUI %d Button %d pushed set to slot %d", guil->ParentId, guil->Id, slotn);
+
+    if (guil->IsPushed)
+        guil->CurrentImage = slotn;
+    guil->PushedImage = slotn;
+
+    guis_need_update = 1;
+    FindAndRemoveButtonAnimation(guil->ParentId, guil->Id);
+}
+
+int Button_GetTextColor(GUIButton *butt) {
+    return butt->TextColor;
+}
+
+void Button_SetTextColor(GUIButton *butt, int newcol) {
+    if (butt->TextColor != newcol) {
+        butt->TextColor = newcol;
+        guis_need_update = 1;
+    }
+}
+
+extern AnimatingGUIButton animbuts[MAX_ANIMATING_BUTTONS];
+extern int numAnimButs;
+
+// ** start animating buttons code
+
+// returns 1 if animation finished
+int UpdateAnimatingButton(int bu) {
+    if (animbuts[bu].wait > 0) {
+        animbuts[bu].wait--;
+        return 0;
+    }
+    ViewStruct *tview = &views[animbuts[bu].view];
+
+    animbuts[bu].frame++;
+
+    if (animbuts[bu].frame >= tview->loops[animbuts[bu].loop].numFrames) 
+    {
+        if (tview->loops[animbuts[bu].loop].RunNextLoop()) {
+            // go to next loop
+            animbuts[bu].loop++;
+            animbuts[bu].frame = 0;
+        }
+        else if (animbuts[bu].repeat) {
+            animbuts[bu].frame = 0;
+            // multi-loop anim, go back
+            while ((animbuts[bu].loop > 0) && 
+                (tview->loops[animbuts[bu].loop - 1].RunNextLoop()))
+                animbuts[bu].loop--;
+        }
+        else
+            return 1;
+    }
+
+    CheckViewFrame(animbuts[bu].view, animbuts[bu].loop, animbuts[bu].frame);
+
+    // update the button's image
+    guibuts[animbuts[bu].buttonid].Image = tview->loops[animbuts[bu].loop].frames[animbuts[bu].frame].pic;
+    guibuts[animbuts[bu].buttonid].CurrentImage = guibuts[animbuts[bu].buttonid].Image;
+    guibuts[animbuts[bu].buttonid].PushedImage = 0;
+    guibuts[animbuts[bu].buttonid].MouseOverImage = 0;
+    guis_need_update = 1;
+
+    animbuts[bu].wait = animbuts[bu].speed + tview->loops[animbuts[bu].loop].frames[animbuts[bu].frame].speed;
+    return 0;
+}
+
+void StopButtonAnimation(int idxn) {
+    numAnimButs--;
+    for (int aa = idxn; aa < numAnimButs; aa++) {
+        animbuts[aa] = animbuts[aa + 1];
+    }
+}
+
+// Returns the index of the AnimatingGUIButton object corresponding to the
+// given button ID; returns -1 if no such animation exists
+int FindAnimatedButton(int guin, int objn)
+{
+    for (int i = 0; i < numAnimButs; ++i)
+    {
+        if (animbuts[i].ongui == guin && animbuts[i].onguibut == objn)
+            return i;
+    }
+    return -1;
+}
+
+void FindAndRemoveButtonAnimation(int guin, int objn)
+{
+    int idx = FindAnimatedButton(guin, objn);
+    if (idx >= 0)
+        StopButtonAnimation(idx);
+}
+// ** end animating buttons code
+
+void Button_Click(GUIButton *butt, int mbut)
+{
+    process_interface_click(butt->ParentId, butt->Id, mbut);
+}
+
+bool Button_IsAnimating(GUIButton *butt)
+{
+    return FindAnimatedButton(butt->ParentId, butt->Id) >= 0;
+}
+
+// NOTE: in correspondance to similar functions for Character & Object,
+// GetView returns (view index + 1), while GetLoop and GetFrame return
+// zero-based index and 0 in case of no animation.
+int Button_GetAnimView(GUIButton *butt)
+{
+    int idx = FindAnimatedButton(butt->ParentId, butt->Id);
+    return idx >= 0 ? animbuts[idx].view + 1 : 0;
+}
+
+int Button_GetAnimLoop(GUIButton *butt)
+{
+    int idx = FindAnimatedButton(butt->ParentId, butt->Id);
+    return idx >= 0 ? animbuts[idx].loop : 0;
+}
+
+int Button_GetAnimFrame(GUIButton *butt)
+{
+    int idx = FindAnimatedButton(butt->ParentId, butt->Id);
+    return idx >= 0 ? animbuts[idx].frame : 0;
+}
+
+int Button_GetTextAlignment(GUIButton *butt)
+{
+    return butt->TextAlignment;
+}
+
+void Button_SetTextAlignment(GUIButton *butt, int align)
+{
+    if (butt->TextAlignment != align) {
+        butt->TextAlignment = (FrameAlignment)align;
+        guis_need_update = 1;
+    }
+}
+
+//=============================================================================
+//
+// Script API Functions
+//
+//=============================================================================
+
+#include "debug/out.h"
+#include "script/script_api.h"
+#include "script/script_runtime.h"
+#include "ac/dynobj/scriptstring.h"
+
+extern ScriptString myScriptStringImpl;
+
+// void | GUIButton *butt, int view, int loop, int speed, int repeat
+RuntimeScriptValue Sc_Button_Animate(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT4(GUIButton, Button_Animate);
+}
+
+// const char* | GUIButton *butt
+RuntimeScriptValue Sc_Button_GetText_New(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_OBJ(GUIButton, const char, myScriptStringImpl, Button_GetText_New);
+}
+
+// void | GUIButton *butt, char *buffer
+RuntimeScriptValue Sc_Button_GetText(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_POBJ(GUIButton, Button_GetText, char);
+}
+
+// void | GUIButton *butt, const char *newtx
+RuntimeScriptValue Sc_Button_SetText(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_POBJ(GUIButton, Button_SetText, const char);
+}
+
+// void | GUIButton *butt, int newFont
+RuntimeScriptValue Sc_Button_SetFont(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(GUIButton, Button_SetFont);
+}
+
+// int | GUIButton *butt
+RuntimeScriptValue Sc_Button_GetFont(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(GUIButton, Button_GetFont);
+}
+
+// int | GUIButton *butt
+RuntimeScriptValue Sc_Button_GetClipImage(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(GUIButton, Button_GetClipImage);
+}
+
+// void | GUIButton *butt, int newval
+RuntimeScriptValue Sc_Button_SetClipImage(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(GUIButton, Button_SetClipImage);
+}
+
+// int | GUIButton *butt
+RuntimeScriptValue Sc_Button_GetGraphic(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(GUIButton, Button_GetGraphic);
+}
+
+// int | GUIButton *butt
+RuntimeScriptValue Sc_Button_GetMouseOverGraphic(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(GUIButton, Button_GetMouseOverGraphic);
+}
+
+// void | GUIButton *guil, int slotn
+RuntimeScriptValue Sc_Button_SetMouseOverGraphic(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(GUIButton, Button_SetMouseOverGraphic);
+}
+
+// int | GUIButton *butt
+RuntimeScriptValue Sc_Button_GetNormalGraphic(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(GUIButton, Button_GetNormalGraphic);
+}
+
+// void | GUIButton *guil, int slotn
+RuntimeScriptValue Sc_Button_SetNormalGraphic(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(GUIButton, Button_SetNormalGraphic);
+}
+
+// int | GUIButton *butt
+RuntimeScriptValue Sc_Button_GetPushedGraphic(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(GUIButton, Button_GetPushedGraphic);
+}
+
+// void | GUIButton *guil, int slotn
+RuntimeScriptValue Sc_Button_SetPushedGraphic(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(GUIButton, Button_SetPushedGraphic);
+}
+
+// int | GUIButton *butt
+RuntimeScriptValue Sc_Button_GetTextColor(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(GUIButton, Button_GetTextColor);
+}
+
+// void | GUIButton *butt, int newcol
+RuntimeScriptValue Sc_Button_SetTextColor(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(GUIButton, Button_SetTextColor);
+}
+
+RuntimeScriptValue Sc_Button_Click(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(GUIButton, Button_Click);
+}
+
+RuntimeScriptValue Sc_Button_GetAnimating(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_BOOL(GUIButton, Button_IsAnimating);
+}
+
+RuntimeScriptValue Sc_Button_GetTextAlignment(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(GUIButton, Button_GetTextAlignment);
+}
+
+RuntimeScriptValue Sc_Button_SetTextAlignment(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(GUIButton, Button_SetTextAlignment);
+}
+
+RuntimeScriptValue Sc_Button_GetFrame(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(GUIButton, Button_GetAnimFrame);
+}
+
+RuntimeScriptValue Sc_Button_GetLoop(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(GUIButton, Button_GetAnimLoop);
+}
+
+RuntimeScriptValue Sc_Button_GetView(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(GUIButton, Button_GetAnimView);
+}
+
+void RegisterButtonAPI()
+{
+    ccAddExternalObjectFunction("Button::Animate^4",            Sc_Button_Animate);
+    ccAddExternalObjectFunction("Button::Click^1",              Sc_Button_Click);
+    ccAddExternalObjectFunction("Button::GetText^1",            Sc_Button_GetText);
+    ccAddExternalObjectFunction("Button::SetText^1",            Sc_Button_SetText);
+    ccAddExternalObjectFunction("Button::get_TextAlignment",    Sc_Button_GetTextAlignment);
+    ccAddExternalObjectFunction("Button::set_TextAlignment",    Sc_Button_SetTextAlignment);
+    ccAddExternalObjectFunction("Button::get_Animating",        Sc_Button_GetAnimating);
+    ccAddExternalObjectFunction("Button::get_ClipImage",        Sc_Button_GetClipImage);
+    ccAddExternalObjectFunction("Button::set_ClipImage",        Sc_Button_SetClipImage);
+    ccAddExternalObjectFunction("Button::get_Font",             Sc_Button_GetFont);
+    ccAddExternalObjectFunction("Button::set_Font",             Sc_Button_SetFont);
+    ccAddExternalObjectFunction("Button::get_Frame",            Sc_Button_GetFrame);
+    ccAddExternalObjectFunction("Button::get_Graphic",          Sc_Button_GetGraphic);
+    ccAddExternalObjectFunction("Button::get_Loop",             Sc_Button_GetLoop);
+    ccAddExternalObjectFunction("Button::get_MouseOverGraphic", Sc_Button_GetMouseOverGraphic);
+    ccAddExternalObjectFunction("Button::set_MouseOverGraphic", Sc_Button_SetMouseOverGraphic);
+    ccAddExternalObjectFunction("Button::get_NormalGraphic",    Sc_Button_GetNormalGraphic);
+    ccAddExternalObjectFunction("Button::set_NormalGraphic",    Sc_Button_SetNormalGraphic);
+    ccAddExternalObjectFunction("Button::get_PushedGraphic",    Sc_Button_GetPushedGraphic);
+    ccAddExternalObjectFunction("Button::set_PushedGraphic",    Sc_Button_SetPushedGraphic);
+    ccAddExternalObjectFunction("Button::get_Text",             Sc_Button_GetText_New);
+    ccAddExternalObjectFunction("Button::set_Text",             Sc_Button_SetText);
+    ccAddExternalObjectFunction("Button::get_TextColor",        Sc_Button_GetTextColor);
+    ccAddExternalObjectFunction("Button::set_TextColor",        Sc_Button_SetTextColor);
+    ccAddExternalObjectFunction("Button::get_View",             Sc_Button_GetView);
+
+    /* ----------------------- Registering unsafe exports for plugins -----------------------*/
+
+    ccAddExternalFunctionForPlugin("Button::Animate^4",            (void*)Button_Animate);
+    ccAddExternalFunctionForPlugin("Button::GetText^1",            (void*)Button_GetText);
+    ccAddExternalFunctionForPlugin("Button::SetText^1",            (void*)Button_SetText);
+    ccAddExternalFunctionForPlugin("Button::get_ClipImage",        (void*)Button_GetClipImage);
+    ccAddExternalFunctionForPlugin("Button::set_ClipImage",        (void*)Button_SetClipImage);
+    ccAddExternalFunctionForPlugin("Button::get_Font",             (void*)Button_GetFont);
+    ccAddExternalFunctionForPlugin("Button::set_Font",             (void*)Button_SetFont);
+    ccAddExternalFunctionForPlugin("Button::get_Graphic",          (void*)Button_GetGraphic);
+    ccAddExternalFunctionForPlugin("Button::get_MouseOverGraphic", (void*)Button_GetMouseOverGraphic);
+    ccAddExternalFunctionForPlugin("Button::set_MouseOverGraphic", (void*)Button_SetMouseOverGraphic);
+    ccAddExternalFunctionForPlugin("Button::get_NormalGraphic",    (void*)Button_GetNormalGraphic);
+    ccAddExternalFunctionForPlugin("Button::set_NormalGraphic",    (void*)Button_SetNormalGraphic);
+    ccAddExternalFunctionForPlugin("Button::get_PushedGraphic",    (void*)Button_GetPushedGraphic);
+    ccAddExternalFunctionForPlugin("Button::set_PushedGraphic",    (void*)Button_SetPushedGraphic);
+    ccAddExternalFunctionForPlugin("Button::get_Text",             (void*)Button_GetText_New);
+    ccAddExternalFunctionForPlugin("Button::set_Text",             (void*)Button_SetText);
+    ccAddExternalFunctionForPlugin("Button::get_TextColor",        (void*)Button_GetTextColor);
+    ccAddExternalFunctionForPlugin("Button::set_TextColor",        (void*)Button_SetTextColor);
+}
diff --git a/engines/ags/engine/ac/button.h b/engines/ags/engine/ac/button.h
new file mode 100644
index 0000000000..5f94aaea18
--- /dev/null
+++ b/engines/ags/engine/ac/button.h
@@ -0,0 +1,47 @@
+//=============================================================================
+//
+// Adventure Game Studio (AGS)
+//
+// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
+// The full list of copyright holders can be found in the Copyright.txt
+// file, which is part of this source code distribution.
+//
+// The AGS source code is provided under the Artistic License 2.0.
+// A copy of this license can be found in the file License.txt and at
+// http://www.opensource.org/licenses/artistic-license-2.0.php
+//
+//=============================================================================
+//
+//
+//
+//=============================================================================
+#ifndef __AGS_EE_AC__BUTTON_H
+#define __AGS_EE_AC__BUTTON_H
+
+#include "gui/guibutton.h"
+
+using AGS::Common::GUIButton;
+
+void		Button_Animate(GUIButton *butt, int view, int loop, int speed, int repeat);
+const char* Button_GetText_New(GUIButton *butt);
+void		Button_GetText(GUIButton *butt, char *buffer);
+void		Button_SetText(GUIButton *butt, const char *newtx);
+void		Button_SetFont(GUIButton *butt, int newFont);
+int			Button_GetFont(GUIButton *butt);
+int			Button_GetClipImage(GUIButton *butt);
+void		Button_SetClipImage(GUIButton *butt, int newval);
+int			Button_GetGraphic(GUIButton *butt);
+int			Button_GetMouseOverGraphic(GUIButton *butt);
+void		Button_SetMouseOverGraphic(GUIButton *guil, int slotn);
+int			Button_GetNormalGraphic(GUIButton *butt);
+void		Button_SetNormalGraphic(GUIButton *guil, int slotn);
+int			Button_GetPushedGraphic(GUIButton *butt);
+void		Button_SetPushedGraphic(GUIButton *guil, int slotn);
+int			Button_GetTextColor(GUIButton *butt);
+void		Button_SetTextColor(GUIButton *butt, int newcol);
+
+int			UpdateAnimatingButton(int bu);
+void		StopButtonAnimation(int idxn);
+void		FindAndRemoveButtonAnimation(int guin, int objn);
+
+#endif // __AGS_EE_AC__BUTTON_H
diff --git a/engines/ags/engine/ac/cdaudio.cpp b/engines/ags/engine/ac/cdaudio.cpp
new file mode 100644
index 0000000000..866d797f50
--- /dev/null
+++ b/engines/ags/engine/ac/cdaudio.cpp
@@ -0,0 +1,39 @@
+//=============================================================================
+//
+// Adventure Game Studio (AGS)
+//
+// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
+// The full list of copyright holders can be found in the Copyright.txt
+// file, which is part of this source code distribution.
+//
+// The AGS source code is provided under the Artistic License 2.0.
+// A copy of this license can be found in the file License.txt and at
+// http://www.opensource.org/licenses/artistic-license-2.0.php
+//
+//=============================================================================
+
+#include "ac/cdaudio.h"
+#include "platform/base/agsplatformdriver.h"
+
+int use_cdplayer=0;
+bool triedToUseCdAudioCommand = false;
+int need_to_stop_cd=0;
+
+int init_cd_player() 
+{
+    use_cdplayer=0;
+    return platform->InitializeCDPlayer();
+}
+
+int cd_manager(int cmdd,int datt) 
+{
+    if (!triedToUseCdAudioCommand)
+    {
+        triedToUseCdAudioCommand = true;
+        init_cd_player();
+    }
+    if (cmdd==0) return use_cdplayer;
+    if (use_cdplayer==0) return 0;  // ignore other commands
+
+    return platform->CDPlayerCommand(cmdd, datt);
+}
diff --git a/engines/ags/engine/ac/cdaudio.h b/engines/ags/engine/ac/cdaudio.h
new file mode 100644
index 0000000000..4009b520fb
--- /dev/null
+++ b/engines/ags/engine/ac/cdaudio.h
@@ -0,0 +1,31 @@
+//=============================================================================
+//
+// Adventure Game Studio (AGS)
+//
+// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
+// The full list of copyright holders can be found in the Copyright.txt
+// file, which is part of this source code distribution.
+//
+// The AGS source code is provided under the Artistic License 2.0.
+// A copy of this license can be found in the file License.txt and at
+// http://www.opensource.org/licenses/artistic-license-2.0.php
+//
+//=============================================================================
+//
+//
+//
+//=============================================================================
+#ifndef __AGS_EE_AC__CDAUDIO_H
+#define __AGS_EE_AC__CDAUDIO_H
+
+// CD Player functions
+// flags returned with cd_getstatus
+#define CDS_DRIVEOPEN    0x0001  // tray is open
+#define CDS_DRIVELOCKED  0x0002  // tray locked shut by software
+#define CDS_AUDIOSUPPORT 0x0010  // supports audio CDs
+#define CDS_DRIVEEMPTY   0x0800  // no CD in drive
+
+int     init_cd_player() ;
+int     cd_manager(int cmdd,int datt) ;
+
+#endif // __AGS_EE_AC__CDAUDIO_H
diff --git a/engines/ags/engine/ac/character.cpp b/engines/ags/engine/ac/character.cpp
new file mode 100644
index 0000000000..526c9705ac
--- /dev/null
+++ b/engines/ags/engine/ac/character.cpp
@@ -0,0 +1,4122 @@
+//=============================================================================
+//
+// Adventure Game Studio (AGS)
+//
+// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
+// The full list of copyright holders can be found in the Copyright.txt
+// file, which is part of this source code distribution.
+//
+// The AGS source code is provided under the Artistic License 2.0.
+// A copy of this license can be found in the file License.txt and at
+// http://www.opensource.org/licenses/artistic-license-2.0.php
+//
+//=============================================================================
+//
+// AGS Character functions
+//
+//=============================================================================
+
+#include "ac/character.h"
+#include "ac/common.h"
+#include "ac/gamesetupstruct.h"
+#include "ac/view.h"
+#include "ac/display.h"
+#include "ac/draw.h"
+#include "ac/event.h"
+#include "ac/game.h"
+#include "ac/global_audio.h"
+#include "ac/global_character.h"
+#include "ac/global_game.h"
+#include "ac/global_object.h"
+#include "ac/global_region.h"
+#include "ac/global_room.h"
+#include "ac/global_translation.h"
+#include "ac/gui.h"
+#include "ac/lipsync.h"
+#include "ac/mouse.h"
+#include "ac/object.h"
+#include "ac/overlay.h"
+#include "ac/properties.h"
+#include "ac/room.h"
+#include "ac/screenoverlay.h"
+#include "ac/string.h"
+#include "ac/system.h"
+#include "ac/viewframe.h"
+#include "ac/walkablearea.h"
+#include "gui/guimain.h"
+#include "ac/route_finder.h"
+#include "ac/gamestate.h"
+#include "debug/debug_log.h"
+#include "main/game_run.h"
+#include "main/update.h"
+#include "ac/spritecache.h"
+#include "util/string_compat.h"
+#include <math.h>
+#include "gfx/graphicsdriver.h"
+#include "script/runtimescriptvalue.h"
+#include "ac/dynobj/cc_character.h"
+#include "ac/dynobj/cc_inventory.h"
+#include "script/script_runtime.h"
+#include "gfx/gfx_def.h"
+#include "media/audio/audio_system.h"
+#include "ac/movelist.h"
+
+using namespace AGS::Common;
+
+extern GameSetupStruct game;
+extern int displayed_room,starting_room;
+extern RoomStruct thisroom;
+extern MoveList *mls;
+extern ViewStruct*views;
+extern RoomObject*objs;
+extern ScriptInvItem scrInv[MAX_INV];
+extern SpriteCache spriteset;
+extern Bitmap *walkable_areas_temp;
+extern IGraphicsDriver *gfxDriver;
+extern Bitmap **actsps;
+extern int is_text_overlay;
+extern int said_speech_line;
+extern int said_text;
+extern int our_eip;
+extern CCCharacter ccDynamicCharacter;
+extern CCInventory ccDynamicInv;
+
+//--------------------------------
+
+
+CharacterExtras *charextra;
+CharacterInfo*playerchar;
+int32_t _sc_PlayerCharPtr = 0;
+int char_lowest_yp;
+
+// Sierra-style speech settings
+int face_talking=-1,facetalkview=0,facetalkwait=0,facetalkframe=0;
+int facetalkloop=0, facetalkrepeat = 0, facetalkAllowBlink = 1;
+int facetalkBlinkLoop = 0;
+CharacterInfo *facetalkchar = nullptr;
+// Do override default portrait position during QFG4-style speech overlay update
+bool facetalk_qfg4_override_placement_x = false;
+bool facetalk_qfg4_override_placement_y = false;
+
+// lip-sync speech settings
+int loops_per_character, text_lips_offset, char_speaking = -1;
+int char_thinking = -1;
+const char *text_lips_text = nullptr;
+SpeechLipSyncLine *splipsync = nullptr;
+int numLipLines = 0, curLipLine = -1, curLipLinePhoneme = 0;
+
+// **** CHARACTER: FUNCTIONS ****
+
+void Character_AddInventory(CharacterInfo *chaa, ScriptInvItem *invi, int addIndex) {
+    int ee;
+
+    if (invi == nullptr)
+        quit("!AddInventoryToCharacter: invalid invnetory number");
+
+    int inum = invi->id;
+
+    if (chaa->inv[inum] >= 32000)
+        quit("!AddInventory: cannot carry more than 32000 of one inventory item");
+
+    chaa->inv[inum]++;
+
+    int charid = chaa->index_id;
+
+    if (game.options[OPT_DUPLICATEINV] == 0) {
+        // Ensure it is only in the list once
+        for (ee = 0; ee < charextra[charid].invorder_count; ee++) {
+            if (charextra[charid].invorder[ee] == inum) {
+                // They already have the item, so don't add it to the list
+                if (chaa == playerchar)
+                    run_on_event (GE_ADD_INV, RuntimeScriptValue().SetInt32(inum));
+                return;
+            }
+        }
+    }
+    if (charextra[charid].invorder_count >= MAX_INVORDER)
+        quit("!Too many inventory items added, max 500 display at one time");
+
+    if ((addIndex == SCR_NO_VALUE) ||
+        (addIndex >= charextra[charid].invorder_count) ||
+        (addIndex < 0)) {
+            // add new item at end of list
+            charextra[charid].invorder[charextra[charid].invorder_count] = inum;
+    }
+    else {
+        // insert new item at index
+        for (ee = charextra[charid].invorder_count - 1; ee >= addIndex; ee--)
+            charextra[charid].invorder[ee + 1] = charextra[charid].invorder[ee];
+
+        charextra[charid].invorder[addIndex] = inum;
+    }
+    charextra[charid].invorder_count++;
+    guis_need_update = 1;
+    if (chaa == playerchar)
+        run_on_event (GE_ADD_INV, RuntimeScriptValue().SetInt32(inum));
+
+}
+
+void Character_AddWaypoint(CharacterInfo *chaa, int x, int y) {
+
+    if (chaa->room != displayed_room)
+        quit("!MoveCharacterPath: specified character not in current room");
+
+    // not already walking, so just do a normal move
+    if (chaa->walking <= 0) {
+        Character_Walk(chaa, x, y, IN_BACKGROUND, ANYWHERE);
+        return;
+    }
+
+    MoveList *cmls = &mls[chaa->walking % TURNING_AROUND];
+    if (cmls->numstage >= MAXNEEDSTAGES)
+    {
+        debug_script_warn("Character_AddWaypoint: move is too complex, cannot add any further paths");
+        return;
+    }
+
+    cmls->pos[cmls->numstage] = (x << 16) + y;
+    // They're already walking there anyway
+    if (cmls->pos[cmls->numstage] == cmls->pos[cmls->numstage - 1])
+        return;
+
+    calculate_move_stage (cmls, cmls->numstage-1);
+    cmls->numstage ++;
+
+}
+
+void Character_AnimateFrom(CharacterInfo *chaa, int loop, int delay, int repeat, int blocking, int direction, int sframe) {
+
+    if (direction == FORWARDS)
+        direction = 0;
+    else if (direction == BACKWARDS)
+        direction = 1;
+    else
+        quit("!Character.Animate: Invalid DIRECTION parameter");
+
+    animate_character(chaa, loop, delay, repeat, 0, direction, sframe);
+
+    if ((blocking == BLOCKING) || (blocking == 1))
+        GameLoopUntilValueIsZero(&chaa->animating);
+    else if ((blocking != IN_BACKGROUND) && (blocking != 0))
+        quit("!Character.Animate: Invalid BLOCKING parameter");
+}
+
+void Character_Animate(CharacterInfo *chaa, int loop, int delay, int repeat, int blocking, int direction) {
+    Character_AnimateFrom(chaa, loop, delay, repeat, blocking, direction, 0);
+}
+
+void Character_ChangeRoomAutoPosition(CharacterInfo *chaa, int room, int newPos) 
+{
+    if (chaa->index_id != game.playercharacter) 
+    {
+        quit("!Character.ChangeRoomAutoPosition can only be used with the player character.");
+    }
+
+    new_room_pos = newPos;
+
+    if (new_room_pos == 0) {
+        // auto place on other side of screen
+        if (chaa->x <= thisroom.Edges.Left + 10)
+            new_room_pos = 2000;
+        else if (chaa->x >= thisroom.Edges.Right - 10)
+            new_room_pos = 1000;
+        else if (chaa->y <= thisroom.Edges.Top + 10)
+            new_room_pos = 3000;
+        else if (chaa->y >= thisroom.Edges.Bottom - 10)
+            new_room_pos = 4000;
+
+        if (new_room_pos < 3000)
+            new_room_pos += chaa->y;
+        else
+            new_room_pos += chaa->x;
+    }
+    NewRoom(room);
+}
+
+void Character_ChangeRoom(CharacterInfo *chaa, int room, int x, int y) {
+    Character_ChangeRoomSetLoop(chaa, room, x, y, SCR_NO_VALUE);
+}
+
+void Character_ChangeRoomSetLoop(CharacterInfo *chaa, int room, int x, int y, int direction) {
+
+    if (chaa->index_id != game.playercharacter) {
+        // NewRoomNPC
+        if ((x != SCR_NO_VALUE) && (y != SCR_NO_VALUE)) {
+            chaa->x = x;
+            chaa->y = y;
+			if (direction != SCR_NO_VALUE && direction>=0) chaa->loop = direction;
+        }
+        chaa->prevroom = chaa->room;
+        chaa->room = room;
+
+		debug_script_log("%s moved to room %d, location %d,%d, loop %d",
+			chaa->scrname, room, chaa->x, chaa->y, chaa->loop);
+
+        return;
+    }
+
+    if ((x != SCR_NO_VALUE) && (y != SCR_NO_VALUE)) {
+        new_room_pos = 0;
+
+        if (loaded_game_file_version <= kGameVersion_272)
+        {
+            // Set position immediately on 2.x.
+            chaa->x = x;
+            chaa->y = y;
+        }
+        else
+        {
+            // don't check X or Y bounds, so that they can do a
+            // walk-in animation if they want
+            new_room_x = x;
+            new_room_y = y;
+			if (direction != SCR_NO_VALUE) new_room_loop = direction;
+        }
+    }
+
+    NewRoom(room);
+}
+
+
+void Character_ChangeView(CharacterInfo *chap, int vii) {
+    vii--;
+
+    if ((vii < 0) || (vii >= game.numviews))
+        quit("!ChangeCharacterView: invalid view number specified");
+
+    // if animating, but not idle view, give warning message
+    if ((chap->flags & CHF_FIXVIEW) && (chap->idleleft >= 0))
+        debug_script_warn("Warning: ChangeCharacterView was used while the view was fixed - call ReleaseCharView first");
+
+    // if the idle animation is playing we should release the view
+    if ( chap->idleleft < 0) {
+      Character_UnlockView(chap);
+      chap->idleleft = chap->idletime;
+    }
+
+    debug_script_log("%s: Change view to %d", chap->scrname, vii+1);
+    chap->defview = vii;
+    chap->view = vii;
+    chap->animating = 0;
+    chap->frame = 0;
+    chap->wait = 0;
+    chap->walkwait = 0;
+    charextra[chap->index_id].animwait = 0;
+    FindReasonableLoopForCharacter(chap);
+}
+
+enum DirectionalLoop
+{
+    kDirLoop_Down      = 0,
+    kDirLoop_Left      = 1,
+    kDirLoop_Right     = 2,
+    kDirLoop_Up        = 3,
+    kDirLoop_DownRight = 4,
+    kDirLoop_UpRight   = 5,
+    kDirLoop_DownLeft  = 6,
+    kDirLoop_UpLeft    = 7,
+
+    kDirLoop_Default        = kDirLoop_Down,
+    kDirLoop_LastOrthogonal = kDirLoop_Up,
+    kDirLoop_Last           = kDirLoop_UpLeft,
+};
+
+// Internal direction-facing functions
+
+DirectionalLoop GetDirectionalLoop(CharacterInfo *chinfo, int x_diff, int y_diff)
+{
+    DirectionalLoop next_loop = kDirLoop_Left; // NOTE: default loop was Left for some reason
+
+    const ViewStruct &chview  = views[chinfo->view];
+    const bool new_version    = loaded_game_file_version > kGameVersion_272;
+    const bool has_down_loop  = ((chview.numLoops > kDirLoop_Down)  && (chview.loops[kDirLoop_Down].numFrames > 0));
+    const bool has_up_loop    = ((chview.numLoops > kDirLoop_Up)    && (chview.loops[kDirLoop_Up].numFrames > 0));
+    // NOTE: 3.+ games required left & right loops to be present at all times
+    const bool has_left_loop  = new_version ||
+                                ((chview.numLoops > kDirLoop_Left)  && (chview.loops[kDirLoop_Left].numFrames > 0));
+    const bool has_right_loop = new_version ||
+                                ((chview.numLoops > kDirLoop_Right) && (chview.loops[kDirLoop_Right].numFrames > 0));
+    const bool has_diagonal_loops = useDiagonal(chinfo) == 0; // NOTE: useDiagonal returns 0 for "true"
+
+    const bool want_horizontal = (abs(y_diff) < abs(x_diff)) ||
+        (new_version && (!has_down_loop || !has_up_loop) )||
+        // NOTE: <= 2.72 games switch to horizontal loops only if both vertical ones are missing
+        (!new_version && (!has_down_loop && !has_up_loop));
+    if (want_horizontal)
+    {
+        const bool want_diagonal = has_diagonal_loops && (abs(y_diff) > abs(x_diff) / 2);
+        if (!has_left_loop && !has_right_loop)
+        {
+            next_loop = kDirLoop_Down;
+        }
+        else if (has_right_loop && (x_diff > 0))
+        {
+            next_loop = want_diagonal ? (y_diff < 0 ? kDirLoop_UpRight : kDirLoop_DownRight) :
+                kDirLoop_Right;
+        }
+        else if (has_left_loop && (x_diff <= 0))
+        {
+            next_loop = want_diagonal ? (y_diff < 0 ? kDirLoop_UpLeft : kDirLoop_DownLeft) :
+                kDirLoop_Left;
+        }
+    }
+    else
+    {
+        const bool want_diagonal = has_diagonal_loops && (abs(x_diff) > abs(y_diff) / 2);
+        if (y_diff > 0 || !has_up_loop)
+        {
+            next_loop = want_diagonal ? (x_diff < 0 ? kDirLoop_DownLeft : kDirLoop_DownRight) :
+                kDirLoop_Down;
+        }
+        else
+        {
+            next_loop = want_diagonal ? (x_diff < 0 ? kDirLoop_UpLeft : kDirLoop_UpRight) :
+                kDirLoop_Up;
+        }
+    }
+    return next_loop;
+}
+
+void FaceDirectionalLoop(CharacterInfo *char1, int direction, int blockingStyle)
+{
+    // Change facing only if the desired direction is different
+    if (direction != char1->loop)
+    {
+        if ((game.options[OPT_TURNTOFACELOC] != 0) &&
+            (in_enters_screen == 0))
+        {
+            const int no_diagonal = useDiagonal (char1);
+            const int highestLoopForTurning = no_diagonal != 1 ? kDirLoop_Last : kDirLoop_LastOrthogonal;
+            if ((char1->loop <= highestLoopForTurning))
+            {
+                // Turn to face new direction
+                Character_StopMoving(char1);
+                if (char1->on == 1)
+                {
+                    // only do the turning if the character is not hidden
+                    // (otherwise GameLoopUntilNotMoving will never return)
+                    start_character_turning (char1, direction, no_diagonal);
+
+                    if ((blockingStyle == BLOCKING) || (blockingStyle == 1))
+                        GameLoopUntilNotMoving(&char1->walking);
+                }
+                else
+                    char1->loop = direction;
+            }
+            else
+                char1->loop = direction;
+        }
+        else
+            char1->loop = direction;
+    }
+
+    char1->frame = 0;
+}
+
+void FaceLocationXY(CharacterInfo *char1, int xx, int yy, int blockingStyle)
+{
+    debug_script_log("%s: Face location %d,%d", char1->scrname, xx, yy);
+
+    const int diffrx = xx - char1->x;
+    const int diffry = yy - char1->y;
+
+    if ((diffrx == 0) && (diffry == 0)) {
+        // FaceLocation called on their current position - do nothing
+        return;
+    }
+
+    FaceDirectionalLoop(char1, GetDirectionalLoop(char1, diffrx, diffry), blockingStyle);
+}
+
+// External direction-facing functions with validation
+
+void Character_FaceDirection(CharacterInfo *char1, int direction, int blockingStyle)
+{
+    if (char1 == nullptr)
+        quit("!FaceDirection: invalid character specified");
+
+    if (direction != SCR_NO_VALUE)
+    {
+        if (direction < 0 || direction > kDirLoop_Last)
+            quit("!FaceDirection: invalid direction specified");
+
+        FaceDirectionalLoop(char1, direction, blockingStyle);
+    }
+}
+
+void Character_FaceLocation(CharacterInfo *char1, int xx, int yy, int blockingStyle)
+{
+    if (char1 == nullptr)
+        quit("!FaceLocation: invalid character specified");
+
+    FaceLocationXY(char1, xx, yy, blockingStyle);
+}
+
+void Character_FaceObject(CharacterInfo *char1, ScriptObject *obj, int blockingStyle) {
+    if (obj == nullptr) 
+        quit("!FaceObject: invalid object specified");
+
+    FaceLocationXY(char1, objs[obj->id].x, objs[obj->id].y, blockingStyle);
+}
+
+void Character_FaceCharacter(CharacterInfo *char1, CharacterInfo *char2, int blockingStyle) {
+    if (char2 == nullptr) 
+        quit("!FaceCharacter: invalid character specified");
+
+    if (char1->room != char2->room)
+        quit("!FaceCharacter: characters are in different rooms");
+
+    FaceLocationXY(char1, char2->x, char2->y, blockingStyle);
+}
+
+void Character_FollowCharacter(CharacterInfo *chaa, CharacterInfo *tofollow, int distaway, int eagerness) {
+
+    if ((eagerness < 0) || (eagerness > 250))
+        quit("!FollowCharacterEx: invalid eagerness: must be 0-250");
+
+    if ((chaa->index_id == game.playercharacter) && (tofollow != nullptr) && 
+        (tofollow->room != chaa->room))
+        quit("!FollowCharacterEx: you cannot tell the player character to follow a character in another room");
+
+    if (tofollow != nullptr) {
+        debug_script_log("%s: Start following %s (dist %d, eager %d)", chaa->scrname, tofollow->scrname, distaway, eagerness);
+    }
+    else {
+        debug_script_log("%s: Stop following other character", chaa->scrname);
+    }
+
+    if ((chaa->following >= 0) &&
+        (chaa->followinfo == FOLLOW_ALWAYSONTOP)) {
+            // if this character was following always-on-top, its baseline will
+            // have been changed, so release it.
+            chaa->baseline = -1;
+    }
+
+    if (tofollow == nullptr)
+        chaa->following = -1;
+    else
+        chaa->following = tofollow->index_id;
+
+    chaa->followinfo=(distaway << 8) | eagerness;
+
+    chaa->flags &= ~CHF_BEHINDSHEPHERD;
+
+    // special case for Always On Other Character
+    if (distaway == FOLLOW_ALWAYSONTOP) {
+        chaa->followinfo = FOLLOW_ALWAYSONTOP;
+        if (eagerness == 1)
+            chaa->flags |= CHF_BEHINDSHEPHERD;
+    }
+
+    if (chaa->animating & CHANIM_REPEAT)
+        debug_script_warn("Warning: FollowCharacter called but the sheep is currently animating looped. It may never start to follow.");
+
+}
+
+int Character_IsCollidingWithChar(CharacterInfo *char1, CharacterInfo *char2) {
+    if (char2 == nullptr)
+        quit("!AreCharactersColliding: invalid char2");
+
+    if (char1->room != char2->room) return 0; // not colliding
+
+    if ((char1->y > char2->y - 5) && (char1->y < char2->y + 5)) ;
+    else return 0;
+
+    int w1 = game_to_data_coord(GetCharacterWidth(char1->index_id));
+    int w2 = game_to_data_coord(GetCharacterWidth(char2->index_id));
+
+    int xps1=char1->x - w1/2;
+    int xps2=char2->x - w2/2;
+
+    if ((xps1 >= xps2 - w1) & (xps1 <= xps2 + w2)) return 1;
+    return 0;
+}
+
+int Character_IsCollidingWithObject(CharacterInfo *chin, ScriptObject *objid) {
+    if (objid == nullptr)
+        quit("!AreCharObjColliding: invalid object number");
+
+    if (chin->room != displayed_room)
+        return 0;
+    if (objs[objid->id].on != 1)
+        return 0;
+
+    Bitmap *checkblk = GetObjectImage(objid->id, nullptr);
+    int objWidth = checkblk->GetWidth();
+    int objHeight = checkblk->GetHeight();
+    int o1x = objs[objid->id].x;
+    int o1y = objs[objid->id].y - game_to_data_coord(objHeight);
+
+    Bitmap *charpic = GetCharacterImage(chin->index_id, nullptr);
+
+    int charWidth = charpic->GetWidth();
+    int charHeight = charpic->GetHeight();
+    int o2x = chin->x - game_to_data_coord(charWidth) / 2;
+    int o2y = chin->get_effective_y() - 5;  // only check feet
+
+    if ((o2x >= o1x - game_to_data_coord(charWidth)) &&
+        (o2x <= o1x + game_to_data_coord(objWidth)) &&
+        (o2y >= o1y - 8) &&
+        (o2y <= o1y + game_to_data_coord(objHeight))) {
+            // the character's feet are on the object
+            if (game.options[OPT_PIXPERFECT] == 0)
+                return 1;
+            // check if they're on a transparent bit of the object
+            int stxp = data_to_game_coord(o2x - o1x);
+            int styp = data_to_game_coord(o2y - o1y);
+            int maskcol = checkblk->GetMaskColor ();
+            int maskcolc = charpic->GetMaskColor ();
+            int thispix, thispixc;
+            // check each pixel of the object along the char's feet
+            for (int i = 0; i < charWidth; i += get_fixed_pixel_size(1)) {
+                for (int j = 0; j < get_fixed_pixel_size(6); j += get_fixed_pixel_size(1)) {
+                    thispix = my_getpixel(checkblk, i + stxp, j + styp);
+                    thispixc = my_getpixel(charpic, i, j + (charHeight - get_fixed_pixel_size(5)));
+
+                    if ((thispix != -1) && (thispix != maskcol) &&
+                        (thispixc != -1) && (thispixc != maskcolc))
+                        return 1;
+                }
+            }
+
+    }
+    return 0;
+}
+
+bool Character_IsInteractionAvailable(CharacterInfo *cchar, int mood) {
+
+    play.check_interaction_only = 1;
+    RunCharacterInteraction(cchar->index_id, mood);
+    int ciwas = play.check_interaction_only;
+    play.check_interaction_only = 0;
+    return (ciwas == 2);
+}
+
+void Character_LockView(CharacterInfo *chap, int vii) {
+    Character_LockViewEx(chap, vii, STOP_MOVING);
+}
+
+void Character_LockViewEx(CharacterInfo *chap, int vii, int stopMoving) {
+
+    if ((vii < 1) || (vii > game.numviews)) {
+        quitprintf("!SetCharacterView: invalid view number (You said %d, max is %d)", vii, game.numviews);
+    }
+    vii--;
+
+    debug_script_log("%s: View locked to %d", chap->scrname, vii+1);
+    if (chap->idleleft < 0) {
+        Character_UnlockView(chap);
+        chap->idleleft = chap->idletime;
+    }
+    if (stopMoving != KEEP_MOVING)
+    {
+        Character_StopMoving(chap);
+    }
+    chap->view=vii;
+    chap->animating=0;
+    FindReasonableLoopForCharacter(chap);
+    chap->frame=0;
+    chap->wait=0;
+    chap->flags|=CHF_FIXVIEW;
+    chap->pic_xoffs = 0;
+    chap->pic_yoffs = 0;
+}
+
+void Character_LockViewAligned_Old(CharacterInfo *chap, int vii, int loop, int align) {
+    Character_LockViewAlignedEx(chap, vii, loop, ConvertLegacyScriptAlignment((LegacyScriptAlignment)align), STOP_MOVING);
+}
+
+void Character_LockViewAlignedEx_Old(CharacterInfo *chap, int vii, int loop, int align, int stopMoving) {
+    Character_LockViewAlignedEx(chap, vii, loop, ConvertLegacyScriptAlignment((LegacyScriptAlignment)align), stopMoving);
+}
+
+void Character_LockViewAligned(CharacterInfo *chap, int vii, int loop, int align) {
+    Character_LockViewAlignedEx(chap, vii, loop, align, STOP_MOVING);
+}
+
+void Character_LockViewAlignedEx(CharacterInfo *chap, int vii, int loop, int align, int stopMoving) {
+    if (chap->view < 0)
+        quit("!SetCharacterLoop: character has invalid old view number");
+
+    int sppic = views[chap->view].loops[chap->loop].frames[chap->frame].pic;
+    int leftSide = data_to_game_coord(chap->x) - game.SpriteInfos[sppic].Width / 2;
+
+    Character_LockViewEx(chap, vii, stopMoving);
+
+    if ((loop < 0) || (loop >= views[chap->view].numLoops))
+        quit("!SetCharacterViewEx: invalid loop specified");
+
+    chap->loop = loop;
+    chap->frame = 0;
+    int newpic = views[chap->view].loops[chap->loop].frames[chap->frame].pic;
+    int newLeft = data_to_game_coord(chap->x) - game.SpriteInfos[newpic].Width / 2;
+    int xdiff = 0;
+
+    if (align & kMAlignLeft)
+        xdiff = leftSide - newLeft;
+    else if (align & kMAlignHCenter)
+        xdiff = 0;
+    else if (align & kMAlignRight)
+        xdiff = (leftSide + game.SpriteInfos[sppic].Width) - (newLeft + game.SpriteInfos[newpic].Width);
+    else
+        quit("!SetCharacterViewEx: invalid alignment type specified");
+
+    chap->pic_xoffs = xdiff;
+    chap->pic_yoffs = 0;
+}
+
+void Character_LockViewFrame(CharacterInfo *chaa, int view, int loop, int frame) {
+    Character_LockViewFrameEx(chaa, view, loop, frame, STOP_MOVING);
+}
+
+void Character_LockViewFrameEx(CharacterInfo *chaa, int view, int loop, int frame, int stopMoving) {
+
+    Character_LockViewEx(chaa, view, stopMoving);
+
+    view--;
+    if ((loop < 0) || (loop >= views[view].numLoops))
+        quit("!SetCharacterFrame: invalid loop specified");
+    if ((frame < 0) || (frame >= views[view].loops[loop].numFrames))
+        quit("!SetCharacterFrame: invalid frame specified");
+
+    chaa->loop = loop;
+    chaa->frame = frame;
+}
+
+void Character_LockViewOffset(CharacterInfo *chap, int vii, int xoffs, int yoffs) {
+    Character_LockViewOffsetEx(chap, vii, xoffs, yoffs, STOP_MOVING);
+}
+
+void Character_LockViewOffsetEx(CharacterInfo *chap, int vii, int xoffs, int yoffs, int stopMoving) {
+    Character_LockViewEx(chap, vii, stopMoving);
+
+    // This function takes offsets in real game coordinates as opposed to script coordinates
+    defgame_to_finalgame_coords(xoffs, yoffs);
+    chap->pic_xoffs = xoffs;
+    chap->pic_yoffs = yoffs;
+}
+
+void Character_LoseInventory(CharacterInfo *chap, ScriptInvItem *invi) {
+
+    if (invi == nullptr)
+        quit("!LoseInventoryFromCharacter: invalid invnetory number");
+
+    int inum = invi->id;
+
+    if (chap->inv[inum] > 0)
+        chap->inv[inum]--;
+
+    if ((chap->activeinv == inum) & (chap->inv[inum] < 1)) {
+        chap->activeinv = -1;
+        if ((chap == playerchar) && (GetCursorMode() == MODE_USE))
+            set_cursor_mode(0);
+    }
+
+    int charid = chap->index_id;
+
+    if ((chap->inv[inum] == 0) || (game.options[OPT_DUPLICATEINV] > 0)) {
+        int xx,tt;
+        for (xx = 0; xx < charextra[charid].invorder_count; xx++) {
+            if (charextra[charid].invorder[xx] == inum) {
+                charextra[charid].invorder_count--;
+                for (tt = xx; tt < charextra[charid].invorder_count; tt++)
+                    charextra[charid].invorder[tt] = charextra[charid].invorder[tt+1];
+                break;
+            }
+        }
+    }
+    guis_need_update = 1;
+
+    if (chap == playerchar)
+        run_on_event (GE_LOSE_INV, RuntimeScriptValue().SetInt32(inum));
+}
+
+void Character_PlaceOnWalkableArea(CharacterInfo *chap) 
+{
+    if (displayed_room < 0)
+        quit("!Character.PlaceOnWalkableArea: no room is currently loaded");
+
+    find_nearest_walkable_area(&chap->x, &chap->y);
+}
+
+void Character_RemoveTint(CharacterInfo *chaa) {
+
+    if (chaa->flags & (CHF_HASTINT | CHF_HASLIGHT)) {
+        debug_script_log("Un-tint %s", chaa->scrname);
+        chaa->flags &= ~(CHF_HASTINT | CHF_HASLIGHT);
+    }
+    else {
+        debug_script_warn("Character.RemoveTint called but character was not tinted");
+    }
+}
+
+int Character_GetHasExplicitTint_Old(CharacterInfo *ch)
+{
+    return ch->has_explicit_tint() || ch->has_explicit_light();
+}
+
+int Character_GetHasExplicitTint(CharacterInfo *ch)
+{
+    return ch->has_explicit_tint();
+}
+
+void Character_Say(CharacterInfo *chaa, const char *text) {
+    _DisplaySpeechCore(chaa->index_id, text);
+}
+
+void Character_SayAt(CharacterInfo *chaa, int x, int y, int width, const char *texx) {
+
+    DisplaySpeechAt(x, y, width, chaa->index_id, (char*)texx);
+}
+
+ScriptOverlay* Character_SayBackground(CharacterInfo *chaa, const char *texx) {
+
+    int ovltype = DisplaySpeechBackground(chaa->index_id, (char*)texx);
+    int ovri = find_overlay_of_type(ovltype);
+    if (ovri<0)
+        quit("!SayBackground internal error: no overlay");
+
+    // Convert the overlay ID to an Overlay object
+    ScriptOverlay *scOver = new ScriptOverlay();
+    scOver->overlayId = ovltype;
+    scOver->borderHeight = 0;
+    scOver->borderWidth = 0;
+    scOver->isBackgroundSpeech = 1;
+    int handl = ccRegisterManagedObject(scOver, scOver);
+    screenover[ovri].associatedOverlayHandle = handl;
+
+    return scOver;
+}
+
+void Character_SetAsPlayer(CharacterInfo *chaa) {
+
+    // Set to same character, so ignore.
+    // But only on versions > 2.61. The relevant entry in the 2.62 changelog is:
+    //  - Fixed SetPlayerCharacter to do nothing at all if you pass the current
+    //    player character to it (previously it was resetting the inventory layout)
+    if ((loaded_game_file_version > kGameVersion_261) && (game.playercharacter == chaa->index_id))
+        return;
+
+    setup_player_character(chaa->index_id);
+
+    //update_invorder();
+
+    debug_script_log("%s is new player character", playerchar->scrname);
+
+    // Within game_start, return now
+    if (displayed_room < 0)
+        return;
+
+    // Ignore invalid room numbers for the character and just place him in
+    // the current room for 2.x. Following script calls to NewRoom() will
+    // make sure this still works as intended.
+    if ((loaded_game_file_version <= kGameVersion_272) && (playerchar->room < 0))
+        playerchar->room = displayed_room;
+
+    if (displayed_room != playerchar->room)
+        NewRoom(playerchar->room);
+    else   // make sure it doesn't run the region interactions
+        play.player_on_region = GetRegionIDAtRoom(playerchar->x, playerchar->y);
+
+    if ((playerchar->activeinv >= 0) && (playerchar->inv[playerchar->activeinv] < 1))
+        playerchar->activeinv = -1;
+
+    // They had inv selected, so change the cursor
+    if (cur_mode == MODE_USE) {
+        if (playerchar->activeinv < 0)
+            SetNextCursor ();
+        else
+            SetActiveInventory (playerchar->activeinv);
+    }
+
+}
+
+
+void Character_SetIdleView(CharacterInfo *chaa, int iview, int itime) {
+
+    if (iview == 1) 
+        quit("!SetCharacterIdle: view 1 cannot be used as an idle view, sorry.");
+
+    // if an idle anim is currently playing, release it
+    if (chaa->idleleft < 0)
+        Character_UnlockView(chaa);
+
+    chaa->idleview = iview - 1;
+    // make sure they don't appear idle while idle anim is disabled
+    if (iview < 1)
+        itime = 10;
+    chaa->idletime = itime;
+    chaa->idleleft = itime;
+
+    // if not currently animating, reset the wait counter
+    if ((chaa->animating == 0) && (chaa->walking == 0))
+        chaa->wait = 0;
+
+    if (iview >= 1) {
+        debug_script_log("Set %s idle view to %d (time %d)", chaa->scrname, iview, itime);
+    }
+    else {
+        debug_script_log("%s idle view disabled", chaa->scrname);
+    }
+    if (chaa->flags & CHF_FIXVIEW) {
+        debug_script_warn("SetCharacterIdle called while character view locked with SetCharacterView; idle ignored");
+        debug_script_log("View locked, idle will not kick in until Released");
+    }
+    // if they switch to a swimming animation, kick it off immediately
+    if (itime == 0)
+        charextra[chaa->index_id].process_idle_this_time = 1;
+
+}
+
+bool Character_GetHasExplicitLight(CharacterInfo *ch)
+{
+    return ch->has_explicit_light();
+}
+
+int Character_GetLightLevel(CharacterInfo *ch)
+{
+    return ch->has_explicit_light() ? charextra[ch->index_id].tint_light : 0;
+}
+
+void Character_SetLightLevel(CharacterInfo *chaa, int light_level)
+{
+    light_level = Math::Clamp(light_level, -100, 100);
+    
+    charextra[chaa->index_id].tint_light = light_level;
+    chaa->flags &= ~CHF_HASTINT;
+    chaa->flags |= CHF_HASLIGHT;
+}
+
+int Character_GetTintRed(CharacterInfo *ch)
+{
+    return ch->has_explicit_tint() ? charextra[ch->index_id].tint_r : 0;
+}
+
+int Character_GetTintGreen(CharacterInfo *ch)
+{
+    return ch->has_explicit_tint() ? charextra[ch->index_id].tint_g : 0;
+}
+
+int Character_GetTintBlue(CharacterInfo *ch)
+{
+    return ch->has_explicit_tint() ? charextra[ch->index_id].tint_b : 0;
+}
+
+int Character_GetTintSaturation(CharacterInfo *ch)
+{
+    return ch->has_explicit_tint() ? charextra[ch->index_id].tint_level : 0;
+}
+
+int Character_GetTintLuminance(CharacterInfo *ch)
+{
+    return ch->has_explicit_tint() ? ((charextra[ch->index_id].tint_light * 10) / 25) : 0;
+}
+
+void Character_SetOption(CharacterInfo *chaa, int flag, int yesorno) {
+
+    if ((yesorno < 0) || (yesorno > 1))
+        quit("!SetCharacterProperty: last parameter must be 0 or 1");
+
+    if (flag & CHF_MANUALSCALING) {
+        // backwards compatibility fix
+        Character_SetIgnoreScaling(chaa, yesorno);
+    }
+    else {
+        chaa->flags &= ~flag;
+        if (yesorno)
+            chaa->flags |= flag;
+    }
+
+}
+
+void Character_SetSpeed(CharacterInfo *chaa, int xspeed, int yspeed) {
+
+    if ((xspeed == 0) || (xspeed > 50) || (yspeed == 0) || (yspeed > 50))
+        quit("!SetCharacterSpeedEx: invalid speed value");
+    if (chaa->walking)
+    {
+        debug_script_warn("Character_SetSpeed: cannot change speed while walking");
+        return;
+    }
+
+    chaa->walkspeed = xspeed;
+
+    if (yspeed == xspeed) 
+        chaa->walkspeed_y = UNIFORM_WALK_SPEED;
+    else
+        chaa->walkspeed_y = yspeed;
+}
+
+
+void Character_StopMoving(CharacterInfo *charp) {
+
+    int chaa = charp->index_id;
+    if (chaa == play.skip_until_char_stops)
+        EndSkippingUntilCharStops();
+
+    if (charextra[chaa].xwas != INVALID_X) {
+        charp->x = charextra[chaa].xwas;
+        charp->y = charextra[chaa].ywas;
+        charextra[chaa].xwas = INVALID_X;
+    }
+    if ((charp->walking > 0) && (charp->walking < TURNING_AROUND)) {
+        // if it's not a MoveCharDirect, make sure they end up on a walkable area
+        if ((mls[charp->walking].direct == 0) && (charp->room == displayed_room))
+            Character_PlaceOnWalkableArea(charp);
+
+        debug_script_log("%s: stop moving", charp->scrname);
+
+        charp->idleleft = charp->idletime;
+        // restart the idle animation straight away
+        charextra[chaa].process_idle_this_time = 1;
+    }
+    if (charp->walking) {
+        // If the character is currently moving, stop them and reset their frame
+        charp->walking = 0;
+        if ((charp->flags & CHF_MOVENOTWALK) == 0)
+            charp->frame = 0;
+    }
+}
+
+void Character_Tint(CharacterInfo *chaa, int red, int green, int blue, int opacity, int luminance) {
+    if ((red < 0) || (green < 0) || (blue < 0) ||
+        (red > 255) || (green > 255) || (blue > 255) ||
+        (opacity < 0) || (opacity > 100) ||
+        (luminance < 0) || (luminance > 100))
+        quit("!Character.Tint: invalid parameter. R,G,B must be 0-255, opacity & luminance 0-100");
+
+    debug_script_log("Set %s tint RGB(%d,%d,%d) %d%%", chaa->scrname, red, green, blue, opacity);
+
+    charextra[chaa->index_id].tint_r = red;
+    charextra[chaa->index_id].tint_g = green;
+    charextra[chaa->index_id].tint_b = blue;
+    charextra[chaa->index_id].tint_level = opacity;
+    charextra[chaa->index_id].tint_light = (luminance * 25) / 10;
+    chaa->flags &= ~CHF_HASLIGHT;
+    chaa->flags |= CHF_HASTINT;
+}
+
+void Character_Think(CharacterInfo *chaa, const char *text) {
+    _DisplayThoughtCore(chaa->index_id, text);
+}
+
+void Character_UnlockView(CharacterInfo *chaa) {
+    Character_UnlockViewEx(chaa, STOP_MOVING);
+}
+
+void Character_UnlockViewEx(CharacterInfo *chaa, int stopMoving) {
+    if (chaa->flags & CHF_FIXVIEW) {
+        debug_script_log("%s: Released view back to default", chaa->scrname);
+    }
+    chaa->flags &= ~CHF_FIXVIEW;
+    chaa->view = chaa->defview;
+    chaa->frame = 0;
+    if (stopMoving != KEEP_MOVING)
+    {
+        Character_StopMoving(chaa);
+    }
+    if (chaa->view >= 0) {
+        int maxloop = views[chaa->view].numLoops;
+        if (((chaa->flags & CHF_NODIAGONAL)!=0) && (maxloop > 4))
+            maxloop = 4;
+        FindReasonableLoopForCharacter(chaa);
+    }
+    chaa->animating = 0;
+    chaa->idleleft = chaa->idletime;
+    chaa->pic_xoffs = 0;
+    chaa->pic_yoffs = 0;
+    // restart the idle animation straight away
+    charextra[chaa->index_id].process_idle_this_time = 1;
+
+}
+
+
+void Character_Walk(CharacterInfo *chaa, int x, int y, int blocking, int direct) 
+{
+    walk_or_move_character(chaa, x, y, blocking, direct, true);
+}
+
+void Character_Move(CharacterInfo *chaa, int x, int y, int blocking, int direct) 
+{
+    walk_or_move_character(chaa, x, y, blocking, direct, false);
+}
+
+void Character_WalkStraight(CharacterInfo *chaa, int xx, int yy, int blocking) {
+
+    if (chaa->room != displayed_room)
+        quit("!MoveCharacterStraight: specified character not in current room");
+
+    Character_StopMoving(chaa);
+    int movetox = xx, movetoy = yy;
+
+    set_wallscreen(prepare_walkable_areas(chaa->index_id));
+
+    int fromXLowres = room_to_mask_coord(chaa->x);
+    int fromYLowres = room_to_mask_coord(chaa->y);
+    int toXLowres = room_to_mask_coord(xx);
+    int toYLowres = room_to_mask_coord(yy);
+
+    if (!can_see_from(fromXLowres, fromYLowres, toXLowres, toYLowres)) {
+        int lastcx, lastcy;
+        get_lastcpos(lastcx, lastcy);
+        movetox = mask_to_room_coord(lastcx);
+        movetoy = mask_to_room_coord(lastcy);
+    }
+
+    walk_character(chaa->index_id, movetox, movetoy, 1, true);
+
+    if ((blocking == BLOCKING) || (blocking == 1))
+        GameLoopUntilNotMoving(&chaa->walking);
+    else if ((blocking != IN_BACKGROUND) && (blocking != 0))
+        quit("!Character.Walk: Blocking must be BLOCKING or IN_BACKGRUOND");
+
+}
+
+void Character_RunInteraction(CharacterInfo *chaa, int mood) {
+
+    RunCharacterInteraction(chaa->index_id, mood);
+}
+
+
+
+// **** CHARACTER: PROPERTIES ****
+
+int Character_GetProperty(CharacterInfo *chaa, const char *property) {
+
+    return get_int_property(game.charProps[chaa->index_id], play.charProps[chaa->index_id], property);
+
+}
+void Character_GetPropertyText(CharacterInfo *chaa, const char *property, char *bufer) {
+    get_text_property(game.charProps[chaa->index_id], play.charProps[chaa->index_id], property, bufer);
+}
+const char* Character_GetTextProperty(CharacterInfo *chaa, const char *property) {
+    return get_text_property_dynamic_string(game.charProps[chaa->index_id], play.charProps[chaa->index_id], property);
+}
+
+bool Character_SetProperty(CharacterInfo *chaa, const char *property, int value)
+{
+    return set_int_property(play.charProps[chaa->index_id], property, value);
+}
+
+bool Character_SetTextProperty(CharacterInfo *chaa, const char *property, const char *value)
+{
+    return set_text_property(play.charProps[chaa->index_id], property, value);
+}
+
+ScriptInvItem* Character_GetActiveInventory(CharacterInfo *chaa) {
+
+    if (chaa->activeinv <= 0)
+        return nullptr;
+
+    return &scrInv[chaa->activeinv];
+}
+
+void Character_SetActiveInventory(CharacterInfo *chaa, ScriptInvItem* iit) {
+    guis_need_update = 1;
+
+    if (iit == nullptr) {
+        chaa->activeinv = -1;
+
+        if (chaa->index_id == game.playercharacter) {
+
+            if (GetCursorMode()==MODE_USE)
+                set_cursor_mode(0);
+        }
+        return;
+    }
+
+    if (chaa->inv[iit->id] < 1)
+    {
+        debug_script_warn("SetActiveInventory: character doesn't have any of that inventory");
+        return;
+    }
+
+    chaa->activeinv = iit->id;
+
+    if (chaa->index_id == game.playercharacter) {
+        // if it's the player character, update mouse cursor
+        update_inv_cursor(iit->id);
+        set_cursor_mode(MODE_USE);
+    }
+}
+
+int Character_GetAnimating(CharacterInfo *chaa) {
+    if (chaa->animating)
+        return 1;
+    return 0;
+}
+
+int Character_GetAnimationSpeed(CharacterInfo *chaa) {
+    return chaa->animspeed;
+}
+
+void Character_SetAnimationSpeed(CharacterInfo *chaa, int newval) {
+
+    chaa->animspeed = newval;
+}
+
+int Character_GetBaseline(CharacterInfo *chaa) {
+
+    if (chaa->baseline < 1)
+        return 0;
+
+    return chaa->baseline;
+}
+
+void Character_SetBaseline(CharacterInfo *chaa, int basel) {
+
+    chaa->baseline = basel;
+}
+
+int Character_GetBlinkInterval(CharacterInfo *chaa) {
+
+    return chaa->blinkinterval;
+}
+
+void Character_SetBlinkInterval(CharacterInfo *chaa, int interval) {
+
+    if (interval < 0)
+        quit("!SetCharacterBlinkView: invalid blink interval");
+
+    chaa->blinkinterval = interval;
+
+    if (chaa->blinktimer > 0)
+        chaa->blinktimer = chaa->blinkinterval;
+}
+
+int Character_GetBlinkView(CharacterInfo *chaa) {
+
+    return chaa->blinkview + 1;
+}
+
+void Character_SetBlinkView(CharacterInfo *chaa, int vii) {
+
+    if (((vii < 2) || (vii > game.numviews)) && (vii != -1))
+        quit("!SetCharacterBlinkView: invalid view number");
+
+    chaa->blinkview = vii - 1;
+}
+
+int Character_GetBlinkWhileThinking(CharacterInfo *chaa) {
+    if (chaa->flags & CHF_NOBLINKANDTHINK)
+        return 0;
+    return 1;
+}
+
+void Character_SetBlinkWhileThinking(CharacterInfo *chaa, int yesOrNo) {
+    chaa->flags &= ~CHF_NOBLINKANDTHINK;
+    if (yesOrNo == 0)
+        chaa->flags |= CHF_NOBLINKANDTHINK;
+}
+
+int Character_GetBlockingHeight(CharacterInfo *chaa) {
+
+    return chaa->blocking_height;
+}
+
+void Character_SetBlockingHeight(CharacterInfo *chaa, int hit) {
+
+    chaa->blocking_height = hit;
+}
+
+int Character_GetBlockingWidth(CharacterInfo *chaa) {
+
+    return chaa->blocking_width;
+}
+
+void Character_SetBlockingWidth(CharacterInfo *chaa, int wid) {
+
+    chaa->blocking_width = wid;
+}
+
+int Character_GetDiagonalWalking(CharacterInfo *chaa) {
+
+    if (chaa->flags & CHF_NODIAGONAL)
+        return 0;
+    return 1;  
+}
+
+void Character_SetDiagonalWalking(CharacterInfo *chaa, int yesorno) {
+
+    chaa->flags &= ~CHF_NODIAGONAL;
+    if (!yesorno)
+        chaa->flags |= CHF_NODIAGONAL;
+}
+
+int Character_GetClickable(CharacterInfo *chaa) {
+
+    if (chaa->flags & CHF_NOINTERACT)
+        return 0;
+    return 1;
+}
+
+void Character_SetClickable(CharacterInfo *chaa, int clik) {
+
+    chaa->flags &= ~CHF_NOINTERACT;
+    // if they don't want it clickable, set the relevant bit
+    if (clik == 0)
+        chaa->flags |= CHF_NOINTERACT;
+}
+
+int Character_GetID(CharacterInfo *chaa) {
+
+    return chaa->index_id;
+
+}
+
+int Character_GetFrame(CharacterInfo *chaa) {
+    return chaa->frame;
+}
+
+void Character_SetFrame(CharacterInfo *chaa, int newval) {
+    chaa->frame = newval;
+}
+
+int Character_GetIdleView(CharacterInfo *chaa) {
+
+    if (chaa->idleview < 1)
+        return -1;
+
+    return chaa->idleview + 1;
+}
+
+int Character_GetIInventoryQuantity(CharacterInfo *chaa, int index) {
+    if ((index < 1) || (index >= game.numinvitems))
+        quitprintf("!Character.InventoryQuantity: invalid inventory index %d", index);
+
+    return chaa->inv[index];
+}
+
+int Character_HasInventory(CharacterInfo *chaa, ScriptInvItem *invi)
+{
+    if (invi == nullptr)
+        quit("!Character.HasInventory: NULL inventory item supplied");
+
+    return (chaa->inv[invi->id] > 0) ? 1 : 0;
+}
+
+void Character_SetIInventoryQuantity(CharacterInfo *chaa, int index, int quant) {
+    if ((index < 1) || (index >= game.numinvitems))
+        quitprintf("!Character.InventoryQuantity: invalid inventory index %d", index);
+
+    if ((quant < 0) || (quant > 32000))
+        quitprintf("!Character.InventoryQuantity: invalid quantity %d", quant);
+
+    chaa->inv[index] = quant;
+}
+
+int Character_GetIgnoreLighting(CharacterInfo *chaa) {
+
+    if (chaa->flags & CHF_NOLIGHTING)
+        return 1;
+    return 0;
+}
+
+void Character_SetIgnoreLighting(CharacterInfo *chaa, int yesorno) {
+
+    chaa->flags &= ~CHF_NOLIGHTING;
+    if (yesorno)
+        chaa->flags |= CHF_NOLIGHTING;
+}
+
+int Character_GetIgnoreScaling(CharacterInfo *chaa) {
+
+    if (chaa->flags & CHF_MANUALSCALING)
+        return 1;
+    return 0;  
+}
+
+void Character_SetIgnoreScaling(CharacterInfo *chaa, int yesorno) {
+
+    if (yesorno) {
+        // when setting IgnoreScaling to 1, should reset zoom level
+        // like it used to in pre-2.71
+        charextra[chaa->index_id].zoom = 100;
+    }
+    Character_SetManualScaling(chaa, yesorno);
+}
+
+void Character_SetManualScaling(CharacterInfo *chaa, int yesorno) {
+
+    chaa->flags &= ~CHF_MANUALSCALING;
+    if (yesorno)
+        chaa->flags |= CHF_MANUALSCALING;
+}
+
+int Character_GetIgnoreWalkbehinds(CharacterInfo *chaa) {
+
+    if (chaa->flags & CHF_NOWALKBEHINDS)
+        return 1;
+    return 0;
+}
+
+void Character_SetIgnoreWalkbehinds(CharacterInfo *chaa, int yesorno) {
+    if (game.options[OPT_BASESCRIPTAPI] >= kScriptAPI_v350)
+        debug_script_warn("IgnoreWalkbehinds is not recommended for use, consider other solutions");
+    chaa->flags &= ~CHF_NOWALKBEHINDS;
+    if (yesorno)
+        chaa->flags |= CHF_NOWALKBEHINDS;
+}
+
+int Character_GetMovementLinkedToAnimation(CharacterInfo *chaa) {
+
+    if (chaa->flags & CHF_ANTIGLIDE)
+        return 1;
+    return 0;
+}
+
+void Character_SetMovementLinkedToAnimation(CharacterInfo *chaa, int yesorno) {
+
+    chaa->flags &= ~CHF_ANTIGLIDE;
+    if (yesorno)
+        chaa->flags |= CHF_ANTIGLIDE;
+}
+
+int Character_GetLoop(CharacterInfo *chaa) {
+    return chaa->loop;
+}
+
+void Character_SetLoop(CharacterInfo *chaa, int newval) {
+    if ((newval < 0) || (newval >= views[chaa->view].numLoops))
+        quit("!Character.Loop: invalid loop number for this view");
+
+    chaa->loop = newval;
+
+    if (chaa->frame >= views[chaa->view].loops[chaa->loop].numFrames)
+        chaa->frame = 0;
+}
+
+int Character_GetMoving(CharacterInfo *chaa) {
+    if (chaa->walking)
+        return 1;
+    return 0;
+}
+
+int Character_GetDestinationX(CharacterInfo *chaa) {
+    if (chaa->walking) {
+        MoveList *cmls = &mls[chaa->walking % TURNING_AROUND];
+        return cmls->pos[cmls->numstage - 1] >> 16;
+    }
+    else
+        return chaa->x;
+}
+
+int Character_GetDestinationY(CharacterInfo *chaa) {
+    if (chaa->walking) {
+        MoveList *cmls = &mls[chaa->walking % TURNING_AROUND];
+        return cmls->pos[cmls->numstage - 1] & 0xFFFF;
+    }
+    else
+        return chaa->y;
+}
+
+const char* Character_GetName(CharacterInfo *chaa) {
+    return CreateNewScriptString(chaa->name);
+}
+
+void Character_SetName(CharacterInfo *chaa, const char *newName) {
+    strncpy(chaa->name, newName, 40);
+    chaa->name[39] = 0;
+}
+
+int Character_GetNormalView(CharacterInfo *chaa) {
+    return chaa->defview + 1;
+}
+
+int Character_GetPreviousRoom(CharacterInfo *chaa) {
+    return chaa->prevroom;
+}
+
+int Character_GetRoom(CharacterInfo *chaa) {
+    return chaa->room;
+}
+
+
+int Character_GetScaleMoveSpeed(CharacterInfo *chaa) {
+
+    if (chaa->flags & CHF_SCALEMOVESPEED)
+        return 1;
+    return 0;  
+}
+
+void Character_SetScaleMoveSpeed(CharacterInfo *chaa, int yesorno) {
+
+    if ((yesorno < 0) || (yesorno > 1))
+        quit("Character.ScaleMoveSpeed: value must be true or false (1 or 0)");
+
+    chaa->flags &= ~CHF_SCALEMOVESPEED;
+    if (yesorno)
+        chaa->flags |= CHF_SCALEMOVESPEED;
+}
+
+int Character_GetScaleVolume(CharacterInfo *chaa) {
+
+    if (chaa->flags & CHF_SCALEVOLUME)
+        return 1;
+    return 0;  
+}
+
+void Character_SetScaleVolume(CharacterInfo *chaa, int yesorno) {
+
+    if ((yesorno < 0) || (yesorno > 1))
+        quit("Character.ScaleVolume: value must be true or false (1 or 0)");
+
+    chaa->flags &= ~CHF_SCALEVOLUME;
+    if (yesorno)
+        chaa->flags |= CHF_SCALEVOLUME;
+}
+
+int Character_GetScaling(CharacterInfo *chaa) {
+    return charextra[chaa->index_id].zoom;
+}
+
+void Character_SetScaling(CharacterInfo *chaa, int zoomlevel) {
+
+    if ((chaa->flags & CHF_MANUALSCALING) == 0)
+    {
+        debug_script_warn("Character.Scaling: cannot set property unless ManualScaling is enabled");
+        return;
+    }
+    if ((zoomlevel < 5) || (zoomlevel > 200))
+        quit("!Character.Scaling: scaling level must be between 5 and 200%");
+
+    charextra[chaa->index_id].zoom = zoomlevel;
+}
+
+int Character_GetSolid(CharacterInfo *chaa) {
+
+    if (chaa->flags & CHF_NOBLOCKING)
+        return 0;
+    return 1;
+}
+
+void Character_SetSolid(CharacterInfo *chaa, int yesorno) {
+
+    chaa->flags &= ~CHF_NOBLOCKING;
+    if (!yesorno)
+        chaa->flags |= CHF_NOBLOCKING;
+}
+
+int Character_GetSpeaking(CharacterInfo *chaa) {
+    if (get_character_currently_talking() == chaa->index_id)
+        return 1;
+
+    return 0;
+}
+
+int Character_GetSpeechColor(CharacterInfo *chaa) {
+
+    return chaa->talkcolor;
+}
+
+void Character_SetSpeechColor(CharacterInfo *chaa, int ncol) {
+
+    chaa->talkcolor = ncol;
+}
+
+void Character_SetSpeechAnimationDelay(CharacterInfo *chaa, int newDelay)
+{
+    if (game.options[OPT_GLOBALTALKANIMSPD] != 0)
+    {
+        debug_script_warn("Character.SpeechAnimationDelay cannot be set when global speech animation speed is enabled");
+        return;
+    }
+
+    chaa->speech_anim_speed = newDelay;
+}
+
+int Character_GetSpeechView(CharacterInfo *chaa) {
+
+    return chaa->talkview + 1;
+}
+
+void Character_SetSpeechView(CharacterInfo *chaa, int vii) {
+    if (vii == -1) {
+        chaa->talkview = -1;
+        return;
+    }
+
+    if ((vii < 1) || (vii > game.numviews))
+        quit("!SetCharacterSpeechView: invalid view number");
+
+    chaa->talkview = vii - 1;
+}
+
+bool Character_GetThinking(CharacterInfo *chaa)
+{
+    return char_thinking == chaa->index_id;
+}
+
+int Character_GetThinkingFrame(CharacterInfo *chaa)
+{
+    if (char_thinking == chaa->index_id)
+        return chaa->thinkview > 0 ? chaa->frame : -1;
+
+    debug_script_warn("Character.ThinkingFrame: character is not currently thinking");
+    return -1;
+}
+
+int Character_GetThinkView(CharacterInfo *chaa) {
+
+    return chaa->thinkview + 1;
+}
+
+void Character_SetThinkView(CharacterInfo *chaa, int vii) {
+    if (((vii < 2) || (vii > game.numviews)) && (vii != -1))
+        quit("!SetCharacterThinkView: invalid view number");
+
+    chaa->thinkview = vii - 1;
+}
+
+int Character_GetTransparency(CharacterInfo *chaa) {
+
+    return GfxDef::LegacyTrans255ToTrans100(chaa->transparency);
+}
+
+void Character_SetTransparency(CharacterInfo *chaa, int trans) {
+
+    if ((trans < 0) || (trans > 100))
+        quit("!SetCharTransparent: transparency value must be between 0 and 100");
+
+    chaa->transparency = GfxDef::Trans100ToLegacyTrans255(trans);
+}
+
+int Character_GetTurnBeforeWalking(CharacterInfo *chaa) {
+
+    if (chaa->flags & CHF_NOTURNING)
+        return 0;
+    return 1;  
+}
+
+void Character_SetTurnBeforeWalking(CharacterInfo *chaa, int yesorno) {
+
+    chaa->flags &= ~CHF_NOTURNING;
+    if (!yesorno)
+        chaa->flags |= CHF_NOTURNING;
+}
+
+int Character_GetView(CharacterInfo *chaa) {
+    return chaa->view + 1;
+}
+
+int Character_GetWalkSpeedX(CharacterInfo *chaa) {
+    return chaa->walkspeed;
+}
+
+int Character_GetWalkSpeedY(CharacterInfo *chaa) {
+    if (chaa->walkspeed_y != UNIFORM_WALK_SPEED)
+        return chaa->walkspeed_y;
+
+    return chaa->walkspeed;
+}
+
+int Character_GetX(CharacterInfo *chaa) {
+    return chaa->x;
+}
+
+void Character_SetX(CharacterInfo *chaa, int newval) {
+    chaa->x = newval;
+}
+
+int Character_GetY(CharacterInfo *chaa) {
+    return chaa->y;
+}
+
+void Character_SetY(CharacterInfo *chaa, int newval) {
+    chaa->y = newval;
+}
+
+int Character_GetZ(CharacterInfo *chaa) {
+    return chaa->z;
+}
+
+void Character_SetZ(CharacterInfo *chaa, int newval) {
+    chaa->z = newval;
+}
+
+extern int char_speaking;
+
+int Character_GetSpeakingFrame(CharacterInfo *chaa) {
+
+    if ((face_talking >= 0) && (facetalkrepeat))
+    {
+        if (facetalkchar->index_id == chaa->index_id)
+        {
+            return facetalkframe;
+        }
+    }
+    else if (char_speaking >= 0)
+    {
+        if (char_speaking == chaa->index_id)
+        {
+            return chaa->frame;
+        }
+    }
+
+    debug_script_warn("Character.SpeakingFrame: character is not currently speaking");
+    return -1;
+}
+
+//=============================================================================
+
+// order of loops to turn character in circle from down to down
+int turnlooporder[8] = {0, 6, 1, 7, 3, 5, 2, 4};
+
+void walk_character(int chac,int tox,int toy,int ignwal, bool autoWalkAnims) {
+    CharacterInfo*chin=&game.chars[chac];
+    if (chin->room!=displayed_room)
+        quit("!MoveCharacter: character not in current room");
+
+    chin->flags &= ~CHF_MOVENOTWALK;
+
+    int toxPassedIn = tox, toyPassedIn = toy;
+    int charX = room_to_mask_coord(chin->x);
+    int charY = room_to_mask_coord(chin->y);
+    tox = room_to_mask_coord(tox);
+    toy = room_to_mask_coord(toy);
+
+    if ((tox == charX) && (toy == charY)) {
+        StopMoving(chac);
+        debug_script_log("%s already at destination, not moving", chin->scrname);
+        return;
+    }
+
+    if ((chin->animating) && (autoWalkAnims))
+        chin->animating = 0;
+
+    if (chin->idleleft < 0) {
+        ReleaseCharacterView(chac);
+        chin->idleleft=chin->idletime;
+    }
+    // stop them to make sure they're on a walkable area
+    // but save their frame first so that if they're already
+    // moving it looks smoother
+    int oldframe = chin->frame;
+    int waitWas = 0, animWaitWas = 0;
+    // if they are currently walking, save the current Wait
+    if (chin->walking)
+    {
+        waitWas = chin->walkwait;
+        animWaitWas = charextra[chac].animwait;
+    }
+
+    StopMoving (chac);
+    chin->frame = oldframe;
+    // use toxPassedIn cached variable so the hi-res co-ordinates
+    // are still displayed as such
+    debug_script_log("%s: Start move to %d,%d", chin->scrname, toxPassedIn, toyPassedIn);
+
+    int move_speed_x = chin->walkspeed;
+    int move_speed_y = chin->walkspeed;
+
+    if (chin->walkspeed_y != UNIFORM_WALK_SPEED)
+        move_speed_y = chin->walkspeed_y;
+
+    if ((move_speed_x == 0) && (move_speed_y == 0)) {
+        debug_script_warn("Warning: MoveCharacter called for '%s' with walk speed 0", chin->name);
+    }
+
+    set_route_move_speed(move_speed_x, move_speed_y);
+    set_color_depth(8);
+    int mslot=find_route(charX, charY, tox, toy, prepare_walkable_areas(chac), chac+CHMLSOFFS, 1, ignwal);
+    set_color_depth(game.GetColorDepth());
+    if (mslot>0) {
+        chin->walking = mslot;
+        mls[mslot].direct = ignwal;
+        convert_move_path_to_room_resolution(&mls[mslot]);
+
+        // cancel any pending waits on current animations
+        // or if they were already moving, keep the current wait - 
+        // this prevents a glitch if MoveCharacter is called when they
+        // are already moving
+        if (autoWalkAnims)
+        {
+            chin->walkwait = waitWas;
+            charextra[chac].animwait = animWaitWas;
+
+            if (mls[mslot].pos[0] != mls[mslot].pos[1]) {
+                fix_player_sprite(&mls[mslot],chin);
+            }
+        }
+        else
+            chin->flags |= CHF_MOVENOTWALK;
+    }
+    else if (autoWalkAnims) // pathfinder couldn't get a route, stand them still
+        chin->frame = 0;
+}
+
+int find_looporder_index (int curloop) {
+    int rr;
+    for (rr = 0; rr < 8; rr++) {
+        if (turnlooporder[rr] == curloop)
+            return rr;
+    }
+    return 0;
+}
+
+// returns 0 to use diagonal, 1 to not
+int useDiagonal (CharacterInfo *char1) {
+    if ((views[char1->view].numLoops < 8) || ((char1->flags & CHF_NODIAGONAL)!=0))
+        return 1;
+    // If they have just provided standing frames for loops 4-7, to
+    // provide smoother turning
+    if (views[char1->view].loops[4].numFrames < 2)
+        return 2;
+    return 0;
+}
+
+// returns 1 normally, or 0 if they only have horizontal animations
+int hasUpDownLoops(CharacterInfo *char1) {
+    // if no loops in the Down animation
+    // or no loops in the Up animation
+    if ((views[char1->view].loops[0].numFrames < 1) ||
+        (views[char1->view].numLoops < 4) ||
+        (views[char1->view].loops[3].numFrames < 1))
+    {
+        return 0;
+    }
+
+    return 1;
+}
+
+void start_character_turning (CharacterInfo *chinf, int useloop, int no_diagonal) {
+    // work out how far round they have to turn 
+    int fromidx = find_looporder_index (chinf->loop);
+    int toidx = find_looporder_index (useloop);
+    //Display("Curloop: %d, needloop: %d",chinf->loop, useloop);
+    int ii, go_anticlock = 0;
+    // work out whether anticlockwise is quicker or not
+    if ((toidx > fromidx) && ((toidx - fromidx) > 4))
+        go_anticlock = 1;
+    if ((toidx < fromidx) && ((fromidx - toidx) < 4))
+        go_anticlock = 1;
+    // strip any current turning_around stages
+    chinf->walking = chinf->walking % TURNING_AROUND;
+    if (go_anticlock)
+        chinf->walking += TURNING_BACKWARDS;
+    else
+        go_anticlock = -1;
+
+    // Allow the diagonal frames just for turning
+    if (no_diagonal == 2)
+        no_diagonal = 0;
+
+    for (ii = fromidx; ii != toidx; ii -= go_anticlock) {
+        if (ii < 0)
+            ii = 7;
+        if (ii >= 8)
+            ii = 0;
+        if (ii == toidx)
+            break;
+        if ((turnlooporder[ii] >= 4) && (no_diagonal > 0))
+            continue;
+        if (views[chinf->view].loops[turnlooporder[ii]].numFrames < 1)
+            continue;
+        if (turnlooporder[ii] < views[chinf->view].numLoops)
+            chinf->walking += TURNING_AROUND;
+    }
+
+}
+
+void fix_player_sprite(MoveList*cmls,CharacterInfo*chinf) {
+    const fixed xpmove = cmls->xpermove[cmls->onstage];
+    const fixed ypmove = cmls->ypermove[cmls->onstage];
+
+    // if not moving, do nothing
+    if ((xpmove == 0) && (ypmove == 0))
+        return;
+
+    const int useloop = GetDirectionalLoop(chinf, xpmove, ypmove);
+
+    if ((game.options[OPT_ROTATECHARS] == 0) || ((chinf->flags & CHF_NOTURNING) != 0)) {
+        chinf->loop = useloop;
+        return;
+    }
+    if ((chinf->loop > kDirLoop_LastOrthogonal) && ((chinf->flags & CHF_NODIAGONAL)!=0)) {
+        // They've just been playing an animation with an extended loop number,
+        // so don't try and rotate using it
+        chinf->loop = useloop;
+        return;
+    }
+    if ((chinf->loop >= views[chinf->view].numLoops) ||
+        (views[chinf->view].loops[chinf->loop].numFrames < 1) ||
+        (hasUpDownLoops(chinf) == 0)) {
+            // Character is not currently on a valid loop, so don't try to rotate
+            // eg. left/right only view, but current loop 0
+            chinf->loop = useloop;
+            return;
+    }
+    const int no_diagonal = useDiagonal (chinf);
+    start_character_turning (chinf, useloop, no_diagonal);
+}
+
+// Check whether two characters have walked into each other
+int has_hit_another_character(int sourceChar) {
+
+    // if the character who's moving doesn't Bitmap *, don't bother checking
+    if (game.chars[sourceChar].flags & CHF_NOBLOCKING)
+        return -1;
+
+    for (int ww = 0; ww < game.numcharacters; ww++) {
+        if (game.chars[ww].on != 1) continue;
+        if (game.chars[ww].room != displayed_room) continue;
+        if (ww == sourceChar) continue;
+        if (game.chars[ww].flags & CHF_NOBLOCKING) continue;
+
+        if (is_char_on_another (sourceChar, ww, nullptr, nullptr)) {
+            // we are now overlapping character 'ww'
+            if ((game.chars[ww].walking) && 
+                ((game.chars[ww].flags & CHF_AWAITINGMOVE) == 0))
+                return ww;
+        }
+
+    }
+    return -1;
+}
+
+// Does the next move from the character's movelist.
+// Returns 1 if they are now waiting for another char to move,
+// otherwise returns 0
+int doNextCharMoveStep (CharacterInfo *chi, int &char_index, CharacterExtras *chex) {
+    int ntf=0, xwas = chi->x, ywas = chi->y;
+
+    if (do_movelist_move(&chi->walking,&chi->x,&chi->y) == 2) 
+    {
+        if ((chi->flags & CHF_MOVENOTWALK) == 0)
+            fix_player_sprite(&mls[chi->walking], chi);
+    }
+
+    ntf = has_hit_another_character(char_index);
+    if (ntf >= 0) {
+        chi->walkwait = 30;
+        if (game.chars[ntf].walkspeed < 5)
+            chi->walkwait += (5 - game.chars[ntf].walkspeed) * 5;
+        // we are now waiting for the other char to move, so
+        // make sure he doesn't stop for us too
+
+        chi->flags |= CHF_AWAITINGMOVE;
+
+        if ((chi->flags & CHF_MOVENOTWALK) == 0)
+        {
+            chi->frame = 0;
+            chex->animwait = chi->walkwait;
+        }
+
+        if ((chi->walking < 1) || (chi->walking >= TURNING_AROUND)) ;
+        else if (mls[chi->walking].onpart > 0) {
+            mls[chi->walking].onpart --;
+            chi->x = xwas;
+            chi->y = ywas;
+        }
+        debug_script_log("%s: Bumped into %s, waiting for them to move", chi->scrname, game.chars[ntf].scrname);
+        return 1;
+    }
+    return 0;
+}
+
+int find_nearest_walkable_area_within(int *xx, int *yy, int range, int step)
+{
+    int ex, ey, nearest = 99999, thisis, nearx = 0, neary = 0;
+    int startx = 0, starty = 14;
+    int roomWidthLowRes = room_to_mask_coord(thisroom.Width);
+    int roomHeightLowRes = room_to_mask_coord(thisroom.Height);
+    int xwidth = roomWidthLowRes, yheight = roomHeightLowRes;
+
+    int xLowRes = room_to_mask_coord(xx[0]);
+    int yLowRes = room_to_mask_coord(yy[0]);
+    int rightEdge = room_to_mask_coord(thisroom.Edges.Right);
+    int leftEdge = room_to_mask_coord(thisroom.Edges.Left);
+    int topEdge = room_to_mask_coord(thisroom.Edges.Top);
+    int bottomEdge = room_to_mask_coord(thisroom.Edges.Bottom);
+
+    // tweak because people forget to move the edges sometimes
+    // if the player is already over the edge, ignore it
+    if (xLowRes >= rightEdge) rightEdge = roomWidthLowRes;
+    if (xLowRes <= leftEdge) leftEdge = 0;
+    if (yLowRes >= bottomEdge) bottomEdge = roomHeightLowRes;
+    if (yLowRes <= topEdge) topEdge = 0;
+
+    if (range > 0) 
+    {
+        startx = xLowRes - range;
+        starty = yLowRes - range;
+        xwidth = startx + range * 2;
+        yheight = starty + range * 2;
+        if (startx < 0) startx = 0;
+        if (starty < 10) starty = 10;
+        if (xwidth > roomWidthLowRes) xwidth = roomWidthLowRes;
+        if (yheight > roomHeightLowRes) yheight = roomHeightLowRes;
+    }
+
+    for (ex = startx; ex < xwidth; ex += step) {
+        for (ey = starty; ey < yheight; ey += step) {
+            // non-walkalbe, so don't go here
+            if (thisroom.WalkAreaMask->GetPixel(ex,ey) == 0) continue;
+            // off a screen edge, don't move them there
+            if ((ex <= leftEdge) || (ex >= rightEdge) ||
+                (ey <= topEdge) || (ey >= bottomEdge))
+                continue;
+            // otherwise, calculate distance from target
+            thisis=(int) ::sqrt((double)((ex - xLowRes) * (ex - xLowRes) + (ey - yLowRes) * (ey - yLowRes)));
+            if (thisis<nearest) { nearest=thisis; nearx=ex; neary=ey; }
+        }
+    }
+    if (nearest < 90000) 
+    {
+        xx[0] = mask_to_room_coord(nearx);
+        yy[0] = mask_to_room_coord(neary);
+        return 1;
+    }
+
+    return 0;
+}
+
+void find_nearest_walkable_area (int *xx, int *yy) {
+
+    int pixValue = thisroom.WalkAreaMask->GetPixel(room_to_mask_coord(xx[0]), room_to_mask_coord(yy[0]));
+    // only fix this code if the game was built with 2.61 or above
+    if (pixValue == 0 || (loaded_game_file_version >= kGameVersion_261 && pixValue < 1))
+    {
+        // First, check every 2 pixels within immediate area
+        if (!find_nearest_walkable_area_within(xx, yy, 20, 2))
+        {
+            // If not, check whole screen at 5 pixel intervals
+            find_nearest_walkable_area_within(xx, yy, -1, 5);
+        }
+    }
+
+}
+
+void FindReasonableLoopForCharacter(CharacterInfo *chap) {
+
+    if (chap->loop >= views[chap->view].numLoops)
+        chap->loop=kDirLoop_Default;
+    if (views[chap->view].numLoops < 1)
+        quitprintf("!View %d does not have any loops", chap->view + 1);
+
+    // if the current loop has no frames, find one that does
+    if (views[chap->view].loops[chap->loop].numFrames < 1) 
+    {
+        for (int i = 0; i < views[chap->view].numLoops; i++) 
+        {
+            if (views[chap->view].loops[i].numFrames > 0) {
+                chap->loop = i;
+                break;
+            }
+        }
+    }
+
+}
+
+void walk_or_move_character(CharacterInfo *chaa, int x, int y, int blocking, int direct, bool isWalk)
+{
+    if (chaa->on != 1)
+    {
+        debug_script_warn("MoveCharacterBlocking: character is turned off and cannot be moved");
+        return;
+    }
+
+    if ((direct == ANYWHERE) || (direct == 1))
+        walk_character(chaa->index_id, x, y, 1, isWalk);
+    else if ((direct == WALKABLE_AREAS) || (direct == 0))
+        walk_character(chaa->index_id, x, y, 0, isWalk);
+    else
+        quit("!Character.Walk: Direct must be ANYWHERE or WALKABLE_AREAS");
+
+    if ((blocking == BLOCKING) || (blocking == 1))
+        GameLoopUntilNotMoving(&chaa->walking);
+    else if ((blocking != IN_BACKGROUND) && (blocking != 0))
+        quit("!Character.Walk: Blocking must be BLOCKING or IN_BACKGRUOND");
+
+}
+
+int is_valid_character(int newchar) {
+    if ((newchar < 0) || (newchar >= game.numcharacters)) return 0;
+    return 1;
+}
+
+int wantMoveNow (CharacterInfo *chi, CharacterExtras *chex) {
+    // check most likely case first
+    if ((chex->zoom == 100) || ((chi->flags & CHF_SCALEMOVESPEED) == 0))
+        return 1;
+
+    // the % checks don't work when the counter is negative, so once
+    // it wraps round, correct it
+    while (chi->walkwaitcounter < 0) {
+        chi->walkwaitcounter += 12000;
+    }
+
+    // scaling 170-200%, move 175% speed
+    if (chex->zoom >= 170) {
+        if ((chi->walkwaitcounter % 4) >= 1)
+            return 2;
+        else
+            return 1;
+    }
+    // scaling 140-170%, move 150% speed
+    else if (chex->zoom >= 140) {
+        if ((chi->walkwaitcounter % 2) == 1)
+            return 2;
+        else
+            return 1;
+    }
+    // scaling 115-140%, move 125% speed
+    else if (chex->zoom >= 115) {
+        if ((chi->walkwaitcounter % 4) >= 3)
+            return 2;
+        else
+            return 1;
+    }
+    // scaling 80-120%, normal speed
+    else if (chex->zoom >= 80)
+        return 1;
+    // scaling 60-80%, move 75% speed
+    if (chex->zoom >= 60) {
+        if ((chi->walkwaitcounter % 4) >= 1)
+            return -1;
+        else if (chex->xwas != INVALID_X) {
+            // move the second half of the movement to make it smoother
+            chi->x = chex->xwas;
+            chi->y = chex->ywas;
+            chex->xwas = INVALID_X;
+        }
+    }
+    // scaling 30-60%, move 50% speed
+    else if (chex->zoom >= 30) {
+        if ((chi->walkwaitcounter % 2) == 1)
+            return -1;
+        else if (chex->xwas != INVALID_X) {
+            // move the second half of the movement to make it smoother
+            chi->x = chex->xwas;
+            chi->y = chex->ywas;
+            chex->xwas = INVALID_X;
+        }
+    }
+    // scaling 0-30%, move 25% speed
+    else {
+        if ((chi->walkwaitcounter % 4) >= 3)
+            return -1;
+        if (((chi->walkwaitcounter % 4) == 1) && (chex->xwas != INVALID_X)) {
+            // move the second half of the movement to make it smoother
+            chi->x = chex->xwas;
+            chi->y = chex->ywas;
+            chex->xwas = INVALID_X;
+        }
+
+    }
+
+    return 0;
+}
+
+void setup_player_character(int charid) {
+    game.playercharacter = charid;
+    playerchar = &game.chars[charid];
+    _sc_PlayerCharPtr = ccGetObjectHandleFromAddress((char*)playerchar);
+    if (loaded_game_file_version < kGameVersion_270) {
+        ccAddExternalDynamicObject("player", playerchar, &ccDynamicCharacter);
+    }
+}
+
+void animate_character(CharacterInfo *chap, int loopn,int sppd,int rept, int noidleoverride, int direction, int sframe) {
+
+    if ((chap->view < 0) || (chap->view > game.numviews)) {
+        quitprintf("!AnimateCharacter: you need to set the view number first\n"
+            "(trying to animate '%s' using loop %d. View is currently %d).",chap->name,loopn,chap->view+1);
+    }
+    debug_script_log("%s: Start anim view %d loop %d, spd %d, repeat %d, frame: %d", chap->scrname, chap->view+1, loopn, sppd, rept, sframe);
+    if ((chap->idleleft < 0) && (noidleoverride == 0)) {
+        // if idle view in progress for the character (and this is not the
+        // "start idle animation" animate_character call), stop the idle anim
+        Character_UnlockView(chap);
+        chap->idleleft=chap->idletime;
+    }
+    if ((loopn < 0) || (loopn >= views[chap->view].numLoops))
+        quit("!AnimateCharacter: invalid loop number specified");
+    if ((sframe < 0) || (sframe >= views[chap->view].loops[loopn].numFrames))
+        quit("!AnimateCharacter: invalid starting frame number specified");
+    Character_StopMoving(chap);
+    chap->animating=1;
+    if (rept) chap->animating |= CHANIM_REPEAT;
+    if (direction) chap->animating |= CHANIM_BACKWARDS;
+
+    chap->animating|=((sppd << 8) & 0xff00);
+    chap->loop=loopn;
+    // reverse animation starts at the *previous frame*
+    if (direction) {
+        sframe--;
+        if (sframe < 0)
+            sframe = views[chap->view].loops[loopn].numFrames - (-sframe);
+    }
+    chap->frame = sframe;
+
+    chap->wait = sppd + views[chap->view].loops[loopn].frames[chap->frame].speed;
+    CheckViewFrameForCharacter(chap);
+}
+
+void CheckViewFrameForCharacter(CharacterInfo *chi) {
+
+    int soundVolume = SCR_NO_VALUE;
+
+    if (chi->flags & CHF_SCALEVOLUME) {
+        // adjust the sound volume using the character's zoom level
+        int zoom_level = charextra[chi->index_id].zoom;
+        if (zoom_level == 0)
+            zoom_level = 100;
+
+        soundVolume = zoom_level;
+
+        if (soundVolume < 0)
+            soundVolume = 0;
+        if (soundVolume > 100)
+            soundVolume = 100;
+    }
+
+    CheckViewFrame(chi->view, chi->loop, chi->frame, soundVolume);
+}
+
+Bitmap *GetCharacterImage(int charid, int *isFlipped) 
+{
+    if (!gfxDriver->HasAcceleratedTransform())
+    {
+        if (actsps[charid + MAX_ROOM_OBJECTS] != nullptr) 
+        {
+            // the actsps image is pre-flipped, so no longer register the image as such
+            if (isFlipped)
+                *isFlipped = 0;
+            return actsps[charid + MAX_ROOM_OBJECTS];
+        }
+    }
+    CharacterInfo*chin=&game.chars[charid];
+    int sppic = views[chin->view].loops[chin->loop].frames[chin->frame].pic;
+    return spriteset[sppic];
+}
+
+CharacterInfo *GetCharacterAtScreen(int xx, int yy) {
+    int hsnum = GetCharIDAtScreen(xx, yy);
+    if (hsnum < 0)
+        return nullptr;
+    return &game.chars[hsnum];
+}
+
+CharacterInfo *GetCharacterAtRoom(int x, int y)
+{
+    int hsnum = is_pos_on_character(x, y);
+    if (hsnum < 0)
+        return nullptr;
+    return &game.chars[hsnum];
+}
+
+extern int char_lowest_yp, obj_lowest_yp;
+
+int is_pos_on_character(int xx,int yy) {
+    int cc,sppic,lowestyp=0,lowestwas=-1;
+    for (cc=0;cc<game.numcharacters;cc++) {
+        if (game.chars[cc].room!=displayed_room) continue;
+        if (game.chars[cc].on==0) continue;
+        if (game.chars[cc].flags & CHF_NOINTERACT) continue;
+        if (game.chars[cc].view < 0) continue;
+        CharacterInfo*chin=&game.chars[cc];
+
+        if ((chin->view < 0) || 
+            (chin->loop >= views[chin->view].numLoops) ||
+            (chin->frame >= views[chin->view].loops[chin->loop].numFrames))
+        {
+            continue;
+        }
+
+        sppic=views[chin->view].loops[chin->loop].frames[chin->frame].pic;
+        int usewid = charextra[cc].width;
+        int usehit = charextra[cc].height;
+        if (usewid==0) usewid=game.SpriteInfos[sppic].Width;
+        if (usehit==0) usehit= game.SpriteInfos[sppic].Height;
+        int xxx = chin->x - game_to_data_coord(usewid) / 2;
+        int yyy = chin->get_effective_y() - game_to_data_coord(usehit);
+
+        int mirrored = views[chin->view].loops[chin->loop].frames[chin->frame].flags & VFLG_FLIPSPRITE;
+        Bitmap *theImage = GetCharacterImage(cc, &mirrored);
+
+        if (is_pos_in_sprite(xx,yy,xxx,yyy, theImage,
+            game_to_data_coord(usewid),
+            game_to_data_coord(usehit), mirrored) == FALSE)
+            continue;
+
+        int use_base = chin->get_baseline();
+        if (use_base < lowestyp) continue;
+        lowestyp=use_base;
+        lowestwas=cc;
+    }
+    char_lowest_yp = lowestyp;
+    return lowestwas;
+}
+
+void get_char_blocking_rect(int charid, int *x1, int *y1, int *width, int *y2) {
+    CharacterInfo *char1 = &game.chars[charid];
+    int cwidth, fromx;
+
+    if (char1->blocking_width < 1)
+        cwidth = game_to_data_coord(GetCharacterWidth(charid)) - 4;
+    else
+        cwidth = char1->blocking_width;
+
+    fromx = char1->x - cwidth/2;
+    if (fromx < 0) {
+        cwidth += fromx;
+        fromx = 0;
+    }
+    if (fromx + cwidth >= mask_to_room_coord(walkable_areas_temp->GetWidth()))
+        cwidth = mask_to_room_coord(walkable_areas_temp->GetWidth()) - fromx;
+
+    if (x1)
+        *x1 = fromx;
+    if (width)
+        *width = cwidth;
+    if (y1)
+        *y1 = char1->get_blocking_top();
+    if (y2)
+        *y2 = char1->get_blocking_bottom();
+}
+
+// Check whether the source char has walked onto character ww
+int is_char_on_another (int sourceChar, int ww, int*fromxptr, int*cwidptr) {
+
+    int fromx, cwidth;
+    int y1, y2;
+    get_char_blocking_rect(ww, &fromx, &y1, &cwidth, &y2);
+
+    if (fromxptr)
+        fromxptr[0] = fromx;
+    if (cwidptr)
+        cwidptr[0] = cwidth;
+
+    // if the character trying to move is already on top of
+    // this char somehow, allow them through
+    if ((sourceChar >= 0) &&
+        // x/width are left and width co-ords, so they need >= and <
+        (game.chars[sourceChar].x >= fromx) &&
+        (game.chars[sourceChar].x < fromx + cwidth) &&
+        // y1/y2 are the top/bottom co-ords, so they need >= / <=
+        (game.chars[sourceChar].y >= y1 ) &&
+        (game.chars[sourceChar].y <= y2 ))
+        return 1;
+
+    return 0;
+}
+
+int my_getpixel(Bitmap *blk, int x, int y) {
+    if ((x < 0) || (y < 0) || (x >= blk->GetWidth()) || (y >= blk->GetHeight()))
+        return -1;
+
+    // strip the alpha channel
+	// TODO: is there a way to do this vtable thing with Bitmap?
+	BITMAP *al_bmp = (BITMAP*)blk->GetAllegroBitmap();
+    return al_bmp->vtable->getpixel(al_bmp, x, y) & 0x00ffffff;
+}
+
+int check_click_on_character(int xx,int yy,int mood) {
+    int lowestwas=is_pos_on_character(xx,yy);
+    if (lowestwas>=0) {
+        RunCharacterInteraction (lowestwas, mood);
+        return 1;
+    }
+    return 0;
+}
+
+void _DisplaySpeechCore(int chid, const char *displbuf) {
+    if (displbuf[0] == 0) {
+        // no text, just update the current character who's speaking
+        // this allows the portrait side to be switched with an empty
+        // speech line
+        play.swap_portrait_lastchar = chid;
+        return;
+    }
+
+    // adjust timing of text (so that DisplaySpeech("%s", str) pauses
+    // for the length of the string not 2 frames)
+    int len = (int)strlen(displbuf);
+    if (len > source_text_length + 3)
+        source_text_length = len;
+
+    DisplaySpeech(displbuf, chid);
+}
+
+void _DisplayThoughtCore(int chid, const char *displbuf) {
+    // adjust timing of text (so that DisplayThought("%s", str) pauses
+    // for the length of the string not 2 frames)
+    int len = (int)strlen(displbuf);
+    if (len > source_text_length + 3)
+        source_text_length = len;
+
+    int xpp = -1, ypp = -1, width = -1;
+
+    if ((game.options[OPT_SPEECHTYPE] == 0) || (game.chars[chid].thinkview <= 0)) {
+        // lucasarts-style, so we want a speech bubble actually above
+        // their head (or if they have no think anim in Sierra-style)
+        width = data_to_game_coord(play.speech_bubble_width);
+        xpp = play.RoomToScreenX(data_to_game_coord(game.chars[chid].x)) - width / 2;
+        if (xpp < 0)
+            xpp = 0;
+        // -1 will automatically put it above the char's head
+        ypp = -1;
+    }
+
+    _displayspeech ((char*)displbuf, chid, xpp, ypp, width, 1);
+}
+
+void _displayspeech(const char*texx, int aschar, int xx, int yy, int widd, int isThought) {
+    if (!is_valid_character(aschar))
+        quit("!DisplaySpeech: invalid character");
+
+    CharacterInfo *speakingChar = &game.chars[aschar];
+    if ((speakingChar->view < 0) || (speakingChar->view >= game.numviews))
+        quit("!DisplaySpeech: character has invalid view");
+
+    if (is_text_overlay > 0)
+    {
+        debug_script_warn("DisplaySpeech: speech was already displayed (nested DisplaySpeech, perhaps room script and global script conflict?)");
+        return;
+    }
+
+    EndSkippingUntilCharStops();
+
+    said_speech_line = 1;
+
+    if (play.bgspeech_stay_on_display == 0) {
+        // remove any background speech
+        for (size_t i = 0; i < screenover.size();) {
+            if (screenover[i].timeout > 0)
+                remove_screen_overlay(screenover[i].type);
+            else
+                i++;
+        }
+    }
+    said_text = 1;
+
+    // the strings are pre-translated
+    //texx = get_translation(texx);
+    our_eip=150;
+
+    int isPause = 1;
+    // if the message is all .'s, don't display anything
+    for (int aa = 0; texx[aa] != 0; aa++) {
+        if (texx[aa] != '.') {
+            isPause = 0;
+            break;
+        }
+    }
+
+    play.messagetime = GetTextDisplayTime(texx);
+    play.speech_in_post_state = false;
+
+    if (isPause) {
+        postpone_scheduled_music_update_by(std::chrono::milliseconds(play.messagetime * 1000 / frames_per_second));
+        GameLoopUntilValueIsNegative(&play.messagetime);
+        return;
+    }
+
+    int textcol = speakingChar->talkcolor;
+
+    // if it's 0, it won't be recognised as speech
+    if (textcol == 0)
+        textcol = 16;
+
+    Rect ui_view = play.GetUIViewport();
+    int allowShrink = 0;
+    int bwidth = widd;
+    if (bwidth < 0)
+        bwidth = ui_view.GetWidth()/2 + ui_view.GetWidth()/4;
+
+    our_eip=151;
+
+    int useview = speakingChar->talkview;
+    if (isThought) {
+        useview = speakingChar->thinkview;
+        // view 0 is not valid for think views
+        if (useview == 0)
+            useview = -1;
+        // speech bubble can shrink to fit
+        allowShrink = 1;
+        if (speakingChar->room != displayed_room) {
+            // not in room, centre it
+            xx = -1;
+            yy = -1;
+        }
+    }
+
+    if (useview >= game.numviews)
+        quitprintf("!Character.Say: attempted to use view %d for animation, but it does not exist", useview + 1);
+
+    int tdxp = xx,tdyp = yy;
+    int oldview=-1, oldloop = -1;
+    int ovr_type = 0;
+
+    text_lips_offset = 0;
+    text_lips_text = texx;
+
+    Bitmap *closeupface=nullptr;
+    // TODO: we always call _display_at later which may also start voice-over;
+    // find out if this may be refactored and voice started only in one place.
+    try_auto_play_speech(texx, texx, aschar, true);
+
+    if (game.options[OPT_SPEECHTYPE] == 3)
+        remove_screen_overlay(OVER_COMPLETE);
+    our_eip=1500;
+
+    if (game.options[OPT_SPEECHTYPE] == 0)
+        allowShrink = 1;
+
+    if (speakingChar->idleleft < 0)  {
+        // if idle anim in progress for the character, stop it
+        ReleaseCharacterView(aschar);
+        //    speakingChar->idleleft = speakingChar->idletime;
+    }
+
+    bool overlayPositionFixed = false;
+    int charFrameWas = 0;
+    int viewWasLocked = 0;
+    if (speakingChar->flags & CHF_FIXVIEW)
+        viewWasLocked = 1;
+
+    /*if ((speakingChar->room == displayed_room) ||
+    ((useview >= 0) && (game.options[OPT_SPEECHTYPE] > 0)) ) {*/
+
+    if (speakingChar->room == displayed_room) {
+        // If the character is in this room, go for it - otherwise
+        // run the "else" clause which  does text in the middle of
+        // the screen.
+        our_eip=1501;
+
+        if (speakingChar->walking)
+            StopMoving(aschar);
+
+        // save the frame we need to go back to
+        // if they were moving, this will be 0 (because we just called
+        // StopMoving); otherwise, it might be a specific animation 
+        // frame which we should return to
+        if (viewWasLocked)
+            charFrameWas = speakingChar->frame;
+
+        // if the current loop doesn't exist in talking view, use loop 0
+        if (speakingChar->loop >= views[speakingChar->view].numLoops)
+            speakingChar->loop = 0;
+
+        if ((speakingChar->view < 0) || 
+            (speakingChar->loop >= views[speakingChar->view].numLoops) ||
+            (views[speakingChar->view].loops[speakingChar->loop].numFrames < 1))
+        {
+            quitprintf("Unable to display speech because the character %s has an invalid view frame (View %d, loop %d, frame %d)", speakingChar->scrname, speakingChar->view + 1, speakingChar->loop, speakingChar->frame);
+        }
+
+        our_eip=1504;
+
+        // Calculate speech position based on character's position on screen
+        auto view = FindNearestViewport(aschar);
+        if (tdxp < 0)
+            tdxp = view->RoomToScreen(data_to_game_coord(speakingChar->x), 0).first.X;
+        if (tdxp < 2)
+            tdxp = 2;
+        tdxp = -tdxp;  // tell it to centre it ([ikm] not sure what's going on here... wrong comment?)
+
+        if (tdyp < 0)
+        {
+            int sppic = views[speakingChar->view].loops[speakingChar->loop].frames[0].pic;
+            int height = (charextra[aschar].height < 1) ? game.SpriteInfos[sppic].Height : height = charextra[aschar].height;
+            tdyp = view->RoomToScreen(0, data_to_game_coord(game.chars[aschar].get_effective_y()) - height).first.Y
+                    - get_fixed_pixel_size(5);
+            if (isThought) // if it's a thought, lift it a bit further up
+                tdyp -= get_fixed_pixel_size(10);
+        }
+        if (tdyp < 5)
+            tdyp = 5;
+
+        our_eip=152;
+
+        if ((useview >= 0) && (game.options[OPT_SPEECHTYPE] > 0)) {
+            // Sierra-style close-up portrait
+
+            if (play.swap_portrait_lastchar != aschar) {
+                // if the portraits are set to Alternate, OR they are
+                // set to Left but swap_portrait has been set to 1 (the old
+                // method for enabling it), then swap them round
+                if ((game.options[OPT_PORTRAITSIDE] == PORTRAIT_ALTERNATE) ||
+                    ((game.options[OPT_PORTRAITSIDE] == 0) &&
+                    (play.swap_portrait_side > 0))) {
+
+                        if (play.swap_portrait_side == 2)
+                            play.swap_portrait_side = 1;
+                        else
+                            play.swap_portrait_side = 2;
+                }
+
+                if (game.options[OPT_PORTRAITSIDE] == PORTRAIT_XPOSITION) {
+                    // Portrait side based on character X-positions
+                    if (play.swap_portrait_lastchar < 0) {
+                        // No previous character been spoken to
+                        // therefore, assume it's the player
+                        if(game.playercharacter != aschar && game.chars[game.playercharacter].room == speakingChar->room && game.chars[game.playercharacter].on == 1)
+                            play.swap_portrait_lastchar = game.playercharacter;
+                        else
+                            // The player's not here. Find another character in this room
+                            // that it could be
+                            for (int ce = 0; ce < game.numcharacters; ce++) {
+                                if ((game.chars[ce].room == speakingChar->room) &&
+                                    (game.chars[ce].on == 1) &&
+                                    (ce != aschar)) {
+                                        play.swap_portrait_lastchar = ce;
+                                        break;
+                                }
+                            }
+                    }
+
+                    if (play.swap_portrait_lastchar >= 0) {
+                        // if this character is right of the one before, put the
+                        // portrait on the right
+                        if (speakingChar->x > game.chars[play.swap_portrait_lastchar].x)
+                            play.swap_portrait_side = -1;
+                        else
+                            play.swap_portrait_side = 0;
+                    }
+                }
+                play.swap_portrait_lastlastchar = play.swap_portrait_lastchar;
+                play.swap_portrait_lastchar = aschar;
+            }
+            else
+                // If the portrait side is based on the character's X position and the same character is
+                // speaking, compare against the previous *previous* character to see where the speech should be
+                if (game.options[OPT_PORTRAITSIDE] == PORTRAIT_XPOSITION && play.swap_portrait_lastlastchar >= 0) {
+                    if (speakingChar->x > game.chars[play.swap_portrait_lastlastchar].x)
+                        play.swap_portrait_side = -1;
+                    else
+                        play.swap_portrait_side = 0;
+                }
+
+            // Determine whether to display the portrait on the left or right
+            int portrait_on_right = 0;
+
+            if (game.options[OPT_SPEECHTYPE] == 3) 
+            { }  // always on left with QFG-style speech
+            else if ((play.swap_portrait_side == 1) ||
+                (play.swap_portrait_side == -1) ||
+                (game.options[OPT_PORTRAITSIDE] == PORTRAIT_RIGHT))
+                portrait_on_right = 1;
+
+
+            int bigx=0,bigy=0,kk;
+            ViewStruct*viptr=&views[useview];
+            for (kk = 0; kk < viptr->loops[0].numFrames; kk++) 
+            {
+                int tw = game.SpriteInfos[viptr->loops[0].frames[kk].pic].Width;
+                if (tw > bigx) bigx=tw;
+                tw = game.SpriteInfos[viptr->loops[0].frames[kk].pic].Height;
+                if (tw > bigy) bigy=tw;
+            }
+
+            // if they accidentally used a large full-screen image as the sierra-style
+            // talk view, correct it
+            if ((game.options[OPT_SPEECHTYPE] != 3) && (bigx > ui_view.GetWidth() - get_fixed_pixel_size(50)))
+                bigx = ui_view.GetWidth() - get_fixed_pixel_size(50);
+
+            if (widd > 0)
+                bwidth = widd - bigx;
+
+            our_eip=153;
+            int ovr_yp = get_fixed_pixel_size(20);
+            int view_frame_x = 0;
+            int view_frame_y = 0;
+            facetalk_qfg4_override_placement_x = false;
+            facetalk_qfg4_override_placement_y = false;
+
+            if (game.options[OPT_SPEECHTYPE] == 3) {
+                // QFG4-style whole screen picture
+                closeupface = BitmapHelper::CreateBitmap(ui_view.GetWidth(), ui_view.GetHeight(), spriteset[viptr->loops[0].frames[0].pic]->GetColorDepth());
+                closeupface->Clear(0);
+                if (xx < 0 && play.speech_portrait_placement)
+                {
+                    facetalk_qfg4_override_placement_x = true;
+                    view_frame_x = play.speech_portrait_x;
+                }
+                if (yy < 0 && play.speech_portrait_placement)
+                {
+                    facetalk_qfg4_override_placement_y = true;
+                    view_frame_y = play.speech_portrait_y;
+                }
+                else
+                {
+                    view_frame_y = ui_view.GetHeight()/2 - game.SpriteInfos[viptr->loops[0].frames[0].pic].Height/2;
+                }
+                bigx = ui_view.GetWidth()/2 - get_fixed_pixel_size(20);
+                ovr_type = OVER_COMPLETE;
+                ovr_yp = 0;
+                tdyp = -1;  // center vertically
+            }
+            else {
+                // KQ6-style close-up face picture
+                if (yy < 0 && play.speech_portrait_placement)
+                {
+                    ovr_yp = play.speech_portrait_y;
+                }
+                else if (yy < 0)
+                    ovr_yp = adjust_y_for_guis (ovr_yp);
+                else
+                    ovr_yp = yy;
+
+                closeupface = BitmapHelper::CreateTransparentBitmap(bigx+1,bigy+1,spriteset[viptr->loops[0].frames[0].pic]->GetColorDepth());
+                ovr_type = OVER_PICTURE;
+
+                if (yy < 0)
+                    tdyp = ovr_yp + get_textwindow_top_border_height(play.speech_textwindow_gui);
+            }
+            const ViewFrame *vf = &viptr->loops[0].frames[0];
+            const bool closeupface_has_alpha = (game.SpriteInfos[vf->pic].Flags & SPF_ALPHACHANNEL) != 0;
+            DrawViewFrame(closeupface, vf, view_frame_x, view_frame_y);
+
+            int overlay_x = get_fixed_pixel_size(10);
+            if (xx < 0) {
+                tdxp = bigx + get_textwindow_border_width(play.speech_textwindow_gui) / 2;
+                if (play.speech_portrait_placement)
+                {
+                    overlay_x = play.speech_portrait_x;
+                    tdxp += overlay_x + get_fixed_pixel_size(6);
+                }
+                else
+                {
+                    tdxp += get_fixed_pixel_size(16);
+                }
+
+                int maxWidth = (ui_view.GetWidth() - tdxp) - get_fixed_pixel_size(5) -
+                    get_textwindow_border_width (play.speech_textwindow_gui) / 2;
+
+                if (bwidth > maxWidth)
+                    bwidth = maxWidth;
+            }
+            else {
+                tdxp = xx + bigx + get_fixed_pixel_size(8);
+                overlay_x = xx;
+            }
+
+            // allow the text box to be shrunk to fit the text
+            allowShrink = 1;
+
+            // if the portrait's on the right, swap it round
+            if (portrait_on_right) {
+                if ((xx < 0) || (widd < 0)) {
+                    tdxp = get_fixed_pixel_size(9);
+                    if (play.speech_portrait_placement)
+                    {
+                        overlay_x = (ui_view.GetWidth() - bigx) - play.speech_portrait_x;
+                        int maxWidth = overlay_x - tdxp - get_fixed_pixel_size(9) - 
+                            get_textwindow_border_width (play.speech_textwindow_gui) / 2;
+                        if (bwidth > maxWidth)
+                            bwidth = maxWidth;
+                    }
+                    else
+                    {
+                        overlay_x = (ui_view.GetWidth() - bigx) - get_fixed_pixel_size(5);
+                    }
+                }
+                else {
+                    overlay_x = (xx + widd - bigx) - get_fixed_pixel_size(5);
+                    tdxp = xx;
+                }
+                tdxp += get_textwindow_border_width(play.speech_textwindow_gui) / 2;
+                allowShrink = 2;
+            }
+            if (game.options[OPT_SPEECHTYPE] == 3)
+                overlay_x = 0;
+            face_talking=add_screen_overlay(overlay_x,ovr_yp,ovr_type,closeupface, closeupface_has_alpha);
+            facetalkframe = 0;
+            facetalkwait = viptr->loops[0].frames[0].speed + GetCharacterSpeechAnimationDelay(speakingChar);
+            facetalkloop = 0;
+            facetalkview = useview;
+            facetalkrepeat = (isThought) ? 0 : 1;
+            facetalkBlinkLoop = 0;
+            facetalkAllowBlink = 1;
+            if ((isThought) && (speakingChar->flags & CHF_NOBLINKANDTHINK))
+                facetalkAllowBlink = 0;
+            facetalkchar = &game.chars[aschar];
+            if (facetalkchar->blinktimer < 0)
+                facetalkchar->blinktimer = facetalkchar->blinkinterval;
+            textcol=-textcol;
+            overlayPositionFixed = true;
+        }
+        else if (useview >= 0) {
+            // Lucasarts-style speech
+            our_eip=154;
+
+            oldview = speakingChar->view;
+            oldloop = speakingChar->loop;
+            speakingChar->animating = 1 | (GetCharacterSpeechAnimationDelay(speakingChar) << 8);
+            // only repeat if speech, not thought
+            if (!isThought)
+                speakingChar->animating |= CHANIM_REPEAT;
+
+            speakingChar->view = useview;
+            speakingChar->frame=0;
+            speakingChar->flags|=CHF_FIXVIEW;
+
+            if (speakingChar->loop >= views[speakingChar->view].numLoops)
+            {
+                // current character loop is outside the normal talking directions
+                speakingChar->loop = 0;
+            }
+
+            facetalkBlinkLoop = speakingChar->loop;
+
+            if (speakingChar->on && // don't bother checking if character is not visible (also fixes 'Trilby's Notes' legacy game)
+                ((speakingChar->loop >= views[speakingChar->view].numLoops) ||
+                (views[speakingChar->view].loops[speakingChar->loop].numFrames < 1)))
+            {
+                quitprintf("!Unable to display speech because the character %s has an invalid speech view (View %d, loop %d, frame %d)", speakingChar->scrname, speakingChar->view + 1, speakingChar->loop, speakingChar->frame);
+            }
+
+            // set up the speed of the first frame
+            speakingChar->wait = GetCharacterSpeechAnimationDelay(speakingChar) + 
+                views[speakingChar->view].loops[speakingChar->loop].frames[0].speed;
+
+            if (widd < 0) {
+                bwidth = ui_view.GetWidth()/2 + ui_view.GetWidth()/6;
+                // If they are close to the screen edge, make the text narrower
+                int relx = play.RoomToScreenX(data_to_game_coord(speakingChar->x));
+                if ((relx < ui_view.GetWidth() / 4) || (relx > ui_view.GetWidth() - (ui_view.GetWidth() / 4)))
+                    bwidth -= ui_view.GetWidth() / 5;
+            }
+            /*   this causes the text to bob up and down as they talk
+            tdxp = OVR_AUTOPLACE;
+            tdyp = aschar;*/
+            if (!isThought)  // set up the lip sync if not thinking
+                char_speaking = aschar;
+
+        }
+    }
+    else
+        allowShrink = 1;
+
+    // it wants the centred position, so make it so
+    if ((xx >= 0) && (tdxp < 0))
+        tdxp -= widd / 2;
+
+    // if they used DisplaySpeechAt, then use the supplied width
+    if ((widd > 0) && (isThought == 0))
+        allowShrink = 0;
+
+    if (isThought)
+        char_thinking = aschar;
+
+    our_eip=155;
+    _display_at(tdxp, tdyp, bwidth, texx, DISPLAYTEXT_SPEECH, textcol, isThought, allowShrink, overlayPositionFixed);
+    our_eip=156;
+    if ((play.in_conversation > 0) && (game.options[OPT_SPEECHTYPE] == 3))
+        closeupface = nullptr;
+    if (closeupface!=nullptr)
+        remove_screen_overlay(ovr_type);
+    mark_screen_dirty();
+    face_talking = -1;
+    facetalkchar = nullptr;
+    our_eip=157;
+    if (oldview>=0) {
+        speakingChar->flags &= ~CHF_FIXVIEW;
+        if (viewWasLocked)
+            speakingChar->flags |= CHF_FIXVIEW;
+        speakingChar->view=oldview;
+
+        // Don't reset the loop in 2.x games
+        if (loaded_game_file_version > kGameVersion_272)
+            speakingChar->loop = oldloop;
+
+        speakingChar->animating=0;
+        speakingChar->frame = charFrameWas;
+        speakingChar->wait=0;
+        speakingChar->idleleft = speakingChar->idletime;
+        // restart the idle animation straight away
+        charextra[aschar].process_idle_this_time = 1;
+    }
+    char_speaking = -1;
+    char_thinking = -1;
+    if (play.IsBlockingVoiceSpeech())
+        stop_voice_speech();
+}
+
+int get_character_currently_talking() {
+    if ((face_talking >= 0) && (facetalkrepeat))
+        return facetalkchar->index_id;
+    else if (char_speaking >= 0)
+        return char_speaking;
+
+    return -1;
+}
+
+void DisplaySpeech(const char*texx, int aschar) {
+    _displayspeech (texx, aschar, -1, -1, -1, 0);
+}
+
+// Calculate which frame of the loop to use for this character of
+// speech
+int GetLipSyncFrame (const char *curtex, int *stroffs) {
+    /*char *frameletters[MAXLIPSYNCFRAMES] =
+    {"./,/ ", "A", "O", "F/V", "D/N/G/L/R", "B/P/M",
+    "Y/H/K/Q/C", "I/T/E/X/th", "U/W", "S/Z/J/ch", NULL,
+    NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL};*/
+
+    int bestfit_len = 0, bestfit = game.default_lipsync_frame;
+    for (int aa = 0; aa < MAXLIPSYNCFRAMES; aa++) {
+        char *tptr = game.lipSyncFrameLetters[aa];
+        while (tptr[0] != 0) {
+            int lenthisbit = strlen(tptr);
+            if (strchr(tptr, '/'))
+                lenthisbit = strchr(tptr, '/') - tptr;
+
+            if ((ags_strnicmp (curtex, tptr, lenthisbit) == 0) && (lenthisbit > bestfit_len)) {
+                bestfit = aa;
+                bestfit_len = lenthisbit;
+            }
+            tptr += lenthisbit;
+            while (tptr[0] == '/')
+                tptr++;
+        }
+    }
+    // If it's an unknown character, use the default frame
+    if (bestfit_len == 0)
+        bestfit_len = 1;
+    *stroffs += bestfit_len;
+    return bestfit;
+}
+
+int update_lip_sync(int talkview, int talkloop, int *talkframeptr) {
+    int talkframe = talkframeptr[0];
+    int talkwait = 0;
+
+    // lip-sync speech
+    const char *nowsaying = &text_lips_text[text_lips_offset];
+    // if it's an apostraphe, skip it (we'll, I'll, etc)
+    if (nowsaying[0] == '\'') {
+        text_lips_offset++;
+        nowsaying++;
+    }
+
+    if (text_lips_offset >= (int)strlen(text_lips_text))
+        talkframe = 0;
+    else {
+        talkframe = GetLipSyncFrame (nowsaying, &text_lips_offset);
+        if (talkframe >= views[talkview].loops[talkloop].numFrames)
+            talkframe = 0;
+    }
+
+    talkwait = loops_per_character + views[talkview].loops[talkloop].frames[talkframe].speed;
+
+    talkframeptr[0] = talkframe;
+    return talkwait;
+}
+
+Rect GetCharacterRoomBBox(int charid, bool use_frame_0)
+{
+    int width, height;
+    const CharacterExtras& chex = charextra[charid];
+    const CharacterInfo& chin = game.chars[charid];
+    int frame = use_frame_0 ? 0 : chin.frame;
+    int pic = views[chin.view].loops[chin.loop].frames[frame].pic;
+    scale_sprite_size(pic, chex.zoom, &width, &height);
+    return RectWH(chin.x - width / 2, chin.y - height, width, height);
+}
+
+PViewport FindNearestViewport(int charid)
+{
+    Rect bbox = GetCharacterRoomBBox(charid, true);
+    float min_dist = -1.f;
+    PViewport nearest_view;
+    for (int i = 0; i < play.GetRoomViewportCount(); ++i)
+    {
+        auto view = play.GetRoomViewport(i);
+        if (!view->IsVisible())
+            continue;
+        auto cam = view->GetCamera();
+        if (!cam)
+            continue;
+        Rect camr = cam->GetRect();
+        float dist = DistanceBetween(bbox, camr);
+        if (dist == 0.f)
+            return view;
+        if (min_dist < 0.f || dist < min_dist)
+        {
+            min_dist = dist;
+            nearest_view = view;
+        }
+    }
+    return nearest_view ? nearest_view : play.GetRoomViewport(0);
+}
+
+//=============================================================================
+//
+// Script API Functions
+//
+//=============================================================================
+
+#include "debug/out.h"
+#include "script/script_api.h"
+#include "script/script_runtime.h"
+#include "ac/dynobj/scriptstring.h"
+
+extern ScriptString myScriptStringImpl;
+
+// void | CharacterInfo *chaa, ScriptInvItem *invi, int addIndex
+RuntimeScriptValue Sc_Character_AddInventory(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_POBJ_PINT(CharacterInfo, Character_AddInventory, ScriptInvItem);
+}
+
+// void | CharacterInfo *chaa, int x, int y
+RuntimeScriptValue Sc_Character_AddWaypoint(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT2(CharacterInfo, Character_AddWaypoint);
+}
+
+// void | CharacterInfo *chaa, int loop, int delay, int repeat, int blocking, int direction
+RuntimeScriptValue Sc_Character_Animate(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT5(CharacterInfo, Character_Animate);
+}
+
+RuntimeScriptValue Sc_Character_AnimateFrom(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT6(CharacterInfo, Character_AnimateFrom);
+}
+
+// void | CharacterInfo *chaa, int room, int x, int y
+RuntimeScriptValue Sc_Character_ChangeRoom(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT3(CharacterInfo, Character_ChangeRoom);
+}
+
+RuntimeScriptValue Sc_Character_ChangeRoomSetLoop(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT4(CharacterInfo, Character_ChangeRoomSetLoop);
+}
+
+// void | CharacterInfo *chaa, int room, int newPos
+RuntimeScriptValue Sc_Character_ChangeRoomAutoPosition(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT2(CharacterInfo, Character_ChangeRoomAutoPosition);
+}
+
+// void | CharacterInfo *chap, int vii
+RuntimeScriptValue Sc_Character_ChangeView(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_ChangeView);
+}
+
+// void | CharacterInfo *char1, CharacterInfo *char2, int blockingStyle
+RuntimeScriptValue Sc_Character_FaceCharacter(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_POBJ_PINT(CharacterInfo, Character_FaceCharacter, CharacterInfo);
+}
+
+// void | CharacterInfo *char1, int direction, int blockingStyle
+RuntimeScriptValue Sc_Character_FaceDirection(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT2(CharacterInfo, Character_FaceDirection);
+}
+
+// void | CharacterInfo *char1, int xx, int yy, int blockingStyle
+RuntimeScriptValue Sc_Character_FaceLocation(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT3(CharacterInfo, Character_FaceLocation);
+}
+
+// void | CharacterInfo *char1, ScriptObject *obj, int blockingStyle
+RuntimeScriptValue Sc_Character_FaceObject(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_POBJ_PINT(CharacterInfo, Character_FaceObject, ScriptObject);
+}
+
+// void | CharacterInfo *chaa, CharacterInfo *tofollow, int distaway, int eagerness
+RuntimeScriptValue Sc_Character_FollowCharacter(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_POBJ_PINT2(CharacterInfo, Character_FollowCharacter, CharacterInfo);
+}
+
+// int (CharacterInfo *chaa, const char *property)
+RuntimeScriptValue Sc_Character_GetProperty(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT_POBJ(CharacterInfo, Character_GetProperty, const char);
+}
+
+// void (CharacterInfo *chaa, const char *property, char *bufer)
+RuntimeScriptValue Sc_Character_GetPropertyText(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_POBJ2(CharacterInfo, Character_GetPropertyText, const char, char);
+}
+
+// const char* (CharacterInfo *chaa, const char *property)
+RuntimeScriptValue Sc_Character_GetTextProperty(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_OBJ_POBJ(CharacterInfo, const char, myScriptStringImpl, Character_GetTextProperty, const char);
+}
+
+RuntimeScriptValue Sc_Character_SetProperty(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_BOOL_POBJ_PINT(CharacterInfo, Character_SetProperty, const char);
+}
+
+RuntimeScriptValue Sc_Character_SetTextProperty(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_BOOL_POBJ2(CharacterInfo, Character_SetTextProperty, const char, const char);
+}
+
+// int (CharacterInfo *chaa, ScriptInvItem *invi)
+RuntimeScriptValue Sc_Character_HasInventory(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT_POBJ(CharacterInfo, Character_HasInventory, ScriptInvItem);
+}
+
+// int (CharacterInfo *char1, CharacterInfo *char2)
+RuntimeScriptValue Sc_Character_IsCollidingWithChar(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT_POBJ(CharacterInfo, Character_IsCollidingWithChar, CharacterInfo);
+}
+
+// int (CharacterInfo *chin, ScriptObject *objid)
+RuntimeScriptValue Sc_Character_IsCollidingWithObject(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT_POBJ(CharacterInfo, Character_IsCollidingWithObject, ScriptObject);
+}
+
+RuntimeScriptValue Sc_Character_IsInteractionAvailable(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_BOOL_PINT(CharacterInfo, Character_IsInteractionAvailable);
+}
+
+// void (CharacterInfo *chap, int vii)
+RuntimeScriptValue Sc_Character_LockView(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_LockView);
+}
+
+// void (CharacterInfo *chap, int vii, int stopMoving)
+RuntimeScriptValue Sc_Character_LockViewEx(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT2(CharacterInfo, Character_LockViewEx);
+}
+
+// void (CharacterInfo *chap, int vii, int loop, int align)
+RuntimeScriptValue Sc_Character_LockViewAligned_Old(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT3(CharacterInfo, Character_LockViewAligned_Old);
+}
+
+// void (CharacterInfo *chap, int vii, int loop, int align, int stopMoving)
+RuntimeScriptValue Sc_Character_LockViewAlignedEx_Old(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT4(CharacterInfo, Character_LockViewAlignedEx_Old);
+}
+
+RuntimeScriptValue Sc_Character_LockViewAligned(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT3(CharacterInfo, Character_LockViewAligned);
+}
+
+RuntimeScriptValue Sc_Character_LockViewAlignedEx(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT4(CharacterInfo, Character_LockViewAlignedEx);
+}
+
+// void (CharacterInfo *chaa, int view, int loop, int frame)
+RuntimeScriptValue Sc_Character_LockViewFrame(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT3(CharacterInfo, Character_LockViewFrame);
+}
+
+// void (CharacterInfo *chaa, int view, int loop, int frame, int stopMoving)
+RuntimeScriptValue Sc_Character_LockViewFrameEx(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT4(CharacterInfo, Character_LockViewFrameEx);
+}
+
+// void (CharacterInfo *chap, int vii, int xoffs, int yoffs)
+RuntimeScriptValue Sc_Character_LockViewOffset(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT3(CharacterInfo, Character_LockViewOffset);
+}
+
+// void (CharacterInfo *chap, int vii, int xoffs, int yoffs, int stopMoving)
+RuntimeScriptValue Sc_Character_LockViewOffsetEx(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT4(CharacterInfo, Character_LockViewOffsetEx);
+}
+
+// void (CharacterInfo *chap, ScriptInvItem *invi)
+RuntimeScriptValue Sc_Character_LoseInventory(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_POBJ(CharacterInfo, Character_LoseInventory, ScriptInvItem);
+}
+
+// void (CharacterInfo *chaa, int x, int y, int blocking, int direct) 
+RuntimeScriptValue Sc_Character_Move(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT4(CharacterInfo, Character_Move);
+}
+
+// void (CharacterInfo *chap) 
+RuntimeScriptValue Sc_Character_PlaceOnWalkableArea(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID(CharacterInfo, Character_PlaceOnWalkableArea);
+}
+
+// void (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_RemoveTint(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID(CharacterInfo, Character_RemoveTint);
+}
+
+// void (CharacterInfo *chaa, int mood)
+RuntimeScriptValue Sc_Character_RunInteraction(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_RunInteraction);
+}
+
+// void (CharacterInfo *chaa, const char *texx, ...)
+RuntimeScriptValue Sc_Character_Say(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_SCRIPT_SPRINTF(Character_Say, 1);
+    Character_Say((CharacterInfo*)self, scsf_buffer);
+    return RuntimeScriptValue((int32_t)0);
+}
+
+// void (CharacterInfo *chaa, int x, int y, int width, const char *texx)
+RuntimeScriptValue Sc_Character_SayAt(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT3_POBJ(CharacterInfo, Character_SayAt, const char);
+}
+
+// ScriptOverlay* (CharacterInfo *chaa, const char *texx)
+RuntimeScriptValue Sc_Character_SayBackground(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_OBJAUTO_POBJ(CharacterInfo, ScriptOverlay, Character_SayBackground, const char);
+}
+
+// void (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_SetAsPlayer(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID(CharacterInfo, Character_SetAsPlayer);
+}
+
+// void (CharacterInfo *chaa, int iview, int itime)
+RuntimeScriptValue Sc_Character_SetIdleView(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT2(CharacterInfo, Character_SetIdleView);
+}
+
+RuntimeScriptValue Sc_Character_HasExplicitLight(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_BOOL(CharacterInfo, Character_GetHasExplicitLight);
+}
+
+RuntimeScriptValue Sc_Character_GetLightLevel(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetLightLevel);
+}
+
+RuntimeScriptValue Sc_Character_SetLightLevel(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetLightLevel);
+}
+
+RuntimeScriptValue Sc_Character_GetTintBlue(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetTintBlue);
+}
+
+RuntimeScriptValue Sc_Character_GetTintGreen(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetTintGreen);
+}
+
+RuntimeScriptValue Sc_Character_GetTintRed(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetTintRed);
+}
+
+RuntimeScriptValue Sc_Character_GetTintSaturation(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetTintSaturation);
+}
+
+RuntimeScriptValue Sc_Character_GetTintLuminance(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetTintLuminance);
+}
+
+/*
+RuntimeScriptValue Sc_Character_SetOption(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+}
+*/
+
+// void (CharacterInfo *chaa, int xspeed, int yspeed)
+RuntimeScriptValue Sc_Character_SetSpeed(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT2(CharacterInfo, Character_SetSpeed);
+}
+
+// void (CharacterInfo *charp)
+RuntimeScriptValue Sc_Character_StopMoving(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID(CharacterInfo, Character_StopMoving);
+}
+
+// void (CharacterInfo *chaa, const char *texx, ...)
+RuntimeScriptValue Sc_Character_Think(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_SCRIPT_SPRINTF(Character_Think, 1);
+    Character_Think((CharacterInfo*)self, scsf_buffer);
+    return RuntimeScriptValue((int32_t)0);
+}
+
+//void (CharacterInfo *chaa, int red, int green, int blue, int opacity, int luminance)
+RuntimeScriptValue Sc_Character_Tint(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT5(CharacterInfo, Character_Tint);
+}
+
+// void (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_UnlockView(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID(CharacterInfo, Character_UnlockView);
+}
+
+// void (CharacterInfo *chaa, int stopMoving)
+RuntimeScriptValue Sc_Character_UnlockViewEx(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_UnlockViewEx);
+}
+
+// void (CharacterInfo *chaa, int x, int y, int blocking, int direct)
+RuntimeScriptValue Sc_Character_Walk(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT4(CharacterInfo, Character_Walk);
+}
+
+// void (CharacterInfo *chaa, int xx, int yy, int blocking)
+RuntimeScriptValue Sc_Character_WalkStraight(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT3(CharacterInfo, Character_WalkStraight);
+}
+
+RuntimeScriptValue Sc_GetCharacterAtRoom(const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_SCALL_OBJ_PINT2(CharacterInfo, ccDynamicCharacter, GetCharacterAtRoom);
+}
+
+// CharacterInfo *(int xx, int yy)
+RuntimeScriptValue Sc_GetCharacterAtScreen(const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_SCALL_OBJ_PINT2(CharacterInfo, ccDynamicCharacter, GetCharacterAtScreen);
+}
+
+// ScriptInvItem* (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetActiveInventory(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_OBJ(CharacterInfo, ScriptInvItem, ccDynamicInv, Character_GetActiveInventory);
+}
+
+// void (CharacterInfo *chaa, ScriptInvItem* iit)
+RuntimeScriptValue Sc_Character_SetActiveInventory(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_POBJ(CharacterInfo, Character_SetActiveInventory, ScriptInvItem);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetAnimating(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetAnimating);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetAnimationSpeed(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetAnimationSpeed);
+}
+
+// void (CharacterInfo *chaa, int newval)
+RuntimeScriptValue Sc_Character_SetAnimationSpeed(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetAnimationSpeed);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetBaseline(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetBaseline);
+}
+
+// void (CharacterInfo *chaa, int basel)
+RuntimeScriptValue Sc_Character_SetBaseline(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetBaseline);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetBlinkInterval(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetBlinkInterval);
+}
+
+// void (CharacterInfo *chaa, int interval)
+RuntimeScriptValue Sc_Character_SetBlinkInterval(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetBlinkInterval);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetBlinkView(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetBlinkView);
+}
+
+// void (CharacterInfo *chaa, int vii)
+RuntimeScriptValue Sc_Character_SetBlinkView(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetBlinkView);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetBlinkWhileThinking(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetBlinkWhileThinking);
+}
+
+// void (CharacterInfo *chaa, int yesOrNo)
+RuntimeScriptValue Sc_Character_SetBlinkWhileThinking(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetBlinkWhileThinking);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetBlockingHeight(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetBlockingHeight);
+}
+
+// void (CharacterInfo *chaa, int hit)
+RuntimeScriptValue Sc_Character_SetBlockingHeight(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetBlockingHeight);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetBlockingWidth(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetBlockingWidth);
+}
+
+// void (CharacterInfo *chaa, int wid)
+RuntimeScriptValue Sc_Character_SetBlockingWidth(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetBlockingWidth);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetClickable(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetClickable);
+}
+
+// void (CharacterInfo *chaa, int clik)
+RuntimeScriptValue Sc_Character_SetClickable(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetClickable);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetDiagonalWalking(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetDiagonalWalking);
+}
+
+// void (CharacterInfo *chaa, int yesorno)
+RuntimeScriptValue Sc_Character_SetDiagonalWalking(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetDiagonalWalking);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetFrame(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetFrame);
+}
+
+// void (CharacterInfo *chaa, int newval)
+RuntimeScriptValue Sc_Character_SetFrame(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetFrame);
+}
+
+RuntimeScriptValue Sc_Character_GetHasExplicitTint_Old(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetHasExplicitTint_Old);
+}
+
+RuntimeScriptValue Sc_Character_GetHasExplicitTint(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetHasExplicitTint);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetID(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetID);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetIdleView(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetIdleView);
+}
+
+// int (CharacterInfo *chaa, int index)
+RuntimeScriptValue Sc_Character_GetIInventoryQuantity(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT_PINT(CharacterInfo, Character_GetIInventoryQuantity);
+}
+
+// void (CharacterInfo *chaa, int index, int quant)
+RuntimeScriptValue Sc_Character_SetIInventoryQuantity(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT2(CharacterInfo, Character_SetIInventoryQuantity);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetIgnoreLighting(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetIgnoreLighting);
+}
+
+// void (CharacterInfo *chaa, int yesorno)
+RuntimeScriptValue Sc_Character_SetIgnoreLighting(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetIgnoreLighting);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetIgnoreScaling(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetIgnoreScaling);
+}
+
+// void (CharacterInfo *chaa, int yesorno)
+RuntimeScriptValue Sc_Character_SetIgnoreScaling(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetIgnoreScaling);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetIgnoreWalkbehinds(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetIgnoreWalkbehinds);
+}
+
+// void (CharacterInfo *chaa, int yesorno)
+RuntimeScriptValue Sc_Character_SetIgnoreWalkbehinds(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetIgnoreWalkbehinds);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetLoop(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetLoop);
+}
+
+// void (CharacterInfo *chaa, int newval)
+RuntimeScriptValue Sc_Character_SetLoop(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetLoop);
+}
+
+// void (CharacterInfo *chaa, int yesorno)
+RuntimeScriptValue Sc_Character_SetManualScaling(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetManualScaling);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetMovementLinkedToAnimation(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetMovementLinkedToAnimation);
+}
+
+// void (CharacterInfo *chaa, int yesorno)
+RuntimeScriptValue Sc_Character_SetMovementLinkedToAnimation(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetMovementLinkedToAnimation);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetMoving(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetMoving);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetDestinationX(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetDestinationX);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetDestinationY(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetDestinationY);
+}
+
+// const char* (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetName(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_OBJ(CharacterInfo, const char, myScriptStringImpl, Character_GetName);
+}
+
+// void (CharacterInfo *chaa, const char *newName)
+RuntimeScriptValue Sc_Character_SetName(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_POBJ(CharacterInfo, Character_SetName, const char);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetNormalView(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetNormalView);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetPreviousRoom(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetPreviousRoom);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetRoom(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetRoom);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetScaleMoveSpeed(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetScaleMoveSpeed);
+}
+
+// void (CharacterInfo *chaa, int yesorno)
+RuntimeScriptValue Sc_Character_SetScaleMoveSpeed(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetScaleMoveSpeed);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetScaleVolume(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetScaleVolume);
+}
+
+// void (CharacterInfo *chaa, int yesorno)
+RuntimeScriptValue Sc_Character_SetScaleVolume(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetScaleVolume);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetScaling(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetScaling);
+}
+
+// void (CharacterInfo *chaa, int zoomlevel)
+RuntimeScriptValue Sc_Character_SetScaling(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetScaling);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetSolid(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetSolid);
+}
+
+// void (CharacterInfo *chaa, int yesorno)
+RuntimeScriptValue Sc_Character_SetSolid(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetSolid);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetSpeaking(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetSpeaking);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetSpeakingFrame(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetSpeakingFrame);
+}
+
+// int (CharacterInfo *cha)
+RuntimeScriptValue Sc_GetCharacterSpeechAnimationDelay(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, GetCharacterSpeechAnimationDelay);
+}
+
+// void (CharacterInfo *chaa, int newDelay)
+RuntimeScriptValue Sc_Character_SetSpeechAnimationDelay(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetSpeechAnimationDelay);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetSpeechColor(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetSpeechColor);
+}
+
+// void (CharacterInfo *chaa, int ncol)
+RuntimeScriptValue Sc_Character_SetSpeechColor(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetSpeechColor);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetSpeechView(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetSpeechView);
+}
+
+// void (CharacterInfo *chaa, int vii)
+RuntimeScriptValue Sc_Character_SetSpeechView(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetSpeechView);
+}
+
+RuntimeScriptValue Sc_Character_GetThinking(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_BOOL(CharacterInfo, Character_GetThinking);
+}
+
+RuntimeScriptValue Sc_Character_GetThinkingFrame(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetThinkingFrame);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetThinkView(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetThinkView);
+}
+
+// void (CharacterInfo *chaa, int vii)
+RuntimeScriptValue Sc_Character_SetThinkView(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetThinkView);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetTransparency(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetTransparency);
+}
+
+// void (CharacterInfo *chaa, int trans)
+RuntimeScriptValue Sc_Character_SetTransparency(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetTransparency);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetTurnBeforeWalking(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetTurnBeforeWalking);
+}
+
+// void (CharacterInfo *chaa, int yesorno)
+RuntimeScriptValue Sc_Character_SetTurnBeforeWalking(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetTurnBeforeWalking);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetView(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetView);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetWalkSpeedX(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetWalkSpeedX);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetWalkSpeedY(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetWalkSpeedY);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetX(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetX);
+}
+
+// void (CharacterInfo *chaa, int newval)
+RuntimeScriptValue Sc_Character_SetX(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetX);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetY(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetY);
+}
+
+// void (CharacterInfo *chaa, int newval)
+RuntimeScriptValue Sc_Character_SetY(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetY);
+}
+
+// int (CharacterInfo *chaa)
+RuntimeScriptValue Sc_Character_GetZ(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(CharacterInfo, Character_GetZ);
+}
+
+// void (CharacterInfo *chaa, int newval)
+RuntimeScriptValue Sc_Character_SetZ(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetZ);
+}
+
+//=============================================================================
+//
+// Exclusive API for Plugins
+//
+//=============================================================================
+
+// void (CharacterInfo *chaa, const char *texx, ...)
+void ScPl_Character_Say(CharacterInfo *chaa, const char *texx, ...)
+{
+    API_PLUGIN_SCRIPT_SPRINTF(texx);
+    Character_Say(chaa, scsf_buffer);
+}
+
+// void (CharacterInfo *chaa, const char *texx, ...)
+void ScPl_Character_Think(CharacterInfo *chaa, const char *texx, ...)
+{
+    API_PLUGIN_SCRIPT_SPRINTF(texx);
+    Character_Think(chaa, scsf_buffer);
+}
+
+void RegisterCharacterAPI(ScriptAPIVersion base_api, ScriptAPIVersion compat_api)
+{
+    ccAddExternalObjectFunction("Character::AddInventory^2",            Sc_Character_AddInventory);
+	ccAddExternalObjectFunction("Character::AddWaypoint^2",             Sc_Character_AddWaypoint);
+	ccAddExternalObjectFunction("Character::Animate^5",                 Sc_Character_Animate);
+    ccAddExternalObjectFunction("Character::Animate^6",                 Sc_Character_AnimateFrom);
+	ccAddExternalObjectFunction("Character::ChangeRoom^3",              Sc_Character_ChangeRoom);
+    ccAddExternalObjectFunction("Character::ChangeRoom^4",              Sc_Character_ChangeRoomSetLoop);
+	ccAddExternalObjectFunction("Character::ChangeRoomAutoPosition^2",  Sc_Character_ChangeRoomAutoPosition);
+	ccAddExternalObjectFunction("Character::ChangeView^1",              Sc_Character_ChangeView);
+	ccAddExternalObjectFunction("Character::FaceCharacter^2",           Sc_Character_FaceCharacter);
+	ccAddExternalObjectFunction("Character::FaceDirection^2",           Sc_Character_FaceDirection);
+	ccAddExternalObjectFunction("Character::FaceLocation^3",            Sc_Character_FaceLocation);
+	ccAddExternalObjectFunction("Character::FaceObject^2",              Sc_Character_FaceObject);
+	ccAddExternalObjectFunction("Character::FollowCharacter^3",         Sc_Character_FollowCharacter);
+	ccAddExternalObjectFunction("Character::GetProperty^1",             Sc_Character_GetProperty);
+	ccAddExternalObjectFunction("Character::GetPropertyText^2",         Sc_Character_GetPropertyText);
+	ccAddExternalObjectFunction("Character::GetTextProperty^1",         Sc_Character_GetTextProperty);
+    ccAddExternalObjectFunction("Character::SetProperty^2",             Sc_Character_SetProperty);
+    ccAddExternalObjectFunction("Character::SetTextProperty^2",         Sc_Character_SetTextProperty);
+	ccAddExternalObjectFunction("Character::HasInventory^1",            Sc_Character_HasInventory);
+	ccAddExternalObjectFunction("Character::IsCollidingWithChar^1",     Sc_Character_IsCollidingWithChar);
+	ccAddExternalObjectFunction("Character::IsCollidingWithObject^1",   Sc_Character_IsCollidingWithObject);
+    ccAddExternalObjectFunction("Character::IsInteractionAvailable^1",  Sc_Character_IsInteractionAvailable);
+	ccAddExternalObjectFunction("Character::LockView^1",                Sc_Character_LockView);
+	ccAddExternalObjectFunction("Character::LockView^2",                Sc_Character_LockViewEx);
+    if (base_api < kScriptAPI_v350)
+    {
+        ccAddExternalObjectFunction("Character::LockViewAligned^3", Sc_Character_LockViewAligned_Old);
+        ccAddExternalObjectFunction("Character::LockViewAligned^4", Sc_Character_LockViewAlignedEx_Old);
+    }
+    else
+    {
+        ccAddExternalObjectFunction("Character::LockViewAligned^3", Sc_Character_LockViewAligned);
+        ccAddExternalObjectFunction("Character::LockViewAligned^4", Sc_Character_LockViewAlignedEx);
+    }
+	ccAddExternalObjectFunction("Character::LockViewFrame^3",           Sc_Character_LockViewFrame);
+	ccAddExternalObjectFunction("Character::LockViewFrame^4",           Sc_Character_LockViewFrameEx);
+	ccAddExternalObjectFunction("Character::LockViewOffset^3",          Sc_Character_LockViewOffset);
+	ccAddExternalObjectFunction("Character::LockViewOffset^4",          Sc_Character_LockViewOffsetEx);
+	ccAddExternalObjectFunction("Character::LoseInventory^1",           Sc_Character_LoseInventory);
+	ccAddExternalObjectFunction("Character::Move^4",                    Sc_Character_Move);
+	ccAddExternalObjectFunction("Character::PlaceOnWalkableArea^0",     Sc_Character_PlaceOnWalkableArea);
+	ccAddExternalObjectFunction("Character::RemoveTint^0",              Sc_Character_RemoveTint);
+	ccAddExternalObjectFunction("Character::RunInteraction^1",          Sc_Character_RunInteraction);
+	ccAddExternalObjectFunction("Character::Say^101",                   Sc_Character_Say);
+	ccAddExternalObjectFunction("Character::SayAt^4",                   Sc_Character_SayAt);
+	ccAddExternalObjectFunction("Character::SayBackground^1",           Sc_Character_SayBackground);
+	ccAddExternalObjectFunction("Character::SetAsPlayer^0",             Sc_Character_SetAsPlayer);
+	ccAddExternalObjectFunction("Character::SetIdleView^2",             Sc_Character_SetIdleView);
+    ccAddExternalObjectFunction("Character::SetLightLevel^1",           Sc_Character_SetLightLevel);
+	//ccAddExternalObjectFunction("Character::SetOption^2",             Sc_Character_SetOption);
+	ccAddExternalObjectFunction("Character::SetWalkSpeed^2",            Sc_Character_SetSpeed);
+	ccAddExternalObjectFunction("Character::StopMoving^0",              Sc_Character_StopMoving);
+	ccAddExternalObjectFunction("Character::Think^101",                 Sc_Character_Think);
+	ccAddExternalObjectFunction("Character::Tint^5",                    Sc_Character_Tint);
+	ccAddExternalObjectFunction("Character::UnlockView^0",              Sc_Character_UnlockView);
+	ccAddExternalObjectFunction("Character::UnlockView^1",              Sc_Character_UnlockViewEx);
+	ccAddExternalObjectFunction("Character::Walk^4",                    Sc_Character_Walk);
+	ccAddExternalObjectFunction("Character::WalkStraight^3",            Sc_Character_WalkStraight);
+
+    ccAddExternalStaticFunction("Character::GetAtRoomXY^2",             Sc_GetCharacterAtRoom);
+	ccAddExternalStaticFunction("Character::GetAtScreenXY^2",           Sc_GetCharacterAtScreen);
+
+	ccAddExternalObjectFunction("Character::get_ActiveInventory",       Sc_Character_GetActiveInventory);
+	ccAddExternalObjectFunction("Character::set_ActiveInventory",       Sc_Character_SetActiveInventory);
+	ccAddExternalObjectFunction("Character::get_Animating",             Sc_Character_GetAnimating);
+	ccAddExternalObjectFunction("Character::get_AnimationSpeed",        Sc_Character_GetAnimationSpeed);
+	ccAddExternalObjectFunction("Character::set_AnimationSpeed",        Sc_Character_SetAnimationSpeed);
+	ccAddExternalObjectFunction("Character::get_Baseline",              Sc_Character_GetBaseline);
+	ccAddExternalObjectFunction("Character::set_Baseline",              Sc_Character_SetBaseline);
+	ccAddExternalObjectFunction("Character::get_BlinkInterval",         Sc_Character_GetBlinkInterval);
+	ccAddExternalObjectFunction("Character::set_BlinkInterval",         Sc_Character_SetBlinkInterval);
+	ccAddExternalObjectFunction("Character::get_BlinkView",             Sc_Character_GetBlinkView);
+	ccAddExternalObjectFunction("Character::set_BlinkView",             Sc_Character_SetBlinkView);
+	ccAddExternalObjectFunction("Character::get_BlinkWhileThinking",    Sc_Character_GetBlinkWhileThinking);
+	ccAddExternalObjectFunction("Character::set_BlinkWhileThinking",    Sc_Character_SetBlinkWhileThinking);
+	ccAddExternalObjectFunction("Character::get_BlockingHeight",        Sc_Character_GetBlockingHeight);
+	ccAddExternalObjectFunction("Character::set_BlockingHeight",        Sc_Character_SetBlockingHeight);
+	ccAddExternalObjectFunction("Character::get_BlockingWidth",         Sc_Character_GetBlockingWidth);
+	ccAddExternalObjectFunction("Character::set_BlockingWidth",         Sc_Character_SetBlockingWidth);
+	ccAddExternalObjectFunction("Character::get_Clickable",             Sc_Character_GetClickable);
+	ccAddExternalObjectFunction("Character::set_Clickable",             Sc_Character_SetClickable);
+	ccAddExternalObjectFunction("Character::get_DestinationX",          Sc_Character_GetDestinationX);
+	ccAddExternalObjectFunction("Character::get_DestinationY",          Sc_Character_GetDestinationY);
+	ccAddExternalObjectFunction("Character::get_DiagonalLoops",         Sc_Character_GetDiagonalWalking);
+	ccAddExternalObjectFunction("Character::set_DiagonalLoops",         Sc_Character_SetDiagonalWalking);
+	ccAddExternalObjectFunction("Character::get_Frame",                 Sc_Character_GetFrame);
+	ccAddExternalObjectFunction("Character::set_Frame",                 Sc_Character_SetFrame);
+    if (base_api < kScriptAPI_v341)
+        ccAddExternalObjectFunction("Character::get_HasExplicitTint",       Sc_Character_GetHasExplicitTint_Old);
+    else
+	    ccAddExternalObjectFunction("Character::get_HasExplicitTint",       Sc_Character_GetHasExplicitTint);
+	ccAddExternalObjectFunction("Character::get_ID",                    Sc_Character_GetID);
+	ccAddExternalObjectFunction("Character::get_IdleView",              Sc_Character_GetIdleView);
+	ccAddExternalObjectFunction("Character::geti_InventoryQuantity",    Sc_Character_GetIInventoryQuantity);
+	ccAddExternalObjectFunction("Character::seti_InventoryQuantity",    Sc_Character_SetIInventoryQuantity);
+	ccAddExternalObjectFunction("Character::get_IgnoreLighting",        Sc_Character_GetIgnoreLighting);
+	ccAddExternalObjectFunction("Character::set_IgnoreLighting",        Sc_Character_SetIgnoreLighting);
+	ccAddExternalObjectFunction("Character::get_IgnoreScaling",         Sc_Character_GetIgnoreScaling);
+	ccAddExternalObjectFunction("Character::set_IgnoreScaling",         Sc_Character_SetIgnoreScaling);
+	ccAddExternalObjectFunction("Character::get_IgnoreWalkbehinds",     Sc_Character_GetIgnoreWalkbehinds);
+	ccAddExternalObjectFunction("Character::set_IgnoreWalkbehinds",     Sc_Character_SetIgnoreWalkbehinds);
+	ccAddExternalObjectFunction("Character::get_Loop",                  Sc_Character_GetLoop);
+	ccAddExternalObjectFunction("Character::set_Loop",                  Sc_Character_SetLoop);
+	ccAddExternalObjectFunction("Character::get_ManualScaling",         Sc_Character_GetIgnoreScaling);
+	ccAddExternalObjectFunction("Character::set_ManualScaling",         Sc_Character_SetManualScaling);
+	ccAddExternalObjectFunction("Character::get_MovementLinkedToAnimation",Sc_Character_GetMovementLinkedToAnimation);
+	ccAddExternalObjectFunction("Character::set_MovementLinkedToAnimation",Sc_Character_SetMovementLinkedToAnimation);
+	ccAddExternalObjectFunction("Character::get_Moving",                Sc_Character_GetMoving);
+	ccAddExternalObjectFunction("Character::get_Name",                  Sc_Character_GetName);
+	ccAddExternalObjectFunction("Character::set_Name",                  Sc_Character_SetName);
+	ccAddExternalObjectFunction("Character::get_NormalView",            Sc_Character_GetNormalView);
+	ccAddExternalObjectFunction("Character::get_PreviousRoom",          Sc_Character_GetPreviousRoom);
+	ccAddExternalObjectFunction("Character::get_Room",                  Sc_Character_GetRoom);
+	ccAddExternalObjectFunction("Character::get_ScaleMoveSpeed",        Sc_Character_GetScaleMoveSpeed);
+	ccAddExternalObjectFunction("Character::set_ScaleMoveSpeed",        Sc_Character_SetScaleMoveSpeed);
+	ccAddExternalObjectFunction("Character::get_ScaleVolume",           Sc_Character_GetScaleVolume);
+	ccAddExternalObjectFunction("Character::set_ScaleVolume",           Sc_Character_SetScaleVolume);
+	ccAddExternalObjectFunction("Character::get_Scaling",               Sc_Character_GetScaling);
+	ccAddExternalObjectFunction("Character::set_Scaling",               Sc_Character_SetScaling);
+	ccAddExternalObjectFunction("Character::get_Solid",                 Sc_Character_GetSolid);
+	ccAddExternalObjectFunction("Character::set_Solid",                 Sc_Character_SetSolid);
+	ccAddExternalObjectFunction("Character::get_Speaking",              Sc_Character_GetSpeaking);
+	ccAddExternalObjectFunction("Character::get_SpeakingFrame",         Sc_Character_GetSpeakingFrame);
+	ccAddExternalObjectFunction("Character::get_SpeechAnimationDelay",  Sc_GetCharacterSpeechAnimationDelay);
+	ccAddExternalObjectFunction("Character::set_SpeechAnimationDelay",  Sc_Character_SetSpeechAnimationDelay);
+	ccAddExternalObjectFunction("Character::get_SpeechColor",           Sc_Character_GetSpeechColor);
+	ccAddExternalObjectFunction("Character::set_SpeechColor",           Sc_Character_SetSpeechColor);
+	ccAddExternalObjectFunction("Character::get_SpeechView",            Sc_Character_GetSpeechView);
+	ccAddExternalObjectFunction("Character::set_SpeechView",            Sc_Character_SetSpeechView);
+    ccAddExternalObjectFunction("Character::get_Thinking",              Sc_Character_GetThinking);
+    ccAddExternalObjectFunction("Character::get_ThinkingFrame",         Sc_Character_GetThinkingFrame);
+	ccAddExternalObjectFunction("Character::get_ThinkView",             Sc_Character_GetThinkView);
+	ccAddExternalObjectFunction("Character::set_ThinkView",             Sc_Character_SetThinkView);
+	ccAddExternalObjectFunction("Character::get_Transparency",          Sc_Character_GetTransparency);
+	ccAddExternalObjectFunction("Character::set_Transparency",          Sc_Character_SetTransparency);
+	ccAddExternalObjectFunction("Character::get_TurnBeforeWalking",     Sc_Character_GetTurnBeforeWalking);
+	ccAddExternalObjectFunction("Character::set_TurnBeforeWalking",     Sc_Character_SetTurnBeforeWalking);
+	ccAddExternalObjectFunction("Character::get_View",                  Sc_Character_GetView);
+	ccAddExternalObjectFunction("Character::get_WalkSpeedX",            Sc_Character_GetWalkSpeedX);
+	ccAddExternalObjectFunction("Character::get_WalkSpeedY",            Sc_Character_GetWalkSpeedY);
+	ccAddExternalObjectFunction("Character::get_X",                     Sc_Character_GetX);
+	ccAddExternalObjectFunction("Character::set_X",                     Sc_Character_SetX);
+	ccAddExternalObjectFunction("Character::get_x",                     Sc_Character_GetX);
+	ccAddExternalObjectFunction("Character::set_x",                     Sc_Character_SetX);
+	ccAddExternalObjectFunction("Character::get_Y",                     Sc_Character_GetY);
+	ccAddExternalObjectFunction("Character::set_Y",                     Sc_Character_SetY);
+	ccAddExternalObjectFunction("Character::get_y",                     Sc_Character_GetY);
+	ccAddExternalObjectFunction("Character::set_y",                     Sc_Character_SetY);
+	ccAddExternalObjectFunction("Character::get_Z",                     Sc_Character_GetZ);
+	ccAddExternalObjectFunction("Character::set_Z",                     Sc_Character_SetZ);
+	ccAddExternalObjectFunction("Character::get_z",                     Sc_Character_GetZ);
+	ccAddExternalObjectFunction("Character::set_z",                     Sc_Character_SetZ);
+
+    ccAddExternalObjectFunction("Character::get_HasExplicitLight",      Sc_Character_HasExplicitLight);
+    ccAddExternalObjectFunction("Character::get_LightLevel",            Sc_Character_GetLightLevel);
+    ccAddExternalObjectFunction("Character::get_TintBlue",              Sc_Character_GetTintBlue);
+    ccAddExternalObjectFunction("Character::get_TintGreen",             Sc_Character_GetTintGreen);
+    ccAddExternalObjectFunction("Character::get_TintRed",               Sc_Character_GetTintRed);
+    ccAddExternalObjectFunction("Character::get_TintSaturation",        Sc_Character_GetTintSaturation);
+    ccAddExternalObjectFunction("Character::get_TintLuminance",         Sc_Character_GetTintLuminance);
+
+    /* ----------------------- Registering unsafe exports for plugins -----------------------*/
+
+    ccAddExternalFunctionForPlugin("Character::AddInventory^2",            (void*)Character_AddInventory);
+    ccAddExternalFunctionForPlugin("Character::AddWaypoint^2",             (void*)Character_AddWaypoint);
+    ccAddExternalFunctionForPlugin("Character::Animate^5",                 (void*)Character_Animate);
+    ccAddExternalFunctionForPlugin("Character::ChangeRoom^3",              (void*)Character_ChangeRoom);
+    ccAddExternalFunctionForPlugin("Character::ChangeRoomAutoPosition^2",  (void*)Character_ChangeRoomAutoPosition);
+    ccAddExternalFunctionForPlugin("Character::ChangeView^1",              (void*)Character_ChangeView);
+    ccAddExternalFunctionForPlugin("Character::FaceCharacter^2",           (void*)Character_FaceCharacter);
+    ccAddExternalFunctionForPlugin("Character::FaceDirection^2",           (void*)Character_FaceDirection);
+    ccAddExternalFunctionForPlugin("Character::FaceLocation^3",            (void*)Character_FaceLocation);
+    ccAddExternalFunctionForPlugin("Character::FaceObject^2",              (void*)Character_FaceObject);
+    ccAddExternalFunctionForPlugin("Character::FollowCharacter^3",         (void*)Character_FollowCharacter);
+    ccAddExternalFunctionForPlugin("Character::GetProperty^1",             (void*)Character_GetProperty);
+    ccAddExternalFunctionForPlugin("Character::GetPropertyText^2",         (void*)Character_GetPropertyText);
+    ccAddExternalFunctionForPlugin("Character::GetTextProperty^1",         (void*)Character_GetTextProperty);
+    ccAddExternalFunctionForPlugin("Character::HasInventory^1",            (void*)Character_HasInventory);
+    ccAddExternalFunctionForPlugin("Character::IsCollidingWithChar^1",     (void*)Character_IsCollidingWithChar);
+    ccAddExternalFunctionForPlugin("Character::IsCollidingWithObject^1",   (void*)Character_IsCollidingWithObject);
+    ccAddExternalFunctionForPlugin("Character::LockView^1",                (void*)Character_LockView);
+    ccAddExternalFunctionForPlugin("Character::LockView^2",                (void*)Character_LockViewEx);
+    if (base_api < kScriptAPI_v341)
+    {
+        ccAddExternalFunctionForPlugin("Character::LockViewAligned^3", (void*)Character_LockViewAligned_Old);
+        ccAddExternalFunctionForPlugin("Character::LockViewAligned^4", (void*)Character_LockViewAlignedEx_Old);
+    }
+    else
+    {
+        ccAddExternalFunctionForPlugin("Character::LockViewAligned^3", (void*)Character_LockViewAligned);
+        ccAddExternalFunctionForPlugin("Character::LockViewAligned^4", (void*)Character_LockViewAlignedEx);
+    }
+    ccAddExternalFunctionForPlugin("Character::LockViewFrame^3",           (void*)Character_LockViewFrame);
+    ccAddExternalFunctionForPlugin("Character::LockViewFrame^4",           (void*)Character_LockViewFrameEx);
+    ccAddExternalFunctionForPlugin("Character::LockViewOffset^3",          (void*)Character_LockViewOffset);
+    ccAddExternalFunctionForPlugin("Character::LockViewOffset^4",          (void*)Character_LockViewOffset);
+    ccAddExternalFunctionForPlugin("Character::LoseInventory^1",           (void*)Character_LoseInventory);
+    ccAddExternalFunctionForPlugin("Character::Move^4",                    (void*)Character_Move);
+    ccAddExternalFunctionForPlugin("Character::PlaceOnWalkableArea^0",     (void*)Character_PlaceOnWalkableArea);
+    ccAddExternalFunctionForPlugin("Character::RemoveTint^0",              (void*)Character_RemoveTint);
+    ccAddExternalFunctionForPlugin("Character::RunInteraction^1",          (void*)Character_RunInteraction);
+    ccAddExternalFunctionForPlugin("Character::Say^101",                   (void*)ScPl_Character_Say);
+    ccAddExternalFunctionForPlugin("Character::SayAt^4",                   (void*)Character_SayAt);
+    ccAddExternalFunctionForPlugin("Character::SayBackground^1",           (void*)Character_SayBackground);
+    ccAddExternalFunctionForPlugin("Character::SetAsPlayer^0",             (void*)Character_SetAsPlayer);
+    ccAddExternalFunctionForPlugin("Character::SetIdleView^2",             (void*)Character_SetIdleView);
+    //ccAddExternalFunctionForPlugin("Character::SetOption^2",             (void*)Character_SetOption);
+    ccAddExternalFunctionForPlugin("Character::SetWalkSpeed^2",            (void*)Character_SetSpeed);
+    ccAddExternalFunctionForPlugin("Character::StopMoving^0",              (void*)Character_StopMoving);
+    ccAddExternalFunctionForPlugin("Character::Think^101",                 (void*)ScPl_Character_Think);
+    ccAddExternalFunctionForPlugin("Character::Tint^5",                    (void*)Character_Tint);
+    ccAddExternalFunctionForPlugin("Character::UnlockView^0",              (void*)Character_UnlockView);
+    ccAddExternalFunctionForPlugin("Character::UnlockView^1",              (void*)Character_UnlockViewEx);
+    ccAddExternalFunctionForPlugin("Character::Walk^4",                    (void*)Character_Walk);
+    ccAddExternalFunctionForPlugin("Character::WalkStraight^3",            (void*)Character_WalkStraight);
+    ccAddExternalFunctionForPlugin("Character::GetAtRoomXY^2",             (void*)GetCharacterAtRoom);
+    ccAddExternalFunctionForPlugin("Character::GetAtScreenXY^2",           (void*)GetCharacterAtScreen);
+    ccAddExternalFunctionForPlugin("Character::get_ActiveInventory",       (void*)Character_GetActiveInventory);
+    ccAddExternalFunctionForPlugin("Character::set_ActiveInventory",       (void*)Character_SetActiveInventory);
+    ccAddExternalFunctionForPlugin("Character::get_Animating",             (void*)Character_GetAnimating);
+    ccAddExternalFunctionForPlugin("Character::get_AnimationSpeed",        (void*)Character_GetAnimationSpeed);
+    ccAddExternalFunctionForPlugin("Character::set_AnimationSpeed",        (void*)Character_SetAnimationSpeed);
+    ccAddExternalFunctionForPlugin("Character::get_Baseline",              (void*)Character_GetBaseline);
+    ccAddExternalFunctionForPlugin("Character::set_Baseline",              (void*)Character_SetBaseline);
+    ccAddExternalFunctionForPlugin("Character::get_BlinkInterval",         (void*)Character_GetBlinkInterval);
+    ccAddExternalFunctionForPlugin("Character::set_BlinkInterval",         (void*)Character_SetBlinkInterval);
+    ccAddExternalFunctionForPlugin("Character::get_BlinkView",             (void*)Character_GetBlinkView);
+    ccAddExternalFunctionForPlugin("Character::set_BlinkView",             (void*)Character_SetBlinkView);
+    ccAddExternalFunctionForPlugin("Character::get_BlinkWhileThinking",    (void*)Character_GetBlinkWhileThinking);
+    ccAddExternalFunctionForPlugin("Character::set_BlinkWhileThinking",    (void*)Character_SetBlinkWhileThinking);
+    ccAddExternalFunctionForPlugin("Character::get_BlockingHeight",        (void*)Character_GetBlockingHeight);
+    ccAddExternalFunctionForPlugin("Character::set_BlockingHeight",        (void*)Character_SetBlockingHeight);
+    ccAddExternalFunctionForPlugin("Character::get_BlockingWidth",         (void*)Character_GetBlockingWidth);
+    ccAddExternalFunctionForPlugin("Character::set_BlockingWidth",         (void*)Character_SetBlockingWidth);
+    ccAddExternalFunctionForPlugin("Character::get_Clickable",             (void*)Character_GetClickable);
+    ccAddExternalFunctionForPlugin("Character::set_Clickable",             (void*)Character_SetClickable);
+    ccAddExternalFunctionForPlugin("Character::get_DestinationX",          (void*)Character_GetDestinationX);
+    ccAddExternalFunctionForPlugin("Character::get_DestinationY",          (void*)Character_GetDestinationY);
+    ccAddExternalFunctionForPlugin("Character::get_DiagonalLoops",         (void*)Character_GetDiagonalWalking);
+    ccAddExternalFunctionForPlugin("Character::set_DiagonalLoops",         (void*)Character_SetDiagonalWalking);
+    ccAddExternalFunctionForPlugin("Character::get_Frame",                 (void*)Character_GetFrame);
+    ccAddExternalFunctionForPlugin("Character::set_Frame",                 (void*)Character_SetFrame);
+    if (base_api < kScriptAPI_v341)
+        ccAddExternalFunctionForPlugin("Character::get_HasExplicitTint",       (void*)Character_GetHasExplicitTint_Old);
+    else
+        ccAddExternalFunctionForPlugin("Character::get_HasExplicitTint",       (void*)Character_GetHasExplicitTint);
+    ccAddExternalFunctionForPlugin("Character::get_ID",                    (void*)Character_GetID);
+    ccAddExternalFunctionForPlugin("Character::get_IdleView",              (void*)Character_GetIdleView);
+    ccAddExternalFunctionForPlugin("Character::geti_InventoryQuantity",    (void*)Character_GetIInventoryQuantity);
+    ccAddExternalFunctionForPlugin("Character::seti_InventoryQuantity",    (void*)Character_SetIInventoryQuantity);
+    ccAddExternalFunctionForPlugin("Character::get_IgnoreLighting",        (void*)Character_GetIgnoreLighting);
+    ccAddExternalFunctionForPlugin("Character::set_IgnoreLighting",        (void*)Character_SetIgnoreLighting);
+    ccAddExternalFunctionForPlugin("Character::get_IgnoreScaling",         (void*)Character_GetIgnoreScaling);
+    ccAddExternalFunctionForPlugin("Character::set_IgnoreScaling",         (void*)Character_SetIgnoreScaling);
+    ccAddExternalFunctionForPlugin("Character::get_IgnoreWalkbehinds",     (void*)Character_GetIgnoreWalkbehinds);
+    ccAddExternalFunctionForPlugin("Character::set_IgnoreWalkbehinds",     (void*)Character_SetIgnoreWalkbehinds);
+    ccAddExternalFunctionForPlugin("Character::get_Loop",                  (void*)Character_GetLoop);
+    ccAddExternalFunctionForPlugin("Character::set_Loop",                  (void*)Character_SetLoop);
+    ccAddExternalFunctionForPlugin("Character::get_ManualScaling",         (void*)Character_GetIgnoreScaling);
+    ccAddExternalFunctionForPlugin("Character::set_ManualScaling",         (void*)Character_SetManualScaling);
+    ccAddExternalFunctionForPlugin("Character::get_MovementLinkedToAnimation",(void*)Character_GetMovementLinkedToAnimation);
+    ccAddExternalFunctionForPlugin("Character::set_MovementLinkedToAnimation",(void*)Character_SetMovementLinkedToAnimation);
+    ccAddExternalFunctionForPlugin("Character::get_Moving",                (void*)Character_GetMoving);
+    ccAddExternalFunctionForPlugin("Character::get_Name",                  (void*)Character_GetName);
+    ccAddExternalFunctionForPlugin("Character::set_Name",                  (void*)Character_SetName);
+    ccAddExternalFunctionForPlugin("Character::get_NormalView",            (void*)Character_GetNormalView);
+    ccAddExternalFunctionForPlugin("Character::get_PreviousRoom",          (void*)Character_GetPreviousRoom);
+    ccAddExternalFunctionForPlugin("Character::get_Room",                  (void*)Character_GetRoom);
+    ccAddExternalFunctionForPlugin("Character::get_ScaleMoveSpeed",        (void*)Character_GetScaleMoveSpeed);
+    ccAddExternalFunctionForPlugin("Character::set_ScaleMoveSpeed",        (void*)Character_SetScaleMoveSpeed);
+    ccAddExternalFunctionForPlugin("Character::get_ScaleVolume",           (void*)Character_GetScaleVolume);
+    ccAddExternalFunctionForPlugin("Character::set_ScaleVolume",           (void*)Character_SetScaleVolume);
+    ccAddExternalFunctionForPlugin("Character::get_Scaling",               (void*)Character_GetScaling);
+    ccAddExternalFunctionForPlugin("Character::set_Scaling",               (void*)Character_SetScaling);
+    ccAddExternalFunctionForPlugin("Character::get_Solid",                 (void*)Character_GetSolid);
+    ccAddExternalFunctionForPlugin("Character::set_Solid",                 (void*)Character_SetSolid);
+    ccAddExternalFunctionForPlugin("Character::get_Speaking",              (void*)Character_GetSpeaking);
+    ccAddExternalFunctionForPlugin("Character::get_SpeakingFrame",         (void*)Character_GetSpeakingFrame);
+    ccAddExternalFunctionForPlugin("Character::get_SpeechAnimationDelay",  (void*)GetCharacterSpeechAnimationDelay);
+    ccAddExternalFunctionForPlugin("Character::set_SpeechAnimationDelay",  (void*)Character_SetSpeechAnimationDelay);
+    ccAddExternalFunctionForPlugin("Character::get_SpeechColor",           (void*)Character_GetSpeechColor);
+    ccAddExternalFunctionForPlugin("Character::set_SpeechColor",           (void*)Character_SetSpeechColor);
+    ccAddExternalFunctionForPlugin("Character::get_SpeechView",            (void*)Character_GetSpeechView);
+    ccAddExternalFunctionForPlugin("Character::set_SpeechView",            (void*)Character_SetSpeechView);
+    ccAddExternalFunctionForPlugin("Character::get_ThinkView",             (void*)Character_GetThinkView);
+    ccAddExternalFunctionForPlugin("Character::set_ThinkView",             (void*)Character_SetThinkView);
+    ccAddExternalFunctionForPlugin("Character::get_Transparency",          (void*)Character_GetTransparency);
+    ccAddExternalFunctionForPlugin("Character::set_Transparency",          (void*)Character_SetTransparency);
+    ccAddExternalFunctionForPlugin("Character::get_TurnBeforeWalking",     (void*)Character_GetTurnBeforeWalking);
+    ccAddExternalFunctionForPlugin("Character::set_TurnBeforeWalking",     (void*)Character_SetTurnBeforeWalking);
+    ccAddExternalFunctionForPlugin("Character::get_View",                  (void*)Character_GetView);
+    ccAddExternalFunctionForPlugin("Character::get_WalkSpeedX",            (void*)Character_GetWalkSpeedX);
+    ccAddExternalFunctionForPlugin("Character::get_WalkSpeedY",            (void*)Character_GetWalkSpeedY);
+    ccAddExternalFunctionForPlugin("Character::get_X",                     (void*)Character_GetX);
+    ccAddExternalFunctionForPlugin("Character::set_X",                     (void*)Character_SetX);
+    ccAddExternalFunctionForPlugin("Character::get_x",                     (void*)Character_GetX);
+    ccAddExternalFunctionForPlugin("Character::set_x",                     (void*)Character_SetX);
+    ccAddExternalFunctionForPlugin("Character::get_Y",                     (void*)Character_GetY);
+    ccAddExternalFunctionForPlugin("Character::set_Y",                     (void*)Character_SetY);
+    ccAddExternalFunctionForPlugin("Character::get_y",                     (void*)Character_GetY);
+    ccAddExternalFunctionForPlugin("Character::set_y",                     (void*)Character_SetY);
+    ccAddExternalFunctionForPlugin("Character::get_Z",                     (void*)Character_GetZ);
+    ccAddExternalFunctionForPlugin("Character::set_Z",                     (void*)Character_SetZ);
+    ccAddExternalFunctionForPlugin("Character::get_z",                     (void*)Character_GetZ);
+    ccAddExternalFunctionForPlugin("Character::set_z",                     (void*)Character_SetZ);
+}
diff --git a/engines/ags/engine/ac/character.h b/engines/ags/engine/ac/character.h
new file mode 100644
index 0000000000..cb678fda3a
--- /dev/null
+++ b/engines/ags/engine/ac/character.h
@@ -0,0 +1,219 @@
+//=============================================================================
+//
+// Adventure Game Studio (AGS)
+//
+// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
+// The full list of copyright holders can be found in the Copyright.txt
+// file, which is part of this source code distribution.
+//
+// The AGS source code is provided under the Artistic License 2.0.
+// A copy of this license can be found in the file License.txt and at
+// http://www.opensource.org/licenses/artistic-license-2.0.php
+//
+//=============================================================================
+//
+//
+//
+//=============================================================================
+#ifndef __AGS_EE_AC__CHARACTER_H
+#define __AGS_EE_AC__CHARACTER_H
+
+#include "ac/characterinfo.h"
+#include "ac/characterextras.h"
+#include "ac/dynobj/scriptobject.h"
+#include "ac/dynobj/scriptinvitem.h"
+#include "ac/dynobj/scriptoverlay.h"
+#include "game/viewport.h"
+#include "util/geometry.h"
+
+// **** CHARACTER: FUNCTIONS ****
+
+void    Character_AddInventory(CharacterInfo *chaa, ScriptInvItem *invi, int addIndex);
+void    Character_AddWaypoint(CharacterInfo *chaa, int x, int y);
+void    Character_Animate(CharacterInfo *chaa, int loop, int delay, int repeat, int blocking, int direction);
+void    Character_ChangeRoomAutoPosition(CharacterInfo *chaa, int room, int newPos);
+void    Character_ChangeRoom(CharacterInfo *chaa, int room, int x, int y);
+void    Character_ChangeRoomSetLoop(CharacterInfo *chaa, int room, int x, int y, int direction);
+void    Character_ChangeView(CharacterInfo *chap, int vii);
+void    Character_FaceDirection(CharacterInfo *char1, int direction, int blockingStyle);
+void    Character_FaceCharacter(CharacterInfo *char1, CharacterInfo *char2, int blockingStyle);
+void    Character_FaceLocation(CharacterInfo *char1, int xx, int yy, int blockingStyle);
+void    Character_FaceObject(CharacterInfo *char1, ScriptObject *obj, int blockingStyle);
+void    Character_FollowCharacter(CharacterInfo *chaa, CharacterInfo *tofollow, int distaway, int eagerness);
+int     Character_IsCollidingWithChar(CharacterInfo *char1, CharacterInfo *char2);
+int     Character_IsCollidingWithObject(CharacterInfo *chin, ScriptObject *objid);
+bool    Character_IsInteractionAvailable(CharacterInfo *cchar, int mood);
+void    Character_LockView(CharacterInfo *chap, int vii);
+void    Character_LockViewEx(CharacterInfo *chap, int vii, int stopMoving);
+void    Character_LockViewAligned(CharacterInfo *chap, int vii, int loop, int align);
+void    Character_LockViewAlignedEx(CharacterInfo *chap, int vii, int loop, int align, int stopMoving);
+void    Character_LockViewFrame(CharacterInfo *chaa, int view, int loop, int frame);
+void    Character_LockViewFrameEx(CharacterInfo *chaa, int view, int loop, int frame, int stopMoving);
+void    Character_LockViewOffset(CharacterInfo *chap, int vii, int xoffs, int yoffs);
+void    Character_LockViewOffsetEx(CharacterInfo *chap, int vii, int xoffs, int yoffs, int stopMoving);
+void    Character_LoseInventory(CharacterInfo *chap, ScriptInvItem *invi);
+void    Character_PlaceOnWalkableArea(CharacterInfo *chap);
+void    Character_RemoveTint(CharacterInfo *chaa);
+int     Character_GetHasExplicitTint(CharacterInfo *chaa);
+void    Character_Say(CharacterInfo *chaa, const char *text);
+void    Character_SayAt(CharacterInfo *chaa, int x, int y, int width, const char *texx);
+ScriptOverlay* Character_SayBackground(CharacterInfo *chaa, const char *texx);
+void    Character_SetAsPlayer(CharacterInfo *chaa);
+void    Character_SetIdleView(CharacterInfo *chaa, int iview, int itime);
+void    Character_SetOption(CharacterInfo *chaa, int flag, int yesorno);
+void    Character_SetSpeed(CharacterInfo *chaa, int xspeed, int yspeed);
+void    Character_StopMoving(CharacterInfo *charp);
+void    Character_Tint(CharacterInfo *chaa, int red, int green, int blue, int opacity, int luminance);
+void    Character_Think(CharacterInfo *chaa, const char *text);
+void    Character_UnlockView(CharacterInfo *chaa);
+void    Character_UnlockViewEx(CharacterInfo *chaa, int stopMoving);
+void    Character_Walk(CharacterInfo *chaa, int x, int y, int blocking, int direct);
+void    Character_Move(CharacterInfo *chaa, int x, int y, int blocking, int direct);
+void    Character_WalkStraight(CharacterInfo *chaa, int xx, int yy, int blocking);
+
+void    Character_RunInteraction(CharacterInfo *chaa, int mood);
+
+// **** CHARACTER: PROPERTIES ****
+
+int Character_GetProperty(CharacterInfo *chaa, const char *property);
+void Character_GetPropertyText(CharacterInfo *chaa, const char *property, char *bufer);
+const char* Character_GetTextProperty(CharacterInfo *chaa, const char *property);
+
+ScriptInvItem* Character_GetActiveInventory(CharacterInfo *chaa);
+void    Character_SetActiveInventory(CharacterInfo *chaa, ScriptInvItem* iit);
+int     Character_GetAnimating(CharacterInfo *chaa);
+int     Character_GetAnimationSpeed(CharacterInfo *chaa);
+void    Character_SetAnimationSpeed(CharacterInfo *chaa, int newval);
+int     Character_GetBaseline(CharacterInfo *chaa);
+void    Character_SetBaseline(CharacterInfo *chaa, int basel);
+int     Character_GetBlinkInterval(CharacterInfo *chaa);
+void    Character_SetBlinkInterval(CharacterInfo *chaa, int interval);
+int     Character_GetBlinkView(CharacterInfo *chaa);
+void    Character_SetBlinkView(CharacterInfo *chaa, int vii);
+int     Character_GetBlinkWhileThinking(CharacterInfo *chaa);
+void    Character_SetBlinkWhileThinking(CharacterInfo *chaa, int yesOrNo);
+int     Character_GetBlockingHeight(CharacterInfo *chaa);
+void    Character_SetBlockingHeight(CharacterInfo *chaa, int hit);
+int     Character_GetBlockingWidth(CharacterInfo *chaa);
+void    Character_SetBlockingWidth(CharacterInfo *chaa, int wid);
+int     Character_GetDiagonalWalking(CharacterInfo *chaa);
+void    Character_SetDiagonalWalking(CharacterInfo *chaa, int yesorno);
+int     Character_GetClickable(CharacterInfo *chaa);
+void    Character_SetClickable(CharacterInfo *chaa, int clik);
+int     Character_GetID(CharacterInfo *chaa);
+int     Character_GetFrame(CharacterInfo *chaa);
+void    Character_SetFrame(CharacterInfo *chaa, int newval);
+int     Character_GetIdleView(CharacterInfo *chaa);
+int     Character_GetIInventoryQuantity(CharacterInfo *chaa, int index);
+int     Character_HasInventory(CharacterInfo *chaa, ScriptInvItem *invi);
+void    Character_SetIInventoryQuantity(CharacterInfo *chaa, int index, int quant);
+int     Character_GetIgnoreLighting(CharacterInfo *chaa);
+void    Character_SetIgnoreLighting(CharacterInfo *chaa, int yesorno);
+int     Character_GetIgnoreScaling(CharacterInfo *chaa);
+void    Character_SetIgnoreScaling(CharacterInfo *chaa, int yesorno);
+void    Character_SetManualScaling(CharacterInfo *chaa, int yesorno);
+int     Character_GetIgnoreWalkbehinds(CharacterInfo *chaa);
+void    Character_SetIgnoreWalkbehinds(CharacterInfo *chaa, int yesorno);
+int     Character_GetMovementLinkedToAnimation(CharacterInfo *chaa);
+void    Character_SetMovementLinkedToAnimation(CharacterInfo *chaa, int yesorno);
+int     Character_GetLoop(CharacterInfo *chaa);
+void    Character_SetLoop(CharacterInfo *chaa, int newval);
+int     Character_GetMoving(CharacterInfo *chaa);
+const char* Character_GetName(CharacterInfo *chaa);
+void    Character_SetName(CharacterInfo *chaa, const char *newName);
+int     Character_GetNormalView(CharacterInfo *chaa);
+int     Character_GetPreviousRoom(CharacterInfo *chaa);
+int     Character_GetRoom(CharacterInfo *chaa);
+int     Character_GetScaleMoveSpeed(CharacterInfo *chaa);
+void    Character_SetScaleMoveSpeed(CharacterInfo *chaa, int yesorno);
+int     Character_GetScaleVolume(CharacterInfo *chaa);
+void    Character_SetScaleVolume(CharacterInfo *chaa, int yesorno);
+int     Character_GetScaling(CharacterInfo *chaa);
+void    Character_SetScaling(CharacterInfo *chaa, int zoomlevel);
+int     Character_GetSolid(CharacterInfo *chaa);
+void    Character_SetSolid(CharacterInfo *chaa, int yesorno);
+int     Character_GetSpeaking(CharacterInfo *chaa);
+int     Character_GetSpeechColor(CharacterInfo *chaa);
+void    Character_SetSpeechColor(CharacterInfo *chaa, int ncol);
+void    Character_SetSpeechAnimationDelay(CharacterInfo *chaa, int newDelay);
+int     Character_GetSpeechView(CharacterInfo *chaa);
+void    Character_SetSpeechView(CharacterInfo *chaa, int vii);
+int     Character_GetThinkView(CharacterInfo *chaa);
+void    Character_SetThinkView(CharacterInfo *chaa, int vii);
+int     Character_GetTransparency(CharacterInfo *chaa);
+void    Character_SetTransparency(CharacterInfo *chaa, int trans);
+int     Character_GetTurnBeforeWalking(CharacterInfo *chaa);
+void    Character_SetTurnBeforeWalking(CharacterInfo *chaa, int yesorno);
+int     Character_GetView(CharacterInfo *chaa);
+int     Character_GetWalkSpeedX(CharacterInfo *chaa);
+int     Character_GetWalkSpeedY(CharacterInfo *chaa);
+int     Character_GetX(CharacterInfo *chaa);
+void    Character_SetX(CharacterInfo *chaa, int newval);
+int     Character_GetY(CharacterInfo *chaa);
+void    Character_SetY(CharacterInfo *chaa, int newval);
+int     Character_GetZ(CharacterInfo *chaa);
+void    Character_SetZ(CharacterInfo *chaa, int newval);
+int     Character_GetSpeakingFrame(CharacterInfo *chaa);
+
+//=============================================================================
+
+struct MoveList;
+namespace AGS { namespace Common { class Bitmap; } }
+using namespace AGS; // FIXME later
+
+void animate_character(CharacterInfo *chap, int loopn,int sppd,int rept, int noidleoverride = 0, int direction = 0, int sframe = 0);
+void walk_character(int chac,int tox,int toy,int ignwal, bool autoWalkAnims);
+int  find_looporder_index (int curloop);
+// returns 0 to use diagonal, 1 to not
+int  useDiagonal (CharacterInfo *char1);
+// returns 1 normally, or 0 if they only have horizontal animations
+int  hasUpDownLoops(CharacterInfo *char1);
+void start_character_turning (CharacterInfo *chinf, int useloop, int no_diagonal);
+void fix_player_sprite(MoveList*cmls,CharacterInfo*chinf);
+// Check whether two characters have walked into each other
+int  has_hit_another_character(int sourceChar);
+int  doNextCharMoveStep (CharacterInfo *chi, int &char_index, CharacterExtras *chex);
+int  find_nearest_walkable_area_within(int *xx, int *yy, int range, int step);
+void find_nearest_walkable_area (int *xx, int *yy);
+void walk_character(int chac,int tox,int toy,int ignwal, bool autoWalkAnims);
+void FindReasonableLoopForCharacter(CharacterInfo *chap);
+void walk_or_move_character(CharacterInfo *chaa, int x, int y, int blocking, int direct, bool isWalk);
+int  is_valid_character(int newchar);
+int  wantMoveNow (CharacterInfo *chi, CharacterExtras *chex);
+void setup_player_character(int charid);
+void CheckViewFrameForCharacter(CharacterInfo *chi);
+Common::Bitmap *GetCharacterImage(int charid, int *isFlipped);
+CharacterInfo *GetCharacterAtScreen(int xx, int yy);
+// Get character ID at the given room coordinates
+int is_pos_on_character(int xx,int yy);
+void get_char_blocking_rect(int charid, int *x1, int *y1, int *width, int *y2);
+// Check whether the source char has walked onto character ww
+int is_char_on_another (int sourceChar, int ww, int*fromxptr, int*cwidptr);
+int my_getpixel(Common::Bitmap *blk, int x, int y);
+// X and Y co-ordinates must be in 320x200 format
+int check_click_on_character(int xx,int yy,int mood);
+int is_pos_on_character(int xx,int yy);
+void _DisplaySpeechCore(int chid, const char *displbuf);
+void _DisplayThoughtCore(int chid, const char *displbuf);
+void _displayspeech(const char*texx, int aschar, int xx, int yy, int widd, int isThought);
+int get_character_currently_talking();
+void DisplaySpeech(const char*texx, int aschar);
+int update_lip_sync(int talkview, int talkloop, int *talkframeptr);
+
+// Calculates character's bounding box in room coordinates (takes only in-room transform into account)
+// use_frame_0 optionally tells to use frame 0 of current loop instead of current frame.
+Rect GetCharacterRoomBBox(int charid, bool use_frame_0 = false);
+// Find a closest viewport given character is to. Checks viewports in their order in game's array,
+// and returns either first viewport character's bounding box intersects with (or rather with its camera),
+// or the one that is least far away from its camera; calculated as a perpendicular distance between two AABBs.
+PViewport FindNearestViewport(int charid);
+
+extern CharacterInfo*playerchar;
+extern CharacterExtras *charextra;
+extern MoveList *mls;
+extern int32_t _sc_PlayerCharPtr;
+
+// order of loops to turn character in circle from down to down
+extern int turnlooporder[8];
+
+#endif // __AGS_EE_AC__CHARACTER_H
diff --git a/engines/ags/engine/ac/charactercache.h b/engines/ags/engine/ac/charactercache.h
new file mode 100644
index 0000000000..f4b5c64012
--- /dev/null
+++ b/engines/ags/engine/ac/charactercache.h
@@ -0,0 +1,35 @@
+//=============================================================================
+//
+// Adventure Game Studio (AGS)
+//
+// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
+// The full list of copyright holders can be found in the Copyright.txt
+// file, which is part of this source code distribution.
+//
+// The AGS source code is provided under the Artistic License 2.0.
+// A copy of this license can be found in the file License.txt and at
+// http://www.opensource.org/licenses/artistic-license-2.0.php
+//
+//=============================================================================
+//
+//
+//
+//=============================================================================
+#ifndef __AGS_EE_AC__CHARACTERCACHE_H
+#define __AGS_EE_AC__CHARACTERCACHE_H
+
+namespace AGS { namespace Common { class Bitmap; } }
+using namespace AGS; // FIXME later
+
+// stores cached info about the character
+struct CharacterCache {
+    Common::Bitmap *image;
+    int sppic;
+    int scaling;
+    int inUse;
+    short tintredwas, tintgrnwas, tintbluwas, tintamntwas;
+    short lightlevwas, tintlightwas;
+    // no mirroredWas is required, since the code inverts the sprite number
+};
+
+#endif // __AGS_EE_AC__CHARACTERCACHE_H
diff --git a/engines/ags/engine/ac/characterextras.cpp b/engines/ags/engine/ac/characterextras.cpp
new file mode 100644
index 0000000000..13c8f81350
--- /dev/null
+++ b/engines/ags/engine/ac/characterextras.cpp
@@ -0,0 +1,56 @@
+//=============================================================================
+//
+// Adventure Game Studio (AGS)
+//
+// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
+// The full list of copyright holders can be found in the Copyright.txt
+// file, which is part of this source code distribution.
+//
+// The AGS source code is provided under the Artistic License 2.0.
+// A copy of this license can be found in the file License.txt and at
+// http://www.opensource.org/licenses/artistic-license-2.0.php
+//
+//=============================================================================
+
+#include "ac/characterextras.h"
+#include "util/stream.h"
+
+using AGS::Common::Stream;
+
+void CharacterExtras::ReadFromFile(Stream *in)
+{
+    in->ReadArrayOfInt16(invorder, MAX_INVORDER);
+    invorder_count = in->ReadInt16();
+    width = in->ReadInt16();
+    height = in->ReadInt16();
+    zoom = in->ReadInt16();
+    xwas = in->ReadInt16();
+    ywas = in->ReadInt16();
+    tint_r = in->ReadInt16();
+    tint_g = in->ReadInt16();
+    tint_b = in->ReadInt16();
+    tint_level = in->ReadInt16();
+    tint_light = in->ReadInt16();
+    process_idle_this_time = in->ReadInt8();
+    slow_move_counter = in->ReadInt8();
+    animwait = in->ReadInt16();
+}
+
+void CharacterExtras::WriteToFile(Stream *out)
+{
+    out->WriteArrayOfInt16(invorder, MAX_INVORDER);
+    out->WriteInt16(invorder_count);
+    out->WriteInt16(width);
+    out->WriteInt16(height);
+    out->WriteInt16(zoom);
+    out->WriteInt16(xwas);
+    out->WriteInt16(ywas);
+    out->WriteInt16(tint_r);
+    out->WriteInt16(tint_g);
+    out->WriteInt16(tint_b);
+    out->WriteInt16(tint_level);
+    out->WriteInt16(tint_light);
+    out->WriteInt8(process_idle_this_time);
+    out->WriteInt8(slow_move_counter);
+    out->WriteInt16(animwait);
+}
diff --git a/engines/ags/engine/ac/characterextras.h b/engines/ags/engine/ac/characterextras.h
new file mode 100644
index 0000000000..2e9d6e6098
--- /dev/null
+++ b/engines/ags/engine/ac/characterextras.h
@@ -0,0 +1,52 @@
+//=============================================================================
+//
+// Adventure Game Studio (AGS)
+//
+// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
+// The full list of copyright holders can be found in the Copyright.txt
+// file, which is part of this source code distribution.
+//
+// The AGS source code is provided under the Artistic License 2.0.
+// A copy of this license can be found in the file License.txt and at
+// http://www.opensource.org/licenses/artistic-license-2.0.php
+//
+//=============================================================================
+//
+//
+//
+//=============================================================================
+#ifndef __AGS_EE_AC__CHARACTEREXTRAS_H
+#define __AGS_EE_AC__CHARACTEREXTRAS_H
+
+#include "ac/runtime_defines.h"
+
+// Forward declaration
+namespace AGS { namespace Common { class Stream; } }
+using namespace AGS; // FIXME later
+
+struct CharacterExtras {
+    // UGLY UGLY UGLY!! The CharacterInfo struct size is fixed because it's
+    // used in the scripts, therefore overflowing stuff has to go here
+    short invorder[MAX_INVORDER];
+    short invorder_count;
+    // TODO: implement full AABB and keep updated, so that engine could rely on these cached values all time;
+    // TODO: consider having both fixed AABB and volatile one that changes with animation frame (unless you change how anims work)
+    short width;
+    short height;
+    short zoom;
+    short xwas;
+    short ywas;
+    short tint_r;
+    short tint_g;
+    short tint_b;
+    short tint_level;
+    short tint_light;
+    char  process_idle_this_time;
+    char  slow_move_counter;
+    short animwait;
+
+    void ReadFromFile(Common::Stream *in);
+    void WriteToFile(Common::Stream *out);
+};
+
+#endif // __AGS_EE_AC__CHARACTEREXTRAS_H
diff --git a/engines/ags/engine/ac/characterinfo_engine.cpp b/engines/ags/engine/ac/characterinfo_engine.cpp
new file mode 100644
index 0000000000..8f6f1a5a83
--- /dev/null
+++ b/engines/ags/engine/ac/characterinfo_engine.cpp
@@ -0,0 +1,508 @@
+//=============================================================================
+//
+// Adventure Game Studio (AGS)
+//
+// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
+// The full list of copyright holders can be found in the Copyright.txt
+// file, which is part of this source code distribution.
+//
+// The AGS source code is provided under the Artistic License 2.0.
+// A copy of this license can be found in the file License.txt and at
+// http://www.opensource.org/licenses/artistic-license-2.0.php
+//
+//=============================================================================
+
+#include "ac/characterinfo.h"
+#include "ac/common.h"
+#include "ac/gamesetupstruct.h"
+#include "ac/character.h"
+#include "ac/characterextras.h"
+#include "ac/gamestate.h"
+#include "ac/global_character.h"
+#include "ac/math.h"
+#include "ac/viewframe.h"
+#include "debug/debug_log.h"
+#include "game/roomstruct.h"
+#include "main/maindefines_ex.h"	// RETURN_CONTINUE
+#include "main/update.h"
+#include "media/audio/audio_system.h"
+
+using namespace AGS::Common;
+
+extern ViewStruct*views;
+extern GameSetupStruct game;
+extern int displayed_room;
+extern GameState play;
+extern int char_speaking;
+extern RoomStruct thisroom;
+extern unsigned int loopcounter;
+
+#define Random __Rand
+
+int CharacterInfo::get_effective_y() {
+    return y - z;
+}
+int CharacterInfo::get_baseline() {
+    if (baseline < 1)
+        return y;
+    return baseline;
+}
+int CharacterInfo::get_blocking_top() {
+    if (blocking_height > 0)
+        return y - blocking_height / 2;
+    return y - 2;
+}
+int CharacterInfo::get_blocking_bottom() {
+    // the blocking_bottom should be 1 less than the top + height
+    // since the code does <= checks on it rather than < checks
+    if (blocking_height > 0)
+        return (y + (blocking_height + 1) / 2) - 1;
+    return y + 3;
+}
+
+void CharacterInfo::UpdateMoveAndAnim(int &char_index, CharacterExtras *chex, int &numSheep, int *followingAsSheep)
+{
+	int res;
+
+	if (on != 1) return;
+    
+	// walking
+	res = update_character_walking(chex);
+	// [IKM] Yes, it should return! upon getting RETURN_CONTINUE here
+	if (res == RETURN_CONTINUE) { // [IKM] now, this is one of those places...
+		return;				      //  must be careful not to screw things up
+	}
+    
+    // Make sure it doesn't flash up a blue cup
+    if (view < 0) ;
+    else if (loop >= views[view].numLoops)
+      loop = 0;
+
+    int doing_nothing = 1;
+
+	update_character_moving(char_index, chex, doing_nothing);
+
+	// [IKM] 2012-06-28:
+	// Character index value is used to set up some variables in there, so I cannot just cease using it
+	res = update_character_animating(char_index, doing_nothing);
+	// [IKM] Yes, it should return! upon getting RETURN_CONTINUE here
+	if (res == RETURN_CONTINUE) { // [IKM] now, this is one of those places...
+		return;				      //  must be careful not to screw things up
+	}
+
+	update_character_follower(char_index, numSheep, followingAsSheep, doing_nothing);
+
+	update_character_idle(chex, doing_nothing);
+
+    chex->process_idle_this_time = 0;
+}
+
+void CharacterInfo::UpdateFollowingExactlyCharacter()
+{
+	x = game.chars[following].x;
+    y = game.chars[following].y;
+    z = game.chars[following].z;
+    room = game.chars[following].room;
+    prevroom = game.chars[following].prevroom;
+
+    int usebase = game.chars[following].get_baseline();
+
+    if (flags & CHF_BEHINDSHEPHERD)
+      baseline = usebase - 1;
+    else
+      baseline = usebase + 1;
+}
+
+int CharacterInfo::update_character_walking(CharacterExtras *chex)
+{
+    if (walking >= TURNING_AROUND) {
+      // Currently rotating to correct direction
+      if (walkwait > 0) walkwait--;
+      else {
+        // Work out which direction is next
+        int wantloop = find_looporder_index(loop) + 1;
+        // going anti-clockwise, take one before instead
+        if (walking >= TURNING_BACKWARDS)
+          wantloop -= 2;
+        while (1) {
+          if (wantloop >= 8)
+            wantloop = 0;
+          if (wantloop < 0)
+            wantloop = 7;
+          if ((turnlooporder[wantloop] >= views[view].numLoops) ||
+              (views[view].loops[turnlooporder[wantloop]].numFrames < 1) ||
+              ((turnlooporder[wantloop] >= 4) && ((flags & CHF_NODIAGONAL)!=0))) {
+            if (walking >= TURNING_BACKWARDS)
+              wantloop--;
+            else
+              wantloop++;
+          }
+          else break;
+        }
+        loop = turnlooporder[wantloop];
+        walking -= TURNING_AROUND;
+        // if still turning, wait for next frame
+        if (walking % TURNING_BACKWARDS >= TURNING_AROUND)
+          walkwait = animspeed;
+        else
+          walking = walking % TURNING_BACKWARDS;
+        chex->animwait = 0;
+      }
+	  return RETURN_CONTINUE;
+      //continue;
+    }
+
+	return 0;
+}
+
+void CharacterInfo::update_character_moving(int &char_index, CharacterExtras *chex, int &doing_nothing)
+{
+	if ((walking > 0) && (room == displayed_room))
+    {
+      if (walkwait > 0) walkwait--;
+      else 
+      {
+        flags &= ~CHF_AWAITINGMOVE;
+
+        // Move the character
+        int numSteps = wantMoveNow(this, chex);
+
+        if ((numSteps) && (chex->xwas != INVALID_X)) {
+          // if the zoom level changed mid-move, the walkcounter
+          // might not have come round properly - so sort it out
+          x = chex->xwas;
+          y = chex->ywas;
+          chex->xwas = INVALID_X;
+        }
+
+        int oldxp = x, oldyp = y;
+
+        for (int ff = 0; ff < abs(numSteps); ff++) {
+          if (doNextCharMoveStep (this, char_index, chex))
+            break;
+          if ((walking == 0) || (walking >= TURNING_AROUND))
+            break;
+        }
+
+        if (numSteps < 0) {
+          // very small scaling, intersperse the movement
+          // to stop it being jumpy
+          chex->xwas = x;
+          chex->ywas = y;
+          x = ((x) - oldxp) / 2 + oldxp;
+          y = ((y) - oldyp) / 2 + oldyp;
+        }
+        else if (numSteps > 0)
+          chex->xwas = INVALID_X;
+
+        if ((flags & CHF_ANTIGLIDE) == 0)
+          walkwaitcounter++;
+      }
+
+      if (loop >= views[view].numLoops)
+        quitprintf("Unable to render character %d (%s) because loop %d does not exist in view %d", index_id, name, loop, view + 1);
+
+      // check don't overflow loop
+      int framesInLoop = views[view].loops[loop].numFrames;
+      if (frame > framesInLoop)
+      {
+        frame = 1;
+
+        if (framesInLoop < 2)
+          frame = 0;
+
+        if (framesInLoop < 1)
+          quitprintf("Unable to render character %d (%s) because there are no frames in loop %d", index_id, name, loop);
+      }
+
+      if (walking<1) {
+        chex->process_idle_this_time = 1;
+        doing_nothing=1;
+        walkwait=0;
+        chex->animwait = 0;
+        // use standing pic
+        Character_StopMoving(this);
+        frame = 0;
+        CheckViewFrameForCharacter(this);
+      }
+      else if (chex->animwait > 0) chex->animwait--;
+      else {
+        if (flags & CHF_ANTIGLIDE)
+          walkwaitcounter++;
+
+        if ((flags & CHF_MOVENOTWALK) == 0)
+        {
+          frame++;
+          if (frame >= views[view].loops[loop].numFrames)
+          {
+            // end of loop, so loop back round skipping the standing frame
+            frame = 1;
+
+            if (views[view].loops[loop].numFrames < 2)
+              frame = 0;
+          }
+
+          chex->animwait = views[view].loops[loop].frames[frame].speed + animspeed;
+
+          if (flags & CHF_ANTIGLIDE)
+            walkwait = chex->animwait;
+          else
+            walkwait = 0;
+
+          CheckViewFrameForCharacter(this);
+        }
+      }
+      doing_nothing = 0;
+    }
+}
+
+int CharacterInfo::update_character_animating(int &aa, int &doing_nothing)
+{
+	// not moving, but animating
+    // idleleft is <0 while idle view is playing (.animating is 0)
+    if (((animating != 0) || (idleleft < 0)) &&
+        ((walking == 0) || ((flags & CHF_MOVENOTWALK) != 0)) &&
+        (room == displayed_room)) 
+    {
+      doing_nothing = 0;
+      // idle anim doesn't count as doing something
+      if (idleleft < 0)
+        doing_nothing = 1;
+
+      if (wait>0) wait--;
+      else if ((char_speaking == aa) && (game.options[OPT_LIPSYNCTEXT] != 0)) {
+        // currently talking with lip-sync speech
+        int fraa = frame;
+        wait = update_lip_sync (view, loop, &fraa) - 1;
+        // closed mouth at end of sentence
+        // NOTE: standard lip-sync is synchronized with text timer, not voice file
+        if (play.speech_in_post_state ||
+            ((play.messagetime >= 0) && (play.messagetime < play.close_mouth_speech_time)))
+          frame = 0;
+
+        if (frame != fraa) {
+          frame = fraa;
+          CheckViewFrameForCharacter(this);
+        }
+        
+        //continue;
+		return RETURN_CONTINUE;
+      }
+      else {
+        int oldframe = frame;
+        if (animating & CHANIM_BACKWARDS) {
+          frame--;
+          if (frame < 0) {
+            // if the previous loop is a Run Next Loop one, go back to it
+            if ((loop > 0) && 
+              (views[view].loops[loop - 1].RunNextLoop())) {
+
+              loop --;
+              frame = views[view].loops[loop].numFrames - 1;
+            }
+            else if (animating & CHANIM_REPEAT) {
+
+              frame = views[view].loops[loop].numFrames - 1;
+
+              while (views[view].loops[loop].RunNextLoop()) {
+                loop++;
+                frame = views[view].loops[loop].numFrames - 1;
+              }
+            }
+            else {
+              frame++;
+              animating = 0;
+            }
+          }
+        }
+        else
+          frame++;
+
+        if ((aa == char_speaking) &&
+             (play.speech_in_post_state ||
+             ((!play.speech_has_voice) &&
+             (play.close_mouth_speech_time > 0) &&
+             (play.messagetime < play.close_mouth_speech_time)))) {
+          // finished talking - stop animation
+          animating = 0;
+          frame = 0;
+        }
+
+        if (frame >= views[view].loops[loop].numFrames) {
+          
+          if (views[view].loops[loop].RunNextLoop()) 
+          {
+            if (loop+1 >= views[view].numLoops)
+              quit("!Animating character tried to overrun last loop in view");
+            loop++;
+            frame=0;
+          }
+          else if ((animating & CHANIM_REPEAT)==0) {
+            animating=0;
+            frame--;
+            // end of idle anim
+            if (idleleft < 0) {
+              // constant anim, reset (need this cos animating==0)
+              if (idletime == 0)
+                frame = 0;
+              // one-off anim, stop
+              else {
+                ReleaseCharacterView(aa);
+                idleleft=idletime;
+              }
+            }
+          }
+          else {
+            frame=0;
+            // if it's a multi-loop animation, go back to start
+            if (play.no_multiloop_repeat == 0) {
+              while ((loop > 0) && 
+                  (views[view].loops[loop - 1].RunNextLoop()))
+                loop--;
+            }
+          }
+        }
+        wait = views[view].loops[loop].frames[frame].speed;
+        // idle anim doesn't have speed stored cos animating==0
+        if (idleleft < 0)
+          wait += animspeed+5;
+        else 
+          wait += (animating >> 8) & 0x00ff;
+
+        if (frame != oldframe)
+          CheckViewFrameForCharacter(this);
+      }
+    }
+
+	return 0;
+}
+
+void CharacterInfo::update_character_follower(int &aa, int &numSheep, int *followingAsSheep, int &doing_nothing)
+{
+	if ((following >= 0) && (followinfo == FOLLOW_ALWAYSONTOP)) {
+      // an always-on-top follow
+      if (numSheep >= MAX_SHEEP)
+        quit("too many sheep");
+      followingAsSheep[numSheep] = aa;
+      numSheep++;
+    }
+    // not moving, but should be following another character
+    else if ((following >= 0) && (doing_nothing == 1)) {
+      short distaway=(followinfo >> 8) & 0x00ff;
+      // no character in this room
+      if ((game.chars[following].on == 0) || (on == 0)) ;
+      else if (room < 0) {
+        room ++;
+        if (room == 0) {
+          // appear in the new room
+          room = game.chars[following].room;
+          x = play.entered_at_x;
+          y = play.entered_at_y;
+        }
+      }
+      // wait a bit, so we're not constantly walking
+      else if (Random(100) < (followinfo & 0x00ff)) ;
+      // the followed character has changed room
+      else if ((room != game.chars[following].room)
+            && (game.chars[following].on == 0))
+        ;  // do nothing if the player isn't visible
+      else if (room != game.chars[following].room) {
+        prevroom = room;
+        room = game.chars[following].room;
+
+        if (room == displayed_room) {
+          // only move to the room-entered position if coming into
+          // the current room
+          if (play.entered_at_x > (thisroom.Width - 8)) {
+            x = thisroom.Width+8;
+            y = play.entered_at_y;
+            }
+          else if (play.entered_at_x < 8) {
+            x = -8;
+            y = play.entered_at_y;
+            }
+          else if (play.entered_at_y > (thisroom.Height - 8)) {
+            y = thisroom.Height+8;
+            x = play.entered_at_x;
+            }
+          else if (play.entered_at_y < thisroom.Edges.Top+8) {
+            y = thisroom.Edges.Top+1;
+            x = play.entered_at_x;
+            }
+          else {
+            // not at one of the edges
+            // delay for a few seconds to let the player move
+            room = -play.follow_change_room_timer;
+          }
+          if (room >= 0) {
+            walk_character(aa,play.entered_at_x,play.entered_at_y,1, true);
+            doing_nothing = 0;
+          }
+        }
+      }
+      else if (room != displayed_room) {
+        // if the characetr is following another character and
+        // neither is in the current room, don't try to move
+      }
+      else if ((abs(game.chars[following].x - x) > distaway+30) |
+        (abs(game.chars[following].y - y) > distaway+30) |
+        ((followinfo & 0x00ff) == 0)) {
+        // in same room
+        int goxoffs=(Random(50)-25);
+        // make sure he's not standing on top of the other man
+        if (goxoffs < 0) goxoffs-=distaway;
+        else goxoffs+=distaway;
+        walk_character(aa,game.chars[following].x + goxoffs,
+          game.chars[following].y + (Random(50)-25),0, true);
+        doing_nothing = 0;
+      }
+    }
+}
+
+void CharacterInfo::update_character_idle(CharacterExtras *chex, int &doing_nothing)
+{
+	// no idle animation, so skip this bit
+    if (idleview < 1) ;
+    // currently playing idle anim
+    else if (idleleft < 0) ;
+    // not in the current room
+    else if (room != displayed_room) ;
+    // they are moving or animating (or the view is locked), so 
+    // reset idle timeout
+    else if ((doing_nothing == 0) || ((flags & CHF_FIXVIEW) != 0))
+      idleleft = idletime;
+    // count idle time
+    else if ((loopcounter%40==0) || (chex->process_idle_this_time == 1)) {
+      idleleft--;
+      if (idleleft == -1) {
+        int useloop=loop;
+        debug_script_log("%s: Now idle (view %d)", scrname, idleview+1);
+		Character_LockView(this, idleview+1);
+        // SetCharView resets it to 0
+        idleleft = -2;
+        int maxLoops = views[idleview].numLoops;
+        // if the char is set to "no diagonal loops", don't try
+        // to use diagonal idle loops either
+        if ((maxLoops > 4) && (useDiagonal(this)))
+          maxLoops = 4;
+        // If it's not a "swimming"-type idleanim, choose a random loop
+        // if there arent enough loops to do the current one.
+        if ((idletime > 0) && (useloop >= maxLoops)) {
+          do {
+            useloop = rand() % maxLoops;
+          // don't select a loop which is a continuation of a previous one
+          } while ((useloop > 0) && (views[idleview].loops[useloop-1].RunNextLoop()));
+        }
+        // Normal idle anim - just reset to loop 0 if not enough to
+        // use the current one
+        else if (useloop >= maxLoops)
+          useloop = 0;
+
+        animate_character(this,useloop,
+          animspeed+5,(idletime == 0) ? 1 : 0, 1);
+
+        // don't set Animating while the idle anim plays
+        animating = 0;
+      }
+    }  // end do idle animation
+}
diff --git a/engines/ags/engine/ac/datetime.cpp b/engines/ags/engine/ac/datetime.cpp
new file mode 100644
index 0000000000..d2f8b230b2
--- /dev/null
+++ b/engines/ags/engine/ac/datetime.cpp
@@ -0,0 +1,141 @@
+//=============================================================================
+//
+// Adventure Game Studio (AGS)
+//
+// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
+// The full list of copyright holders can be found in the Copyright.txt
+// file, which is part of this source code distribution.
+//
+// The AGS source code is provided under the Artistic License 2.0.
+// A copy of this license can be found in the file License.txt and at
+// http://www.opensource.org/licenses/artistic-license-2.0.php
+//
+//=============================================================================
+
+#include <time.h>
+#include "ac/datetime.h"
+#include "platform/base/agsplatformdriver.h"
+#include "script/runtimescriptvalue.h"
+
+ScriptDateTime* DateTime_Now_Core() {
+    ScriptDateTime *sdt = new ScriptDateTime();
+
+    platform->GetSystemTime(sdt);
+
+    return sdt;
+}
+
+ScriptDateTime* DateTime_Now() {
+    ScriptDateTime *sdt = DateTime_Now_Core();
+    ccRegisterManagedObject(sdt, sdt);
+    return sdt;
+}
+
+int DateTime_GetYear(ScriptDateTime *sdt) {
+    return sdt->year;
+}
+
+int DateTime_GetMonth(ScriptDateTime *sdt) {
+    return sdt->month;
+}
+
+int DateTime_GetDayOfMonth(ScriptDateTime *sdt) {
+    return sdt->day;
+}
+
+int DateTime_GetHour(ScriptDateTime *sdt) {
+    return sdt->hour;
+}
+
+int DateTime_GetMinute(ScriptDateTime *sdt) {
+    return sdt->minute;
+}
+
+int DateTime_GetSecond(ScriptDateTime *sdt) {
+    return sdt->second;
+}
+
+int DateTime_GetRawTime(ScriptDateTime *sdt) {
+    return sdt->rawUnixTime;
+}
+
+//=============================================================================
+//
+// Script API Functions
+//
+//=============================================================================
+
+#include "debug/out.h"
+#include "script/script_api.h"
+#include "script/script_runtime.h"
+
+// ScriptDateTime* ()
+RuntimeScriptValue Sc_DateTime_Now(const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_SCALL_OBJAUTO(ScriptDateTime, DateTime_Now);
+}
+
+// int (ScriptDateTime *sdt)
+RuntimeScriptValue Sc_DateTime_GetYear(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptDateTime, DateTime_GetYear);
+}
+
+// int (ScriptDateTime *sdt)
+RuntimeScriptValue Sc_DateTime_GetMonth(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptDateTime, DateTime_GetMonth);
+}
+
+// int (ScriptDateTime *sdt)
+RuntimeScriptValue Sc_DateTime_GetDayOfMonth(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptDateTime, DateTime_GetDayOfMonth);
+}
+
+// int (ScriptDateTime *sdt)
+RuntimeScriptValue Sc_DateTime_GetHour(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptDateTime, DateTime_GetHour);
+}
+
+// int (ScriptDateTime *sdt)
+RuntimeScriptValue Sc_DateTime_GetMinute(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptDateTime, DateTime_GetMinute);
+}
+
+// int (ScriptDateTime *sdt)
+RuntimeScriptValue Sc_DateTime_GetSecond(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptDateTime, DateTime_GetSecond);
+}
+
+// int (ScriptDateTime *sdt)
+RuntimeScriptValue Sc_DateTime_GetRawTime(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptDateTime, DateTime_GetRawTime);
+}
+
+void RegisterDateTimeAPI()
+{
+    ccAddExternalStaticFunction("DateTime::get_Now",        Sc_DateTime_Now);
+    ccAddExternalObjectFunction("DateTime::get_DayOfMonth", Sc_DateTime_GetDayOfMonth);
+    ccAddExternalObjectFunction("DateTime::get_Hour",       Sc_DateTime_GetHour);
+    ccAddExternalObjectFunction("DateTime::get_Minute",     Sc_DateTime_GetMinute);
+    ccAddExternalObjectFunction("DateTime::get_Month",      Sc_DateTime_GetMonth);
+    ccAddExternalObjectFunction("DateTime::get_RawTime",    Sc_DateTime_GetRawTime);
+    ccAddExternalObjectFunction("DateTime::get_Second",     Sc_DateTime_GetSecond);
+    ccAddExternalObjectFunction("DateTime::get_Year",       Sc_DateTime_GetYear);
+
+    /* ----------------------- Registering unsafe exports for plugins -----------------------*/
+
+    ccAddExternalFunctionForPlugin("DateTime::get_Now",        (void*)DateTime_Now);
+    ccAddExternalFunctionForPlugin("DateTime::get_DayOfMonth", (void*)DateTime_GetDayOfMonth);
+    ccAddExternalFunctionForPlugin("DateTime::get_Hour",       (void*)DateTime_GetHour);
+    ccAddExternalFunctionForPlugin("DateTime::get_Minute",     (void*)DateTime_GetMinute);
+    ccAddExternalFunctionForPlugin("DateTime::get_Month",      (void*)DateTime_GetMonth);
+    ccAddExternalFunctionForPlugin("DateTime::get_RawTime",    (void*)DateTime_GetRawTime);
+    ccAddExternalFunctionForPlugin("DateTime::get_Second",     (void*)DateTime_GetSecond);
+    ccAddExternalFunctionForPlugin("DateTime::get_Year",       (void*)DateTime_GetYear);
+}
diff --git a/engines/ags/engine/ac/datetime.h b/engines/ags/engine/ac/datetime.h
new file mode 100644
index 0000000000..76d474ee00
--- /dev/null
+++ b/engines/ags/engine/ac/datetime.h
@@ -0,0 +1,33 @@
+//=============================================================================
+//
+// Adventure Game Studio (AGS)
+//
+// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
+// The full list of copyright holders can be found in the Copyright.txt
+// file, which is part of this source code distribution.
+//
+// The AGS source code is provided under the Artistic License 2.0.
+// A copy of this license can be found in the file License.txt and at
+// http://www.opensource.org/licenses/artistic-license-2.0.php
+//
+//=============================================================================
+//
+//
+//
+//=============================================================================
+#ifndef __AGS_EE_AC__DATETIME_H
+#define __AGS_EE_AC__DATETIME_H
+
+#include "ac/dynobj/scriptdatetime.h"
+
+ScriptDateTime* DateTime_Now_Core();
+ScriptDateTime* DateTime_Now();
+int             DateTime_GetYear(ScriptDateTime *sdt);
+int             DateTime_GetMonth(ScriptDateTime *sdt);
+int             DateTime_GetDayOfMonth(ScriptDateTime *sdt);
+int             DateTime_GetHour(ScriptDateTime *sdt);
+int             DateTime_GetMinute(ScriptDateTime *sdt);
+int             DateTime_GetSecond(ScriptDateTime *sdt);
+int             DateTime_GetRawTime(ScriptDateTime *sdt);
+
+#endif // __AGS_EE_AC__DATETIME_H
diff --git a/engines/ags/engine/ac/dialog.cpp b/engines/ags/engine/ac/dialog.cpp
new file mode 100644
index 0000000000..d27fe02f94
--- /dev/null
+++ b/engines/ags/engine/ac/dialog.cpp
@@ -0,0 +1,1324 @@
+//=============================================================================
+//
+// Adventure Game Studio (AGS)
+//
+// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
+// The full list of copyright holders can be found in the Copyright.txt
+// file, which is part of this source code distribution.
+//
+// The AGS source code is provided under the Artistic License 2.0.
+// A copy of this license can be found in the file License.txt and at
+// http://www.opensource.org/licenses/artistic-license-2.0.php
+//
+//=============================================================================
+
+#include "ac/dialog.h"
+#include "ac/common.h"
+#include "ac/character.h"
+#include "ac/characterinfo.h"
+#include "ac/dialogtopic.h"
+#include "ac/display.h"
+#include "ac/draw.h"
+#include "ac/gamestate.h"
+#include "ac/gamesetupstruct.h"
+#include "ac/global_character.h"
+#include "ac/global_dialog.h"
+#include "ac/global_display.h"
+#include "ac/global_game.h"
+#include "ac/global_gui.h"
+#include "ac/global_room.h"
+#include "ac/global_translation.h"
+#include "ac/keycode.h"
+#include "ac/overlay.h"
+#include "ac/mouse.h"
+#include "ac/parser.h"
+#include "ac/sys_events.h"
+#include "ac/string.h"
+#include "ac/dynobj/scriptdialogoptionsrendering.h"
+#include "ac/dynobj/scriptdrawingsurface.h"
+#include "ac/system.h"
+#include "debug/debug_log.h"
+#include "font/fonts.h"
+#include "script/cc_instance.h"
+#include "gui/guimain.h"
+#include "gui/guitextbox.h"
+#include "main/game_run.h"
+#include "platform/base/agsplatformdriver.h"
+#include "script/script.h"
+#include "ac/spritecache.h"
+#include "gfx/ddb.h"
+#include "gfx/gfx_util.h"
+#include "gfx/graphicsdriver.h"
+#include "ac/mouse.h"
+#include "media/audio/audio_system.h"
+
+using namespace AGS::Common;
+
+extern GameSetupStruct game;
+extern GameState play;
+extern ccInstance *dialogScriptsInst;
+extern int in_new_room;
+extern CharacterInfo*playerchar;
+extern SpriteCache spriteset;
+extern AGSPlatformDriver *platform;
+extern int cur_mode,cur_cursor;
+extern IGraphicsDriver *gfxDriver;
+
+DialogTopic *dialog;
+ScriptDialogOptionsRendering ccDialogOptionsRendering;
+ScriptDrawingSurface* dialogOptionsRenderingSurface;
+
+int said_speech_line; // used while in dialog to track whether screen needs updating
+
+// Old dialog support
+std::vector< std::shared_ptr<unsigned char> > old_dialog_scripts;
+std::vector<String> old_speech_lines;
+
+int said_text = 0;
+int longestline = 0;
+
+
+
+
+void Dialog_Start(ScriptDialog *sd) {
+  RunDialog(sd->id);
+}
+
+#define CHOSE_TEXTPARSER -3053
+#define SAYCHOSEN_USEFLAG 1
+#define SAYCHOSEN_YES 2
+#define SAYCHOSEN_NO  3 
+
+int Dialog_DisplayOptions(ScriptDialog *sd, int sayChosenOption)
+{
+  if ((sayChosenOption < 1) || (sayChosenOption > 3))
+    quit("!Dialog.DisplayOptions: invalid parameter passed");
+
+  int chose = show_dialog_options(sd->id, sayChosenOption, (game.options[OPT_RUNGAMEDLGOPTS] != 0));
+  if (chose != CHOSE_TEXTPARSER)
+  {
+    chose++;
+  }
+  return chose;
+}
+
+void Dialog_SetOptionState(ScriptDialog *sd, int option, int newState) {
+  SetDialogOption(sd->id, option, newState);
+}
+
+int Dialog_GetOptionState(ScriptDialog *sd, int option) {
+  return GetDialogOption(sd->id, option);
+}
+
+int Dialog_HasOptionBeenChosen(ScriptDialog *sd, int option)
+{
+  if ((option < 1) || (option > dialog[sd->id].numoptions))
+    quit("!Dialog.HasOptionBeenChosen: Invalid option number specified");
+  option--;
+
+  if (dialog[sd->id].optionflags[option] & DFLG_HASBEENCHOSEN)
+    return 1;
+  return 0;
+}
+
+void Dialog_SetHasOptionBeenChosen(ScriptDialog *sd, int option, bool chosen)
+{
+    if (option < 1 || option > dialog[sd->id].numoptions)
+    {
+        quit("!Dialog.HasOptionBeenChosen: Invalid option number specified");
+    }
+    option--;
+    if (chosen)
+    {
+        dialog[sd->id].optionflags[option] |= DFLG_HASBEENCHOSEN;
+    }
+    else
+    {
+        dialog[sd->id].optionflags[option] &= ~DFLG_HASBEENCHOSEN;
+    }
+}
+
+int Dialog_GetOptionCount(ScriptDialog *sd)
+{
+  return dialog[sd->id].numoptions;
+}
+
+int Dialog_GetShowTextParser(ScriptDialog *sd)
+{
+  return (dialog[sd->id].topicFlags & DTFLG_SHOWPARSER) ? 1 : 0;
+}
+
+const char* Dialog_GetOptionText(ScriptDialog *sd, int option)
+{
+  if ((option < 1) || (option > dialog[sd->id].numoptions))
+    quit("!Dialog.GetOptionText: Invalid option number specified");
+
+  option--;
+
+  return CreateNewScriptString(get_translation(dialog[sd->id].optionnames[option]));
+}
+
+int Dialog_GetID(ScriptDialog *sd) {
+  return sd->id;
+}
+
+//=============================================================================
+
+#define RUN_DIALOG_STAY          -1
+#define RUN_DIALOG_STOP_DIALOG   -2
+#define RUN_DIALOG_GOTO_PREVIOUS -4
+// dialog manager stuff
+
+void get_dialog_script_parameters(unsigned char* &script, unsigned short* param1, unsigned short* param2)
+{
+  script++;
+  *param1 = *script;
+  script++;
+  *param1 += *script * 256;
+  script++;
+  
+  if (param2)
+  {
+    *param2 = *script;
+    script++;
+    *param2 += *script * 256;
+    script++;
+  }
+}
+
+int run_dialog_script(DialogTopic*dtpp, int dialogID, int offse, int optionIndex) {
+  said_speech_line = 0;
+  int result = RUN_DIALOG_STAY;
+
+  if (dialogScriptsInst)
+  {
+    char funcName[100];
+    sprintf(funcName, "_run_dialog%d", dialogID);
+    RunTextScriptIParam(dialogScriptsInst, funcName, RuntimeScriptValue().SetInt32(optionIndex));
+    result = dialogScriptsInst->returnValue;
+  }
+  else
+  {
+    // old dialog format
+    if (offse == -1)
+      return result;	
+	
+    unsigned char* script = old_dialog_scripts[dialogID].get() + offse;
+
+    unsigned short param1 = 0;
+    unsigned short param2 = 0;
+    bool script_running = true;
+
+    while (script_running)
+    {
+      switch (*script)
+      {
+        case DCMD_SAY:
+          get_dialog_script_parameters(script, &param1, &param2);
+          
+          if (param1 == DCHAR_PLAYER)
+            param1 = game.playercharacter;
+
+          if (param1 == DCHAR_NARRATOR)
+            Display(get_translation(old_speech_lines[param2]));
+          else
+            DisplaySpeech(get_translation(old_speech_lines[param2]), param1);
+
+          said_speech_line = 1;
+          break;
+
+        case DCMD_OPTOFF:
+          get_dialog_script_parameters(script, &param1, nullptr);
+          SetDialogOption(dialogID, param1 + 1, 0, true);
+          break;
+
+        case DCMD_OPTON:
+          get_dialog_script_parameters(script, &param1, nullptr);
+          SetDialogOption(dialogID, param1 + 1, DFLG_ON, true);
+          break;
+
+        case DCMD_RETURN:
+          script_running = false;
+          break;
+
+        case DCMD_STOPDIALOG:
+          result = RUN_DIALOG_STOP_DIALOG;
+          script_running = false;
+          break;
+
+        case DCMD_OPTOFFFOREVER:
+          get_dialog_script_parameters(script, &param1, nullptr);
+          SetDialogOption(dialogID, param1 + 1, DFLG_OFFPERM, true);
+          break;
+
+        case DCMD_RUNTEXTSCRIPT:
+          get_dialog_script_parameters(script, &param1, nullptr);
+          result = run_dialog_request(param1);
+          script_running = (result == RUN_DIALOG_STAY);
+          break;
+
+        case DCMD_GOTODIALOG:
+          get_dialog_script_parameters(script, &param1, nullptr);
+          result = param1;
+          script_running = false;
+          break;
+
+        case DCMD_PLAYSOUND:
+          get_dialog_script_parameters(script, &param1, nullptr);
+          play_sound(param1);
+          break;
+
+        case DCMD_ADDINV:
+          get_dialog_script_parameters(script, &param1, nullptr);
+          add_inventory(param1);
+          break;
+
+        case DCMD_SETSPCHVIEW:
+          get_dialog_script_parameters(script, &param1, &param2);
+          SetCharacterSpeechView(param1, param2);
+          break;
+
+        case DCMD_NEWROOM:
+          get_dialog_script_parameters(script, &param1, nullptr);
+          NewRoom(param1);
+          in_new_room = 1;
+          result = RUN_DIALOG_STOP_DIALOG;
+          script_running = false;
+          break;
+
+        case DCMD_SETGLOBALINT:
+          get_dialog_script_parameters(script, &param1, &param2);
+          SetGlobalInt(param1, param2);
+          break;
+
+        case DCMD_GIVESCORE:
+          get_dialog_script_parameters(script, &param1, nullptr);
+          GiveScore(param1);
+          break;
+
+        case DCMD_GOTOPREVIOUS:
+          result = RUN_DIALOG_GOTO_PREVIOUS;
+          script_running = false;
+          break;
+
+        case DCMD_LOSEINV:
+          get_dialog_script_parameters(script, &param1, nullptr);
+          lose_inventory(param1);
+          break;
+
+        case DCMD_ENDSCRIPT:
+          result = RUN_DIALOG_STOP_DIALOG;
+          script_running = false;
+          break;
+      }
+    }
+  }
+
+  if (in_new_room > 0)
+    return RUN_DIALOG_STOP_DIALOG;
+
+  if (said_speech_line > 0) {
+    // the line below fixes the problem with the close-up face remaining on the
+    // screen after they finish talking; however, it makes the dialog options
+    // area flicker when going between topics.
+    DisableInterface();
+    UpdateGameOnce(); // redraw the screen to make sure it looks right
+    EnableInterface();
+    // if we're not about to abort the dialog, switch back to arrow
+    if (result != RUN_DIALOG_STOP_DIALOG)
+      set_mouse_cursor(CURS_ARROW);
+  }
+
+  return result;
+}
+
+int write_dialog_options(Bitmap *ds, bool ds_has_alpha, int dlgxp, int curyp, int numdisp, int mouseison, int areawid,
+    int bullet_wid, int usingfont, DialogTopic*dtop, char*disporder, short*dispyp,
+    int linespacing, int utextcol, int padding) {
+  int ww;
+
+  color_t text_color;
+  for (ww=0;ww<numdisp;ww++) {
+
+    if ((dtop->optionflags[disporder[ww]] & DFLG_HASBEENCHOSEN) &&
+        (play.read_dialog_option_colour >= 0)) {
+      // 'read' colour
+      text_color = ds->GetCompatibleColor(play.read_dialog_option_colour);
+    }
+    else {
+      // 'unread' colour
+      text_color = ds->GetCompatibleColor(playerchar->talkcolor);
+    }
+
+    if (mouseison==ww) {
+      if (text_color == ds->GetCompatibleColor(utextcol))
+        text_color = ds->GetCompatibleColor(13); // the normal colour is the same as highlight col
+      else text_color = ds->GetCompatibleColor(utextcol);
+    }
+
+    break_up_text_into_lines(get_translation(dtop->optionnames[disporder[ww]]), Lines, areawid-(2*padding+2+bullet_wid), usingfont);
+    dispyp[ww]=curyp;
+    if (game.dialog_bullet > 0)
+    {
+        draw_gui_sprite_v330(ds, game.dialog_bullet, dlgxp, curyp, ds_has_alpha);
+    }
+    if (game.options[OPT_DIALOGNUMBERED] == kDlgOptNumbering) {
+      char tempbfr[20];
+      int actualpicwid = 0;
+      if (game.dialog_bullet > 0)
+        actualpicwid = game.SpriteInfos[game.dialog_bullet].Width+3;
+
+      sprintf (tempbfr, "%d.", ww + 1);
+      wouttext_outline (ds, dlgxp + actualpicwid, curyp, usingfont, text_color, tempbfr);
+    }
+    for (size_t cc=0;cc<Lines.Count();cc++) {
+      wouttext_outline(ds, dlgxp+((cc==0) ? 0 : 9)+bullet_wid, curyp, usingfont, text_color, Lines[cc]);
+      curyp+=linespacing;
+    }
+    if (ww < numdisp-1)
+      curyp += data_to_game_coord(game.options[OPT_DIALOGGAP]);
+  }
+  return curyp;
+}
+
+
+
+#define GET_OPTIONS_HEIGHT {\
+  needheight = 0;\
+  for (int i = 0; i < numdisp; ++i) {\
+    break_up_text_into_lines(get_translation(dtop->optionnames[disporder[i]]), Lines, areawid-(2*padding+2+bullet_wid), usingfont);\
+    needheight += getheightoflines(usingfont, Lines.Count()) + data_to_game_coord(game.options[OPT_DIALOGGAP]);\
+  }\
+  if (parserInput) needheight += parserInput->Height + data_to_game_coord(game.options[OPT_DIALOGGAP]);\
+ }
+
+
+void draw_gui_for_dialog_options(Bitmap *ds, GUIMain *guib, int dlgxp, int dlgyp) {
+  if (guib->BgColor != 0) {
+    color_t draw_color = ds->GetCompatibleColor(guib->BgColor);
+    ds->FillRect(Rect(dlgxp, dlgyp, dlgxp + guib->Width, dlgyp + guib->Height), draw_color);
+  }
+  if (guib->BgImage > 0)
+      GfxUtil::DrawSpriteWithTransparency(ds, spriteset[guib->BgImage], dlgxp, dlgyp);
+}
+
+bool get_custom_dialog_options_dimensions(int dlgnum)
+{
+  ccDialogOptionsRendering.Reset();
+  ccDialogOptionsRendering.dialogID = dlgnum;
+
+  getDialogOptionsDimensionsFunc.params[0].SetDynamicObject(&ccDialogOptionsRendering, &ccDialogOptionsRendering);
+  run_function_on_non_blocking_thread(&getDialogOptionsDimensionsFunc);
+
+  if ((ccDialogOptionsRendering.width > 0) &&
+      (ccDialogOptionsRendering.height > 0))
+  {
+    return true;
+  }
+  return false;
+}
+
+#define MAX_TOPIC_HISTORY 50
+#define DLG_OPTION_PARSER 99
+
+struct DialogOptions
+{
+    int dlgnum;
+    bool runGameLoopsInBackground;
+
+    int dlgxp;
+    int dlgyp;
+    int dialog_abs_x; // absolute dialog position on screen
+    int padding;
+    int usingfont;
+    int lineheight;
+    int linespacing;
+    int curswas;
+    int bullet_wid;
+    int needheight;
+    IDriverDependantBitmap *ddb;
+    Bitmap *subBitmap;
+    GUITextBox *parserInput;
+    DialogTopic*dtop;
+
+    char disporder[MAXTOPICOPTIONS];
+    short dispyp[MAXTOPICOPTIONS];
+
+    int numdisp;
+    int chose;
+
+    Bitmap *tempScrn;
+    int parserActivated;
+
+    int curyp;
+    bool wantRefresh;
+    bool usingCustomRendering;
+    int orixp;
+    int oriyp;
+    int areawid;
+    int is_textwindow;
+    int dirtyx;
+    int dirtyy;
+    int dirtywidth;
+    int dirtyheight;
+
+    int mouseison;
+    int mousewason;
+
+    int forecol;
+
+    void Prepare(int _dlgnum, bool _runGameLoopsInBackground);
+    void Show();
+    void Redraw();
+    bool Run();
+    void Close();
+};
+
+void DialogOptions::Prepare(int _dlgnum, bool _runGameLoopsInBackground)
+{
+  dlgnum = _dlgnum;
+  runGameLoopsInBackground = _runGameLoopsInBackground;
+
+  dlgyp = get_fixed_pixel_size(160);
+  usingfont=FONT_NORMAL;
+  lineheight = getfontheight_outlined(usingfont);
+  linespacing = getfontspacing_outlined(usingfont);
+  curswas=cur_cursor;
+  bullet_wid = 0;
+  ddb = nullptr;
+  subBitmap = nullptr;
+  parserInput = nullptr;
+  dtop = nullptr;
+
+  if ((dlgnum < 0) || (dlgnum >= game.numdialog))
+    quit("!RunDialog: invalid dialog number specified");
+
+  can_run_delayed_command();
+
+  play.in_conversation ++;
+
+  update_polled_stuff_if_runtime();
+
+  if (game.dialog_bullet > 0)
+    bullet_wid = game.SpriteInfos[game.dialog_bullet].Width+3;
+
+  // numbered options, leave space for the numbers
+  if (game.options[OPT_DIALOGNUMBERED] == kDlgOptNumbering)
+    bullet_wid += wgettextwidth_compensate("9. ", usingfont);
+
+  said_text = 0;
+
+  update_polled_stuff_if_runtime();
+
+  const Rect &ui_view = play.GetUIViewport();
+  tempScrn = BitmapHelper::CreateBitmap(ui_view.GetWidth(), ui_view.GetHeight(), game.GetColorDepth());
+
+  set_mouse_cursor(CURS_ARROW);
+
+  dtop=&dialog[dlgnum];
+
+  chose=-1;
+  numdisp=0;
+
+  parserActivated = 0;
+  if ((dtop->topicFlags & DTFLG_SHOWPARSER) && (play.disable_dialog_parser == 0)) {
+    parserInput = new GUITextBox();
+    parserInput->Height = lineheight + get_fixed_pixel_size(4);
+    parserInput->SetShowBorder(true);
+    parserInput->Font = usingfont;
+  }
+
+  numdisp=0;
+  for (int i = 0; i < dtop->numoptions; ++i) {
+    if ((dtop->optionflags[i] & DFLG_ON)==0) continue;
+    ensure_text_valid_for_font(dtop->optionnames[i], usingfont);
+    disporder[numdisp]=i;
+    numdisp++;
+  }
+}
+
+void DialogOptions::Show()
+{
+  if (numdisp<1) quit("!DoDialog: all options have been turned off");
+  // Don't display the options if there is only one and the parser
+  // is not enabled.
+  if (!((numdisp > 1) || (parserInput != nullptr) || (play.show_single_dialog_option)))
+  {
+      chose = disporder[0];  // only one choice, so select it
+      return;
+  }
+
+    is_textwindow = 0;
+    forecol = play.dialog_options_highlight_color;
+
+    mouseison=-1;
+    mousewason=-10;
+    const Rect &ui_view = play.GetUIViewport();
+    dirtyx = 0;
+    dirtyy = 0;
+    dirtywidth = ui_view.GetWidth();
+    dirtyheight = ui_view.GetHeight();
+    usingCustomRendering = false;
+
+
+    dlgxp = 1;
+    if (get_custom_dialog_options_dimensions(dlgnum))
+    {
+      usingCustomRendering = true;
+      dirtyx = data_to_game_coord(ccDialogOptionsRendering.x);
+      dirtyy = data_to_game_coord(ccDialogOptionsRendering.y);
+      dirtywidth = data_to_game_coord(ccDialogOptionsRendering.width);
+      dirtyheight = data_to_game_coord(ccDialogOptionsRendering.height);
+      dialog_abs_x = dirtyx;
+    }
+    else if (game.options[OPT_DIALOGIFACE] > 0)
+    {
+      GUIMain*guib=&guis[game.options[OPT_DIALOGIFACE]];
+      if (guib->IsTextWindow()) {
+        // text-window, so do the QFG4-style speech options
+        is_textwindow = 1;
+        forecol = guib->FgColor;
+      }
+      else {
+        dlgxp = guib->X;
+        dlgyp = guib->Y;
+
+        dirtyx = dlgxp;
+        dirtyy = dlgyp;
+        dirtywidth = guib->Width;
+        dirtyheight = guib->Height;
+        dialog_abs_x = guib->X;
+
+        areawid=guib->Width - 5;
+        padding = TEXTWINDOW_PADDING_DEFAULT;
+
+        GET_OPTIONS_HEIGHT
+
+        if (game.options[OPT_DIALOGUPWARDS]) {
+          // They want the options upwards from the bottom
+          dlgyp = (guib->Y + guib->Height) - needheight;
+        }
+        
+      }
+    }
+    else {
+      //dlgyp=(play.viewport.GetHeight()-numdisp*txthit)-1;
+      const Rect &ui_view = play.GetUIViewport();
+      areawid= ui_view.GetWidth()-5;
+      padding = TEXTWINDOW_PADDING_DEFAULT;
+      GET_OPTIONS_HEIGHT
+      dlgyp = ui_view.GetHeight() - needheight;
+
+      dirtyx = 0;
+      dirtyy = dlgyp - 1;
+      dirtywidth = ui_view.GetWidth();
+      dirtyheight = ui_view.GetHeight() - dirtyy;
+      dialog_abs_x = 0;
+    }
+    if (!is_textwindow)
+      areawid -= data_to_game_coord(play.dialog_options_x) * 2;
+
+    orixp = dlgxp;
+    oriyp = dlgyp;
+    wantRefresh = false;
+    mouseison=-10;
+    
+    update_polled_stuff_if_runtime();
+    if (!play.mouse_cursor_hidden)
+      ags_domouse(DOMOUSE_ENABLE);
+    update_polled_stuff_if_runtime();
+
+    Redraw();
+    while(Run());
+
+    if (!play.mouse_cursor_hidden)
+      ags_domouse(DOMOUSE_DISABLE);
+}
+
+void DialogOptions::Redraw()
+{
+    wantRefresh = true;
+
+    if (usingCustomRendering)
+    {
+      tempScrn = recycle_bitmap(tempScrn, game.GetColorDepth(), 
+        data_to_game_coord(ccDialogOptionsRendering.width), 
+        data_to_game_coord(ccDialogOptionsRendering.height));
+    }
+
+    tempScrn->ClearTransparent();
+    Bitmap *ds = tempScrn;
+
+    dlgxp = orixp;
+    dlgyp = oriyp;
+    const Rect &ui_view = play.GetUIViewport();
+
+    bool options_surface_has_alpha = false;
+
+    if (usingCustomRendering)
+    {
+      ccDialogOptionsRendering.surfaceToRenderTo = dialogOptionsRenderingSurface;
+      ccDialogOptionsRendering.surfaceAccessed = false;
+      dialogOptionsRenderingSurface->linkedBitmapOnly = tempScrn;
+      dialogOptionsRenderingSurface->hasAlphaChannel = ccDialogOptionsRendering.hasAlphaChannel;
+      options_surface_has_alpha = dialogOptionsRenderingSurface->hasAlphaChannel != 0;
+
+      renderDialogOptionsFunc.params[0].SetDynamicObject(&ccDialogOptionsRendering, &ccDialogOptionsRendering);
+      run_function_on_non_blocking_thread(&renderDialogOptionsFunc);
+
+      if (!ccDialogOptionsRendering.surfaceAccessed)
+          debug_script_warn("dialog_options_get_dimensions was implemented, but no dialog_options_render function drew anything to the surface");
+
+      if (parserInput)
+      {
+        parserInput->X = data_to_game_coord(ccDialogOptionsRendering.parserTextboxX);
+        curyp = data_to_game_coord(ccDialogOptionsRendering.parserTextboxY);
+        areawid = data_to_game_coord(ccDialogOptionsRendering.parserTextboxWidth);
+        if (areawid == 0)
+          areawid = tempScrn->GetWidth();
+      }
+      ccDialogOptionsRendering.needRepaint = false;
+    }
+    else if (is_textwindow) {
+      // text window behind the options
+      areawid = data_to_game_coord(play.max_dialogoption_width);
+      int biggest = 0;
+      padding = guis[game.options[OPT_DIALOGIFACE]].Padding;
+      for (int i = 0; i < numdisp; ++i) {
+        break_up_text_into_lines(get_translation(dtop->optionnames[disporder[i]]), Lines, areawid-((2*padding+2)+bullet_wid), usingfont);
+        if (longestline > biggest)
+          biggest = longestline;
+      }
+      if (biggest < areawid - ((2*padding+6)+bullet_wid))
+        areawid = biggest + ((2*padding+6)+bullet_wid);
+
+      if (areawid < data_to_game_coord(play.min_dialogoption_width)) {
+        areawid = data_to_game_coord(play.min_dialogoption_width);
+        if (play.min_dialogoption_width > play.max_dialogoption_width)
+          quit("!game.min_dialogoption_width is larger than game.max_dialogoption_width");
+      }
+
+      GET_OPTIONS_HEIGHT
+
+      int savedwid = areawid;
+      int txoffs=0,tyoffs=0,yspos = ui_view.GetHeight()/2-(2*padding+needheight)/2;
+      int xspos = ui_view.GetWidth()/2 - areawid/2;
+      // shift window to the right if QG4-style full-screen pic
+      if ((game.options[OPT_SPEECHTYPE] == 3) && (said_text > 0))
+        xspos = (ui_view.GetWidth() - areawid) - get_fixed_pixel_size(10);
+
+      // needs to draw the right text window, not the default
+      Bitmap *text_window_ds = nullptr;
+      draw_text_window(&text_window_ds, false, &txoffs,&tyoffs,&xspos,&yspos,&areawid,nullptr,needheight, game.options[OPT_DIALOGIFACE]);
+      options_surface_has_alpha = guis[game.options[OPT_DIALOGIFACE]].HasAlphaChannel();
+      // since draw_text_window incrases the width, restore it
+      areawid = savedwid;
+
+      dirtyx = xspos;
+      dirtyy = yspos;
+      dirtywidth = text_window_ds->GetWidth();
+      dirtyheight = text_window_ds->GetHeight();
+      dialog_abs_x = txoffs + xspos;
+
+      GfxUtil::DrawSpriteWithTransparency(ds, text_window_ds, xspos, yspos);
+      // TODO: here we rely on draw_text_window always assigning new bitmap to text_window_ds;
+      // should make this more explicit
+      delete text_window_ds;
+
+      // Ignore the dialog_options_x/y offsets when using a text window
+      txoffs += xspos;
+      tyoffs += yspos;
+      dlgyp = tyoffs;
+      curyp = write_dialog_options(ds, options_surface_has_alpha, txoffs,tyoffs,numdisp,mouseison,areawid,bullet_wid,usingfont,dtop,disporder,dispyp,linespacing,forecol,padding);
+      if (parserInput)
+        parserInput->X = txoffs;
+    }
+    else {
+
+      if (wantRefresh) {
+        // redraw the black background so that anti-alias
+        // fonts don't re-alias themselves
+        if (game.options[OPT_DIALOGIFACE] == 0) {
+          color_t draw_color = ds->GetCompatibleColor(16);
+          ds->FillRect(Rect(0,dlgyp-1, ui_view.GetWidth()-1, ui_view.GetHeight()-1), draw_color);
+        }
+        else {
+          GUIMain* guib = &guis[game.options[OPT_DIALOGIFACE]];
+          if (!guib->IsTextWindow())
+            draw_gui_for_dialog_options(ds, guib, dlgxp, dlgyp);
+        }
+      }
+
+      dirtyx = 0;
+      dirtywidth = ui_view.GetWidth();
+
+      if (game.options[OPT_DIALOGIFACE] > 0) 
+      {
+        // the whole GUI area should be marked dirty in order
+        // to ensure it gets drawn
+        GUIMain* guib = &guis[game.options[OPT_DIALOGIFACE]];
+        dirtyheight = guib->Height;
+        dirtyy = dlgyp;
+        options_surface_has_alpha = guib->HasAlphaChannel();
+      }
+      else
+      {
+        dirtyy = dlgyp - 1;
+        dirtyheight = needheight + 1;
+        options_surface_has_alpha = false;
+      }
+
+      dlgxp += data_to_game_coord(play.dialog_options_x);
+      dlgyp += data_to_game_coord(play.dialog_options_y);
+
+      // if they use a negative dialog_options_y, make sure the
+      // area gets marked as dirty
+      if (dlgyp < dirtyy)
+        dirtyy = dlgyp;
+
+      //curyp = dlgyp + 1;
+      curyp = dlgyp;
+      curyp = write_dialog_options(ds, options_surface_has_alpha, dlgxp,curyp,numdisp,mouseison,areawid,bullet_wid,usingfont,dtop,disporder,dispyp,linespacing,forecol,padding);
+
+      /*if (curyp > play.viewport.GetHeight()) {
+        dlgyp = play.viewport.GetHeight() - (curyp - dlgyp);
+        ds->FillRect(Rect(0,dlgyp-1,play.viewport.GetWidth()-1,play.viewport.GetHeight()-1);
+        goto redraw_options;
+      }*/
+      if (parserInput)
+        parserInput->X = dlgxp;
+    }
+
+    if (parserInput) {
+      // Set up the text box, if present
+      parserInput->Y = curyp + data_to_game_coord(game.options[OPT_DIALOGGAP]);
+      parserInput->Width = areawid - get_fixed_pixel_size(10);
+      parserInput->TextColor = playerchar->talkcolor;
+      if (mouseison == DLG_OPTION_PARSER)
+        parserInput->TextColor = forecol;
+
+      if (game.dialog_bullet)  // the parser X will get moved in a second
+      {
+          draw_gui_sprite_v330(ds, game.dialog_bullet, parserInput->X, parserInput->Y, options_surface_has_alpha);
+      }
+
+      parserInput->Width -= bullet_wid;
+      parserInput->X += bullet_wid;
+
+      parserInput->Draw(ds);
+      parserInput->IsActivated = false;
+    }
+
+    wantRefresh = false;
+
+    update_polled_stuff_if_runtime();
+
+    subBitmap = recycle_bitmap(subBitmap, tempScrn->GetColorDepth(), dirtywidth, dirtyheight);
+    subBitmap = ReplaceBitmapWithSupportedFormat(subBitmap);
+
+    update_polled_stuff_if_runtime();
+
+    if (usingCustomRendering)
+    {
+      subBitmap->Blit(tempScrn, 0, 0, 0, 0, tempScrn->GetWidth(), tempScrn->GetHeight());
+      invalidate_rect(dirtyx, dirtyy, dirtyx + subBitmap->GetWidth(), dirtyy + subBitmap->GetHeight(), false);
+    }
+    else
+    {
+      subBitmap->Blit(tempScrn, dirtyx, dirtyy, 0, 0, dirtywidth, dirtyheight);
+    }
+
+    if ((ddb != nullptr) && 
+      ((ddb->GetWidth() != dirtywidth) ||
+       (ddb->GetHeight() != dirtyheight)))
+    {
+      gfxDriver->DestroyDDB(ddb);
+      ddb = nullptr;
+    }
+    
+    if (ddb == nullptr)
+      ddb = gfxDriver->CreateDDBFromBitmap(subBitmap, options_surface_has_alpha, false);
+    else
+      gfxDriver->UpdateDDBFromBitmap(ddb, subBitmap, options_surface_has_alpha);
+
+    if (runGameLoopsInBackground)
+    {
+        render_graphics(ddb, dirtyx, dirtyy);
+    }
+}
+
+bool DialogOptions::Run()
+{
+    const bool new_custom_render = usingCustomRendering && game.options[OPT_DIALOGOPTIONSAPI] >= 0;
+
+      if (runGameLoopsInBackground)
+      {
+        play.disabled_user_interface++;
+        UpdateGameOnce(false, ddb, dirtyx, dirtyy);
+        play.disabled_user_interface--;
+      }
+      else
+      {
+        update_audio_system_on_game_loop();
+        render_graphics(ddb, dirtyx, dirtyy);
+      }
+
+      if (new_custom_render)
+      {
+        runDialogOptionRepExecFunc.params[0].SetDynamicObject(&ccDialogOptionsRendering, &ccDialogOptionsRendering);
+        run_function_on_non_blocking_thread(&runDialogOptionRepExecFunc);
+      }
+
+      int gkey;
+      if (run_service_key_controls(gkey) && !play.IsIgnoringInput()) {
+        if (parserInput) {
+          wantRefresh = true;
+          // type into the parser 
+          if ((gkey == 361) || ((gkey == ' ') && (strlen(parserInput->Text) == 0))) {
+            // write previous contents into textbox (F3 or Space when box is empty)
+            for (unsigned int i = strlen(parserInput->Text); i < strlen(play.lastParserEntry); i++) {
+              parserInput->OnKeyPress(play.lastParserEntry[i]);
+            }
+            //ags_domouse(DOMOUSE_DISABLE);
+            Redraw();
+            return true; // continue running loop
+          }
+          else if ((gkey >= 32) || (gkey == 13) || (gkey == 8)) {
+            parserInput->OnKeyPress(gkey);
+            if (!parserInput->IsActivated) {
+              //ags_domouse(DOMOUSE_DISABLE);
+              Redraw();
+              return true; // continue running loop
+            }
+          }
+        }
+        else if (new_custom_render)
+        {
+            runDialogOptionKeyPressHandlerFunc.params[0].SetDynamicObject(&ccDialogOptionsRendering, &ccDialogOptionsRendering);
+            runDialogOptionKeyPressHandlerFunc.params[1].SetInt32(GetKeyForKeyPressCb(gkey));
+            run_function_on_non_blocking_thread(&runDialogOptionKeyPressHandlerFunc);
+        }
+        // Allow selection of options by keyboard shortcuts
+        else if (game.options[OPT_DIALOGNUMBERED] >= kDlgOptKeysOnly &&
+                 gkey >= '1' && gkey <= '9')
+        {
+          gkey -= '1';
+          if (gkey < numdisp) {
+            chose = disporder[gkey];
+            return false; // end dialog options running loop
+          }
+        }
+      }
+      mousewason=mouseison;
+      mouseison=-1;
+      if (new_custom_render); // do not automatically detect option under mouse
+      else if (usingCustomRendering)
+      {
+        if ((mousex >= dirtyx) && (mousey >= dirtyy) &&
+            (mousex < dirtyx + tempScrn->GetWidth()) &&
+            (mousey < dirtyy + tempScrn->GetHeight()))
+        {
+          getDialogOptionUnderCursorFunc.params[0].SetDynamicObject(&ccDialogOptionsRendering, &ccDialogOptionsRendering);
+          run_function_on_non_blocking_thread(&getDialogOptionUnderCursorFunc);
+
+          if (!getDialogOptionUnderCursorFunc.atLeastOneImplementationExists)
+            quit("!The script function dialog_options_get_active is not implemented. It must be present to use a custom dialogue system.");
+
+          mouseison = ccDialogOptionsRendering.activeOptionID;
+        }
+        else
+        {
+          ccDialogOptionsRendering.activeOptionID = -1;
+        }
+      }
+      else if (mousex >= dialog_abs_x && mousex < (dialog_abs_x + areawid) &&
+               mousey >= dlgyp && mousey < curyp)
+      {
+        mouseison=numdisp-1;
+        for (int i = 0; i < numdisp; ++i) {
+          if (mousey < dispyp[i]) { mouseison=i-1; break; }
+        }
+        if ((mouseison<0) | (mouseison>=numdisp)) mouseison=-1;
+      }
+
+      if (parserInput != nullptr) {
+        int relativeMousey = mousey;
+        if (usingCustomRendering)
+          relativeMousey -= dirtyy;
+
+        if ((relativeMousey > parserInput->Y) && 
+            (relativeMousey < parserInput->Y + parserInput->Height))
+          mouseison = DLG_OPTION_PARSER;
+
+        if (parserInput->IsActivated)
+          parserActivated = 1;
+      }
+
+      int mouseButtonPressed = NONE;
+      int mouseWheelTurn = 0;
+      if (run_service_mb_controls(mouseButtonPressed, mouseWheelTurn) && mouseButtonPressed >= 0 &&
+          !play.IsIgnoringInput())
+      {
+        if (mouseison < 0 && !new_custom_render)
+        {
+          if (usingCustomRendering)
+          {
+            runDialogOptionMouseClickHandlerFunc.params[0].SetDynamicObject(&ccDialogOptionsRendering, &ccDialogOptionsRendering);
+            runDialogOptionMouseClickHandlerFunc.params[1].SetInt32(mouseButtonPressed + 1);
+            run_function_on_non_blocking_thread(&runDialogOptionMouseClickHandlerFunc);
+
+            if (runDialogOptionMouseClickHandlerFunc.atLeastOneImplementationExists)
+            {
+              Redraw();
+              return true; // continue running loop
+            }
+          }
+          return true; // continue running loop
+        }
+        if (mouseison == DLG_OPTION_PARSER) {
+          // they clicked the text box
+          parserActivated = 1;
+        }
+        else if (new_custom_render)
+        {
+            runDialogOptionMouseClickHandlerFunc.params[0].SetDynamicObject(&ccDialogOptionsRendering, &ccDialogOptionsRendering);
+            runDialogOptionMouseClickHandlerFunc.params[1].SetInt32(mouseButtonPressed + 1);
+            run_function_on_non_blocking_thread(&runDialogOptionMouseClickHandlerFunc);
+        }
+        else if (usingCustomRendering)
+        {
+          chose = mouseison;
+          return false; // end dialog options running loop
+        }
+        else {
+          chose=disporder[mouseison];
+          return false; // end dialog options running loop
+        }
+      }
+
+      if (usingCustomRendering)
+      {
+        if (mouseWheelTurn != 0)
+        {
+            runDialogOptionMouseClickHandlerFunc.params[0].SetDynamicObject(&ccDialogOptionsRendering, &ccDialogOptionsRendering);
+            runDialogOptionMouseClickHandlerFunc.params[1].SetInt32((mouseWheelTurn < 0) ? 9 : 8);
+            run_function_on_non_blocking_thread(&runDialogOptionMouseClickHandlerFunc);
+
+            if (!new_custom_render)
+            {
+                if (runDialogOptionMouseClickHandlerFunc.atLeastOneImplementationExists)
+                    Redraw();
+                return true; // continue running loop
+            }
+        }
+      }
+
+      if (parserActivated) {
+        // They have selected a custom parser-based option
+        if (!parserInput->Text.IsEmpty() != 0) {
+          chose = DLG_OPTION_PARSER;
+          return false; // end dialog options running loop
+        }
+        else {
+          parserActivated = 0;
+          parserInput->IsActivated = 0;
+        }
+      }
+      if (mousewason != mouseison) {
+        //ags_domouse(DOMOUSE_DISABLE);
+        Redraw();
+        return true; // continue running loop
+      }
+      if (new_custom_render)
+      {
+        if (ccDialogOptionsRendering.chosenOptionID >= 0)
+        {
+            chose = ccDialogOptionsRendering.chosenOptionID;
+            ccDialogOptionsRendering.chosenOptionID = -1;
+            return false; // end dialog options running loop
+        }
+        if (ccDialogOptionsRendering.needRepaint)
+        {
+            Redraw();
+            return true; // continue running loop
+        }
+      }
+
+      update_polled_stuff_if_runtime();
+
+      if (play.fast_forward == 0)
+      {
+          WaitForNextFrame();
+      }
+
+      return true; // continue running loop
+}
+
+void DialogOptions::Close()
+{
+  ags_clear_input_buffer();
+  invalidate_screen();
+
+  if (parserActivated) 
+  {
+    strcpy (play.lastParserEntry, parserInput->Text);
+    ParseText (parserInput->Text);
+    chose = CHOSE_TEXTPARSER;
+  }
+
+  if (parserInput) {
+    delete parserInput;
+    parserInput = nullptr;
+  }
+
+  if (ddb != nullptr)
+    gfxDriver->DestroyDDB(ddb);
+  delete subBitmap;
+
+  set_mouse_cursor(curswas);
+  // In case it's the QFG4 style dialog, remove the black screen
+  play.in_conversation--;
+  remove_screen_overlay(OVER_COMPLETE);
+
+  delete tempScrn;
+}
+
+DialogOptions DlgOpt;
+
+int show_dialog_options(int _dlgnum, int sayChosenOption, bool _runGameLoopsInBackground) 
+{
+  DlgOpt.Prepare(_dlgnum, _runGameLoopsInBackground);
+  DlgOpt.Show();
+  DlgOpt.Close();  
+
+  int dialog_choice = DlgOpt.chose;
+  if (dialog_choice != CHOSE_TEXTPARSER)
+  {
+    DialogTopic *dialog_topic = DlgOpt.dtop;
+    int &option_flags = dialog_topic->optionflags[dialog_choice];
+    const char *option_name = DlgOpt.dtop->optionnames[dialog_choice];
+
+    option_flags |= DFLG_HASBEENCHOSEN;
+    bool sayTheOption = false;
+    if (sayChosenOption == SAYCHOSEN_YES)
+    {
+      sayTheOption = true;
+    }
+    else if (sayChosenOption == SAYCHOSEN_USEFLAG)
+    {
+      sayTheOption = ((option_flags & DFLG_NOREPEAT) == 0);
+    }
+
+    if (sayTheOption)
+      DisplaySpeech(get_translation(option_name), game.playercharacter);
+  }
+
+  return dialog_choice;
+}
+
+void do_conversation(int dlgnum) 
+{
+  EndSkippingUntilCharStops();
+
+  // AGS 2.x always makes the mouse cursor visible when displaying a dialog.
+  if (loaded_game_file_version <= kGameVersion_272)
+    play.mouse_cursor_hidden = 0;
+
+  int dlgnum_was = dlgnum;
+  int previousTopics[MAX_TOPIC_HISTORY];
+  int numPrevTopics = 0;
+  DialogTopic *dtop = &dialog[dlgnum];
+
+  // run the startup script
+  int tocar = run_dialog_script(dtop, dlgnum, dtop->startupentrypoint, 0);
+  if ((tocar == RUN_DIALOG_STOP_DIALOG) ||
+      (tocar == RUN_DIALOG_GOTO_PREVIOUS)) 
+  {
+    // 'stop' or 'goto-previous' from first startup script
+    remove_screen_overlay(OVER_COMPLETE);
+    play.in_conversation--;
+    return;
+  }
+  else if (tocar >= 0)
+    dlgnum = tocar;
+
+  while (dlgnum >= 0)
+  {
+    if (dlgnum >= game.numdialog)
+      quit("!RunDialog: invalid dialog number specified");
+
+    dtop = &dialog[dlgnum];
+
+    if (dlgnum != dlgnum_was) 
+    {
+      // dialog topic changed, so play the startup
+      // script for the new topic
+      tocar = run_dialog_script(dtop, dlgnum, dtop->startupentrypoint, 0);
+      dlgnum_was = dlgnum;
+      if (tocar == RUN_DIALOG_GOTO_PREVIOUS) {
+        if (numPrevTopics < 1) {
+          // goto-previous on first topic -- end dialog
+          tocar = RUN_DIALOG_STOP_DIALOG;
+        }
+        else {
+          tocar = previousTopics[numPrevTopics - 1];
+          numPrevTopics--;
+        }
+      }
+      if (tocar == RUN_DIALOG_STOP_DIALOG)
+        break;
+      else if (tocar >= 0) {
+        // save the old topic number in the history
+        if (numPrevTopics < MAX_TOPIC_HISTORY) {
+          previousTopics[numPrevTopics] = dlgnum;
+          numPrevTopics++;
+        }
+        dlgnum = tocar;
+        continue;
+      }
+    }
+
+    int chose = show_dialog_options(dlgnum, SAYCHOSEN_USEFLAG, (game.options[OPT_RUNGAMEDLGOPTS] != 0));
+
+    if (chose == CHOSE_TEXTPARSER)
+    {
+      said_speech_line = 0;
+  
+      tocar = run_dialog_request(dlgnum);
+
+      if (said_speech_line > 0) {
+        // fix the problem with the close-up face remaining on screen
+        DisableInterface();
+        UpdateGameOnce(); // redraw the screen to make sure it looks right
+        EnableInterface();
+        set_mouse_cursor(CURS_ARROW);
+      }
+    }
+    else 
+    {
+      tocar = run_dialog_script(dtop, dlgnum, dtop->entrypoints[chose], chose + 1);
+    }
+
+    if (tocar == RUN_DIALOG_GOTO_PREVIOUS) {
+      if (numPrevTopics < 1) {
+        tocar = RUN_DIALOG_STOP_DIALOG;
+      }
+      else {
+        tocar = previousTopics[numPrevTopics - 1];
+        numPrevTopics--;
+      }
+    }
+    if (tocar == RUN_DIALOG_STOP_DIALOG) break;
+    else if (tocar >= 0) {
+      // save the old topic number in the history
+      if (numPrevTopics < MAX_TOPIC_HISTORY) {
+        previousTopics[numPrevTopics] = dlgnum;
+        numPrevTopics++;
+      }
+      dlgnum = tocar;
+    }
+
+  }
+
+}
+
+// end dialog manager
+
+
+//=============================================================================
+//
+// Script API Functions
+//
+//=============================================================================
+
+#include "debug/out.h"
+#include "script/script_api.h"
+#include "script/script_runtime.h"
+#include "ac/dynobj/scriptstring.h"
+
+extern ScriptString myScriptStringImpl;
+
+// int (ScriptDialog *sd)
+RuntimeScriptValue Sc_Dialog_GetID(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptDialog, Dialog_GetID);
+}
+
+// int (ScriptDialog *sd)
+RuntimeScriptValue Sc_Dialog_GetOptionCount(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptDialog, Dialog_GetOptionCount);
+}
+
+// int (ScriptDialog *sd)
+RuntimeScriptValue Sc_Dialog_GetShowTextParser(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptDialog, Dialog_GetShowTextParser);
+}
+
+// int (ScriptDialog *sd, int sayChosenOption)
+RuntimeScriptValue Sc_Dialog_DisplayOptions(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT_PINT(ScriptDialog, Dialog_DisplayOptions);
+}
+
+// int (ScriptDialog *sd, int option)
+RuntimeScriptValue Sc_Dialog_GetOptionState(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT_PINT(ScriptDialog, Dialog_GetOptionState);
+}
+
+// const char* (ScriptDialog *sd, int option)
+RuntimeScriptValue Sc_Dialog_GetOptionText(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_OBJ_PINT(ScriptDialog, const char, myScriptStringImpl, Dialog_GetOptionText);
+}
+
+// int (ScriptDialog *sd, int option)
+RuntimeScriptValue Sc_Dialog_HasOptionBeenChosen(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT_PINT(ScriptDialog, Dialog_HasOptionBeenChosen);
+}
+
+RuntimeScriptValue Sc_Dialog_SetHasOptionBeenChosen(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT_PBOOL(ScriptDialog, Dialog_SetHasOptionBeenChosen);
+}
+
+// void (ScriptDialog *sd, int option, int newState)
+RuntimeScriptValue Sc_Dialog_SetOptionState(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT2(ScriptDialog, Dialog_SetOptionState);
+}
+
+// void (ScriptDialog *sd)
+RuntimeScriptValue Sc_Dialog_Start(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID(ScriptDialog, Dialog_Start);
+}
+
+void RegisterDialogAPI()
+{
+    ccAddExternalObjectFunction("Dialog::get_ID",               Sc_Dialog_GetID);
+    ccAddExternalObjectFunction("Dialog::get_OptionCount",      Sc_Dialog_GetOptionCount);
+    ccAddExternalObjectFunction("Dialog::get_ShowTextParser",   Sc_Dialog_GetShowTextParser);
+    ccAddExternalObjectFunction("Dialog::DisplayOptions^1",     Sc_Dialog_DisplayOptions);
+    ccAddExternalObjectFunction("Dialog::GetOptionState^1",     Sc_Dialog_GetOptionState);
+    ccAddExternalObjectFunction("Dialog::GetOptionText^1",      Sc_Dialog_GetOptionText);
+    ccAddExternalObjectFunction("Dialog::HasOptionBeenChosen^1", Sc_Dialog_HasOptionBeenChosen);
+    ccAddExternalObjectFunction("Dialog::SetHasOptionBeenChosen^2", Sc_Dialog_SetHasOptionBeenChosen);
+    ccAddExternalObjectFunction("Dialog::SetOptionState^2",     Sc_Dialog_SetOptionState);
+    ccAddExternalObjectFunction("Dialog::Start^0",              Sc_Dialog_Start);
+
+    /* ----------------------- Registering unsafe exports for plugins -----------------------*/
+
+    ccAddExternalFunctionForPlugin("Dialog::get_ID",               (void*)Dialog_GetID);
+    ccAddExternalFunctionForPlugin("Dialog::get_OptionCount",      (void*)Dialog_GetOptionCount);
+    ccAddExternalFunctionForPlugin("Dialog::get_ShowTextParser",   (void*)Dialog_GetShowTextParser);
+    ccAddExternalFunctionForPlugin("Dialog::DisplayOptions^1",     (void*)Dialog_DisplayOptions);
+    ccAddExternalFunctionForPlugin("Dialog::GetOptionState^1",     (void*)Dialog_GetOptionState);
+    ccAddExternalFunctionForPlugin("Dialog::GetOptionText^1",      (void*)Dialog_GetOptionText);
+    ccAddExternalFunctionForPlugin("Dialog::HasOptionBeenChosen^1", (void*)Dialog_HasOptionBeenChosen);
+    ccAddExternalFunctionForPlugin("Dialog::SetOptionState^2",     (void*)Dialog_SetOptionState);
+    ccAddExternalFunctionForPlugin("Dialog::Start^0",              (void*)Dialog_Start);
+}
diff --git a/engines/ags/engine/ac/dialog.h b/engines/ags/engine/ac/dialog.h
new file mode 100644
index 0000000000..93fcf4868c
--- /dev/null
+++ b/engines/ags/engine/ac/dialog.h
@@ -0,0 +1,39 @@
+//=============================================================================
+//
+// Adventure Game Studio (AGS)
+//
+// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
+// The full list of copyright holders can be found in the Copyright.txt
+// file, which is part of this source code distribution.
+//
+// The AGS source code is provided under the Artistic License 2.0.
+// A copy of this license can be found in the file License.txt and at
+// http://www.opensource.org/licenses/artistic-license-2.0.php
+//
+//=============================================================================
+//
+//
+//
+//=============================================================================
+#ifndef __AGS_EE_AC__DIALOG_H
+#define __AGS_EE_AC__DIALOG_H
+
+#include <vector>
+#include "ac/dynobj/scriptdialog.h"
+
+int  Dialog_GetID(ScriptDialog *sd);
+int  Dialog_GetOptionCount(ScriptDialog *sd);
+int  Dialog_GetShowTextParser(ScriptDialog *sd);
+const char* Dialog_GetOptionText(ScriptDialog *sd, int option);
+int  Dialog_DisplayOptions(ScriptDialog *sd, int sayChosenOption);
+int  Dialog_GetOptionState(ScriptDialog *sd, int option);
+int  Dialog_HasOptionBeenChosen(ScriptDialog *sd, int option);
+void Dialog_SetOptionState(ScriptDialog *sd, int option, int newState);
+void Dialog_Start(ScriptDialog *sd);
+
+void do_conversation(int dlgnum);
+int  show_dialog_options(int dlgnum, int sayChosenOption, bool runGameLoopsInBackground) ;
+
+extern ScriptDialog *scrDialog;
+
+#endif // __AGS_EE_AC__DIALOG_H
diff --git a/engines/ags/engine/ac/dialogoptionsrendering.cpp b/engines/ags/engine/ac/dialogoptionsrendering.cpp
new file mode 100644
index 0000000000..08f2e876ab
--- /dev/null
+++ b/engines/ags/engine/ac/dialogoptionsrendering.cpp
@@ -0,0 +1,332 @@
+//=============================================================================
+//
+// Adventure Game Studio (AGS)
+//
+// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
+// The full list of copyright holders can be found in the Copyright.txt
+// file, which is part of this source code distribution.
+//
+// The AGS source code is provided under the Artistic License 2.0.
+// A copy of this license can be found in the file License.txt and at
+// http://www.opensource.org/licenses/artistic-license-2.0.php
+//
+//=============================================================================
+
+#include "ac/dialog.h"
+#include "ac/dialogtopic.h"
+#include "ac/dialogoptionsrendering.h"
+#include "ac/gamestructdefines.h"
+#include "debug/debug_log.h"
+#include "script/runtimescriptvalue.h"
+#include "ac/dynobj/cc_dialog.h"
+
+extern DialogTopic *dialog;
+extern CCDialog ccDynamicDialog;
+
+// ** SCRIPT DIALOGOPTIONSRENDERING OBJECT
+
+void DialogOptionsRendering_Update(ScriptDialogOptionsRendering *dlgOptRender)
+{
+    dlgOptRender->needRepaint = true;
+}
+
+bool DialogOptionsRendering_RunActiveOption(ScriptDialogOptionsRendering *dlgOptRender)
+{
+    dlgOptRender->chosenOptionID = dlgOptRender->activeOptionID;
+    return dlgOptRender->chosenOptionID >= 0;
+}
+
+int DialogOptionsRendering_GetX(ScriptDialogOptionsRendering *dlgOptRender)
+{
+    return dlgOptRender->x;
+}
+
+void DialogOptionsRendering_SetX(ScriptDialogOptionsRendering *dlgOptRender, int newX)
+{
+    dlgOptRender->x = newX;
+}
+
+int DialogOptionsRendering_GetY(ScriptDialogOptionsRendering *dlgOptRender)
+{
+    return dlgOptRender->y;
+}
+
+void DialogOptionsRendering_SetY(ScriptDialogOptionsRendering *dlgOptRender, int newY)
+{
+    dlgOptRender->y = newY;
+}
+
+int DialogOptionsRendering_GetWidth(ScriptDialogOptionsRendering *dlgOptRender)
+{
+    return dlgOptRender->width;
+}
+
+void DialogOptionsRendering_SetWidth(ScriptDialogOptionsRendering *dlgOptRender, int newWidth)
+{
+    dlgOptRender->width = newWidth;
+}
+
+int DialogOptionsRendering_GetHeight(ScriptDialogOptionsRendering *dlgOptRender)
+{
+    return dlgOptRender->height;
+}
+
+void DialogOptionsRendering_SetHeight(ScriptDialogOptionsRendering *dlgOptRender, int newHeight)
+{
+    dlgOptRender->height = newHeight;
+}
+
+int DialogOptionsRendering_GetHasAlphaChannel(ScriptDialogOptionsRendering *dlgOptRender)
+{
+    return dlgOptRender->hasAlphaChannel;
+}
+
+void DialogOptionsRendering_SetHasAlphaChannel(ScriptDialogOptionsRendering *dlgOptRender, bool hasAlphaChannel)
+{
+    dlgOptRender->hasAlphaChannel = hasAlphaChannel;
+}
+
+int DialogOptionsRendering_GetParserTextboxX(ScriptDialogOptionsRendering *dlgOptRender)
+{
+    return dlgOptRender->parserTextboxX;
+}
+
+void DialogOptionsRendering_SetParserTextboxX(ScriptDialogOptionsRendering *dlgOptRender, int newX)
+{
+    dlgOptRender->parserTextboxX = newX;
+}
+
+int DialogOptionsRendering_GetParserTextboxY(ScriptDialogOptionsRendering *dlgOptRender)
+{
+    return dlgOptRender->parserTextboxY;
+}
+
+void DialogOptionsRendering_SetParserTextboxY(ScriptDialogOptionsRendering *dlgOptRender, int newY)
+{
+    dlgOptRender->parserTextboxY = newY;
+}
+
+int DialogOptionsRendering_GetParserTextboxWidth(ScriptDialogOptionsRendering *dlgOptRender)
+{
+    return dlgOptRender->parserTextboxWidth;
+}
+
+void DialogOptionsRendering_SetParserTextboxWidth(ScriptDialogOptionsRendering *dlgOptRender, int newWidth)
+{
+    dlgOptRender->parserTextboxWidth = newWidth;
+}
+
+ScriptDialog* DialogOptionsRendering_GetDialogToRender(ScriptDialogOptionsRendering *dlgOptRender)
+{
+    return &scrDialog[dlgOptRender->dialogID];
+}
+
+ScriptDrawingSurface* DialogOptionsRendering_GetSurface(ScriptDialogOptionsRendering *dlgOptRender)
+{
+    dlgOptRender->surfaceAccessed = true;
+    return dlgOptRender->surfaceToRenderTo;
+}
+
+int DialogOptionsRendering_GetActiveOptionID(ScriptDialogOptionsRendering *dlgOptRender)
+{
+    return dlgOptRender->activeOptionID + 1;
+}
+
+void DialogOptionsRendering_SetActiveOptionID(ScriptDialogOptionsRendering *dlgOptRender, int activeOptionID)
+{
+    int optionCount = dialog[scrDialog[dlgOptRender->dialogID].id].numoptions;
+    if ((activeOptionID < 0) || (activeOptionID > optionCount))
+        quitprintf("DialogOptionsRenderingInfo.ActiveOptionID: invalid ID specified for this dialog (specified %d, valid range: 1..%d)", activeOptionID, optionCount);
+
+    if (dlgOptRender->activeOptionID != activeOptionID - 1)
+    {
+        dlgOptRender->activeOptionID = activeOptionID - 1;
+        dlgOptRender->needRepaint = true;
+    }
+}
+
+//=============================================================================
+//
+// Script API Functions
+//
+//=============================================================================
+
+#include "debug/out.h"
+#include "script/script_api.h"
+#include "script/script_runtime.h"
+
+RuntimeScriptValue Sc_DialogOptionsRendering_Update(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID(ScriptDialogOptionsRendering, DialogOptionsRendering_Update);
+}
+
+RuntimeScriptValue Sc_DialogOptionsRendering_RunActiveOption(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_BOOL(ScriptDialogOptionsRendering, DialogOptionsRendering_RunActiveOption);
+}
+
+// int (ScriptDialogOptionsRendering *dlgOptRender)
+RuntimeScriptValue Sc_DialogOptionsRendering_GetActiveOptionID(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptDialogOptionsRendering, DialogOptionsRendering_GetActiveOptionID);
+}
+
+// void (ScriptDialogOptionsRendering *dlgOptRender, int activeOptionID)
+RuntimeScriptValue Sc_DialogOptionsRendering_SetActiveOptionID(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(ScriptDialogOptionsRendering, DialogOptionsRendering_SetActiveOptionID);
+}
+
+// ScriptDialog* (ScriptDialogOptionsRendering *dlgOptRender)
+RuntimeScriptValue Sc_DialogOptionsRendering_GetDialogToRender(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_OBJ(ScriptDialogOptionsRendering, ScriptDialog, ccDynamicDialog, DialogOptionsRendering_GetDialogToRender);
+}
+
+// int (ScriptDialogOptionsRendering *dlgOptRender)
+RuntimeScriptValue Sc_DialogOptionsRendering_GetHeight(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptDialogOptionsRendering, DialogOptionsRendering_GetHeight);
+}
+
+// void (ScriptDialogOptionsRendering *dlgOptRender, int newHeight)
+RuntimeScriptValue Sc_DialogOptionsRendering_SetHeight(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(ScriptDialogOptionsRendering, DialogOptionsRendering_SetHeight);
+}
+
+// int (ScriptDialogOptionsRendering *dlgOptRender)
+RuntimeScriptValue Sc_DialogOptionsRendering_GetParserTextboxX(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptDialogOptionsRendering, DialogOptionsRendering_GetParserTextboxX);
+}
+
+// void (ScriptDialogOptionsRendering *dlgOptRender, int newX)
+RuntimeScriptValue Sc_DialogOptionsRendering_SetParserTextboxX(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(ScriptDialogOptionsRendering, DialogOptionsRendering_SetParserTextboxX);
+}
+
+// int (ScriptDialogOptionsRendering *dlgOptRender)
+RuntimeScriptValue Sc_DialogOptionsRendering_GetParserTextboxY(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptDialogOptionsRendering, DialogOptionsRendering_GetParserTextboxY);
+}
+
+// void (ScriptDialogOptionsRendering *dlgOptRender, int newY)
+RuntimeScriptValue Sc_DialogOptionsRendering_SetParserTextboxY(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(ScriptDialogOptionsRendering, DialogOptionsRendering_SetParserTextboxY);
+}
+
+// int (ScriptDialogOptionsRendering *dlgOptRender)
+RuntimeScriptValue Sc_DialogOptionsRendering_GetParserTextboxWidth(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptDialogOptionsRendering, DialogOptionsRendering_GetParserTextboxWidth);
+}
+
+// void (ScriptDialogOptionsRendering *dlgOptRender, int newWidth)
+RuntimeScriptValue Sc_DialogOptionsRendering_SetParserTextboxWidth(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(ScriptDialogOptionsRendering, DialogOptionsRendering_SetParserTextboxWidth);
+}
+
+// ScriptDrawingSurface* (ScriptDialogOptionsRendering *dlgOptRender)
+RuntimeScriptValue Sc_DialogOptionsRendering_GetSurface(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_OBJAUTO(ScriptDialogOptionsRendering, ScriptDrawingSurface, DialogOptionsRendering_GetSurface);
+}
+
+// int (ScriptDialogOptionsRendering *dlgOptRender)
+RuntimeScriptValue Sc_DialogOptionsRendering_GetWidth(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptDialogOptionsRendering, DialogOptionsRendering_GetWidth);
+}
+
+// void (ScriptDialogOptionsRendering *dlgOptRender, int newWidth)
+RuntimeScriptValue Sc_DialogOptionsRendering_SetWidth(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(ScriptDialogOptionsRendering, DialogOptionsRendering_SetWidth);
+}
+
+// int (ScriptDialogOptionsRendering *dlgOptRender)
+RuntimeScriptValue Sc_DialogOptionsRendering_GetX(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptDialogOptionsRendering, DialogOptionsRendering_GetX);
+}
+
+// void (ScriptDialogOptionsRendering *dlgOptRender, int newX)
+RuntimeScriptValue Sc_DialogOptionsRendering_SetX(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(ScriptDialogOptionsRendering, DialogOptionsRendering_SetX);
+}
+
+// int (ScriptDialogOptionsRendering *dlgOptRender)
+RuntimeScriptValue Sc_DialogOptionsRendering_GetY(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptDialogOptionsRendering, DialogOptionsRendering_GetY);
+}
+
+// void (ScriptDialogOptionsRendering *dlgOptRender, int newY)
+RuntimeScriptValue Sc_DialogOptionsRendering_SetY(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PINT(ScriptDialogOptionsRendering, DialogOptionsRendering_SetY);
+}
+
+RuntimeScriptValue Sc_DialogOptionsRendering_GetHasAlphaChannel(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_INT(ScriptDialogOptionsRendering, DialogOptionsRendering_GetHasAlphaChannel);
+}
+
+RuntimeScriptValue Sc_DialogOptionsRendering_SetHasAlphaChannel(void *self, const RuntimeScriptValue *params, int32_t param_count)
+{
+    API_OBJCALL_VOID_PBOOL(ScriptDialogOptionsRendering, DialogOptionsRendering_SetHasAlphaChannel);
+}
+
+
+void RegisterDialogOptionsRenderingAPI()
+{
+    ccAddExternalObjectFunction("DialogOptionsRenderingInfo::Update^0",             Sc_DialogOptionsRendering_Update);
+    ccAddExternalObjectFunction("DialogOptionsRenderingInfo::RunActiveOption^0",    Sc_DialogOptionsRendering_RunActiveOption);
+    ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_ActiveOptionID",   Sc_DialogOptionsRendering_GetActiveOptionID);
+    ccAddExternalObjectFunction("DialogOptionsRenderingInfo::set_ActiveOptionID",   Sc_DialogOptionsRendering_SetActiveOptionID);
+    ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_DialogToRender",   Sc_DialogOptionsRendering_GetDialogToRender);
+    ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_Height",           Sc_DialogOptionsRendering_GetHeight);
+    ccAddExternalObjectFunction("DialogOptionsRenderingInfo::set_Height",           Sc_DialogOptionsRendering_SetHeight);
+    ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_ParserTextBoxX",   Sc_DialogOptionsRendering_GetParserTextboxX);
+    ccAddExternalObjectFunction("DialogOptionsRenderingInfo::set_ParserTextBoxX",   Sc_DialogOptionsRendering_SetParserTextboxX);
+    ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_ParserTextBoxY",   Sc_DialogOptionsRendering_GetParserTextboxY);
+    ccAddExternalObjectFunction("DialogOptionsRenderingInfo::set_ParserTextBoxY",   Sc_DialogOptionsRendering_SetParserTextboxY);
+    ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_ParserTextBoxWidth", Sc_DialogOptionsRendering_GetParserTextboxWidth);
+    ccAddExternalObjectFunction("DialogOptionsRenderingInfo::set_ParserTextBoxWidth", Sc_DialogOptionsRendering_SetParserTextboxWidth);
+    ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_Surface",          Sc_DialogOptionsRendering_GetSurface);
+    ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_Width",            Sc_DialogOptionsRendering_GetWidth);
+    ccAddExternalObjectFunction("DialogOptionsRenderingInfo::set_Width",            Sc_DialogOptionsRendering_SetWidth);
+    ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_X",                Sc_DialogOptionsRendering_GetX);
+    ccAddExternalObjectFunction("DialogOptionsRenderingInfo::set_X",                Sc_DialogOptionsRendering_SetX);
+    ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_Y",                Sc_DialogOptionsRendering_GetY);
+    ccAddExternalObjectFunction("DialogOptionsRenderingInfo::set_Y",                Sc_DialogOptionsRendering_SetY);
+    ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_HasAlphaChannel",  Sc_DialogOptionsRendering_GetHasAlphaChannel);
+    ccAddExternalObjectFunction("DialogOptionsRenderingInfo::set_HasAlphaChannel",  Sc_DialogOptionsRendering_SetHasAlphaChannel);
+
+    /* ----------------------- Registering unsafe exports for plugins -----------------------*/
+
+    ccAddExternalFunctionForPlugin("DialogOptionsRenderingInfo::get_ActiveOptionID",   (void*)DialogOptionsRendering_GetActiveOptionID);
+    ccAddExternalFunctionForPlugin("DialogOptionsRenderingInfo::set_ActiveOptionID",   (void*)DialogOptionsRendering_SetActiveOptionID);
+    ccAddExternalFunctionForPlugin("DialogOptionsRenderingInfo::get_DialogToRender",   (void*)DialogOptionsRendering_GetDialogToRender);
+    ccAddExternalFunctionForPlugin("DialogOptionsRenderingInfo::get_Height",           (void*)DialogOptionsRendering_GetHeight);
+    ccAddExternalFunctionForPlugin("DialogOptionsRenderingInfo::set_Height",           (void*)DialogOptionsRendering_SetHeight);
+    ccAddExternalFunctionForPlugin("DialogOptionsRenderingInfo::get_ParserTextBoxX",   (void*)DialogOptionsRendering_GetParserTextboxX);
+    ccAddExternalFunctionForPlugin("DialogOptionsRenderingInfo::set_ParserTextBoxX",   (void*)DialogOptionsRendering_SetParserTextboxX);
+    ccAddExternalFunctionForPlugin("DialogOptionsRenderingInfo::get_ParserTextBoxY",   (void*)DialogOptionsRendering_GetParserTextboxY);
+    ccAddExternalFunctionForPlugin("DialogOptionsRenderingInfo::set_ParserTextBoxY",   (void*)DialogOptionsRendering_SetParserTextboxY);
+    ccAddExternalFunctionForPlugin("DialogOptionsRenderingInfo::get_ParserTextBoxWidth", (void*)DialogOptionsRendering_GetParserTextboxWidth);
+    ccAddExternalFunctionForPlugin("DialogOptionsRenderingInfo::set_ParserTextBoxWidth", (void*)DialogOptionsRendering_SetParserTextboxWidth);
+    ccAddExternalFunctionForPlugin("DialogOptionsRenderingInfo::get_Surface",          (void*)DialogOptionsRendering_GetSurface);
+    ccAddExternalFunctionForPlugin("DialogOptionsRenderingInfo::get_Width",            (void*)DialogOptionsRendering_GetWidth);
+    ccAddExternalFunctionForPlugin("DialogOptionsRenderingInfo::set_Width",            (void*)DialogOptionsRendering_SetWidth);
+    ccAddExternalFunctionForPlugin("DialogOptionsRenderingInfo::get_X",                (void*)DialogOptionsRendering_GetX);
+    ccAddExternalFunctionForPlugin("DialogOptionsRenderingInfo::set_X",                (void*)DialogOptionsRendering_SetX);
+    ccAddExternalFunctionForPlugin("DialogOptionsRenderingInfo::get_Y",                (void*)DialogOptionsRendering_GetY);
+    ccAddExternalFunctionForPlugin("DialogOptionsRenderingInfo::set_Y",                (void*)DialogOptionsRendering_SetY);
+}
diff --git a/engines/ags/engine/ac/dialogoptionsrendering.h b/engines/ags/engine/ac/dialogoptionsrendering.h
new file mode 100644
index 0000000000..f08366df3d
--- /dev/null
+++ b/engines/ags/engine/ac/dialogoptionsrendering.h
@@ -0,0 +1,45 @@
+//=============================================================================
+//
+// Adventure Game Studio (AGS)
+//
+// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
+// The full list of copyright holders can be found in the Copyright.txt
+// file, which is part of this source code distribution.
+//
+// The AGS source code is provided under the Artistic License 2.0.
+// A copy of this license can be found in the file License.txt and at
+// http://www.opensource.org/licenses/artistic-license-2.0.php
+//
+//=============================================================================
+//
+//
+//
+//=============================================================================
+#ifndef __AGS_EE_AC__DIALOGOPTIONSRENDERING_H
+#define __AGS_EE_AC__DIALOGOPTIONSRENDERING_H
+
+#include "ac/dynobj/scriptdialog.h"
+#include "ac/dynobj/scriptdialogoptionsrendering.h"
+
+int  DialogOptionsRendering_GetX(ScriptDialogOptionsRendering *dlgOptRender);
+void DialogOptionsRendering_SetX(ScriptDialogOptionsRendering *dlgOptRender, int newX);
+int  DialogOptionsRendering_GetY(ScriptDialogOptionsRendering *dlgOptRender);
+void DialogOptionsRendering_SetY(ScriptDialogOptionsRendering *dlgOptRender, int newY);
+int  DialogOptionsRendering_GetWidth(ScriptDialogOptionsRendering *dlgOptRender);
+void DialogOptionsRendering_SetWidth(ScriptDialogOptionsRendering *dlgOptRender, int newWidth);
+int  DialogOptionsRendering_GetHeight(ScriptDialogOptionsRendering *dlgOptRender);
+void DialogOptionsRendering_SetHeight(ScriptDialogOptionsRendering *dlgOptRender, int newHeight);
+int  DialogOptionsRendering_GetHasAlphaChannel(ScriptDialogOptionsRendering *dlgOptRender);
+void DialogOptionsRendering_SetHasAlphaChannel(ScriptDialogOptionsRendering *dlgOptRender, bool hasAlphaChannel);
+int  DialogOptionsRendering_GetParserTextboxX(ScriptDialogOptionsRendering *dlgOptRender);
+void DialogOptionsRendering_SetParserTextboxX(ScriptDialogOptionsRendering *dlgOptRender, int newX);
+int  DialogOptionsRendering_GetParserTextboxY(ScriptDialogOptionsRendering *dlgOptRender);
+void DialogOptionsRendering_SetParserTextboxY(ScriptDialogOptionsRendering *dlgOptRender, int newY);
+int  DialogOptionsRendering_GetParserTextboxWidth(ScriptDialogOptionsRendering *dlgOptRender);
+void DialogOptionsRendering_SetParserTextboxWidth(ScriptDialogOptionsRendering *dlgOptRender, int newWidth);
+ScriptDialog* DialogOptionsRendering_GetDialogToRender(ScriptDialogOptionsRendering *dlgOptRender);
+ScriptDrawingSurface* DialogOptionsRendering_GetSurface(ScriptDialogOptionsRendering *dlgOptRender);
+int  DialogOptionsRendering_GetActiveOptionID(ScriptDialogOptionsRendering *dlgOptRender);
+void DialogOptionsRendering_SetActiveOptionID(ScriptDialogOptionsRendering *dlgOptRender, int activeOptionID);
+
+#endif // __AGS_EE_AC__DIALOGOPTIONSRENDERING_H
diff --git a/engines/ags/engine/ac/display.cpp b/engines/ags/engine/ac/display.cpp
new file mode 100644
index 0000000000..f31db06414
--- /dev/null
+++ b/engines/ags/engine/ac/display.cpp
@@ -0,0 +1,832 @@
+//=============================================================================
+//
+// Adventure Game Studio (AGS)
+//
+// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
+// The full list of copyright holders can be found in the Copyright.txt
+// file, which is part of this source code distribution.
+//
+// The AGS source code is provided under the Artistic License 2.0.
+// A copy of this license can be found in the file License.txt and at
+// http://www.opensource.org/licenses/artistic-license-2.0.php
+//
+//=============================================================================
+
+#include <math.h>
+
+#include "ac/display.h"
+#include "ac/common.h"
+#include "font/agsfontrenderer.h"
+#include "font/fonts.h"
+#include "ac/character.h"
+#include "ac/draw.h"
+#include "ac/game.h"
+#include "ac/gamesetupstruct.h"
+#include "ac/gamestate.h"
+#include "ac/global_audio.h"
+#include "ac/global_game.h"
+#include "ac/gui.h"
+#include "ac/mouse.h"
+#include "ac/overlay.h"
+#include "ac/sys_events.h"
+#include "ac/screenoverlay.h"
+#include "ac/speech.h"
+#include "ac/string.h"
+#include "ac/system.h"
+#include "ac/topbarsettings.h"
+#include "debug/debug_log.h"
+#include "gfx/blender.h"
+#include "gui/guibutton.h"
+#include "gui/guimain.h"
+#include "main/game_run.h"
+#include "platform/base/agsplatformdriver.h"
+#include "ac/spritecache.h"
+#include "gfx/gfx_util.h"
+#include "util/string_utils.h"
+#include "ac/mouse.h"
+#include "media/audio/audio_system.h"
+#include "ac/timer.h"
+
+using namespace AGS::Common;
+using namespace AGS::Common::BitmapHelper;
+
+extern GameState play;
+extern GameSetupStruct game;
+extern int longestline;
+extern AGSPlatformDriver *platform;
+extern int loops_per_character;
+extern SpriteCache spriteset;
+
+int display_message_aschar=0;
+
+
+TopBarSettings topBar;
+struct DisplayVars
+{
+    int lineheight;    // font's height of single line
+    int linespacing;   // font's line spacing
+    int fulltxtheight; // total height of all the text
+} disp;
+
+// Pass yy = -1 to find Y co-ord automatically
+// allowShrink = 0 for none, 1 for leftwards, 2 for rightwards
+// pass blocking=2 to create permanent overlay
+int _display_main(int xx, int yy, int wii, const char *text, int disp_type, int usingfont, int asspch, int isThought, int allowShrink, bool overlayPositionFixed) 
+{
+    const bool use_speech_textwindow = (asspch < 0) && (game.options[OPT_SPEECHTYPE] >= 2);
+    const bool use_thought_gui = (isThought) && (game.options[OPT_THOUGHTGUI] > 0);
+
+    bool alphaChannel = false;
+    char todis[STD_BUFFER_SIZE];
+    snprintf(todis, STD_BUFFER_SIZE - 1, "%s", text);
+    int usingGui = -1;
+    if (use_speech_textwindow)
+	    usingGui = play.speech_textwindow_gui;
+    else if (use_thought_gui)
+	    usingGui = game.options[OPT_THOUGHTGUI];
+
+    int padding = get_textwindow_padding(usingGui);
+    int paddingScaled = get_fixed_pixel_size(padding);
+    int paddingDoubledScaled = get_fixed_pixel_size(padding * 2); // Just in case screen size does is not neatly divisible by 320x200
+
+    ensure_text_valid_for_font(todis, usingfont);
+    break_up_text_into_lines(todis, Lines, wii-2*padding, usingfont);
+    disp.lineheight = getfontheight_outlined(usingfont);
+    disp.linespacing= getfontspacing_outlined(usingfont);
+    disp.fulltxtheight = getheightoflines(usingfont, Lines.Count());
+
+    // AGS 2.x: If the screen is faded out, fade in again when displaying a message box.
+    if (!asspch && (loaded_game_file_version <= kGameVersion_272))
+        play.screen_is_faded_out = 0;
+
+    // if it's a normal message box and the game was being skipped,
+    // ensure that the screen is up to date before the message box
+    // is drawn on top of it
+    // TODO: is this really necessary anymore?
+    if ((play.skip_until_char_stops >= 0) && (disp_type == DISPLAYTEXT_MESSAGEBOX))
+        render_graphics();
+
+    EndSkippingUntilCharStops();
+
+    if (topBar.wantIt) {
+        // ensure that the window is wide enough to display
+        // any top bar text
+        int topBarWid = wgettextwidth_compensate(topBar.text, topBar.font);
+        topBarWid += data_to_game_coord(play.top_bar_borderwidth + 2) * 2;
+        if (longestline < topBarWid)
+            longestline = topBarWid;
+        // the top bar should behave like DisplaySpeech wrt blocking
+        disp_type = DISPLAYTEXT_SPEECH;
+    }
+
+    if (asspch > 0) {
+        // update the all_buttons_disabled variable in advance
+        // of the adjust_x/y_for_guis calls
+        play.disabled_user_interface++;
+        update_gui_disabled_status();
+        play.disabled_user_interface--;
+    }
+
+    const Rect &ui_view = play.GetUIViewport();
+    if (xx == OVR_AUTOPLACE) ;
+    // centre text in middle of screen
+    else if (yy<0) yy= ui_view.GetHeight()/2-disp.fulltxtheight/2-padding;
+    // speech, so it wants to be above the character's head
+    else if (asspch > 0) {
+        yy-=disp.fulltxtheight;
+        if (yy < 5) yy=5;
+        yy = adjust_y_for_guis (yy);
+    }
+
+    if (longestline < wii - paddingDoubledScaled) {
+        // shrink the width of the dialog box to fit the text
+        int oldWid = wii;
+        //if ((asspch >= 0) || (allowShrink > 0))
+        // If it's not speech, or a shrink is allowed, then shrink it
+        if ((asspch == 0) || (allowShrink > 0))
+            wii = longestline + paddingDoubledScaled;
+
+        // shift the dialog box right to align it, if necessary
+        if ((allowShrink == 2) && (xx >= 0))
+            xx += (oldWid - wii);
+    }
+
+    if (xx<-1) { 
+        xx=(-xx)-wii/2;
+        if (xx < 0)
+            xx = 0;
+
+        xx = adjust_x_for_guis (xx, yy);
+
+        if (xx + wii >= ui_view.GetWidth())
+            xx = (ui_view.GetWidth() - wii) - 5;
+    }
+    else if (xx<0) xx= ui_view.GetWidth()/2-wii/2;
+
+    int extraHeight = paddingDoubledScaled;
+    color_t text_color = MakeColor(15);
+    if (disp_type < DISPLAYTEXT_NORMALOVERLAY)
+        remove_screen_overlay(OVER_TEXTMSG); // remove any previous blocking texts
+
+    Bitmap *text_window_ds = BitmapHelper::CreateTransparentBitmap((wii > 0) ? wii : 2, disp.fulltxtheight + extraHeight, game.GetColorDepth());
+
+    // inform draw_text_window to free the old bitmap
+    const bool wantFreeScreenop = true;
+
+    //
+    // Creating displayed graphic
+    //
+    // may later change if usingGUI, needed to avoid changing original coordinates
+    int adjustedXX = xx;
+    int adjustedYY = yy;
+
+    if ((strlen (todis) < 1) || (strcmp (todis, "  ") == 0) || (wii == 0)) ;
+    // if it's an empty speech line, don't draw anything
+    else if (asspch) { //text_color = ds->GetCompatibleColor(12);
+        int ttxleft = 0, ttxtop = paddingScaled, oriwid = wii - padding * 2;
+        int drawBackground = 0;
+
+        if (use_speech_textwindow) {
+            drawBackground = 1;
+        }
+        else if (use_thought_gui) {
+            // make it treat it as drawing inside a window now
+            if (asspch > 0)
+                asspch = -asspch;
+            drawBackground = 1;
+        }
+
+        if (drawBackground)
+        {
+            draw_text_window_and_bar(&text_window_ds, wantFreeScreenop, &ttxleft, &ttxtop, &adjustedXX, &adjustedYY, &wii, &text_color, 0, usingGui);
+            if (usingGui > 0)
+            {
+                alphaChannel = guis[usingGui].HasAlphaChannel();
+            }
+        }
+        else if ((ShouldAntiAliasText()) && (game.GetColorDepth() >= 24))
+            alphaChannel = true;
+
+        for (size_t ee=0;ee<Lines.Count();ee++) {
+            //int ttxp=wii/2 - wgettextwidth_compensate(lines[ee], usingfont)/2;
+            int ttyp=ttxtop+ee*disp.linespacing;
+            // asspch < 0 means that it's inside a text box so don't
+            // centre the text
+            if (asspch < 0) {
+                if ((usingGui >= 0) && 
+                    ((game.options[OPT_SPEECHTYPE] >= 2) || (isThought)))
+                    text_color = text_window_ds->GetCompatibleColor(guis[usingGui].FgColor);
+                else
+                    text_color = text_window_ds->GetCompatibleColor(-asspch);
+
+                wouttext_aligned(text_window_ds, ttxleft, ttyp, oriwid, usingfont, text_color, Lines[ee], play.text_align);
+            }
+            else {
+                text_color = text_window_ds->GetCompatibleColor(asspch);
+                wouttext_aligned(text_window_ds, ttxleft, ttyp, wii, usingfont, text_color, Lines[ee], play.speech_text_align);
+            }
+        }
+    }
+    else {
+        int xoffs,yoffs, oriwid = wii - padding * 2;
+        draw_text_window_and_bar(&text_window_ds, wantFreeScreenop, &xoffs,&yoffs,&xx,&yy,&wii,&text_color);
+
+        if (game.options[OPT_TWCUSTOM] > 0)
+        {
+            alphaChannel = guis[game.options[OPT_TWCUSTOM]].HasAlphaChannel();
+        }
+
+        adjust_y_coordinate_for_text(&yoffs, usingfont);
+
+        for (size_t ee=0;ee<Lines.Count();ee++)
+            wouttext_aligned (text_window_ds, xoffs, yoffs + ee * disp.linespacing, oriwid, usingfont, text_color, Lines[ee], play.text_align);
+    }
+
+    int ovrtype = OVER_TEXTMSG;
+    if (disp_type == DISPLAYTEXT_NORMALOVERLAY) ovrtype=OVER_CUSTOM;
+    else if (disp_type >= OVER_CUSTOM) ovrtype = disp_type;
+
+    int nse = add_screen_overlay(xx, yy, ovrtype, text_window_ds, adjustedXX - xx, adjustedYY - yy, alphaChannel);
+    // we should not delete text_window_ds here, because it is now owned by Overlay
+
+    if (disp_type >= DISPLAYTEXT_NORMALOVERLAY) {
+        return screenover[nse].type;
+    }
+
+    //
+    // Wait for the blocking text to timeout or until skipped by another command
+    //
+    if (disp_type == DISPLAYTEXT_MESSAGEBOX) {
+        // If fast-forwarding, then skip immediately
+        if (play.fast_forward) {
+            remove_screen_overlay(OVER_TEXTMSG);
+            play.messagetime=-1;
+            return 0;
+        }
+
+        if (!play.mouse_cursor_hidden)
+            ags_domouse(DOMOUSE_ENABLE);
+        int countdown = GetTextDisplayTime (todis);
+        int skip_setting = user_to_internal_skip_speech((SkipSpeechStyle)play.skip_display);
+        // Loop until skipped
+        while (true) {
+            update_audio_system_on_game_loop();
+            render_graphics();
+            int mbut, mwheelz;
+            if (run_service_mb_controls(mbut, mwheelz) && mbut >= 0) {
+                check_skip_cutscene_mclick(mbut);
+                if (play.fast_forward)
+                    break;
+                if (skip_setting & SKIP_MOUSECLICK && !play.IsIgnoringInput())
+                    break;
+            }
+            int kp;
+            if (run_service_key_controls(kp)) {
+                check_skip_cutscene_keypress (kp);
+                if (play.fast_forward)
+                    break;
+                if ((skip_setting & SKIP_KEYPRESS) && !play.IsIgnoringInput())
+                    break;
+            }
+            
+            update_polled_stuff_if_runtime();
+
+            if (play.fast_forward == 0)
+            {
+                WaitForNextFrame();
+            }
+
+            countdown--;
+
+            // Special behavior when coupled with a voice-over
+            if (play.speech_has_voice) {
+                // extend life of text if the voice hasn't finished yet
+                if (channel_is_playing(SCHAN_SPEECH) && (play.fast_forward == 0)) {
+                    if (countdown <= 1)
+                        countdown = 1;
+                }
+                else  // if the voice has finished, remove the speech
+                    countdown = 0;
+            }
+            // Test for the timed auto-skip
+            if ((countdown < 1) && (skip_setting & SKIP_AUTOTIMER))
+            {
+                play.SetIgnoreInput(play.ignore_user_input_after_text_timeout_ms);
+                break;
+            }
+            // if skipping cutscene, don't get stuck on No Auto Remove text boxes
+            if ((countdown < 1) && (play.fast_forward))
+                break;
+        }
+        if (!play.mouse_cursor_hidden)
+            ags_domouse(DOMOUSE_DISABLE);
+        remove_screen_overlay(OVER_TEXTMSG);
+        invalidate_screen();
+    }
+    else {
+        // if the speech does not time out, but we are skipping a cutscene,
+        // allow it to time out
+        if ((play.messagetime < 0) && (play.fast_forward))
+            play.messagetime = 2;
+
+        if (!overlayPositionFixed)
+        {
+            screenover[nse].positionRelativeToScreen = false;
+            VpPoint vpt = play.GetRoomViewport(0)->ScreenToRoom(screenover[nse].x, screenover[nse].y, false);
+            screenover[nse].x = vpt.first.X;
+            screenover[nse].y = vpt.first.Y;
+        }
+
+        GameLoopUntilNoOverlay();
+    }
+
+    play.messagetime=-1;
+    return 0;
+}
+
+void _display_at(int xx, int yy, int wii, const char *text, int disp_type, int asspch, int isThought, int allowShrink, bool overlayPositionFixed) {
+    int usingfont=FONT_NORMAL;
+    if (asspch) usingfont=FONT_SPEECH;
+    // TODO: _display_at may be called from _displayspeech, which can start
+    // and finalize voice speech on its own. Find out if we really need to
+    // keep track of this and not just stop voice regardless.
+    bool need_stop_speech = false;
+
+    EndSkippingUntilCharStops();
+
+    if (try_auto_play_speech(text, text, play.narrator_speech, true))
+    {// TODO: is there any need for this flag?
+        need_stop_speech = true;
+    }
+    _display_main(xx, yy, wii, text, disp_type, usingfont, asspch, isThought, allowShrink, overlayPositionFixed);
+
+    if (need_stop_speech)
+        stop_voice_speech();
+}
+
+bool try_auto_play_speech(const char *text, const char *&replace_text, int charid, bool blocking)
+{
+    const char *src = text;
+    if (src[0] != '&')
+        return false;
+
+    int sndid = atoi(&src[1]);
+    while ((src[0] != ' ') & (src[0] != 0)) src++;
+    if (src[0] == ' ') src++;
+    if (sndid <= 0)
+        quit("DisplaySpeech: auto-voice symbol '&' not followed by valid integer");
+
+    replace_text = src; // skip voice tag
+    if (play_voice_speech(charid, sndid))
+    {
+        // if Voice Only, then blank out the text
+        if (play.want_speech == 2)
+            replace_text = "  ";
+        return true;
+    }
+    return false;
+}
+
+// TODO: refactor this global variable out; currently it is set at the every get_translation call.
+// Be careful: a number of Say/Display functions expect it to be set beforehand.
+int source_text_length = -1;
+
+int GetTextDisplayLength(const char *text)
+{
+    int len = (int)strlen(text);
+    if ((text[0] == '&') && (play.unfactor_speech_from_textlength != 0))
+    {
+        // if there's an "&12 text" type line, remove "&12 " from the source length
+        size_t j = 0;
+        while ((text[j] != ' ') && (text[j] != 0))
+            j++;
+        j++;
+        len -= j;
+    }
+    return len;
+}
+
+int GetTextDisplayTime(const char *text, int canberel) {
+    int uselen = 0;
+    auto fpstimer = ::lround(get_current_fps());
+
+    // if it's background speech, make it stay relative to game speed
+    if ((canberel == 1) && (play.bgspeech_game_speed == 1))
+        fpstimer = 40;
+
+    if (source_text_length >= 0) {
+        // sync to length of original text, to make sure any animations
+        // and music sync up correctly
+        uselen = source_text_length;
+        source_text_length = -1;
+    }
+    else {
+        uselen = GetTextDisplayLength(text);
+    }
+
+    if (uselen <= 0)
+        return 0;
+
+    if (play.text_speed + play.text_speed_modifier <= 0)
+        quit("!Text speed is zero; unable to display text. Check your game.text_speed settings.");
+
+    // Store how many game loops per character of text
+    // This is calculated using a hard-coded 15 for the text speed,
+    // so that it's always the same no matter how fast the user
+    // can read.
+    loops_per_character = (((uselen/play.lipsync_speed)+1) * fpstimer) / uselen;
+
+    int textDisplayTimeInMS = ((uselen / (play.text_speed + play.text_speed_modifier)) + 1) * 1000;
+    if (textDisplayTimeInMS < play.text_min_display_time_ms)
+        textDisplayTimeInMS = play.text_min_display_time_ms;
+
+    return (textDisplayTimeInMS * fpstimer) / 1000;
+}
+
+bool ShouldAntiAliasText() {
+    return (game.options[OPT_ANTIALIASFONTS] != 0);
+}
+
+#if defined (AGS_FONTOUTLINE_MOREOPAQUE)
+// TODO: was suggested by fernewelten, but it's unclear whether is necessary
+// Make semi-transparent bits much more opaque
+void wouttextxy_AutoOutline_Semitransparent2Opaque(Bitmap *map)
+{
+    if (map->GetColorDepth() < 32)
+        return; // such maps don't feature partial transparency
+    size_t const width = map->GetWidth();
+    size_t const height = map->GetHeight();
+
+    for (size_t y = 0; y < height; y++)
+    {
+        int32 *sc_line = reinterpret_cast<int32 *>(map->GetScanLineForWriting(y));
+        for (size_t x = 0; x < width; x++)
+        {
+            int32 &px = sc_line[x];
+            int const transparency = geta(px);
+            if (0 < transparency && transparency < 255)
+                px = makeacol32(
+                    getr32(px), 
+                    getg32(px), 
+                    getb32(px), 
+                    std::min(85 + transparency * 2, 255));
+        }
+    }
+}
+#endif
+
+// Draw outline that is calculated from the text font, not derived from an outline font
+void wouttextxy_AutoOutline(Bitmap *ds, size_t font, int32_t color, const char *texx, int &xxp, int &yyp)
+{
+    int const thickness = game.fonts.at(font).AutoOutlineThickness;
+    auto const style = game.fonts.at(font).AutoOutlineStyle;
+    if (thickness <= 0)
+        return;
+
+    // 16-bit games should use 32-bit stencils to keep anti-aliasing working
+    int const  ds_cd = ds->GetColorDepth();
+    bool const antialias = ds_cd >= 16 && game.options[OPT_ANTIALIASFONTS] != 0 && !is_bitmap_font(font);
+    int const  stencil_cd = antialias ? 32 : ds_cd;
+    if (antialias) // This is to make sure TTFs render proper alpha channel in 16-bit games too
+        color |= makeacol32(0, 0, 0, 0xff);
+
+    size_t const t_width = wgettextwidth(texx, font);
+    size_t const t_height = wgettextheight(texx, font);
+    if (t_width == 0 || t_height == 0)
+        return;
+    Bitmap texx_stencil, outline_stencil;
+    texx_stencil.CreateTransparent(t_width, t_height, stencil_cd);
+    outline_stencil.CreateTransparent(t_width, t_height + 2 * thickness, stencil_cd);
+    if (outline_stencil.IsNull() || texx_stencil.IsNull())
+        return;
+    wouttextxy(&texx_stencil, 0, 0, font, color, texx);
+#if defined (AGS_FONTOUTLINE_MOREOPAQUE)
+    wouttextxy_AutoOutline_Semitransparent2Opaque(texx_stencil);
+#endif
+
+    void(Bitmap::*pfn_drawstencil)(Bitmap *src, int dst_x, int dst_y);
+    if (antialias)
+    { // NOTE: we must set out blender AFTER wouttextxy, or it will be overidden
+        set_argb2any_blender();
+        pfn_drawstencil = &Bitmap::TransBlendBlt;
+    }
+    else
+    {
+        pfn_drawstencil = &Bitmap::MaskedBlit;
+    }
+    
+    // move start of text so that the outline doesn't drop off the bitmap
+    xxp += thickness;
+    int const outline_y = yyp;
+    yyp += thickness;
+    
+    int largest_y_diff_reached_so_far = -1; 
+    for (int x_diff = thickness; x_diff >= 0; x_diff--)
+    {
+        // Integer arithmetics: In the following, we use terms k*(k + 1) to account for rounding.
+        //     (k + 0.5)^2 == k*k + 2*k*0.5 + 0.5^2 == k*k + k + 0.25 ==approx. k*(k + 1)
+        int y_term_limit = thickness * (thickness + 1);
+        if (FontInfo::kRounded == style)
+            y_term_limit -= x_diff * x_diff;
+
+        // extend the outline stencil to the top and bottom
+        for (int y_diff = largest_y_diff_reached_so_far + 1; 
+            y_diff <= thickness && y_diff * y_diff  <= y_term_limit; 
+            y_diff++)
+        {
+            (outline_stencil.*pfn_drawstencil)(&texx_stencil, 0, thickness - y_diff);
+            if (y_diff > 0)
+                (outline_stencil.*pfn_drawstencil)(&texx_stencil, 0, thickness + y_diff);
+            largest_y_diff_reached_so_far = y_diff;
+        }
+
+        // stamp the outline stencil to the left and right of the text
+        (ds->*pfn_drawstencil)(&outline_stencil, xxp - x_diff, outline_y);
+        if (x_diff > 0)
+            (ds->*pfn_drawstencil)(&outline_stencil, xxp + x_diff, outline_y);
+    }
+}
+
+// Draw an outline if requested, then draw the text on top 
+void wouttext_outline(Common::Bitmap *ds, int xxp, int yyp, int font, color_t text_color, const char *texx) 
+{    
+    size_t const text_font = static_cast<size_t>(font);
+    // Draw outline (a backdrop) if requested
+    color_t const outline_color = ds->GetCompatibleColor(play.speech_text_shadow);
+    int const outline_font = get_font_outline(font);
+    if (outline_font >= 0)
+        wouttextxy(ds, xxp, yyp, static_cast<size_t>(outline_font), outline_color, texx);
+    else if (outline_font == FONT_OUTLINE_AUTO)
+        wouttextxy_AutoOutline(ds, text_font, outline_color, texx, xxp, yyp);
+    else
+        ; // no outline
+
+    // Draw text on top
+    wouttextxy(ds, xxp, yyp, text_font, text_color, texx);
+}
+
+void wouttext_aligned(Bitmap *ds, int usexp, int yy, int oriwid, int usingfont, color_t text_color, const char *text, HorAlignment align) {
+
+    if (align & kMAlignHCenter)
+        usexp = usexp + (oriwid / 2) - (wgettextwidth_compensate(text, usingfont) / 2);
+    else if (align & kMAlignRight)
+        usexp = usexp + (oriwid - wgettextwidth_compensate(text, usingfont));
+
+    wouttext_outline(ds, usexp, yy, usingfont, text_color, (char *)text);
+}
+
+// Get outline's thickness addition to the font's width or height
+int get_outline_padding(int font)
+{
+    if (get_font_outline(font) == FONT_OUTLINE_AUTO) {
+        return get_font_outline_thickness(font) * 2;
+    }
+    return 0;
+}
+
+int getfontheight_outlined(int font)
+{
+    return getfontheight(font) + get_outline_padding(font);
+}
+
+int getfontspacing_outlined(int font)
+{
+    return use_default_linespacing(font) ?
+        getfontheight_outlined(font) :
+        getfontlinespacing(font);
+}
+
+int getfontlinegap(int font)
+{
+    return getfontspacing_outlined(font) - getfontheight_outlined(font);
+}
+
+int getheightoflines(int font, int numlines)
+{
+    return getfontspacing_outlined(font) * (numlines - 1) + getfontheight_outlined(font);
+}
+
+int wgettextwidth_compensate(const char *tex, int font)
+{
+    return wgettextwidth(tex, font) + get_outline_padding(font);
+}
+
+void do_corner(Bitmap *ds, int sprn, int x, int y, int offx, int offy) {
+    if (sprn<0) return;
+    if (spriteset[sprn] == nullptr)
+    {
+        sprn = 0;
+    }
+
+    x = x + offx * game.SpriteInfos[sprn].Width;
+    y = y + offy * game.SpriteInfos[sprn].Height;
+    draw_gui_sprite_v330(ds, sprn, x, y);
+}
+
+int get_but_pic(GUIMain*guo,int indx)
+{
+    int butid = guo->GetControlID(indx);
+    return butid >= 0 ? guibuts[butid].Image : 0;
+}
+
+void draw_button_background(Bitmap *ds, int xx1,int yy1,int xx2,int yy2,GUIMain*iep) {
+    color_t draw_color;
+    if (iep==nullptr) {  // standard window
+        draw_color = ds->GetCompatibleColor(15);
+        ds->FillRect(Rect(xx1,yy1,xx2,yy2), draw_color);
+        draw_color = ds->GetCompatibleColor(16);
+        ds->DrawRect(Rect(xx1,yy1,xx2,yy2), draw_color);
+        /*    draw_color = ds->GetCompatibleColor(opts.tws.backcol); ds->FillRect(Rect(xx1,yy1,xx2,yy2);
+        draw_color = ds->GetCompatibleColor(opts.tws.ds->GetTextColor()); ds->DrawRect(Rect(xx1+1,yy1+1,xx2-1,yy2-1);*/
+    }
+    else {
+        if (loaded_game_file_version < kGameVersion_262) // < 2.62
+        {
+            // Color 0 wrongly shows as transparent instead of black
+            // From the changelog of 2.62:
+            //  - Fixed text windows getting a black background if colour 0 was
+            //    specified, rather than being transparent.
+            if (iep->BgColor == 0)
+                iep->BgColor = 16;
+        }
+
+        if (iep->BgColor >= 0) draw_color = ds->GetCompatibleColor(iep->BgColor);
+        else draw_color = ds->GetCompatibleColor(0); // black backrgnd behind picture
+
+        if (iep->BgColor > 0)
+            ds->FillRect(Rect(xx1,yy1,xx2,yy2), draw_color);
+
+        int leftRightWidth = game.SpriteInfos[get_but_pic(iep,4)].Width;
+        int topBottomHeight = game.SpriteInfos[get_but_pic(iep,6)].Height;
+        if (iep->BgImage>0) {
+            if ((loaded_game_file_version <= kGameVersion_272) // 2.xx
+                && (spriteset[iep->BgImage]->GetWidth() == 1)
+                && (spriteset[iep->BgImage]->GetHeight() == 1) 
+                && (*((unsigned int*)spriteset[iep->BgImage]->GetData()) == 0x00FF00FF))
+            {
+                // Don't draw fully transparent dummy GUI backgrounds
+            }
+            else
+            {
+                // offset the background image and clip it so that it is drawn
+                // such that the border graphics can have a transparent outside
+                // edge
+                int bgoffsx = xx1 - leftRightWidth / 2;
+                int bgoffsy = yy1 - topBottomHeight / 2;
+                ds->SetClip(Rect(bgoffsx, bgoffsy, xx2 + leftRightWidth / 2, yy2 + topBottomHeight / 2));
+                int bgfinishx = xx2;
+                int bgfinishy = yy2;
+                int bgoffsyStart = bgoffsy;
+                while (bgoffsx <= bgfinishx)
+                {
+                    bgoffsy = bgoffsyStart;
+                    while (bgoffsy <= bgfinishy)
+                    {
+                        draw_gui_sprite_v330(ds, iep->BgImage, bgoffsx, bgoffsy);
+                        bgoffsy += game.SpriteInfos[iep->BgImage].Height;
+                    }
+                    bgoffsx += game.SpriteInfos[iep->BgImage].Width;
+                }
+                // return to normal clipping rectangle
+                ds->SetClip(Rect(0, 0, ds->GetWidth() - 1, ds->GetHeight() - 1));
+            }
+        }
+        int uu;
+        for (uu=yy1;uu <= yy2;uu+= game.SpriteInfos[get_but_pic(iep,4)].Height) {
+            do_corner(ds, get_but_pic(iep,4),xx1,uu,-1,0);   // left side
+            do_corner(ds, get_but_pic(iep,5),xx2+1,uu,0,0);  // right side
+        }
+        for (uu=xx1;uu <= xx2;uu+=game.SpriteInfos[get_but_pic(iep,6)].Width) {
+            do_corner(ds, get_but_pic(iep,6),uu,yy1,0,-1);  // top side
+            do_corner(ds, get_but_pic(iep,7),uu,yy2+1,0,0); // bottom side
+        }
+        do_corner(ds, get_but_pic(iep,0),xx1,yy1,-1,-1);  // top left
+        do_corner(ds, get_but_pic(iep,1),xx1,yy2+1,-1,0);  // bottom left
+        do_corner(ds, get_but_pic(iep,2),xx2+1,yy1,0,-1);  //  top right
+        do_corner(ds, get_but_pic(iep,3),xx2+1,yy2+1,0,0);  // bottom right
+    }
+}
+
+// Calculate the width that the left and right border of the textwindow
+// GUI take up
+int get_textwindow_border_width (int twgui) {
+    if (twgui < 0)
+        return 0;
+
+    if (!guis[twgui].IsTextWindow())
+        quit("!GUI set as text window but is not actually a text window GUI");
+
+    int borwid = game.SpriteInfos[get_but_pic(&guis[twgui], 4)].Width + 
+        game.SpriteInfos[get_but_pic(&guis[twgui], 5)].Width;
+
+    return borwid;
+}
+
+// get the hegiht of the text window's top border
+int get_textwindow_top_border_height (int twgui) {
+    if (twgui < 0)
+        return 0;
+
+    if (!guis[twgui].IsTextWindow())
+        quit("!GUI set as text window but is not actually a text window GUI");
+
+    return game.SpriteInfos[get_but_pic(&guis[twgui], 6)].Height;
+}
+
+// Get the padding for a text window
+// -1 for the game's custom text window
+int get_textwindow_padding(int ifnum) {
+    int result;
+
+    if (ifnum < 0)
+        ifnum = game.options[OPT_TWCUSTOM];
+    if (ifnum > 0 && ifnum < game.numgui)
+        result = guis[ifnum].Padding;
+    else
+        result = TEXTWINDOW_PADDING_DEFAULT;
+
+    return result;
+}
+
+void draw_text_window(Bitmap **text_window_ds, bool should_free_ds,
+                      int*xins,int*yins,int*xx,int*yy,int*wii, color_t *set_text_color, int ovrheight, int ifnum) {
+
+    Bitmap *ds = *text_window_ds;
+    if (ifnum < 0)
+        ifnum = game.options[OPT_TWCUSTOM];
+
+    if (ifnum <= 0) {
+        if (ovrheight)
+            quit("!Cannot use QFG4 style options without custom text window");
+        draw_button_background(ds, 0,0,ds->GetWidth() - 1,ds->GetHeight() - 1,nullptr);
+        if (set_text_color)
+            *set_text_color = ds->GetCompatibleColor(16);
+        xins[0]=3;
+        yins[0]=3;
+    }
+    else {
+        if (ifnum >= game.numgui)
+            quitprintf("!Invalid GUI %d specified as text window (total GUIs: %d)", ifnum, game.numgui);
+        if (!guis[ifnum].IsTextWindow())
+            quit("!GUI set as text window but is not actually a text window GUI");
+
+        int tbnum = get_but_pic(&guis[ifnum], 0);
+
+        wii[0] += get_textwindow_border_width (ifnum);
+        xx[0]-=game.SpriteInfos[tbnum].Width;
+        yy[0]-=game.SpriteInfos[tbnum].Height;
+        if (ovrheight == 0)
+            ovrheight = disp.fulltxtheight;
+
+        if (should_free_ds)
+            delete *text_window_ds;
+        int padding = get_textwindow_padding(ifnum);
+        *text_window_ds = BitmapHelper::CreateTransparentBitmap(wii[0],ovrheight+(padding*2)+ game.SpriteInfos[tbnum].Height*2,game.GetColorDepth());
+        ds = *text_window_ds;
+        int xoffs=game.SpriteInfos[tbnum].Width,yoffs= game.SpriteInfos[tbnum].Height;
+        draw_button_background(ds, xoffs,yoffs,(ds->GetWidth() - xoffs) - 1,(ds->GetHeight() - yoffs) - 1,&guis[ifnum]);
+        if (set_text_color)
+            *set_text_color = ds->GetCompatibleColor(guis[ifnum].FgColor);
+        xins[0]=xoffs+padding;
+        yins[0]=yoffs+padding;
+    }
+}
+
+void draw_text_window_and_bar(Bitmap **text_window_ds, bool should_free_ds,
+                              int*xins,int*yins,int*xx,int*yy,int*wii,color_t *set_text_color,int ovrheight, int ifnum) {
+
+    draw_text_window(text_window_ds, should_free_ds, xins, yins, xx, yy, wii, set_text_color, ovrheight, ifnum);
+
+    if ((topBar.wantIt) && (text_window_ds && *text_window_ds)) {
+        // top bar on the dialog window with character's name
+        // create an enlarged window, then free the old one
+        Bitmap *ds = *text_window_ds;
+        Bitmap *newScreenop = BitmapHelper::CreateBitmap(ds->GetWidth(), ds->GetHeight() + topBar.height, game.GetColorDepth());
+        newScreenop->Blit(ds, 0, 0, 0, topBar.height, ds->GetWidth(), ds->GetHeight());
+        delete *text_window_ds;
+        *text_window_ds = newScreenop;
+        ds = *text_window_ds;
+
+        // draw the top bar
+        color_t draw_color = ds->GetCompatibleColor(play.top_bar_backcolor);
+        ds->FillRect(Rect(0, 0, ds->GetWidth() - 1, topBar.height - 1), draw_color);
+        if (play.top_bar_backcolor != play.top_bar_bordercolor) {
+            // draw the border
+            draw_color = ds->GetCompatibleColor(play.top_bar_bordercolor);
+            for (int j = 0; j < data_to_game_coord(play.top_bar_borderwidth); j++)
+                ds->DrawRect(Rect(j, j, ds->GetWidth() - (j + 1), topBar.height - (j + 1)), draw_color);
+        }
+
+        // draw the text
+        int textx = (ds->GetWidth() / 2) - wgettextwidth_compensate(topBar.text, topBar.font) / 2;
+        color_t text_color = ds->GetCompatibleColor(play.top_bar_textcolor);
+        wouttext_outline(ds, textx, play.top_bar_borderwidth + get_fixed_pixel_size(1), topBar.font, text_color, topBar.text);
+
+        // don't draw it next time
+        topBar.wantIt = 0;
+        // adjust the text Y position
+        yins[0] += topBar.height;
+    }
+    else if (topBar.wantIt)
+        topBar.wantIt = 0;
+}
diff --git a/engines/ags/engine/ac/display.h b/engines/ags/engine/ac/display.h
new file mode 100644
index 0000000000..68b00bfdad
--- /dev/null
+++ b/engines/ags/engine/ac/display.h
@@ -0,0 +1,80 @@
+//=============================================================================
+//
+// Adventure Game Studio (AGS)
+//
+// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
+// The full list of copyright holders can be found in the Copyright.txt
+// file, which is part of this source code distribution.
+//
+// The AGS source code is provided under the Artistic License 2.0.
+// A copy of this license can be found in the file License.txt and at
+// http://www.opensource.org/licenses/artistic-license-2.0.php
+//
+//=============================================================================
+//
+//
+//
+//=============================================================================
+#ifndef __AGS_EE_AC__DISPLAY_H
+#define __AGS_EE_AC__DISPLAY_H
+
+#include "gui/guimain.h"
+
+using AGS::Common::GUIMain;
+
+// options for 'disp_type' parameter
+#define DISPLAYTEXT_SPEECH        0
+#define DISPLAYTEXT_MESSAGEBOX    1
+#define DISPLAYTEXT_NORMALOVERLAY 2
+// also accepts explicit overlay ID >= OVER_CUSTOM
+
+int  _display_main(int xx, int yy, int wii, const char *text, int disp_type, int usingfont, int asspch, int isThought, int allowShrink, bool overlayPositionFixed);
+void _display_at(int xx, int yy, int wii, const char *text, int disp_type, int asspch, int isThought, int allowShrink, bool overlayPositionFixed);
+// Tests the given string for the voice-over tags and plays cue clip for the given character;
+// will assign replacement string, which will be blank string if game is in "voice-only" mode
+// and clip was started, or string cleaned from voice-over tags which is safe to display on screen.
+// Returns whether voice-over clip was started successfully.
+bool try_auto_play_speech(const char *text, const char *&replace_text, int charid, bool blocking);
+bool ShouldAntiAliasText();
+// Calculates meaningful length of the displayed text
+int GetTextDisplayLength(const char *text);
+// Calculates number of game loops for displaying a text on screen
+int GetTextDisplayTime(const char *text, int canberel = 0);
+// Draw an outline if requested, then draw the text on top 
+void wouttext_outline(Common::Bitmap *ds, int xxp, int yyp, int usingfont, color_t text_color, const char *texx);
+void wouttext_aligned (Common::Bitmap *ds, int usexp, int yy, int oriwid, int usingfont, color_t text_color, const char *text, HorAlignment align);
+// TODO: GUI classes located in Common library do not make use of outlining,
+// need to find a way to make all code use same functions.
+// Get the maximal height of the given font, with corresponding outlining
+int getfontheight_outlined(int font);
+// Get line spacing for the given font, with possible outlining in mind
+int getfontspacing_outlined(int font);
+// Get the distance between bottom one one line and top of the next line (may be negative!)
+int getfontlinegap(int font);
+// Gets the total maximal height of the given number of lines printed with the given font
+int getheightoflines(int font, int numlines);
+// Get the maximal width of the given font, with corresponding outlining
+int wgettextwidth_compensate(const char *tex, int font);
+void do_corner(Common::Bitmap *ds, int sprn,int xx1,int yy1,int typx,int typy);
+// Returns the image of a button control on the GUI under given child index
+int get_but_pic(GUIMain*guo,int indx);
+void draw_button_background(Common::Bitmap *ds, int xx1,int yy1,int xx2,int yy2,GUIMain*iep);
+// Calculate the width that the left and right border of the textwindow
+// GUI take up
+int get_textwindow_border_width (int twgui);
+// get the hegiht of the text window's top border
+int get_textwindow_top_border_height (int twgui);
+// draw_text_window: draws the normal or custom text window
+// create a new bitmap the size of the window before calling, and
+//   point text_window_ds to it
+// returns text start x & y pos in parameters
+// Warning!: draw_text_window() and draw_text_window_and_bar() can create new text_window_ds
+void draw_text_window(Common::Bitmap **text_window_ds, bool should_free_ds, int*xins,int*yins,int*xx,int*yy,int*wii,color_t *set_text_color,int ovrheight, int ifnum);
+void draw_text_window_and_bar(Common::Bitmap **text_window_ds, bool should_free_ds,
+                              int*xins,int*yins,int*xx,int*yy,int*wii,color_t *set_text_color,int ovrheight=0, int ifnum=-1);
+int get_textwindow_padding(int ifnum);
+
+// The efficient length of the last source text prepared for display
+extern int source_text_length;
+
+#endif // __AGS_EE_AC__DISPLAY_H
diff --git a/engines/ags/engine/ac/draw.cpp b/engines/ags/engine/ac/draw.cpp
new file mode 100644
index 0000000000..fe24f1c453
--- /dev/null
+++ b/engines/ags/engine/ac/draw.cpp
@@ -0,0 +1,2563 @@
+//=============================================================================
+//
+// Adventure Game Studio (AGS)
+//
+// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
+// The full list of copyright holders can be found in the Copyright.txt
+// file, which is part of this source code distribution.
+//
+// The AGS source code is provided under the Artistic License 2.0.
+// A copy of this license can be found in the file License.txt and at
+// http://www.opensource.org/licenses/artistic-license-2.0.php
+//
+//=============================================================================
+
+#include <algorithm>
+#include <cmath>
+#include "aastr.h"
+#include "core/platform.h"
+#include "ac/common.h"
+#include "util/compress.h"
+#include "ac/view.h"
+#include "ac/charactercache.h"
+#include "ac/characterextras.h"
+#include "ac/characterinfo.h"
+#include "ac/display.h"
+#include "ac/draw.h"
+#include "ac/draw_software.h"
+#include "ac/gamesetup.h"
+#include "ac/gamesetupstruct.h"
+#include "ac/gamestate.h"
+#include "ac/global_game.h"
+#include "ac/global_gui.h"
+#include "ac/global_region.h"
+#include "ac/gui.h"
+#include "ac/mouse.h"
+#include "ac/objectcache.h"
+#include "ac/overlay.h"
+#include "ac/sys_events.h"
+#include "ac/roomobject.h"
+#include "ac/roomstatus.h"
+#include "ac/runtime_defines.h"
+#include "ac/screenoverlay.h"
+#include "ac/sprite.h"
+#include "ac/spritelistentry.h"
+#include "ac/string.h"
+#include "ac/system.h"
+#include "ac/viewframe.h"
+#include "ac/walkablearea.h"
+#include "ac/walkbehind.h"
+#include "ac/dynobj/scriptsystem.h"
+#include "debug/debugger.h"
+#include "debug/debug_log.h"
+#include "font/fonts.h"
+#include "gui/guimain.h"
+#include "platform/base/agsplatformdriver.h"
+#include "plugin/agsplugin.h"
+#include "plugin/plugin_engine.h"
+#include "ac/spritecache.h"
+#include "gfx/gfx_util.h"
+#include "gfx/graphicsdriver.h"
+#include "gfx/ali3dexception.h"
+#include "gfx/blender.h"
+#include "media/audio/audio_system.h"
+#include "ac/game.h"
+
+using namespace AGS::Common;
+using namespace AGS::Engine;
+
+#if AGS_PLATFORM_OS_ANDROID
+#include <sys/stat.h>
+#include <android/log.h>
+
+extern "C" void android_render();
+#endif
+
+#if AGS_PLATFORM_OS_IOS
+extern "C" void ios_render();
+#endif
+
+extern GameSetup usetup;
+extern GameSetupStruct game;
+extern GameState play;
+extern int convert_16bit_bgr;
+extern ScriptSystem scsystem;
+extern AGSPlatformDriver *platform;
+extern RoomStruct thisroom;
+extern char noWalkBehindsAtAll;
+extern unsigned int loopcounter;
+extern char *walkBehindExists;  // whether a WB area is in this column
+extern int *walkBehindStartY, *walkBehindEndY;
+extern int walkBehindLeft[MAX_WALK_BEHINDS], walkBehindTop[MAX_WALK_BEHINDS];
+extern int walkBehindRight[MAX_WALK_BEHINDS], walkBehindBottom[MAX_WALK_BEHINDS];
+extern IDriverDependantBitmap *walkBehindBitmap[MAX_WALK_BEHINDS];
+extern int walkBehindsCachedForBgNum;
+extern WalkBehindMethodEnum walkBehindMethod;
+extern int walk_behind_baselines_changed;
+extern SpriteCache spriteset;
+extern RoomStatus*croom;
+extern int our_eip;
+extern int in_new_room;
+extern RoomObject*objs;
+extern ViewStruct*views;
+extern CharacterCache *charcache;
+extern ObjectCache objcache[MAX_ROOM_OBJECTS];
+extern int displayed_room;
+extern CharacterExtras *charextra;
+extern CharacterInfo*playerchar;
+extern int eip_guinum;
+extern int is_complete_overlay;
+extern int cur_mode,cur_cursor;
+extern int mouse_frame,mouse_delay;
+extern int lastmx,lastmy;
+extern IDriverDependantBitmap *mouseCursor;
+extern int hotx,hoty;
+extern int bg_just_changed;
+
+color palette[256];
+
+COLOR_MAP maincoltable;
+
+IGraphicsDriver *gfxDriver;
+IDriverDependantBitmap *blankImage = nullptr;
+IDriverDependantBitmap *blankSidebarImage = nullptr;
+IDriverDependantBitmap *debugConsole = nullptr;
+
+// actsps is used for temporary storage of the bitamp image
+// of the latest version of the sprite
+int actSpsCount = 0;
+Bitmap **actsps;
+IDriverDependantBitmap* *actspsbmp;
+// temporary cache of walk-behind for this actsps image
+Bitmap **actspswb;
+IDriverDependantBitmap* *actspswbbmp;
+CachedActSpsData* actspswbcache;
+
+bool current_background_is_dirty = false;
+
+// Room background sprite
+IDriverDependantBitmap* roomBackgroundBmp = nullptr;
+// Buffer and info flags for viewport/camera pairs rendering in software mode
+struct RoomCameraDrawData
+{
+    // Intermediate bitmap for the software drawing method.
+    // We use this bitmap in case room camera has scaling enabled, we draw dirty room rects on it,
+    // and then pass to software renderer which draws sprite on top and then either blits or stretch-blits
+    // to the virtual screen.
+    // For more details see comment in ALSoftwareGraphicsDriver::RenderToBackBuffer().
+    PBitmap Buffer;      // this is the actual bitmap
+    PBitmap Frame;       // this is either same bitmap reference or sub-bitmap of virtual screen
+    bool    IsOffscreen; // whether room viewport was offscreen (cannot use sub-bitmap)
+    bool    IsOverlap;   // whether room viewport overlaps any others (marking dirty rects is complicated)
+};
+std::vector<RoomCameraDrawData> CameraDrawData;
+
+std::vector<SpriteListEntry> sprlist;
+std::vector<SpriteListEntry> thingsToDrawList;
+
+Bitmap **guibg = nullptr;
+IDriverDependantBitmap **guibgbmp = nullptr;
+
+
+Bitmap *debugConsoleBuffer = nullptr;
+
+// whether there are currently remnants of a DisplaySpeech
+bool screen_is_dirty = false;
+
+Bitmap *raw_saved_screen = nullptr;
+Bitmap *dynamicallyCreatedSurfaces[MAX_DYNAMIC_SURFACES];
+
+
+SpriteListEntry::SpriteListEntry()
+    : bmp(nullptr)
+    , pic(nullptr)
+    , baseline(0), x(0), y(0)
+    , transparent(0)
+    , takesPriorityIfEqual(false), hasAlphaChannel(false)
+{
+}
+
+void setpal() {
+    set_palette_range(palette, 0, 255, 0);
+}
+
+int _places_r = 3, _places_g = 2, _places_b = 3;
+
+// convert RGB to BGR for strange graphics cards
+Bitmap *convert_16_to_16bgr(Bitmap *tempbl) {
+
+    int x,y;
+    unsigned short c,r,ds,b;
+
+    for (y=0; y < tempbl->GetHeight(); y++) {
+        unsigned short*p16 = (unsigned short *)tempbl->GetScanLine(y);
+
+        for (x=0; x < tempbl->GetWidth(); x++) {
+            c = p16[x];
+            if (c != MASK_COLOR_16) {
+                b = _rgb_scale_5[c & 0x1F];
+                ds = _rgb_scale_6[(c >> 5) & 0x3F];
+                r = _rgb_scale_5[(c >> 11) & 0x1F];
+                // allegro assumes 5-6-5 for 16-bit
+                p16[x] = (((r >> _places_r) << _rgb_r_shift_16) |
+                    ((ds >> _places_g) << _rgb_g_shift_16) |
+                    ((b >> _places_b) << _rgb_b_shift_16));
+
+            }
+        }
+    }
+
+    return tempbl;
+}
+
+// PSP: convert 32 bit RGB to BGR.
+Bitmap *convert_32_to_32bgr(Bitmap *tempbl) {
+
+    int i = 0;
+    int j = 0;
+    unsigned char* current;
+    while (i < tempbl->GetHeight())
+    {
+        current = tempbl->GetScanLineForWriting(i);
+        while (j < tempbl->GetWidth())
+        {
+            current[0] ^= current[2];
+            current[2] ^= current[0];
+            current[0] ^= current[2];
+            current += 4;
+            j++;
+        }
+        i++;
+        j = 0;
+    }
+
+    return tempbl;
+}
+
+// NOTE: Some of these conversions are required  even when using
+// D3D and OpenGL rendering, for two reasons:
+// 1) certain raw drawing operations are still performed by software
+// Allegro methods, hence bitmaps should be kept compatible to any native
+// software operations, such as blitting two bitmaps of different formats.
+// 2) mobile ports feature an OpenGL renderer built in Allegro library,
+// that assumes native bitmaps are in OpenGL-compatible format, so that it
+// could copy them to texture without additional changes.
+// AGS own OpenGL renderer tries to sync its behavior with the former one.
+//
+// TODO: make gfxDriver->GetCompatibleBitmapFormat describe all necessary
+// conversions, so that we did not have to guess.
+//
+Bitmap *AdjustBitmapForUseWithDisplayMode(Bitmap* bitmap, bool has_alpha)
+{
+    const int bmp_col_depth = bitmap->GetColorDepth();
+    const int sys_col_depth = System_GetColorDepth();
+    const int game_col_depth = game.GetColorDepth();
+    Bitmap *new_bitmap = bitmap;
+
+    //
+    // The only special case when bitmap needs to be prepared for graphics driver
+    //
+    // In 32-bit display mode, 32-bit bitmaps may require component conversion
+    // to match graphics driver expectation about pixel format.
+    // TODO: make GetCompatibleBitmapFormat tell this somehow
+#if defined (AGS_INVERTED_COLOR_ORDER)
+    if (sys_col_depth > 16 && bmp_col_depth == 32)
+    {
+        // Convert RGB to BGR.
+        new_bitmap = convert_32_to_32bgr(bitmap);
+    }
+#endif
+
+    //
+    // The rest is about bringing bitmaps to the native game's format
+    // (has no dependency on display mode).
+    //
+    // In 32-bit game 32-bit bitmaps should have transparent pixels marked
+    // (this adjustment is probably needed for DrawingSurface ops)
+    if (game_col_depth == 32 && bmp_col_depth == 32)
+    {
+        if (has_alpha) 
+            set_rgb_mask_using_alpha_channel(new_bitmap);
+    }
+    // In 32-bit game hicolor bitmaps must be converted to the true color
+    else if (game_col_depth == 32 && (bmp_col_depth > 8 && bmp_col_depth <= 16))
+    {
+        new_bitmap = BitmapHelper::CreateBitmapCopy(bitmap, game_col_depth);
+    }
+    // In non-32-bit game truecolor bitmaps must be downgraded
+    else if (game_col_depth <= 16 && bmp_col_depth > 16)
+    {
+        if (has_alpha) // if has valid alpha channel, convert it to regular transparency mask
+            new_bitmap = remove_alpha_channel(bitmap);
+        else // else simply convert bitmap
+            new_bitmap = BitmapHelper::CreateBitmapCopy(bitmap, game_col_depth);
+    }
+    // Special case when we must convert 16-bit RGB to BGR
+    else if (convert_16bit_bgr == 1 && bmp_col_depth == 16)
+    {
+        new_bitmap = convert_16_to_16bgr(bitmap);
+    }
+    return new_bitmap;
+}
+
+Bitmap *ReplaceBitmapWithSupportedFormat(Bitmap *bitmap)
+{
+    Bitmap *new_bitmap = GfxUtil::ConvertBitmap(bitmap, gfxDriver->GetCompatibleBitmapFormat(bitmap->GetColorDepth()));
+    if (new_bitmap != bitmap)
+        delete bitmap;
+    return new_bitmap;
+}
+
+Bitmap *PrepareSpriteForUse(Bitmap* bitmap, bool has_alpha)
+{
+    bool must_switch_palette = bitmap->GetColorDepth() == 8 && game.GetColorDepth() > 8;
+    if (must_switch_palette)
+        select_palette(palette);
+
+    Bitmap *new_bitmap = AdjustBitmapForUseWithDisplayMode(bitmap, has_alpha);
+    if (new_bitmap != bitmap)
+        delete bitmap;
+    new_bitmap = ReplaceBitmapWithSupportedFormat(new_bitmap);
+
+    if (must_switch_palette)
+        unselect_palette();
+    return new_bitmap;
+}
+
+PBitmap PrepareSpriteForUse(PBitmap bitmap, bool has_alpha)
+{
+    bool must_switch_palette = bitmap->GetColorDepth() == 8 && System_GetColorDepth() > 8;
+    if (must_switch_palette)
+        select_palette(palette);
+
+    Bitmap *new_bitmap = AdjustBitmapForUseWithDisplayMode(bitmap.get(), has_alpha);
+    new_bitmap = ReplaceBitmapWithSupportedFormat(new_bitmap);
+
+    if (must_switch_palette)
+        unselect_palette();
+    return new_bitmap == bitmap.get() ? bitmap : PBitmap(new_bitmap); // if bitmap is same, don't create new smart ptr!
+}
+
+Bitmap *CopyScreenIntoBitmap(int width, int height, bool at_native_res)
+{
+    Bitmap *dst = new Bitmap(width, height, game.GetColorDepth());
+    GraphicResolution want_fmt;
+    // If the size and color depth are supported we may copy right into our bitmap
+    if (gfxDriver->GetCopyOfScreenIntoBitmap(dst, at_native_res, &want_fmt))
+        return dst;
+    // Otherwise we might need to copy between few bitmaps...
+    Bitmap *buf_screenfmt = new Bitmap(want_fmt.Width, want_fmt.Height, want_fmt.ColorDepth);
+    gfxDriver->GetCopyOfScreenIntoBitmap(buf_screenfmt, at_native_res);
+    // If at least size matches then we may blit
+    if (dst->GetSize() == buf_screenfmt->GetSize())
+    {
+        dst->Blit(buf_screenfmt);
+    }
+    // Otherwise we need to go through another bitmap of the matching format
+    else
+    {
+        Bitmap *buf_dstfmt = new Bitmap(buf_screenfmt->GetWidth(), buf_screenfmt->GetHeight(), dst->GetColorDepth());
+        buf_dstfmt->Blit(buf_screenfmt);
+        dst->StretchBlt(buf_dstfmt, RectWH(dst->GetSize()));
+        delete buf_dstfmt;
+    }
+    delete buf_screenfmt;
+    return dst;
+}
+
+
+// Begin resolution system functions
+
+// Multiplies up the number of pixels depending on the current 
+// resolution, to give a relatively fixed size at any game res
+AGS_INLINE int get_fixed_pixel_size(int pixels)
+{
+    return pixels * game.GetRelativeUIMult();
+}
+
+AGS_INLINE int data_to_game_coord(int coord)
+{
+    return coord * game.GetDataUpscaleMult();
+}
+
+AGS_INLINE void data_to_game_coords(int *x, int *y)
+{
+    const int mul = game.GetDataUpscaleMult();
+    x[0] *= mul;
+    y[0] *= mul;
+}
+
+AGS_INLINE void data_to_game_round_up(int *x, int *y)
+{
+    const int mul = game.GetDataUpscaleMult();
+    x[0] = x[0] * mul + (mul - 1);
+    y[0] = y[0] * mul + (mul - 1);
+}
+
+AGS_INLINE int game_to_data_coord(int coord)
+{
+    return coord / game.GetDataUpscaleMult();
+}
+
+AGS_INLINE void game_to_data_coords(int &x, int &y)
+{
+    const int mul = game.GetDataUpscaleMult();
+    x /= mul;
+    y /= mul;
+}
+
+AGS_INLINE int game_to_data_round_up(int coord)
+{
+    const int mul = game.GetDataUpscaleMult();
+    return (coord / mul) + (mul - 1);
+}
+
+AGS_INLINE void ctx_data_to_game_coord(int &x, int &y, bool hires_ctx)
+{
+    if (hires_ctx && !game.IsLegacyHiRes())
+    {
+        x /= HIRES_COORD_MULTIPLIER;
+        y /= HIRES_COORD_MULTIPLIER;
+    }
+    else if (!hires_ctx && game.IsLegacyHiRes())
+    {
+        x *= HIRES_COORD_MULTIPLIER;
+        y *= HIRES_COORD_MULTIPLIER;
+    }
+}
+
+AGS_INLINE void ctx_data_to_game_size(int &w, int &h, bool hires_ctx)
+{
+    if (hires_ctx && !game.IsLegacyHiRes())
+    {
+        w = Math::Max(1, (w / HIRES_COORD_MULTIPLIER));
+        h = Math::Max(1, (h / HIRES_COORD_MULTIPLIER));
+    }
+    else if (!hires_ctx && game.IsLegacyHiRes())
+    {
+        w *= HIRES_COORD_MULTIPLIER;
+        h *= HIRES_COORD_MULTIPLIER;
+    }
+}
+
+AGS_INLINE int ctx_data_to_game_size(int size, bool hires_ctx)
+{
+    if (hires_ctx && !game.IsLegacyHiRes())
+        return Math::Max(1, (size / HIRES_COORD_MULTIPLIER));
+    if (!hires_ctx && game.IsLegacyHiRes())
+        return size * HIRES_COORD_MULTIPLIER;
+    return size;
+}
+
+AGS_INLINE int game_to_ctx_data_size(int size, bool hires_ctx)
+{
+    if (hires_ctx && !game.IsLegacyHiRes())
+        return size * HIRES_COORD_MULTIPLIER;
+    else if (!hires_ctx && game.IsLegacyHiRes())
+        return Math::Max(1, (size / HIRES_COORD_MULTIPLIER));
+    return size;
+}
+
+AGS_INLINE void defgame_to_finalgame_coords(int &x, int &y)
+{ // Note we support only upscale now
+    x *= game.GetScreenUpscaleMult();
+    y *= game.GetScreenUpscaleMult();
+}
+
+// End resolution system functions
+
+// Create blank (black) images used to repaint borders around game frame
+void create_blank_image(int coldepth)
+{
+    // this is the first time that we try to use the graphics driver,
+    // so it's the most likey place for a crash
+    try
+    {
+        Bitmap *blank = BitmapHelper::CreateBitmap(16, 16, coldepth);
+        blank = ReplaceBitmapWithSupportedFormat(blank);
+        blank->Clear();
+        blankImage = gfxDriver->CreateDDBFromBitmap(blank, false, true);
+        blankSidebarImage = gfxDriver->CreateDDBFromBitmap(blank, false, true);
+        delete blank;
+    }
+    catch (Ali3DException gfxException)
+    {
+        quit((char*)gfxException._message);
+    }
+}
+
+void destroy_blank_image()
+{
+    if (blankImage)
+        gfxDriver->DestroyDDB(blankImage);
+    if (blankSidebarImage)
+        gfxDriver->DestroyDDB(blankSidebarImage);
+    blankImage = nullptr;
+    blankSidebarImage = nullptr;
+}
+
+int MakeColor(int color_index)
+{
+    color_t real_color = 0;
+    __my_setcolor(&real_color, color_index, game.GetColorDepth());
+    return real_color;
+}
+
+void init_draw_method()
+{
+    if (gfxDriver->HasAcceleratedTransform())
+    {
+        walkBehindMethod = DrawAsSeparateSprite;
+        create_blank_image(game.GetColorDepth());
+    }
+    else
+    {
+        walkBehindMethod = DrawOverCharSprite;
+    }
+
+    on_mainviewport_changed();
+    init_room_drawdata();
+    if (gfxDriver->UsesMemoryBackBuffer())
+        gfxDriver->GetMemoryBackBuffer()->Clear();
+}
+
+void dispose_draw_method()
+{
+    dispose_room_drawdata();
+    dispose_invalid_regions(false);
+    destroy_blank_image();
+}
+
+void dispose_room_drawdata()
+{
+    CameraDrawData.clear();
+    dispose_invalid_regions(true);
+}
+
+void on_mainviewport_changed()
+{
+    if (!gfxDriver->RequiresFullRedrawEachFrame())
+    {
+        init_invalid_regions(-1, play.GetMainViewport().GetSize(), RectWH(play.GetMainViewport().GetSize()));
+        if (game.GetGameRes().ExceedsByAny(play.GetMainViewport().GetSize()))
+            clear_letterbox_borders();
+    }
+}
+
+// Allocates a bitmap for rendering camera/viewport pair (software render mode)
+void prepare_roomview_frame(Viewport *view)
+{
+    const int view_index = view->GetID();
+    const Size view_sz = view->GetRect().GetSize();
+    const Size cam_sz = view->GetCamera()->GetRect().GetSize();
+    RoomCameraDrawData &draw_dat = CameraDrawData[view_index];
+    // We use intermediate bitmap to render camera/viewport pair in software mode under these conditions:
+    // * camera size and viewport size are different (this may be suboptimal to paint dirty rects stretched,
+    //   and also Allegro backend cannot stretch background of different colour depth).
+    // * viewport is located outside of the virtual screen (even if partially): subbitmaps cannot contain
+    //   regions outside of master bitmap, and we must not clamp surface size to virtual screen because
+    //   plugins may want to also use viewport bitmap, therefore it should retain full size.
+    if (cam_sz == view_sz && !draw_dat.IsOffscreen)
+    { // note we keep the buffer allocated in case it will become useful later
+        draw_dat.Frame.reset();
+    }
+    else
+    {
+        PBitmap &camera_frame = draw_dat.Frame;
+        PBitmap &camera_buffer = draw_dat.Buffer;
+        if (!camera_buffer || camera_buffer->GetWidth() < cam_sz.Width || camera_buffer->GetHeight() < cam_sz.Height)
+        {
+            // Allocate new buffer bitmap with an extra size in case they will want to zoom out
+            int room_width = data_to_game_coord(thisroom.Width);
+            int room_height = data_to_game_coord(thisroom.Height);
+            Size alloc_sz = Size::Clamp(cam_sz * 2, Size(1, 1), Size(room_width, room_height));
+            camera_buffer.reset(new Bitmap(alloc_sz.Width, alloc_sz.Height, gfxDriver->GetMemoryBackBuffer()->GetColorDepth()));
+        }
+
+        if (!camera_frame || camera_frame->GetSize() != cam_sz)
+        {
+            camera_frame.reset(BitmapHelper::CreateSubBitmap(camera_buffer.get(), RectWH(cam_sz)));
+        }
+    }
+}
+
+// Syncs room viewport and camera in case either size has changed
+void sync_roomview(Viewport *view)
+{
+    if (view->GetCamera() == nullptr)
+        return;
+    init_invalid_regions(view->GetID(), view->GetCamera()->GetRect().GetSize(), play.GetRoomViewportAbs(view->GetID()));
+    prepare_roomview_frame(view);
+}
+
+void init_room_drawdata()
+{
+    if (gfxDriver->RequiresFullRedrawEachFrame())
+        return;
+    // Make sure all frame buffers are created for software drawing
+    int view_count = play.GetRoomViewportCount();
+    CameraDrawData.resize(view_count);
+    for (int i = 0; i < play.GetRoomViewportCount(); ++i)
+        sync_roomview(play.GetRoomViewport(i).get());
+}
+
+void on_roomviewport_created(int index)
+{
+    if (!gfxDriver || gfxDriver->RequiresFullRedrawEachFrame())
+        return;
+    if ((size_t)index < CameraDrawData.size())
+        return;
+    CameraDrawData.resize(index + 1);
+}
+
+void on_roomviewport_deleted(int index)
+{
+    if (gfxDriver->RequiresFullRedrawEachFrame())
+        return;
+    CameraDrawData.erase(CameraDrawData.begin() + index);
+    delete_invalid_regions(index);
+}
+
+void on_roomviewport_changed(Viewport *view)
+{
+    if (gfxDriver->RequiresFullRedrawEachFrame())
+        return;
+    if (!view->IsVisible() || view->GetCamera() == nullptr)
+        return;
+    const bool off = !IsRectInsideRect(RectWH(gfxDriver->GetMemoryBackBuffer()->GetSize()), view->GetRect());
+    const bool off_changed = off != CameraDrawData[view->GetID()].IsOffscreen;
+    CameraDrawData[view->GetID()].IsOffscreen = off;
+    if (view->HasChangedSize())
+        sync_roomview(view);
+    else if (off_changed)
+        prepare_roomview_frame(view);
+    // TODO: don't have to do this all the time, perhaps do "dirty rect" method
+    // and only clear previous viewport location?
+    invalidate_screen();
+    gfxDriver->GetMemoryBackBuffer()->Clear();
+}
+
+void detect_roomviewport_overlaps(size_t z_index)
+{
+    if (gfxDriver->RequiresFullRedrawEachFrame())
+        return;
+    // Find out if we overlap or are overlapped by anything;
+    const auto &viewports = play.GetRoomViewportsZOrdered();
+    for (; z_index < viewports.size(); ++z_index)
+    {
+        auto this_view = viewports[z_index];
+        const int this_id = this_view->GetID();
+        bool is_overlap = false;
+        if (!this_view->IsVisible()) continue;
+        for (size_t z_index2 = 0; z_index2 < z_index; ++z_index)
+        {
+            if (!viewports[z_index2]->IsVisible()) continue;
+            if (AreRectsIntersecting(this_view->GetRect(), viewports[z_index2]->GetRect()))
+            {
+                is_overlap = true;
+                break;
+            }
+        }
+        if (CameraDrawData[this_id].IsOverlap != is_overlap)
+        {
+            CameraDrawData[this_id].IsOverlap = is_overlap;
+            prepare_roomview_frame(this_view.get());
+        }
+    }
+}
+
+void on_roomcamera_changed(Camera *cam)
+{
+    if (gfxDriver->RequiresFullRedrawEachFrame())
+        return;
+    if (cam->HasChangedSize())
+    {
+        auto viewrefs = cam->GetLinkedViewports();
+        for (auto vr : viewrefs)
+        {
+            PViewport vp = vr.lock();
+            if (vp)
+                sync_roomview(vp.get());
+        }
+    }
+    // TODO: only invalidate what this particular camera sees
+    invalidate_screen();
+}
+
+void mark_screen_dirty()
+{
+    screen_is_dirty = true;
+}
+
+bool is_screen_dirty()
+{
+    return screen_is_dirty;
+}
+
+void invalidate_screen()
+{
+    invalidate_all_rects();
+}
+
+void invalidate_camera_frame(int index)
+{
+    invalidate_all_camera_rects(index);
+}
+
+void invalidate_rect(int x1, int y1, int x2, int y2, bool in_room)
+{
+    //if (!in_room)
+    invalidate_rect_ds(x1, y1, x2, y2, in_room);
+}
+
+void invalidate_sprite(int x1, int y1, IDriverDependantBitmap *pic, bool in_room)
+{
+    //if (!in_room)
+    invalidate_rect_ds(x1, y1, x1 + pic->GetWidth(), y1 + pic->GetHeight(), in_room);
+}
+
+void mark_current_background_dirty()
+{
+    current_background_is_dirty = true;
+}
+
+
+void draw_and_invalidate_text(Bitmap *ds, int x1, int y1, int font, color_t text_color, const char *text)
+{
+    wouttext_outline(ds, x1, y1, font, text_color, (char*)text);
+    invalidate_rect(x1, y1, x1 + wgettextwidth_compensate(text, font), y1 + getfontheight_outlined(font) + get_fixed_pixel_size(1), false);
+}
+
+// Renders black borders for the legacy boxed game mode,
+// where whole game screen changes size between large and small rooms
+void render_black_borders()
+{
+    if (gfxDriver->UsesMemoryBackBuffer())
+        return;
+    {
+        gfxDriver->BeginSpriteBatch(RectWH(game.GetGameRes()), SpriteTransform());
+        const Rect &viewport = play.GetMainViewport();
+        if (viewport.Top > 0)
+        {
+            // letterbox borders
+            blankImage->SetStretch(game.GetGameRes().Width, viewport.Top, false);
+            gfxDriver->DrawSprite(0, 0, blankImage);
+            gfxDriver->DrawSprite(0, viewport.Bottom + 1, blankImage);
+        }
+        if (viewport.Left > 0)
+        {
+            // sidebar borders for widescreen
+            blankSidebarImage->SetStretch(viewport.Left, viewport.GetHeight(), false);
+            gfxDriver->DrawSprite(0, 0, blankSidebarImage);
+            gfxDriver->DrawSprite(viewport.Right + 1, 0, blankSidebarImage);
+        }
+    }
+}
+
+
+void render_to_screen()
+{
+    // Stage: final plugin callback (still drawn on game screen
+    if (pl_any_want_hook(AGSE_FINALSCREENDRAW))
+    {
+        gfxDriver->BeginSpriteBatch(play.GetMainViewport(), SpriteTransform(), Point(0, play.shake_screen_yoff), (GlobalFlipType)play.screen_flipped);
+        gfxDriver->DrawSprite(AGSE_FINALSCREENDRAW, 0, nullptr);
+    }
+    // Stage: engine overlay
+    construct_engine_overlay();
+
+    // only vsync in full screen mode, it makes things worse in a window
+    gfxDriver->EnableVsyncBeforeRender((scsystem.vsync > 0) && (!scsystem.windowed));
+
+    bool succeeded = false;
+    while (!succeeded)
+    {
+        try
+        {


Commit: bd6a58d1a1964f9fb097b5cb677f82e8ad01ea4c
    https://github.com/scummvm/scummvm/commit/bd6a58d1a1964f9fb097b5cb677f82e8ad01ea4c
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Adding ScummVM comment headers

Changed paths:
  R engines/ags/engine/main/main_allegro.cpp
    engines/ags/engine/ac/asset_helper.h
    engines/ags/engine/ac/audiochannel.cpp
    engines/ags/engine/ac/audiochannel.h
    engines/ags/engine/ac/audioclip.cpp
    engines/ags/engine/ac/audioclip.h
    engines/ags/engine/ac/button.cpp
    engines/ags/engine/ac/button.h
    engines/ags/engine/ac/cdaudio.cpp
    engines/ags/engine/ac/cdaudio.h
    engines/ags/engine/ac/character.cpp
    engines/ags/engine/ac/character.h
    engines/ags/engine/ac/charactercache.h
    engines/ags/engine/ac/characterextras.cpp
    engines/ags/engine/ac/characterextras.h
    engines/ags/engine/ac/characterinfo_engine.cpp
    engines/ags/engine/ac/datetime.cpp
    engines/ags/engine/ac/datetime.h
    engines/ags/engine/ac/dialog.cpp
    engines/ags/engine/ac/dialog.h
    engines/ags/engine/ac/dialogoptionsrendering.cpp
    engines/ags/engine/ac/dialogoptionsrendering.h
    engines/ags/engine/ac/display.cpp
    engines/ags/engine/ac/display.h
    engines/ags/engine/ac/draw.cpp
    engines/ags/engine/ac/draw.h
    engines/ags/engine/ac/draw_software.cpp
    engines/ags/engine/ac/draw_software.h
    engines/ags/engine/ac/drawingsurface.cpp
    engines/ags/engine/ac/drawingsurface.h
    engines/ags/engine/ac/dynamicsprite.cpp
    engines/ags/engine/ac/dynamicsprite.h
    engines/ags/engine/ac/dynobj/all_dynamicclasses.h
    engines/ags/engine/ac/dynobj/all_scriptclasses.h
    engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp
    engines/ags/engine/ac/dynobj/cc_agsdynamicobject.h
    engines/ags/engine/ac/dynobj/cc_audiochannel.cpp
    engines/ags/engine/ac/dynobj/cc_audiochannel.h
    engines/ags/engine/ac/dynobj/cc_audioclip.cpp
    engines/ags/engine/ac/dynobj/cc_audioclip.h
    engines/ags/engine/ac/dynobj/cc_character.cpp
    engines/ags/engine/ac/dynobj/cc_character.h
    engines/ags/engine/ac/dynobj/cc_dialog.cpp
    engines/ags/engine/ac/dynobj/cc_dialog.h
    engines/ags/engine/ac/dynobj/cc_dynamicarray.cpp
    engines/ags/engine/ac/dynobj/cc_dynamicarray.h
    engines/ags/engine/ac/dynobj/cc_dynamicobject.cpp
    engines/ags/engine/ac/dynobj/cc_dynamicobject.h
    engines/ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h
    engines/ags/engine/ac/dynobj/cc_gui.cpp
    engines/ags/engine/ac/dynobj/cc_gui.h
    engines/ags/engine/ac/dynobj/cc_guiobject.cpp
    engines/ags/engine/ac/dynobj/cc_guiobject.h
    engines/ags/engine/ac/dynobj/cc_hotspot.cpp
    engines/ags/engine/ac/dynobj/cc_hotspot.h
    engines/ags/engine/ac/dynobj/cc_inventory.cpp
    engines/ags/engine/ac/dynobj/cc_inventory.h
    engines/ags/engine/ac/dynobj/cc_object.cpp
    engines/ags/engine/ac/dynobj/cc_object.h
    engines/ags/engine/ac/dynobj/cc_region.cpp
    engines/ags/engine/ac/dynobj/cc_region.h
    engines/ags/engine/ac/dynobj/cc_serializer.cpp
    engines/ags/engine/ac/dynobj/cc_serializer.h
    engines/ags/engine/ac/dynobj/managedobjectpool.cpp
    engines/ags/engine/ac/dynobj/managedobjectpool.h
    engines/ags/engine/ac/dynobj/scriptaudiochannel.h
    engines/ags/engine/ac/dynobj/scriptcamera.cpp
    engines/ags/engine/ac/dynobj/scriptcamera.h
    engines/ags/engine/ac/dynobj/scriptcontainers.h
    engines/ags/engine/ac/dynobj/scriptdatetime.cpp
    engines/ags/engine/ac/dynobj/scriptdatetime.h
    engines/ags/engine/ac/dynobj/scriptdialog.h
    engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.cpp
    engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.h
    engines/ags/engine/ac/dynobj/scriptdict.cpp
    engines/ags/engine/ac/dynobj/scriptdict.h
    engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp
    engines/ags/engine/ac/dynobj/scriptdrawingsurface.h
    engines/ags/engine/ac/dynobj/scriptdynamicsprite.cpp
    engines/ags/engine/ac/dynobj/scriptdynamicsprite.h
    engines/ags/engine/ac/dynobj/scriptfile.cpp
    engines/ags/engine/ac/dynobj/scriptfile.h
    engines/ags/engine/ac/dynobj/scriptgui.h
    engines/ags/engine/ac/dynobj/scripthotspot.h
    engines/ags/engine/ac/dynobj/scriptinvitem.h
    engines/ags/engine/ac/dynobj/scriptmouse.h
    engines/ags/engine/ac/dynobj/scriptobject.h
    engines/ags/engine/ac/dynobj/scriptoverlay.cpp
    engines/ags/engine/ac/dynobj/scriptoverlay.h
    engines/ags/engine/ac/dynobj/scriptregion.h
    engines/ags/engine/ac/dynobj/scriptset.cpp
    engines/ags/engine/ac/dynobj/scriptset.h
    engines/ags/engine/ac/dynobj/scriptstring.cpp
    engines/ags/engine/ac/dynobj/scriptstring.h
    engines/ags/engine/ac/dynobj/scriptsystem.h
    engines/ags/engine/ac/dynobj/scriptuserobject.cpp
    engines/ags/engine/ac/dynobj/scriptuserobject.h
    engines/ags/engine/ac/dynobj/scriptviewframe.cpp
    engines/ags/engine/ac/dynobj/scriptviewframe.h
    engines/ags/engine/ac/dynobj/scriptviewport.cpp
    engines/ags/engine/ac/dynobj/scriptviewport.h
    engines/ags/engine/ac/event.cpp
    engines/ags/engine/ac/event.h
    engines/ags/engine/ac/file.cpp
    engines/ags/engine/ac/file.h
    engines/ags/engine/ac/game.cpp
    engines/ags/engine/ac/game.h
    engines/ags/engine/ac/gamesetup.cpp
    engines/ags/engine/ac/gamesetup.h
    engines/ags/engine/ac/gamestate.cpp
    engines/ags/engine/ac/gamestate.h
    engines/ags/engine/ac/global_api.cpp
    engines/ags/engine/ac/global_audio.cpp
    engines/ags/engine/ac/global_audio.h
    engines/ags/engine/ac/global_button.cpp
    engines/ags/engine/ac/global_button.h
    engines/ags/engine/ac/global_character.cpp
    engines/ags/engine/ac/global_character.h
    engines/ags/engine/ac/global_datetime.cpp
    engines/ags/engine/ac/global_datetime.h
    engines/ags/engine/ac/global_debug.cpp
    engines/ags/engine/ac/global_debug.h
    engines/ags/engine/ac/global_dialog.cpp
    engines/ags/engine/ac/global_dialog.h
    engines/ags/engine/ac/global_display.cpp
    engines/ags/engine/ac/global_display.h
    engines/ags/engine/ac/global_drawingsurface.cpp
    engines/ags/engine/ac/global_drawingsurface.h
    engines/ags/engine/ac/global_dynamicsprite.cpp
    engines/ags/engine/ac/global_dynamicsprite.h
    engines/ags/engine/ac/global_file.cpp
    engines/ags/engine/ac/global_file.h
    engines/ags/engine/ac/global_game.cpp
    engines/ags/engine/ac/global_game.h
    engines/ags/engine/ac/global_gui.cpp
    engines/ags/engine/ac/global_gui.h
    engines/ags/engine/ac/global_hotspot.cpp
    engines/ags/engine/ac/global_hotspot.h
    engines/ags/engine/ac/global_inventoryitem.cpp
    engines/ags/engine/ac/global_inventoryitem.h
    engines/ags/engine/ac/global_invwindow.cpp
    engines/ags/engine/ac/global_invwindow.h
    engines/ags/engine/ac/global_label.cpp
    engines/ags/engine/ac/global_label.h
    engines/ags/engine/ac/global_listbox.cpp
    engines/ags/engine/ac/global_listbox.h
    engines/ags/engine/ac/global_mouse.cpp
    engines/ags/engine/ac/global_mouse.h
    engines/ags/engine/ac/global_object.cpp
    engines/ags/engine/ac/global_object.h
    engines/ags/engine/ac/global_overlay.cpp
    engines/ags/engine/ac/global_overlay.h
    engines/ags/engine/ac/global_palette.cpp
    engines/ags/engine/ac/global_palette.h
    engines/ags/engine/ac/global_parser.cpp
    engines/ags/engine/ac/global_parser.h
    engines/ags/engine/ac/global_plugin.h
    engines/ags/engine/ac/global_record.cpp
    engines/ags/engine/ac/global_record.h
    engines/ags/engine/ac/global_region.cpp
    engines/ags/engine/ac/global_region.h
    engines/ags/engine/ac/global_room.cpp
    engines/ags/engine/ac/global_room.h
    engines/ags/engine/ac/global_screen.cpp
    engines/ags/engine/ac/global_screen.h
    engines/ags/engine/ac/global_slider.cpp
    engines/ags/engine/ac/global_slider.h
    engines/ags/engine/ac/global_string.cpp
    engines/ags/engine/ac/global_string.h
    engines/ags/engine/ac/global_textbox.cpp
    engines/ags/engine/ac/global_textbox.h
    engines/ags/engine/ac/global_timer.cpp
    engines/ags/engine/ac/global_timer.h
    engines/ags/engine/ac/global_translation.cpp
    engines/ags/engine/ac/global_translation.h
    engines/ags/engine/ac/global_video.cpp
    engines/ags/engine/ac/global_video.h
    engines/ags/engine/ac/global_viewframe.cpp
    engines/ags/engine/ac/global_viewframe.h
    engines/ags/engine/ac/global_viewport.cpp
    engines/ags/engine/ac/global_viewport.h
    engines/ags/engine/ac/global_walkablearea.cpp
    engines/ags/engine/ac/global_walkablearea.h
    engines/ags/engine/ac/global_walkbehind.cpp
    engines/ags/engine/ac/global_walkbehind.h
    engines/ags/engine/ac/gui.cpp
    engines/ags/engine/ac/gui.h
    engines/ags/engine/ac/guicontrol.cpp
    engines/ags/engine/ac/guicontrol.h
    engines/ags/engine/ac/guiinv.cpp
    engines/ags/engine/ac/hotspot.cpp
    engines/ags/engine/ac/hotspot.h
    engines/ags/engine/ac/interfacebutton.cpp
    engines/ags/engine/ac/interfaceelement.cpp
    engines/ags/engine/ac/inventoryitem.cpp
    engines/ags/engine/ac/inventoryitem.h
    engines/ags/engine/ac/invwindow.cpp
    engines/ags/engine/ac/invwindow.h
    engines/ags/engine/ac/keycode.cpp
    engines/ags/engine/ac/keycode.h
    engines/ags/engine/ac/label.cpp
    engines/ags/engine/ac/label.h
    engines/ags/engine/ac/lipsync.h
    engines/ags/engine/ac/listbox.cpp
    engines/ags/engine/ac/listbox.h
    engines/ags/engine/ac/math.cpp
    engines/ags/engine/ac/math.h
    engines/ags/engine/ac/mouse.cpp
    engines/ags/engine/ac/mouse.h
    engines/ags/engine/ac/movelist.cpp
    engines/ags/engine/ac/movelist.h
    engines/ags/engine/ac/object.cpp
    engines/ags/engine/ac/object.h
    engines/ags/engine/ac/objectcache.h
    engines/ags/engine/ac/overlay.cpp
    engines/ags/engine/ac/overlay.h
    engines/ags/engine/ac/parser.cpp
    engines/ags/engine/ac/parser.h
    engines/ags/engine/ac/path_helper.h
    engines/ags/engine/ac/properties.cpp
    engines/ags/engine/ac/properties.h
    engines/ags/engine/ac/region.cpp
    engines/ags/engine/ac/region.h
    engines/ags/engine/ac/richgamemedia.cpp
    engines/ags/engine/ac/richgamemedia.h
    engines/ags/engine/ac/room.cpp
    engines/ags/engine/ac/room.h
    engines/ags/engine/ac/roomobject.cpp
    engines/ags/engine/ac/roomobject.h
    engines/ags/engine/ac/roomstatus.cpp
    engines/ags/engine/ac/roomstatus.h
    engines/ags/engine/ac/route_finder.cpp
    engines/ags/engine/ac/route_finder.h
    engines/ags/engine/ac/route_finder_impl.cpp
    engines/ags/engine/ac/route_finder_impl.h
    engines/ags/engine/ac/route_finder_impl_legacy.cpp
    engines/ags/engine/ac/route_finder_impl_legacy.h
    engines/ags/engine/ac/runtime_defines.h
    engines/ags/engine/ac/screen.cpp
    engines/ags/engine/ac/screen.h
    engines/ags/engine/ac/screenoverlay.cpp
    engines/ags/engine/ac/screenoverlay.h
    engines/ags/engine/ac/scriptcontainers.cpp
    engines/ags/engine/ac/slider.cpp
    engines/ags/engine/ac/slider.h
    engines/ags/engine/ac/speech.cpp
    engines/ags/engine/ac/speech.h
    engines/ags/engine/ac/sprite.cpp
    engines/ags/engine/ac/sprite.h
    engines/ags/engine/ac/spritecache_engine.cpp
    engines/ags/engine/ac/spritelistentry.h
    engines/ags/engine/ac/statobj/agsstaticobject.cpp
    engines/ags/engine/ac/statobj/agsstaticobject.h
    engines/ags/engine/ac/statobj/staticarray.cpp
    engines/ags/engine/ac/statobj/staticarray.h
    engines/ags/engine/ac/statobj/staticobject.h
    engines/ags/engine/ac/string.cpp
    engines/ags/engine/ac/string.h
    engines/ags/engine/ac/sys_events.cpp
    engines/ags/engine/ac/sys_events.h
    engines/ags/engine/ac/system.cpp
    engines/ags/engine/ac/system.h
    engines/ags/engine/ac/textbox.cpp
    engines/ags/engine/ac/textbox.h
    engines/ags/engine/ac/timer.cpp
    engines/ags/engine/ac/timer.h
    engines/ags/engine/ac/topbarsettings.h
    engines/ags/engine/ac/translation.cpp
    engines/ags/engine/ac/translation.h
    engines/ags/engine/ac/tree_map.cpp
    engines/ags/engine/ac/tree_map.h
    engines/ags/engine/ac/viewframe.cpp
    engines/ags/engine/ac/viewframe.h
    engines/ags/engine/ac/viewport_script.cpp
    engines/ags/engine/ac/walkablearea.cpp
    engines/ags/engine/ac/walkablearea.h
    engines/ags/engine/ac/walkbehind.cpp
    engines/ags/engine/ac/walkbehind.h
    engines/ags/engine/debugging/agseditordebugger.h
    engines/ags/engine/debugging/consoleoutputtarget.cpp
    engines/ags/engine/debugging/consoleoutputtarget.h
    engines/ags/engine/debugging/debug.cpp
    engines/ags/engine/debugging/debug_log.h
    engines/ags/engine/debugging/debugger.h
    engines/ags/engine/debugging/dummyagsdebugger.h
    engines/ags/engine/debugging/filebasedagsdebugger.cpp
    engines/ags/engine/debugging/filebasedagsdebugger.h
    engines/ags/engine/debugging/logfile.cpp
    engines/ags/engine/debugging/logfile.h
    engines/ags/engine/debugging/messagebuffer.cpp
    engines/ags/engine/debugging/messagebuffer.h
    engines/ags/engine/device/mousew32.cpp
    engines/ags/engine/device/mousew32.h
    engines/ags/engine/font/fonts_engine.cpp
    engines/ags/engine/game/game_init.cpp
    engines/ags/engine/game/game_init.h
    engines/ags/engine/game/savegame.cpp
    engines/ags/engine/game/savegame.h
    engines/ags/engine/game/savegame_components.cpp
    engines/ags/engine/game/savegame_components.h
    engines/ags/engine/game/savegame_internal.h
    engines/ags/engine/game/viewport.cpp
    engines/ags/engine/game/viewport.h
    engines/ags/engine/gfx/ali3dexception.h
    engines/ags/engine/gfx/ali3dogl.cpp
    engines/ags/engine/gfx/ali3dogl.h
    engines/ags/engine/gfx/ali3dsw.cpp
    engines/ags/engine/gfx/ali3dsw.h
    engines/ags/engine/gfx/blender.cpp
    engines/ags/engine/gfx/blender.h
    engines/ags/engine/gfx/color_engine.cpp
    engines/ags/engine/gfx/ddb.h
    engines/ags/engine/gfx/gfx_util.cpp
    engines/ags/engine/gfx/gfx_util.h
    engines/ags/engine/gfx/gfxdefines.h
    engines/ags/engine/gfx/gfxdriverbase.cpp
    engines/ags/engine/gfx/gfxdriverbase.h
    engines/ags/engine/gfx/gfxdriverfactory.cpp
    engines/ags/engine/gfx/gfxdriverfactory.h
    engines/ags/engine/gfx/gfxdriverfactorybase.h
    engines/ags/engine/gfx/gfxfilter.h
    engines/ags/engine/gfx/gfxfilter_aad3d.cpp
    engines/ags/engine/gfx/gfxfilter_aad3d.h
    engines/ags/engine/gfx/gfxfilter_aaogl.cpp
    engines/ags/engine/gfx/gfxfilter_aaogl.h
    engines/ags/engine/gfx/gfxfilter_allegro.cpp
    engines/ags/engine/gfx/gfxfilter_allegro.h
    engines/ags/engine/gfx/gfxfilter_d3d.cpp
    engines/ags/engine/gfx/gfxfilter_d3d.h
    engines/ags/engine/gfx/gfxfilter_hqx.cpp
    engines/ags/engine/gfx/gfxfilter_hqx.h
    engines/ags/engine/gfx/gfxfilter_ogl.cpp
    engines/ags/engine/gfx/gfxfilter_ogl.h
    engines/ags/engine/gfx/gfxfilter_scaling.cpp
    engines/ags/engine/gfx/gfxfilter_scaling.h
    engines/ags/engine/gfx/gfxmodelist.h
    engines/ags/engine/gfx/graphicsdriver.h
    engines/ags/engine/gfx/hq2x3x.h
    engines/ags/engine/gfx/ogl_headers.h
    engines/ags/engine/gui/animatingguibutton.cpp
    engines/ags/engine/gui/animatingguibutton.h
    engines/ags/engine/gui/cscidialog.cpp
    engines/ags/engine/gui/cscidialog.h
    engines/ags/engine/gui/gui_engine.cpp
    engines/ags/engine/gui/guidialog.cpp
    engines/ags/engine/gui/guidialog.h
    engines/ags/engine/gui/guidialogdefines.h
    engines/ags/engine/gui/guidialoginternaldefs.h
    engines/ags/engine/gui/mycontrols.h
    engines/ags/engine/gui/mylabel.cpp
    engines/ags/engine/gui/mylabel.h
    engines/ags/engine/gui/mylistbox.cpp
    engines/ags/engine/gui/mylistbox.h
    engines/ags/engine/gui/mypushbutton.cpp
    engines/ags/engine/gui/mypushbutton.h
    engines/ags/engine/gui/mytextbox.cpp
    engines/ags/engine/gui/mytextbox.h
    engines/ags/engine/gui/newcontrol.cpp
    engines/ags/engine/gui/newcontrol.h
    engines/ags/engine/main/config.cpp
    engines/ags/engine/main/config.h
    engines/ags/engine/main/engine.cpp
    engines/ags/engine/main/engine.h
    engines/ags/engine/main/engine_setup.cpp
    engines/ags/engine/main/engine_setup.h
    engines/ags/engine/main/game_file.cpp
    engines/ags/engine/main/game_file.h
    engines/ags/engine/main/game_run.cpp
    engines/ags/engine/main/game_run.h
    engines/ags/engine/main/game_start.cpp
    engines/ags/engine/main/game_start.h
    engines/ags/engine/main/graphics_mode.cpp
    engines/ags/engine/main/graphics_mode.h
    engines/ags/engine/main/main.cpp
    engines/ags/engine/main/main.h
    engines/ags/engine/main/main_allegro.h
    engines/ags/engine/main/maindefines_ex.h
    engines/ags/engine/main/mainheader.h
    engines/ags/engine/main/quit.cpp
    engines/ags/engine/main/quit.h
    engines/ags/engine/main/update.cpp
    engines/ags/engine/main/update.h
    engines/ags/engine/media/audio/ambientsound.cpp
    engines/ags/engine/media/audio/ambientsound.h
    engines/ags/engine/media/audio/audio.cpp
    engines/ags/engine/media/audio/audio.h
    engines/ags/engine/media/audio/audio_system.h
    engines/ags/engine/media/audio/audiodefines.h
    engines/ags/engine/media/audio/audiointernaldefs.h
    engines/ags/engine/media/audio/clip_mydumbmod.cpp
    engines/ags/engine/media/audio/clip_mydumbmod.h
    engines/ags/engine/media/audio/clip_myjgmod.cpp
    engines/ags/engine/media/audio/clip_myjgmod.h
    engines/ags/engine/media/audio/clip_mymidi.cpp
    engines/ags/engine/media/audio/clip_mymidi.h
    engines/ags/engine/media/audio/clip_mymp3.cpp
    engines/ags/engine/media/audio/clip_mymp3.h
    engines/ags/engine/media/audio/clip_myogg.cpp
    engines/ags/engine/media/audio/clip_myogg.h
    engines/ags/engine/media/audio/clip_mystaticmp3.cpp
    engines/ags/engine/media/audio/clip_mystaticmp3.h
    engines/ags/engine/media/audio/clip_mystaticogg.cpp
    engines/ags/engine/media/audio/clip_mystaticogg.h
    engines/ags/engine/media/audio/clip_mywave.cpp
    engines/ags/engine/media/audio/clip_mywave.h
    engines/ags/engine/media/audio/queuedaudioitem.cpp
    engines/ags/engine/media/audio/queuedaudioitem.h
    engines/ags/engine/media/audio/sound.cpp
    engines/ags/engine/media/audio/sound.h
    engines/ags/engine/media/audio/soundcache.cpp
    engines/ags/engine/media/audio/soundcache.h
    engines/ags/engine/media/audio/soundclip.cpp
    engines/ags/engine/media/audio/soundclip.h
    engines/ags/engine/media/video/VMR9Graph.h
    engines/ags/engine/media/video/video.cpp
    engines/ags/engine/media/video/video.h
    engines/ags/engine/platform/android/acpland.cpp
    engines/ags/engine/platform/base/agsplatformdriver.cpp
    engines/ags/engine/platform/base/agsplatformdriver.h
    engines/ags/engine/platform/ios/acplios.cpp
    engines/ags/engine/platform/linux/acpllnx.cpp
    engines/ags/engine/platform/osx/acplmac.cpp
    engines/ags/engine/platform/util/pe.h
    engines/ags/engine/platform/windows/acplwin.cpp
    engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
    engines/ags/engine/platform/windows/gfx/ali3dd3d.h
    engines/ags/engine/platform/windows/media/video/acwavi.cpp
    engines/ags/engine/platform/windows/media/video/acwavi3d.cpp
    engines/ags/engine/platform/windows/minidump.cpp
    engines/ags/engine/platform/windows/setup/winsetup.cpp
    engines/ags/engine/platform/windows/setup/winsetup.h
    engines/ags/engine/platform/windows/win_ex_handling.cpp
    engines/ags/engine/platform/windows/win_ex_handling.h
    engines/ags/engine/platform/windows/winapi_exclusive.h
    engines/ags/engine/plugin/agsplugin.cpp
    engines/ags/engine/plugin/agsplugin.h
    engines/ags/engine/plugin/global_plugin.cpp
    engines/ags/engine/plugin/plugin_builtin.h
    engines/ags/engine/plugin/plugin_engine.h
    engines/ags/engine/plugin/pluginobjectreader.cpp
    engines/ags/engine/plugin/pluginobjectreader.h
    engines/ags/engine/resource/resource.h
    engines/ags/engine/script/cc_instance.cpp
    engines/ags/engine/script/cc_instance.h
    engines/ags/engine/script/executingscript.cpp
    engines/ags/engine/script/executingscript.h
    engines/ags/engine/script/exports.cpp
    engines/ags/engine/script/exports.h
    engines/ags/engine/script/nonblockingscriptfunction.h
    engines/ags/engine/script/runtimescriptvalue.cpp
    engines/ags/engine/script/runtimescriptvalue.h
    engines/ags/engine/script/script.cpp
    engines/ags/engine/script/script.h
    engines/ags/engine/script/script_api.cpp
    engines/ags/engine/script/script_api.h
    engines/ags/engine/script/script_engine.cpp
    engines/ags/engine/script/script_runtime.cpp
    engines/ags/engine/script/script_runtime.h
    engines/ags/engine/script/systemimports.cpp
    engines/ags/engine/script/systemimports.h
    engines/ags/engine/util/library.h
    engines/ags/engine/util/library_dummy.h
    engines/ags/engine/util/library_posix.h
    engines/ags/engine/util/library_psp.h
    engines/ags/engine/util/library_windows.h
    engines/ags/engine/util/mutex.h
    engines/ags/engine/util/mutex_base.h
    engines/ags/engine/util/mutex_lock.h
    engines/ags/engine/util/mutex_psp.h
    engines/ags/engine/util/mutex_pthread.h
    engines/ags/engine/util/mutex_std.h
    engines/ags/engine/util/mutex_wii.h
    engines/ags/engine/util/mutex_windows.h
    engines/ags/engine/util/scaling.h
    engines/ags/engine/util/thread.h
    engines/ags/engine/util/thread_psp.h
    engines/ags/engine/util/thread_pthread.h
    engines/ags/engine/util/thread_std.h
    engines/ags/engine/util/thread_wii.h
    engines/ags/engine/util/thread_windows.h
    engines/ags/shared/ac/audiocliptype.cpp
    engines/ags/shared/ac/audiocliptype.h
    engines/ags/shared/ac/characterinfo.cpp
    engines/ags/shared/ac/characterinfo.h
    engines/ags/shared/ac/common.cpp
    engines/ags/shared/ac/common.h
    engines/ags/shared/ac/common_defines.h
    engines/ags/shared/ac/dialogtopic.cpp
    engines/ags/shared/ac/dialogtopic.h
    engines/ags/shared/ac/dynobj/scriptaudioclip.cpp
    engines/ags/shared/ac/dynobj/scriptaudioclip.h
    engines/ags/shared/ac/game_version.h
    engines/ags/shared/ac/gamesetupstruct.cpp
    engines/ags/shared/ac/gamesetupstruct.h
    engines/ags/shared/ac/gamesetupstructbase.cpp
    engines/ags/shared/ac/gamesetupstructbase.h
    engines/ags/shared/ac/gamestructdefines.h
    engines/ags/shared/ac/interfacebutton.h
    engines/ags/shared/ac/interfaceelement.h
    engines/ags/shared/ac/inventoryiteminfo.cpp
    engines/ags/shared/ac/inventoryiteminfo.h
    engines/ags/shared/ac/mousecursor.cpp
    engines/ags/shared/ac/mousecursor.h
    engines/ags/shared/ac/oldgamesetupstruct.h
    engines/ags/shared/ac/spritecache.cpp
    engines/ags/shared/ac/spritecache.h
    engines/ags/shared/ac/view.cpp
    engines/ags/shared/ac/view.h
    engines/ags/shared/ac/wordsdictionary.cpp
    engines/ags/shared/ac/wordsdictionary.h
    engines/ags/shared/api/stream_api.h
    engines/ags/shared/core/asset.cpp
    engines/ags/shared/core/asset.h
    engines/ags/shared/core/assetmanager.cpp
    engines/ags/shared/core/assetmanager.h
    engines/ags/shared/core/def_version.h
    engines/ags/shared/core/platform.h
    engines/ags/shared/core/types.h
    engines/ags/shared/debugging/assert.h
    engines/ags/shared/debugging/debugmanager.cpp
    engines/ags/shared/debugging/debugmanager.h
    engines/ags/shared/debugging/out.h
    engines/ags/shared/debugging/outputhandler.h
    engines/ags/shared/font/agsfontrenderer.h
    engines/ags/shared/font/fonts.cpp
    engines/ags/shared/font/fonts.h
    engines/ags/shared/font/ttffontrenderer.cpp
    engines/ags/shared/font/ttffontrenderer.h
    engines/ags/shared/font/wfnfont.cpp
    engines/ags/shared/font/wfnfont.h
    engines/ags/shared/font/wfnfontrenderer.cpp
    engines/ags/shared/font/wfnfontrenderer.h
    engines/ags/shared/game/customproperties.cpp
    engines/ags/shared/game/customproperties.h
    engines/ags/shared/game/interactions.cpp
    engines/ags/shared/game/interactions.h
    engines/ags/shared/game/main_game_file.cpp
    engines/ags/shared/game/main_game_file.h
    engines/ags/shared/game/plugininfo.h
    engines/ags/shared/game/room_file.cpp
    engines/ags/shared/game/room_file.h
    engines/ags/shared/game/room_file_deprecated.cpp
    engines/ags/shared/game/room_version.h
    engines/ags/shared/game/roomstruct.cpp
    engines/ags/shared/game/roomstruct.h
    engines/ags/shared/gfx/allegrobitmap.cpp
    engines/ags/shared/gfx/allegrobitmap.h
    engines/ags/shared/gfx/bitmap.cpp
    engines/ags/shared/gfx/bitmap.h
    engines/ags/shared/gfx/gfx_def.h
    engines/ags/shared/gui/guibutton.cpp
    engines/ags/shared/gui/guibutton.h
    engines/ags/shared/gui/guidefines.h
    engines/ags/shared/gui/guiinv.cpp
    engines/ags/shared/gui/guiinv.h
    engines/ags/shared/gui/guilabel.cpp
    engines/ags/shared/gui/guilabel.h
    engines/ags/shared/gui/guilistbox.cpp
    engines/ags/shared/gui/guilistbox.h
    engines/ags/shared/gui/guimain.cpp
    engines/ags/shared/gui/guimain.h
    engines/ags/shared/gui/guiobject.cpp
    engines/ags/shared/gui/guiobject.h
    engines/ags/shared/gui/guislider.cpp
    engines/ags/shared/gui/guislider.h
    engines/ags/shared/gui/guitextbox.cpp
    engines/ags/shared/gui/guitextbox.h
    engines/ags/shared/script/cc_error.cpp
    engines/ags/shared/script/cc_error.h
    engines/ags/shared/script/cc_options.cpp
    engines/ags/shared/script/cc_options.h
    engines/ags/shared/script/cc_script.cpp
    engines/ags/shared/script/cc_script.h
    engines/ags/shared/script/script_common.h
    engines/ags/shared/util/alignedstream.cpp
    engines/ags/shared/util/alignedstream.h
    engines/ags/shared/util/bbop.h
    engines/ags/shared/util/bufferedstream.cpp
    engines/ags/shared/util/bufferedstream.h
    engines/ags/shared/util/compress.cpp
    engines/ags/shared/util/compress.h
    engines/ags/shared/util/datastream.cpp
    engines/ags/shared/util/datastream.h
    engines/ags/shared/util/directory.cpp
    engines/ags/shared/util/directory.h
    engines/ags/shared/util/error.h
    engines/ags/shared/util/file.cpp
    engines/ags/shared/util/file.h
    engines/ags/shared/util/filestream.cpp
    engines/ags/shared/util/filestream.h
    engines/ags/shared/util/geometry.cpp
    engines/ags/shared/util/geometry.h
    engines/ags/shared/util/ini_util.cpp
    engines/ags/shared/util/ini_util.h
    engines/ags/shared/util/inifile.cpp
    engines/ags/shared/util/inifile.h
    engines/ags/shared/util/lzw.cpp
    engines/ags/shared/util/lzw.h
    engines/ags/shared/util/math.h
    engines/ags/shared/util/memory.h
    engines/ags/shared/util/misc.cpp
    engines/ags/shared/util/misc.h
    engines/ags/shared/util/multifilelib.h
    engines/ags/shared/util/mutifilelib.cpp
    engines/ags/shared/util/path.cpp
    engines/ags/shared/util/path.h
    engines/ags/shared/util/proxystream.cpp
    engines/ags/shared/util/proxystream.h
    engines/ags/shared/util/stdio_compat.h
    engines/ags/shared/util/stream.cpp
    engines/ags/shared/util/stream.h
    engines/ags/shared/util/string.cpp
    engines/ags/shared/util/string.h
    engines/ags/shared/util/string_compat.h
    engines/ags/shared/util/string_types.h
    engines/ags/shared/util/string_utils.cpp
    engines/ags/shared/util/string_utils.h
    engines/ags/shared/util/textreader.h
    engines/ags/shared/util/textstreamreader.cpp
    engines/ags/shared/util/textstreamreader.h
    engines/ags/shared/util/textstreamwriter.cpp
    engines/ags/shared/util/textstreamwriter.h
    engines/ags/shared/util/textwriter.h
    engines/ags/shared/util/version.cpp
    engines/ags/shared/util/version.h
    engines/ags/shared/util/wgt2allg.cpp
    engines/ags/shared/util/wgt2allg.h


diff --git a/engines/ags/engine/ac/asset_helper.h b/engines/ags/engine/ac/asset_helper.h
index 9c6c442166..fa62fecc2b 100644
--- a/engines/ags/engine/ac/asset_helper.h
+++ b/engines/ags/engine/ac/asset_helper.h
@@ -1,20 +1,31 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
+/* 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.
+ *
+ */
+
 //=============================================================================
 //
 // Functions related to finding and opening game assets.
 //
 //=============================================================================
+
 #ifndef __AGS_EE_AC__ASSETHELPER_H
 #define __AGS_EE_AC__ASSETHELPER_H
 #include <memory>
diff --git a/engines/ags/engine/ac/audiochannel.cpp b/engines/ags/engine/ac/audiochannel.cpp
index 4ac75c4e7a..3f1190b017 100644
--- a/engines/ags/engine/ac/audiochannel.cpp
+++ b/engines/ags/engine/ac/audiochannel.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/audiochannel.h"
 #include "ac/gamestate.h"
diff --git a/engines/ags/engine/ac/audiochannel.h b/engines/ags/engine/ac/audiochannel.h
index de655725ad..1955cc146c 100644
--- a/engines/ags/engine/ac/audiochannel.h
+++ b/engines/ags/engine/ac/audiochannel.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__AUDIOCHANNEL_H
 #define __AGS_EE_AC__AUDIOCHANNEL_H
 
diff --git a/engines/ags/engine/ac/audioclip.cpp b/engines/ags/engine/ac/audioclip.cpp
index 5489ee5a3b..2a02f1fd95 100644
--- a/engines/ags/engine/ac/audioclip.cpp
+++ b/engines/ags/engine/ac/audioclip.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/asset_helper.h"
 #include "ac/audioclip.h"
diff --git a/engines/ags/engine/ac/audioclip.h b/engines/ags/engine/ac/audioclip.h
index ffb4a100b5..113ed78423 100644
--- a/engines/ags/engine/ac/audioclip.h
+++ b/engines/ags/engine/ac/audioclip.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__AUDIOCLIP_H
 #define __AGS_EE_AC__AUDIOCLIP_H
 
diff --git a/engines/ags/engine/ac/button.cpp b/engines/ags/engine/ac/button.cpp
index ecbcb1b1bc..f235292a3a 100644
--- a/engines/ags/engine/ac/button.cpp
+++ b/engines/ags/engine/ac/button.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/button.h"
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/button.h b/engines/ags/engine/ac/button.h
index 5f94aaea18..7a36b24552 100644
--- a/engines/ags/engine/ac/button.h
+++ b/engines/ags/engine/ac/button.h
@@ -1,15 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
+/* 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.
+ *
+ */
+
 //=============================================================================
 //
 //
diff --git a/engines/ags/engine/ac/cdaudio.cpp b/engines/ags/engine/ac/cdaudio.cpp
index 866d797f50..b8f3a1e5ac 100644
--- a/engines/ags/engine/ac/cdaudio.cpp
+++ b/engines/ags/engine/ac/cdaudio.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/cdaudio.h"
 #include "platform/base/agsplatformdriver.h"
diff --git a/engines/ags/engine/ac/cdaudio.h b/engines/ags/engine/ac/cdaudio.h
index 4009b520fb..feda127c91 100644
--- a/engines/ags/engine/ac/cdaudio.h
+++ b/engines/ags/engine/ac/cdaudio.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__CDAUDIO_H
 #define __AGS_EE_AC__CDAUDIO_H
 
diff --git a/engines/ags/engine/ac/character.cpp b/engines/ags/engine/ac/character.cpp
index 526c9705ac..5338101469 100644
--- a/engines/ags/engine/ac/character.cpp
+++ b/engines/ags/engine/ac/character.cpp
@@ -1,15 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
+/* 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.
+ *
+ */
+
 //=============================================================================
 //
 // AGS Character functions
diff --git a/engines/ags/engine/ac/character.h b/engines/ags/engine/ac/character.h
index cb678fda3a..32016da906 100644
--- a/engines/ags/engine/ac/character.h
+++ b/engines/ags/engine/ac/character.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__CHARACTER_H
 #define __AGS_EE_AC__CHARACTER_H
 
diff --git a/engines/ags/engine/ac/charactercache.h b/engines/ags/engine/ac/charactercache.h
index f4b5c64012..ca914d3f47 100644
--- a/engines/ags/engine/ac/charactercache.h
+++ b/engines/ags/engine/ac/charactercache.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__CHARACTERCACHE_H
 #define __AGS_EE_AC__CHARACTERCACHE_H
 
diff --git a/engines/ags/engine/ac/characterextras.cpp b/engines/ags/engine/ac/characterextras.cpp
index 13c8f81350..211534e075 100644
--- a/engines/ags/engine/ac/characterextras.cpp
+++ b/engines/ags/engine/ac/characterextras.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/characterextras.h"
 #include "util/stream.h"
diff --git a/engines/ags/engine/ac/characterextras.h b/engines/ags/engine/ac/characterextras.h
index 2e9d6e6098..c694b2c964 100644
--- a/engines/ags/engine/ac/characterextras.h
+++ b/engines/ags/engine/ac/characterextras.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__CHARACTEREXTRAS_H
 #define __AGS_EE_AC__CHARACTEREXTRAS_H
 
diff --git a/engines/ags/engine/ac/characterinfo_engine.cpp b/engines/ags/engine/ac/characterinfo_engine.cpp
index 8f6f1a5a83..819b92fc11 100644
--- a/engines/ags/engine/ac/characterinfo_engine.cpp
+++ b/engines/ags/engine/ac/characterinfo_engine.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/characterinfo.h"
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/datetime.cpp b/engines/ags/engine/ac/datetime.cpp
index d2f8b230b2..e11d967b74 100644
--- a/engines/ags/engine/ac/datetime.cpp
+++ b/engines/ags/engine/ac/datetime.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 <time.h>
 #include "ac/datetime.h"
diff --git a/engines/ags/engine/ac/datetime.h b/engines/ags/engine/ac/datetime.h
index 76d474ee00..34be0b0e68 100644
--- a/engines/ags/engine/ac/datetime.h
+++ b/engines/ags/engine/ac/datetime.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__DATETIME_H
 #define __AGS_EE_AC__DATETIME_H
 
diff --git a/engines/ags/engine/ac/dialog.cpp b/engines/ags/engine/ac/dialog.cpp
index d27fe02f94..4cf2f530bf 100644
--- a/engines/ags/engine/ac/dialog.cpp
+++ b/engines/ags/engine/ac/dialog.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/dialog.h"
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/dialog.h b/engines/ags/engine/ac/dialog.h
index 93fcf4868c..817c3ac1cc 100644
--- a/engines/ags/engine/ac/dialog.h
+++ b/engines/ags/engine/ac/dialog.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__DIALOG_H
 #define __AGS_EE_AC__DIALOG_H
 
diff --git a/engines/ags/engine/ac/dialogoptionsrendering.cpp b/engines/ags/engine/ac/dialogoptionsrendering.cpp
index 08f2e876ab..686de549b0 100644
--- a/engines/ags/engine/ac/dialogoptionsrendering.cpp
+++ b/engines/ags/engine/ac/dialogoptionsrendering.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/dialog.h"
 #include "ac/dialogtopic.h"
diff --git a/engines/ags/engine/ac/dialogoptionsrendering.h b/engines/ags/engine/ac/dialogoptionsrendering.h
index f08366df3d..7917ae15b0 100644
--- a/engines/ags/engine/ac/dialogoptionsrendering.h
+++ b/engines/ags/engine/ac/dialogoptionsrendering.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__DIALOGOPTIONSRENDERING_H
 #define __AGS_EE_AC__DIALOGOPTIONSRENDERING_H
 
diff --git a/engines/ags/engine/ac/display.cpp b/engines/ags/engine/ac/display.cpp
index f31db06414..dbf7b27ad5 100644
--- a/engines/ags/engine/ac/display.cpp
+++ b/engines/ags/engine/ac/display.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 <math.h>
 
diff --git a/engines/ags/engine/ac/display.h b/engines/ags/engine/ac/display.h
index 68b00bfdad..69e980ecc7 100644
--- a/engines/ags/engine/ac/display.h
+++ b/engines/ags/engine/ac/display.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__DISPLAY_H
 #define __AGS_EE_AC__DISPLAY_H
 
diff --git a/engines/ags/engine/ac/draw.cpp b/engines/ags/engine/ac/draw.cpp
index fe24f1c453..96b420cf5a 100644
--- a/engines/ags/engine/ac/draw.cpp
+++ b/engines/ags/engine/ac/draw.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 <algorithm>
 #include <cmath>
diff --git a/engines/ags/engine/ac/draw.h b/engines/ags/engine/ac/draw.h
index af6e8e9354..19e2274319 100644
--- a/engines/ags/engine/ac/draw.h
+++ b/engines/ags/engine/ac/draw.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__DRAW_H
 #define __AGS_EE_AC__DRAW_H
 
diff --git a/engines/ags/engine/ac/draw_software.cpp b/engines/ags/engine/ac/draw_software.cpp
index 721b676924..014713495a 100644
--- a/engines/ags/engine/ac/draw_software.cpp
+++ b/engines/ags/engine/ac/draw_software.cpp
@@ -1,15 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
+/* 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.
+ *
+ */
+
 //=============================================================================
 //
 // Software drawing component. Optimizes drawing for software renderer using
diff --git a/engines/ags/engine/ac/draw_software.h b/engines/ags/engine/ac/draw_software.h
index 47db5b227f..e0e59339eb 100644
--- a/engines/ags/engine/ac/draw_software.h
+++ b/engines/ags/engine/ac/draw_software.h
@@ -1,21 +1,32 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
+/* 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.
+ *
+ */
+
 //=============================================================================
 //
 // Software drawing component. Optimizes drawing for software renderer using
 // dirty rectangles technique.
 //
 //=============================================================================
+
 #ifndef __AGS_EE_AC__DRAWSOFTWARE_H
 #define __AGS_EE_AC__DRAWSOFTWARE_H
 
diff --git a/engines/ags/engine/ac/drawingsurface.cpp b/engines/ags/engine/ac/drawingsurface.cpp
index 5dc0ccdf9e..3e8fc26de1 100644
--- a/engines/ags/engine/ac/drawingsurface.cpp
+++ b/engines/ags/engine/ac/drawingsurface.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/draw.h"
 #include "ac/drawingsurface.h"
diff --git a/engines/ags/engine/ac/drawingsurface.h b/engines/ags/engine/ac/drawingsurface.h
index 5bd6b7aac7..511cf1b441 100644
--- a/engines/ags/engine/ac/drawingsurface.h
+++ b/engines/ags/engine/ac/drawingsurface.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__DRAWINGSURFACE_H
 #define __AGS_EE_AC__DRAWINGSURFACE_H
 
diff --git a/engines/ags/engine/ac/dynamicsprite.cpp b/engines/ags/engine/ac/dynamicsprite.cpp
index 480a233e1a..18e5b2c264 100644
--- a/engines/ags/engine/ac/dynamicsprite.cpp
+++ b/engines/ags/engine/ac/dynamicsprite.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 <math.h>
 #include "ac/dynamicsprite.h"
diff --git a/engines/ags/engine/ac/dynamicsprite.h b/engines/ags/engine/ac/dynamicsprite.h
index 6602c85402..0f644f4aed 100644
--- a/engines/ags/engine/ac/dynamicsprite.h
+++ b/engines/ags/engine/ac/dynamicsprite.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__DYNAMICSPRITE_H
 #define __AGS_EE_AC__DYNAMICSPRITE_H
 
diff --git a/engines/ags/engine/ac/dynobj/all_dynamicclasses.h b/engines/ags/engine/ac/dynobj/all_dynamicclasses.h
index cc6cb71c13..d4687da0a9 100644
--- a/engines/ags/engine/ac/dynobj/all_dynamicclasses.h
+++ b/engines/ags/engine/ac/dynobj/all_dynamicclasses.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_DYNOBJ__ALLDYNAMICCLASSES_H
 #define __AGS_EE_DYNOBJ__ALLDYNAMICCLASSES_H
 
diff --git a/engines/ags/engine/ac/dynobj/all_scriptclasses.h b/engines/ags/engine/ac/dynobj/all_scriptclasses.h
index bcaf7a1d47..6a703be07e 100644
--- a/engines/ags/engine/ac/dynobj/all_scriptclasses.h
+++ b/engines/ags/engine/ac/dynobj/all_scriptclasses.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_DYNOBJ__ALLSCRIPTCLASSES_H
 #define __AGS_EE_DYNOBJ__ALLSCRIPTCLASSES_H
 
diff --git a/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp b/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp
index e1d0e6e6ee..ef775fcb98 100644
--- a/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 <string.h>
 #include "core/types.h"
diff --git a/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.h b/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.h
index 3c2d795e1b..c0a0eab4dc 100644
--- a/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.h
+++ b/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.h
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 __AC_CCDYNAMICOBJECT_H
 #define __AC_CCDYNAMICOBJECT_H
@@ -57,4 +65,4 @@ protected:
 
 };
 
-#endif // __AC_CCDYNAMICOBJECT_H
\ No newline at end of file
+#endif // __AC_CCDYNAMICOBJECT_H
diff --git a/engines/ags/engine/ac/dynobj/cc_audiochannel.cpp b/engines/ags/engine/ac/dynobj/cc_audiochannel.cpp
index 40f96af170..e93da266f5 100644
--- a/engines/ags/engine/ac/dynobj/cc_audiochannel.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_audiochannel.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/dynobj/cc_audiochannel.h"
 #include "ac/dynobj/scriptaudiochannel.h"
diff --git a/engines/ags/engine/ac/dynobj/cc_audiochannel.h b/engines/ags/engine/ac/dynobj/cc_audiochannel.h
index d13dd4cd09..b7c0eb0ef3 100644
--- a/engines/ags/engine/ac/dynobj/cc_audiochannel.h
+++ b/engines/ags/engine/ac/dynobj/cc_audiochannel.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_DYNOBJ__CCAUDIOCHANNEL_H
 #define __AGS_EE_DYNOBJ__CCAUDIOCHANNEL_H
 
diff --git a/engines/ags/engine/ac/dynobj/cc_audioclip.cpp b/engines/ags/engine/ac/dynobj/cc_audioclip.cpp
index 31e4a0105b..90607a3c5c 100644
--- a/engines/ags/engine/ac/dynobj/cc_audioclip.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_audioclip.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/dynobj/cc_audioclip.h"
 #include "ac/dynobj/scriptaudioclip.h"
diff --git a/engines/ags/engine/ac/dynobj/cc_audioclip.h b/engines/ags/engine/ac/dynobj/cc_audioclip.h
index b8b633a63c..6439ec35db 100644
--- a/engines/ags/engine/ac/dynobj/cc_audioclip.h
+++ b/engines/ags/engine/ac/dynobj/cc_audioclip.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_DYNOBJ__CCAUDIOCLIP_H
 #define __AGS_EE_DYNOBJ__CCAUDIOCLIP_H
 
diff --git a/engines/ags/engine/ac/dynobj/cc_character.cpp b/engines/ags/engine/ac/dynobj/cc_character.cpp
index 00478f2b08..f54087b0f2 100644
--- a/engines/ags/engine/ac/dynobj/cc_character.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_character.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/dynobj/cc_character.h"
 #include "ac/characterinfo.h"
diff --git a/engines/ags/engine/ac/dynobj/cc_character.h b/engines/ags/engine/ac/dynobj/cc_character.h
index d610cb914f..06ff2e28d4 100644
--- a/engines/ags/engine/ac/dynobj/cc_character.h
+++ b/engines/ags/engine/ac/dynobj/cc_character.h
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 __AC_CCCHARACTER_H
 #define __AC_CCCHARACTER_H
@@ -31,4 +39,4 @@ struct CCCharacter final : AGSCCDynamicObject {
     void WriteInt16(const char *address, intptr_t offset, int16_t val) override;
 };
 
-#endif // __AC_CCCHARACTER_H
\ No newline at end of file
+#endif // __AC_CCCHARACTER_H
diff --git a/engines/ags/engine/ac/dynobj/cc_dialog.cpp b/engines/ags/engine/ac/dynobj/cc_dialog.cpp
index 5c52802cae..1b9cdfc0be 100644
--- a/engines/ags/engine/ac/dynobj/cc_dialog.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_dialog.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/dynobj/cc_dialog.h"
 #include "ac/dialog.h"
diff --git a/engines/ags/engine/ac/dynobj/cc_dialog.h b/engines/ags/engine/ac/dynobj/cc_dialog.h
index bf1a95e122..0e7a701789 100644
--- a/engines/ags/engine/ac/dynobj/cc_dialog.h
+++ b/engines/ags/engine/ac/dynobj/cc_dialog.h
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 __AC_CCDIALOG_H
 #define __AC_CCDIALOG_H
diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicarray.cpp b/engines/ags/engine/ac/dynobj/cc_dynamicarray.cpp
index 694ef90213..9bf273b14b 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicarray.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicarray.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 <string.h>
 #include "cc_dynamicarray.h"
diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicarray.h b/engines/ags/engine/ac/dynobj/cc_dynamicarray.h
index 4619ff7137..ed29167244 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicarray.h
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicarray.h
@@ -1,16 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 __CC_DYNAMICARRAY_H
 #define __CC_DYNAMICARRAY_H
 
@@ -55,4 +64,4 @@ namespace DynamicArrayHelpers
     DynObjectRef CreateStringArray(const std::vector<const char*>);
 };
 
-#endif
\ No newline at end of file
+#endif
diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicobject.cpp b/engines/ags/engine/ac/dynobj/cc_dynamicobject.cpp
index 7c9a1039d4..0bc70e3aee 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicobject.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicobject.cpp
@@ -1,15 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
+/* 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.
+ *
+ */
+
 //=============================================================================
 //
 // C-Script run-time interpreter (c) 2001 Chris Jones
diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicobject.h b/engines/ags/engine/ac/dynobj/cc_dynamicobject.h
index 2d417d5018..aeca72f4d0 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicobject.h
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicobject.h
@@ -1,15 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
+/* 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.
+ *
+ */
+
 //=============================================================================
 //
 // Managed script object interface.
diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h b/engines/ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h
index 0f22f30f17..4323d97652 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h
@@ -1,3 +1,25 @@
+/* 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 ADDR_AND_MANAGER_H
 #define ADDR_AND_MANAGER_H
 
diff --git a/engines/ags/engine/ac/dynobj/cc_gui.cpp b/engines/ags/engine/ac/dynobj/cc_gui.cpp
index 40ff70c4a1..e453edd45b 100644
--- a/engines/ags/engine/ac/dynobj/cc_gui.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_gui.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/dynobj/cc_gui.h"
 #include "ac/dynobj/scriptgui.h"
@@ -35,4 +43,4 @@ void CCGUI::Unserialize(int index, const char *serializedData, int dataSize) {
     StartUnserialize(serializedData, dataSize);
     int num = UnserializeInt();
     ccRegisterUnserializedObject(index, &scrGui[num], this);
-}
\ No newline at end of file
+}
diff --git a/engines/ags/engine/ac/dynobj/cc_gui.h b/engines/ags/engine/ac/dynobj/cc_gui.h
index b29f5171bc..39c892d48d 100644
--- a/engines/ags/engine/ac/dynobj/cc_gui.h
+++ b/engines/ags/engine/ac/dynobj/cc_gui.h
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 __AC_CCGUI_H
 #define __AC_CCGUI_H
diff --git a/engines/ags/engine/ac/dynobj/cc_guiobject.cpp b/engines/ags/engine/ac/dynobj/cc_guiobject.cpp
index a4d6153327..5983f6561b 100644
--- a/engines/ags/engine/ac/dynobj/cc_guiobject.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_guiobject.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/dynobj/cc_guiobject.h"
 #include "ac/dynobj/scriptgui.h"
diff --git a/engines/ags/engine/ac/dynobj/cc_guiobject.h b/engines/ags/engine/ac/dynobj/cc_guiobject.h
index 2d261956f2..a6bf881654 100644
--- a/engines/ags/engine/ac/dynobj/cc_guiobject.h
+++ b/engines/ags/engine/ac/dynobj/cc_guiobject.h
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 __AC_CCGUIOBJECT_H
 #define __AC_CCGUIOBJECT_H
@@ -30,4 +38,4 @@ struct CCGUIObject final : AGSCCDynamicObject {
 
 };
 
-#endif // __AC_CCGUIOBJECT_H
\ No newline at end of file
+#endif // __AC_CCGUIOBJECT_H
diff --git a/engines/ags/engine/ac/dynobj/cc_hotspot.cpp b/engines/ags/engine/ac/dynobj/cc_hotspot.cpp
index cc109cd228..073cd65714 100644
--- a/engines/ags/engine/ac/dynobj/cc_hotspot.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_hotspot.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/dynobj/cc_hotspot.h"
 #include "ac/dynobj/scripthotspot.h"
@@ -37,4 +45,4 @@ void CCHotspot::Unserialize(int index, const char *serializedData, int dataSize)
     StartUnserialize(serializedData, dataSize);
     int num = UnserializeInt();
     ccRegisterUnserializedObject(index, &scrHotspot[num], this);
-}
\ No newline at end of file
+}
diff --git a/engines/ags/engine/ac/dynobj/cc_hotspot.h b/engines/ags/engine/ac/dynobj/cc_hotspot.h
index 8137cd3740..05722895fb 100644
--- a/engines/ags/engine/ac/dynobj/cc_hotspot.h
+++ b/engines/ags/engine/ac/dynobj/cc_hotspot.h
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 __AC_CCHOTSPOT_H
 #define __AC_CCHOTSPOT_H
@@ -30,4 +38,4 @@ struct CCHotspot final : AGSCCDynamicObject {
 
 };
 
-#endif // __AC_CCHOTSPOT_H
\ No newline at end of file
+#endif // __AC_CCHOTSPOT_H
diff --git a/engines/ags/engine/ac/dynobj/cc_inventory.cpp b/engines/ags/engine/ac/dynobj/cc_inventory.cpp
index cf9268c997..9333b5d96c 100644
--- a/engines/ags/engine/ac/dynobj/cc_inventory.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_inventory.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/dynobj/cc_inventory.h"
 #include "ac/dynobj/scriptinvitem.h"
@@ -36,4 +44,4 @@ void CCInventory::Unserialize(int index, const char *serializedData, int dataSiz
     StartUnserialize(serializedData, dataSize);
     int num = UnserializeInt();
     ccRegisterUnserializedObject(index, &scrInv[num], this);
-}
\ No newline at end of file
+}
diff --git a/engines/ags/engine/ac/dynobj/cc_inventory.h b/engines/ags/engine/ac/dynobj/cc_inventory.h
index 4e668aff70..aba9dc7c8a 100644
--- a/engines/ags/engine/ac/dynobj/cc_inventory.h
+++ b/engines/ags/engine/ac/dynobj/cc_inventory.h
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 __AC_CCINVENTORY_H
 #define __AC_CCINVENTORY_H
@@ -30,4 +38,4 @@ struct CCInventory final : AGSCCDynamicObject {
 
 };
 
-#endif // __AC_CCINVENTORY_H
\ No newline at end of file
+#endif // __AC_CCINVENTORY_H
diff --git a/engines/ags/engine/ac/dynobj/cc_object.cpp b/engines/ags/engine/ac/dynobj/cc_object.cpp
index 215ad0e469..355456e78c 100644
--- a/engines/ags/engine/ac/dynobj/cc_object.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_object.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/dynobj/cc_object.h"
 #include "ac/dynobj/scriptobject.h"
diff --git a/engines/ags/engine/ac/dynobj/cc_object.h b/engines/ags/engine/ac/dynobj/cc_object.h
index 6e65444132..f81b0d5cdf 100644
--- a/engines/ags/engine/ac/dynobj/cc_object.h
+++ b/engines/ags/engine/ac/dynobj/cc_object.h
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 __AC_CCOBJECT_H
 #define __AC_CCOBJECT_H
@@ -30,4 +38,4 @@ struct CCObject final : AGSCCDynamicObject {
 
 };
 
-#endif // __AC_CCOBJECT_H
\ No newline at end of file
+#endif // __AC_CCOBJECT_H
diff --git a/engines/ags/engine/ac/dynobj/cc_region.cpp b/engines/ags/engine/ac/dynobj/cc_region.cpp
index 92ba349118..31130c9b5e 100644
--- a/engines/ags/engine/ac/dynobj/cc_region.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_region.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/dynobj/cc_region.h"
 #include "ac/dynobj/scriptregion.h"
diff --git a/engines/ags/engine/ac/dynobj/cc_region.h b/engines/ags/engine/ac/dynobj/cc_region.h
index 626ee4e2bc..6abb7df153 100644
--- a/engines/ags/engine/ac/dynobj/cc_region.h
+++ b/engines/ags/engine/ac/dynobj/cc_region.h
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 __AC_CCREGION_H
 #define __AC_CCREGION_H
@@ -30,4 +38,4 @@ struct CCRegion final : AGSCCDynamicObject {
 
 };
 
-#endif // __AC_CCREGION_H
\ No newline at end of file
+#endif // __AC_CCREGION_H
diff --git a/engines/ags/engine/ac/dynobj/cc_serializer.cpp b/engines/ags/engine/ac/dynobj/cc_serializer.cpp
index 140613116a..f183747b98 100644
--- a/engines/ags/engine/ac/dynobj/cc_serializer.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_serializer.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 <string.h>
 #include "ac/dynobj/cc_serializer.h"
diff --git a/engines/ags/engine/ac/dynobj/cc_serializer.h b/engines/ags/engine/ac/dynobj/cc_serializer.h
index d30a8f477d..9de17b54d5 100644
--- a/engines/ags/engine/ac/dynobj/cc_serializer.h
+++ b/engines/ags/engine/ac/dynobj/cc_serializer.h
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 __AC_SERIALIZER_H
 #define __AC_SERIALIZER_H
@@ -24,4 +32,4 @@ struct AGSDeSerializer : ICCObjectReader {
 
 extern AGSDeSerializer ccUnserializer;
 
-#endif // __AC_SERIALIZER_H
\ No newline at end of file
+#endif // __AC_SERIALIZER_H
diff --git a/engines/ags/engine/ac/dynobj/managedobjectpool.cpp b/engines/ags/engine/ac/dynobj/managedobjectpool.cpp
index 422aff050f..2d43014743 100644
--- a/engines/ags/engine/ac/dynobj/managedobjectpool.cpp
+++ b/engines/ags/engine/ac/dynobj/managedobjectpool.cpp
@@ -1,16 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 <vector>
 #include <string.h>
 #include "ac/dynobj/managedobjectpool.h"
diff --git a/engines/ags/engine/ac/dynobj/managedobjectpool.h b/engines/ags/engine/ac/dynobj/managedobjectpool.h
index 6107cadb81..6697592d9b 100644
--- a/engines/ags/engine/ac/dynobj/managedobjectpool.h
+++ b/engines/ags/engine/ac/dynobj/managedobjectpool.h
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 __CC_MANAGEDOBJECTPOOL_H
 #define __CC_MANAGEDOBJECTPOOL_H
diff --git a/engines/ags/engine/ac/dynobj/scriptaudiochannel.h b/engines/ags/engine/ac/dynobj/scriptaudiochannel.h
index c256ead6e2..c8ecb6fbf8 100644
--- a/engines/ags/engine/ac/dynobj/scriptaudiochannel.h
+++ b/engines/ags/engine/ac/dynobj/scriptaudiochannel.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_DYNOBJ__SCRIPTAUDIOCHANNEL_H
 #define __AGS_EE_DYNOBJ__SCRIPTAUDIOCHANNEL_H
 
diff --git a/engines/ags/engine/ac/dynobj/scriptcamera.cpp b/engines/ags/engine/ac/dynobj/scriptcamera.cpp
index e9db1cb998..a4f44f881b 100644
--- a/engines/ags/engine/ac/dynobj/scriptcamera.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptcamera.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/dynobj/scriptcamera.h"
 #include "ac/gamestate.h"
diff --git a/engines/ags/engine/ac/dynobj/scriptcamera.h b/engines/ags/engine/ac/dynobj/scriptcamera.h
index 4aa25304e5..292e022160 100644
--- a/engines/ags/engine/ac/dynobj/scriptcamera.h
+++ b/engines/ags/engine/ac/dynobj/scriptcamera.h
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 __AC_SCRIPTCAMERA_H
 #define __AC_SCRIPTCAMERA_H
diff --git a/engines/ags/engine/ac/dynobj/scriptcontainers.h b/engines/ags/engine/ac/dynobj/scriptcontainers.h
index a0a374831a..5159a237ef 100644
--- a/engines/ags/engine/ac/dynobj/scriptcontainers.h
+++ b/engines/ags/engine/ac/dynobj/scriptcontainers.h
@@ -1,16 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 __AC_SCRIPTCONTAINERS_H
 #define __AC_SCRIPTCONTAINERS_H
 
diff --git a/engines/ags/engine/ac/dynobj/scriptdatetime.cpp b/engines/ags/engine/ac/dynobj/scriptdatetime.cpp
index eb57fbdf76..45836d06e4 100644
--- a/engines/ags/engine/ac/dynobj/scriptdatetime.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptdatetime.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/dynobj/scriptdatetime.h"
 
diff --git a/engines/ags/engine/ac/dynobj/scriptdatetime.h b/engines/ags/engine/ac/dynobj/scriptdatetime.h
index bc12bf2797..c898e93fa6 100644
--- a/engines/ags/engine/ac/dynobj/scriptdatetime.h
+++ b/engines/ags/engine/ac/dynobj/scriptdatetime.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_DYNOBJ__SCRIPTDATETIME_H
 #define __AGS_EE_DYNOBJ__SCRIPTDATETIME_H
 
diff --git a/engines/ags/engine/ac/dynobj/scriptdialog.h b/engines/ags/engine/ac/dynobj/scriptdialog.h
index 9d8222e550..f549afcd1e 100644
--- a/engines/ags/engine/ac/dynobj/scriptdialog.h
+++ b/engines/ags/engine/ac/dynobj/scriptdialog.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_DYNOBJ__SCRIPTDIALOG_H
 #define __AGS_EE_DYNOBJ__SCRIPTDIALOG_H
 
diff --git a/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.cpp b/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.cpp
index d05f638905..d844282b78 100644
--- a/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/dynobj/scriptdialogoptionsrendering.h"
 
diff --git a/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.h b/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.h
index a50d9d02e2..d13ab0e8c3 100644
--- a/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.h
+++ b/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.h
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 __AC_SCRIPTDIALOGOPTIONSRENDERING_H
 #define __AC_SCRIPTDIALOGOPTIONSRENDERING_H
@@ -44,4 +52,4 @@ struct ScriptDialogOptionsRendering final : AGSCCDynamicObject {
 };
 
 
-#endif // __AC_SCRIPTDIALOGOPTIONSRENDERING_H
\ No newline at end of file
+#endif // __AC_SCRIPTDIALOGOPTIONSRENDERING_H
diff --git a/engines/ags/engine/ac/dynobj/scriptdict.cpp b/engines/ags/engine/ac/dynobj/scriptdict.cpp
index 5676ae2603..4bec65ce42 100644
--- a/engines/ags/engine/ac/dynobj/scriptdict.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptdict.cpp
@@ -1,16 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/dynobj/scriptdict.h"
 
 int ScriptDictBase::Dispose(const char *address, bool force)
diff --git a/engines/ags/engine/ac/dynobj/scriptdict.h b/engines/ags/engine/ac/dynobj/scriptdict.h
index e89d22c10e..62039f4c76 100644
--- a/engines/ags/engine/ac/dynobj/scriptdict.h
+++ b/engines/ags/engine/ac/dynobj/scriptdict.h
@@ -1,15 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
+/* 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.
+ *
+ */
+
 //=============================================================================
 //
 // Managed script object wrapping std::map<String, String> and
@@ -22,6 +32,7 @@
 // types as keys; need to research what perfomance impact that would make.
 //
 //=============================================================================
+
 #ifndef __AC_SCRIPTDICT_H
 #define __AC_SCRIPTDICT_H
 
diff --git a/engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp b/engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp
index 1f68eb1ec5..14e66298f4 100644
--- a/engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/dynobj/scriptdrawingsurface.h"
 #include "ac/spritecache.h"
diff --git a/engines/ags/engine/ac/dynobj/scriptdrawingsurface.h b/engines/ags/engine/ac/dynobj/scriptdrawingsurface.h
index 4751be333a..8cf35a6d93 100644
--- a/engines/ags/engine/ac/dynobj/scriptdrawingsurface.h
+++ b/engines/ags/engine/ac/dynobj/scriptdrawingsurface.h
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 __AC_SCRIPTDRAWINGSURFACE_H
 #define __AC_SCRIPTDRAWINGSURFACE_H
@@ -52,4 +60,4 @@ struct ScriptDrawingSurface final : AGSCCDynamicObject {
     ScriptDrawingSurface();
 };
 
-#endif // __AC_SCRIPTDRAWINGSURFACE_H
\ No newline at end of file
+#endif // __AC_SCRIPTDRAWINGSURFACE_H
diff --git a/engines/ags/engine/ac/dynobj/scriptdynamicsprite.cpp b/engines/ags/engine/ac/dynobj/scriptdynamicsprite.cpp
index 6023eb607f..0063e7ae87 100644
--- a/engines/ags/engine/ac/dynobj/scriptdynamicsprite.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptdynamicsprite.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/dynobj/scriptdynamicsprite.h"
 #include "ac/dynamicsprite.h"
diff --git a/engines/ags/engine/ac/dynobj/scriptdynamicsprite.h b/engines/ags/engine/ac/dynobj/scriptdynamicsprite.h
index 11a53ed68d..fccb51ba38 100644
--- a/engines/ags/engine/ac/dynobj/scriptdynamicsprite.h
+++ b/engines/ags/engine/ac/dynobj/scriptdynamicsprite.h
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 __AC_SCRIPTDYNAMICSPRITE_H
 #define __AC_SCRIPTDYNAMICSPRITE_H
@@ -29,4 +37,4 @@ struct ScriptDynamicSprite final  : AGSCCDynamicObject {
     ScriptDynamicSprite();
 };
 
-#endif // __AC_SCRIPTDYNAMICSPRITE_H
\ No newline at end of file
+#endif // __AC_SCRIPTDYNAMICSPRITE_H
diff --git a/engines/ags/engine/ac/dynobj/scriptfile.cpp b/engines/ags/engine/ac/dynobj/scriptfile.cpp
index d52000c7d5..9341c5d004 100644
--- a/engines/ags/engine/ac/dynobj/scriptfile.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptfile.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/dynobj/scriptfile.h"
 #include "ac/global_file.h"
diff --git a/engines/ags/engine/ac/dynobj/scriptfile.h b/engines/ags/engine/ac/dynobj/scriptfile.h
index f039e9768e..538d79c206 100644
--- a/engines/ags/engine/ac/dynobj/scriptfile.h
+++ b/engines/ags/engine/ac/dynobj/scriptfile.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_DYNOBJ__SCRIPTFILE_H
 #define __AGS_EE_DYNOBJ__SCRIPTFILE_H
 
diff --git a/engines/ags/engine/ac/dynobj/scriptgui.h b/engines/ags/engine/ac/dynobj/scriptgui.h
index c6651a22c5..6dffd085c3 100644
--- a/engines/ags/engine/ac/dynobj/scriptgui.h
+++ b/engines/ags/engine/ac/dynobj/scriptgui.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_DYNOBJ__SCRIPTGUI_H
 #define __AGS_EE_DYNOBJ__SCRIPTGUI_H
 
diff --git a/engines/ags/engine/ac/dynobj/scripthotspot.h b/engines/ags/engine/ac/dynobj/scripthotspot.h
index 1af83a772a..181b3b2bca 100644
--- a/engines/ags/engine/ac/dynobj/scripthotspot.h
+++ b/engines/ags/engine/ac/dynobj/scripthotspot.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_DYNOBJ__SCRIPTHOTSPOT_H
 #define __AGS_EE_DYNOBJ__SCRIPTHOTSPOT_H
 
diff --git a/engines/ags/engine/ac/dynobj/scriptinvitem.h b/engines/ags/engine/ac/dynobj/scriptinvitem.h
index a614a5f5bf..e55e98dbf9 100644
--- a/engines/ags/engine/ac/dynobj/scriptinvitem.h
+++ b/engines/ags/engine/ac/dynobj/scriptinvitem.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_DYNOBJ__SCRIPTINVITEM_H
 #define __AGS_EE_DYNOBJ__SCRIPTINVITEM_H
 
diff --git a/engines/ags/engine/ac/dynobj/scriptmouse.h b/engines/ags/engine/ac/dynobj/scriptmouse.h
index d0ee4316ea..2eb0697aba 100644
--- a/engines/ags/engine/ac/dynobj/scriptmouse.h
+++ b/engines/ags/engine/ac/dynobj/scriptmouse.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_DYNOBJ__SCRIPTMOUSE_H
 #define __AGS_EE_DYNOBJ__SCRIPTMOUSE_H
 
diff --git a/engines/ags/engine/ac/dynobj/scriptobject.h b/engines/ags/engine/ac/dynobj/scriptobject.h
index 57a9ee9868..37545d2c78 100644
--- a/engines/ags/engine/ac/dynobj/scriptobject.h
+++ b/engines/ags/engine/ac/dynobj/scriptobject.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_DYNOBJ__SCRIPTOBJECT_H
 #define __AGS_EE_DYNOBJ__SCRIPTOBJECT_H
 
diff --git a/engines/ags/engine/ac/dynobj/scriptoverlay.cpp b/engines/ags/engine/ac/dynobj/scriptoverlay.cpp
index d640ab8eb6..f165a0bbcc 100644
--- a/engines/ags/engine/ac/dynobj/scriptoverlay.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptoverlay.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/dynobj/scriptoverlay.h"
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/dynobj/scriptoverlay.h b/engines/ags/engine/ac/dynobj/scriptoverlay.h
index 0b027b62bb..8b678605f5 100644
--- a/engines/ags/engine/ac/dynobj/scriptoverlay.h
+++ b/engines/ags/engine/ac/dynobj/scriptoverlay.h
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 __AC_SCRIPTOVERLAY_H
 #define __AC_SCRIPTOVERLAY_H
@@ -31,4 +39,4 @@ struct ScriptOverlay final : AGSCCDynamicObject {
     ScriptOverlay();
 };
 
-#endif // __AC_SCRIPTOVERLAY_H
\ No newline at end of file
+#endif // __AC_SCRIPTOVERLAY_H
diff --git a/engines/ags/engine/ac/dynobj/scriptregion.h b/engines/ags/engine/ac/dynobj/scriptregion.h
index 9e2aff4fb3..4bf38a95c7 100644
--- a/engines/ags/engine/ac/dynobj/scriptregion.h
+++ b/engines/ags/engine/ac/dynobj/scriptregion.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_DYNOBJ__SCRIPTREGION_H
 #define __AGS_EE_DYNOBJ__SCRIPTREGION_H
 
diff --git a/engines/ags/engine/ac/dynobj/scriptset.cpp b/engines/ags/engine/ac/dynobj/scriptset.cpp
index 472671add1..a17a48c1ff 100644
--- a/engines/ags/engine/ac/dynobj/scriptset.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptset.cpp
@@ -1,16 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/dynobj/scriptset.h"
 
 int ScriptSetBase::Dispose(const char *address, bool force)
diff --git a/engines/ags/engine/ac/dynobj/scriptset.h b/engines/ags/engine/ac/dynobj/scriptset.h
index 12dc89c914..d5ad8a9155 100644
--- a/engines/ags/engine/ac/dynobj/scriptset.h
+++ b/engines/ags/engine/ac/dynobj/scriptset.h
@@ -1,15 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
+/* 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.
+ *
+ */
+
 //=============================================================================
 //
 // Managed script object wrapping std::set<String> and unordered_set<String>.
@@ -21,6 +31,7 @@
 // types as keys; need to research what perfomance impact that would make.
 //
 //=============================================================================
+
 #ifndef __AC_SCRIPTSET_H
 #define __AC_SCRIPTSET_H
 
diff --git a/engines/ags/engine/ac/dynobj/scriptstring.cpp b/engines/ags/engine/ac/dynobj/scriptstring.cpp
index d130d63e5b..be95335bd8 100644
--- a/engines/ags/engine/ac/dynobj/scriptstring.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptstring.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/dynobj/scriptstring.h"
 #include "ac/string.h"
diff --git a/engines/ags/engine/ac/dynobj/scriptstring.h b/engines/ags/engine/ac/dynobj/scriptstring.h
index 916d48998d..041f3b3f32 100644
--- a/engines/ags/engine/ac/dynobj/scriptstring.h
+++ b/engines/ags/engine/ac/dynobj/scriptstring.h
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 __AC_SCRIPTSTRING_H
 #define __AC_SCRIPTSTRING_H
@@ -31,4 +39,4 @@ struct ScriptString final : AGSCCDynamicObject, ICCStringClass {
     ScriptString(const char *fromText);
 };
 
-#endif // __AC_SCRIPTSTRING_H
\ No newline at end of file
+#endif // __AC_SCRIPTSTRING_H
diff --git a/engines/ags/engine/ac/dynobj/scriptsystem.h b/engines/ags/engine/ac/dynobj/scriptsystem.h
index e7c29b3d7a..815d30cb02 100644
--- a/engines/ags/engine/ac/dynobj/scriptsystem.h
+++ b/engines/ags/engine/ac/dynobj/scriptsystem.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_DYNOBJ__SCRIPTSYSTEM_H
 #define __AGS_EE_DYNOBJ__SCRIPTSYSTEM_H
 
diff --git a/engines/ags/engine/ac/dynobj/scriptuserobject.cpp b/engines/ags/engine/ac/dynobj/scriptuserobject.cpp
index 4b70941a13..b3cdb00bcf 100644
--- a/engines/ags/engine/ac/dynobj/scriptuserobject.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptuserobject.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 <memory.h>
 #include "scriptuserobject.h"
diff --git a/engines/ags/engine/ac/dynobj/scriptuserobject.h b/engines/ags/engine/ac/dynobj/scriptuserobject.h
index 931bdaa23c..36bfe28909 100644
--- a/engines/ags/engine/ac/dynobj/scriptuserobject.h
+++ b/engines/ags/engine/ac/dynobj/scriptuserobject.h
@@ -1,20 +1,31 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
+/* 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.
+ *
+ */
+
 //=============================================================================
 //
 // Managed object, which size and contents are defined by user script
 //
 //=============================================================================
+
 #ifndef __AGS_EE_DYNOBJ__SCRIPTUSERSTRUCT_H
 #define __AGS_EE_DYNOBJ__SCRIPTUSERSTRUCT_H
 
diff --git a/engines/ags/engine/ac/dynobj/scriptviewframe.cpp b/engines/ags/engine/ac/dynobj/scriptviewframe.cpp
index 803269a46f..955af85f63 100644
--- a/engines/ags/engine/ac/dynobj/scriptviewframe.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptviewframe.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/dynobj/scriptviewframe.h"
 
diff --git a/engines/ags/engine/ac/dynobj/scriptviewframe.h b/engines/ags/engine/ac/dynobj/scriptviewframe.h
index 1abb47e6d9..83ad44b88f 100644
--- a/engines/ags/engine/ac/dynobj/scriptviewframe.h
+++ b/engines/ags/engine/ac/dynobj/scriptviewframe.h
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 __AC_SCRIPTVIEWFRAME_H
 #define __AC_SCRIPTVIEWFRAME_H
@@ -29,4 +37,4 @@ struct ScriptViewFrame final : AGSCCDynamicObject {
     ScriptViewFrame();
 };
 
-#endif // __AC_SCRIPTVIEWFRAME_H
\ No newline at end of file
+#endif // __AC_SCRIPTVIEWFRAME_H
diff --git a/engines/ags/engine/ac/dynobj/scriptviewport.cpp b/engines/ags/engine/ac/dynobj/scriptviewport.cpp
index 0bd8a0af4f..f2563a5662 100644
--- a/engines/ags/engine/ac/dynobj/scriptviewport.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptviewport.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/dynobj/scriptviewport.h"
 #include "ac/gamestate.h"
diff --git a/engines/ags/engine/ac/dynobj/scriptviewport.h b/engines/ags/engine/ac/dynobj/scriptviewport.h
index d742dfe12d..a9fe886283 100644
--- a/engines/ags/engine/ac/dynobj/scriptviewport.h
+++ b/engines/ags/engine/ac/dynobj/scriptviewport.h
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 __AC_SCRIPTVIEWPORT_H
 #define __AC_SCRIPTVIEWPORT_H
diff --git a/engines/ags/engine/ac/event.cpp b/engines/ags/engine/ac/event.cpp
index dc3bf6f6f8..c2960351c4 100644
--- a/engines/ags/engine/ac/event.cpp
+++ b/engines/ags/engine/ac/event.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "event.h"
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/event.h b/engines/ags/engine/ac/event.h
index 6c4b843de5..78e7b486e9 100644
--- a/engines/ags/engine/ac/event.h
+++ b/engines/ags/engine/ac/event.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__EVENT_H
 #define __AGS_EE_AC__EVENT_H
 
diff --git a/engines/ags/engine/ac/file.cpp b/engines/ags/engine/ac/file.cpp
index ebb1fec45a..99a18b531d 100644
--- a/engines/ags/engine/ac/file.cpp
+++ b/engines/ags/engine/ac/file.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "aldumb.h"
 #include "ac/asset_helper.h"
diff --git a/engines/ags/engine/ac/file.h b/engines/ags/engine/ac/file.h
index cc12e75206..0f0b2aeac8 100644
--- a/engines/ags/engine/ac/file.h
+++ b/engines/ags/engine/ac/file.h
@@ -1,20 +1,31 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
+/* 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.
+ *
+ */
+
 //=============================================================================
 //
 // Script File API implementation.
 //
 //=============================================================================
+
 #ifndef __AGS_EE_AC__FILE_H
 #define __AGS_EE_AC__FILE_H
 
diff --git a/engines/ags/engine/ac/game.cpp b/engines/ags/engine/ac/game.cpp
index ac3f6dc70a..220349f2c0 100644
--- a/engines/ags/engine/ac/game.cpp
+++ b/engines/ags/engine/ac/game.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/game.h"
 
diff --git a/engines/ags/engine/ac/game.h b/engines/ags/engine/ac/game.h
index 9bed7f02c2..c09fc59b24 100644
--- a/engines/ags/engine/ac/game.h
+++ b/engines/ags/engine/ac/game.h
@@ -1,15 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
+/* 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.
+ *
+ */
+
 //=============================================================================
 //
 // AGS Runtime header
diff --git a/engines/ags/engine/ac/gamesetup.cpp b/engines/ags/engine/ac/gamesetup.cpp
index 88a22f4fce..6dc749f381 100644
--- a/engines/ags/engine/ac/gamesetup.cpp
+++ b/engines/ags/engine/ac/gamesetup.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "util/wgt2allg.h" // DIGI_AUTODETECT & MIDI_AUTODETECT
 #include "ac/gamesetup.h"
diff --git a/engines/ags/engine/ac/gamesetup.h b/engines/ags/engine/ac/gamesetup.h
index 672eb66d91..54708a26cd 100644
--- a/engines/ags/engine/ac/gamesetup.h
+++ b/engines/ags/engine/ac/gamesetup.h
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 __AC_GAMESETUP_H
 #define __AC_GAMESETUP_H
@@ -83,4 +91,4 @@ struct GameSetup {
 // Perhaps it makes sense to separate those two group of vars at some point.
 extern GameSetup usetup;
 
-#endif // __AC_GAMESETUP_H
\ No newline at end of file
+#endif // __AC_GAMESETUP_H
diff --git a/engines/ags/engine/ac/gamestate.cpp b/engines/ags/engine/ac/gamestate.cpp
index da4ec8079d..0366ec5e68 100644
--- a/engines/ags/engine/ac/gamestate.cpp
+++ b/engines/ags/engine/ac/gamestate.cpp
@@ -1,16 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 <algorithm>
 #include "ac/draw.h"
 #include "ac/game_version.h"
diff --git a/engines/ags/engine/ac/gamestate.h b/engines/ags/engine/ac/gamestate.h
index b5843c130c..413b508b46 100644
--- a/engines/ags/engine/ac/gamestate.h
+++ b/engines/ags/engine/ac/gamestate.h
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 __AC_GAMESTATE_H
 #define __AC_GAMESTATE_H
diff --git a/engines/ags/engine/ac/global_api.cpp b/engines/ags/engine/ac/global_api.cpp
index f7e6d4474d..ce838680e8 100644
--- a/engines/ags/engine/ac/global_api.cpp
+++ b/engines/ags/engine/ac/global_api.cpp
@@ -1,15 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
+/* 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.
+ *
+ */
+
 //=============================================================================
 //
 // Script API Functions
diff --git a/engines/ags/engine/ac/global_audio.cpp b/engines/ags/engine/ac/global_audio.cpp
index cf232e91f5..85899b47c3 100644
--- a/engines/ags/engine/ac/global_audio.cpp
+++ b/engines/ags/engine/ac/global_audio.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/common.h"
 #include "ac/game.h"
diff --git a/engines/ags/engine/ac/global_audio.h b/engines/ags/engine/ac/global_audio.h
index 9c9b557678..9bf1c5b95b 100644
--- a/engines/ags/engine/ac/global_audio.h
+++ b/engines/ags/engine/ac/global_audio.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALAUDIO_H
 #define __AGS_EE_AC__GLOBALAUDIO_H
 
diff --git a/engines/ags/engine/ac/global_button.cpp b/engines/ags/engine/ac/global_button.cpp
index f2d66f585a..e122ad6201 100644
--- a/engines/ags/engine/ac/global_button.cpp
+++ b/engines/ags/engine/ac/global_button.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/global_button.h"
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/global_button.h b/engines/ags/engine/ac/global_button.h
index cb98cb53e2..d4f2561e91 100644
--- a/engines/ags/engine/ac/global_button.h
+++ b/engines/ags/engine/ac/global_button.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALBUTTON_H
 #define __AGS_EE_AC__GLOBALBUTTON_H
 
diff --git a/engines/ags/engine/ac/global_character.cpp b/engines/ags/engine/ac/global_character.cpp
index 39f018ce68..6788617f2b 100644
--- a/engines/ags/engine/ac/global_character.cpp
+++ b/engines/ags/engine/ac/global_character.cpp
@@ -1,15 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
+/* 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.
+ *
+ */
+
 //=============================================================================
 //
 // AGS Character functions
diff --git a/engines/ags/engine/ac/global_character.h b/engines/ags/engine/ac/global_character.h
index ad066c3ad2..48483a03a3 100644
--- a/engines/ags/engine/ac/global_character.h
+++ b/engines/ags/engine/ac/global_character.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALCHARACTER_H
 #define __AGS_EE_AC__GLOBALCHARACTER_H
 
diff --git a/engines/ags/engine/ac/global_datetime.cpp b/engines/ags/engine/ac/global_datetime.cpp
index e89311efc0..700005ceb2 100644
--- a/engines/ags/engine/ac/global_datetime.cpp
+++ b/engines/ags/engine/ac/global_datetime.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 <time.h>
 #include "ac/global_datetime.h"
diff --git a/engines/ags/engine/ac/global_datetime.h b/engines/ags/engine/ac/global_datetime.h
index 59080d1a7a..caf287111c 100644
--- a/engines/ags/engine/ac/global_datetime.h
+++ b/engines/ags/engine/ac/global_datetime.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALDATETIME_H
 #define __AGS_EE_AC__GLOBALDATETIME_H
 
diff --git a/engines/ags/engine/ac/global_debug.cpp b/engines/ags/engine/ac/global_debug.cpp
index 582e1d2009..41f9ac5d23 100644
--- a/engines/ags/engine/ac/global_debug.cpp
+++ b/engines/ags/engine/ac/global_debug.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/global_debug.h"
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/global_debug.h b/engines/ags/engine/ac/global_debug.h
index a4d50d0d4f..bdaabba917 100644
--- a/engines/ags/engine/ac/global_debug.h
+++ b/engines/ags/engine/ac/global_debug.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALDEBUG_H
 #define __AGS_EE_AC__GLOBALDEBUG_H
 
diff --git a/engines/ags/engine/ac/global_dialog.cpp b/engines/ags/engine/ac/global_dialog.cpp
index dbab9333a7..5115355e9d 100644
--- a/engines/ags/engine/ac/global_dialog.cpp
+++ b/engines/ags/engine/ac/global_dialog.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/global_dialog.h"
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/global_dialog.h b/engines/ags/engine/ac/global_dialog.h
index feb16ae10f..7dc7e0e724 100644
--- a/engines/ags/engine/ac/global_dialog.h
+++ b/engines/ags/engine/ac/global_dialog.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALDIALOG_H
 #define __AGS_EE_AC__GLOBALDIALOG_H
 
diff --git a/engines/ags/engine/ac/global_display.cpp b/engines/ags/engine/ac/global_display.cpp
index dfcd76bcc4..06398c1ef8 100644
--- a/engines/ags/engine/ac/global_display.cpp
+++ b/engines/ags/engine/ac/global_display.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 <cstdio>
 #include <stdarg.h>
diff --git a/engines/ags/engine/ac/global_display.h b/engines/ags/engine/ac/global_display.h
index 538d293924..226e5fa986 100644
--- a/engines/ags/engine/ac/global_display.h
+++ b/engines/ags/engine/ac/global_display.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALDISPLAY_H
 #define __AGS_EE_AC__GLOBALDISPLAY_H
 
diff --git a/engines/ags/engine/ac/global_drawingsurface.cpp b/engines/ags/engine/ac/global_drawingsurface.cpp
index 4003c78f65..2c5dea5b3d 100644
--- a/engines/ags/engine/ac/global_drawingsurface.cpp
+++ b/engines/ags/engine/ac/global_drawingsurface.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/common.h"
 #include "ac/display.h"
diff --git a/engines/ags/engine/ac/global_drawingsurface.h b/engines/ags/engine/ac/global_drawingsurface.h
index d62ea61909..c755113faa 100644
--- a/engines/ags/engine/ac/global_drawingsurface.h
+++ b/engines/ags/engine/ac/global_drawingsurface.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALDRAWINGSURFACE_H
 #define __AGS_EE_AC__GLOBALDRAWINGSURFACE_H
 
diff --git a/engines/ags/engine/ac/global_dynamicsprite.cpp b/engines/ags/engine/ac/global_dynamicsprite.cpp
index b77a3f3c7a..00898e7cfc 100644
--- a/engines/ags/engine/ac/global_dynamicsprite.cpp
+++ b/engines/ags/engine/ac/global_dynamicsprite.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/global_dynamicsprite.h"
 #include "util/wgt2allg.h" // Allegro RGB, PALETTE
diff --git a/engines/ags/engine/ac/global_dynamicsprite.h b/engines/ags/engine/ac/global_dynamicsprite.h
index a6f3ea8cca..82b264c167 100644
--- a/engines/ags/engine/ac/global_dynamicsprite.h
+++ b/engines/ags/engine/ac/global_dynamicsprite.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALDYNAMICSPRITE_H
 #define __AGS_EE_AC__GLOBALDYNAMICSPRITE_H
 
diff --git a/engines/ags/engine/ac/global_file.cpp b/engines/ags/engine/ac/global_file.cpp
index d88a295cbb..d2fb8775b4 100644
--- a/engines/ags/engine/ac/global_file.cpp
+++ b/engines/ags/engine/ac/global_file.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 <string.h>
 #include "ac/global_file.h"
diff --git a/engines/ags/engine/ac/global_file.h b/engines/ags/engine/ac/global_file.h
index 1e827088ee..be67d1288c 100644
--- a/engines/ags/engine/ac/global_file.h
+++ b/engines/ags/engine/ac/global_file.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALFILE_H
 #define __AGS_EE_AC__GLOBALFILE_H
 
diff --git a/engines/ags/engine/ac/global_game.cpp b/engines/ags/engine/ac/global_game.cpp
index 40e263122c..1939308192 100644
--- a/engines/ags/engine/ac/global_game.cpp
+++ b/engines/ags/engine/ac/global_game.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 <math.h>
 
diff --git a/engines/ags/engine/ac/global_game.h b/engines/ags/engine/ac/global_game.h
index 25e471a733..93c309bfc9 100644
--- a/engines/ags/engine/ac/global_game.h
+++ b/engines/ags/engine/ac/global_game.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALGAME_H
 #define __AGS_EE_AC__GLOBALGAME_H
 
diff --git a/engines/ags/engine/ac/global_gui.cpp b/engines/ags/engine/ac/global_gui.cpp
index 3c8e6250ac..ba3134ab59 100644
--- a/engines/ags/engine/ac/global_gui.cpp
+++ b/engines/ags/engine/ac/global_gui.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/common.h"
 #include "ac/display.h"
diff --git a/engines/ags/engine/ac/global_gui.h b/engines/ags/engine/ac/global_gui.h
index 2047fecc4b..ef18f75eab 100644
--- a/engines/ags/engine/ac/global_gui.h
+++ b/engines/ags/engine/ac/global_gui.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALGUI_H
 #define __AGS_EE_AC__GLOBALGUI_H
 
diff --git a/engines/ags/engine/ac/global_hotspot.cpp b/engines/ags/engine/ac/global_hotspot.cpp
index cab508f562..55da388454 100644
--- a/engines/ags/engine/ac/global_hotspot.cpp
+++ b/engines/ags/engine/ac/global_hotspot.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/global_hotspot.h"
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/global_hotspot.h b/engines/ags/engine/ac/global_hotspot.h
index ec595042ea..b19c05f587 100644
--- a/engines/ags/engine/ac/global_hotspot.h
+++ b/engines/ags/engine/ac/global_hotspot.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALHOTSPOT_H
 #define __AGS_EE_AC__GLOBALHOTSPOT_H
 
diff --git a/engines/ags/engine/ac/global_inventoryitem.cpp b/engines/ags/engine/ac/global_inventoryitem.cpp
index 4180cc283c..680b6afd47 100644
--- a/engines/ags/engine/ac/global_inventoryitem.cpp
+++ b/engines/ags/engine/ac/global_inventoryitem.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/common.h"
 #include "ac/gamesetupstruct.h"
diff --git a/engines/ags/engine/ac/global_inventoryitem.h b/engines/ags/engine/ac/global_inventoryitem.h
index 840bb73e0e..af2590db77 100644
--- a/engines/ags/engine/ac/global_inventoryitem.h
+++ b/engines/ags/engine/ac/global_inventoryitem.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALINVENTORYITEM_H
 #define __AGS_EE_AC__GLOBALINVENTORYITEM_H
 
diff --git a/engines/ags/engine/ac/global_invwindow.cpp b/engines/ags/engine/ac/global_invwindow.cpp
index edd4ed926b..d09043e99a 100644
--- a/engines/ags/engine/ac/global_invwindow.cpp
+++ b/engines/ags/engine/ac/global_invwindow.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/gamestate.h"
 #include "ac/global_invwindow.h"
diff --git a/engines/ags/engine/ac/global_invwindow.h b/engines/ags/engine/ac/global_invwindow.h
index afa1d25c5c..02a51d9f4b 100644
--- a/engines/ags/engine/ac/global_invwindow.h
+++ b/engines/ags/engine/ac/global_invwindow.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALINVWINDOW_H
 #define __AGS_EE_AC__GLOBALINVWINDOW_H
 
diff --git a/engines/ags/engine/ac/global_label.cpp b/engines/ags/engine/ac/global_label.cpp
index 7a0335e937..a7e4cad662 100644
--- a/engines/ags/engine/ac/global_label.cpp
+++ b/engines/ags/engine/ac/global_label.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/global_label.h"
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/global_label.h b/engines/ags/engine/ac/global_label.h
index fa96942f75..c3f0cb49f0 100644
--- a/engines/ags/engine/ac/global_label.h
+++ b/engines/ags/engine/ac/global_label.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALLABEL_H
 #define __AGS_EE_AC__GLOBALLABEL_H
 
diff --git a/engines/ags/engine/ac/global_listbox.cpp b/engines/ags/engine/ac/global_listbox.cpp
index 546eac2e00..f5d93df57f 100644
--- a/engines/ags/engine/ac/global_listbox.cpp
+++ b/engines/ags/engine/ac/global_listbox.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/global_listbox.h"
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/global_listbox.h b/engines/ags/engine/ac/global_listbox.h
index d6be2f449f..f49cc5bd7c 100644
--- a/engines/ags/engine/ac/global_listbox.h
+++ b/engines/ags/engine/ac/global_listbox.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALLISTBOX_H
 #define __AGS_EE_AC__GLOBALLISTBOX_H
 
diff --git a/engines/ags/engine/ac/global_mouse.cpp b/engines/ags/engine/ac/global_mouse.cpp
index 206f502977..a17871e828 100644
--- a/engines/ags/engine/ac/global_mouse.cpp
+++ b/engines/ags/engine/ac/global_mouse.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/global_mouse.h"
 #include "ac/gamestate.h"
diff --git a/engines/ags/engine/ac/global_mouse.h b/engines/ags/engine/ac/global_mouse.h
index dbff7fa386..5a0345518d 100644
--- a/engines/ags/engine/ac/global_mouse.h
+++ b/engines/ags/engine/ac/global_mouse.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALMOUSE_H
 #define __AGS_EE_AC__GLOBALMOUSE_H
 
diff --git a/engines/ags/engine/ac/global_object.cpp b/engines/ags/engine/ac/global_object.cpp
index aa43d906b7..1132b8184a 100644
--- a/engines/ags/engine/ac/global_object.cpp
+++ b/engines/ags/engine/ac/global_object.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/global_object.h"
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/global_object.h b/engines/ags/engine/ac/global_object.h
index ac4a877657..4eed9fd27c 100644
--- a/engines/ags/engine/ac/global_object.h
+++ b/engines/ags/engine/ac/global_object.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALOBJECT_H
 #define __AGS_EE_AC__GLOBALOBJECT_H
 
diff --git a/engines/ags/engine/ac/global_overlay.cpp b/engines/ags/engine/ac/global_overlay.cpp
index d952581034..99f67a9fc5 100644
--- a/engines/ags/engine/ac/global_overlay.cpp
+++ b/engines/ags/engine/ac/global_overlay.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/global_overlay.h"
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/global_overlay.h b/engines/ags/engine/ac/global_overlay.h
index 0282bdc868..4e43a54b51 100644
--- a/engines/ags/engine/ac/global_overlay.h
+++ b/engines/ags/engine/ac/global_overlay.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALOVERLAY_H
 #define __AGS_EE_AC__GLOBALOVERLAY_H
 
diff --git a/engines/ags/engine/ac/global_palette.cpp b/engines/ags/engine/ac/global_palette.cpp
index 8904889765..0fb925f050 100644
--- a/engines/ags/engine/ac/global_palette.cpp
+++ b/engines/ags/engine/ac/global_palette.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/common.h"
 #include "ac/draw.h"
diff --git a/engines/ags/engine/ac/global_palette.h b/engines/ags/engine/ac/global_palette.h
index 95b03d449d..9a131d52ce 100644
--- a/engines/ags/engine/ac/global_palette.h
+++ b/engines/ags/engine/ac/global_palette.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALPALETTE_H
 #define __AGS_EE_AC__GLOBALPALETTE_H
 
diff --git a/engines/ags/engine/ac/global_parser.cpp b/engines/ags/engine/ac/global_parser.cpp
index eae49baf92..a51a151e20 100644
--- a/engines/ags/engine/ac/global_parser.cpp
+++ b/engines/ags/engine/ac/global_parser.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 <cstring> //strcpy()
 #include "ac/global_parser.h"
diff --git a/engines/ags/engine/ac/global_parser.h b/engines/ags/engine/ac/global_parser.h
index 07ceebd3a6..427723dff6 100644
--- a/engines/ags/engine/ac/global_parser.h
+++ b/engines/ags/engine/ac/global_parser.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALPARSER_H
 #define __AGS_EE_AC__GLOBALPARSER_H
 
diff --git a/engines/ags/engine/ac/global_plugin.h b/engines/ags/engine/ac/global_plugin.h
index e3e1a9c281..9fdae6e20e 100644
--- a/engines/ags/engine/ac/global_plugin.h
+++ b/engines/ags/engine/ac/global_plugin.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_PLUGIN__PLUGINFUNC_H
 #define __AGS_EE_PLUGIN__PLUGINFUNC_H
 
diff --git a/engines/ags/engine/ac/global_record.cpp b/engines/ags/engine/ac/global_record.cpp
index afada9a47e..5b799f5290 100644
--- a/engines/ags/engine/ac/global_record.cpp
+++ b/engines/ags/engine/ac/global_record.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/global_record.h"
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/global_record.h b/engines/ags/engine/ac/global_record.h
index 51c4972f56..adc9f60946 100644
--- a/engines/ags/engine/ac/global_record.h
+++ b/engines/ags/engine/ac/global_record.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALRECORD_H
 #define __AGS_EE_AC__GLOBALRECORD_H
 
diff --git a/engines/ags/engine/ac/global_region.cpp b/engines/ags/engine/ac/global_region.cpp
index 6c14421312..1ee83973fe 100644
--- a/engines/ags/engine/ac/global_region.cpp
+++ b/engines/ags/engine/ac/global_region.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/global_region.h"
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/global_region.h b/engines/ags/engine/ac/global_region.h
index 40c65e0eeb..5dbfdd382f 100644
--- a/engines/ags/engine/ac/global_region.h
+++ b/engines/ags/engine/ac/global_region.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALREGION_H
 #define __AGS_EE_AC__GLOBALREGION_H
 
diff --git a/engines/ags/engine/ac/global_room.cpp b/engines/ags/engine/ac/global_room.cpp
index daccbd40bb..e3f35b833a 100644
--- a/engines/ags/engine/ac/global_room.cpp
+++ b/engines/ags/engine/ac/global_room.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/global_room.h"
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/global_room.h b/engines/ags/engine/ac/global_room.h
index 4028423a17..f19a849f67 100644
--- a/engines/ags/engine/ac/global_room.h
+++ b/engines/ags/engine/ac/global_room.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALROOM_H
 #define __AGS_EE_AC__GLOBALROOM_H
 
diff --git a/engines/ags/engine/ac/global_screen.cpp b/engines/ags/engine/ac/global_screen.cpp
index 2a77a12914..7b6846ee7e 100644
--- a/engines/ags/engine/ac/global_screen.cpp
+++ b/engines/ags/engine/ac/global_screen.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/common.h"
 #include "ac/gamesetup.h"
diff --git a/engines/ags/engine/ac/global_screen.h b/engines/ags/engine/ac/global_screen.h
index 7158285d8a..a412ae37d9 100644
--- a/engines/ags/engine/ac/global_screen.h
+++ b/engines/ags/engine/ac/global_screen.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALSCREEN_H
 #define __AGS_EE_AC__GLOBALSCREEN_H
 
diff --git a/engines/ags/engine/ac/global_slider.cpp b/engines/ags/engine/ac/global_slider.cpp
index 613f2a1283..d8847ec22b 100644
--- a/engines/ags/engine/ac/global_slider.cpp
+++ b/engines/ags/engine/ac/global_slider.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/global_slider.h"
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/global_slider.h b/engines/ags/engine/ac/global_slider.h
index 27e0edf9b3..bf6b59f336 100644
--- a/engines/ags/engine/ac/global_slider.h
+++ b/engines/ags/engine/ac/global_slider.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALSLIDER_H
 #define __AGS_EE_AC__GLOBALSLIDER_H
 
diff --git a/engines/ags/engine/ac/global_string.cpp b/engines/ags/engine/ac/global_string.cpp
index 7851ae91d2..598e9ec767 100644
--- a/engines/ags/engine/ac/global_string.cpp
+++ b/engines/ags/engine/ac/global_string.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 <string.h>
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/global_string.h b/engines/ags/engine/ac/global_string.h
index 9196666191..6369fae8fa 100644
--- a/engines/ags/engine/ac/global_string.h
+++ b/engines/ags/engine/ac/global_string.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALSTRING_H
 #define __AGS_EE_AC__GLOBALSTRING_H
 
diff --git a/engines/ags/engine/ac/global_textbox.cpp b/engines/ags/engine/ac/global_textbox.cpp
index 672c0807e2..ddd6f1fe12 100644
--- a/engines/ags/engine/ac/global_textbox.cpp
+++ b/engines/ags/engine/ac/global_textbox.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/global_textbox.h"
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/global_textbox.h b/engines/ags/engine/ac/global_textbox.h
index 1962f4f30c..f5e6f9cf85 100644
--- a/engines/ags/engine/ac/global_textbox.h
+++ b/engines/ags/engine/ac/global_textbox.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALTEXTBOX_H
 #define __AGS_EE_AC__GLOBALTEXTBOX_H
 
diff --git a/engines/ags/engine/ac/global_timer.cpp b/engines/ags/engine/ac/global_timer.cpp
index 4f197d889a..86c080a10f 100644
--- a/engines/ags/engine/ac/global_timer.cpp
+++ b/engines/ags/engine/ac/global_timer.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/global_timer.h"
 #include "ac/runtime_defines.h"
diff --git a/engines/ags/engine/ac/global_timer.h b/engines/ags/engine/ac/global_timer.h
index 589a97ee8d..b244766b82 100644
--- a/engines/ags/engine/ac/global_timer.h
+++ b/engines/ags/engine/ac/global_timer.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALTIMER_H
 #define __AGS_EE_AC__GLOBALTIMER_H
 
diff --git a/engines/ags/engine/ac/global_translation.cpp b/engines/ags/engine/ac/global_translation.cpp
index f793e11194..fb86e11e68 100644
--- a/engines/ags/engine/ac/global_translation.cpp
+++ b/engines/ags/engine/ac/global_translation.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 <string.h>
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/global_translation.h b/engines/ags/engine/ac/global_translation.h
index b506fd9498..0e6d0b1008 100644
--- a/engines/ags/engine/ac/global_translation.h
+++ b/engines/ags/engine/ac/global_translation.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALTRANSLATION_H
 #define __AGS_EE_AC__GLOBALTRANSLATION_H
 
diff --git a/engines/ags/engine/ac/global_video.cpp b/engines/ags/engine/ac/global_video.cpp
index 438fcc8337..89da7e59ff 100644
--- a/engines/ags/engine/ac/global_video.cpp
+++ b/engines/ags/engine/ac/global_video.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 <allegro.h>
 #include "ac/gamesetup.h"
@@ -82,4 +90,4 @@ void pause_sound_if_necessary_and_play_video(const char *name, int skip, int fla
 
 void pause_sound_if_necessary_and_play_video(const char *name, int skip, int flags) {}
 
-#endif
\ No newline at end of file
+#endif
diff --git a/engines/ags/engine/ac/global_video.h b/engines/ags/engine/ac/global_video.h
index c3fa993847..a297fa2151 100644
--- a/engines/ags/engine/ac/global_video.h
+++ b/engines/ags/engine/ac/global_video.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALVIDEO_H
 #define __AGS_EE_AC__GLOBALVIDEO_H
 
diff --git a/engines/ags/engine/ac/global_viewframe.cpp b/engines/ags/engine/ac/global_viewframe.cpp
index 81d55ca1b0..08a4486b0e 100644
--- a/engines/ags/engine/ac/global_viewframe.cpp
+++ b/engines/ags/engine/ac/global_viewframe.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/global_viewframe.h"
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/global_viewframe.h b/engines/ags/engine/ac/global_viewframe.h
index b92c3400b7..140c09ddbd 100644
--- a/engines/ags/engine/ac/global_viewframe.h
+++ b/engines/ags/engine/ac/global_viewframe.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALVIEWFRAME_H
 #define __AGS_EE_AC__GLOBALVIEWFRAME_H
 
diff --git a/engines/ags/engine/ac/global_viewport.cpp b/engines/ags/engine/ac/global_viewport.cpp
index ea2b1dd8a2..88397ecd20 100644
--- a/engines/ags/engine/ac/global_viewport.cpp
+++ b/engines/ags/engine/ac/global_viewport.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/global_viewport.h"
 #include "ac/draw.h"
diff --git a/engines/ags/engine/ac/global_viewport.h b/engines/ags/engine/ac/global_viewport.h
index 5c3903cb5e..d56d7efc8a 100644
--- a/engines/ags/engine/ac/global_viewport.h
+++ b/engines/ags/engine/ac/global_viewport.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALVIEWPORT_H
 #define __AGS_EE_AC__GLOBALVIEWPORT_H
 
diff --git a/engines/ags/engine/ac/global_walkablearea.cpp b/engines/ags/engine/ac/global_walkablearea.cpp
index 219333f3dd..584b6a702f 100644
--- a/engines/ags/engine/ac/global_walkablearea.cpp
+++ b/engines/ags/engine/ac/global_walkablearea.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/global_walkablearea.h"
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/global_walkablearea.h b/engines/ags/engine/ac/global_walkablearea.h
index 87f6ab811d..4e4b7aeb2a 100644
--- a/engines/ags/engine/ac/global_walkablearea.h
+++ b/engines/ags/engine/ac/global_walkablearea.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALWALKABLEAREA_H
 #define __AGS_EE_AC__GLOBALWALKABLEAREA_H
 
diff --git a/engines/ags/engine/ac/global_walkbehind.cpp b/engines/ags/engine/ac/global_walkbehind.cpp
index 4e0181a475..3a14fde331 100644
--- a/engines/ags/engine/ac/global_walkbehind.cpp
+++ b/engines/ags/engine/ac/global_walkbehind.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/global_walkbehind.h"
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/global_walkbehind.h b/engines/ags/engine/ac/global_walkbehind.h
index acf56b9472..9c3d554cb2 100644
--- a/engines/ags/engine/ac/global_walkbehind.h
+++ b/engines/ags/engine/ac/global_walkbehind.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GLOBALWALKBEHIND_H
 #define __AGS_EE_AC__GLOBALWALKBEHIND_H
 
diff --git a/engines/ags/engine/ac/gui.cpp b/engines/ags/engine/ac/gui.cpp
index 330674102d..deb12cf0ed 100644
--- a/engines/ags/engine/ac/gui.cpp
+++ b/engines/ags/engine/ac/gui.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 <cstdio>
 #include "ac/gui.h"
diff --git a/engines/ags/engine/ac/gui.h b/engines/ags/engine/ac/gui.h
index 6bdcbdc049..371fc7a9c5 100644
--- a/engines/ags/engine/ac/gui.h
+++ b/engines/ags/engine/ac/gui.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GUI_H
 #define __AGS_EE_AC__GUI_H
 
diff --git a/engines/ags/engine/ac/guicontrol.cpp b/engines/ags/engine/ac/guicontrol.cpp
index b007330da0..2587cac7eb 100644
--- a/engines/ags/engine/ac/guicontrol.cpp
+++ b/engines/ags/engine/ac/guicontrol.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/common.h"
 #include "ac/guicontrol.h"
diff --git a/engines/ags/engine/ac/guicontrol.h b/engines/ags/engine/ac/guicontrol.h
index aa9ec3ad4c..03b11b8dbd 100644
--- a/engines/ags/engine/ac/guicontrol.h
+++ b/engines/ags/engine/ac/guicontrol.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__GUICONTROL_H
 #define __AGS_EE_AC__GUICONTROL_H
 
diff --git a/engines/ags/engine/ac/guiinv.cpp b/engines/ags/engine/ac/guiinv.cpp
index 411bca2ec0..cb56307b1d 100644
--- a/engines/ags/engine/ac/guiinv.cpp
+++ b/engines/ags/engine/ac/guiinv.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "gui/guiinv.h"
 #include "gui/guimain.h"
diff --git a/engines/ags/engine/ac/hotspot.cpp b/engines/ags/engine/ac/hotspot.cpp
index bca406d772..a013cbffa8 100644
--- a/engines/ags/engine/ac/hotspot.cpp
+++ b/engines/ags/engine/ac/hotspot.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/dynobj/cc_hotspot.h"
 #include "ac/hotspot.h"
diff --git a/engines/ags/engine/ac/hotspot.h b/engines/ags/engine/ac/hotspot.h
index d1bb46f8b2..4e69030e2e 100644
--- a/engines/ags/engine/ac/hotspot.h
+++ b/engines/ags/engine/ac/hotspot.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__HOTSPOT_H
 #define __AGS_EE_AC__HOTSPOT_H
 
diff --git a/engines/ags/engine/ac/interfacebutton.cpp b/engines/ags/engine/ac/interfacebutton.cpp
index c474bb7ecb..080f85296a 100644
--- a/engines/ags/engine/ac/interfacebutton.cpp
+++ b/engines/ags/engine/ac/interfacebutton.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/interfacebutton.h"
 
@@ -18,4 +26,4 @@ void InterfaceButton::set(int xx, int yy, int picc, int overpicc, int actionn) {
     x = xx; y = yy; pic = picc; overpic = overpicc; leftclick = actionn; pushpic = 0;
     rightclick = 0; flags = IBFLG_ENABLED;
     reserved_for_future = 0;
-}
\ No newline at end of file
+}
diff --git a/engines/ags/engine/ac/interfaceelement.cpp b/engines/ags/engine/ac/interfaceelement.cpp
index 13abc93fdc..229b9e05d7 100644
--- a/engines/ags/engine/ac/interfaceelement.cpp
+++ b/engines/ags/engine/ac/interfaceelement.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 <string.h>
 #include "ac/interfaceelement.h"
diff --git a/engines/ags/engine/ac/inventoryitem.cpp b/engines/ags/engine/ac/inventoryitem.cpp
index 8f28fd6136..9eb8ff499d 100644
--- a/engines/ags/engine/ac/inventoryitem.cpp
+++ b/engines/ags/engine/ac/inventoryitem.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/inventoryitem.h"
 #include "ac/characterinfo.h"
diff --git a/engines/ags/engine/ac/inventoryitem.h b/engines/ags/engine/ac/inventoryitem.h
index 833209a659..76733125f4 100644
--- a/engines/ags/engine/ac/inventoryitem.h
+++ b/engines/ags/engine/ac/inventoryitem.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__INVENTORYITEM_H
 #define __AGS_EE_AC__INVENTORYITEM_H
 
diff --git a/engines/ags/engine/ac/invwindow.cpp b/engines/ags/engine/ac/invwindow.cpp
index faffb294e0..cb124cf406 100644
--- a/engines/ags/engine/ac/invwindow.cpp
+++ b/engines/ags/engine/ac/invwindow.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/invwindow.h"
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/invwindow.h b/engines/ags/engine/ac/invwindow.h
index 7c192b11a1..72802c2572 100644
--- a/engines/ags/engine/ac/invwindow.h
+++ b/engines/ags/engine/ac/invwindow.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__INVWINDOW_H
 #define __AGS_EE_AC__INVWINDOW_H
 
diff --git a/engines/ags/engine/ac/keycode.cpp b/engines/ags/engine/ac/keycode.cpp
index ba6b0390a3..c4442eb5a8 100644
--- a/engines/ags/engine/ac/keycode.cpp
+++ b/engines/ags/engine/ac/keycode.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 "ac/keycode.h"
 
diff --git a/engines/ags/engine/ac/keycode.h b/engines/ags/engine/ac/keycode.h
index f2df0ac3b0..6269dafca3 100644
--- a/engines/ags/engine/ac/keycode.h
+++ b/engines/ags/engine/ac/keycode.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__KEYCODE_H
 #define __AGS_EE_AC__KEYCODE_H
 
diff --git a/engines/ags/engine/ac/label.cpp b/engines/ags/engine/ac/label.cpp
index d7d61850bc..d16026956c 100644
--- a/engines/ags/engine/ac/label.cpp
+++ b/engines/ags/engine/ac/label.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 <string.h>
 #include "ac/label.h"
diff --git a/engines/ags/engine/ac/label.h b/engines/ags/engine/ac/label.h
index 684e4268cc..26464eefcf 100644
--- a/engines/ags/engine/ac/label.h
+++ b/engines/ags/engine/ac/label.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__LABEL_H
 #define __AGS_EE_AC__LABEL_H
 
diff --git a/engines/ags/engine/ac/lipsync.h b/engines/ags/engine/ac/lipsync.h
index 5272f5e11f..2301ef2d38 100644
--- a/engines/ags/engine/ac/lipsync.h
+++ b/engines/ags/engine/ac/lipsync.h
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 __AC_LIPSYNC_H
 #define __AC_LIPSYNC_H
@@ -22,4 +30,4 @@ struct SpeechLipSyncLine {
     short numPhonemes;
 };
 
-#endif // __AC_LIPSYNC_H
\ No newline at end of file
+#endif // __AC_LIPSYNC_H
diff --git a/engines/ags/engine/ac/listbox.cpp b/engines/ags/engine/ac/listbox.cpp
index c6fe065c9b..142b75e2aa 100644
--- a/engines/ags/engine/ac/listbox.cpp
+++ b/engines/ags/engine/ac/listbox.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 <set>
 #include "ac/listbox.h"
diff --git a/engines/ags/engine/ac/listbox.h b/engines/ags/engine/ac/listbox.h
index 24ba70af11..eb6c5d06ab 100644
--- a/engines/ags/engine/ac/listbox.h
+++ b/engines/ags/engine/ac/listbox.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__LISTBOX_H
 #define __AGS_EE_AC__LISTBOX_H
 
diff --git a/engines/ags/engine/ac/math.cpp b/engines/ags/engine/ac/math.cpp
index 5c81231643..48e27b7edc 100644
--- a/engines/ags/engine/ac/math.cpp
+++ b/engines/ags/engine/ac/math.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 <cmath>
 #include "ac/math.h"
diff --git a/engines/ags/engine/ac/math.h b/engines/ags/engine/ac/math.h
index 872b445c5b..ce047992de 100644
--- a/engines/ags/engine/ac/math.h
+++ b/engines/ags/engine/ac/math.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__MATH_H
 #define __AGS_EE_AC__MATH_H
 
diff --git a/engines/ags/engine/ac/mouse.cpp b/engines/ags/engine/ac/mouse.cpp
index eceb5e680c..1c6e8e1a97 100644
--- a/engines/ags/engine/ac/mouse.cpp
+++ b/engines/ags/engine/ac/mouse.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/mouse.h"
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/mouse.h b/engines/ags/engine/ac/mouse.h
index 97e7467f09..f49e2e9f79 100644
--- a/engines/ags/engine/ac/mouse.h
+++ b/engines/ags/engine/ac/mouse.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__MOUSE_H
 #define __AGS_EE_AC__MOUSE_H
 
diff --git a/engines/ags/engine/ac/movelist.cpp b/engines/ags/engine/ac/movelist.cpp
index 47b9ca2b7f..4020726e54 100644
--- a/engines/ags/engine/ac/movelist.cpp
+++ b/engines/ags/engine/ac/movelist.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/movelist.h"
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/movelist.h b/engines/ags/engine/ac/movelist.h
index 2f860dc3a8..cff9328138 100644
--- a/engines/ags/engine/ac/movelist.h
+++ b/engines/ags/engine/ac/movelist.h
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 __AC_MOVE_H
 #define __AC_MOVE_H
diff --git a/engines/ags/engine/ac/object.cpp b/engines/ags/engine/ac/object.cpp
index b33eaed3df..289d060900 100644
--- a/engines/ags/engine/ac/object.cpp
+++ b/engines/ags/engine/ac/object.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/object.h"
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/object.h b/engines/ags/engine/ac/object.h
index 0e044fab95..5679ec5d9e 100644
--- a/engines/ags/engine/ac/object.h
+++ b/engines/ags/engine/ac/object.h
@@ -1,15 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
+/* 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.
+ *
+ */
+
 //=============================================================================
 //
 //
@@ -17,6 +27,7 @@
 // world of programming 'object' is usually a base class; should not we
 // rename this to RoomObject one day?
 //=============================================================================
+
 #ifndef __AGS_EE_AC__OBJECT_H
 #define __AGS_EE_AC__OBJECT_H
 
diff --git a/engines/ags/engine/ac/objectcache.h b/engines/ags/engine/ac/objectcache.h
index 78ddcede18..cff0fcb8f6 100644
--- a/engines/ags/engine/ac/objectcache.h
+++ b/engines/ags/engine/ac/objectcache.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__OBJECTCACHE_H
 #define __AGS_EE_AC__OBJECTCACHE_H
 
diff --git a/engines/ags/engine/ac/overlay.cpp b/engines/ags/engine/ac/overlay.cpp
index 3904b795b1..f74603f0ac 100644
--- a/engines/ags/engine/ac/overlay.cpp
+++ b/engines/ags/engine/ac/overlay.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/overlay.h"
 #include "ac/common.h"
diff --git a/engines/ags/engine/ac/overlay.h b/engines/ags/engine/ac/overlay.h
index 073ae9c46d..ed315510e6 100644
--- a/engines/ags/engine/ac/overlay.h
+++ b/engines/ags/engine/ac/overlay.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__OVERLAY_H
 #define __AGS_EE_AC__OVERLAY_H
 #include <vector>
diff --git a/engines/ags/engine/ac/parser.cpp b/engines/ags/engine/ac/parser.cpp
index 6225249a33..1f62782c95 100644
--- a/engines/ags/engine/ac/parser.cpp
+++ b/engines/ags/engine/ac/parser.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 <cctype> //isalnum()
 #include <cstdio>
diff --git a/engines/ags/engine/ac/parser.h b/engines/ags/engine/ac/parser.h
index eddeaebe5c..e13edaf89a 100644
--- a/engines/ags/engine/ac/parser.h
+++ b/engines/ags/engine/ac/parser.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__PARSER_H
 #define __AGS_EE_AC__PARSER_H
 
diff --git a/engines/ags/engine/ac/path_helper.h b/engines/ags/engine/ac/path_helper.h
index 57898ac55e..9efb1190d3 100644
--- a/engines/ags/engine/ac/path_helper.h
+++ b/engines/ags/engine/ac/path_helper.h
@@ -1,20 +1,31 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
+/* 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.
+ *
+ */
+
 //=============================================================================
 //
 // Functions related to constructing game and script paths.
 //
 //=============================================================================
+
 #ifndef __AGS_EE_AC__PATHHELPER_H
 #define __AGS_EE_AC__PATHHELPER_H
 
diff --git a/engines/ags/engine/ac/properties.cpp b/engines/ags/engine/ac/properties.cpp
index d9da238488..5c773c93bc 100644
--- a/engines/ags/engine/ac/properties.cpp
+++ b/engines/ags/engine/ac/properties.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/common.h"
 #include "ac/gamesetupstruct.h"
diff --git a/engines/ags/engine/ac/properties.h b/engines/ags/engine/ac/properties.h
index f16831ead8..428265777a 100644
--- a/engines/ags/engine/ac/properties.h
+++ b/engines/ags/engine/ac/properties.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__PROPERTIES_H
 #define __AGS_EE_AC__PROPERTIES_H
 
diff --git a/engines/ags/engine/ac/region.cpp b/engines/ags/engine/ac/region.cpp
index 6210ae3878..39fd7f233a 100644
--- a/engines/ags/engine/ac/region.cpp
+++ b/engines/ags/engine/ac/region.cpp
@@ -1,16 +1,24 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
+/* 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 "ac/region.h"
 #include "ac/common_defines.h"
diff --git a/engines/ags/engine/ac/region.h b/engines/ags/engine/ac/region.h
index 66ca3b3c19..f12636f465 100644
--- a/engines/ags/engine/ac/region.h
+++ b/engines/ags/engine/ac/region.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__REGION_H
 #define __AGS_EE_AC__REGION_H
 
diff --git a/engines/ags/engine/ac/richgamemedia.cpp b/engines/ags/engine/ac/richgamemedia.cpp
index a0ed4187d0..dd8313ab1d 100644
--- a/engines/ags/engine/ac/richgamemedia.cpp
+++ b/engines/ags/engine/ac/richgamemedia.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 "ac/richgamemedia.h"
 #include "util/stream.h"
diff --git a/engines/ags/engine/ac/richgamemedia.h b/engines/ags/engine/ac/richgamemedia.h
index 0206ea841f..c0570e89f0 100644
--- a/engines/ags/engine/ac/richgamemedia.h
+++ b/engines/ags/engine/ac/richgamemedia.h
@@ -1,20 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-//
-//
-//=============================================================================
+/* 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 __AGS_EE_AC__RICHGAMEMEDIA_H
 #define __AGS_EE_AC__RICHGAMEMEDIA_H
 
diff --git a/engines/ags/engine/ac/room.cpp b/engines/ags/engine/ac/room.cpp
index 016d2cbd00..f62d72e90c 100644
--- a/engines/ags/engine/ac/room.cpp
+++ b/engines/ags/engine/ac/room.cpp
@@ -1,16 +1,24 @@


Commit: 90ec822f76956b4fe8d0a89c4e15188e3a96b014
    https://github.com/scummvm/scummvm/commit/90ec822f76956b4fe8d0a89c4e15188e3a96b014
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Cleaning up header file guard defines

Changed paths:
  A engines/ags/engine/platform/windows/debugging/namedpipesagsdebugger.cpp
  A engines/ags/engine/platform/windows/debugging/namedpipesagsdebugger.h
    engines/ags/engine/ac/asset_helper.h
    engines/ags/engine/ac/audiochannel.h
    engines/ags/engine/ac/audioclip.h
    engines/ags/engine/ac/button.h
    engines/ags/engine/ac/cdaudio.h
    engines/ags/engine/ac/character.h
    engines/ags/engine/ac/charactercache.h
    engines/ags/engine/ac/characterextras.h
    engines/ags/engine/ac/datetime.h
    engines/ags/engine/ac/dialog.h
    engines/ags/engine/ac/dialogoptionsrendering.h
    engines/ags/engine/ac/display.h
    engines/ags/engine/ac/draw.h
    engines/ags/engine/ac/draw_software.h
    engines/ags/engine/ac/drawingsurface.h
    engines/ags/engine/ac/dynamicsprite.h
    engines/ags/engine/ac/dynobj/all_dynamicclasses.h
    engines/ags/engine/ac/dynobj/all_scriptclasses.h
    engines/ags/engine/ac/dynobj/cc_agsdynamicobject.h
    engines/ags/engine/ac/dynobj/cc_audiochannel.h
    engines/ags/engine/ac/dynobj/cc_audioclip.h
    engines/ags/engine/ac/dynobj/cc_character.h
    engines/ags/engine/ac/dynobj/cc_dialog.h
    engines/ags/engine/ac/dynobj/cc_dynamicarray.h
    engines/ags/engine/ac/dynobj/cc_dynamicobject.h
    engines/ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h
    engines/ags/engine/ac/dynobj/cc_gui.h
    engines/ags/engine/ac/dynobj/cc_guiobject.h
    engines/ags/engine/ac/dynobj/cc_hotspot.h
    engines/ags/engine/ac/dynobj/cc_inventory.h
    engines/ags/engine/ac/dynobj/cc_object.h
    engines/ags/engine/ac/dynobj/cc_region.h
    engines/ags/engine/ac/dynobj/cc_serializer.h
    engines/ags/engine/ac/dynobj/managedobjectpool.h
    engines/ags/engine/ac/dynobj/scriptaudiochannel.h
    engines/ags/engine/ac/dynobj/scriptcamera.h
    engines/ags/engine/ac/dynobj/scriptcontainers.h
    engines/ags/engine/ac/dynobj/scriptdatetime.h
    engines/ags/engine/ac/dynobj/scriptdialog.h
    engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.h
    engines/ags/engine/ac/dynobj/scriptdict.h
    engines/ags/engine/ac/dynobj/scriptdrawingsurface.h
    engines/ags/engine/ac/dynobj/scriptdynamicsprite.h
    engines/ags/engine/ac/dynobj/scriptfile.h
    engines/ags/engine/ac/dynobj/scriptgui.h
    engines/ags/engine/ac/dynobj/scripthotspot.h
    engines/ags/engine/ac/dynobj/scriptinvitem.h
    engines/ags/engine/ac/dynobj/scriptmouse.h
    engines/ags/engine/ac/dynobj/scriptobject.h
    engines/ags/engine/ac/dynobj/scriptoverlay.h
    engines/ags/engine/ac/dynobj/scriptregion.h
    engines/ags/engine/ac/dynobj/scriptset.h
    engines/ags/engine/ac/dynobj/scriptstring.h
    engines/ags/engine/ac/dynobj/scriptsystem.h
    engines/ags/engine/ac/dynobj/scriptuserobject.h
    engines/ags/engine/ac/dynobj/scriptviewframe.h
    engines/ags/engine/ac/dynobj/scriptviewport.h
    engines/ags/engine/ac/event.h
    engines/ags/engine/ac/file.h
    engines/ags/engine/ac/game.h
    engines/ags/engine/ac/gamesetup.h
    engines/ags/engine/ac/gamestate.h
    engines/ags/engine/ac/global_audio.h
    engines/ags/engine/ac/global_button.h
    engines/ags/engine/ac/global_character.h
    engines/ags/engine/ac/global_datetime.h
    engines/ags/engine/ac/global_debug.h
    engines/ags/engine/ac/global_dialog.h
    engines/ags/engine/ac/global_display.h
    engines/ags/engine/ac/global_drawingsurface.h
    engines/ags/engine/ac/global_dynamicsprite.h
    engines/ags/engine/ac/global_file.h
    engines/ags/engine/ac/global_game.h
    engines/ags/engine/ac/global_gui.h
    engines/ags/engine/ac/global_hotspot.h
    engines/ags/engine/ac/global_inventoryitem.h
    engines/ags/engine/ac/global_invwindow.h
    engines/ags/engine/ac/global_label.h
    engines/ags/engine/ac/global_listbox.h
    engines/ags/engine/ac/global_mouse.h
    engines/ags/engine/ac/global_object.h
    engines/ags/engine/ac/global_overlay.h
    engines/ags/engine/ac/global_palette.h
    engines/ags/engine/ac/global_parser.h
    engines/ags/engine/ac/global_plugin.h
    engines/ags/engine/ac/global_record.h
    engines/ags/engine/ac/global_region.h
    engines/ags/engine/ac/global_room.h
    engines/ags/engine/ac/global_screen.h
    engines/ags/engine/ac/global_slider.h
    engines/ags/engine/ac/global_string.h
    engines/ags/engine/ac/global_textbox.h
    engines/ags/engine/ac/global_timer.h
    engines/ags/engine/ac/global_translation.h
    engines/ags/engine/ac/global_video.h
    engines/ags/engine/ac/global_viewframe.h
    engines/ags/engine/ac/global_viewport.h
    engines/ags/engine/ac/global_walkablearea.h
    engines/ags/engine/ac/global_walkbehind.h
    engines/ags/engine/ac/gui.h
    engines/ags/engine/ac/guicontrol.h
    engines/ags/engine/ac/hotspot.h
    engines/ags/engine/ac/inventoryitem.h
    engines/ags/engine/ac/invwindow.h
    engines/ags/engine/ac/keycode.h
    engines/ags/engine/ac/label.h
    engines/ags/engine/ac/lipsync.h
    engines/ags/engine/ac/listbox.h
    engines/ags/engine/ac/math.h
    engines/ags/engine/ac/mouse.h
    engines/ags/engine/ac/movelist.h
    engines/ags/engine/ac/object.h
    engines/ags/engine/ac/objectcache.h
    engines/ags/engine/ac/overlay.h
    engines/ags/engine/ac/parser.h
    engines/ags/engine/ac/path_helper.h
    engines/ags/engine/ac/properties.h
    engines/ags/engine/ac/region.h
    engines/ags/engine/ac/richgamemedia.h
    engines/ags/engine/ac/room.h
    engines/ags/engine/ac/roomobject.h
    engines/ags/engine/ac/roomstatus.h
    engines/ags/engine/ac/route_finder.h
    engines/ags/engine/ac/route_finder_impl.h
    engines/ags/engine/ac/route_finder_impl_legacy.h
    engines/ags/engine/ac/runtime_defines.h
    engines/ags/engine/ac/screen.h
    engines/ags/engine/ac/screenoverlay.h
    engines/ags/engine/ac/slider.h
    engines/ags/engine/ac/speech.h
    engines/ags/engine/ac/sprite.h
    engines/ags/engine/ac/spritelistentry.h
    engines/ags/engine/ac/statobj/agsstaticobject.h
    engines/ags/engine/ac/statobj/staticarray.h
    engines/ags/engine/ac/statobj/staticobject.h
    engines/ags/engine/ac/string.h
    engines/ags/engine/ac/sys_events.h
    engines/ags/engine/ac/system.h
    engines/ags/engine/ac/textbox.h
    engines/ags/engine/ac/timer.h
    engines/ags/engine/ac/topbarsettings.h
    engines/ags/engine/ac/translation.h
    engines/ags/engine/ac/tree_map.h
    engines/ags/engine/ac/viewframe.h
    engines/ags/engine/ac/walkablearea.h
    engines/ags/engine/ac/walkbehind.h
    engines/ags/engine/debugging/agseditordebugger.h
    engines/ags/engine/debugging/consoleoutputtarget.h
    engines/ags/engine/debugging/debug_log.h
    engines/ags/engine/debugging/debugger.h
    engines/ags/engine/debugging/dummyagsdebugger.h
    engines/ags/engine/debugging/filebasedagsdebugger.h
    engines/ags/engine/debugging/logfile.h
    engines/ags/engine/debugging/messagebuffer.h
    engines/ags/engine/game/game_init.h
    engines/ags/engine/game/savegame.h
    engines/ags/engine/game/savegame_components.h
    engines/ags/engine/game/savegame_internal.h
    engines/ags/engine/game/viewport.h
    engines/ags/engine/gfx/ali3dexception.h
    engines/ags/engine/gfx/ali3dogl.h
    engines/ags/engine/gfx/ali3dsw.h
    engines/ags/engine/gfx/blender.h
    engines/ags/engine/gfx/ddb.h
    engines/ags/engine/gfx/gfx_util.h
    engines/ags/engine/gfx/gfxdefines.h
    engines/ags/engine/gfx/gfxdriverbase.h
    engines/ags/engine/gfx/gfxdriverfactory.h
    engines/ags/engine/gfx/gfxdriverfactorybase.h
    engines/ags/engine/gfx/gfxfilter.h
    engines/ags/engine/gfx/gfxfilter_aad3d.h
    engines/ags/engine/gfx/gfxfilter_aaogl.h
    engines/ags/engine/gfx/gfxfilter_allegro.h
    engines/ags/engine/gfx/gfxfilter_d3d.h
    engines/ags/engine/gfx/gfxfilter_hqx.h
    engines/ags/engine/gfx/gfxfilter_ogl.h
    engines/ags/engine/gfx/gfxfilter_scaling.h
    engines/ags/engine/gfx/gfxmodelist.h
    engines/ags/engine/gfx/graphicsdriver.h
    engines/ags/engine/gfx/hq2x3x.h
    engines/ags/engine/gui/animatingguibutton.h
    engines/ags/engine/gui/cscidialog.h
    engines/ags/engine/gui/guidialog.h
    engines/ags/engine/gui/guidialogdefines.h
    engines/ags/engine/gui/guidialoginternaldefs.h
    engines/ags/engine/gui/mycontrols.h
    engines/ags/engine/gui/mylabel.h
    engines/ags/engine/gui/mylistbox.h
    engines/ags/engine/gui/mypushbutton.h
    engines/ags/engine/gui/mytextbox.h
    engines/ags/engine/gui/newcontrol.h
    engines/ags/engine/main/config.h
    engines/ags/engine/main/engine.h
    engines/ags/engine/main/engine_setup.h
    engines/ags/engine/main/game_file.h
    engines/ags/engine/main/game_run.h
    engines/ags/engine/main/game_start.h
    engines/ags/engine/main/graphics_mode.h
    engines/ags/engine/main/main.h
    engines/ags/engine/main/main_allegro.h
    engines/ags/engine/main/maindefines_ex.h
    engines/ags/engine/main/mainheader.h
    engines/ags/engine/main/quit.h
    engines/ags/engine/main/update.h
    engines/ags/engine/media/audio/ambientsound.h
    engines/ags/engine/media/audio/audio.h
    engines/ags/engine/media/audio/audio_system.h
    engines/ags/engine/media/audio/audiodefines.h
    engines/ags/engine/media/audio/audiointernaldefs.h
    engines/ags/engine/media/audio/clip_mydumbmod.h
    engines/ags/engine/media/audio/clip_myjgmod.h
    engines/ags/engine/media/audio/clip_mymidi.h
    engines/ags/engine/media/audio/clip_mymp3.h
    engines/ags/engine/media/audio/clip_myogg.h
    engines/ags/engine/media/audio/clip_mystaticmp3.h
    engines/ags/engine/media/audio/clip_mystaticogg.h
    engines/ags/engine/media/audio/clip_mywave.h
    engines/ags/engine/media/audio/queuedaudioitem.h
    engines/ags/engine/media/audio/sound.h
    engines/ags/engine/media/audio/soundcache.h
    engines/ags/engine/media/audio/soundclip.h
    engines/ags/engine/media/video/VMR9Graph.h
    engines/ags/engine/media/video/video.h
    engines/ags/engine/platform/base/agsplatformdriver.h
    engines/ags/engine/platform/util/pe.h
    engines/ags/engine/platform/windows/gfx/ali3dd3d.h
    engines/ags/engine/platform/windows/setup/winsetup.h
    engines/ags/engine/platform/windows/win_ex_handling.h
    engines/ags/engine/platform/windows/winapi_exclusive.h
    engines/ags/engine/plugin/agsplugin.h
    engines/ags/engine/plugin/plugin_builtin.h
    engines/ags/engine/plugin/plugin_engine.h
    engines/ags/engine/plugin/pluginobjectreader.h
    engines/ags/engine/script/cc_instance.h
    engines/ags/engine/script/executingscript.h
    engines/ags/engine/script/exports.h
    engines/ags/engine/script/nonblockingscriptfunction.h
    engines/ags/engine/script/runtimescriptvalue.h
    engines/ags/engine/script/script.h
    engines/ags/engine/script/script_api.h
    engines/ags/engine/script/script_runtime.h
    engines/ags/engine/script/systemimports.h
    engines/ags/engine/util/library.h
    engines/ags/engine/util/library_dummy.h
    engines/ags/engine/util/library_posix.h
    engines/ags/engine/util/library_psp.h
    engines/ags/engine/util/library_windows.h
    engines/ags/engine/util/mutex.h
    engines/ags/engine/util/mutex_base.h
    engines/ags/engine/util/mutex_lock.h
    engines/ags/engine/util/mutex_psp.h
    engines/ags/engine/util/mutex_pthread.h
    engines/ags/engine/util/mutex_std.h
    engines/ags/engine/util/mutex_wii.h
    engines/ags/engine/util/mutex_windows.h
    engines/ags/engine/util/scaling.h
    engines/ags/engine/util/thread.h
    engines/ags/engine/util/thread_psp.h
    engines/ags/engine/util/thread_pthread.h
    engines/ags/engine/util/thread_std.h
    engines/ags/engine/util/thread_wii.h
    engines/ags/engine/util/thread_windows.h
    engines/ags/shared/ac/audiocliptype.h
    engines/ags/shared/ac/characterinfo.h
    engines/ags/shared/ac/common.h
    engines/ags/shared/ac/common_defines.h
    engines/ags/shared/ac/dialogtopic.h
    engines/ags/shared/ac/dynobj/scriptaudioclip.h
    engines/ags/shared/ac/game_version.h
    engines/ags/shared/ac/gamesetupstruct.h
    engines/ags/shared/ac/gamesetupstructbase.h
    engines/ags/shared/ac/gamestructdefines.h
    engines/ags/shared/ac/interfacebutton.h
    engines/ags/shared/ac/interfaceelement.h
    engines/ags/shared/ac/inventoryiteminfo.h
    engines/ags/shared/ac/mousecursor.h
    engines/ags/shared/ac/oldgamesetupstruct.h
    engines/ags/shared/ac/spritecache.h
    engines/ags/shared/ac/view.h
    engines/ags/shared/ac/wordsdictionary.h
    engines/ags/shared/api/stream_api.h
    engines/ags/shared/core/asset.h
    engines/ags/shared/core/assetmanager.h
    engines/ags/shared/core/def_version.h
    engines/ags/shared/core/platform.h
    engines/ags/shared/core/types.h
    engines/ags/shared/debugging/assert.h
    engines/ags/shared/debugging/debugmanager.h
    engines/ags/shared/debugging/out.h
    engines/ags/shared/debugging/outputhandler.h
    engines/ags/shared/font/agsfontrenderer.h
    engines/ags/shared/font/fonts.h
    engines/ags/shared/font/ttffontrenderer.h
    engines/ags/shared/font/wfnfont.h
    engines/ags/shared/font/wfnfontrenderer.h
    engines/ags/shared/game/customproperties.h
    engines/ags/shared/game/interactions.h
    engines/ags/shared/game/main_game_file.h
    engines/ags/shared/game/plugininfo.h
    engines/ags/shared/game/room_file.h
    engines/ags/shared/game/room_version.h
    engines/ags/shared/game/roomstruct.h
    engines/ags/shared/gfx/allegrobitmap.h
    engines/ags/shared/gfx/bitmap.h
    engines/ags/shared/gfx/gfx_def.h
    engines/ags/shared/gui/guibutton.h
    engines/ags/shared/gui/guidefines.h
    engines/ags/shared/gui/guiinv.h
    engines/ags/shared/gui/guilabel.h
    engines/ags/shared/gui/guilistbox.h
    engines/ags/shared/gui/guimain.h
    engines/ags/shared/gui/guiobject.h
    engines/ags/shared/gui/guislider.h
    engines/ags/shared/gui/guitextbox.h
    engines/ags/shared/script/cc_error.h
    engines/ags/shared/script/cc_options.h
    engines/ags/shared/script/cc_script.h
    engines/ags/shared/script/script_common.h
    engines/ags/shared/util/alignedstream.h
    engines/ags/shared/util/bbop.h
    engines/ags/shared/util/bufferedstream.h
    engines/ags/shared/util/compress.h
    engines/ags/shared/util/datastream.h
    engines/ags/shared/util/directory.h
    engines/ags/shared/util/error.h
    engines/ags/shared/util/file.h
    engines/ags/shared/util/filestream.h
    engines/ags/shared/util/geometry.h
    engines/ags/shared/util/ini_util.h
    engines/ags/shared/util/inifile.h
    engines/ags/shared/util/lzw.h
    engines/ags/shared/util/math.h
    engines/ags/shared/util/memory.h
    engines/ags/shared/util/misc.h
    engines/ags/shared/util/multifilelib.h
    engines/ags/shared/util/path.h
    engines/ags/shared/util/proxystream.h
    engines/ags/shared/util/stdio_compat.h
    engines/ags/shared/util/stream.h
    engines/ags/shared/util/string.h
    engines/ags/shared/util/string_compat.h
    engines/ags/shared/util/string_types.h
    engines/ags/shared/util/string_utils.h
    engines/ags/shared/util/textreader.h
    engines/ags/shared/util/textstreamreader.h
    engines/ags/shared/util/textstreamwriter.h
    engines/ags/shared/util/textwriter.h
    engines/ags/shared/util/version.h
    engines/ags/shared/util/wgt2allg.h


diff --git a/engines/ags/engine/ac/asset_helper.h b/engines/ags/engine/ac/asset_helper.h
index fa62fecc2b..bfe4130c31 100644
--- a/engines/ags/engine/ac/asset_helper.h
+++ b/engines/ags/engine/ac/asset_helper.h
@@ -26,8 +26,9 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_AC__ASSETHELPER_H
-#define __AGS_EE_AC__ASSETHELPER_H
+#ifndef AGS_ENGINE_AC_ASSETHELPER_H
+#define AGS_ENGINE_AC_ASSETHELPER_H
+
 #include <memory>
 #include <utility>
 #include "util/string.h"
@@ -75,4 +76,4 @@ PACKFILE *PackfileFromAsset(const AssetPath &path, size_t &asset_size);
 DUMBFILE *DUMBfileFromAsset(const AssetPath &path, size_t &asset_size);
 bool DoesAssetExistInLib(const AssetPath &assetname);
 
-#endif // __AGS_EE_AC__ASSETHELPER_H
+#endif
diff --git a/engines/ags/engine/ac/audiochannel.h b/engines/ags/engine/ac/audiochannel.h
index 1955cc146c..e3f4a82853 100644
--- a/engines/ags/engine/ac/audiochannel.h
+++ b/engines/ags/engine/ac/audiochannel.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__AUDIOCHANNEL_H
-#define __AGS_EE_AC__AUDIOCHANNEL_H
+#ifndef AGS_ENGINE_AC_AUDIOCHANNEL_H
+#define AGS_ENGINE_AC_AUDIOCHANNEL_H
 
 #include "ac/dynobj/scriptaudioclip.h"
 #include "ac/dynobj/scriptaudiochannel.h"
@@ -40,4 +40,4 @@ void    AudioChannel_Stop(ScriptAudioChannel *channel);
 void    AudioChannel_Seek(ScriptAudioChannel *channel, int newPosition);
 void    AudioChannel_SetRoomLocation(ScriptAudioChannel *channel, int xPos, int yPos);
 
-#endif // __AGS_EE_AC__AUDIOCHANNEL_H
+#endif
diff --git a/engines/ags/engine/ac/audioclip.h b/engines/ags/engine/ac/audioclip.h
index 113ed78423..7c66b2e057 100644
--- a/engines/ags/engine/ac/audioclip.h
+++ b/engines/ags/engine/ac/audioclip.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__AUDIOCLIP_H
-#define __AGS_EE_AC__AUDIOCLIP_H
+#ifndef AGS_ENGINE_AC_AUDIOCLIP_H
+#define AGS_ENGINE_AC_AUDIOCLIP_H
 
 #include "ac/dynobj/scriptaudioclip.h"
 #include "ac/dynobj/scriptaudiochannel.h"
@@ -34,4 +34,4 @@ ScriptAudioChannel* AudioClip_Play(ScriptAudioClip *clip, int priority, int repe
 ScriptAudioChannel* AudioClip_PlayFrom(ScriptAudioClip *clip, int position, int priority, int repeat);
 ScriptAudioChannel* AudioClip_PlayQueued(ScriptAudioClip *clip, int priority, int repeat);
 
-#endif // __AGS_EE_AC__AUDIOCLIP_H
+#endif
diff --git a/engines/ags/engine/ac/button.h b/engines/ags/engine/ac/button.h
index 7a36b24552..47022d8ce1 100644
--- a/engines/ags/engine/ac/button.h
+++ b/engines/ags/engine/ac/button.h
@@ -20,13 +20,8 @@
  *
  */
 
-//=============================================================================
-//
-//
-//
-//=============================================================================
-#ifndef __AGS_EE_AC__BUTTON_H
-#define __AGS_EE_AC__BUTTON_H
+#ifndef AGS_ENGINE_AC_BUTTON_H
+#define AGS_ENGINE_AC_BUTTON_H
 
 #include "gui/guibutton.h"
 
@@ -54,4 +49,4 @@ int			UpdateAnimatingButton(int bu);
 void		StopButtonAnimation(int idxn);
 void		FindAndRemoveButtonAnimation(int guin, int objn);
 
-#endif // __AGS_EE_AC__BUTTON_H
+#endif
diff --git a/engines/ags/engine/ac/cdaudio.h b/engines/ags/engine/ac/cdaudio.h
index feda127c91..62852277ee 100644
--- a/engines/ags/engine/ac/cdaudio.h
+++ b/engines/ags/engine/ac/cdaudio.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__CDAUDIO_H
-#define __AGS_EE_AC__CDAUDIO_H
+#ifndef AGS_ENGINE_AC_CDAUDIO_H
+#define AGS_ENGINE_AC_CDAUDIO_H
 
 // CD Player functions
 // flags returned with cd_getstatus
@@ -33,4 +33,4 @@
 int     init_cd_player() ;
 int     cd_manager(int cmdd,int datt) ;
 
-#endif // __AGS_EE_AC__CDAUDIO_H
+#endif
diff --git a/engines/ags/engine/ac/character.h b/engines/ags/engine/ac/character.h
index 32016da906..948465e554 100644
--- a/engines/ags/engine/ac/character.h
+++ b/engines/ags/engine/ac/character.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__CHARACTER_H
-#define __AGS_EE_AC__CHARACTER_H
+#ifndef AGS_ENGINE_AC_CHARACTER_H
+#define AGS_ENGINE_AC_CHARACTER_H
 
 #include "ac/characterinfo.h"
 #include "ac/characterextras.h"
@@ -221,4 +221,4 @@ extern int32_t _sc_PlayerCharPtr;
 // order of loops to turn character in circle from down to down
 extern int turnlooporder[8];
 
-#endif // __AGS_EE_AC__CHARACTER_H
+#endif
diff --git a/engines/ags/engine/ac/charactercache.h b/engines/ags/engine/ac/charactercache.h
index ca914d3f47..2ba84e66ed 100644
--- a/engines/ags/engine/ac/charactercache.h
+++ b/engines/ags/engine/ac/charactercache.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__CHARACTERCACHE_H
-#define __AGS_EE_AC__CHARACTERCACHE_H
+#ifndef AGS_ENGINE_AC_CHARACTERCACHE_H
+#define AGS_ENGINE_AC_CHARACTERCACHE_H
 
 namespace AGS { namespace Common { class Bitmap; } }
 using namespace AGS; // FIXME later
@@ -37,4 +37,4 @@ struct CharacterCache {
     // no mirroredWas is required, since the code inverts the sprite number
 };
 
-#endif // __AGS_EE_AC__CHARACTERCACHE_H
+#endif
diff --git a/engines/ags/engine/ac/characterextras.h b/engines/ags/engine/ac/characterextras.h
index c694b2c964..d5d86dcfe4 100644
--- a/engines/ags/engine/ac/characterextras.h
+++ b/engines/ags/engine/ac/characterextras.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__CHARACTEREXTRAS_H
-#define __AGS_EE_AC__CHARACTEREXTRAS_H
+#ifndef AGS_ENGINE_AC_CHARACTEREXTRAS_H
+#define AGS_ENGINE_AC_CHARACTEREXTRAS_H
 
 #include "ac/runtime_defines.h"
 
@@ -54,4 +54,4 @@ struct CharacterExtras {
     void WriteToFile(Common::Stream *out);
 };
 
-#endif // __AGS_EE_AC__CHARACTEREXTRAS_H
+#endif
diff --git a/engines/ags/engine/ac/datetime.h b/engines/ags/engine/ac/datetime.h
index 34be0b0e68..612870825f 100644
--- a/engines/ags/engine/ac/datetime.h
+++ b/engines/ags/engine/ac/datetime.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__DATETIME_H
-#define __AGS_EE_AC__DATETIME_H
+#ifndef AGS_ENGINE_AC_DATETIME_H
+#define AGS_ENGINE_AC_DATETIME_H
 
 #include "ac/dynobj/scriptdatetime.h"
 
@@ -35,4 +35,4 @@ int             DateTime_GetMinute(ScriptDateTime *sdt);
 int             DateTime_GetSecond(ScriptDateTime *sdt);
 int             DateTime_GetRawTime(ScriptDateTime *sdt);
 
-#endif // __AGS_EE_AC__DATETIME_H
+#endif
diff --git a/engines/ags/engine/ac/dialog.h b/engines/ags/engine/ac/dialog.h
index 817c3ac1cc..076c8d05c1 100644
--- a/engines/ags/engine/ac/dialog.h
+++ b/engines/ags/engine/ac/dialog.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__DIALOG_H
-#define __AGS_EE_AC__DIALOG_H
+#ifndef AGS_ENGINE_AC_DIALOG_H
+#define AGS_ENGINE_AC_DIALOG_H
 
 #include <vector>
 #include "ac/dynobj/scriptdialog.h"
@@ -41,4 +41,4 @@ int  show_dialog_options(int dlgnum, int sayChosenOption, bool runGameLoopsInBac
 
 extern ScriptDialog *scrDialog;
 
-#endif // __AGS_EE_AC__DIALOG_H
+#endif
diff --git a/engines/ags/engine/ac/dialogoptionsrendering.h b/engines/ags/engine/ac/dialogoptionsrendering.h
index 7917ae15b0..a4d0aab4b2 100644
--- a/engines/ags/engine/ac/dialogoptionsrendering.h
+++ b/engines/ags/engine/ac/dialogoptionsrendering.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__DIALOGOPTIONSRENDERING_H
-#define __AGS_EE_AC__DIALOGOPTIONSRENDERING_H
+#ifndef AGS_ENGINE_AC_DIALOGOPTIONSRENDERING_H
+#define AGS_ENGINE_AC_DIALOGOPTIONSRENDERING_H
 
 #include "ac/dynobj/scriptdialog.h"
 #include "ac/dynobj/scriptdialogoptionsrendering.h"
@@ -47,4 +47,4 @@ ScriptDrawingSurface* DialogOptionsRendering_GetSurface(ScriptDialogOptionsRende
 int  DialogOptionsRendering_GetActiveOptionID(ScriptDialogOptionsRendering *dlgOptRender);
 void DialogOptionsRendering_SetActiveOptionID(ScriptDialogOptionsRendering *dlgOptRender, int activeOptionID);
 
-#endif // __AGS_EE_AC__DIALOGOPTIONSRENDERING_H
+#endif
diff --git a/engines/ags/engine/ac/display.h b/engines/ags/engine/ac/display.h
index 69e980ecc7..72bd83c571 100644
--- a/engines/ags/engine/ac/display.h
+++ b/engines/ags/engine/ac/display.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__DISPLAY_H
-#define __AGS_EE_AC__DISPLAY_H
+#ifndef AGS_ENGINE_AC_DISPLAY_H
+#define AGS_ENGINE_AC_DISPLAY_H
 
 #include "gui/guimain.h"
 
@@ -82,4 +82,4 @@ int get_textwindow_padding(int ifnum);
 // The efficient length of the last source text prepared for display
 extern int source_text_length;
 
-#endif // __AGS_EE_AC__DISPLAY_H
+#endif
diff --git a/engines/ags/engine/ac/draw.h b/engines/ags/engine/ac/draw.h
index 19e2274319..63bcb7432a 100644
--- a/engines/ags/engine/ac/draw.h
+++ b/engines/ags/engine/ac/draw.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__DRAW_H
-#define __AGS_EE_AC__DRAW_H
+#ifndef AGS_ENGINE_AC_DRAW_H
+#define AGS_ENGINE_AC_DRAW_H
 
 #include <memory>
 #include "core/types.h"
@@ -177,4 +177,4 @@ Common::PBitmap PrepareSpriteForUse(Common::PBitmap bitmap, bool has_alpha);
 // of the requested width and height and game's native color depth.
 Common::Bitmap *CopyScreenIntoBitmap(int width, int height, bool at_native_res = false);
 
-#endif // __AGS_EE_AC__DRAW_H
+#endif
diff --git a/engines/ags/engine/ac/draw_software.h b/engines/ags/engine/ac/draw_software.h
index e0e59339eb..b27a8c3412 100644
--- a/engines/ags/engine/ac/draw_software.h
+++ b/engines/ags/engine/ac/draw_software.h
@@ -27,8 +27,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_AC__DRAWSOFTWARE_H
-#define __AGS_EE_AC__DRAWSOFTWARE_H
+#ifndef AGS_ENGINE_AC_DRAWSOFTWARE_H
+#define AGS_ENGINE_AC_DRAWSOFTWARE_H
 
 #include "gfx/bitmap.h"
 #include "gfx/ddb.h"
@@ -54,4 +54,4 @@ void update_black_invreg_and_reset(AGS::Common::Bitmap *ds);
 // no_transform flag tells the system that the regions should be plain copied to the ds.
 void update_room_invreg_and_reset(int view_index, AGS::Common::Bitmap *ds, AGS::Common::Bitmap *src, bool no_transform);
 
-#endif // __AGS_EE_AC__DRAWSOFTWARE_H
+#endif
diff --git a/engines/ags/engine/ac/drawingsurface.h b/engines/ags/engine/ac/drawingsurface.h
index 511cf1b441..20737be5a4 100644
--- a/engines/ags/engine/ac/drawingsurface.h
+++ b/engines/ags/engine/ac/drawingsurface.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__DRAWINGSURFACE_H
-#define __AGS_EE_AC__DRAWINGSURFACE_H
+#ifndef AGS_ENGINE_AC_DRAWINGSURFACE_H
+#define AGS_ENGINE_AC_DRAWINGSURFACE_H
 
 #include "ac/dynobj/scriptdrawingsurface.h"
 
@@ -47,4 +47,4 @@ void	DrawingSurface_DrawLine(ScriptDrawingSurface *sds, int fromx, int fromy, in
 void	DrawingSurface_DrawPixel(ScriptDrawingSurface *sds, int x, int y);
 int		DrawingSurface_GetPixel(ScriptDrawingSurface *sds, int x, int y);
 
-#endif // __AGS_EE_AC__DRAWINGSURFACE_H
+#endif
diff --git a/engines/ags/engine/ac/dynamicsprite.h b/engines/ags/engine/ac/dynamicsprite.h
index 0f644f4aed..f6d7674780 100644
--- a/engines/ags/engine/ac/dynamicsprite.h
+++ b/engines/ags/engine/ac/dynamicsprite.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__DYNAMICSPRITE_H
-#define __AGS_EE_AC__DYNAMICSPRITE_H
+#ifndef AGS_ENGINE_AC_DYNAMICSPRITE_H
+#define AGS_ENGINE_AC_DYNAMICSPRITE_H
 
 #include "ac/dynobj/scriptdynamicsprite.h"
 #include "ac/dynobj/scriptdrawingsurface.h"
@@ -53,4 +53,4 @@ ScriptDynamicSprite* DynamicSprite_CreateFromBackground(int frame, int x1, int y
 void	add_dynamic_sprite(int gotSlot, Common::Bitmap *redin, bool hasAlpha = false);
 void	free_dynamic_sprite (int gotSlot);
 
-#endif // __AGS_EE_AC__DYNAMICSPRITE_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/all_dynamicclasses.h b/engines/ags/engine/ac/dynobj/all_dynamicclasses.h
index d4687da0a9..e9d32a1557 100644
--- a/engines/ags/engine/ac/dynobj/all_dynamicclasses.h
+++ b/engines/ags/engine/ac/dynobj/all_dynamicclasses.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_DYNOBJ__ALLDYNAMICCLASSES_H
-#define __AGS_EE_DYNOBJ__ALLDYNAMICCLASSES_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_ALLDYNAMICCLASSES_H
+#define AGS_ENGINE_AC_DYNOBJ_ALLDYNAMICCLASSES_H
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 #include "ac/dynobj/cc_audiochannel.h"
@@ -37,4 +37,4 @@
 
 #include "ac/dynobj/cc_serializer.h"
 
-#endif // __AGS_EE_DYNOBJ__ALLDYNAMICCLASSES_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/all_scriptclasses.h b/engines/ags/engine/ac/dynobj/all_scriptclasses.h
index 6a703be07e..7c9776d2cb 100644
--- a/engines/ags/engine/ac/dynobj/all_scriptclasses.h
+++ b/engines/ags/engine/ac/dynobj/all_scriptclasses.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_DYNOBJ__ALLSCRIPTCLASSES_H
-#define __AGS_EE_DYNOBJ__ALLSCRIPTCLASSES_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_ALLSCRIPTCLASSES_H
+#define AGS_ENGINE_AC_DYNOBJ_ALLSCRIPTCLASSES_H
 
 #include "ac/dynobj/scriptdatetime.h"
 #include "ac/dynobj/scriptdialog.h"
@@ -39,4 +39,4 @@
 #include "ac/dynobj/scriptsystem.h"
 #include "ac/dynobj/scriptviewframe.h"
 
-#endif // __AGS_EE_DYNOBJ__ALLSCRIPTOBJECTS_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.h b/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.h
index c0a0eab4dc..30f83e8a5a 100644
--- a/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.h
+++ b/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_CCDYNAMICOBJECT_H
-#define __AC_CCDYNAMICOBJECT_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_CC_AGSDYNAMICOBJECT_H
+#define AGS_ENGINE_AC_DYNOBJ_CC_AGSDYNAMICOBJECT_H
 
 #include "ac/dynobj/cc_dynamicobject.h"
 
@@ -65,4 +65,4 @@ protected:
 
 };
 
-#endif // __AC_CCDYNAMICOBJECT_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/cc_audiochannel.h b/engines/ags/engine/ac/dynobj/cc_audiochannel.h
index b7c0eb0ef3..8f5b2a05d8 100644
--- a/engines/ags/engine/ac/dynobj/cc_audiochannel.h
+++ b/engines/ags/engine/ac/dynobj/cc_audiochannel.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_DYNOBJ__CCAUDIOCHANNEL_H
-#define __AGS_EE_DYNOBJ__CCAUDIOCHANNEL_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_CC_AUDIOCHANNEL_H
+#define AGS_ENGINE_AC_DYNOBJ_CC_AUDIOCHANNEL_H
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
@@ -31,4 +31,4 @@ struct CCAudioChannel final : AGSCCDynamicObject {
     void Unserialize(int index, const char *serializedData, int dataSize) override;
 };
 
-#endif // __AGS_EE_DYNOBJ__CCAUDIOCHANNEL_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/cc_audioclip.h b/engines/ags/engine/ac/dynobj/cc_audioclip.h
index 6439ec35db..5d715bbe9b 100644
--- a/engines/ags/engine/ac/dynobj/cc_audioclip.h
+++ b/engines/ags/engine/ac/dynobj/cc_audioclip.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_DYNOBJ__CCAUDIOCLIP_H
-#define __AGS_EE_DYNOBJ__CCAUDIOCLIP_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_CCAUDIOCLIP_H
+#define AGS_ENGINE_AC_DYNOBJ_CCAUDIOCLIP_H
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
@@ -31,4 +31,4 @@ struct CCAudioClip final : AGSCCDynamicObject {
     void Unserialize(int index, const char *serializedData, int dataSize) override;
 };
 
-#endif // __AGS_EE_DYNOBJ__CCAUDIOCLIP_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/cc_character.h b/engines/ags/engine/ac/dynobj/cc_character.h
index 06ff2e28d4..e9d461e416 100644
--- a/engines/ags/engine/ac/dynobj/cc_character.h
+++ b/engines/ags/engine/ac/dynobj/cc_character.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_CCCHARACTER_H
-#define __AC_CCCHARACTER_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_CCCHARACTER_H
+#define AGS_ENGINE_AC_DYNOBJ_CCCHARACTER_H
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
@@ -39,4 +39,4 @@ struct CCCharacter final : AGSCCDynamicObject {
     void WriteInt16(const char *address, intptr_t offset, int16_t val) override;
 };
 
-#endif // __AC_CCCHARACTER_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/cc_dialog.h b/engines/ags/engine/ac/dynobj/cc_dialog.h
index 0e7a701789..6146522622 100644
--- a/engines/ags/engine/ac/dynobj/cc_dialog.h
+++ b/engines/ags/engine/ac/dynobj/cc_dialog.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_CCDIALOG_H
-#define __AC_CCDIALOG_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_CCDIALOG_H
+#define AGS_ENGINE_AC_DYNOBJ_CCDIALOG_H
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
@@ -38,4 +38,4 @@ struct CCDialog final : AGSCCDynamicObject {
 
 };
 
-#endif // __AC_CCDIALOG_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicarray.h b/engines/ags/engine/ac/dynobj/cc_dynamicarray.h
index ed29167244..8ee984eb39 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicarray.h
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicarray.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __CC_DYNAMICARRAY_H
-#define __CC_DYNAMICARRAY_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_CCDYNAMICARRAY_H
+#define AGS_ENGINE_AC_DYNOBJ_CCDYNAMICARRAY_H
 
 #include <vector>
 #include "ac/dynobj/cc_dynamicobject.h"   // ICCDynamicObject
diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicobject.h b/engines/ags/engine/ac/dynobj/cc_dynamicobject.h
index aeca72f4d0..ada26fd3ff 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicobject.h
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicobject.h
@@ -25,8 +25,9 @@
 // Managed script object interface.
 //
 //=============================================================================
-#ifndef __CC_DYNAMICOBJECT_H
-#define __CC_DYNAMICOBJECT_H
+
+#ifndef AGS_ENGINE_AC_DYNOBJ_CCDYNAMICOBJECT_H
+#define AGS_ENGINE_AC_DYNOBJ_CCDYNAMICOBJECT_H
 
 #include <utility>
 #include "core/types.h"
@@ -123,4 +124,4 @@ extern int ccReleaseObjectReference(int32_t handle);
 
 extern ICCStringClass *stringClassImpl;
 
-#endif // __CC_DYNAMICOBJECT_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h b/engines/ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h
index 4323d97652..99d55e5f0e 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef ADDR_AND_MANAGER_H
-#define ADDR_AND_MANAGER_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_ADDR_AND_MANAGER_H
+#define AGS_ENGINE_AC_DYNOBJ_ADDR_AND_MANAGER_H
 
 #include "script/runtimescriptvalue.h"
 #include "ac/dynobj/cc_dynamicobject.h"
diff --git a/engines/ags/engine/ac/dynobj/cc_gui.h b/engines/ags/engine/ac/dynobj/cc_gui.h
index 39c892d48d..8d1b608387 100644
--- a/engines/ags/engine/ac/dynobj/cc_gui.h
+++ b/engines/ags/engine/ac/dynobj/cc_gui.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_CCGUI_H
-#define __AC_CCGUI_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_CCGUI_H
+#define AGS_ENGINE_AC_DYNOBJ_CCGUI_H
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
@@ -37,4 +37,4 @@ struct CCGUI final : AGSCCDynamicObject {
     void Unserialize(int index, const char *serializedData, int dataSize) override;
 };
 
-#endif // __AC_CCGUI_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/cc_guiobject.h b/engines/ags/engine/ac/dynobj/cc_guiobject.h
index a6bf881654..bb457bed10 100644
--- a/engines/ags/engine/ac/dynobj/cc_guiobject.h
+++ b/engines/ags/engine/ac/dynobj/cc_guiobject.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_CCGUIOBJECT_H
-#define __AC_CCGUIOBJECT_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_CCGUI_H
+#define AGS_ENGINE_AC_DYNOBJ_CCGUI_H
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
@@ -38,4 +38,4 @@ struct CCGUIObject final : AGSCCDynamicObject {
 
 };
 
-#endif // __AC_CCGUIOBJECT_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/cc_hotspot.h b/engines/ags/engine/ac/dynobj/cc_hotspot.h
index 05722895fb..e5ca7a7756 100644
--- a/engines/ags/engine/ac/dynobj/cc_hotspot.h
+++ b/engines/ags/engine/ac/dynobj/cc_hotspot.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_CCHOTSPOT_H
-#define __AC_CCHOTSPOT_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_CCHOTSPOT_H
+#define AGS_ENGINE_AC_DYNOBJ_CCHOTSPOT_H
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
@@ -38,4 +38,4 @@ struct CCHotspot final : AGSCCDynamicObject {
 
 };
 
-#endif // __AC_CCHOTSPOT_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/cc_inventory.h b/engines/ags/engine/ac/dynobj/cc_inventory.h
index aba9dc7c8a..4b793b3394 100644
--- a/engines/ags/engine/ac/dynobj/cc_inventory.h
+++ b/engines/ags/engine/ac/dynobj/cc_inventory.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_CCINVENTORY_H
-#define __AC_CCINVENTORY_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_CCINVENTORY_H
+#define AGS_ENGINE_AC_DYNOBJ_CCINVENTORY_H
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
@@ -38,4 +38,4 @@ struct CCInventory final : AGSCCDynamicObject {
 
 };
 
-#endif // __AC_CCINVENTORY_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/cc_object.h b/engines/ags/engine/ac/dynobj/cc_object.h
index f81b0d5cdf..88533aaebe 100644
--- a/engines/ags/engine/ac/dynobj/cc_object.h
+++ b/engines/ags/engine/ac/dynobj/cc_object.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_CCOBJECT_H
-#define __AC_CCOBJECT_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_CCOBJECT_H
+#define AGS_ENGINE_AC_DYNOBJ_CCOBJECT_H
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
@@ -38,4 +38,4 @@ struct CCObject final : AGSCCDynamicObject {
 
 };
 
-#endif // __AC_CCOBJECT_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/cc_region.h b/engines/ags/engine/ac/dynobj/cc_region.h
index 6abb7df153..c16136d599 100644
--- a/engines/ags/engine/ac/dynobj/cc_region.h
+++ b/engines/ags/engine/ac/dynobj/cc_region.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_CCREGION_H
-#define __AC_CCREGION_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_CCREGION_H
+#define AGS_ENGINE_AC_DYNOBJ_CCREGION_H
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
@@ -38,4 +38,4 @@ struct CCRegion final : AGSCCDynamicObject {
 
 };
 
-#endif // __AC_CCREGION_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/cc_serializer.h b/engines/ags/engine/ac/dynobj/cc_serializer.h
index 9de17b54d5..655138738b 100644
--- a/engines/ags/engine/ac/dynobj/cc_serializer.h
+++ b/engines/ags/engine/ac/dynobj/cc_serializer.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_SERIALIZER_H
-#define __AC_SERIALIZER_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_CCSERIALIZER_H
+#define AGS_ENGINE_AC_DYNOBJ_CCSERIALIZER_H
 
 #include "ac/dynobj/cc_dynamicobject.h"
 
@@ -32,4 +32,4 @@ struct AGSDeSerializer : ICCObjectReader {
 
 extern AGSDeSerializer ccUnserializer;
 
-#endif // __AC_SERIALIZER_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/managedobjectpool.h b/engines/ags/engine/ac/dynobj/managedobjectpool.h
index 6697592d9b..b082842225 100644
--- a/engines/ags/engine/ac/dynobj/managedobjectpool.h
+++ b/engines/ags/engine/ac/dynobj/managedobjectpool.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __CC_MANAGEDOBJECTPOOL_H
-#define __CC_MANAGEDOBJECTPOOL_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_MANAGEDOBJECTPOOL_H
+#define AGS_ENGINE_AC_DYNOBJ_MANAGEDOBJECTPOOL_H
 
 #include <vector>
 #include <queue>
@@ -93,4 +93,4 @@ extern ManagedObjectPool pool;
 #define ManagedObjectLog(...)
 #endif
 
-#endif // __CC_MANAGEDOBJECTPOOL_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/scriptaudiochannel.h b/engines/ags/engine/ac/dynobj/scriptaudiochannel.h
index c8ecb6fbf8..8b762f7ec3 100644
--- a/engines/ags/engine/ac/dynobj/scriptaudiochannel.h
+++ b/engines/ags/engine/ac/dynobj/scriptaudiochannel.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_DYNOBJ__SCRIPTAUDIOCHANNEL_H
-#define __AGS_EE_DYNOBJ__SCRIPTAUDIOCHANNEL_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTAUDIOCHANNEL_H
+#define AGS_ENGINE_AC_DYNOBJ_SCRIPTAUDIOCHANNEL_H
 
 struct ScriptAudioChannel
 {
@@ -29,4 +29,4 @@ struct ScriptAudioChannel
     int reserved;
 };
 
-#endif // __AGS_EE_DYNOBJ__SCRIPTAUDIOCHANNEL_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/scriptcamera.h b/engines/ags/engine/ac/dynobj/scriptcamera.h
index 292e022160..16708a1e83 100644
--- a/engines/ags/engine/ac/dynobj/scriptcamera.h
+++ b/engines/ags/engine/ac/dynobj/scriptcamera.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_SCRIPTCAMERA_H
-#define __AC_SCRIPTCAMERA_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTCAMERA_H
+#define AGS_ENGINE_AC_DYNOBJ_SCRIPTCAMERA_H
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
@@ -49,4 +49,4 @@ private:
 // Unserialize camera from the memory stream
 ScriptCamera *Camera_Unserialize(int handle, const char *serializedData, int dataSize);
 
-#endif // __AC_SCRIPTCAMERA_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/scriptcontainers.h b/engines/ags/engine/ac/dynobj/scriptcontainers.h
index 5159a237ef..f735c6514b 100644
--- a/engines/ags/engine/ac/dynobj/scriptcontainers.h
+++ b/engines/ags/engine/ac/dynobj/scriptcontainers.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_SCRIPTCONTAINERS_H
-#define __AC_SCRIPTCONTAINERS_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTCONTAINERS_H
+#define AGS_ENGINE_AC_DYNOBJ_SCRIPTCONTAINERS_H
 
 class ScriptDictBase;
 class ScriptSetBase;
@@ -35,4 +35,4 @@ ScriptSetBase *Set_Create(bool sorted, bool case_sensitive);
 // Unserialize set from the memory stream
 ScriptSetBase *Set_Unserialize(int index, const char *serializedData, int dataSize);
 
-#endif // __AC_SCRIPTCONTAINERS_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/scriptdatetime.h b/engines/ags/engine/ac/dynobj/scriptdatetime.h
index c898e93fa6..e65661a319 100644
--- a/engines/ags/engine/ac/dynobj/scriptdatetime.h
+++ b/engines/ags/engine/ac/dynobj/scriptdatetime.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_DYNOBJ__SCRIPTDATETIME_H
-#define __AGS_EE_DYNOBJ__SCRIPTDATETIME_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTDATETIME_H
+#define AGS_ENGINE_AC_DYNOBJ_SCRIPTDATETIME_H
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
@@ -38,4 +38,4 @@ struct ScriptDateTime final : AGSCCDynamicObject {
     ScriptDateTime();
 };
 
-#endif // __AGS_EE_DYNOBJ__SCRIPTDATETIME_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/scriptdialog.h b/engines/ags/engine/ac/dynobj/scriptdialog.h
index f549afcd1e..9668fa4d62 100644
--- a/engines/ags/engine/ac/dynobj/scriptdialog.h
+++ b/engines/ags/engine/ac/dynobj/scriptdialog.h
@@ -20,12 +20,12 @@
  *
  */
 
-#ifndef __AGS_EE_DYNOBJ__SCRIPTDIALOG_H
-#define __AGS_EE_DYNOBJ__SCRIPTDIALOG_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTDIALOG_H
+#define AGS_ENGINE_AC_DYNOBJ_SCRIPTDIALOG_H
 
 struct ScriptDialog {
     int id;
     int reserved;
 };
 
-#endif // __AGS_EE_DYNOBJ__SCRIPTDIALOG_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.h b/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.h
index d13ab0e8c3..bc09dd8d8c 100644
--- a/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.h
+++ b/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_SCRIPTDIALOGOPTIONSRENDERING_H
-#define __AC_SCRIPTDIALOGOPTIONSRENDERING_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTDIALOGOPTIONSRENDERING_H
+#define AGS_ENGINE_AC_DYNOBJ_SCRIPTDIALOGOPTIONSRENDERING_H
 
 #include "ac/dynobj/scriptdrawingsurface.h"
 
@@ -52,4 +52,4 @@ struct ScriptDialogOptionsRendering final : AGSCCDynamicObject {
 };
 
 
-#endif // __AC_SCRIPTDIALOGOPTIONSRENDERING_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/scriptdict.h b/engines/ags/engine/ac/dynobj/scriptdict.h
index 62039f4c76..da8062ed08 100644
--- a/engines/ags/engine/ac/dynobj/scriptdict.h
+++ b/engines/ags/engine/ac/dynobj/scriptdict.h
@@ -33,8 +33,8 @@
 //
 //=============================================================================
 
-#ifndef __AC_SCRIPTDICT_H
-#define __AC_SCRIPTDICT_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTDICT_H
+#define AGS_ENGINE_AC_DYNOBJ_SCRIPTDICT_H
 
 #include <map>
 #include <unordered_map>
@@ -194,4 +194,4 @@ typedef ScriptDictImpl< std::map<String, String, StrLessNoCase>, true, false > S
 typedef ScriptDictImpl< std::unordered_map<String, String>, false, true > ScriptHashDict;
 typedef ScriptDictImpl< std::unordered_map<String, String, HashStrNoCase, StrEqNoCase>, false, false > ScriptHashDictCI;
 
-#endif // __AC_SCRIPTDICT_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/scriptdrawingsurface.h b/engines/ags/engine/ac/dynobj/scriptdrawingsurface.h
index 8cf35a6d93..b3f4a190e4 100644
--- a/engines/ags/engine/ac/dynobj/scriptdrawingsurface.h
+++ b/engines/ags/engine/ac/dynobj/scriptdrawingsurface.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_SCRIPTDRAWINGSURFACE_H
-#define __AC_SCRIPTDRAWINGSURFACE_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTDRAWINGSURFACE_H
+#define AGS_ENGINE_AC_DYNOBJ_SCRIPTDRAWINGSURFACE_H
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 #include "game/roomstruct.h"
@@ -60,4 +60,4 @@ struct ScriptDrawingSurface final : AGSCCDynamicObject {
     ScriptDrawingSurface();
 };
 
-#endif // __AC_SCRIPTDRAWINGSURFACE_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/scriptdynamicsprite.h b/engines/ags/engine/ac/dynobj/scriptdynamicsprite.h
index fccb51ba38..0104d759b1 100644
--- a/engines/ags/engine/ac/dynobj/scriptdynamicsprite.h
+++ b/engines/ags/engine/ac/dynobj/scriptdynamicsprite.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_SCRIPTDYNAMICSPRITE_H
-#define __AC_SCRIPTDYNAMICSPRITE_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTDYNAMICSPRITE_H
+#define AGS_ENGINE_AC_DYNOBJ_SCRIPTDYNAMICSPRITE_H
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
@@ -37,4 +37,4 @@ struct ScriptDynamicSprite final  : AGSCCDynamicObject {
     ScriptDynamicSprite();
 };
 
-#endif // __AC_SCRIPTDYNAMICSPRITE_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/scriptfile.h b/engines/ags/engine/ac/dynobj/scriptfile.h
index 538d79c206..3a1571fb61 100644
--- a/engines/ags/engine/ac/dynobj/scriptfile.h
+++ b/engines/ags/engine/ac/dynobj/scriptfile.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_DYNOBJ__SCRIPTFILE_H
-#define __AGS_EE_DYNOBJ__SCRIPTFILE_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTFILE_H
+#define AGS_ENGINE_AC_DYNOBJ_SCRIPTFILE_H
 
 #include "ac/dynobj/cc_dynamicobject.h"
 #include "util/file.h"
@@ -63,4 +63,4 @@ struct sc_File final : ICCDynamicObject {
     void    WriteFloat(const char *address, intptr_t offset, float val) override;
 };
 
-#endif // __AGS_EE_DYNOBJ__SCRIPTFILE_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/scriptgui.h b/engines/ags/engine/ac/dynobj/scriptgui.h
index 6dffd085c3..690a803ef2 100644
--- a/engines/ags/engine/ac/dynobj/scriptgui.h
+++ b/engines/ags/engine/ac/dynobj/scriptgui.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_DYNOBJ__SCRIPTGUI_H
-#define __AGS_EE_DYNOBJ__SCRIPTGUI_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTGUI_H
+#define AGS_ENGINE_AC_DYNOBJ_SCRIPTGUI_H
 
 // 64 bit: This struct must be 8 byte long
 struct ScriptGUI {
@@ -29,4 +29,4 @@ struct ScriptGUI {
   int __padding;
 };
 
-#endif // __AGS_EE_DYNOBJ__SCRIPTGUI_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/scripthotspot.h b/engines/ags/engine/ac/dynobj/scripthotspot.h
index 181b3b2bca..dd93e1aa70 100644
--- a/engines/ags/engine/ac/dynobj/scripthotspot.h
+++ b/engines/ags/engine/ac/dynobj/scripthotspot.h
@@ -20,12 +20,12 @@
  *
  */
 
-#ifndef __AGS_EE_DYNOBJ__SCRIPTHOTSPOT_H
-#define __AGS_EE_DYNOBJ__SCRIPTHOTSPOT_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTHOTSPOT_H
+#define AGS_ENGINE_AC_DYNOBJ_SCRIPTHOTSPOT_H
 
 struct ScriptHotspot {
     int id;
     int reserved;
 };
 
-#endif // __AGS_EE_DYNOBJ__SCRIPTHOTSPOT_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/scriptinvitem.h b/engines/ags/engine/ac/dynobj/scriptinvitem.h
index e55e98dbf9..b6da8b17ab 100644
--- a/engines/ags/engine/ac/dynobj/scriptinvitem.h
+++ b/engines/ags/engine/ac/dynobj/scriptinvitem.h
@@ -20,12 +20,12 @@
  *
  */
 
-#ifndef __AGS_EE_DYNOBJ__SCRIPTINVITEM_H
-#define __AGS_EE_DYNOBJ__SCRIPTINVITEM_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTINVITEM_H
+#define AGS_ENGINE_AC_DYNOBJ_SCRIPTINVITEM_H
 
 struct ScriptInvItem {
     int id;
     int reserved;
 };
 
-#endif // __AGS_EE_DYNOBJ__SCRIPTINVITEM_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/scriptmouse.h b/engines/ags/engine/ac/dynobj/scriptmouse.h
index 2eb0697aba..c2cc4f75d9 100644
--- a/engines/ags/engine/ac/dynobj/scriptmouse.h
+++ b/engines/ags/engine/ac/dynobj/scriptmouse.h
@@ -20,12 +20,12 @@
  *
  */
 
-#ifndef __AGS_EE_DYNOBJ__SCRIPTMOUSE_H
-#define __AGS_EE_DYNOBJ__SCRIPTMOUSE_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTMOUSE_H
+#define AGS_ENGINE_AC_DYNOBJ_SCRIPTMOUSE_H
 
 // The text script's "mouse" struct
 struct ScriptMouse {
     int x,y;
 };
 
-#endif // __AGS_EE_DYNOBJ__SCRIPTMOUSE_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/scriptobject.h b/engines/ags/engine/ac/dynobj/scriptobject.h
index 37545d2c78..154393ce1e 100644
--- a/engines/ags/engine/ac/dynobj/scriptobject.h
+++ b/engines/ags/engine/ac/dynobj/scriptobject.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_DYNOBJ__SCRIPTOBJECT_H
-#define __AGS_EE_DYNOBJ__SCRIPTOBJECT_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTOBJECT_H
+#define AGS_ENGINE_AC_DYNOBJ_SCRIPTOBJECT_H
 
 #include "ac/roomobject.h"
 
@@ -32,4 +32,4 @@ struct ScriptObject {
   int __padding;
 };
 
-#endif // __AGS_EE_DYNOBJ__SCRIPTOBJECT_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/scriptoverlay.h b/engines/ags/engine/ac/dynobj/scriptoverlay.h
index 8b678605f5..76785cd922 100644
--- a/engines/ags/engine/ac/dynobj/scriptoverlay.h
+++ b/engines/ags/engine/ac/dynobj/scriptoverlay.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_SCRIPTOVERLAY_H
-#define __AC_SCRIPTOVERLAY_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTOVERLAY_H
+#define AGS_ENGINE_AC_DYNOBJ_SCRIPTOVERLAY_H
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
@@ -39,4 +39,4 @@ struct ScriptOverlay final : AGSCCDynamicObject {
     ScriptOverlay();
 };
 
-#endif // __AC_SCRIPTOVERLAY_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/scriptregion.h b/engines/ags/engine/ac/dynobj/scriptregion.h
index 4bf38a95c7..86deb65f0b 100644
--- a/engines/ags/engine/ac/dynobj/scriptregion.h
+++ b/engines/ags/engine/ac/dynobj/scriptregion.h
@@ -20,12 +20,12 @@
  *
  */
 
-#ifndef __AGS_EE_DYNOBJ__SCRIPTREGION_H
-#define __AGS_EE_DYNOBJ__SCRIPTREGION_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTREGION_H
+#define AGS_ENGINE_AC_DYNOBJ_SCRIPTREGION_H
 
 struct ScriptRegion {
     int id;
     int reserved;
 };
 
-#endif // __AGS_EE_DYNOBJ__SCRIPTREGION_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/scriptset.h b/engines/ags/engine/ac/dynobj/scriptset.h
index d5ad8a9155..3f71b19b8f 100644
--- a/engines/ags/engine/ac/dynobj/scriptset.h
+++ b/engines/ags/engine/ac/dynobj/scriptset.h
@@ -32,8 +32,8 @@
 //
 //=============================================================================
 
-#ifndef __AC_SCRIPTSET_H
-#define __AC_SCRIPTSET_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTSET_H
+#define AGS_ENGINE_AC_DYNOBJ_SCRIPTSET_H
 
 #include <set>
 #include <unordered_set>
@@ -152,4 +152,4 @@ typedef ScriptSetImpl< std::set<String, StrLessNoCase>, true, false > ScriptSetC
 typedef ScriptSetImpl< std::unordered_set<String>, false, true > ScriptHashSet;
 typedef ScriptSetImpl< std::unordered_set<String, HashStrNoCase, StrEqNoCase>, false, false > ScriptHashSetCI;
 
-#endif // __AC_SCRIPTSET_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/scriptstring.h b/engines/ags/engine/ac/dynobj/scriptstring.h
index 041f3b3f32..b59595b094 100644
--- a/engines/ags/engine/ac/dynobj/scriptstring.h
+++ b/engines/ags/engine/ac/dynobj/scriptstring.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_SCRIPTSTRING_H
-#define __AC_SCRIPTSTRING_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTSTRING_H
+#define AGS_ENGINE_AC_DYNOBJ_SCRIPTSTRING_H
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
@@ -39,4 +39,4 @@ struct ScriptString final : AGSCCDynamicObject, ICCStringClass {
     ScriptString(const char *fromText);
 };
 
-#endif // __AC_SCRIPTSTRING_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/scriptsystem.h b/engines/ags/engine/ac/dynobj/scriptsystem.h
index 815d30cb02..4b5d19a8fd 100644
--- a/engines/ags/engine/ac/dynobj/scriptsystem.h
+++ b/engines/ags/engine/ac/dynobj/scriptsystem.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_DYNOBJ__SCRIPTSYSTEM_H
-#define __AGS_EE_DYNOBJ__SCRIPTSYSTEM_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTSYSTEM_H
+#define AGS_ENGINE_AC_DYNOBJ_SCRIPTSYSTEM_H
 
 // The text script's "system" struct
 struct ScriptSystem {
@@ -35,4 +35,4 @@ struct ScriptSystem {
     int reserved[5];  // so that future scripts don't overwrite data
 };
 
-#endif // __AGS_EE_DYNOBJ__SCRIPTSYSTEM_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/scriptuserobject.h b/engines/ags/engine/ac/dynobj/scriptuserobject.h
index 36bfe28909..f89ac7fe76 100644
--- a/engines/ags/engine/ac/dynobj/scriptuserobject.h
+++ b/engines/ags/engine/ac/dynobj/scriptuserobject.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_DYNOBJ__SCRIPTUSERSTRUCT_H
-#define __AGS_EE_DYNOBJ__SCRIPTUSERSTRUCT_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTUSERSTRUCT_H
+#define AGS_ENGINE_AC_DYNOBJ_SCRIPTUSERSTRUCT_H
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
@@ -83,4 +83,4 @@ namespace ScriptStructHelpers
     ScriptUserObject *CreatePoint(int x, int y);
 };
 
-#endif // __AGS_EE_DYNOBJ__SCRIPTUSERSTRUCT_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/scriptviewframe.h b/engines/ags/engine/ac/dynobj/scriptviewframe.h
index 83ad44b88f..b625328b02 100644
--- a/engines/ags/engine/ac/dynobj/scriptviewframe.h
+++ b/engines/ags/engine/ac/dynobj/scriptviewframe.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_SCRIPTVIEWFRAME_H
-#define __AC_SCRIPTVIEWFRAME_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTVIEWFRAME_H
+#define AGS_ENGINE_AC_DYNOBJ_SCRIPTVIEWFRAME_H
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
@@ -37,4 +37,4 @@ struct ScriptViewFrame final : AGSCCDynamicObject {
     ScriptViewFrame();
 };
 
-#endif // __AC_SCRIPTVIEWFRAME_H
+#endif
diff --git a/engines/ags/engine/ac/dynobj/scriptviewport.h b/engines/ags/engine/ac/dynobj/scriptviewport.h
index a9fe886283..26ca3cde8c 100644
--- a/engines/ags/engine/ac/dynobj/scriptviewport.h
+++ b/engines/ags/engine/ac/dynobj/scriptviewport.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_SCRIPTVIEWPORT_H
-#define __AC_SCRIPTVIEWPORT_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTVIEWPORT_H
+#define AGS_ENGINE_AC_DYNOBJ_SCRIPTVIEWPORT_H
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
@@ -48,4 +48,4 @@ private:
 // Unserialize viewport from the memory stream
 ScriptViewport *Viewport_Unserialize(int handle, const char *serializedData, int dataSize);
 
-#endif // __AC_SCRIPTVIEWPORT_H
+#endif
diff --git a/engines/ags/engine/ac/event.h b/engines/ags/engine/ac/event.h
index 78e7b486e9..d22acd0979 100644
--- a/engines/ags/engine/ac/event.h
+++ b/engines/ags/engine/ac/event.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__EVENT_H
-#define __AGS_EE_AC__EVENT_H
+#ifndef AGS_ENGINE_AC_EVENT_H
+#define AGS_ENGINE_AC_EVENT_H
 
 #include "ac/runtime_defines.h"
 #include "script/runtimescriptvalue.h"
@@ -84,5 +84,4 @@ extern int eventClaimed;
 
 extern const char*tsnames[4];
 
-#endif // __AGS_EE_AC__EVENT_H
-
+#endif
diff --git a/engines/ags/engine/ac/file.h b/engines/ags/engine/ac/file.h
index 0f0b2aeac8..dd00616365 100644
--- a/engines/ags/engine/ac/file.h
+++ b/engines/ags/engine/ac/file.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_AC__FILE_H
-#define __AGS_EE_AC__FILE_H
+#ifndef AGS_ENGINE_AC_FILE_H
+#define AGS_ENGINE_AC_FILE_H
 
 #include "ac/dynobj/scriptfile.h"
 #include "ac/runtime_defines.h"
@@ -65,4 +65,4 @@ ScriptFileHandle *check_valid_file_handle_ptr(Stream *stream_ptr, const char *op
 ScriptFileHandle *check_valid_file_handle_int32(int32_t handle, const char *operation_name);
 Stream *get_valid_file_stream_from_handle(int32_t handle, const char *operation_name);
 
-#endif // __AGS_EE_AC__FILE_H
+#endif
diff --git a/engines/ags/engine/ac/game.h b/engines/ags/engine/ac/game.h
index c09fc59b24..a3e9b4cbee 100644
--- a/engines/ags/engine/ac/game.h
+++ b/engines/ags/engine/ac/game.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_AC__GAME_H
-#define __AGS_EE_AC__GAME_H
+#ifndef AGS_ENGINE_AC_GAME_H
+#define AGS_ENGINE_AC_GAME_H
 
 #include "ac/dynobj/scriptviewframe.h"
 #include "main/game_file.h"
@@ -199,4 +199,4 @@ extern unsigned int loopcounter;
 extern void set_loop_counter(unsigned int new_counter);
 extern int game_paused;
 
-#endif // __AGS_EE_AC__GAME_H
+#endif
diff --git a/engines/ags/engine/ac/gamesetup.h b/engines/ags/engine/ac/gamesetup.h
index 54708a26cd..9f204c624d 100644
--- a/engines/ags/engine/ac/gamesetup.h
+++ b/engines/ags/engine/ac/gamesetup.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_GAMESETUP_H
-#define __AC_GAMESETUP_H
+#ifndef AGS_ENGINE_AC_GAMESETUP_H
+#define AGS_ENGINE_AC_GAMESETUP_H
 
 #include "main/graphics_mode.h"
 #include "util/string.h"
@@ -91,4 +91,4 @@ struct GameSetup {
 // Perhaps it makes sense to separate those two group of vars at some point.
 extern GameSetup usetup;
 
-#endif // __AC_GAMESETUP_H
+#endif
diff --git a/engines/ags/engine/ac/gamestate.h b/engines/ags/engine/ac/gamestate.h
index 413b508b46..24d6b64ff8 100644
--- a/engines/ags/engine/ac/gamestate.h
+++ b/engines/ags/engine/ac/gamestate.h
@@ -20,9 +20,8 @@
  *
  */
 
-#ifndef __AC_GAMESTATE_H
-#define __AC_GAMESTATE_H
-
+#ifndef AGS_ENGINE_AC_GAMESTATE_H
+#define AGS_ENGINE_AC_GAMESTATE_H
 
 #include <memory>
 #include <vector>
@@ -401,4 +400,4 @@ HorAlignment ReadScriptAlignment(int32_t align);
 
 extern GameState play;
 
-#endif // __AC_GAMESTATE_H
+#endif
diff --git a/engines/ags/engine/ac/global_audio.h b/engines/ags/engine/ac/global_audio.h
index 9bf1c5b95b..0f6a7f61bd 100644
--- a/engines/ags/engine/ac/global_audio.h
+++ b/engines/ags/engine/ac/global_audio.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALAUDIO_H
-#define __AGS_EE_AC__GLOBALAUDIO_H
+#ifndef AGS_ENGINE_AC_GLOBALAUDIO_H
+#define AGS_ENGINE_AC_GLOBALAUDIO_H
 
 void    StopAmbientSound (int channel);
 void    PlayAmbientSound (int channel, int sndnum, int vol, int x, int y);
@@ -73,4 +73,4 @@ void    stop_voice_speech();
 // Stop non-blocking voice-over and revert audio volumes if necessary
 void    stop_voice_nonblocking();
 
-#endif // __AGS_EE_AC__GLOBALAUDIO_H
+#endif
diff --git a/engines/ags/engine/ac/global_button.h b/engines/ags/engine/ac/global_button.h
index d4f2561e91..518e73c63f 100644
--- a/engines/ags/engine/ac/global_button.h
+++ b/engines/ags/engine/ac/global_button.h
@@ -20,12 +20,12 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALBUTTON_H
-#define __AGS_EE_AC__GLOBALBUTTON_H
+#ifndef AGS_ENGINE_AC_GLOBALBUTTON_H
+#define AGS_ENGINE_AC_GLOBALBUTTON_H
 
 void SetButtonText(int guin,int objn, const char*newtx);
 void AnimateButton(int guin, int objn, int view, int loop, int speed, int repeat);
 int  GetButtonPic(int guin, int objn, int ptype);
 void SetButtonPic(int guin,int objn,int ptype,int slotn);
 
-#endif // __AGS_EE_AC__GLOBALBUTTON_H
+#endif
diff --git a/engines/ags/engine/ac/global_character.h b/engines/ags/engine/ac/global_character.h
index 48483a03a3..e9d19b4c21 100644
--- a/engines/ags/engine/ac/global_character.h
+++ b/engines/ags/engine/ac/global_character.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALCHARACTER_H
-#define __AGS_EE_AC__GLOBALCHARACTER_H
+#ifndef AGS_ENGINE_AC_GLOBALCHARACTER_H
+#define AGS_ENGINE_AC_GLOBALCHARACTER_H
 
 #include "ac/characterinfo.h"
 
@@ -89,4 +89,4 @@ void __sc_displayspeech(int chid, const char *text);
 void DisplaySpeechAt (int xx, int yy, int wii, int aschar, const char*spch);
 int DisplaySpeechBackground(int charid, const char*speel);
 
-#endif // __AGS_EE_AC__CHARACTEREXTRAS_H
+#endif
diff --git a/engines/ags/engine/ac/global_datetime.h b/engines/ags/engine/ac/global_datetime.h
index caf287111c..55fd3abe63 100644
--- a/engines/ags/engine/ac/global_datetime.h
+++ b/engines/ags/engine/ac/global_datetime.h
@@ -20,10 +20,10 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALDATETIME_H
-#define __AGS_EE_AC__GLOBALDATETIME_H
+#ifndef AGS_ENGINE_AC_GLOBALDATETIME_H
+#define AGS_ENGINE_AC_GLOBALDATETIME_H
 
 int sc_GetTime(int whatti) ;
 int GetRawTime ();
 
-#endif // __AGS_EE_AC__GLOBALDATETIME_H
+#endif
diff --git a/engines/ags/engine/ac/global_debug.h b/engines/ags/engine/ac/global_debug.h
index bdaabba917..2f4e444515 100644
--- a/engines/ags/engine/ac/global_debug.h
+++ b/engines/ags/engine/ac/global_debug.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALDEBUG_H
-#define __AGS_EE_AC__GLOBALDEBUG_H
+#ifndef AGS_ENGINE_AC_GLOBALDEBUG_H
+#define AGS_ENGINE_AC_GLOBALDEBUG_H
 
 #include <cstdio>
 #include "util/string.h"
@@ -29,4 +29,4 @@
 AGS::Common::String GetRuntimeInfo();
 void script_debug(int cmdd,int dataa);
 
-#endif // __AGS_EE_AC__GLOBALDEBUG_H
+#endif
diff --git a/engines/ags/engine/ac/global_dialog.h b/engines/ags/engine/ac/global_dialog.h
index 7dc7e0e724..faf0539b83 100644
--- a/engines/ags/engine/ac/global_dialog.h
+++ b/engines/ags/engine/ac/global_dialog.h
@@ -20,12 +20,12 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALDIALOG_H
-#define __AGS_EE_AC__GLOBALDIALOG_H
+#ifndef AGS_ENGINE_AC_GLOBALDIALOG_H
+#define AGS_ENGINE_AC_GLOBALDIALOG_H
 
 void RunDialog(int tum);
 int GetDialogOption (int dlg, int opt);
 void SetDialogOption(int dlg, int opt, int onoroff, bool dlg_script = false);
 void StopDialog();
 
-#endif // __AGS_EE_AC__GLOBALDIALOG_H
+#endif
diff --git a/engines/ags/engine/ac/global_display.h b/engines/ags/engine/ac/global_display.h
index 226e5fa986..f71803675c 100644
--- a/engines/ags/engine/ac/global_display.h
+++ b/engines/ags/engine/ac/global_display.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALDISPLAY_H
-#define __AGS_EE_AC__GLOBALDISPLAY_H
+#ifndef AGS_ENGINE_AC_GLOBALDISPLAY_H
+#define AGS_ENGINE_AC_GLOBALDISPLAY_H
 
 #include "ac/speech.h"
 
@@ -39,4 +39,4 @@ void SetSpeechStyle (int newstyle);
 void SetSkipSpeech (SkipSpeechStyle newval);
 SkipSpeechStyle GetSkipSpeech();
 
-#endif // __AGS_EE_AC__GLOBALDISPLAY_H
+#endif
diff --git a/engines/ags/engine/ac/global_drawingsurface.h b/engines/ags/engine/ac/global_drawingsurface.h
index c755113faa..a65fe88a79 100644
--- a/engines/ags/engine/ac/global_drawingsurface.h
+++ b/engines/ags/engine/ac/global_drawingsurface.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALDRAWINGSURFACE_H
-#define __AGS_EE_AC__GLOBALDRAWINGSURFACE_H
+#ifndef AGS_ENGINE_AC_GLOBALDRAWINGSURFACE_H
+#define AGS_ENGINE_AC_GLOBALDRAWINGSURFACE_H
 
 void RawSaveScreen ();
 // RawRestoreScreen: copy backup bitmap back to screen; we
@@ -46,4 +46,4 @@ void RawDrawCircle (int xx, int yy, int rad);
 void RawDrawRectangle(int x1, int y1, int x2, int y2);
 void RawDrawTriangle(int x1, int y1, int x2, int y2, int x3, int y3);
 
-#endif // __AGS_EE_AC__GLOBALDRAWINGSURFACE_H
+#endif
diff --git a/engines/ags/engine/ac/global_dynamicsprite.h b/engines/ags/engine/ac/global_dynamicsprite.h
index 82b264c167..db6fe2d06d 100644
--- a/engines/ags/engine/ac/global_dynamicsprite.h
+++ b/engines/ags/engine/ac/global_dynamicsprite.h
@@ -20,9 +20,9 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALDYNAMICSPRITE_H
-#define __AGS_EE_AC__GLOBALDYNAMICSPRITE_H
+#ifndef AGS_ENGINE_AC_GLOBAL_DYNAMICSPRITE_H
+#define AGS_ENGINE_AC_GLOBAL_DYNAMICSPRITE_H
 
 int LoadImageFile(const char *filename);
 
-#endif // __AGS_EE_AC__GLOBALDYNAMICSPRITE_H
+#endif
diff --git a/engines/ags/engine/ac/global_file.h b/engines/ags/engine/ac/global_file.h
index be67d1288c..7f5b59ee5d 100644
--- a/engines/ags/engine/ac/global_file.h
+++ b/engines/ags/engine/ac/global_file.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALFILE_H
-#define __AGS_EE_AC__GLOBALFILE_H
+#ifndef AGS_ENGINE_AC_GLOBAL_FILE_H
+#define AGS_ENGINE_AC_GLOBAL_FILE_H
 
 #include "util/file.h"
 
@@ -43,4 +43,4 @@ char  FileReadRawChar(int32_t handle);
 int   FileReadRawInt(int32_t handle);
 void  FileWriteRawChar(int32_t handle, int chartoWrite);
 
-#endif // __AGS_EE_AC__GLOBALFILE_H
+#endif
diff --git a/engines/ags/engine/ac/global_game.h b/engines/ags/engine/ac/global_game.h
index 93c309bfc9..a7a4418c99 100644
--- a/engines/ags/engine/ac/global_game.h
+++ b/engines/ags/engine/ac/global_game.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALGAME_H
-#define __AGS_EE_AC__GLOBALGAME_H
+#ifndef AGS_ENGINE_AC_GLOBAL_GAME_H
+#define AGS_ENGINE_AC_GLOBAL_GAME_H
 
 #include "util/string.h"
 using namespace AGS; // FIXME later
@@ -90,4 +90,4 @@ int WaitMouse(int nloops);
 int WaitMouseKey(int nloops);
 void SkipWait();
 
-#endif // __AGS_EE_AC__GLOBALGAME_H
+#endif
diff --git a/engines/ags/engine/ac/global_gui.h b/engines/ags/engine/ac/global_gui.h
index ef18f75eab..680021442a 100644
--- a/engines/ags/engine/ac/global_gui.h
+++ b/engines/ags/engine/ac/global_gui.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALGUI_H
-#define __AGS_EE_AC__GLOBALGUI_H
+#ifndef AGS_ENGINE_AC_GLOBAL_GUI_H
+#define AGS_ENGINE_AC_GLOBAL_GUI_H
 
 // IsGUIOn tells whether GUI is actually displayed on screen right now
 int  IsGUIOn (int guinum);
@@ -56,4 +56,4 @@ int GetGUIObjectAt (int xx, int yy);
 int GetGUIAt (int xx,int yy);
 void SetTextWindowGUI (int guinum);
 
-#endif // __AGS_EE_AC__GLOBALGUI_H
+#endif
diff --git a/engines/ags/engine/ac/global_hotspot.h b/engines/ags/engine/ac/global_hotspot.h
index b19c05f587..339322b9c3 100644
--- a/engines/ags/engine/ac/global_hotspot.h
+++ b/engines/ags/engine/ac/global_hotspot.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALHOTSPOT_H
-#define __AGS_EE_AC__GLOBALHOTSPOT_H
+#ifndef AGS_ENGINE_AC_GLOBAL_HOTSPOT_H
+#define AGS_ENGINE_AC_GLOBAL_HOTSPOT_H
 
 void DisableHotspot(int hsnum);
 void EnableHotspot(int hsnum);
@@ -37,4 +37,4 @@ int  GetHotspotProperty (int hss, const char *property);
 void GetHotspotPropertyText (int item, const char *property, char *bufer);
 
 
-#endif // __AGS_EE_AC__GLOBALHOTSPOT_H
+#endif
diff --git a/engines/ags/engine/ac/global_inventoryitem.h b/engines/ags/engine/ac/global_inventoryitem.h
index af2590db77..56dad5c651 100644
--- a/engines/ags/engine/ac/global_inventoryitem.h
+++ b/engines/ags/engine/ac/global_inventoryitem.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALINVENTORYITEM_H
-#define __AGS_EE_AC__GLOBALINVENTORYITEM_H
+#ifndef AGS_ENGINE_AC_GLOBAL_INVENTORYITEM_H
+#define AGS_ENGINE_AC_GLOBAL_INVENTORYITEM_H
 
 void set_inv_item_pic(int invi, int piccy);
 void SetInvItemName(int invi, const char *newName);
@@ -33,4 +33,4 @@ int  IsInventoryInteractionAvailable (int item, int mood);
 int  GetInvProperty (int item, const char *property);
 void GetInvPropertyText (int item, const char *property, char *bufer);
 
-#endif // __AGS_EE_AC__GLOBALINVENTORYITEM_H
+#endif
diff --git a/engines/ags/engine/ac/global_invwindow.h b/engines/ags/engine/ac/global_invwindow.h
index 02a51d9f4b..fa2e5b6752 100644
--- a/engines/ags/engine/ac/global_invwindow.h
+++ b/engines/ags/engine/ac/global_invwindow.h
@@ -20,10 +20,10 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALINVWINDOW_H
-#define __AGS_EE_AC__GLOBALINVWINDOW_H
+#ifndef AGS_ENGINE_AC_GLOBAL_INVWINDOW_H
+#define AGS_ENGINE_AC_GLOBAL_INVWINDOW_H
 
 void sc_invscreen();
 void SetInvDimensions(int ww,int hh);
 
-#endif // __AGS_EE_AC__GLOBALINVWINDOW_H
+#endif
diff --git a/engines/ags/engine/ac/global_label.h b/engines/ags/engine/ac/global_label.h
index c3f0cb49f0..f3553a5393 100644
--- a/engines/ags/engine/ac/global_label.h
+++ b/engines/ags/engine/ac/global_label.h
@@ -20,11 +20,11 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALLABEL_H
-#define __AGS_EE_AC__GLOBALLABEL_H
+#ifndef AGS_ENGINE_AC_GLOBAL_LABEL_H
+#define AGS_ENGINE_AC_GLOBAL_LABEL_H
 
 void		SetLabelColor(int guin,int objn, int colr);
 void		SetLabelText(int guin,int objn, const char*newtx);
 void		SetLabelFont(int guin,int objn, int fontnum);
 
-#endif // __AGS_EE_AC__GLOBALLABEL_H
+#endif
diff --git a/engines/ags/engine/ac/global_listbox.h b/engines/ags/engine/ac/global_listbox.h
index f49cc5bd7c..df48eadd77 100644
--- a/engines/ags/engine/ac/global_listbox.h
+++ b/engines/ags/engine/ac/global_listbox.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALLISTBOX_H
-#define __AGS_EE_AC__GLOBALLISTBOX_H
+#ifndef AGS_ENGINE_AC_GLOBAL_LISTBOX_H
+#define AGS_ENGINE_AC_GLOBAL_LISTBOX_H
 
 void		ListBoxClear(int guin, int objn);
 void		ListBoxAdd(int guin, int objn, const char*newitem);
@@ -34,4 +34,4 @@ void		ListBoxSetTopItem (int guin, int objn, int item);
 int			ListBoxSaveGameList (int guin, int objn);
 void		ListBoxDirList (int guin, int objn, const char*filemask);
 
-#endif // __AGS_EE_AC__GLOBALLISTBOX_H
+#endif
diff --git a/engines/ags/engine/ac/global_mouse.h b/engines/ags/engine/ac/global_mouse.h
index 5a0345518d..dacbf5e8ee 100644
--- a/engines/ags/engine/ac/global_mouse.h
+++ b/engines/ags/engine/ac/global_mouse.h
@@ -20,10 +20,10 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALMOUSE_H
-#define __AGS_EE_AC__GLOBALMOUSE_H
+#ifndef AGS_ENGINE_AC_GLOBAL_MOUSE_H
+#define AGS_ENGINE_AC_GLOBAL_MOUSE_H
 
 void HideMouseCursor ();
 void ShowMouseCursor ();
 
-#endif // __AGS_EE_AC__GLOBALMOUSE_H
+#endif
diff --git a/engines/ags/engine/ac/global_object.h b/engines/ags/engine/ac/global_object.h
index 4eed9fd27c..65b364fd29 100644
--- a/engines/ags/engine/ac/global_object.h
+++ b/engines/ags/engine/ac/global_object.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALOBJECT_H
-#define __AGS_EE_AC__GLOBALOBJECT_H
+#ifndef AGS_ENGINE_AC_GLOBAL_OBJECT_H
+#define AGS_ENGINE_AC_GLOBAL_OBJECT_H
 
 namespace AGS { namespace Common { class Bitmap; } }
 using namespace AGS; // FIXME later
@@ -73,4 +73,4 @@ void GetObjectPropertyText (int item, const char *property, char *bufer);
 
 Common::Bitmap *GetObjectImage(int obj, int *isFlipped);
 
-#endif // __AGS_EE_AC__GLOBALOBJECT_H
+#endif
diff --git a/engines/ags/engine/ac/global_overlay.h b/engines/ags/engine/ac/global_overlay.h
index 4e43a54b51..3cb71b53f6 100644
--- a/engines/ags/engine/ac/global_overlay.h
+++ b/engines/ags/engine/ac/global_overlay.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALOVERLAY_H
-#define __AGS_EE_AC__GLOBALOVERLAY_H
+#ifndef AGS_ENGINE_AC_GLOBALOVERLAY_H
+#define AGS_ENGINE_AC_GLOBALOVERLAY_H
 
 void RemoveOverlay(int ovrid);
 int  CreateGraphicOverlay(int xx, int yy, int slott, int trans);
@@ -31,4 +31,4 @@ void SetTextOverlay(int ovrid, int xx, int yy, int wii, int fontid, int text_col
 void MoveOverlay(int ovrid, int newx, int newy);
 int  IsOverlayValid(int ovrid);
 
-#endif // __AGS_EE_AC__GLOBALOVERLAY_H
+#endif
diff --git a/engines/ags/engine/ac/global_palette.h b/engines/ags/engine/ac/global_palette.h
index 9a131d52ce..9005c16619 100644
--- a/engines/ags/engine/ac/global_palette.h
+++ b/engines/ags/engine/ac/global_palette.h
@@ -20,11 +20,11 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALPALETTE_H
-#define __AGS_EE_AC__GLOBALPALETTE_H
+#ifndef AGS_ENGINE_AC_GLOBAL_PALETTE_H
+#define AGS_ENGINE_AC_GLOBAL_PALETTE_H
 
 void CyclePalette(int strt,int eend);
 void SetPalRGB(int inndx,int rr,int gg,int bb);
 void UpdatePalette();
 
-#endif // __AGS_EE_AC__GLOBALPALETTE_H
+#endif
diff --git a/engines/ags/engine/ac/global_parser.h b/engines/ags/engine/ac/global_parser.h
index 427723dff6..9277267809 100644
--- a/engines/ags/engine/ac/global_parser.h
+++ b/engines/ags/engine/ac/global_parser.h
@@ -20,9 +20,9 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALPARSER_H
-#define __AGS_EE_AC__GLOBALPARSER_H
+#ifndef AGS_ENGINE_AC_GLOBAL_PARSER_H
+#define AGS_ENGINE_AC_GLOBAL_PARSER_H
 
 int SaidUnknownWord (char*buffer);
 
-#endif // __AGS_EE_AC__GLOBALPARSER_H
+#endif
diff --git a/engines/ags/engine/ac/global_plugin.h b/engines/ags/engine/ac/global_plugin.h
index 9fdae6e20e..7d14d7f8ad 100644
--- a/engines/ags/engine/ac/global_plugin.h
+++ b/engines/ags/engine/ac/global_plugin.h
@@ -20,10 +20,10 @@
  *
  */
 
-#ifndef __AGS_EE_PLUGIN__PLUGINFUNC_H
-#define __AGS_EE_PLUGIN__PLUGINFUNC_H
+#ifndef AGS_ENGINE_AC_GLOBAL_PLUGIN_H
+#define AGS_ENGINE_AC_GLOBAL_PLUGIN_H
 
 void PluginSimulateMouseClick(int pluginButtonID);
 bool RegisterPluginStubs(const char* name);
 
-#endif // __AGS_EE_PLUGIN__PLUGINFUNC_H
+#endif
diff --git a/engines/ags/engine/ac/global_record.h b/engines/ags/engine/ac/global_record.h
index adc9f60946..1a924b3701 100644
--- a/engines/ags/engine/ac/global_record.h
+++ b/engines/ags/engine/ac/global_record.h
@@ -20,9 +20,9 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALRECORD_H
-#define __AGS_EE_AC__GLOBALRECORD_H
+#ifndef AGS_ENGINE_AC_GLOBAL_RECORD_H
+#define AGS_ENGINE_AC_GLOBAL_RECORD_H
 
 void scStartRecording (int keyToStop);
 
-#endif // __AGS_EE_AC__GLOBALRECORD_H
+#endif
diff --git a/engines/ags/engine/ac/global_region.h b/engines/ags/engine/ac/global_region.h
index 5dbfdd382f..0c69239d85 100644
--- a/engines/ags/engine/ac/global_region.h
+++ b/engines/ags/engine/ac/global_region.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALREGION_H
-#define __AGS_EE_AC__GLOBALREGION_H
+#ifndef AGS_ENGINE_AC_GLOBAL_REGION_H
+#define AGS_ENGINE_AC_GLOBAL_REGION_H
 
 // Gets region ID at the given room coordinates;
 // if region is disabled or non-existing, returns 0 (no area)
@@ -34,4 +34,4 @@ void DisableGroundLevelAreas(int alsoEffects);
 void EnableGroundLevelAreas();
 void RunRegionInteraction (int regnum, int mood);
 
-#endif // __AGS_EE_AC__GLOBALREGION_H
+#endif
diff --git a/engines/ags/engine/ac/global_room.h b/engines/ags/engine/ac/global_room.h
index f19a849f67..e469d7a34f 100644
--- a/engines/ags/engine/ac/global_room.h
+++ b/engines/ags/engine/ac/global_room.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALROOM_H
-#define __AGS_EE_AC__GLOBALROOM_H
+#ifndef AGS_ENGINE_AC_GLOBAL_ROOM_H
+#define AGS_ENGINE_AC_GLOBAL_ROOM_H
 
 void SetAmbientTint (int red, int green, int blue, int opacity, int luminance);
 void SetAmbientLightLevel(int light_level);
@@ -37,4 +37,4 @@ void GetRoomPropertyText (const char *property, char *bufer);
 void SetBackgroundFrame(int frnum);
 int GetBackgroundFrame() ;
 
-#endif // __AGS_EE_AC__GLOBALROOM_H
+#endif
diff --git a/engines/ags/engine/ac/global_screen.h b/engines/ags/engine/ac/global_screen.h
index a412ae37d9..ea6d5f1be6 100644
--- a/engines/ags/engine/ac/global_screen.h
+++ b/engines/ags/engine/ac/global_screen.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALSCREEN_H
-#define __AGS_EE_AC__GLOBALSCREEN_H
+#ifndef AGS_ENGINE_AC_GLOBAL_SCREEN_H
+#define AGS_ENGINE_AC_GLOBAL_SCREEN_H
 
 void FlipScreen(int amount);
 void ShakeScreen(int severe);
@@ -33,4 +33,4 @@ void SetNextScreenTransition(int newtrans);
 void SetFadeColor(int red, int green, int blue);
 void FadeIn(int sppd);
 
-#endif // __AGS_EE_AC__GLOBALSCREEN_H
+#endif
diff --git a/engines/ags/engine/ac/global_slider.h b/engines/ags/engine/ac/global_slider.h
index bf6b59f336..a904619574 100644
--- a/engines/ags/engine/ac/global_slider.h
+++ b/engines/ags/engine/ac/global_slider.h
@@ -20,10 +20,10 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALSLIDER_H
-#define __AGS_EE_AC__GLOBALSLIDER_H
+#ifndef AGS_ENGINE_AC_GLOBAL_SLIDER_H
+#define AGS_ENGINE_AC_GLOBAL_SLIDER_H
 
 void	SetSliderValue(int guin,int objn, int valn);
 int		GetSliderValue(int guin,int objn);
 
-#endif // __AGS_EE_AC__GLOBALSLIDER_H
+#endif
diff --git a/engines/ags/engine/ac/global_string.h b/engines/ags/engine/ac/global_string.h
index 6369fae8fa..a78b30b552 100644
--- a/engines/ags/engine/ac/global_string.h
+++ b/engines/ags/engine/ac/global_string.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALSTRING_H
-#define __AGS_EE_AC__GLOBALSTRING_H
+#ifndef AGS_ENGINE_AC_GLOBAL_STRING_H
+#define AGS_ENGINE_AC_GLOBAL_STRING_H
 
 int StrGetCharAt (const char *strin, int posn);
 void StrSetCharAt (char *strin, int posn, int nchar);
@@ -30,4 +30,4 @@ void _sc_strlower (char *desbuf);
 void _sc_strupper (char *desbuf);
 void _sc_strcpy(char*destt, const char*text);
 
-#endif // __AGS_EE_AC__GLOBALSTRING_H
+#endif
diff --git a/engines/ags/engine/ac/global_textbox.h b/engines/ags/engine/ac/global_textbox.h
index f5e6f9cf85..d42f1ddd3b 100644
--- a/engines/ags/engine/ac/global_textbox.h
+++ b/engines/ags/engine/ac/global_textbox.h
@@ -20,11 +20,11 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALTEXTBOX_H
-#define __AGS_EE_AC__GLOBALTEXTBOX_H
+#ifndef AGS_ENGINE_AC_GLOBAL_TEXTBOX_H
+#define AGS_ENGINE_AC_GLOBAL_TEXTBOX_H
 
 void SetTextBoxFont(int guin,int objn, int fontnum);
 void GetTextBoxText(int guin, int objn, char*txbuf);
 void SetTextBoxText(int guin, int objn, const char*txbuf);
 
-#endif // __AGS_EE_AC__GLOBALTEXTBOX_H
+#endif
diff --git a/engines/ags/engine/ac/global_timer.h b/engines/ags/engine/ac/global_timer.h
index b244766b82..b387bd8955 100644
--- a/engines/ags/engine/ac/global_timer.h
+++ b/engines/ags/engine/ac/global_timer.h
@@ -20,10 +20,10 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALTIMER_H
-#define __AGS_EE_AC__GLOBALTIMER_H
+#ifndef AGS_ENGINE_AC_GLOBAL_TIMER_H
+#define AGS_ENGINE_AC_GLOBAL_TIMER_H
 
 void script_SetTimer(int tnum,int timeout);
 int  IsTimerExpired(int tnum);
 
-#endif // __AGS_EE_AC__GLOBALTIMER_H
+#endif
diff --git a/engines/ags/engine/ac/global_translation.h b/engines/ags/engine/ac/global_translation.h
index 0e6d0b1008..ab462602cd 100644
--- a/engines/ags/engine/ac/global_translation.h
+++ b/engines/ags/engine/ac/global_translation.h
@@ -20,11 +20,11 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALTRANSLATION_H
-#define __AGS_EE_AC__GLOBALTRANSLATION_H
+#ifndef AGS_ENGINE_AC_GLOBAL_TRANSLATION_H
+#define AGS_ENGINE_AC_GLOBAL_TRANSLATION_H
 
 const char *get_translation (const char *text);
 int IsTranslationAvailable ();
 int GetTranslationName (char* buffer);
 
-#endif // __AGS_EE_AC__GLOBALTRANSLATION_H
+#endif
diff --git a/engines/ags/engine/ac/global_video.h b/engines/ags/engine/ac/global_video.h
index a297fa2151..ac381da671 100644
--- a/engines/ags/engine/ac/global_video.h
+++ b/engines/ags/engine/ac/global_video.h
@@ -20,10 +20,10 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALVIDEO_H
-#define __AGS_EE_AC__GLOBALVIDEO_H
+#ifndef AGS_ENGINE_AC_GLOBAL_VIDEO_H
+#define AGS_ENGINE_AC_GLOBAL_VIDEO_H
 
 void scrPlayVideo(const char* name, int skip, int flags);
 void pause_sound_if_necessary_and_play_video(const char *name, int skip, int flags);
 
-#endif // __AGS_EE_AC__GLOBALVIDEO_H
+#endif
diff --git a/engines/ags/engine/ac/global_viewframe.h b/engines/ags/engine/ac/global_viewframe.h
index 140c09ddbd..ca0100e8ea 100644
--- a/engines/ags/engine/ac/global_viewframe.h
+++ b/engines/ags/engine/ac/global_viewframe.h
@@ -20,9 +20,9 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALVIEWFRAME_H
-#define __AGS_EE_AC__GLOBALVIEWFRAME_H
+#ifndef AGS_ENGINE_AC_GLOBAL_VIEWFRAME_H
+#define AGS_ENGINE_AC_GLOBAL_VIEWFRAME_H
 
 void SetFrameSound (int vii, int loop, int frame, int sound);
 
-#endif // __AGS_EE_AC__GLOBALVIEWFRAME_H
+#endif
diff --git a/engines/ags/engine/ac/global_viewport.h b/engines/ags/engine/ac/global_viewport.h
index d56d7efc8a..4e68532410 100644
--- a/engines/ags/engine/ac/global_viewport.h
+++ b/engines/ags/engine/ac/global_viewport.h
@@ -20,12 +20,12 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALVIEWPORT_H
-#define __AGS_EE_AC__GLOBALVIEWPORT_H
+#ifndef AGS_ENGINE_AC_GLOBAL_VIEWPORT_H
+#define AGS_ENGINE_AC_GLOBAL_VIEWPORT_H
 
 void SetViewport(int offsx,int offsy);
 void ReleaseViewport();
 int  GetViewportX ();
 int  GetViewportY ();
 
-#endif // __AGS_EE_AC__GLOBAL_VIEWPORT_H
+#endif
diff --git a/engines/ags/engine/ac/global_walkablearea.h b/engines/ags/engine/ac/global_walkablearea.h
index 4e4b7aeb2a..7ab0e11881 100644
--- a/engines/ags/engine/ac/global_walkablearea.h
+++ b/engines/ags/engine/ac/global_walkablearea.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALWALKABLEAREA_H
-#define __AGS_EE_AC__GLOBALWALKABLEAREA_H
+#ifndef AGS_ENGINE_AC_GLOBAL_WALKABLEAREA_H
+#define AGS_ENGINE_AC_GLOBAL_WALKABLEAREA_H
 
 int   GetScalingAt (int x, int y);
 void  SetAreaScaling(int area, int min, int max);
@@ -34,4 +34,4 @@ int   GetWalkableAreaAtRoom(int x, int y);
 // if area is disabled or non-existing, returns 0 (no area)
 int   GetWalkableAreaAtScreen(int x, int y);
 
-#endif // __AGS_EE_AC__GLOBALWALKABLEAREA_H
+#endif
diff --git a/engines/ags/engine/ac/global_walkbehind.h b/engines/ags/engine/ac/global_walkbehind.h
index 9c3d554cb2..0e9b1efabe 100644
--- a/engines/ags/engine/ac/global_walkbehind.h
+++ b/engines/ags/engine/ac/global_walkbehind.h
@@ -20,9 +20,9 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GLOBALWALKBEHIND_H
-#define __AGS_EE_AC__GLOBALWALKBEHIND_H
+#ifndef AGS_ENGINE_AC_GLOBAL_WALKBEHIND_H
+#define AGS_ENGINE_AC_GLOBAL_WALKBEHIND_H
 
 void SetWalkBehindBase(int wa,int bl);
 
-#endif // __AGS_EE_AC__GLOBALWALKBEHIND_H
+#endif
diff --git a/engines/ags/engine/ac/gui.h b/engines/ags/engine/ac/gui.h
index 371fc7a9c5..a80f884357 100644
--- a/engines/ags/engine/ac/gui.h
+++ b/engines/ags/engine/ac/gui.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GUI_H
-#define __AGS_EE_AC__GUI_H
+#ifndef AGS_ENGINE_AC_GUI_H
+#define AGS_ENGINE_AC_GUI_H
 
 #include "ac/dynobj/scriptgui.h"
 #include "gui/guimain.h"
@@ -90,4 +90,4 @@ extern int ifacepopped;
 extern int ifacepopped;
 extern int mouse_on_iface;
 
-#endif // __AGS_EE_AC__GUI_H
+#endif
diff --git a/engines/ags/engine/ac/guicontrol.h b/engines/ags/engine/ac/guicontrol.h
index 03b11b8dbd..fd2d0c2452 100644
--- a/engines/ags/engine/ac/guicontrol.h
+++ b/engines/ags/engine/ac/guicontrol.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__GUICONTROL_H
-#define __AGS_EE_AC__GUICONTROL_H
+#ifndef AGS_ENGINE_AC_GUICONTROL_H
+#define AGS_ENGINE_AC_GUICONTROL_H
 
 #include "gui/guiobject.h"
 #include "gui/guibutton.h"
@@ -70,4 +70,4 @@ void		GUIControl_SetSize(GUIObject *guio, int newwid, int newhit);
 void		GUIControl_SendToBack(GUIObject *guio);
 void		GUIControl_BringToFront(GUIObject *guio);
 
-#endif // __AGS_EE_AC__GUICONTROL_H
+#endif
diff --git a/engines/ags/engine/ac/hotspot.h b/engines/ags/engine/ac/hotspot.h
index 4e69030e2e..e1c7804b27 100644
--- a/engines/ags/engine/ac/hotspot.h
+++ b/engines/ags/engine/ac/hotspot.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__HOTSPOT_H
-#define __AGS_EE_AC__HOTSPOT_H
+#ifndef AGS_ENGINE_AC_HOTSPOT_H
+#define AGS_ENGINE_AC_HOTSPOT_H
 
 #include "ac/dynobj/scripthotspot.h"
 
@@ -44,4 +44,4 @@ const char* Hotspot_GetTextProperty(ScriptHotspot *hss, const char *property);
 // if hotspot is disabled or non-existing, returns 0 (no area)
 int     get_hotspot_at(int xpp,int ypp);
 
-#endif // __AGS_EE_AC__HOTSPOT_H
+#endif
diff --git a/engines/ags/engine/ac/inventoryitem.h b/engines/ags/engine/ac/inventoryitem.h
index 76733125f4..1fedcabd5a 100644
--- a/engines/ags/engine/ac/inventoryitem.h
+++ b/engines/ags/engine/ac/inventoryitem.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__INVENTORYITEM_H
-#define __AGS_EE_AC__INVENTORYITEM_H
+#ifndef AGS_ENGINE_AC_INVENTORYITEM_H
+#define AGS_ENGINE_AC_INVENTORYITEM_H
 
 #include "ac/dynobj/scriptinvitem.h"
 
@@ -42,4 +42,4 @@ const char* InventoryItem_GetTextProperty(ScriptInvItem *scii, const char *prope
 
 void set_inv_item_cursorpic(int invItemId, int piccy);
 
-#endif // __AGS_EE_AC__INVENTORYITEM_H
+#endif
diff --git a/engines/ags/engine/ac/invwindow.h b/engines/ags/engine/ac/invwindow.h
index 72802c2572..fe1e9a8105 100644
--- a/engines/ags/engine/ac/invwindow.h
+++ b/engines/ags/engine/ac/invwindow.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__INVWINDOW_H
-#define __AGS_EE_AC__INVWINDOW_H
+#ifndef AGS_ENGINE_AC_INVWINDOW_H
+#define AGS_ENGINE_AC_INVWINDOW_H
 
 #include "ac/characterinfo.h"
 #include "ac/dynobj/scriptinvitem.h"
@@ -50,4 +50,4 @@ int				offset_over_inv(GUIInvWindow *inv);
 // NOTE: This function is valid for AGS 2.72 and lower
 int             invscreen();
 
-#endif // __AGS_EE_AC__INVWINDOW_H
+#endif
diff --git a/engines/ags/engine/ac/keycode.h b/engines/ags/engine/ac/keycode.h
index 6269dafca3..292274b60e 100644
--- a/engines/ags/engine/ac/keycode.h
+++ b/engines/ags/engine/ac/keycode.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__KEYCODE_H
-#define __AGS_EE_AC__KEYCODE_H
+#ifndef AGS_ENGINE_AC_KEYCODE_H
+#define AGS_ENGINE_AC_KEYCODE_H
 
 #include "core/platform.h"
 
@@ -177,4 +177,4 @@ int GetKeyForKeyPressCb(int keycode);
 // Returns -1 if not found.
 int PlatformKeyFromAgsKey(int key);
 
-#endif // __AGS_EE_AC__KEYCODE_H
+#endif
diff --git a/engines/ags/engine/ac/label.h b/engines/ags/engine/ac/label.h
index 26464eefcf..8aa5976cd5 100644
--- a/engines/ags/engine/ac/label.h
+++ b/engines/ags/engine/ac/label.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__LABEL_H
-#define __AGS_EE_AC__LABEL_H
+#ifndef AGS_ENGINE_AC_LABEL_H
+#define AGS_ENGINE_AC_LABEL_H
 
 #include "gui/guilabel.h"
 
@@ -35,4 +35,4 @@ void		Label_SetColor(GUILabel *labl, int colr);
 int			Label_GetFont(GUILabel *labl);
 void		Label_SetFont(GUILabel *guil, int fontnum);
 
-#endif // __AGS_EE_AC__LABEL_H
+#endif
diff --git a/engines/ags/engine/ac/lipsync.h b/engines/ags/engine/ac/lipsync.h
index 2301ef2d38..694d02489f 100644
--- a/engines/ags/engine/ac/lipsync.h
+++ b/engines/ags/engine/ac/lipsync.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_LIPSYNC_H
-#define __AC_LIPSYNC_H
+#ifndef AGS_ENGINE_AC_LIPSYNC_H
+#define AGS_ENGINE_AC_LIPSYNC_H
 
 struct SpeechLipSyncLine {
     char  filename[14];
@@ -30,4 +30,4 @@ struct SpeechLipSyncLine {
     short numPhonemes;
 };
 
-#endif // __AC_LIPSYNC_H
+#endif
diff --git a/engines/ags/engine/ac/listbox.h b/engines/ags/engine/ac/listbox.h
index eb6c5d06ab..2b0c07af26 100644
--- a/engines/ags/engine/ac/listbox.h
+++ b/engines/ags/engine/ac/listbox.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__LISTBOX_H
-#define __AGS_EE_AC__LISTBOX_H
+#ifndef AGS_ENGINE_AC_LISTBOX_H
+#define AGS_ENGINE_AC_LISTBOX_H
 
 #include "gui/guilistbox.h"
 
@@ -55,4 +55,4 @@ void		ListBox_ScrollUp(GUIListBox *listbox);
 
 GUIListBox* is_valid_listbox (int guin, int objn);
 
-#endif // __AGS_EE_AC__LISTBOX_H
+#endif
diff --git a/engines/ags/engine/ac/math.h b/engines/ags/engine/ac/math.h
index ce047992de..8dd7d8f55e 100644
--- a/engines/ags/engine/ac/math.h
+++ b/engines/ags/engine/ac/math.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__MATH_H
-#define __AGS_EE_AC__MATH_H
+#ifndef AGS_ENGINE_AC_MATH_H
+#define AGS_ENGINE_AC_MATH_H
 
 #include "core/types.h"
 
@@ -57,4 +57,4 @@ float Math_Sqrt(float value);
 int __Rand(int upto);
 #define Random __Rand
 
-#endif // __AGS_EE_AC__MATH_H
+#endif
diff --git a/engines/ags/engine/ac/mouse.h b/engines/ags/engine/ac/mouse.h
index f49e2e9f79..a38abde706 100644
--- a/engines/ags/engine/ac/mouse.h
+++ b/engines/ags/engine/ac/mouse.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__MOUSE_H
-#define __AGS_EE_AC__MOUSE_H
+#ifndef AGS_ENGINE_AC_MOUSE_H
+#define AGS_ENGINE_AC_MOUSE_H
 
 #include "ac/dynobj/scriptmouse.h"
 
@@ -78,4 +78,4 @@ extern ScriptMouse scmouse;
 extern int cur_mode;
 extern int cur_cursor;
 
-#endif // __AGS_EE_AC__MOUSE_H
+#endif
diff --git a/engines/ags/engine/ac/movelist.h b/engines/ags/engine/ac/movelist.h
index cff9328138..ce47eb45cb 100644
--- a/engines/ags/engine/ac/movelist.h
+++ b/engines/ags/engine/ac/movelist.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_MOVE_H
-#define __AC_MOVE_H
+#ifndef AGS_ENGINE_AC_MOVE_H
+#define AGS_ENGINE_AC_MOVE_H
 
 #include "util/wgt2allg.h" // fixed type
 #include "game/savegame.h"
@@ -48,4 +48,4 @@ struct MoveList {
     void WriteToFile(Common::Stream *out);
 };
 
-#endif // __AC_MOVE_H
+#endif
diff --git a/engines/ags/engine/ac/object.h b/engines/ags/engine/ac/object.h
index 5679ec5d9e..0d7262a78a 100644
--- a/engines/ags/engine/ac/object.h
+++ b/engines/ags/engine/ac/object.h
@@ -28,8 +28,8 @@
 // rename this to RoomObject one day?
 //=============================================================================
 
-#ifndef __AGS_EE_AC__OBJECT_H
-#define __AGS_EE_AC__OBJECT_H
+#ifndef AGS_ENGINE_AC_OBJECT_H
+#define AGS_ENGINE_AC_OBJECT_H
 
 #include "ac/common_defines.h"
 #include "ac/dynobj/scriptobject.h"
@@ -96,5 +96,4 @@ int     is_pos_in_sprite(int xx,int yy,int arx,int ary, Common::Bitmap *sprit, i
 // X and Y are ROOM coordinates
 int     check_click_on_object(int roomx, int roomy, int mood);
 
-#endif // __AGS_EE_AC__OBJECT_H
-
+#endif
diff --git a/engines/ags/engine/ac/objectcache.h b/engines/ags/engine/ac/objectcache.h
index cff0fcb8f6..916b47c462 100644
--- a/engines/ags/engine/ac/objectcache.h
+++ b/engines/ags/engine/ac/objectcache.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__OBJECTCACHE_H
-#define __AGS_EE_AC__OBJECTCACHE_H
+#ifndef AGS_ENGINE_AC_OBJECTCACHE_H
+#define AGS_ENGINE_AC_OBJECTCACHE_H
 
 // stores cached object info
 struct ObjectCache {
@@ -33,4 +33,4 @@ struct ObjectCache {
     int   xwas, ywas;
 };
 
-#endif // __AGS_EE_AC__OBJECTCACHE_H
+#endif
diff --git a/engines/ags/engine/ac/overlay.h b/engines/ags/engine/ac/overlay.h
index ed315510e6..96f5b38875 100644
--- a/engines/ags/engine/ac/overlay.h
+++ b/engines/ags/engine/ac/overlay.h
@@ -20,8 +20,9 @@
  *
  */
 
-#ifndef __AGS_EE_AC__OVERLAY_H
-#define __AGS_EE_AC__OVERLAY_H
+#ifndef AGS_ENGINE_AC_OVERLAY_H
+#define AGS_ENGINE_AC_OVERLAY_H
+
 #include <vector>
 #include "ac/screenoverlay.h"
 #include "ac/dynobj/scriptoverlay.h"
@@ -53,4 +54,4 @@ extern int is_text_overlay; // blocking text overlay on screen
 
 extern std::vector<ScreenOverlay> screenover;
 
-#endif // __AGS_EE_AC__OVERLAY_H
+#endif
diff --git a/engines/ags/engine/ac/parser.h b/engines/ags/engine/ac/parser.h
index e13edaf89a..6da49934ab 100644
--- a/engines/ags/engine/ac/parser.h
+++ b/engines/ags/engine/ac/parser.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__PARSER_H
-#define __AGS_EE_AC__PARSER_H
+#ifndef AGS_ENGINE_AC_PARSER_H
+#define AGS_ENGINE_AC_PARSER_H
 
 int Parser_FindWordID(const char *wordToFind);
 const char* Parser_SaidUnknownWord();
@@ -35,4 +35,4 @@ int is_valid_word_char(char theChar);
 int FindMatchingMultiWordWord(char *thisword, const char **text);
 int parse_sentence (const char *src_text, int *numwords, short*wordarray, short*compareto, int comparetonum);
 
-#endif // __AGS_EE_AC__PARSER_H
+#endif
diff --git a/engines/ags/engine/ac/path_helper.h b/engines/ags/engine/ac/path_helper.h
index 9efb1190d3..a5cd9d89da 100644
--- a/engines/ags/engine/ac/path_helper.h
+++ b/engines/ags/engine/ac/path_helper.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_AC__PATHHELPER_H
-#define __AGS_EE_AC__PATHHELPER_H
+#ifndef AGS_ENGINE_AC_PATHHELPER_H
+#define AGS_ENGINE_AC_PATHHELPER_H
 
 #include "util/string.h"
 
@@ -83,4 +83,4 @@ String  get_audio_install_dir();
 String  get_voice_install_dir();
 void    get_install_dir_path(char* buffer, const char *fileName);
 
-#endif // __AGS_EE_AC__PATHHELPER_H
+#endif
diff --git a/engines/ags/engine/ac/properties.h b/engines/ags/engine/ac/properties.h
index 428265777a..f0d233a8c8 100644
--- a/engines/ags/engine/ac/properties.h
+++ b/engines/ags/engine/ac/properties.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__PROPERTIES_H
-#define __AGS_EE_AC__PROPERTIES_H
+#ifndef AGS_ENGINE_AC_PROPERTIES_H
+#define AGS_ENGINE_AC_PROPERTIES_H
 
 #include "game/customproperties.h"
 
@@ -39,4 +39,4 @@ const char* get_text_property_dynamic_string(const StringIMap &st_prop, const St
 bool set_int_property(StringIMap &rt_prop, const char *property, int value);
 bool set_text_property(StringIMap &rt_prop, const char *property, const char* value);
 
-#endif // __AGS_EE_AC__PROPERTIES_H
+#endif
diff --git a/engines/ags/engine/ac/region.h b/engines/ags/engine/ac/region.h
index f12636f465..9deb80b133 100644
--- a/engines/ags/engine/ac/region.h
+++ b/engines/ags/engine/ac/region.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__REGION_H
-#define __AGS_EE_AC__REGION_H
+#ifndef AGS_ENGINE_AC_REGION_H
+#define AGS_ENGINE_AC_REGION_H
 
 #include "ac/dynobj/scriptregion.h"
 
@@ -42,4 +42,4 @@ void	Region_RunInteraction(ScriptRegion *ssr, int mood);
 
 void    generate_light_table();
 
-#endif // __AGS_EE_AC__REGION_H
+#endif
diff --git a/engines/ags/engine/ac/richgamemedia.h b/engines/ags/engine/ac/richgamemedia.h
index c0570e89f0..28acaf2cbb 100644
--- a/engines/ags/engine/ac/richgamemedia.h
+++ b/engines/ags/engine/ac/richgamemedia.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__RICHGAMEMEDIA_H
-#define __AGS_EE_AC__RICHGAMEMEDIA_H
+#ifndef AGS_ENGINE_AC_RICHGAMEMEDIA_H
+#define AGS_ENGINE_AC_RICHGAMEMEDIA_H
 
 // Windows Vista Rich Save Games, modified to be platform-agnostic
 
@@ -53,4 +53,4 @@ typedef struct _RICH_GAME_MEDIA_HEADER
 } RICH_GAME_MEDIA_HEADER;
 #pragma pack(pop)
 
-#endif // __AGS_EE_AC__RICHGAMEMEDIA_H
+#endif
diff --git a/engines/ags/engine/ac/room.h b/engines/ags/engine/ac/room.h
index d091369a74..e34e1f9506 100644
--- a/engines/ags/engine/ac/room.h
+++ b/engines/ags/engine/ac/room.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__ROOM_H
-#define __AGS_EE_AC__ROOM_H
+#ifndef AGS_ENGINE_AC_ROOM_H
+#define AGS_ENGINE_AC_ROOM_H
 
 #include "ac/dynobj/scriptdrawingsurface.h"
 #include "ac/characterinfo.h"
@@ -76,4 +76,4 @@ void convert_move_path_to_room_resolution(MoveList *ml);
 
 extern AGS::Common::RoomStruct thisroom;
 
-#endif // __AGS_EE_AC__ROOM_H
+#endif
diff --git a/engines/ags/engine/ac/roomobject.h b/engines/ags/engine/ac/roomobject.h
index 3fb6148073..af648ba35f 100644
--- a/engines/ags/engine/ac/roomobject.h
+++ b/engines/ags/engine/ac/roomobject.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__ROOMOBJECT_H
-#define __AGS_EE_AC__ROOMOBJECT_H
+#ifndef AGS_ENGINE_AC_ROOMOBJECT_H
+#define AGS_ENGINE_AC_ROOMOBJECT_H
 
 #include "ac/common_defines.h"
 
@@ -64,4 +64,4 @@ struct RoomObject {
     void WriteToFile(Common::Stream *out) const;
 };
 
-#endif // __AGS_EE_AC__ROOMOBJECT_H
+#endif
diff --git a/engines/ags/engine/ac/roomstatus.h b/engines/ags/engine/ac/roomstatus.h
index 6e6dad69bd..a570368151 100644
--- a/engines/ags/engine/ac/roomstatus.h
+++ b/engines/ags/engine/ac/roomstatus.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__ROOMSTATUS_H
-#define __AGS_EE_AC__ROOMSTATUS_H
+#ifndef AGS_ENGINE_AC_ROOMSTATUS_H
+#define AGS_ENGINE_AC_ROOMSTATUS_H
 
 #include "ac/roomobject.h"
 #include "game/roomstruct.h"
@@ -82,4 +82,4 @@ RoomStatus* getRoomStatus(int room);
 bool isRoomStatusValid(int room);
 void resetRoomStatuses();
 
-#endif // __AGS_EE_AC__ROOMSTATUS_H
+#endif
diff --git a/engines/ags/engine/ac/route_finder.h b/engines/ags/engine/ac/route_finder.h
index 60a7748e27..35dc05fc24 100644
--- a/engines/ags/engine/ac/route_finder.h
+++ b/engines/ags/engine/ac/route_finder.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_ROUTEFND_H
-#define __AC_ROUTEFND_H
+#ifndef AGS_ENGINE_AC_ROUTEFND_H
+#define AGS_ENGINE_AC_ROUTEFND_H
 
 #include "ac/game_version.h"
 
@@ -42,4 +42,4 @@ void set_route_move_speed(int speed_x, int speed_y);
 int find_route(short srcx, short srcy, short xx, short yy, AGS::Common::Bitmap *onscreen, int movlst, int nocross = 0, int ignore_walls = 0);
 void calculate_move_stage(MoveList * mlsp, int aaa);
 
-#endif // __AC_ROUTEFND_H
+#endif
diff --git a/engines/ags/engine/ac/route_finder_impl.h b/engines/ags/engine/ac/route_finder_impl.h
index 9c71d4606a..147733899d 100644
--- a/engines/ags/engine/ac/route_finder_impl.h
+++ b/engines/ags/engine/ac/route_finder_impl.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_ROUTE_FINDER_IMPL
-#define __AC_ROUTE_FINDER_IMPL
+#ifndef AGS_ENGINE_AC_ROUTE_FINDER_IMPL
+#define AGS_ENGINE_AC_ROUTE_FINDER_IMPL
 
 #include "ac/game_version.h"
 
@@ -50,4 +50,4 @@ void calculate_move_stage(MoveList * mlsp, int aaa);
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AC_ROUTE_FINDER_IMPL
+#endif
diff --git a/engines/ags/engine/ac/route_finder_impl_legacy.h b/engines/ags/engine/ac/route_finder_impl_legacy.h
index e87ad59066..26e9f69730 100644
--- a/engines/ags/engine/ac/route_finder_impl_legacy.h
+++ b/engines/ags/engine/ac/route_finder_impl_legacy.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_ROUTE_FINDER_IMPL_LEGACY
-#define __AC_ROUTE_FINDER_IMPL_LEGACY
+#ifndef AGS_ENGINE_AC_ROUTE_FINDER_IMPL_LEGACY
+#define AGS_ENGINE_AC_ROUTE_FINDER_IMPL_LEGACY
 
 // Forward declaration
 namespace AGS { namespace Common { class Bitmap; }}
@@ -48,4 +48,4 @@ void calculate_move_stage(MoveList * mlsp, int aaa);
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AC_ROUTE_FINDER_IMPL_LEGACY
+#endif
diff --git a/engines/ags/engine/ac/runtime_defines.h b/engines/ags/engine/ac/runtime_defines.h
index 95c43b85a0..b48320eb30 100644
--- a/engines/ags/engine/ac/runtime_defines.h
+++ b/engines/ags/engine/ac/runtime_defines.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_RUNTIMEDEFINES_H
-#define __AC_RUNTIMEDEFINES_H
+#ifndef AGS_ENGINE_AC_RUNTIMEDEFINES_H
+#define AGS_ENGINE_AC_RUNTIMEDEFINES_H
 
 // xalleg.h pulls in an Allegro-internal definition of MAX_TIMERS which
 // conflicts with the definition in runtime_defines.h. Forget it.
@@ -158,4 +158,4 @@ const int LegacyRoomVolumeFactor            = 30;
 
 #include "ac/common_defines.h"
 
-#endif // __AC_RUNTIMEDEFINES_H
+#endif
diff --git a/engines/ags/engine/ac/screen.h b/engines/ags/engine/ac/screen.h
index d0898bc73a..a89012f50e 100644
--- a/engines/ags/engine/ac/screen.h
+++ b/engines/ags/engine/ac/screen.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__SCREEN_H
-#define __AGS_EE_AC__SCREEN_H
+#ifndef AGS_ENGINE_AC_SCREEN_H
+#define AGS_ENGINE_AC_SCREEN_H
 
 namespace AGS { namespace Common { class Bitmap; } }
 namespace AGS { namespace Engine { class IDriverDependantBitmap; } }
@@ -33,4 +33,4 @@ AGS::Engine::IDriverDependantBitmap* prepare_screen_for_transition_in();
 // Screenshot made in the last room, used during some of the transition effects
 extern AGS::Common::Bitmap *saved_viewport_bitmap;
 
-#endif // __AGS_EE_AC__SCREEN_H
+#endif
diff --git a/engines/ags/engine/ac/screenoverlay.h b/engines/ags/engine/ac/screenoverlay.h
index 18657baf21..3f772edb49 100644
--- a/engines/ags/engine/ac/screenoverlay.h
+++ b/engines/ags/engine/ac/screenoverlay.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__SCREENOVERLAY_H
-#define __AGS_EE_AC__SCREENOVERLAY_H
+#ifndef AGS_ENGINE_AC_SCREENOVERLAY_H
+#define AGS_ENGINE_AC_SCREENOVERLAY_H
 
 #include <stdint.h>
 
@@ -46,4 +46,4 @@ struct ScreenOverlay {
     void WriteToFile(Common::Stream *out) const;
 };
 
-#endif // __AGS_EE_AC__SCREENOVERLAY_H
+#endif
diff --git a/engines/ags/engine/ac/slider.h b/engines/ags/engine/ac/slider.h
index e0e87e497f..3ce4329cc2 100644
--- a/engines/ags/engine/ac/slider.h
+++ b/engines/ags/engine/ac/slider.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__SLIDER_H
-#define __AGS_EE_AC__SLIDER_H
+#ifndef AGS_ENGINE_AC_SLIDER_H
+#define AGS_ENGINE_AC_SLIDER_H
 
 #include "gui/guislider.h"
 
@@ -40,4 +40,4 @@ void	Slider_SetHandleGraphic(GUISlider *guisl, int newImage);
 int		Slider_GetHandleOffset(GUISlider *guisl);
 void	Slider_SetHandleOffset(GUISlider *guisl, int newOffset);
 
-#endif // __AGS_EE_AC__SLIDER_H
+#endif
diff --git a/engines/ags/engine/ac/speech.h b/engines/ags/engine/ac/speech.h
index 11dfe68961..58179f8327 100644
--- a/engines/ags/engine/ac/speech.h
+++ b/engines/ags/engine/ac/speech.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__SPEECH_H
-#define __AGS_EE_AC__SPEECH_H
+#ifndef AGS_ENGINE_AC_SPEECH_H
+#define AGS_ENGINE_AC_SPEECH_H
 
 enum SkipSpeechStyle
 {
@@ -41,4 +41,4 @@ enum SkipSpeechStyle
 int user_to_internal_skip_speech(SkipSpeechStyle userval);
 SkipSpeechStyle internal_skip_speech_to_user(int internal_val);
 
-#endif // __AGS_EE_AC__SPEECH_H
+#endif
diff --git a/engines/ags/engine/ac/sprite.h b/engines/ags/engine/ac/sprite.h
index e2ba8cdc90..d97d00f74a 100644
--- a/engines/ags/engine/ac/sprite.h
+++ b/engines/ags/engine/ac/sprite.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__SPRITE_H
-#define __AGS_EE_AC__SPRITE_H
+#ifndef AGS_ENGINE_AC_SPRITE_H
+#define AGS_ENGINE_AC_SPRITE_H
 
 void get_new_size_for_sprite (int ee, int ww, int hh, int &newwid, int &newhit);
 // set any alpha-transparent pixels in the image to the appropriate
@@ -32,4 +32,4 @@ Common::Bitmap *remove_alpha_channel(Common::Bitmap *from);
 void pre_save_sprite(int ee);
 void initialize_sprite (int ee);
 
-#endif // __AGS_EE_AC__SPRITE_H
+#endif
diff --git a/engines/ags/engine/ac/spritelistentry.h b/engines/ags/engine/ac/spritelistentry.h
index aa0be21f2e..aa45aad77c 100644
--- a/engines/ags/engine/ac/spritelistentry.h
+++ b/engines/ags/engine/ac/spritelistentry.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__SPRITELISTENTRY_H
-#define __AGS_EE_AC__SPRITELISTENTRY_H
+#ifndef AGS_ENGINE_AC_SPRITELISTENTRY_H
+#define AGS_ENGINE_AC_SPRITELISTENTRY_H
 
 #include "gfx/ddb.h"
 
@@ -38,4 +38,4 @@ struct SpriteListEntry
     SpriteListEntry();
 };
 
-#endif // __AGS_EE_AC__SPRITELISTENTRY_H
+#endif
diff --git a/engines/ags/engine/ac/statobj/agsstaticobject.h b/engines/ags/engine/ac/statobj/agsstaticobject.h
index efccc6c2c0..49e00f0653 100644
--- a/engines/ags/engine/ac/statobj/agsstaticobject.h
+++ b/engines/ags/engine/ac/statobj/agsstaticobject.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_STATOBJ__AGSSTATICOBJECT_H
-#define __AGS_EE_STATOBJ__AGSSTATICOBJECT_H
+#ifndef _AGS_ENGINE_AC_STATICOBJ_AGSSTATICOBJECT_H
+#define _AGS_ENGINE_AC_STATICOBJ_AGSSTATICOBJECT_H
 
 #include "ac/statobj/staticobject.h"
 
@@ -50,4 +50,4 @@ struct StaticGame : public AGSStaticObject {
 extern AGSStaticObject GlobalStaticManager;
 extern StaticGame      GameStaticManager;
 
-#endif // __AGS_EE_STATOBJ__AGSSTATICOBJECT_H
+#endif
diff --git a/engines/ags/engine/ac/statobj/staticarray.h b/engines/ags/engine/ac/statobj/staticarray.h
index a4cf70e711..950894a721 100644
--- a/engines/ags/engine/ac/statobj/staticarray.h
+++ b/engines/ags/engine/ac/statobj/staticarray.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_STATOBJ__STATICARRAY_H
-#define __AGS_EE_STATOBJ__STATICARRAY_H
+#ifndef _AGS_ENGINE_AC_STATICOBJ_STATICARRAY_H
+#define _AGS_ENGINE_AC_STATICOBJ_STATICARRAY_H
 
 #include "ac/statobj/staticobject.h"
 
@@ -66,4 +66,4 @@ private:
     int                 _elemCount;
 };
 
-#endif // __AGS_EE_STATOBJ__STATICOBJECT_H
+#endif
diff --git a/engines/ags/engine/ac/statobj/staticobject.h b/engines/ags/engine/ac/statobj/staticobject.h
index e9fdabde4f..3580f0c678 100644
--- a/engines/ags/engine/ac/statobj/staticobject.h
+++ b/engines/ags/engine/ac/statobj/staticobject.h
@@ -28,8 +28,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_STATOBJ__STATICOBJECT_H
-#define __AGS_EE_STATOBJ__STATICOBJECT_H
+#ifndef AGS_ENGINE_AC_STATICOBJ_STATICOBJECT_H
+#define AGS_ENGINE_AC_STATICOBJ_STATICOBJECT_H
 
 #include "core/types.h"
 
@@ -50,4 +50,4 @@ struct ICCStaticObject {
     virtual void    WriteFloat(const char *address, intptr_t offset, float val)     = 0;
 };
 
-#endif // __AGS_EE_STATOBJ__STATICOBJECT_H
+#endif
diff --git a/engines/ags/engine/ac/string.h b/engines/ags/engine/ac/string.h
index a045e93777..3a2865e637 100644
--- a/engines/ags/engine/ac/string.h
+++ b/engines/ags/engine/ac/string.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__STRING_H
-#define __AGS_EE_AC__STRING_H
+#ifndef AGS_ENGINE_AC_STRING_H
+#define AGS_ENGINE_AC_STRING_H
 
 #include <stdarg.h>
 #include "ac/dynobj/cc_dynamicobject.h"
@@ -58,4 +58,4 @@ size_t break_up_text_into_lines(const char *todis, SplitLines &lines, int wii, i
 void check_strlen(char*ptt);
 void my_strncpy(char *dest, const char *src, int len);
 
-#endif // __AGS_EE_AC__STRING_H
+#endif
diff --git a/engines/ags/engine/ac/sys_events.h b/engines/ags/engine/ac/sys_events.h
index 001ef11bed..42e34f9c86 100644
--- a/engines/ags/engine/ac/sys_events.h
+++ b/engines/ags/engine/ac/sys_events.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__SYS_EVENTS_H
-#define __AGS_EE_AC__SYS_EVENTS_H
+#ifndef AGS_ENGINE_AC_SYS_EVENTS_H
+#define AGS_ENGINE_AC_SYS_EVENTS_H
 
 int  ags_getch ();
 int  ags_kbhit ();
@@ -38,4 +38,4 @@ void ags_clear_input_buffer();
 // TODO: seriously not a good design, replace with event listening
 void ags_wait_until_keypress();
 
-#endif // __AGS_EE_AC__SYS_EVENTS_H
+#endif
diff --git a/engines/ags/engine/ac/system.h b/engines/ags/engine/ac/system.h
index ff096eb487..ba372a3797 100644
--- a/engines/ags/engine/ac/system.h
+++ b/engines/ags/engine/ac/system.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__SYSTEMAUDIO_H
-#define __AGS_EE_AC__SYSTEMAUDIO_H
+#ifndef AGS_ENGINE_AC_SYSTEMAUDIO_H
+#define AGS_ENGINE_AC_SYSTEMAUDIO_H
 
 #include "ac/dynobj/scriptaudiochannel.h"
 
@@ -50,4 +50,4 @@ void    System_SetVolume(int newvol);
 const char *System_GetRuntimeInfo();
 
 
-#endif // __AGS_EE_AC_SYSTEMAUDIO_H
+#endif
diff --git a/engines/ags/engine/ac/textbox.h b/engines/ags/engine/ac/textbox.h
index 844f87b7d6..2f671e9988 100644
--- a/engines/ags/engine/ac/textbox.h
+++ b/engines/ags/engine/ac/textbox.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__TEXTBOX_H
-#define __AGS_EE_AC__TEXTBOX_H
+#ifndef AGS_ENGINE_AC_TEXTBOX_H
+#define AGS_ENGINE_AC_TEXTBOX_H
 
 #include "gui/guitextbox.h"
 
@@ -35,4 +35,4 @@ void		TextBox_SetTextColor(GUITextBox *guit, int colr);
 int			TextBox_GetFont(GUITextBox *guit);
 void		TextBox_SetFont(GUITextBox *guit, int fontnum);
 
-#endif // __AGS_EE_AC__TEXTBOX_H
+#endif
diff --git a/engines/ags/engine/ac/timer.h b/engines/ags/engine/ac/timer.h
index 44460d051b..f6f1f0947b 100644
--- a/engines/ags/engine/ac/timer.h
+++ b/engines/ags/engine/ac/timer.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__TIMER_H
-#define __AGS_EE_AC__TIMER_H
+#ifndef AGS_ENGINE_AC_TIMER_H
+#define AGS_ENGINE_AC_TIMER_H
 
 #include <type_traits>
 #include <chrono>
@@ -42,4 +42,4 @@ extern bool isTimerFpsMaxed();
 extern bool waitingForNextTick();  // store last tick time.
 extern void skipMissedTicks();  // if more than N frames, just skip all, start a fresh.
 
-#endif // __AGS_EE_AC__TIMER_H
+#endif
diff --git a/engines/ags/engine/ac/topbarsettings.h b/engines/ags/engine/ac/topbarsettings.h
index cf815fb7cd..5a23efb1f8 100644
--- a/engines/ags/engine/ac/topbarsettings.h
+++ b/engines/ags/engine/ac/topbarsettings.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__TOPBARSETTINGS_H
-#define __AGS_EE_AC__TOPBARSETTINGS_H
+#ifndef AGS_ENGINE_AC_TOPBARSETTINGS_H
+#define AGS_ENGINE_AC_TOPBARSETTINGS_H
 
 struct TopBarSettings {
     int wantIt;
@@ -37,4 +37,4 @@ struct TopBarSettings {
     }
 };
 
-#endif // __AGS_EE_AC__TOPBARSETTINGS_H
+#endif
diff --git a/engines/ags/engine/ac/translation.h b/engines/ags/engine/ac/translation.h
index 2f65f56df8..a7692089c3 100644
--- a/engines/ags/engine/ac/translation.h
+++ b/engines/ags/engine/ac/translation.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__TRANSLATION_H
-#define __AGS_EE_AC__TRANSLATION_H
+#ifndef AGS_ENGINE_AC_TRANSLATION_H
+#define AGS_ENGINE_AC_TRANSLATION_H
 
 #include "util/string.h"
 
@@ -30,4 +30,4 @@ using AGS::Common::String;
 void close_translation ();
 bool init_translation (const String &lang, const String &fallback_lang, bool quit_on_error);
 
-#endif // __AGS_EE_AC__TRANSLATION_H
+#endif
diff --git a/engines/ags/engine/ac/tree_map.h b/engines/ags/engine/ac/tree_map.h
index 7e907fb06f..6c181f8e2c 100644
--- a/engines/ags/engine/ac/tree_map.h
+++ b/engines/ags/engine/ac/tree_map.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__TREEMAP_H
-#define __AGS_EE_AC__TREEMAP_H
+#ifndef AGS_ENGINE_AC_TREEMAP_H
+#define AGS_ENGINE_AC_TREEMAP_H
 
 // Binary tree structure for holding translations, allows fast
 // access
@@ -37,4 +37,4 @@ struct TreeMap {
     ~TreeMap();
 };
 
-#endif // __AGS_EE_AC__TREEMAP_H
+#endif
diff --git a/engines/ags/engine/ac/viewframe.h b/engines/ags/engine/ac/viewframe.h
index d195b4fcdc..6b5e3b8388 100644
--- a/engines/ags/engine/ac/viewframe.h
+++ b/engines/ags/engine/ac/viewframe.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__VIEWFRAME_H
-#define __AGS_EE_AC__VIEWFRAME_H
+#ifndef AGS_ENGINE_AC_VIEWFRAME_H
+#define AGS_ENGINE_AC_VIEWFRAME_H
 
 #include "ac/runtime_defines.h"
 #include "ac/view.h"
@@ -49,4 +49,4 @@ void CheckViewFrame (int view, int loop, int frame, int sound_volume=SCR_NO_VALU
 // draws a view frame, flipped if appropriate
 void DrawViewFrame(Common::Bitmap *ds, const ViewFrame *vframe, int x, int y, bool alpha_blend = false);
 
-#endif // __AGS_EE_AC__VIEWFRAME_H
+#endif
diff --git a/engines/ags/engine/ac/walkablearea.h b/engines/ags/engine/ac/walkablearea.h
index 8d024b948f..b5694934bb 100644
--- a/engines/ags/engine/ac/walkablearea.h
+++ b/engines/ags/engine/ac/walkablearea.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__WALKABLEAREA_H
-#define __AGS_EE_AC__WALKABLEAREA_H
+#ifndef AGS_ENGINE_AC_WALKABLEAREA_H
+#define AGS_ENGINE_AC_WALKABLEAREA_H
 
 void  redo_walkable_areas();
 int   get_walkable_area_pixel(int x, int y);
@@ -33,4 +33,4 @@ Common::Bitmap *prepare_walkable_areas (int sourceChar);
 int   get_walkable_area_at_location(int xx, int yy);
 int   get_walkable_area_at_character (int charnum);
 
-#endif // __AGS_EE_AC__WALKABLEAREA_H
+#endif
diff --git a/engines/ags/engine/ac/walkbehind.h b/engines/ags/engine/ac/walkbehind.h
index 458081f76b..a2210ede87 100644
--- a/engines/ags/engine/ac/walkbehind.h
+++ b/engines/ags/engine/ac/walkbehind.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_AC__WALKBEHIND_H
-#define __AGS_EE_AC__WALKBEHIND_H
+#ifndef AGS_ENGINE_AC_WALKBEHIND_H
+#define AGS_ENGINE_AC_WALKBEHIND_H
 
 enum WalkBehindMethodEnum
 {
@@ -33,4 +33,4 @@ enum WalkBehindMethodEnum
 void update_walk_behind_images();
 void recache_walk_behinds ();
 
-#endif // __AGS_EE_AC__WALKBEHIND_H
+#endif
diff --git a/engines/ags/engine/debugging/agseditordebugger.h b/engines/ags/engine/debugging/agseditordebugger.h
index b94fd496f7..fdee2419e9 100644
--- a/engines/ags/engine/debugging/agseditordebugger.h
+++ b/engines/ags/engine/debugging/agseditordebugger.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_DEBUG__AGSEDITORDEBUGGER_H
-#define __AGS_EE_DEBUG__AGSEDITORDEBUGGER_H
+#ifndef AGS_ENGINE_DEBUGGING_AGSEDITORDEBUGGER_H
+#define AGS_ENGINE_DEBUGGING_AGSEDITORDEBUGGER_H
 
 struct IAGSEditorDebugger
 {
@@ -36,4 +36,4 @@ public:
     virtual char* GetNextMessage() = 0;
 };
 
-#endif // __AGS_EE_DEBUG__AGSEDITORDEBUGGER_H
+#endif
diff --git a/engines/ags/engine/debugging/consoleoutputtarget.h b/engines/ags/engine/debugging/consoleoutputtarget.h
index c3913772d2..d6cab71dce 100644
--- a/engines/ags/engine/debugging/consoleoutputtarget.h
+++ b/engines/ags/engine/debugging/consoleoutputtarget.h
@@ -27,8 +27,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_DEBUG__CONSOLEOUTPUTTARGET_H
-#define __AGS_EE_DEBUG__CONSOLEOUTPUTTARGET_H
+#ifndef AGS_ENGINE_DEBUGGING_CONSOLEOUTPUTTARGET_H
+#define AGS_ENGINE_DEBUGGING_CONSOLEOUTPUTTARGET_H
 
 #include "debug/outputhandler.h"
 
@@ -52,4 +52,4 @@ public:
 }   // namespace Engine
 }   // namespace AGS
 
-#endif // __AGS_EE_DEBUG__CONSOLEOUTPUTTARGET_H
+#endif
diff --git a/engines/ags/engine/debugging/debug_log.h b/engines/ags/engine/debugging/debug_log.h
index afd62a973a..f5b677da84 100644
--- a/engines/ags/engine/debugging/debug_log.h
+++ b/engines/ags/engine/debugging/debug_log.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_DEBUG_LOG_H
-#define __AC_DEBUG_LOG_H
+#ifndef AGS_ENGINE_DEBUGGING_LOG_H
+#define AGS_ENGINE_DEBUGGING_LOG_H
 
 #include "script/cc_instance.h"
 #include "ac/runtime_defines.h"
@@ -53,4 +53,4 @@ extern int first_debug_line, last_debug_line, display_console;
 
 extern AGSPlatformDriver *platform;
 
-#endif // __AC_DEBUG_LOG_H
+#endif
diff --git a/engines/ags/engine/debugging/debugger.h b/engines/ags/engine/debugging/debugger.h
index 9d57120cc7..5f8cb21a0e 100644
--- a/engines/ags/engine/debugging/debugger.h
+++ b/engines/ags/engine/debugging/debugger.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_DEBUGGER_H
-#define __AC_DEBUGGER_H
+#ifndef AGS_ENGINE_DEBUGGING_DEBUGGER_H
+#define AGS_ENGINE_DEBUGGING_DEBUGGER_H
 
 #include "util/string.h"
 
@@ -65,4 +65,4 @@ extern float fps;
 extern FPSDisplayMode display_fps;
 extern int debug_flags;
 
-#endif // __AC_DEBUGGER_H
+#endif
diff --git a/engines/ags/engine/debugging/dummyagsdebugger.h b/engines/ags/engine/debugging/dummyagsdebugger.h
index 448b3b21a4..140baffc30 100644
--- a/engines/ags/engine/debugging/dummyagsdebugger.h
+++ b/engines/ags/engine/debugging/dummyagsdebugger.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_DUMMYAGSDEBUGGER_H
-#define __AC_DUMMYAGSDEBUGGER_H
+#ifndef AGS_ENGINE_DEBUGGING_DUMMYAGSDEBUGGER_H
+#define AGS_ENGINE_DEBUGGING_DUMMYAGSDEBUGGER_H
 
 #include "debug/debugger.h"
 
@@ -36,4 +36,4 @@ public:
     virtual char* GetNextMessage() override { return NULL; }
 };
 
-#endif // __AC_DUMMYAGSDEBUGGER_H
+#endif
diff --git a/engines/ags/engine/debugging/filebasedagsdebugger.h b/engines/ags/engine/debugging/filebasedagsdebugger.h
index 25e7a177a1..1caeee702e 100644
--- a/engines/ags/engine/debugging/filebasedagsdebugger.h
+++ b/engines/ags/engine/debugging/filebasedagsdebugger.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_FILEBASEDAGSDEBUGGER_H
-#define __AC_FILEBASEDAGSDEBUGGER_H
+#ifndef AGS_ENGINE_DEBUGGING_FILEBASEDAGSDEBUGGER_H
+#define AGS_ENGINE_DEBUGGING_FILEBASEDAGSDEBUGGER_H
 
 #include "debug/agseditordebugger.h"
 
@@ -39,4 +39,4 @@ public:
 
 extern const char* SENT_MESSAGE_FILE_NAME;
 
-#endif // __AC_FILEBASEDAGSDEBUGGER_H
+#endif
diff --git a/engines/ags/engine/debugging/logfile.h b/engines/ags/engine/debugging/logfile.h
index 9761216563..4bf8d8a96a 100644
--- a/engines/ags/engine/debugging/logfile.h
+++ b/engines/ags/engine/debugging/logfile.h
@@ -32,8 +32,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_DEBUG__LOGFILE_H
-#define __AGS_EE_DEBUG__LOGFILE_H
+#ifndef AGS_ENGINE_DEBUGGING_LOGFILE_H
+#define AGS_ENGINE_DEBUGGING_LOGFILE_H
 
 #include <memory>
 #include "debug/outputhandler.h"
@@ -86,4 +86,4 @@ private:
 }   // namespace Engine
 }   // namespace AGS
 
-#endif // __AGS_EE_DEBUG__LOGFILE_H
+#endif
diff --git a/engines/ags/engine/debugging/messagebuffer.h b/engines/ags/engine/debugging/messagebuffer.h
index effde36a4c..e8f986f111 100644
--- a/engines/ags/engine/debugging/messagebuffer.h
+++ b/engines/ags/engine/debugging/messagebuffer.h
@@ -28,8 +28,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_DEBUG__MESSAGEBUFFER_H
-#define __AGS_EE_DEBUG__MESSAGEBUFFER_H
+#ifndef AGS_ENGINE_DEBUGGING_MESSAGEBUFFER_H
+#define AGS_ENGINE_DEBUGGING_MESSAGEBUFFER_H
 
 #include <vector>
 #include "debug/outputhandler.h"
@@ -65,4 +65,4 @@ private:
 }   // namespace Engine
 }   // namespace AGS
 
-#endif // __AGS_EE_DEBUG__MESSAGEBUFFER_H
+#endif
diff --git a/engines/ags/engine/game/game_init.h b/engines/ags/engine/game/game_init.h
index 2ad5752ce8..89ce79c917 100644
--- a/engines/ags/engine/game/game_init.h
+++ b/engines/ags/engine/game/game_init.h
@@ -27,8 +27,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_GAME__GAMEINIT_H
-#define __AGS_EE_GAME__GAMEINIT_H
+#ifndef AGS_ENGINE_GAME_GAMEINIT_H
+#define AGS_ENGINE_GAME_GAMEINIT_H
 
 #include "game/main_game_file.h"
 #include "util/string.h"
@@ -64,4 +64,4 @@ HGameInitError  InitGameState(const LoadedGameEntities &ents, GameDataVersion da
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_GAME__GAMEINIT_H
+#endif
diff --git a/engines/ags/engine/game/savegame.h b/engines/ags/engine/game/savegame.h
index d6b4cd49f1..d13ddebe8b 100644
--- a/engines/ags/engine/game/savegame.h
+++ b/engines/ags/engine/game/savegame.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_GAME__SAVEGAME_H
-#define __AGS_EE_GAME__SAVEGAME_H
+#ifndef AGS_ENGINE_GAME_SAVEGAME_H
+#define AGS_ENGINE_GAME_SAVEGAME_H
 
 #include <memory>
 #include "ac/game_version.h"
@@ -174,4 +174,4 @@ void           SaveGameState(PStream out);
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_GAME__SAVEGAME_H
+#endif
diff --git a/engines/ags/engine/game/savegame_components.h b/engines/ags/engine/game/savegame_components.h
index 95b8555b1a..7f99fe7d50 100644
--- a/engines/ags/engine/game/savegame_components.h
+++ b/engines/ags/engine/game/savegame_components.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_GAME__SAVEGAMECOMPONENTS_H
-#define __AGS_EE_GAME__SAVEGAMECOMPONENTS_H
+#ifndef AGS_ENGINE_GAME_SAVEGAMECOMPONENTS_H
+#define AGS_ENGINE_GAME_SAVEGAMECOMPONENTS_H
 
 #include "game/savegame.h"
 #include "util/stream.h"
@@ -61,4 +61,4 @@ namespace SavegameComponents
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_GAME__SAVEGAMECOMPONENTS_H
+#endif
diff --git a/engines/ags/engine/game/savegame_internal.h b/engines/ags/engine/game/savegame_internal.h
index 8633fc53f3..bfbda8f0b4 100644
--- a/engines/ags/engine/game/savegame_internal.h
+++ b/engines/ags/engine/game/savegame_internal.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_GAME__SAVEGAMEINTERNAL_H
-#define __AGS_EE_GAME__SAVEGAMEINTERNAL_H
+#ifndef AGS_ENGINE_GAME_SAVEGAMEINTERNAL_H
+#define AGS_ENGINE_GAME_SAVEGAMEINTERNAL_H
 
 #include <memory>
 #include <vector>
@@ -149,4 +149,4 @@ struct RestoredData
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_GAME__SAVEGAMEINTERNAL_H
+#endif
diff --git a/engines/ags/engine/game/viewport.h b/engines/ags/engine/game/viewport.h
index 6f4604d228..f6f820f14d 100644
--- a/engines/ags/engine/game/viewport.h
+++ b/engines/ags/engine/game/viewport.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_AC__VIEWPORT_H
-#define __AGS_EE_AC__VIEWPORT_H
+#ifndef AGS_ENGINE_GAME_VIEWPORT_H
+#define AGS_ENGINE_GAME_VIEWPORT_H
 
 #include <memory>
 #include <vector>
@@ -200,4 +200,4 @@ private:
     bool _hasChangedVisible = false;
 };
 
-#endif // __AGS_EE_AC__VIEWPORT_H
+#endif
diff --git a/engines/ags/engine/gfx/ali3dexception.h b/engines/ags/engine/gfx/ali3dexception.h
index f27d24194b..ab5fc94230 100644
--- a/engines/ags/engine/gfx/ali3dexception.h
+++ b/engines/ags/engine/gfx/ali3dexception.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_GFX__ALI3DEXCEPTION_H
-#define __AGS_EE_GFX__ALI3DEXCEPTION_H
+#ifndef AGS_ENGINE_GFX_ALI3DEXCEPTION_H
+#define AGS_ENGINE_GFX_ALI3DEXCEPTION_H
 
 namespace AGS
 {
@@ -56,4 +56,4 @@ public:
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_GFX__ALI3DEXCEPTION_H
+#endif
diff --git a/engines/ags/engine/gfx/ali3dogl.h b/engines/ags/engine/gfx/ali3dogl.h
index d3d6268fa4..2b3a6eece9 100644
--- a/engines/ags/engine/gfx/ali3dogl.h
+++ b/engines/ags/engine/gfx/ali3dogl.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_GFX__ALI3DOGL_H
-#define __AGS_EE_GFX__ALI3DOGL_H
+#ifndef AGS_ENGINE_GFX_ALI3DOGL_H
+#define AGS_ENGINE_GFX_ALI3DOGL_H
 
 #include <memory>
 #include "gfx/bitmap.h"
@@ -369,4 +369,4 @@ private:
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_GFX__ALI3DOGL_H
+#endif
diff --git a/engines/ags/engine/gfx/ali3dsw.h b/engines/ags/engine/gfx/ali3dsw.h
index 4d8327d75a..d59ae5e0e5 100644
--- a/engines/ags/engine/gfx/ali3dsw.h
+++ b/engines/ags/engine/gfx/ali3dsw.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_GFX__ALI3DSW_H
-#define __AGS_EE_GFX__ALI3DSW_H
+#ifndef AGS_ENGINE_GFX_ALI3DSW_H
+#define AGS_ENGINE_GFX_ALI3DSW_H
 
 #include <memory>
 
@@ -277,4 +277,4 @@ private:
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_GFX__ALI3DSW_H
+#endif
diff --git a/engines/ags/engine/gfx/blender.h b/engines/ags/engine/gfx/blender.h
index 084d937d2b..2c07ce4009 100644
--- a/engines/ags/engine/gfx/blender.h
+++ b/engines/ags/engine/gfx/blender.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AC_BLENDER_H
-#define __AC_BLENDER_H
+#ifndef AGS_ENGINE_GFX_BLENDER_H
+#define AGS_ENGINE_GFX_BLENDER_H
 
 //
 // Allegro's standard alpha blenders result in:
@@ -72,4 +72,4 @@ void set_opaque_alpha_blender();
 // Sets argb2argb for 32-bit mode, and provides appropriate funcs for blending 32-bit onto 15/16/24-bit destination
 void set_argb2any_blender();
 
-#endif // __AC_BLENDER_H
+#endif
diff --git a/engines/ags/engine/gfx/ddb.h b/engines/ags/engine/gfx/ddb.h
index 442fa3d218..4dc159f739 100644
--- a/engines/ags/engine/gfx/ddb.h
+++ b/engines/ags/engine/gfx/ddb.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_GFX__DDB_H
-#define __AGS_EE_GFX__DDB_H
+#ifndef AGS_ENGINE_GFX_DDB_H
+#define AGS_ENGINE_GFX_DDB_H
 
 namespace AGS
 {
@@ -53,4 +53,4 @@ public:
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_GFX__DDB_H
+#endif
diff --git a/engines/ags/engine/gfx/gfx_util.h b/engines/ags/engine/gfx/gfx_util.h
index a459a1b4e0..a782b94f08 100644
--- a/engines/ags/engine/gfx/gfx_util.h
+++ b/engines/ags/engine/gfx/gfx_util.h
@@ -32,8 +32,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_GFX__GFXUTIL_H
-#define __AGS_EE_GFX__GFXUTIL_H
+#ifndef AGS_ENGINE_GFX_GFXUTIL_H
+#define AGS_ENGINE_GFX_GFXUTIL_H
 
 #include "gfx/bitmap.h"
 #include "gfx/gfx_def.h"
@@ -67,4 +67,4 @@ namespace GfxUtil
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_GFX__GFXUTIL_H
+#endif
diff --git a/engines/ags/engine/gfx/gfxdefines.h b/engines/ags/engine/gfx/gfxdefines.h
index a40e5f6f9a..939510f6b2 100644
--- a/engines/ags/engine/gfx/gfxdefines.h
+++ b/engines/ags/engine/gfx/gfxdefines.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_GFX__GFXDEFINES_H
-#define __AGS_EE_GFX__GFXDEFINES_H
+#ifndef AGS_ENGINE_GFX_GFXDEFINES_H
+#define AGS_ENGINE_GFX_GFXDEFINES_H
 
 #include "core/types.h"
 
@@ -87,4 +87,4 @@ struct DisplayMode : public GraphicResolution
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_GFX__GFXDEFINES_H
+#endif
diff --git a/engines/ags/engine/gfx/gfxdriverbase.h b/engines/ags/engine/gfx/gfxdriverbase.h
index 64d8dad05c..ea4a696cfc 100644
--- a/engines/ags/engine/gfx/gfxdriverbase.h
+++ b/engines/ags/engine/gfx/gfxdriverbase.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_GFX__GFXDRIVERBASE_H
-#define __AGS_EE_GFX__GFXDRIVERBASE_H
+#ifndef AGS_ENGINE_GFX_GFXDRIVERBASE_H
+#define AGS_ENGINE_GFX_GFXDRIVERBASE_H
 
 #include <vector>
 #include "gfx/ddb.h"
@@ -259,4 +259,4 @@ private:
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_GFX__GFXDRIVERBASE_H
+#endif
diff --git a/engines/ags/engine/gfx/gfxdriverfactory.h b/engines/ags/engine/gfx/gfxdriverfactory.h
index 63d6479e70..75e10ef402 100644
--- a/engines/ags/engine/gfx/gfxdriverfactory.h
+++ b/engines/ags/engine/gfx/gfxdriverfactory.h
@@ -30,8 +30,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_GFX__GFXDRIVERFACTORY_H
-#define __AGS_EE_GFX__GFXDRIVERFACTORY_H
+#ifndef AGS_ENGINE_GFX_GFXDRIVERFACTORY_H
+#define AGS_ENGINE_GFX_GFXDRIVERFACTORY_H
 
 #include <memory>
 #include "util/string.h"
@@ -84,4 +84,4 @@ IGfxDriverFactory *GetGfxDriverFactory(const String id);
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_GFX__GFXDRIVERFACTORY_H
+#endif
diff --git a/engines/ags/engine/gfx/gfxdriverfactorybase.h b/engines/ags/engine/gfx/gfxdriverfactorybase.h
index 93710a3ad8..7962d35d8d 100644
--- a/engines/ags/engine/gfx/gfxdriverfactorybase.h
+++ b/engines/ags/engine/gfx/gfxdriverfactorybase.h
@@ -30,8 +30,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_GFX__GFXDRIVERFACTORYBASE_H
-#define __AGS_EE_GFX__GFXDRIVERFACTORYBASE_H
+#ifndef AGS_ENGINE_GFX_GFXDRIVERFACTORYBASE_H
+#define AGS_ENGINE_GFX_GFXDRIVERFACTORYBASE_H
 
 #include <vector>
 #include "gfx/gfxdriverfactory.h"
@@ -117,4 +117,4 @@ protected:
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_GFX__GFXDRIVERFACTORYBASE_H
+#endif
diff --git a/engines/ags/engine/gfx/gfxfilter.h b/engines/ags/engine/gfx/gfxfilter.h
index 5f6554dda2..04e937ac84 100644
--- a/engines/ags/engine/gfx/gfxfilter.h
+++ b/engines/ags/engine/gfx/gfxfilter.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_GFX__GFXFILTER_H
-#define __AGS_EE_GFX__GFXFILTER_H
+#ifndef AGS_ENGINE_GFX_GFXFILTER_H
+#define AGS_ENGINE_GFX_GFXFILTER_H
 
 #include <memory>
 #include "util/geometry.h"
@@ -78,4 +78,4 @@ typedef std::shared_ptr<IGfxFilter> PGfxFilter;
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_GFX__GFXFILTER_H
+#endif
diff --git a/engines/ags/engine/gfx/gfxfilter_aad3d.h b/engines/ags/engine/gfx/gfxfilter_aad3d.h
index 5ae4af25c5..e730cde9b2 100644
--- a/engines/ags/engine/gfx/gfxfilter_aad3d.h
+++ b/engines/ags/engine/gfx/gfxfilter_aad3d.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_GFX__AAD3DGFXFILTER_H
-#define __AGS_EE_GFX__AAD3DGFXFILTER_H
+#ifndef AGS_ENGINE_GFX_AAD3DGFXFILTER_H
+#define AGS_ENGINE_GFX_AAD3DGFXFILTER_H
 
 #include "gfx/gfxfilter_d3d.h"
 
@@ -53,4 +53,4 @@ public:
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_GFX__AAD3DGFXFILTER_H
+#endif
diff --git a/engines/ags/engine/gfx/gfxfilter_aaogl.h b/engines/ags/engine/gfx/gfxfilter_aaogl.h
index d1f5f93d1a..d8939efce8 100644
--- a/engines/ags/engine/gfx/gfxfilter_aaogl.h
+++ b/engines/ags/engine/gfx/gfxfilter_aaogl.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_GFX__AAOGLGFXFILTER_H
-#define __AGS_EE_GFX__AAOGLGFXFILTER_H
+#ifndef AGS_ENGINE_GFX_AAOGLGFXFILTER_H
+#define AGS_ENGINE_GFX_AAOGLGFXFILTER_H
 
 #include "gfx/gfxfilter_ogl.h"
 
@@ -53,4 +53,4 @@ public:
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_GFX__AAOGLGFXFILTER_H
+#endif
diff --git a/engines/ags/engine/gfx/gfxfilter_allegro.h b/engines/ags/engine/gfx/gfxfilter_allegro.h
index 74f01b341b..9c2497740e 100644
--- a/engines/ags/engine/gfx/gfxfilter_allegro.h
+++ b/engines/ags/engine/gfx/gfxfilter_allegro.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_GFX__ALLEGROGFXFILTER_H
-#define __AGS_EE_GFX__ALLEGROGFXFILTER_H
+#ifndef AGS_ENGINE_GFX_ALLEGROGFXFILTER_H
+#define AGS_ENGINE_GFX_ALLEGROGFXFILTER_H
 
 #include "gfx/bitmap.h"
 #include "gfx/gfxfilter_scaling.h"
@@ -78,4 +78,4 @@ protected:
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_GFX__ALLEGROGFXFILTER_H
+#endif
diff --git a/engines/ags/engine/gfx/gfxfilter_d3d.h b/engines/ags/engine/gfx/gfxfilter_d3d.h
index c688ddfec3..1b1798c2cc 100644
--- a/engines/ags/engine/gfx/gfxfilter_d3d.h
+++ b/engines/ags/engine/gfx/gfxfilter_d3d.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_GFX__D3DGFXFILTER_H
-#define __AGS_EE_GFX__D3DGFXFILTER_H
+#ifndef AGS_ENGINE_GFX_D3DGFXFILTER_H
+#define AGS_ENGINE_GFX_D3DGFXFILTER_H
 
 #include "gfx/gfxfilter_scaling.h"
 
@@ -53,4 +53,4 @@ public:
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_GFX__D3DGFXFILTER_H
+#endif
diff --git a/engines/ags/engine/gfx/gfxfilter_hqx.h b/engines/ags/engine/gfx/gfxfilter_hqx.h
index 97c0d0ef73..fc3db3c64f 100644
--- a/engines/ags/engine/gfx/gfxfilter_hqx.h
+++ b/engines/ags/engine/gfx/gfxfilter_hqx.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_GFX__HQ2XGFXFILTER_H
-#define __AGS_EE_GFX__HQ2XGFXFILTER_H
+#ifndef AGS_ENGINE_GFX_HQ2XGFXFILTER_H
+#define AGS_ENGINE_GFX_HQ2XGFXFILTER_H
 
 #include "gfx/gfxfilter_allegro.h"
 
@@ -65,4 +65,4 @@ protected:
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_GFX__HQ2XGFXFILTER_H
+#endif
diff --git a/engines/ags/engine/gfx/gfxfilter_ogl.h b/engines/ags/engine/gfx/gfxfilter_ogl.h
index c41bc6f56b..4b90e56c9a 100644
--- a/engines/ags/engine/gfx/gfxfilter_ogl.h
+++ b/engines/ags/engine/gfx/gfxfilter_ogl.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_GFX__OGLGFXFILTER_H
-#define __AGS_EE_GFX__OGLGFXFILTER_H
+#ifndef AGS_ENGINE_GFX_OGLGFXFILTER_H
+#define AGS_ENGINE_GFX_OGLGFXFILTER_H
 
 #include "gfx/gfxfilter_scaling.h"
 
@@ -53,4 +53,4 @@ public:
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_GFX__OGLGFXFILTER_H
+#endif
diff --git a/engines/ags/engine/gfx/gfxfilter_scaling.h b/engines/ags/engine/gfx/gfxfilter_scaling.h
index 228e934dd5..fb1e2f3428 100644
--- a/engines/ags/engine/gfx/gfxfilter_scaling.h
+++ b/engines/ags/engine/gfx/gfxfilter_scaling.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_GFX__SCALINGGFXFILTER_H
-#define __AGS_EE_GFX__SCALINGGFXFILTER_H
+#ifndef AGS_ENGINE_GFX_SCALINGGFXFILTER_H
+#define AGS_ENGINE_GFX_SCALINGGFXFILTER_H
 
 #include "gfx/gfxfilter.h"
 #include "util/scaling.h"
@@ -53,4 +53,4 @@ protected:
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_GFX__SCALINGGFXFILTER_H
+#endif
diff --git a/engines/ags/engine/gfx/gfxmodelist.h b/engines/ags/engine/gfx/gfxmodelist.h
index 62eb38f690..7ae841776e 100644
--- a/engines/ags/engine/gfx/gfxmodelist.h
+++ b/engines/ags/engine/gfx/gfxmodelist.h
@@ -25,8 +25,9 @@
 // Supported graphics mode interface
 //
 //=============================================================================
-#ifndef __AGS_EE_GFX__GFXMODELIST_H
-#define __AGS_EE_GFX__GFXMODELIST_H
+
+#ifndef AGS_ENGINE_GFX_GFXMODELIST_H
+#define AGS_ENGINE_GFX_GFXMODELIST_H
 
 #include "core/types.h"
 #include "gfx/gfxdefines.h"
@@ -47,4 +48,4 @@ public:
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_GFX__GFXMODELIST_H
+#endif
diff --git a/engines/ags/engine/gfx/graphicsdriver.h b/engines/ags/engine/gfx/graphicsdriver.h
index 0af51ecd1c..52fb906198 100644
--- a/engines/ags/engine/gfx/graphicsdriver.h
+++ b/engines/ags/engine/gfx/graphicsdriver.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_GFX__GRAPHICSDRIVER_H
-#define __AGS_EE_GFX__GRAPHICSDRIVER_H
+#ifndef AGS_ENGINE_GFX_GRAPHICSDRIVER_H
+#define AGS_ENGINE_GFX_GRAPHICSDRIVER_H
 
 #include <memory>
 #include "gfx/gfxdefines.h"
@@ -197,4 +197,4 @@ public:
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_GFX__GRAPHICSDRIVER_H
+#endif
diff --git a/engines/ags/engine/gfx/hq2x3x.h b/engines/ags/engine/gfx/hq2x3x.h
index d569a642c6..b6d2595936 100644
--- a/engines/ags/engine/gfx/hq2x3x.h
+++ b/engines/ags/engine/gfx/hq2x3x.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_HQ2X3X_H
-#define __AC_HQ2X3X_H
+#ifndef AGS_ENGINE_GFX_HQ2X3X_H
+#define AGS_ENGINE_GFX_HQ2X3X_H
 
 #include "core/platform.h"
 
@@ -35,4 +35,4 @@ void hq2x_32( unsigned char * pIn, unsigned char * pOut, int Xres, int Yres, int
 void hq3x_32( unsigned char * pIn, unsigned char * pOut, int Xres, int Yres, int BpL );
 #endif
 
-#endif // __AC_HQ2X3X_H
+#endif
diff --git a/engines/ags/engine/gui/animatingguibutton.h b/engines/ags/engine/gui/animatingguibutton.h
index fccdd74328..7fb060da90 100644
--- a/engines/ags/engine/gui/animatingguibutton.h
+++ b/engines/ags/engine/gui/animatingguibutton.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_GUI__ANIMATINGGUIBUTTON_H
-#define __AGS_EE_GUI__ANIMATINGGUIBUTTON_H
+#ifndef AGS_ENGINE_GUI_ANIMATINGGUIBUTTON_H
+#define AGS_ENGINE_GUI_ANIMATINGGUIBUTTON_H
 
 #include "ac/runtime_defines.h"
 
@@ -40,4 +40,4 @@ struct AnimatingGUIButton {
     void WriteToFile(Common::Stream *out);
 };
 
-#endif // __AGS_EE_GUI__ANIMATINGGUIBUTTON_H
+#endif
diff --git a/engines/ags/engine/gui/cscidialog.h b/engines/ags/engine/gui/cscidialog.h
index 0246479e76..ebee093d29 100644
--- a/engines/ags/engine/gui/cscidialog.h
+++ b/engines/ags/engine/gui/cscidialog.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_GUI__CSCIDIALOG_H
-#define __AGS_EE_GUI__CSCIDIALOG_H
+#ifndef AGS_ENGINE_GUI_CSCIDIALOG_H
+#define AGS_ENGINE_GUI_CSCIDIALOG_H
 
 #include "gui/guidialoginternaldefs.h"
 
@@ -44,4 +44,4 @@ int  checkcontrols();
 int  finddefaultcontrol(int flagmask);
 int  GetBaseWidth ();
 
-#endif // __AGS_EE_GUI__CSCIDIALOG_H
+#endif
diff --git a/engines/ags/engine/gui/guidialog.h b/engines/ags/engine/gui/guidialog.h
index aedca86099..1c605e3cc1 100644
--- a/engines/ags/engine/gui/guidialog.h
+++ b/engines/ags/engine/gui/guidialog.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_GUI__GUIDIALOG_H
-#define __AGS_EE_GUI__GUIDIALOG_H
+#ifndef AGS_ENGINE_GUI_GUIDIALOG_H
+#define AGS_ENGINE_GUI_GUIDIALOG_H
 
 namespace AGS { namespace Common { class Bitmap; } }
 
@@ -46,4 +46,4 @@ int  quitdialog();
 // last string value in gui dialog.
 char *get_gui_dialog_buffer();
 
-#endif // __AGS_EE_GUI__GUIDIALOG_H
+#endif
diff --git a/engines/ags/engine/gui/guidialogdefines.h b/engines/ags/engine/gui/guidialogdefines.h
index 82d783d502..c805a77f3e 100644
--- a/engines/ags/engine/gui/guidialogdefines.h
+++ b/engines/ags/engine/gui/guidialogdefines.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_GUI__GUIDIALOGDEFINES_H
-#define __AGS_EE_GUI__GUIDIALOGDEFINES_H
+#ifndef AGS_ENGINE_GUI_GUIDIALOGDEFINES_H
+#define AGS_ENGINE_GUI_GUIDIALOGDEFINES_H
 
 #define MSG_RESTORE      984
 #define MSG_CANCEL       985    // "Cancel"
@@ -113,4 +113,4 @@ struct OnScreenWindow
     OnScreenWindow();
 };
 
-#endif // __AGS_EE_GUI__GUIDIALOGDEFINES_H
+#endif
diff --git a/engines/ags/engine/gui/guidialoginternaldefs.h b/engines/ags/engine/gui/guidialoginternaldefs.h
index 2de4f5639a..c00842cdde 100644
--- a/engines/ags/engine/gui/guidialoginternaldefs.h
+++ b/engines/ags/engine/gui/guidialoginternaldefs.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_GUI__GUIDIALOGINTERNALDEFS_H
-#define __AGS_EE_GUI__GUIDIALOGINTERNALDEFS_H
+#ifndef AGS_ENGINE_GUI_GUIDIALOGINTERNALDEFS_H
+#define AGS_ENGINE_GUI_GUIDIALOGINTERNALDEFS_H
 
 #include "gui/guidialogdefines.h"
 
@@ -34,4 +34,4 @@ extern int ags_misbuttondown (int but);
 #define mbutrelease(X) (!ags_misbuttondown(X))
 #define TEXT_HT usetup.textheight
 
-#endif // __AGS_EE_GUI__GUIDIALOGINTERNALDEFS_H
+#endif
diff --git a/engines/ags/engine/gui/mycontrols.h b/engines/ags/engine/gui/mycontrols.h
index df6b2b178d..d0fd99a808 100644
--- a/engines/ags/engine/gui/mycontrols.h
+++ b/engines/ags/engine/gui/mycontrols.h
@@ -26,12 +26,12 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_GUI__MYCONTROLS_H
-#define __AGS_EE_GUI__MYCONTROLS_H
+#ifndef AGS_ENGINE_GUI_MYCONTROLS_H
+#define AGS_ENGINE_GUI_MYCONTROLS_H
 
 #include "gui/mylabel.h"
 #include "gui/mylistbox.h"
 #include "gui/mypushbutton.h"
 #include "gui/mytextbox.h"
 
-#endif // __AGS_EE_GUI__MYCONTROLS_H
+#endif
diff --git a/engines/ags/engine/gui/mylabel.h b/engines/ags/engine/gui/mylabel.h
index efa6ec8b43..49f891b28d 100644
--- a/engines/ags/engine/gui/mylabel.h
+++ b/engines/ags/engine/gui/mylabel.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_MYLABEL_H
-#define __AC_MYLABEL_H
+#ifndef AGS_ENGINE_GUI_MYLABEL_H
+#define AGS_ENGINE_GUI_MYLABEL_H
 
 #include "gui/newcontrol.h"
 
@@ -37,4 +37,4 @@ struct MyLabel:public NewControl
   int processmessage(int mcode, int wParam, long lParam) override;
 };
 
-#endif // __AC_MYLABEL_H
+#endif
diff --git a/engines/ags/engine/gui/mylistbox.h b/engines/ags/engine/gui/mylistbox.h
index 271bdbd94f..d65a6b69cd 100644
--- a/engines/ags/engine/gui/mylistbox.h
+++ b/engines/ags/engine/gui/mylistbox.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_MYLISTBOX_H
-#define __AC_MYLISTBOX_H
+#ifndef AGS_ENGINE_GUI_MYLISTBOX_H
+#define AGS_ENGINE_GUI_MYLISTBOX_H
 
 #include "gui/newcontrol.h"
 
@@ -42,4 +42,4 @@ struct MyListBox:public NewControl
   int processmessage(int mcode, int wParam, long lParam) override;
 };
 
-#endif // __AC_MYLISTBOX_H
+#endif
diff --git a/engines/ags/engine/gui/mypushbutton.h b/engines/ags/engine/gui/mypushbutton.h
index 56832759cc..00b21f624e 100644
--- a/engines/ags/engine/gui/mypushbutton.h
+++ b/engines/ags/engine/gui/mypushbutton.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_PUSHBUTTON_H
-#define __AC_PUSHBUTTON_H
+#ifndef AGS_ENGINE_GUI_PUSHBUTTON_H
+#define AGS_ENGINE_GUI_PUSHBUTTON_H
 
 #include "gui/newcontrol.h"
 
@@ -34,4 +34,4 @@ struct MyPushButton:public NewControl
   int processmessage(int mcode, int wParam, long lParam) override;
 };
 
-#endif // __AC_PUSHBUTTON_H
+#endif
diff --git a/engines/ags/engine/gui/mytextbox.h b/engines/ags/engine/gui/mytextbox.h
index 6fb47c2588..0dd68f4a63 100644
--- a/engines/ags/engine/gui/mytextbox.h
+++ b/engines/ags/engine/gui/mytextbox.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_MYTEXTBOX_H
-#define __AC_MYTEXTBOX_H
+#ifndef AGS_ENGINE_GUI_MYTEXTBOX_H
+#define AGS_ENGINE_GUI_MYTEXTBOX_H
 
 #include "gui/newcontrol.h"
 
@@ -35,4 +35,4 @@ struct MyTextBox:public NewControl
   int processmessage(int mcode, int wParam, long lParam) override;
 };
 
-#endif // __AC_MYTEXTBOX_H
+#endif
diff --git a/engines/ags/engine/gui/newcontrol.h b/engines/ags/engine/gui/newcontrol.h
index 550e661988..a0b7e20813 100644
--- a/engines/ags/engine/gui/newcontrol.h
+++ b/engines/ags/engine/gui/newcontrol.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_GUI__NEWCONTROL_H
-#define __AGS_EE_GUI__NEWCONTROL_H
+#ifndef AGS_ENGINE_GUI_NEWCONTROL_H
+#define AGS_ENGINE_GUI_NEWCONTROL_H
 
 #include "gfx/bitmap.h"
 
@@ -44,4 +44,4 @@ struct NewControl
   void drawandmouse();
 };
 
-#endif // __AGS_EE_GUI__NEWCONTROL_H
+#endif
diff --git a/engines/ags/engine/main/config.h b/engines/ags/engine/main/config.h
index 98ae421437..77dab9e323 100644
--- a/engines/ags/engine/main/config.h
+++ b/engines/ags/engine/main/config.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_MAIN__CONFIG_H
-#define __AGS_EE_MAIN__CONFIG_H
+#ifndef AGS_ENGINE_MAIN_CONFIG_H
+#define AGS_ENGINE_MAIN_CONFIG_H
 
 #include "main/graphics_mode.h"
 #include "util/ini_util.h"
@@ -78,4 +78,4 @@ void INIwritestring(ConfigTree &cfg, const String &sectn, const String &item, co
 void INIwriteint(ConfigTree &cfg, const String &sectn, const String &item, int value);
 
 
-#endif // __AGS_EE_MAIN__CONFIG_H
+#endif
diff --git a/engines/ags/engine/main/engine.h b/engines/ags/engine/main/engine.h
index 5a83b47883..ef3e96796e 100644
--- a/engines/ags/engine/main/engine.h
+++ b/engines/ags/engine/main/engine.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_MAIN__ENGINE_H
-#define __AGS_EE_MAIN__ENGINE_H
+#ifndef AGS_ENGINE_MAIN_ENGINE_H
+#define AGS_ENGINE_MAIN_ENGINE_H
 
 #include "util/ini_util.h"
 
@@ -64,4 +64,4 @@ extern ResourcePaths ResPaths;
 typedef void (*t_engine_pre_init_callback)(void);
 extern void engine_set_pre_init_callback(t_engine_pre_init_callback callback);
 
-#endif // __AGS_EE_MAIN__ENGINE_H
+#endif
diff --git a/engines/ags/engine/main/engine_setup.h b/engines/ags/engine/main/engine_setup.h
index a1d9dd2c3b..9c4a424517 100644
--- a/engines/ags/engine/main/engine_setup.h
+++ b/engines/ags/engine/main/engine_setup.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_MAIN__ENGINESETUP_H
-#define __AGS_EE_MAIN__ENGINESETUP_H
+#ifndef AGS_ENGINE_MAIN_ENGINESETUP_H
+#define AGS_ENGINE_MAIN_ENGINESETUP_H
 
 #include "util/geometry.h"
 #include "gfx/gfxdefines.h"
@@ -38,4 +38,4 @@ void engine_pre_gfxsystem_shutdown();
 // Applies necessary changes after screen<->virtual coordinate transformation has changed
 void on_coordinates_scaling_changed();
 
-#endif // __AGS_EE_MAIN__ENGINESETUP_H
+#endif
diff --git a/engines/ags/engine/main/game_file.h b/engines/ags/engine/main/game_file.h
index 6422096f42..d63929bff5 100644
--- a/engines/ags/engine/main/game_file.h
+++ b/engines/ags/engine/main/game_file.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_MAIN__GAMEFILE_H
-#define __AGS_EE_MAIN__GAMEFILE_H
+#ifndef AGS_ENGINE_MAIN_GAMEFILE_H
+#define AGS_ENGINE_MAIN_GAMEFILE_H
 
 #include "util/error.h"
 #include "util/string.h"
@@ -34,4 +34,4 @@ HError preload_game_data();
 HError load_game_file();
 void display_game_file_error(HError err);
 
-#endif // __AGS_EE_MAIN__GAMEFILE_H
+#endif
diff --git a/engines/ags/engine/main/game_run.h b/engines/ags/engine/main/game_run.h
index 2a87af861b..58ddaa6ddb 100644
--- a/engines/ags/engine/main/game_run.h
+++ b/engines/ags/engine/main/game_run.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_MAIN__GAMERUN_H
-#define __AGS_EE_MAIN__GAMERUN_H
+#ifndef AGS_ENGINE_MAIN_GAME_RUN_H
+#define AGS_ENGINE_MAIN_GAME_RUN_H
 
 namespace AGS { namespace Engine { class IDriverDependantBitmap; }}
 using namespace AGS::Engine; // FIXME later
@@ -50,4 +50,4 @@ bool run_service_key_controls(int &kgn);
 // otherwise returns true and provides mouse button code.
 bool run_service_mb_controls(int &mbut, int &mwheelz);
 
-#endif // __AGS_EE_MAIN__GAMERUN_H
+#endif
diff --git a/engines/ags/engine/main/game_start.h b/engines/ags/engine/main/game_start.h
index 4f79e4e71d..d672229c98 100644
--- a/engines/ags/engine/main/game_start.h
+++ b/engines/ags/engine/main/game_start.h
@@ -20,10 +20,10 @@
  *
  */
 
-#ifndef __AGS_EE_MAIN__GAMESTART_H
-#define __AGS_EE_MAIN__GAMESTART_H
+#ifndef AGS_ENGINE_MAIN_GAME_START_H
+#define AGS_ENGINE_MAIN_GAME_START_H
 
 void start_game();
 void initialize_start_and_play_game(int override_start_room, const char *loadSaveGameOnStartup);
 
-#endif // __AGS_EE_MAIN__GAMESTART_H
+#endif
diff --git a/engines/ags/engine/main/graphics_mode.h b/engines/ags/engine/main/graphics_mode.h
index 426f3d2200..8e5f7a23e6 100644
--- a/engines/ags/engine/main/graphics_mode.h
+++ b/engines/ags/engine/main/graphics_mode.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_MAIN__GRAPHICSMODE_H
-#define __AGS_EE_MAIN__GRAPHICSMODE_H
+#ifndef AGS_ENGINE_MAIN_GRAPHICSMODE_H
+#define AGS_ENGINE_MAIN_GRAPHICSMODE_H
 
 #include "gfx/gfxdefines.h"
 #include "util/scaling.h"
@@ -160,4 +160,4 @@ bool graphics_mode_set_filter(const String &filter_id);
 // Releases current graphic mode and shuts down renderer
 void graphics_mode_shutdown();
 
-#endif // __AGS_EE_MAIN__GRAPHICSMODE_H
+#endif
diff --git a/engines/ags/engine/main/main.h b/engines/ags/engine/main/main.h
index 9dc115506d..cd3a27e9b9 100644
--- a/engines/ags/engine/main/main.h
+++ b/engines/ags/engine/main/main.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_MAIN__MAIN_H
-#define __AGS_EE_MAIN__MAIN_H
+#ifndef AGS_ENGINE_MAIN_MAIN_H
+#define AGS_ENGINE_MAIN_MAIN_H
 
 #include "core/platform.h"
 #include "util/version.h"
@@ -67,4 +67,4 @@ void main_print_help();
 
 int ags_entry_point(int argc, char *argv[]);
 
-#endif // __AGS_EE_MAIN__MAIN_H
+#endif
diff --git a/engines/ags/engine/main/main_allegro.h b/engines/ags/engine/main/main_allegro.h
index 177c7d9328..c6f0d3e7db 100644
--- a/engines/ags/engine/main/main_allegro.h
+++ b/engines/ags/engine/main/main_allegro.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_MAIN__MAINALLEGRO_H
-#define __AGS_EE_MAIN__MAINALLEGRO_H
+#ifndef AGS_ENGINE_MAIN_MAINALLEGRO_H
+#define AGS_ENGINE_MAIN_MAINALLEGRO_H
 
 // Gets allegro_error as a const string.
 // Please, use this getter to acquire error text, do not use allegro_error
@@ -33,4 +33,4 @@ const char *get_allegro_error();
 // truncated. Null terminator is always guaranteed.
 const char *set_allegro_error(const char *format, ...);
 
-#endif // __AGS_EE_MAIN__MAINALLEGRO_H
+#endif
diff --git a/engines/ags/engine/main/maindefines_ex.h b/engines/ags/engine/main/maindefines_ex.h
index 32e2144647..6c66b3ed11 100644
--- a/engines/ags/engine/main/maindefines_ex.h
+++ b/engines/ags/engine/main/maindefines_ex.h
@@ -20,9 +20,9 @@
  *
  */
 
-#ifndef __AGS_EE_MAIN__MAINDEFINES_H
-#define __AGS_EE_MAIN__MAINDEFINES_H
+#ifndef AGS_ENGINE_MAIN_MAINDEFINES_H
+#define AGS_ENGINE_MAIN_MAINDEFINES_H
 
 #define RETURN_CONTINUE      1
 
-#endif // __AGS_EE_MAIN__MAINDEFINES_H
+#endif
diff --git a/engines/ags/engine/main/mainheader.h b/engines/ags/engine/main/mainheader.h
index 1739068bcb..406e5c0787 100644
--- a/engines/ags/engine/main/mainheader.h
+++ b/engines/ags/engine/main/mainheader.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_MAIN__MAINHEADER_H
-#define __AGS_EE_MAIN__MAINHEADER_H
+#ifndef AGS_ENGINE_MAIN_MAINHEADER_H
+#define AGS_ENGINE_MAIN_MAINHEADER_H
 
 #include "core/platform.h"
 
@@ -49,4 +49,4 @@ extern "C" void selectLatestSavegame();
 extern bool psp_load_latest_savegame;
 #endif
 
-#endif // __AGS_EE_MAIN__MAINHEADER_H
+#endif
diff --git a/engines/ags/engine/main/quit.h b/engines/ags/engine/main/quit.h
index 2afd0eeaa5..569aa90e5e 100644
--- a/engines/ags/engine/main/quit.h
+++ b/engines/ags/engine/main/quit.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_MAIN__QUIT_H
-#define __AGS_EE_MAIN__QUIT_H
+#ifndef AGS_ENGINE_MAIN_QUIT_H
+#define AGS_ENGINE_MAIN_QUIT_H
 
 enum QuitReason
 {
@@ -47,4 +47,4 @@ enum QuitReason
     kQuit_FatalError    = kQuitKind_EngineException
 };
 
-#endif // __AGS_EE_MAIN__QUIT_H
+#endif
diff --git a/engines/ags/engine/main/update.h b/engines/ags/engine/main/update.h
index ff89a549e2..c7bcde862e 100644
--- a/engines/ags/engine/main/update.h
+++ b/engines/ags/engine/main/update.h
@@ -20,12 +20,12 @@
  *
  */
 
-#ifndef __AGS_EE_MAIN__UPDATE_H
-#define __AGS_EE_MAIN__UPDATE_H
+#ifndef AGS_ENGINE_MAIN_UPDATE_H
+#define AGS_ENGINE_MAIN_UPDATE_H
 
 #define MAX_SHEEP 30	// sheep == follower
 
 int do_movelist_move(short*mlnum,int*xx,int*yy);
 void update_stuff();
 
-#endif // __AGS_EE_MAIN__UPDATE_H
+#endif
diff --git a/engines/ags/engine/media/audio/ambientsound.h b/engines/ags/engine/media/audio/ambientsound.h
index 1144eda9ad..edefea665c 100644
--- a/engines/ags/engine/media/audio/ambientsound.h
+++ b/engines/ags/engine/media/audio/ambientsound.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_AMBIENTSOUND_H
-#define __AC_AMBIENTSOUND_H
+#ifndef AGS_ENGINE_MEDIA_AUDIO_AMBIENTSOUND_H
+#define AGS_ENGINE_MEDIA_AUDIO_AMBIENTSOUND_H
 
 // Forward declaration
 namespace AGS { namespace Common { class Stream; } }
@@ -42,4 +42,4 @@ struct AmbientSound {
     void WriteToFile(Common::Stream *out);
 };
 
-#endif // __AC_AMBIENTSOUND_H
+#endif
diff --git a/engines/ags/engine/media/audio/audio.h b/engines/ags/engine/media/audio/audio.h
index 1d0a239dce..eff2c5dd6a 100644
--- a/engines/ags/engine/media/audio/audio.h
+++ b/engines/ags/engine/media/audio/audio.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_AUDIO_H
-#define __AC_AUDIO_H
+#ifndef AGS_ENGINE_MEDIA_AUDIO_AUDIO_H
+#define AGS_ENGINE_MEDIA_AUDIO_AUDIO_H
 
 #include <array>
 #include "media/audio/audiodefines.h"
@@ -158,4 +158,4 @@ extern SOUNDCLIP *cachedQueuedMusic;
 // TODO: double check that ambient sounds array actually needs +1
 extern std::array<AmbientSound,MAX_SOUND_CHANNELS+1> ambient;
 
-#endif // __AC_AUDIO_H
+#endif
diff --git a/engines/ags/engine/media/audio/audio_system.h b/engines/ags/engine/media/audio/audio_system.h
index 9bb5e1cb1a..202f0238d2 100644
--- a/engines/ags/engine/media/audio/audio_system.h
+++ b/engines/ags/engine/media/audio/audio_system.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_MEDIA_AUDIO_SYSTEM_H
-#define __AC_MEDIA_AUDIO_SYSTEM_H
+#ifndef AGS_ENGINE_MEDIA_AUDIO_AUDIO_SYSTEM_H
+#define AGS_ENGINE_MEDIA_AUDIO_AUDIO_SYSTEM_H
 
 #include "media/audio/audiodefines.h"
 #include "media/audio/ambientsound.h"
diff --git a/engines/ags/engine/media/audio/audiodefines.h b/engines/ags/engine/media/audio/audiodefines.h
index ee7757cc90..9f8cf7d7be 100644
--- a/engines/ags/engine/media/audio/audiodefines.h
+++ b/engines/ags/engine/media/audio/audiodefines.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_AUDIODEFINES_H
-#define __AC_AUDIODEFINES_H
+#ifndef AGS_ENGINE_MEDIA_AUDIO_AUDIODEFINES_H
+#define AGS_ENGINE_MEDIA_AUDIO_AUDIODEFINES_H
 
 #define MUS_MIDI 1
 #define MUS_MP3  2
@@ -44,4 +44,4 @@
 #define AUDIOTYPE_LEGACY_MUSIC 2
 #define AUDIOTYPE_LEGACY_SOUND 3
 
-#endif // __AC_AUDIODEFINES_H
+#endif
diff --git a/engines/ags/engine/media/audio/audiointernaldefs.h b/engines/ags/engine/media/audio/audiointernaldefs.h
index 3dce5d80ca..94fb568bc1 100644
--- a/engines/ags/engine/media/audio/audiointernaldefs.h
+++ b/engines/ags/engine/media/audio/audiointernaldefs.h
@@ -20,10 +20,10 @@
  *
  */
 
-#ifndef __AC_SOUNDINTERNALDEFS_H
-#define __AC_SOUNDINTERNALDEFS_H
+#ifndef AGS_ENGINE_MEDIA_AUDIO_SOUNDINTERNALDEFS_H
+#define AGS_ENGINE_MEDIA_AUDIO_SOUNDINTERNALDEFS_H
 
 //#define MP3CHUNKSIZE 100000
 #define MP3CHUNKSIZE 32768
 
-#endif // __AC_SOUNDINTERNALDEFS_H
+#endif
diff --git a/engines/ags/engine/media/audio/clip_mydumbmod.h b/engines/ags/engine/media/audio/clip_mydumbmod.h
index 8c20a135ae..bb7e274174 100644
--- a/engines/ags/engine/media/audio/clip_mydumbmod.h
+++ b/engines/ags/engine/media/audio/clip_mydumbmod.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_MYDUMBMOD_H
-#define __AC_MYDUMBMOD_H
+#ifndef AGS_ENGINE_MEDIA_AUDIO_CLIP_MYDUMBMOD_H
+#define AGS_ENGINE_MEDIA_AUDIO_CLIP_MYDUMBMOD_H
 
 #include "aldumb.h"
 #include "media/audio/soundclip.h"
@@ -74,4 +74,4 @@ protected:
     int get_real_mod_pos();
 };
 
-#endif // __AC_MYDUMBMOD_H
+#endif
diff --git a/engines/ags/engine/media/audio/clip_myjgmod.h b/engines/ags/engine/media/audio/clip_myjgmod.h
index 9ddb82bbf2..82d7ff3e03 100644
--- a/engines/ags/engine/media/audio/clip_myjgmod.h
+++ b/engines/ags/engine/media/audio/clip_myjgmod.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_MYJGMOD_H
-#define __AC_MYJGMOD_H
+#ifndef AGS_ENGINE_MEDIA_AUDIO_CLIP_MYJGMOD_H
+#define AGS_ENGINE_MEDIA_AUDIO_CLIP_MYJGMOD_H
 
 #include "jgmod.h"
 #include "media/audio/soundclip.h"
@@ -54,4 +54,4 @@ struct MYMOD:public SOUNDCLIP
     MYMOD();
 };
 
-#endif // __AC_MYJGMOD_H
+#endif
diff --git a/engines/ags/engine/media/audio/clip_mymidi.h b/engines/ags/engine/media/audio/clip_mymidi.h
index 0eccf714a8..b7970f60ef 100644
--- a/engines/ags/engine/media/audio/clip_mymidi.h
+++ b/engines/ags/engine/media/audio/clip_mymidi.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_MYMIDI_H
-#define __AC_MYMIDI_H
+#ifndef AGS_ENGINE_MEDIA_AUDIO_CLIP_MYMIDI_H
+#define AGS_ENGINE_MEDIA_AUDIO_CLIP_MYMIDI_H
 
 #include "media/audio/soundclip.h"
 
@@ -60,4 +60,4 @@ protected:
     void adjust_volume() override;
 };
 
-#endif // __AC_MYMIDI_H
+#endif
diff --git a/engines/ags/engine/media/audio/clip_mymp3.h b/engines/ags/engine/media/audio/clip_mymp3.h
index cf5ee292fd..c7cde052f1 100644
--- a/engines/ags/engine/media/audio/clip_mymp3.h
+++ b/engines/ags/engine/media/audio/clip_mymp3.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_MYMP3_H
-#define __AC_MYMP3_H
+#ifndef AGS_ENGINE_MEDIA_AUDIO_CLIP_MYMP3_H
+#define AGS_ENGINE_MEDIA_AUDIO_CLIP_MYMP3_H
 
 #include "almp3.h"
 #include "media/audio/soundclip.h"
@@ -55,4 +55,4 @@ private:
     void adjust_stream();
 };
 
-#endif // __AC_MYMP3_H
+#endif
diff --git a/engines/ags/engine/media/audio/clip_myogg.h b/engines/ags/engine/media/audio/clip_myogg.h
index 26625f5c52..06793a8e31 100644
--- a/engines/ags/engine/media/audio/clip_myogg.h
+++ b/engines/ags/engine/media/audio/clip_myogg.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_MYOGG_H
-#define __AC_MYOGG_H
+#ifndef AGS_ENGINE_MEDIA_AUDIO_CLIP_MYOGG_H
+#define AGS_ENGINE_MEDIA_AUDIO_CLIP_MYOGG_H
 
 #include "alogg.h"
 #include "media/audio/soundclip.h"
@@ -65,4 +65,4 @@ private:
     void adjust_stream();
 };
 
-#endif // __AC_MYOGG_H
+#endif
diff --git a/engines/ags/engine/media/audio/clip_mystaticmp3.h b/engines/ags/engine/media/audio/clip_mystaticmp3.h
index a5b8031353..0c992cd0ac 100644
--- a/engines/ags/engine/media/audio/clip_mystaticmp3.h
+++ b/engines/ags/engine/media/audio/clip_mystaticmp3.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_MYSTATICMP3_H
-#define __AC_MYSTATICMP3_H
+#ifndef AGS_ENGINE_MEDIA_AUDIO_CLIP_MYSTATICMP3_H
+#define AGS_ENGINE_MEDIA_AUDIO_CLIP_MYSTATICMP3_H
 
 #include "almp3.h"
 #include "media/audio/soundclip.h"
@@ -62,4 +62,4 @@ private:
     void adjust_stream();
 };
 
-#endif // __AC_MYSTATICMP3_H
+#endif
diff --git a/engines/ags/engine/media/audio/clip_mystaticogg.h b/engines/ags/engine/media/audio/clip_mystaticogg.h
index 4e2f3a1de2..e40bc2b792 100644
--- a/engines/ags/engine/media/audio/clip_mystaticogg.h
+++ b/engines/ags/engine/media/audio/clip_mystaticogg.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_MYSTATICOGG_H
-#define __AC_MYSTATICOGG_H
+#ifndef AGS_ENGINE_MEDIA_AUDIO_CLIP_MYSTATICOGG_H
+#define AGS_ENGINE_MEDIA_AUDIO_CLIP_MYSTATICOGG_H
 
 #include "alogg.h"
 #include "media/audio/soundclip.h"
@@ -68,4 +68,4 @@ private:
     void adjust_stream();
 };
 
-#endif // __AC_MYSTATICOGG_H
+#endif
diff --git a/engines/ags/engine/media/audio/clip_mywave.h b/engines/ags/engine/media/audio/clip_mywave.h
index 094f36eedb..d80947bf53 100644
--- a/engines/ags/engine/media/audio/clip_mywave.h
+++ b/engines/ags/engine/media/audio/clip_mywave.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_MYWAVE_H
-#define __AC_MYWAVE_H
+#ifndef AGS_ENGINE_MEDIA_AUDIO_CLIP_MYWAVE_H
+#define AGS_ENGINE_MEDIA_AUDIO_CLIP_MYWAVE_H
 
 #include "media/audio/soundclip.h"
 
@@ -55,4 +55,4 @@ protected:
     void adjust_volume() override;
 };
 
-#endif // __AC_MYWAVE_H
+#endif
diff --git a/engines/ags/engine/media/audio/queuedaudioitem.h b/engines/ags/engine/media/audio/queuedaudioitem.h
index d5024de57c..7b548da50b 100644
--- a/engines/ags/engine/media/audio/queuedaudioitem.h
+++ b/engines/ags/engine/media/audio/queuedaudioitem.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_QUEUEDAUDIOITEM_H
-#define __AC_QUEUEDAUDIOITEM_H
+#ifndef AGS_ENGINE_MEDIA_AUDIO_QUEUEDAUDIOITEM_H
+#define AGS_ENGINE_MEDIA_AUDIO_QUEUEDAUDIOITEM_H
 
 struct SOUNDCLIP;
 
@@ -38,4 +38,4 @@ struct QueuedAudioItem {
     void WriteToFile(Common::Stream *out) const;
 };
 
-#endif // __AC_QUEUEDAUDIOITEM_H
+#endif
diff --git a/engines/ags/engine/media/audio/sound.h b/engines/ags/engine/media/audio/sound.h
index 67c9438e1a..0d51ffbeda 100644
--- a/engines/ags/engine/media/audio/sound.h
+++ b/engines/ags/engine/media/audio/sound.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AC_SOUND_H
-#define __AC_SOUND_H
+#ifndef AGS_ENGINE_MEDIA_AUDIO_SOUND_H
+#define AGS_ENGINE_MEDIA_AUDIO_SOUND_H
 
 #include "ac/asset_helper.h"
 #include "media/audio/soundclip.h"
@@ -42,4 +42,4 @@ SOUNDCLIP *my_load_mod(const AssetPath &asset_name, int repet);
 
 extern int use_extra_sound_offset;
 
-#endif // __AC_SOUND_H
+#endif
diff --git a/engines/ags/engine/media/audio/soundcache.h b/engines/ags/engine/media/audio/soundcache.h
index 21bb6b6b67..1943462cc2 100644
--- a/engines/ags/engine/media/audio/soundcache.h
+++ b/engines/ags/engine/media/audio/soundcache.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_SOUNDCACHE_H
-#define __AC_SOUNDCACHE_H
+#ifndef AGS_ENGINE_MEDIA_AUDIO_SOUNDCACHE_H
+#define AGS_ENGINE_MEDIA_AUDIO_SOUNDCACHE_H
 
 #include "ac/asset_helper.h"
 
@@ -53,4 +53,4 @@ void sound_cache_free(char* buffer, bool is_wave);
 char* get_cached_sound(const AssetPath &asset_name, bool is_wave, size_t &size);
 
 
-#endif // __AC_SOUNDCACHE_H
+#endif
diff --git a/engines/ags/engine/media/audio/soundclip.h b/engines/ags/engine/media/audio/soundclip.h
index 5a0d6e9a60..e2f2300fda 100644
--- a/engines/ags/engine/media/audio/soundclip.h
+++ b/engines/ags/engine/media/audio/soundclip.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AC_SOUNDCLIP_H
-#define __AC_SOUNDCLIP_H
+#ifndef AGS_ENGINE_MEDIA_AUDIO_SOUNDCLIP_H
+#define AGS_ENGINE_MEDIA_AUDIO_SOUNDCLIP_H
 
 #include "util/mutex.h"
 
@@ -177,4 +177,4 @@ protected:
     }
 };
 
-#endif // __AC_SOUNDCLIP_H
+#endif
diff --git a/engines/ags/engine/media/video/VMR9Graph.h b/engines/ags/engine/media/video/VMR9Graph.h
index 3f424dd556..2b6b52011f 100644
--- a/engines/ags/engine/media/video/VMR9Graph.h
+++ b/engines/ags/engine/media/video/VMR9Graph.h
@@ -31,7 +31,7 @@
 
 #if _MSC_VER > 1000
 #pragma once
-#endif // _MSC_VER > 1000
+#endif
 
 #include <dshow.h>
 #include <Vmr9.h>
@@ -157,4 +157,4 @@ protected:
 	IDirect3DSurface9*			m_pD3DSurface;
 };
 
-#endif // !defined(AFX_VMR9GRAPH_H__449FDB5B_6719_4134_B5A7_B651C08D109E__INCLUDED_)
+#endif
diff --git a/engines/ags/engine/media/video/video.h b/engines/ags/engine/media/video/video.h
index b627fe13ba..fd33082055 100644
--- a/engines/ags/engine/media/video/video.h
+++ b/engines/ags/engine/media/video/video.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_MEDIA__VIDEO_H
-#define __AGS_EE_MEDIA__VIDEO_H
+#ifndef AGS_ENGINE_MEDIA_VIDEO_VIDEO_H
+#define AGS_ENGINE_MEDIA_VIDEO_VIDEO_H
 
 void play_theora_video(const char *name, int skip, int flags);
 void play_flc_file(int numb,int playflags);
@@ -29,4 +29,4 @@ void play_flc_file(int numb,int playflags);
 // Update video playback if the display mode has changed
 void video_on_gfxmode_changed();
 
-#endif // __AGS_EE_MEDIA__VIDEO_H
+#endif
diff --git a/engines/ags/engine/platform/base/agsplatformdriver.h b/engines/ags/engine/platform/base/agsplatformdriver.h
index 5ce00e0e90..c8b6975c6a 100644
--- a/engines/ags/engine/platform/base/agsplatformdriver.h
+++ b/engines/ags/engine/platform/base/agsplatformdriver.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_PLATFORM__AGSPLATFORMDRIVER_H
-#define __AGS_EE_PLATFORM__AGSPLATFORMDRIVER_H
+#ifndef AGS_ENGINE_PLATFORM_BASE_AGSPLATFORMDRIVER_H
+#define AGS_ENGINE_PLATFORM_BASE_AGSPLATFORMDRIVER_H
 
 #include <errno.h>
 #include <vector>
@@ -177,4 +177,4 @@ int cd_player_control(int cmdd, int datt);
 // instance by calling AGSPlatformDriver::GetDriver()?
 extern AGSPlatformDriver *platform;
 
-#endif // __AGS_EE_PLATFORM__AGSPLATFORMDRIVER_H
+#endif
diff --git a/engines/ags/engine/platform/util/pe.h b/engines/ags/engine/platform/util/pe.h
index 060968f776..871079f4d3 100644
--- a/engines/ags/engine/platform/util/pe.h
+++ b/engines/ags/engine/platform/util/pe.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_PLATFORM_UTIL_PE_H
-#define __AGS_EE_PLATFORM_UTIL_PE_H
+#ifndef AGS_ENGINE_PLATFORM_UTIL_PE_H
+#define AGS_ENGINE_PLATFORM_UTIL_PE_H
 
 #ifdef __cplusplus
 extern "C" {
@@ -39,4 +39,4 @@ int getVersionInformation(char* filename, version_info_t* version_info);
 }
 #endif
 
-#endif // __AGS_EE_PLATFORM_UTIL_PE_H
+#endif
diff --git a/engines/ags/engine/platform/windows/debugging/namedpipesagsdebugger.cpp b/engines/ags/engine/platform/windows/debugging/namedpipesagsdebugger.cpp
new file mode 100644
index 0000000000..d540ddb7c7
--- /dev/null
+++ b/engines/ags/engine/platform/windows/debugging/namedpipesagsdebugger.cpp
@@ -0,0 +1,108 @@
+/* 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 "core/platform.h"
+
+#if AGS_PLATFORM_OS_WINDOWS
+
+#include "platform/windows/debug/namedpipesagsdebugger.h"
+
+#include <stdio.h> // sprintf
+
+void NamedPipesAGSDebugger::SendAcknowledgement()
+{
+    DWORD bytesWritten;
+    WriteFile(_hPipeSending, "MSGACK", 6, &bytesWritten, NULL);
+}
+
+
+NamedPipesAGSDebugger::NamedPipesAGSDebugger(const char *instanceToken)
+{
+    _hPipeSending = NULL;
+    _hPipeReading = NULL;
+    _instanceToken = instanceToken;
+}
+
+bool NamedPipesAGSDebugger::Initialize()
+{
+    // can't use a single duplex pipe as it was deadlocking
+    char pipeNameBuffer[MAX_PATH];
+    sprintf(pipeNameBuffer, "\\\\.\\pipe\\AGSEditorDebuggerGameToEd%s", _instanceToken);
+    _hPipeSending = CreateFile(pipeNameBuffer, GENERIC_WRITE, 0, NULL, OPEN_EXISTING,0, NULL);
+
+    sprintf(pipeNameBuffer, "\\\\.\\pipe\\AGSEditorDebuggerEdToGame%s", _instanceToken);
+    _hPipeReading = CreateFile(pipeNameBuffer, GENERIC_READ, 0, NULL, OPEN_EXISTING,0, NULL);
+
+    if ((_hPipeReading == INVALID_HANDLE_VALUE) ||
+        (_hPipeSending == INVALID_HANDLE_VALUE))
+        return false;
+
+    return true;
+}
+
+void NamedPipesAGSDebugger::Shutdown()
+{
+    if (_hPipeReading != NULL)
+    {
+        CloseHandle(_hPipeReading);
+        CloseHandle(_hPipeSending);
+        _hPipeReading = NULL;
+    }
+}
+
+bool NamedPipesAGSDebugger::SendMessageToEditor(const char *message) 
+{
+    DWORD bytesWritten;
+    return (WriteFile(_hPipeSending, message, strlen(message), &bytesWritten, NULL ) != 0);
+}
+
+bool NamedPipesAGSDebugger::IsMessageAvailable()
+{
+    DWORD bytesAvailable = 0;
+    PeekNamedPipe(_hPipeReading, NULL, 0, NULL, &bytesAvailable, NULL);
+
+    return (bytesAvailable > 0);
+}
+
+char* NamedPipesAGSDebugger::GetNextMessage()
+{
+    DWORD bytesAvailable = 0;
+    PeekNamedPipe(_hPipeReading, NULL, 0, NULL, &bytesAvailable, NULL);
+
+    if (bytesAvailable > 0)
+    {
+        char* buffer = (char*)malloc(bytesAvailable + 1);
+        DWORD bytesRead = 0;
+        ReadFile(_hPipeReading, buffer, bytesAvailable, &bytesRead, NULL);
+        buffer[bytesRead] = 0;
+
+        SendAcknowledgement();
+        return buffer;
+    }
+    else
+    {
+        return NULL;
+    }
+
+}
+
+#endif // AGS_PLATFORM_OS_WINDOWS
diff --git a/engines/ags/engine/platform/windows/debugging/namedpipesagsdebugger.h b/engines/ags/engine/platform/windows/debugging/namedpipesagsdebugger.h
new file mode 100644
index 0000000000..104e31804f
--- /dev/null
+++ b/engines/ags/engine/platform/windows/debugging/namedpipesagsdebugger.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 AGS_ENGINE_DEBUGGING_NAMEDPIPESAGSDEBUGGER_H
+#define AGS_ENGINE_DEBUGGING_NAMEDPIPESAGSDEBUGGER_H
+
+#include <windows.h>
+#include <io.h>
+#include "debug/agseditordebugger.h"
+
+struct NamedPipesAGSDebugger : IAGSEditorDebugger
+{
+private:
+    HANDLE _hPipeSending;
+    HANDLE _hPipeReading;
+    const char *_instanceToken;
+
+    void SendAcknowledgement();
+public:
+
+    NamedPipesAGSDebugger(const char *instanceToken);
+    virtual bool Initialize() override;
+    virtual void Shutdown() override;
+    virtual bool SendMessageToEditor(const char *message) override;
+    virtual bool IsMessageAvailable() override;
+    virtual char* GetNextMessage() override;
+};
+
+#endif
diff --git a/engines/ags/engine/platform/windows/gfx/ali3dd3d.h b/engines/ags/engine/platform/windows/gfx/ali3dd3d.h
index cd04214f68..f809f43a38 100644
--- a/engines/ags/engine/platform/windows/gfx/ali3dd3d.h
+++ b/engines/ags/engine/platform/windows/gfx/ali3dd3d.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_GFX__ALI3DD3D_H
-#define __AGS_EE_GFX__ALI3DD3D_H
+#ifndef AGS_ENGINE_PLATFORM_WINDOWS_ALI3DD3D_H
+#define AGS_ENGINE_PLATFORM_WINDOWS_ALI3DD3D_H
 
 #include "core/platform.h"
 
@@ -343,4 +343,4 @@ private:
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_GFX__ALI3DD3D_H
+#endif
diff --git a/engines/ags/engine/platform/windows/setup/winsetup.h b/engines/ags/engine/platform/windows/setup/winsetup.h
index ac02d809f0..0b59f4b663 100644
--- a/engines/ags/engine/platform/windows/setup/winsetup.h
+++ b/engines/ags/engine/platform/windows/setup/winsetup.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_SETUP__WINSETUP_H
-#define __AGS_EE_SETUP__WINSETUP_H
+#ifndef AGS_ENGINE_PLATFORM_WINDOWS_SETUP_WINSETUP_H
+#define AGS_ENGINE_PLATFORM_WINDOWS_SETUP_WINSETUP_H
 
 #include "util/ini_util.h"
 
@@ -45,4 +45,4 @@ SetupReturnValue WinSetup(const ConfigTree &cfg_in, ConfigTree &cfg_out,
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_SETUP__WINSETUP_H
+#endif
diff --git a/engines/ags/engine/platform/windows/win_ex_handling.h b/engines/ags/engine/platform/windows/win_ex_handling.h
index 211fcd36f1..6caa91b572 100644
--- a/engines/ags/engine/platform/windows/win_ex_handling.h
+++ b/engines/ags/engine/platform/windows/win_ex_handling.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_PLATFORM__WIN_EXCEPTION_HANDLING_H
-#define __AGS_EE_PLATFORM__WIN_EXCEPTION_HANDLING_H
+#ifndef AGS_ENGINE_PLATFORM_WINDOWS_WIN_EX_HANDLING_H
+#define AGS_ENGINE_PLATFORM_WINDOWS_WIN_EX_HANDLING_H
 
 #include "util/ini_util.h"
 
@@ -30,4 +30,4 @@ int  initialize_engine_with_exception_handling(
     int (initialize_engine)(const AGS::Common::ConfigTree &startup_opts),
     const AGS::Common::ConfigTree &startup_opts);
 
-#endif // __AGS_EE_PLATFORM__WIN_EXCEPTION_HANDLING_H
+#endif
diff --git a/engines/ags/engine/platform/windows/winapi_exclusive.h b/engines/ags/engine/platform/windows/winapi_exclusive.h
index 6b8a26f9dc..69ac06b83b 100644
--- a/engines/ags/engine/platform/windows/winapi_exclusive.h
+++ b/engines/ags/engine/platform/windows/winapi_exclusive.h
@@ -28,8 +28,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_PLATFORM__WINAPI_EXCLUSIVE_H
-#define __AGS_EE_PLATFORM__WINAPI_EXCLUSIVE_H
+#ifndef AGS_ENGINE_PLATFORM_WINDOWS_WINAPI_EXCLUSIVE_H
+#define AGS_ENGINE_PLATFORM_WINDOWS_WINAPI_EXCLUSIVE_H
 
 #ifndef _WINDOWS_ // do not include if windows.h was included first
 #define _WINDOWS_ // there can be only one
@@ -57,6 +57,6 @@ typedef HANDLE HWND;
 
 typedef int (FAR WINAPI *FARPROC)();
 
-#endif // _WINDOWS_
+#endif
 
-#endif // __AGS_EE_PLATFORM__WINAPI_EXCLUSIVE_H
+#endif
diff --git a/engines/ags/engine/plugin/agsplugin.h b/engines/ags/engine/plugin/agsplugin.h
index 0b640d84cc..a480f69053 100644
--- a/engines/ags/engine/plugin/agsplugin.h
+++ b/engines/ags/engine/plugin/agsplugin.h
@@ -28,8 +28,8 @@
 //
 //=============================================================================
 
-#ifndef _AGS_PLUGIN_H
-#define _AGS_PLUGIN_H
+#ifndef AGS_ENGINE_PLUGIN_AGSPLUGIN_H
+#define AGS_ENGINE_PLUGIN_AGSPLUGIN_H
 
 // If the plugin isn't using DDraw, don't require the headers
 #ifndef DIRECTDRAW_VERSION
diff --git a/engines/ags/engine/plugin/plugin_builtin.h b/engines/ags/engine/plugin/plugin_builtin.h
index 0bfe0c4e49..d5caec7bc2 100644
--- a/engines/ags/engine/plugin/plugin_builtin.h
+++ b/engines/ags/engine/plugin/plugin_builtin.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_PLUGIN__PLUGINBUILTIN_H
-#define __AGS_EE_PLUGIN__PLUGINBUILTIN_H
+#ifndef AGS_ENGINE_PLUGIN_PLUGIN_BUILTIN_H
+#define AGS_ENGINE_PLUGIN_PLUGIN_BUILTIN_H
 
 #define PLUGIN_FILENAME_MAX (49)
 
@@ -49,4 +49,4 @@ struct InbuiltPluginDetails {
 // Register a builtin plugin.
 int pl_register_builtin_plugin(InbuiltPluginDetails const &details);
 
-#endif // __AGS_EE_PLUGIN__PLUGINBUILTIN_H
+#endif
diff --git a/engines/ags/engine/plugin/plugin_engine.h b/engines/ags/engine/plugin/plugin_engine.h
index 3c90f3775c..9c6f1282e3 100644
--- a/engines/ags/engine/plugin/plugin_engine.h
+++ b/engines/ags/engine/plugin/plugin_engine.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_PLUGIN__PLUGINENGINE_H
-#define __AGS_EE_PLUGIN__PLUGINENGINE_H
+#ifndef AGS_ENGINE_PLUGIN_PLUGIN_ENGINE_H
+#define AGS_ENGINE_PLUGIN_PLUGIN_ENGINE_H
 
 #include <vector>
 #include "game/game_init.h"
@@ -54,4 +54,4 @@ bool pl_any_want_hook(int event);
 void pl_set_file_handle(long data, AGS::Common::Stream *stream);
 void pl_clear_file_handle();
 
-#endif // __AGS_EE_PLUGIN__PLUGINENGINE_H
+#endif
diff --git a/engines/ags/engine/plugin/pluginobjectreader.h b/engines/ags/engine/plugin/pluginobjectreader.h
index 00cb03c569..a768ad00dc 100644
--- a/engines/ags/engine/plugin/pluginobjectreader.h
+++ b/engines/ags/engine/plugin/pluginobjectreader.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_PLUGIN__PLUGINOBJECTREADER_H
-#define __AGS_EE_PLUGIN__PLUGINOBJECTREADER_H
+#ifndef AGS_ENGINE_PLUGIN_PLUGINOBJECTREADER_H
+#define AGS_ENGINE_PLUGIN_PLUGINOBJECTREADER_H
 
 class IAGSManagedObjectReader;
 
@@ -30,4 +30,4 @@ struct PluginObjectReader {
     const char *type;
 };
 
-#endif // __AGS_EE_PLUGIN__PLUGINOBJECTREADER_H
+#endif
diff --git a/engines/ags/engine/script/cc_instance.h b/engines/ags/engine/script/cc_instance.h
index f01ac4a975..725f3681e6 100644
--- a/engines/ags/engine/script/cc_instance.h
+++ b/engines/ags/engine/script/cc_instance.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __CC_INSTANCE_H
-#define __CC_INSTANCE_H
+#ifndef AGS_ENGINE_SCRIPT_CCINSTANCE_H
+#define AGS_ENGINE_SCRIPT_CCINSTANCE_H
 
 #include <memory>
 #include <unordered_map>
@@ -228,4 +228,4 @@ protected:
     void    PopFromFuncCallStack(FunctionCallStack &func_callstack, int32_t num_entries);
 };
 
-#endif // __CC_INSTANCE_H
+#endif
diff --git a/engines/ags/engine/script/executingscript.h b/engines/ags/engine/script/executingscript.h
index ffe68fcc37..1d09f6781b 100644
--- a/engines/ags/engine/script/executingscript.h
+++ b/engines/ags/engine/script/executingscript.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_SCRIPT__EXECUTINGSCRIPT_H
-#define __AGS_EE_SCRIPT__EXECUTINGSCRIPT_H
+#ifndef AGS_ENGINE_SCRIPT_EXECUTINGSCRIPT_H
+#define AGS_ENGINE_SCRIPT_EXECUTINGSCRIPT_H
 
 #include "script/cc_instance.h"
 
@@ -76,4 +76,4 @@ struct ExecutingScript {
     ExecutingScript();
 };
 
-#endif // __AGS_EE_SCRIPT__EXECUTINGSCRIPT_H
+#endif
diff --git a/engines/ags/engine/script/exports.h b/engines/ags/engine/script/exports.h
index 0829c9557e..81459c6fdc 100644
--- a/engines/ags/engine/script/exports.h
+++ b/engines/ags/engine/script/exports.h
@@ -26,9 +26,9 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_SCRIPT__EXPORTS_H
-#define __AGS_EE_SCRIPT__EXPORTS_H
+#ifndef AGS_ENGINE_SCRIPT_EXPORTS_H
+#define AGS_ENGINE_SCRIPT_EXPORTS_H
 
 void setup_script_exports(ScriptAPIVersion base_api, ScriptAPIVersion compat_api);
 
-#endif // __AGS_EE_SCRIPT__EXPORTS_H
+#endif
diff --git a/engines/ags/engine/script/nonblockingscriptfunction.h b/engines/ags/engine/script/nonblockingscriptfunction.h
index d924296809..61b6af8001 100644
--- a/engines/ags/engine/script/nonblockingscriptfunction.h
+++ b/engines/ags/engine/script/nonblockingscriptfunction.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_SCRIPT__NONBLOCKINGSCRIPTFUNCTION_H
-#define __AGS_EE_SCRIPT__NONBLOCKINGSCRIPTFUNCTION_H
+#ifndef AGS_ENGINE_SCRIPT_NONBLOCKINGSCRIPTFUNCTION_H
+#define AGS_ENGINE_SCRIPT_NONBLOCKINGSCRIPTFUNCTION_H
 
 #include "ac/runtime_defines.h"
 #include "script/runtimescriptvalue.h"
@@ -50,4 +50,4 @@ struct NonBlockingScriptFunction
     }
 };
 
-#endif // __AGS_EE_SCRIPT__NONBLOCKINGSCRIPTFUNCTION_H
+#endif
diff --git a/engines/ags/engine/script/runtimescriptvalue.h b/engines/ags/engine/script/runtimescriptvalue.h
index 85b1b716a6..7397a8346c 100644
--- a/engines/ags/engine/script/runtimescriptvalue.h
+++ b/engines/ags/engine/script/runtimescriptvalue.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_SCRIPT__RUNTIMESCRIPTVALUE_H
-#define __AGS_EE_SCRIPT__RUNTIMESCRIPTVALUE_H
+#ifndef AGS_ENGINE_SCRIPT_RUNTIMESCRIPTVALUE_H
+#define AGS_ENGINE_SCRIPT_RUNTIMESCRIPTVALUE_H
 
 #include "script/script_api.h"
 #include "util/memory.h"
@@ -393,4 +393,4 @@ public:
     intptr_t           GetDirectPtr() const;
 };
 
-#endif // __AGS_EE_SCRIPT__RUNTIMESCRIPTVALUE_H
+#endif
diff --git a/engines/ags/engine/script/script.h b/engines/ags/engine/script/script.h
index 7404f776ac..68ac9d598b 100644
--- a/engines/ags/engine/script/script.h
+++ b/engines/ags/engine/script/script.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_SCRIPT__SCRIPT_H
-#define __AGS_EE_SCRIPT__SCRIPT_H
+#ifndef AGS_ENGINE_SCRIPT_SCRIPT_H
+#define AGS_ENGINE_SCRIPT_SCRIPT_H
 
 #include <vector>
 
@@ -121,4 +121,4 @@ extern std::vector<AGS::Common::String> characterScriptObjNames;
 extern AGS::Common::String objectScriptObjNames[MAX_ROOM_OBJECTS];
 extern std::vector<AGS::Common::String> guiScriptObjNames;
 
-#endif // __AGS_EE_SCRIPT__SCRIPT_H
+#endif
diff --git a/engines/ags/engine/script/script_api.h b/engines/ags/engine/script/script_api.h
index 601ace14f7..e333c7dc86 100644
--- a/engines/ags/engine/script/script_api.h
+++ b/engines/ags/engine/script/script_api.h
@@ -27,8 +27,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_SCRIPT__SCRIPTAPI_H
-#define __AGS_EE_SCRIPT__SCRIPTAPI_H
+#ifndef AGS_ENGINE_SCRIPT_SCRIPTAPI_H
+#define AGS_ENGINE_SCRIPT_SCRIPTAPI_H
 
 #include <stdarg.h>
 #include "core/types.h"
@@ -558,4 +558,4 @@ inline const char *ScriptVSprintf(char *buffer, size_t buf_length, const char *f
     RET_CLASS* ret_obj = METHOD((CLASS*)self, (P1CLASS*)params[0].Ptr); \
     return RuntimeScriptValue().SetDynamicObject(ret_obj, ret_obj)
 
-#endif // __AGS_EE_SCRIPT__SCRIPTAPI_H
+#endif
diff --git a/engines/ags/engine/script/script_runtime.h b/engines/ags/engine/script/script_runtime.h
index af636ab774..a98f075f5f 100644
--- a/engines/ags/engine/script/script_runtime.h
+++ b/engines/ags/engine/script/script_runtime.h
@@ -34,8 +34,8 @@
 //
 //=============================================================================
 
-#ifndef __CS_RUNTIME_H
-#define __CS_RUNTIME_H
+#ifndef AGS_ENGINE_SCRIPT_SCRIPT_RUNTIME_H
+#define AGS_ENGINE_SCRIPT_SCRIPT_RUNTIME_H
 
 #include "script/cc_script.h"      // ccScript
 #include "script/cc_instance.h"    // ccInstance
@@ -74,7 +74,6 @@ extern void *ccGetSymbolAddressForPlugin(const String &name);
 // DEBUG HOOK
 typedef void (*new_line_hook_type) (ccInstance *, int);
 extern void ccSetDebugHook(new_line_hook_type jibble);
-#endif
 
 // Set the number of while loop iterations that aborts the script
 extern void ccSetScriptAliveTimer (int);
@@ -83,3 +82,5 @@ extern void ccNotifyScriptStillAlive ();
 // for calling exported plugin functions old-style
 extern int call_function(intptr_t addr, const RuntimeScriptValue *object, int numparm, const RuntimeScriptValue *parms);
 extern void nullfree(void *data); // in script/script_runtime
+
+#endif
diff --git a/engines/ags/engine/script/systemimports.h b/engines/ags/engine/script/systemimports.h
index 90dc7ea968..99392bdadd 100644
--- a/engines/ags/engine/script/systemimports.h
+++ b/engines/ags/engine/script/systemimports.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __CC_SYSTEMIMPORTS_H
-#define __CC_SYSTEMIMPORTS_H
+#ifndef AGS_ENGINE_SCRIPT_SYSTEMIMPORTS_H
+#define AGS_ENGINE_SCRIPT_SYSTEMIMPORTS_H
 
 #include <map>
 #include "script/cc_instance.h"    // ccInstance
@@ -68,4 +68,4 @@ extern SystemImports simp;
 // perform old style unsafe function calls
 extern SystemImports simp_for_plugin;
 
-#endif  // __CC_SYSTEMIMPORTS_H
+#endif
diff --git a/engines/ags/engine/util/library.h b/engines/ags/engine/util/library.h
index 7e4f7ac707..c5c6976977 100644
--- a/engines/ags/engine/util/library.h
+++ b/engines/ags/engine/util/library.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_UTIL__LIBRARY_H
-#define __AGS_EE_UTIL__LIBRARY_H
+#ifndef AGS_ENGINE_UTIL_LIBRARY_H
+#define AGS_ENGINE_UTIL_LIBRARY_H
 
 #include "core/platform.h"
 #include "util/string.h"
@@ -31,7 +31,6 @@ namespace AGS
 namespace Engine
 {
 
-
 class BaseLibrary
 {
 public:
@@ -66,5 +65,4 @@ public:
 
 #endif
 
-
-#endif // __AGS_EE_UTIL__MUTEX_H
+#endif
diff --git a/engines/ags/engine/util/library_dummy.h b/engines/ags/engine/util/library_dummy.h
index dd22849d5b..189f5c6110 100644
--- a/engines/ags/engine/util/library_dummy.h
+++ b/engines/ags/engine/util/library_dummy.h
@@ -20,9 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_UTIL__LIBRARY_DUMMY_H
-#define __AGS_EE_UTIL__LIBRARY_DUMMY_H
-
+#ifndef AGS_ENGINE_UTIL_LIBRARY_DUMMY_H
+#define AGS_ENGINE_UTIL_LIBRARY_DUMMY_H
 
 namespace AGS
 {
@@ -70,6 +69,4 @@ typedef DummyLibrary Library;
 } // namespace Engine
 } // namespace AGS
 
-
-
-#endif // __AGS_EE_UTIL__LIBRARY_DUMMY_H
+#endif
diff --git a/engines/ags/engine/util/library_posix.h b/engines/ags/engine/util/library_posix.h
index 1b738d230f..4cf166ed18 100644
--- a/engines/ags/engine/util/library_posix.h
+++ b/engines/ags/engine/util/library_posix.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_UTIL__LIBRARY_POSIX_H
-#define __AGS_EE_UTIL__LIBRARY_POSIX_H
+#ifndef AGS_ENGINE_UTIL_LIBRARY_POSIX_H
+#define AGS_ENGINE_UTIL_LIBRARY_POSIX_H
 
 #include <dlfcn.h>
 #include "core/platform.h"
@@ -156,6 +156,4 @@ typedef PosixLibrary Library;
 } // namespace Engine
 } // namespace AGS
 
-
-
-#endif // __AGS_EE_UTIL__LIBRARY_POSIX_H
+#endif
diff --git a/engines/ags/engine/util/library_psp.h b/engines/ags/engine/util/library_psp.h
index 0ab345d4af..845f7b35f7 100644
--- a/engines/ags/engine/util/library_psp.h
+++ b/engines/ags/engine/util/library_psp.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_UTIL__LIBRARY_PSP_H
-#define __AGS_EE_UTIL__LIBRARY_PSP_H
+#ifndef AGS_ENGINE_UTIL_LIBRARY_PSP_H
+#define AGS_ENGINE_UTIL_LIBRARY_PSP_H
 
 #include <pspsdk.h>
 #include "util/string.h"
@@ -155,11 +155,7 @@ private:
 
 typedef PSPLibrary Library;
 
-
-
 } // namespace Engine
 } // namespace AGS
 
-
-
-#endif // __AGS_EE_UTIL__LIBRARY_PSP_H
+#endif
diff --git a/engines/ags/engine/util/library_windows.h b/engines/ags/engine/util/library_windows.h
index 7b811689fe..27e804aafa 100644
--- a/engines/ags/engine/util/library_windows.h
+++ b/engines/ags/engine/util/library_windows.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_UTIL__LIBRARY_WINDOWS_H
-#define __AGS_EE_UTIL__LIBRARY_WINDOWS_H
+#ifndef AGS_ENGINE_UTIL_LIBRARY_WINDOWS_H
+#define AGS_ENGINE_UTIL_LIBRARY_WINDOWS_H
 
 #include "debug/out.h"
 #include "platform/windows/winapi_exclusive.h"
@@ -118,6 +118,4 @@ typedef WindowsLibrary Library;
 } // namespace Engine
 } // namespace AGS
 
-
-
-#endif // __AGS_EE_UTIL__LIBRARY_WINDOWS_H
+#endif
diff --git a/engines/ags/engine/util/mutex.h b/engines/ags/engine/util/mutex.h
index b559680af4..7919a1c442 100644
--- a/engines/ags/engine/util/mutex.h
+++ b/engines/ags/engine/util/mutex.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_UTIL__MUTEX_H
-#define __AGS_EE_UTIL__MUTEX_H
+#ifndef AGS_ENGINE_UTIL_MUTEX_H
+#define AGS_ENGINE_UTIL_MUTEX_H
 
 namespace AGS
 {
@@ -55,4 +55,4 @@ public:
 #include "mutex_std.h"
 #endif
 
-#endif // __AGS_EE_UTIL__MUTEX_H
+#endif
diff --git a/engines/ags/engine/util/mutex_base.h b/engines/ags/engine/util/mutex_base.h
index 9329f1c2a9..e4d63f48e5 100644
--- a/engines/ags/engine/util/mutex_base.h
+++ b/engines/ags/engine/util/mutex_base.h
@@ -20,9 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_PLATFORM__MUTEX_BASE_H
-#define __AGS_EE_PLATFORM__MUTEX_BASE_H
-
+#ifndef AGS_ENGINE_UTIL_MUTEX_BASE_H
+#define AGS_ENGINE_UTIL_MUTEX_BASE_H
 
 namespace AGS
 {
@@ -43,4 +42,4 @@ public:
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_EE_PLATFORM__MUTEX_BASE_H
+#endif
diff --git a/engines/ags/engine/util/mutex_lock.h b/engines/ags/engine/util/mutex_lock.h
index c9561d95c9..a6d5873991 100644
--- a/engines/ags/engine/util/mutex_lock.h
+++ b/engines/ags/engine/util/mutex_lock.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_UTIL__MUTEX_LOCK_H
-#define __AGS_EE_UTIL__MUTEX_LOCK_H
+#ifndef AGS_ENGINE_UTIL_MUTEX_LOCK_H
+#define AGS_ENGINE_UTIL_MUTEX_LOCK_H
 
 #include "util/mutex.h"
 
@@ -71,4 +71,4 @@ public:
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_UTIL__MUTEX_LOCK_H
+#endif
diff --git a/engines/ags/engine/util/mutex_psp.h b/engines/ags/engine/util/mutex_psp.h
index 81920a28af..8e40697e8b 100644
--- a/engines/ags/engine/util/mutex_psp.h
+++ b/engines/ags/engine/util/mutex_psp.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_UTIL__PSP_MUTEX_H
-#define __AGS_EE_UTIL__PSP_MUTEX_H
+#ifndef AGS_ENGINE_UTIL_PSP_MUTEX_H
+#define AGS_ENGINE_UTIL_PSP_MUTEX_H
 
 #include <pspsdk.h>
 #include <pspkernel.h>
@@ -67,4 +67,4 @@ typedef PSPMutex Mutex;
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_UTIL__PSP_MUTEX_H
+#endif
diff --git a/engines/ags/engine/util/mutex_pthread.h b/engines/ags/engine/util/mutex_pthread.h
index 940531b19e..9716e3f7fd 100644
--- a/engines/ags/engine/util/mutex_pthread.h
+++ b/engines/ags/engine/util/mutex_pthread.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_UTIL__MUTEX_PTHREAD_H
-#define __AGS_EE_UTIL__MUTEX_PTHREAD_H
+#ifndef AGS_ENGINE_UTIL_MUTEX_PTHREAD_H
+#define AGS_ENGINE_UTIL_MUTEX_PTHREAD_H
 
 #include <pthread.h>
 
@@ -64,4 +64,4 @@ typedef PThreadMutex Mutex;
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_UTIL__MUTEX_PTHREAD_H
+#endif
diff --git a/engines/ags/engine/util/mutex_std.h b/engines/ags/engine/util/mutex_std.h
index 137c132108..28ad2f44ff 100644
--- a/engines/ags/engine/util/mutex_std.h
+++ b/engines/ags/engine/util/mutex_std.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_UTIL__MUTEX_STD_H
-#define __AGS_EE_UTIL__MUTEX_STD_H
+#ifndef AGS_ENGINE_UTIL_MUTEX_STD_H
+#define AGS_ENGINE_UTIL_MUTEX_STD_H
 
 #include <mutex>
 
@@ -51,4 +51,4 @@ typedef StdMutex Mutex;
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_UTIL__MUTEX_STD_H
+#endif
diff --git a/engines/ags/engine/util/mutex_wii.h b/engines/ags/engine/util/mutex_wii.h
index 93ae9f3b74..fbc635993d 100644
--- a/engines/ags/engine/util/mutex_wii.h
+++ b/engines/ags/engine/util/mutex_wii.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_UTIL__WII_MUTEX_H
-#define __AGS_EE_UTIL__WII_MUTEX_H
+#ifndef AGS_ENGINE_UTIL_WII_MUTEX_H
+#define AGS_ENGINE_UTIL_WII_MUTEX_H
 
 #include <gccore.h>
 
@@ -65,4 +65,4 @@ typedef WiiMutex Mutex;
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_UTIL__WII_MUTEX_H
+#endif
diff --git a/engines/ags/engine/util/mutex_windows.h b/engines/ags/engine/util/mutex_windows.h
index 0e3c4c0ba5..4f4748451c 100644
--- a/engines/ags/engine/util/mutex_windows.h
+++ b/engines/ags/engine/util/mutex_windows.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_UTIL__WINDOWS_MUTEX_H
-#define __AGS_EE_UTIL__WINDOWS_MUTEX_H
+#ifndef AGS_ENGINE_UTIL_MUTEXT_WINDOWS_H
+#define AGS_ENGINE_UTIL_MUTEXT_WINDOWS_H
 
 namespace AGS
 {
@@ -71,4 +71,4 @@ typedef WindowsMutex Mutex;
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_UTIL__WINDOWS_MUTEX_H
+#endif
diff --git a/engines/ags/engine/util/scaling.h b/engines/ags/engine/util/scaling.h
index 8ccf81e9bc..d8c2b1e6cd 100644
--- a/engines/ags/engine/util/scaling.h
+++ b/engines/ags/engine/util/scaling.h
@@ -29,8 +29,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_EE_UTIL__SCALING_H
-#define __AGS_EE_UTIL__SCALING_H
+#ifndef AGS_ENGINE_UTIL_SCALING_H
+#define AGS_ENGINE_UTIL_SCALING_H
 
 #include "core/types.h"
 #include "util/geometry.h"
@@ -181,4 +181,4 @@ struct PlaneScaling
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_UTIL__SCALING_H
+#endif
diff --git a/engines/ags/engine/util/thread.h b/engines/ags/engine/util/thread.h
index 8a64b3caa5..00625915a6 100644
--- a/engines/ags/engine/util/thread.h
+++ b/engines/ags/engine/util/thread.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_UTIL__THREAD_H
-#define __AGS_EE_UTIL__THREAD_H
+#ifndef AGS_ENGINE_UTIL_THREAD_H
+#define AGS_ENGINE_UTIL_THREAD_H
 
 namespace AGS
 {
@@ -61,4 +61,4 @@ public:
 #endif
 
 
-#endif // __AGS_EE_UTIL__THREAD_H
+#endif
diff --git a/engines/ags/engine/util/thread_psp.h b/engines/ags/engine/util/thread_psp.h
index 1439f6a768..10d7d059ed 100644
--- a/engines/ags/engine/util/thread_psp.h
+++ b/engines/ags/engine/util/thread_psp.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_UTIL__PSP_THREAD_H
-#define __AGS_EE_UTIL__PSP_THREAD_H
+#ifndef AGS_ENGINE_UTIL_PSP_THREAD_H
+#define AGS_ENGINE_UTIL_PSP_THREAD_H
 
 #include <pspsdk.h>
 #include <pspkernel.h>
@@ -120,4 +120,4 @@ typedef PSPThread Thread;
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_UTIL__PSP_THREAD_H
+#endif
diff --git a/engines/ags/engine/util/thread_pthread.h b/engines/ags/engine/util/thread_pthread.h
index ebfad040b9..5a8ecc6a87 100644
--- a/engines/ags/engine/util/thread_pthread.h
+++ b/engines/ags/engine/util/thread_pthread.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_PLATFORM__THREAD_PTHREAD_H
-#define __AGS_EE_PLATFORM__THREAD_PTHREAD_H
+#ifndef AGS_ENGINE_UTIL_THREAD_PTHREAD_H
+#define AGS_ENGINE_UTIL_THREAD_PTHREAD_H
 
 #include <pthread.h>
 
@@ -119,4 +119,4 @@ typedef PThreadThread Thread;
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_PLATFORM__THREAD_PTHREAD_H
+#endif
diff --git a/engines/ags/engine/util/thread_std.h b/engines/ags/engine/util/thread_std.h
index bb56882d0a..8bb4501ef3 100644
--- a/engines/ags/engine/util/thread_std.h
+++ b/engines/ags/engine/util/thread_std.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_PLATFORM__THREAD_STD_H
-#define __AGS_EE_PLATFORM__THREAD_STD_H
+#ifndef AGS_ENGINE_UTIL_THREAD_STD_H
+#define AGS_ENGINE_UTIL_THREAD_STD_H
 
 #include <system_error>
 #include <thread>
@@ -102,4 +102,4 @@ typedef StdThread Thread;
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_PLATFORM__THREAD_STD_H
+#endif
diff --git a/engines/ags/engine/util/thread_wii.h b/engines/ags/engine/util/thread_wii.h
index f4baec16ae..134ded3f9f 100644
--- a/engines/ags/engine/util/thread_wii.h
+++ b/engines/ags/engine/util/thread_wii.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_PLATFORM__THREAD_WII_H
-#define __AGS_EE_PLATFORM__THREAD_WII_H
+#ifndef AGS_ENGINE_UTIL_THREAD_WII_H
+#define AGS_ENGINE_UTIL_THREAD_WII_H
 
 #include <gccore.h>
 
@@ -119,4 +119,4 @@ typedef WiiThread Thread;
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_PLATFORM__THREAD_WII_H
+#endif
diff --git a/engines/ags/engine/util/thread_windows.h b/engines/ags/engine/util/thread_windows.h
index d8a09cf1be..a27c4018ad 100644
--- a/engines/ags/engine/util/thread_windows.h
+++ b/engines/ags/engine/util/thread_windows.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_EE_PLATFORM__THREAD_WINDOWS_H
-#define __AGS_EE_PLATFORM__THREAD_WINDOWS_H
+#ifndef AGS_ENGINE_UTIL_THREAD_WINDOWS_H
+#define AGS_ENGINE_UTIL_THREAD_WINDOWS_H
 
 namespace AGS
 {
@@ -120,4 +120,4 @@ typedef WindowsThread Thread;
 } // namespace Engine
 } // namespace AGS
 
-#endif // __AGS_EE_PLATFORM__THREAD_WINDOWS_H
+#endif
diff --git a/engines/ags/shared/ac/audiocliptype.h b/engines/ags/shared/ac/audiocliptype.h
index 80628d3f05..c7997705fb 100644
--- a/engines/ags/shared/ac/audiocliptype.h
+++ b/engines/ags/shared/ac/audiocliptype.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_AUDIOCLIPTYPE_H
-#define __AC_AUDIOCLIPTYPE_H
+#ifndef AGS_SHARED_AC_AUDIOCLIPTYPE_H
+#define AGS_SHARED_AC_AUDIOCLIPTYPE_H
 
 // Forward declaration
 namespace AGS { namespace Common { class Stream; } }
@@ -41,4 +41,4 @@ struct AudioClipType {
     void WriteToSavegame(Common::Stream *out) const;
 };
 
-#endif // __AC_AUDIOCLIPTYPE_H
+#endif
diff --git a/engines/ags/shared/ac/characterinfo.h b/engines/ags/shared/ac/characterinfo.h
index adafa53d82..614179ec66 100644
--- a/engines/ags/shared/ac/characterinfo.h
+++ b/engines/ags/shared/ac/characterinfo.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_CHARACTERINFO_H
-#define __AC_CHARACTERINFO_H
+#ifndef AGS_SHARED_AC_CHARACTERINFO_H
+#define AGS_SHARED_AC_CHARACTERINFO_H
 
 #include "ac/common_defines.h" // constants
 
@@ -149,4 +149,4 @@ struct OldCharacterInfo {
 #define COPY_CHAR_VAR(name) ci->name = oci->name
 void ConvertOldCharacterToNew (OldCharacterInfo *oci, CharacterInfo *ci);
 
-#endif // __AC_CHARACTERINFO_H
+#endif
diff --git a/engines/ags/shared/ac/common.h b/engines/ags/shared/ac/common.h
index 54b7e87ede..2d857485f6 100644
--- a/engines/ags/shared/ac/common.h
+++ b/engines/ags/shared/ac/common.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_COMMON_H
-#define __AC_COMMON_H
+#ifndef AGS_SHARED_AC_COMMON_H
+#define AGS_SHARED_AC_COMMON_H
 
 // These are the project-dependent functions, they are defined both in Engine.App and AGS.Native.
 void quit(const char *);
@@ -32,4 +32,4 @@ int  get_our_eip();
 
 extern const char *game_file_sig;
 
-#endif // __AC_COMMON_H
+#endif
diff --git a/engines/ags/shared/ac/common_defines.h b/engines/ags/shared/ac/common_defines.h
index 9cf5bfa55d..c7b658005e 100644
--- a/engines/ags/shared/ac/common_defines.h
+++ b/engines/ags/shared/ac/common_defines.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_DEFINES_H
-#define __AC_DEFINES_H
+#ifndef AGS_SHARED_AC_DEFINES_H
+#define AGS_SHARED_AC_DEFINES_H
 
 #include "core/platform.h"
 
@@ -128,4 +128,4 @@
 #define OBJF_LEGACY_LOCKED  0x40  // object position is locked in the editor (OBSOLETE since 3.5.0)
 #define OBJF_HASLIGHT       0x80  // the tint_light is valid and treated as brightness
 
-#endif // __AC_DEFINES_H
+#endif
diff --git a/engines/ags/shared/ac/dialogtopic.h b/engines/ags/shared/ac/dialogtopic.h
index e26b7284b9..431123b062 100644
--- a/engines/ags/shared/ac/dialogtopic.h
+++ b/engines/ags/shared/ac/dialogtopic.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_CN_AC__DIALOGTOPIC_H
-#define __AGS_CN_AC__DIALOGTOPIC_H
+#ifndef AGS_SHARED_AC_DIALOGTOPIC_H
+#define AGS_SHARED_AC_DIALOGTOPIC_H
 
 namespace AGS { namespace Common { class Stream; } }
 using namespace AGS; // FIXME later
@@ -70,4 +70,4 @@ struct DialogTopic {
 };
 
 
-#endif // __AGS_CN_AC__DIALOGTOPIC_H
+#endif
diff --git a/engines/ags/shared/ac/dynobj/scriptaudioclip.h b/engines/ags/shared/ac/dynobj/scriptaudioclip.h
index a9165dadbb..adad724dcd 100644
--- a/engines/ags/shared/ac/dynobj/scriptaudioclip.h
+++ b/engines/ags/shared/ac/dynobj/scriptaudioclip.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_CN_DYNOBJ__SCRIPTAUDIOCLIP_H
-#define __AGS_CN_DYNOBJ__SCRIPTAUDIOCLIP_H
+#ifndef AGS_SHARED_AC_DYNOBJ_SCRIPTAUDIOCLIP_H
+#define AGS_SHARED_AC_DYNOBJ_SCRIPTAUDIOCLIP_H
 
 #include "util/string.h"
 
@@ -56,4 +56,4 @@ struct ScriptAudioClip {
     void ReadFromFile(Common::Stream *in);
 };
 
-#endif // __AGS_CN_DYNOBJ__SCRIPTAUDIOCLIP_H
+#endif
diff --git a/engines/ags/shared/ac/game_version.h b/engines/ags/shared/ac/game_version.h
index 745f181e8c..7706953f85 100644
--- a/engines/ags/shared/ac/game_version.h
+++ b/engines/ags/shared/ac/game_version.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_AC__GAMEVERSION_H
-#define __AGS_CN_AC__GAMEVERSION_H
+#ifndef AGS_SHARED_AC_GAMEVERSION_H
+#define AGS_SHARED_AC_GAMEVERSION_H
 
 /*
 
@@ -153,4 +153,4 @@ enum GameDataVersion
 
 extern GameDataVersion loaded_game_file_version;
 
-#endif // __AGS_CN_AC__GAMEVERSION_H
+#endif
diff --git a/engines/ags/shared/ac/gamesetupstruct.h b/engines/ags/shared/ac/gamesetupstruct.h
index b7f97cf632..dce49ef7d8 100644
--- a/engines/ags/shared/ac/gamesetupstruct.h
+++ b/engines/ags/shared/ac/gamesetupstruct.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_CN_AC__GAMESETUPSTRUCT_H
-#define __AGS_CN_AC__GAMESETUPSTRUCT_H
+#ifndef AGS_SHARED_AC_GAMESETUPSTRUCT_H
+#define AGS_SHARED_AC_GAMESETUPSTRUCT_H
 
 #include <vector>
 #include "ac/audiocliptype.h"
@@ -167,4 +167,4 @@ void ConvertOldGameStruct (OldGameSetupStruct *ogss, GameSetupStruct *gss);
 // Finds an audio clip using legacy convention index
 ScriptAudioClip* GetAudioClipForOldStyleNumber(GameSetupStruct &game, bool is_music, int num);
 
-#endif // __AGS_CN_AC__GAMESETUPSTRUCT_H
+#endif
diff --git a/engines/ags/shared/ac/gamesetupstructbase.h b/engines/ags/shared/ac/gamesetupstructbase.h
index bb3fdaffa8..1dd2c6fc2a 100644
--- a/engines/ags/shared/ac/gamesetupstructbase.h
+++ b/engines/ags/shared/ac/gamesetupstructbase.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_CN_AC__GAMESETUPSTRUCTBASE_H
-#define __AGS_CN_AC__GAMESETUPSTRUCTBASE_H
+#ifndef AGS_SHARED_AC_GAMESETUPSTRUCTBASE_H
+#define AGS_SHARED_AC_GAMESETUPSTRUCTBASE_H
 
 #include "ac/game_version.h"
 #include "ac/gamestructdefines.h"
@@ -224,4 +224,4 @@ private:
     int _screenUpscaleMult;
 };
 
-#endif // __AGS_CN_AC__GAMESETUPSTRUCTBASE_H
+#endif
diff --git a/engines/ags/shared/ac/gamestructdefines.h b/engines/ags/shared/ac/gamestructdefines.h
index 4458a7de49..d079c08d0b 100644
--- a/engines/ags/shared/ac/gamestructdefines.h
+++ b/engines/ags/shared/ac/gamestructdefines.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_CN_AC__GAMESTRUCTDEFINES_H
-#define __AGS_CN_AC__GAMESTRUCTDEFINES_H
+#ifndef AGS_SHARED_AC_GAMESTRUCTDEFINES_H
+#define AGS_SHARED_AC_GAMESTRUCTDEFINES_H
 
 #include "util/geometry.h"
 #include "core/types.h"
@@ -258,4 +258,4 @@ struct FontInfo
     FontInfo();
 };
 
-#endif // __AGS_CN_AC__GAMESTRUCTDEFINES_H
+#endif
diff --git a/engines/ags/shared/ac/interfacebutton.h b/engines/ags/shared/ac/interfacebutton.h
index 1f0caa63c2..b5990dda81 100644
--- a/engines/ags/shared/ac/interfacebutton.h
+++ b/engines/ags/shared/ac/interfacebutton.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_INTERFACEBUTTON_H
-#define __AC_INTERFACEBUTTON_H
+#ifndef AGS_SHARED_AC_INTERFACEBUTTON_H
+#define AGS_SHARED_AC_INTERFACEBUTTON_H
 
 #define MAXBUTTON       20
 #define IBFLG_ENABLED   1
@@ -34,4 +34,4 @@ struct InterfaceButton {
     void set(int xx, int yy, int picc, int overpicc, int actionn);
 };
 
-#endif // __AC_INTERFACEBUTTON_H
+#endif
diff --git a/engines/ags/shared/ac/interfaceelement.h b/engines/ags/shared/ac/interfaceelement.h
index 0a899d0bcc..4ecd3d5116 100644
--- a/engines/ags/shared/ac/interfaceelement.h
+++ b/engines/ags/shared/ac/interfaceelement.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_INTERFACEELEMENT_H
-#define __AC_INTERFACEELEMENT_H
+#ifndef AGS_SHARED_AC_INTERFACEELEMENT_H
+#define AGS_SHARED_AC_INTERFACEELEMENT_H
 
 #include "ac/interfacebutton.h" // InterfaceButton
 
@@ -56,4 +56,4 @@ button[0].set(0,13,3,-1,0);
 }
 };*/
 
-#endif // __AC_INTERFACEELEMENT_H
+#endif
diff --git a/engines/ags/shared/ac/inventoryiteminfo.h b/engines/ags/shared/ac/inventoryiteminfo.h
index 79d7e8360d..1506622a52 100644
--- a/engines/ags/shared/ac/inventoryiteminfo.h
+++ b/engines/ags/shared/ac/inventoryiteminfo.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_INVENTORYITEMINFO_H
-#define __AC_INVENTORYITEMINFO_H
+#ifndef AGS_SHARED_AC_INVENTORYITEMINFO_H
+#define AGS_SHARED_AC_INVENTORYITEMINFO_H
 
 namespace AGS { namespace Common { class Stream; } }
 using namespace AGS; // FIXME later
@@ -40,4 +40,4 @@ struct InventoryItemInfo {
     void WriteToSavegame(Common::Stream *out) const;
 };
 
-#endif // __AC_INVENTORYITEMINFO_H
+#endif
diff --git a/engines/ags/shared/ac/mousecursor.h b/engines/ags/shared/ac/mousecursor.h
index fc7294fe7f..732b6b49fc 100644
--- a/engines/ags/shared/ac/mousecursor.h
+++ b/engines/ags/shared/ac/mousecursor.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_MOUSECURSOR_H
-#define __AC_MOUSECURSOR_H
+#ifndef AGS_SHARED_AC_MOUSECURSOR_H
+#define AGS_SHARED_AC_MOUSECURSOR_H
 
 namespace AGS { namespace Common { class Stream; } }
 using namespace AGS; // FIXME later
@@ -45,4 +45,4 @@ struct MouseCursor {
     void WriteToSavegame(Common::Stream *out) const;
 };
 
-#endif // __AC_MOUSECURSOR_H
+#endif
diff --git a/engines/ags/shared/ac/oldgamesetupstruct.h b/engines/ags/shared/ac/oldgamesetupstruct.h
index fa24eb727f..b0cd0f23d9 100644
--- a/engines/ags/shared/ac/oldgamesetupstruct.h
+++ b/engines/ags/shared/ac/oldgamesetupstruct.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_CN_AC__OLDGAMESETUPSTRUCT_H
-#define __AGS_CN_AC__OLDGAMESETUPSTRUCT_H
+#ifndef AGS_SHARED_AC_OLDGAMESETUPSTRUCT_H
+#define AGS_SHARED_AC_OLDGAMESETUPSTRUCT_H
 
 #include "ac/characterinfo.h"       // OldCharacterInfo, CharacterInfo
 #ifdef UNUSED_CODE
@@ -80,4 +80,4 @@ struct OldGameSetupStruct : public OriGameSetupStruct2 {
     unsigned char spriteflags[LEGACY_MAX_SPRITES_V25];
 };
 
-#endif // __AGS_CN_AC__OLDGAMESETUPSTRUCT_H
+#endif
diff --git a/engines/ags/shared/ac/spritecache.h b/engines/ags/shared/ac/spritecache.h
index 8d547ae80f..c1bdfe1803 100644
--- a/engines/ags/shared/ac/spritecache.h
+++ b/engines/ags/shared/ac/spritecache.h
@@ -42,8 +42,8 @@
 //
 //=============================================================================
 
-#ifndef __SPRCACHE_H
-#define __SPRCACHE_H
+#ifndef AGS_SHARED_AC_SPRITECACHE_H
+#define AGS_SHARED_AC_SPRITECACHE_H
 
 #include <memory>
 #include <vector>
@@ -247,4 +247,4 @@ private:
 
 extern SpriteCache spriteset;
 
-#endif // __SPRCACHE_H
+#endif
diff --git a/engines/ags/shared/ac/view.h b/engines/ags/shared/ac/view.h
index 65fb8bf89a..6a257e14f4 100644
--- a/engines/ags/shared/ac/view.h
+++ b/engines/ags/shared/ac/view.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_VIEW_H
-#define __AC_VIEW_H
+#ifndef AGS_SHARED_AC_VIEW_H
+#define AGS_SHARED_AC_VIEW_H
 
 #include <vector>
 
@@ -85,4 +85,4 @@ struct ViewStruct272 {
 
 void Convert272ViewsToNew(const std::vector<ViewStruct272> &oldv, ViewStruct *newv);
 
-#endif // __AC_VIEW_H
+#endif
diff --git a/engines/ags/shared/ac/wordsdictionary.h b/engines/ags/shared/ac/wordsdictionary.h
index 667b987145..dd499f7b69 100644
--- a/engines/ags/shared/ac/wordsdictionary.h
+++ b/engines/ags/shared/ac/wordsdictionary.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_WORDSDICTIONARY_H
-#define __AC_WORDSDICTIONARY_H
+#ifndef AGS_SHARED_AC_WORDSDICTIONARY_H
+#define AGS_SHARED_AC_WORDSDICTIONARY_H
 
 #include "core/types.h"
 
@@ -60,4 +60,4 @@ extern void encrypt_text(char *toenc);
 extern void write_string_encrypt(Common::Stream *out, const char *s);
 extern void write_dictionary (WordsDictionary *dict, Common::Stream *out);
 
-#endif // __AC_WORDSDICTIONARY_H
+#endif
diff --git a/engines/ags/shared/api/stream_api.h b/engines/ags/shared/api/stream_api.h
index 09db657444..283a440128 100644
--- a/engines/ags/shared/api/stream_api.h
+++ b/engines/ags/shared/api/stream_api.h
@@ -30,8 +30,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_API__IAGSSTREAM_H
-#define __AGS_CN_API__IAGSSTREAM_H
+#ifndef AGS_SHARED_API_IAGSSTREAM_H
+#define AGS_SHARED_API_IAGSSTREAM_H
 
 // TODO: it would probably be better to not include core definition headers
 // in API class headers, but make separate core headers specifically for
@@ -98,4 +98,4 @@ public:
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_API__IAGSSTREAM_H
+#endif
diff --git a/engines/ags/shared/core/asset.h b/engines/ags/shared/core/asset.h
index 07505adeec..14f906f5be 100644
--- a/engines/ags/shared/core/asset.h
+++ b/engines/ags/shared/core/asset.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_CORE__ASSET_H
-#define __AGS_CN_CORE__ASSET_H
+#ifndef AGS_SHARED_CORE_ASSET_H
+#define AGS_SHARED_CORE_ASSET_H
 
 #include <vector>
 #include "util/string.h"
@@ -67,4 +67,4 @@ struct AssetLibInfo
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_CORE__ASSET_H
+#endif
diff --git a/engines/ags/shared/core/assetmanager.h b/engines/ags/shared/core/assetmanager.h
index b1e4f5e0b0..f12fccba13 100644
--- a/engines/ags/shared/core/assetmanager.h
+++ b/engines/ags/shared/core/assetmanager.h
@@ -41,8 +41,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_CORE__ASSETMANAGER_H
-#define __AGS_CN_CORE__ASSETMANAGER_H
+#ifndef AGS_SHARED_CORE_ASSETMANAGER_H
+#define AGS_SHARED_CORE_ASSETMANAGER_H
 
 #include "util/file.h" // TODO: extract filestream mode constants or introduce generic ones
 
@@ -162,4 +162,4 @@ String GetAssetErrorText(AssetError err);
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_CORE__ASSETMANAGER_H
+#endif
diff --git a/engines/ags/shared/core/def_version.h b/engines/ags/shared/core/def_version.h
index 45a3dc9bdf..81495f30b9 100644
--- a/engines/ags/shared/core/def_version.h
+++ b/engines/ags/shared/core/def_version.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_CN_CORE__DEFVERSION_H
-#define __AGS_CN_CORE__DEFVERSION_H
+#ifndef AGS_SHARED_CORE_DEFVERSION_H
+#define AGS_SHARED_CORE_DEFVERSION_H
 
 #define ACI_VERSION_STR      "3.5.1.0"
 #if defined (RC_INVOKED) // for MSVC resource compiler
@@ -36,4 +36,4 @@
 
 #define ACI_COPYRIGHT_YEARS "2011-2020"
 
-#endif // __AGS_CN_CORE__DEFVERSION_H
+#endif
diff --git a/engines/ags/shared/core/platform.h b/engines/ags/shared/core/platform.h
index f1494d0939..85f640973e 100644
--- a/engines/ags/shared/core/platform.h
+++ b/engines/ags/shared/core/platform.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_PLATFORM_H
-#define __AC_PLATFORM_H
+#ifndef AGS_SHARED_CORE_PLATFORM_H
+#define AGS_SHARED_CORE_PLATFORM_H
 
 // platform definitions. Not intended for replacing types or checking for libraries.
 
@@ -124,4 +124,4 @@
     #define AGS_PLATFORM_DEBUG  (0)
 #endif
 
-#endif // __AC_PLATFORM_H
+#endif
diff --git a/engines/ags/shared/core/types.h b/engines/ags/shared/core/types.h
index 03da2bbb74..d476de63e6 100644
--- a/engines/ags/shared/core/types.h
+++ b/engines/ags/shared/core/types.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_CORE__TYPES_H
-#define __AGS_CN_CORE__TYPES_H
+#ifndef AGS_SHARED_CORE_TYPES_H
+#define AGS_SHARED_CORE_TYPES_H
 
 #include <stddef.h>
 #include <stdint.h>
@@ -69,4 +69,4 @@ enum
     kUnit     = 1 << kShift
 };
 
-#endif // __AGS_CN_CORE__TYPES_H
+#endif
diff --git a/engines/ags/shared/debugging/assert.h b/engines/ags/shared/debugging/assert.h
index fd02a7f0bc..cb355fa6df 100644
--- a/engines/ags/shared/debugging/assert.h
+++ b/engines/ags/shared/debugging/assert.h
@@ -26,9 +26,9 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_DEBUG__ASSERT_H
-#define __AGS_CN_DEBUG__ASSERT_H
+#ifndef AGS_SHARED_DEBUGGING_ASSERT_H
+#define AGS_SHARED_DEBUGGING_ASSERT_H
 
 #include <assert.h>
 
-#endif // __AGS_CN_DEBUG__ASSERT_H
+#endif
diff --git a/engines/ags/shared/debugging/debugmanager.h b/engines/ags/shared/debugging/debugmanager.h
index fa100f746a..d001012d5a 100644
--- a/engines/ags/shared/debugging/debugmanager.h
+++ b/engines/ags/shared/debugging/debugmanager.h
@@ -44,8 +44,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_DEBUG__DEBUGMANAGER_H
-#define __AGS_CN_DEBUG__DEBUGMANAGER_H
+#ifndef AGS_SHARED_DEBUGGING_DEBUGMANAGER_H
+#define AGS_SHARED_DEBUGGING_DEBUGMANAGER_H
 
 #include <memory>
 #include <unordered_map>
@@ -170,4 +170,4 @@ extern DebugManager DbgMgr;
 }   // namespace Common
 }   // namespace AGS
 
-#endif // __AGS_CN_DEBUG__DEBUGMANAGER_H
+#endif
diff --git a/engines/ags/shared/debugging/out.h b/engines/ags/shared/debugging/out.h
index d77d4ba68d..7e18324357 100644
--- a/engines/ags/shared/debugging/out.h
+++ b/engines/ags/shared/debugging/out.h
@@ -74,8 +74,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_DEBUG__OUT_H
-#define __AGS_CN_DEBUG__OUT_H
+#ifndef AGS_SHARED_DEBUGGING_OUT_H
+#define AGS_SHARED_DEBUGGING_OUT_H
 
 #include "util/string.h"
 
@@ -162,4 +162,4 @@ namespace Debug
 }   // namespace Common
 }   // namespace AGS
 
-#endif // __AGS_CN_DEBUG__OUT_H
+#endif
diff --git a/engines/ags/shared/debugging/outputhandler.h b/engines/ags/shared/debugging/outputhandler.h
index 35eadc595d..397e4cbfd7 100644
--- a/engines/ags/shared/debugging/outputhandler.h
+++ b/engines/ags/shared/debugging/outputhandler.h
@@ -27,8 +27,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_DEBUG__OUTPUTHANDLER_H
-#define __AGS_CN_DEBUG__OUTPUTHANDLER_H
+#ifndef AGS_SHARED_DEBUGGING_OUTPUTHANDLER_H
+#define AGS_SHARED_DEBUGGING_OUTPUTHANDLER_H
 
 #include "debug/out.h"
 #include "util/string.h"
@@ -67,4 +67,4 @@ public:
 }   // namespace Common
 }   // namespace AGS
 
-#endif // __AGS_CN_DEBUG__OUTPUTHANDLER_H
+#endif
diff --git a/engines/ags/shared/font/agsfontrenderer.h b/engines/ags/shared/font/agsfontrenderer.h
index f738a11eff..4d25170eec 100644
--- a/engines/ags/shared/font/agsfontrenderer.h
+++ b/engines/ags/shared/font/agsfontrenderer.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_AGSFONTRENDERER_H
-#define __AC_AGSFONTRENDERER_H
+#ifndef AGS_SHARED_FONT_AGSFONTRENDERER_H
+#define AGS_SHARED_FONT_AGSFONTRENDERER_H
 
 struct BITMAP;
 
@@ -64,4 +64,4 @@ protected:
   ~IAGSFontRenderer2() = default;
 };
 
-#endif // __AC_AGSFONTRENDERER_H
+#endif
diff --git a/engines/ags/shared/font/fonts.h b/engines/ags/shared/font/fonts.h
index 8502109b87..7c71b232f8 100644
--- a/engines/ags/shared/font/fonts.h
+++ b/engines/ags/shared/font/fonts.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_FONT_H
-#define __AC_FONT_H
+#ifndef AGS_SHARED_FONT_FONTS_H
+#define AGS_SHARED_FONT_FONTS_H
 
 #include <vector>
 #include "core/types.h"
@@ -117,4 +117,4 @@ size_t split_lines(const char *texx, SplitLines &lines, int width, int fontNumbe
 
 namespace AGS { namespace Common { extern SplitLines Lines; } }
 
-#endif // __AC_FONT_H
+#endif
diff --git a/engines/ags/shared/font/ttffontrenderer.h b/engines/ags/shared/font/ttffontrenderer.h
index 4a7cf6722b..1fbb088345 100644
--- a/engines/ags/shared/font/ttffontrenderer.h
+++ b/engines/ags/shared/font/ttffontrenderer.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_TTFFONTRENDERER_H
-#define __AC_TTFFONTRENDERER_H
+#ifndef AGS_SHARED_FONT_TTFFONTRENDERER_H
+#define AGS_SHARED_FONT_TTFFONTRENDERER_H
 
 #include <map>
 #include "font/agsfontrenderer.h"
@@ -53,4 +53,4 @@ private:
     std::map<int, FontData> _fontData;
 };
 
-#endif // __AC_TTFFONTRENDERER_H
+#endif
diff --git a/engines/ags/shared/font/wfnfont.h b/engines/ags/shared/font/wfnfont.h
index dd83c60b47..1f85d65d9f 100644
--- a/engines/ags/shared/font/wfnfont.h
+++ b/engines/ags/shared/font/wfnfont.h
@@ -43,8 +43,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_FONT__WFNFONT_H
-#define __AGS_CN_FONT__WFNFONT_H
+#ifndef AGS_SHARED_FONT_WFNFONT_H
+#define AGS_SHARED_FONT_WFNFONT_H
 
 #include <vector>
 #include "core/types.h"
@@ -109,4 +109,4 @@ protected:
     static const WFNChar        _emptyChar; // a dummy character to substitute bad symbols
 };
 
-#endif // __AGS_CN_FONT__WFNFONT_H
+#endif
diff --git a/engines/ags/shared/font/wfnfontrenderer.h b/engines/ags/shared/font/wfnfontrenderer.h
index a7cb943d1e..4a164bac92 100644
--- a/engines/ags/shared/font/wfnfontrenderer.h
+++ b/engines/ags/shared/font/wfnfontrenderer.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_WFNFONTRENDERER_H
-#define __AC_WFNFONTRENDERER_H
+#ifndef AGS_SHARED_FONT_WFNFONTRENDERER_H
+#define AGS_SHARED_FONT_WFNFONTRENDERER_H
 
 #include <map>
 #include "font/agsfontrenderer.h"
@@ -51,4 +51,4 @@ private:
   std::map<int, FontData> _fontData;
 };
 
-#endif // __AC_WFNFONTRENDERER_H
+#endif
diff --git a/engines/ags/shared/game/customproperties.h b/engines/ags/shared/game/customproperties.h
index e875cd9416..325cc21ac9 100644
--- a/engines/ags/shared/game/customproperties.h
+++ b/engines/ags/shared/game/customproperties.h
@@ -33,8 +33,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_GAME__CUSTOMPROPERTIES_H
-#define __AGS_CN_GAME__CUSTOMPROPERTIES_H
+#ifndef AGS_SHARED_GAME_CUSTOMPROPERTIES_H
+#define AGS_SHARED_GAME_CUSTOMPROPERTIES_H
 
 #include <unordered_map>
 #include "util/string.h"
@@ -110,4 +110,4 @@ namespace Properties
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_GAME__CUSTOMPROPERTIES_H
+#endif
diff --git a/engines/ags/shared/game/interactions.h b/engines/ags/shared/game/interactions.h
index aae290ec8e..a82b6b7ff3 100644
--- a/engines/ags/shared/game/interactions.h
+++ b/engines/ags/shared/game/interactions.h
@@ -46,8 +46,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_GAME__INTEREACTIONS_H
-#define __AGS_CN_GAME__INTEREACTIONS_H
+#ifndef AGS_SHARED_GAME_INTEREACTIONS_H
+#define AGS_SHARED_GAME_INTEREACTIONS_H
 
 #include <memory>
 #include "util/string_types.h"
@@ -220,4 +220,4 @@ typedef std::shared_ptr<InteractionScripts> PInteractionScripts;
 extern AGS::Common::InteractionVariable globalvars[MAX_GLOBAL_VARIABLES];
 extern int numGlobalVars;
 
-#endif // __AGS_CN_GAME__INTEREACTIONS_H
+#endif
diff --git a/engines/ags/shared/game/main_game_file.h b/engines/ags/shared/game/main_game_file.h
index 48d08ba1ec..2ed4f483d4 100644
--- a/engines/ags/shared/game/main_game_file.h
+++ b/engines/ags/shared/game/main_game_file.h
@@ -28,8 +28,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_GAME__MAINGAMEFILE_H
-#define __AGS_CN_GAME__MAINGAMEFILE_H
+#ifndef AGS_SHARED_GAME_MAINGAMEFILE_H
+#define AGS_SHARED_GAME_MAINGAMEFILE_H
 
 #include <memory>
 #include <set>
@@ -154,4 +154,4 @@ void               FixupSaveDirectory(GameSetupStruct &game);
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_GAME__MAINGAMEFILE_H
+#endif
diff --git a/engines/ags/shared/game/plugininfo.h b/engines/ags/shared/game/plugininfo.h
index 4d1a461d8a..ec068cc8bf 100644
--- a/engines/ags/shared/game/plugininfo.h
+++ b/engines/ags/shared/game/plugininfo.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_GAME__PLUGININFO_H
-#define __AGS_CN_GAME__PLUGININFO_H
+#ifndef AGS_SHARED_GAME_PLUGININFO_H
+#define AGS_SHARED_GAME_PLUGININFO_H
 
 #include <memory>
 #include "util/string.h"
@@ -54,4 +54,4 @@ struct PluginInfo
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_GAME__PLUGININFO_H
+#endif
diff --git a/engines/ags/shared/game/room_file.h b/engines/ags/shared/game/room_file.h
index bf7244fac8..727a97c476 100644
--- a/engines/ags/shared/game/room_file.h
+++ b/engines/ags/shared/game/room_file.h
@@ -28,8 +28,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_GAME_ROOMFILE_H
-#define __AGS_CN_GAME_ROOMFILE_H
+#ifndef AGS_SHARED_GAME_ROOMFILE_H
+#define AGS_SHARED_GAME_ROOMFILE_H
 
 #include <memory>
 #include <vector>
@@ -99,4 +99,4 @@ HRoomFileError WriteRoomData(const RoomStruct *room, Stream *out, RoomFileVersio
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_GAME_ROOMFILE_H
+#endif
diff --git a/engines/ags/shared/game/room_version.h b/engines/ags/shared/game/room_version.h
index 47507757f1..f5a14998e2 100644
--- a/engines/ags/shared/game/room_version.h
+++ b/engines/ags/shared/game/room_version.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_AC__ROOMVERSION_H
-#define __AGS_CN_AC__ROOMVERSION_H
+#ifndef AGS_SHARED_GAME_ROOMVERSION_H
+#define AGS_SHARED_GAME_ROOMVERSION_H
 
 /* room file versions history
 8:  final v1.14 release
@@ -93,4 +93,4 @@ enum RoomFileVersion
     kRoomVersion_Current = kRoomVersion_3508
 };
 
-#endif // __AGS_CN_AC__ROOMVERSION_H
+#endif
diff --git a/engines/ags/shared/game/roomstruct.h b/engines/ags/shared/game/roomstruct.h
index a6895058eb..722c60ce5c 100644
--- a/engines/ags/shared/game/roomstruct.h
+++ b/engines/ags/shared/game/roomstruct.h
@@ -45,8 +45,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_GAME__ROOMINFO_H
-#define __AGS_CN_GAME__ROOMINFO_H
+#ifndef AGS_SHARED_GAME_ROOMINFO_H
+#define AGS_SHARED_GAME_ROOMINFO_H
 
 #include <memory>
 #include "ac/common_defines.h"
@@ -394,4 +394,4 @@ PBitmap FixBitmap(PBitmap bmp, int dst_width, int dst_height);
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_GAME__ROOMINFO_H
+#endif
diff --git a/engines/ags/shared/gfx/allegrobitmap.h b/engines/ags/shared/gfx/allegrobitmap.h
index c7f437daa6..94c22a4b88 100644
--- a/engines/ags/shared/gfx/allegrobitmap.h
+++ b/engines/ags/shared/gfx/allegrobitmap.h
@@ -29,8 +29,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_GFX__ALLEGROBITMAP_H
-#define __AGS_CN_GFX__ALLEGROBITMAP_H
+#ifndef AGS_SHARED_GFX_ALLEGROBITMAP_H
+#define AGS_SHARED_GFX_ALLEGROBITMAP_H
 
 #include <allegro.h>
 #include "core/types.h"
@@ -257,4 +257,4 @@ namespace BitmapHelper
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_GFX__ALLEGROBITMAP_H
+#endif
diff --git a/engines/ags/shared/gfx/bitmap.h b/engines/ags/shared/gfx/bitmap.h
index 6e58b95b72..7d0a7e99a2 100644
--- a/engines/ags/shared/gfx/bitmap.h
+++ b/engines/ags/shared/gfx/bitmap.h
@@ -25,8 +25,9 @@
 // Base bitmap header
 //
 //=============================================================================
-#ifndef __AGS_CN_GFX__BITMAP_H
-#define __AGS_CN_GFX__BITMAP_H
+
+#ifndef AGS_SHARED_GFX_BITMAP_H
+#define AGS_SHARED_GFX_BITMAP_H
 
 #include "util/geometry.h"
 
@@ -94,4 +95,4 @@ namespace BitmapHelper
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_GFX__BITMAP_H
+#endif
diff --git a/engines/ags/shared/gfx/gfx_def.h b/engines/ags/shared/gfx/gfx_def.h
index 99254cc8b3..af0582ae1d 100644
--- a/engines/ags/shared/gfx/gfx_def.h
+++ b/engines/ags/shared/gfx/gfx_def.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_GFX__GFXDEF_H
-#define __AGS_CN_GFX__GFXDEF_H
+#ifndef AGS_SHARED_GFX_GFXDEF_H
+#define AGS_SHARED_GFX_GFXDEF_H
 
 namespace AGS
 {
@@ -125,4 +125,4 @@ namespace GfxDef
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_GFX__GFXDEF_H
+#endif
diff --git a/engines/ags/shared/gui/guibutton.h b/engines/ags/shared/gui/guibutton.h
index b32efe8ac8..8637c05aab 100644
--- a/engines/ags/shared/gui/guibutton.h
+++ b/engines/ags/shared/gui/guibutton.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_GUIBUTTON_H
-#define __AC_GUIBUTTON_H
+#ifndef AGS_SHARED_GUI_GUIBUTTON_H
+#define AGS_SHARED_GUI_GUIBUTTON_H
 
 #include <vector>
 #include "gui/guiobject.h"
@@ -141,4 +141,4 @@ extern int numguibuts;
 int UpdateAnimatingButton(int bu);
 void StopButtonAnimation(int idxn);
 
-#endif // __AC_GUIBUTTON_H
+#endif
diff --git a/engines/ags/shared/gui/guidefines.h b/engines/ags/shared/gui/guidefines.h
index 3d43b88b70..d9c27e42bb 100644
--- a/engines/ags/shared/gui/guidefines.h
+++ b/engines/ags/shared/gui/guidefines.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_GUIDEFINES_H
-#define __AC_GUIDEFINES_H
+#ifndef AGS_SHARED_GUI_GUIDEFINES_H
+#define AGS_SHARED_GUI_GUIDEFINES_H
 
 #define GUIMAGIC          0xcafebeef
 #define MAX_GUIOBJ_EVENTS 10
@@ -190,4 +190,4 @@ enum GuiSvgVersion
 
 extern int guis_need_update;
 
-#endif // __AC_GUIDEFINES_H
+#endif
diff --git a/engines/ags/shared/gui/guiinv.h b/engines/ags/shared/gui/guiinv.h
index ee3959300e..0acab662d1 100644
--- a/engines/ags/shared/gui/guiinv.h
+++ b/engines/ags/shared/gui/guiinv.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_GUIINV_H
-#define __AC_GUIINV_H
+#ifndef AGS_SHARED_GUI_GUIINV_H
+#define AGS_SHARED_GUI_GUIINV_H
 
 #include <vector>
 #include "gui/guiobject.h"
@@ -75,4 +75,4 @@ private:
 extern std::vector<AGS::Common::GUIInvWindow> guiinv;
 extern int numguiinv;
 
-#endif // __AC_GUIINV_H
+#endif
diff --git a/engines/ags/shared/gui/guilabel.h b/engines/ags/shared/gui/guilabel.h
index f9f5a70f02..86ea4b9e37 100644
--- a/engines/ags/shared/gui/guilabel.h
+++ b/engines/ags/shared/gui/guilabel.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_GUILABEL_H
-#define __AC_GUILABEL_H
+#ifndef AGS_SHARED_GUI_GUILABEL_H
+#define AGS_SHARED_GUI_GUILABEL_H
 
 #include <vector>
 #include "gui/guiobject.h"
@@ -72,4 +72,4 @@ private:
 extern std::vector<AGS::Common::GUILabel> guilabels;
 extern int numguilabels;
 
-#endif // __AC_GUILABEL_H
+#endif
diff --git a/engines/ags/shared/gui/guilistbox.h b/engines/ags/shared/gui/guilistbox.h
index ce68c495a2..fcee121ce6 100644
--- a/engines/ags/shared/gui/guilistbox.h
+++ b/engines/ags/shared/gui/guilistbox.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_GUILISTBOX_H
-#define __AC_GUILISTBOX_H
+#ifndef AGS_SHARED_GUI_GUILISTBOX_H
+#define AGS_SHARED_GUI_GUILISTBOX_H
 
 #include <vector>
 #include "gui/guiobject.h"
@@ -103,4 +103,4 @@ private:
 extern std::vector<AGS::Common::GUIListBox> guilist;
 extern int numguilist;
 
-#endif // __AC_GUILISTBOX_H
+#endif
diff --git a/engines/ags/shared/gui/guimain.h b/engines/ags/shared/gui/guimain.h
index 8166edc876..5ec98205da 100644
--- a/engines/ags/shared/gui/guimain.h
+++ b/engines/ags/shared/gui/guimain.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_GUIMAIN_H
-#define __AC_GUIMAIN_H
+#ifndef AGS_SHARED_GUI_GUIMAIN_H
+#define AGS_SHARED_GUI_GUIMAIN_H
 
 #include <vector>
 #include "ac/common_defines.h" // TODO: split out gui drawing helpers
@@ -246,4 +246,4 @@ extern int get_eip_guiobj();
 
 extern bool outlineGuiObjects;
 
-#endif // __AC_GUIMAIN_H
+#endif
diff --git a/engines/ags/shared/gui/guiobject.h b/engines/ags/shared/gui/guiobject.h
index 0d85a68f82..2768dd9a66 100644
--- a/engines/ags/shared/gui/guiobject.h
+++ b/engines/ags/shared/gui/guiobject.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_GUIOBJECT_H
-#define __AC_GUIOBJECT_H
+#ifndef AGS_SHARED_GUI_GUIOBJECT_H
+#define AGS_SHARED_GUI_GUIOBJECT_H
 
 #include "core/types.h"
 #include "gfx/bitmap.h"
@@ -131,4 +131,4 @@ extern int all_buttons_disabled;
 // Tells if the given control is considered enabled, taking global flag into account
 inline bool IsGUIEnabled(AGS::Common::GUIObject *g) { return !all_buttons_disabled && g->IsEnabled(); }
 
-#endif // __AC_GUIOBJECT_H
+#endif
diff --git a/engines/ags/shared/gui/guislider.h b/engines/ags/shared/gui/guislider.h
index 93b1241302..c5dd69c6b0 100644
--- a/engines/ags/shared/gui/guislider.h
+++ b/engines/ags/shared/gui/guislider.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_GUISLIDER_H
-#define __AC_GUISLIDER_H
+#ifndef AGS_SHARED_GUI_GUISLIDER_H
+#define AGS_SHARED_GUI_GUISLIDER_H
 
 #include <vector>
 #include "gui/guiobject.h"
@@ -76,4 +76,4 @@ private:
 extern std::vector<AGS::Common::GUISlider> guislider;
 extern int numguislider;
 
-#endif // __AC_GUISLIDER_H
+#endif
diff --git a/engines/ags/shared/gui/guitextbox.h b/engines/ags/shared/gui/guitextbox.h
index 8c37567dd3..0617e8c358 100644
--- a/engines/ags/shared/gui/guitextbox.h
+++ b/engines/ags/shared/gui/guitextbox.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_GUITEXTBOX_H
-#define __AC_GUITEXTBOX_H
+#ifndef AGS_SHARED_GUI_GUITEXTBOX_H
+#define AGS_SHARED_GUI_GUITEXTBOX_H
 
 #include <vector>
 #include "gui/guiobject.h"
@@ -70,4 +70,4 @@ private:
 extern std::vector<AGS::Common::GUITextBox> guitext;
 extern int numguitext;
 
-#endif // __AC_GUITEXTBOX_H
+#endif
diff --git a/engines/ags/shared/script/cc_error.h b/engines/ags/shared/script/cc_error.h
index 7f9c49ae4b..c3d9591b1e 100644
--- a/engines/ags/shared/script/cc_error.h
+++ b/engines/ags/shared/script/cc_error.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __CC_ERROR_H
-#define __CC_ERROR_H
+#ifndef AGS_SHARED_SCRIPT_ERROR_H
+#define AGS_SHARED_SCRIPT_ERROR_H
 
 #include "util/string.h"
 
@@ -41,4 +41,4 @@ extern AGS::Common::String ccErrorCallStack; // callstack where error happened
 extern bool ccErrorIsUserError;
 extern const char *ccCurScriptName; // name of currently compiling script
 
-#endif // __CC_ERROR_H
+#endif
diff --git a/engines/ags/shared/script/cc_options.h b/engines/ags/shared/script/cc_options.h
index beeef08070..e2ccbb6b7c 100644
--- a/engines/ags/shared/script/cc_options.h
+++ b/engines/ags/shared/script/cc_options.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __CC_OPTIONS_H
-#define __CC_OPTIONS_H
+#ifndef AGS_SHARED_SCRIPT_CC_OPTIONS_H
+#define AGS_SHARED_SCRIPT_CC_OPTIONS_H
 
 #define SCOPT_EXPORTALL      1   // export all functions automatically
 #define SCOPT_SHOWWARNINGS   2   // printf warnings to console
diff --git a/engines/ags/shared/script/cc_script.h b/engines/ags/shared/script/cc_script.h
index c8a69186d5..07f8d86de0 100644
--- a/engines/ags/shared/script/cc_script.h
+++ b/engines/ags/shared/script/cc_script.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __CC_SCRIPT_H
-#define __CC_SCRIPT_H
+#ifndef AGS_SHARED_SCRIPT_CC_SCRIPT_H
+#define AGS_SHARED_SCRIPT_CC_SCRIPT_H
 
 #include <memory>
 #include "core/types.h"
@@ -82,4 +82,4 @@ protected:
 
 typedef std::shared_ptr<ccScript> PScript;
 
-#endif // __CC_SCRIPT_H
+#endif
diff --git a/engines/ags/shared/script/script_common.h b/engines/ags/shared/script/script_common.h
index cd6a0ce2ed..42fbf6991e 100644
--- a/engines/ags/shared/script/script_common.h
+++ b/engines/ags/shared/script/script_common.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __CS_COMMON_H
-#define __CS_COMMON_H
+#ifndef AGS_SHARED_SCRIPT_SCRIPT_COMMON_H
+#define AGS_SHARED_SCRIPT_SCRIPT_COMMON_H
 
 #define SCOM_VERSION 90
 #define SCOM_VERSIONSTR "0.90"
@@ -138,4 +138,4 @@ extern int currentline;
 extern const char scfilesig[5];
 #define ENDFILESIG 0xbeefcafe
 
-#endif // __CS_COMMON_H
+#endif
diff --git a/engines/ags/shared/util/alignedstream.h b/engines/ags/shared/util/alignedstream.h
index 6b1a4576c8..fd158b4937 100644
--- a/engines/ags/shared/util/alignedstream.h
+++ b/engines/ags/shared/util/alignedstream.h
@@ -42,8 +42,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_UTIL__ALIGNEDSTREAM_H
-#define __AGS_CN_UTIL__ALIGNEDSTREAM_H
+#ifndef AGS_SHARED_UTIL_ALIGNEDSTREAM_H
+#define AGS_SHARED_UTIL_ALIGNEDSTREAM_H
 
 #include "util/proxystream.h"
 
@@ -114,4 +114,4 @@ private:
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_UTIL__ALIGNEDSTREAM_H
+#endif
diff --git a/engines/ags/shared/util/bbop.h b/engines/ags/shared/util/bbop.h
index 6081aef917..4b80fe66a7 100644
--- a/engines/ags/shared/util/bbop.h
+++ b/engines/ags/shared/util/bbop.h
@@ -25,8 +25,9 @@
 // Various utility bit and byte operations
 //
 //=============================================================================
-#ifndef __AGS_CN_UTIL__BBOP_H
-#define __AGS_CN_UTIL__BBOP_H
+
+#ifndef AGS_SHARED_UTIL_BBOP_H
+#define AGS_SHARED_UTIL_BBOP_H
 
 #include "core/platform.h"
 #include "core/types.h"
@@ -165,4 +166,4 @@ namespace BBOp  = BitByteOperations;
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_UTIL__BBOP_H
+#endif
diff --git a/engines/ags/shared/util/bufferedstream.h b/engines/ags/shared/util/bufferedstream.h
index 3652c3fe0d..efb2cdc785 100644
--- a/engines/ags/shared/util/bufferedstream.h
+++ b/engines/ags/shared/util/bufferedstream.h
@@ -20,13 +20,8 @@
  *
  */
 
-//=============================================================================
-//
-//
-//
-//=============================================================================
-#ifndef __AGS_CN_UTIL__BUFFEREDSTREAM_H
-#define __AGS_CN_UTIL__BUFFEREDSTREAM_H
+#ifndef AGS_SHARED_UTIL_BUFFEREDSTREAM_H
+#define AGS_SHARED_UTIL_BUFFEREDSTREAM_H
 
 #include <vector>
 #include "util/filestream.h"
@@ -76,4 +71,4 @@ private:
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_UTIL__BUFFEREDSTREAM_H
+#endif
diff --git a/engines/ags/shared/util/compress.h b/engines/ags/shared/util/compress.h
index eb8e6c7d93..199020deab 100644
--- a/engines/ags/shared/util/compress.h
+++ b/engines/ags/shared/util/compress.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AC_COMPRESS_H
-#define __AC_COMPRESS_H
+#ifndef AGS_SHARED_UTIL_COMPRESS_H
+#define AGS_SHARED_UTIL_COMPRESS_H
 
 #include "util/wgt2allg.h" // color (allegro RGB)
 
@@ -45,4 +45,4 @@ void load_lzw(Common::Stream *in, Common::Bitmap **bmm, int dst_bpp, color *pall
 void savecompressed_allegro(Common::Stream *out, const Common::Bitmap *bmpp, const color *pall);
 void loadcompressed_allegro(Common::Stream *in, Common::Bitmap **bimpp, color *pall);
 
-#endif // __AC_COMPRESS_H
+#endif
diff --git a/engines/ags/shared/util/datastream.h b/engines/ags/shared/util/datastream.h
index c3b530bba0..6bbc92ff3f 100644
--- a/engines/ags/shared/util/datastream.h
+++ b/engines/ags/shared/util/datastream.h
@@ -28,8 +28,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_UTIL__DATASTREAM_H
-#define __AGS_CN_UTIL__DATASTREAM_H
+#ifndef AGS_SHARED_UTIL_DATASTREAM_H
+#define AGS_SHARED_UTIL_DATASTREAM_H
 
 #include "util/bbop.h"
 #include "util/stream.h"
@@ -140,4 +140,4 @@ protected:
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_UTIL__DATASTREAM_H
+#endif
diff --git a/engines/ags/shared/util/directory.h b/engines/ags/shared/util/directory.h
index 881c8aa59d..85164e9bf1 100644
--- a/engines/ags/shared/util/directory.h
+++ b/engines/ags/shared/util/directory.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_UTIL__DIRECTORY_H
-#define __AGS_CN_UTIL__DIRECTORY_H
+#ifndef AGS_SHARED_UTIL_DIRECTORY_H
+#define AGS_SHARED_UTIL_DIRECTORY_H
 
 #include "core/platform.h"
 #include "util/string.h"
@@ -53,4 +53,4 @@ namespace Directory
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_UTIL__DIRECTORY_H
+#endif
diff --git a/engines/ags/shared/util/error.h b/engines/ags/shared/util/error.h
index 599ab1aeb2..7024c37005 100644
--- a/engines/ags/shared/util/error.h
+++ b/engines/ags/shared/util/error.h
@@ -27,8 +27,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_UTIL__ERROR_H
-#define __AGS_CN_UTIL__ERROR_H
+#ifndef AGS_SHARED_UTIL_ERROR_H
+#define AGS_SHARED_UTIL_ERROR_H
 
 #include <memory>
 #include "util/string.h"
@@ -142,4 +142,4 @@ public:
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_UTIL__ERROR_H
+#endif
diff --git a/engines/ags/shared/util/file.h b/engines/ags/shared/util/file.h
index 8a513eeafd..5b1d830ab3 100644
--- a/engines/ags/shared/util/file.h
+++ b/engines/ags/shared/util/file.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_UTIL__FILE_H
-#define __AGS_CN_UTIL__FILE_H
+#ifndef AGS_SHARED_UTIL_FILE_H
+#define AGS_SHARED_UTIL_FILE_H
 
 #include "core/platform.h"
 #include "util/string.h"
@@ -94,4 +94,4 @@ namespace File
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_UTIL__FILE_H
+#endif
diff --git a/engines/ags/shared/util/filestream.h b/engines/ags/shared/util/filestream.h
index 55dba895db..4397b0dd28 100644
--- a/engines/ags/shared/util/filestream.h
+++ b/engines/ags/shared/util/filestream.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_CN_UTIL__FILESTREAM_H
-#define __AGS_CN_UTIL__FILESTREAM_H
+#ifndef AGS_SHARED_UTIL_FILESTREAM_H
+#define AGS_SHARED_UTIL_FILESTREAM_H
 
 #include <stdio.h>
 
@@ -79,4 +79,4 @@ private:
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_UTIL__FILESTREAM_H
+#endif
diff --git a/engines/ags/shared/util/geometry.h b/engines/ags/shared/util/geometry.h
index acfc8536cd..c0ebbaa9b5 100644
--- a/engines/ags/shared/util/geometry.h
+++ b/engines/ags/shared/util/geometry.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_UTIL__GEOMETRY_H
-#define __AGS_CN_UTIL__GEOMETRY_H
+#ifndef AGS_SHARED_UTIL_GEOMETRY_H
+#define AGS_SHARED_UTIL_GEOMETRY_H
 
 #include "util/math.h"
 
@@ -413,4 +413,4 @@ Rect PlaceInRect(const Rect &place, const Rect &item, const RectPlacement &place
 //} // namespace Common
 //} // namespace AGS
 
-#endif // __AGS_CN_UTIL__GEOMETRY_H
+#endif
diff --git a/engines/ags/shared/util/ini_util.h b/engines/ags/shared/util/ini_util.h
index 7ca76ca514..9f3d7b3aa5 100644
--- a/engines/ags/shared/util/ini_util.h
+++ b/engines/ags/shared/util/ini_util.h
@@ -27,8 +27,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_UTIL__INIUTIL_H
-#define __AGS_CN_UTIL__INIUTIL_H
+#ifndef AGS_SHARED_UTIL_INIUTIL_H
+#define AGS_SHARED_UTIL_INIUTIL_H
 
 #include <map>
 #include "util/string.h"
@@ -74,4 +74,4 @@ namespace IniUtil
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_UTIL__INIUTIL_H
+#endif
diff --git a/engines/ags/shared/util/inifile.h b/engines/ags/shared/util/inifile.h
index b77bf5ed05..b69b89582a 100644
--- a/engines/ags/shared/util/inifile.h
+++ b/engines/ags/shared/util/inifile.h
@@ -30,8 +30,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_UTIL__INIFILE_H
-#define __AGS_CN_UTIL__INIFILE_H
+#ifndef AGS_SHARED_UTIL_INIFILE_H
+#define AGS_SHARED_UTIL_INIFILE_H
 
 #include <list>
 #include "util/string.h"
@@ -142,4 +142,4 @@ private:
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_UTIL__INIFILE_H
+#endif
diff --git a/engines/ags/shared/util/lzw.h b/engines/ags/shared/util/lzw.h
index 46af7bbcc2..f4a7b45915 100644
--- a/engines/ags/shared/util/lzw.h
+++ b/engines/ags/shared/util/lzw.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_CN_UTIL__LZW_H
-#define __AGS_CN_UTIL__LZW_H
+#ifndef AGS_SHARED_UTIL_LZW_H
+#define AGS_SHARED_UTIL_LZW_H
 
 namespace AGS { namespace Common { class Stream; } }
 using namespace AGS; // FIXME later
@@ -31,4 +31,4 @@ unsigned char *lzwexpand_to_mem(Common::Stream *in);
 
 extern long outbytes, maxsize, putbytes;
 
-#endif // __AGS_CN_UTIL__LZW_H
+#endif
diff --git a/engines/ags/shared/util/math.h b/engines/ags/shared/util/math.h
index 85be2a33c8..02da48ff1e 100644
--- a/engines/ags/shared/util/math.h
+++ b/engines/ags/shared/util/math.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_UTIL__MATH_H
-#define __AGS_CN_UTIL__MATH_H
+#ifndef AGS_SHARED_UTIL_MATH_H
+#define AGS_SHARED_UTIL_MATH_H
 
 #ifndef M_PI
 #define M_PI 3.14159265358979323846
@@ -98,4 +98,4 @@ namespace Math
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_UTIL__MATH_H
+#endif
diff --git a/engines/ags/shared/util/memory.h b/engines/ags/shared/util/memory.h
index f84666b090..0b4761d246 100644
--- a/engines/ags/shared/util/memory.h
+++ b/engines/ags/shared/util/memory.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_UTIL__MEMORY_H
-#define __AGS_CN_UTIL__MEMORY_H
+#ifndef AGS_SHARED_UTIL_MEMORY_H
+#define AGS_SHARED_UTIL_MEMORY_H
 
 #include <string.h>
 #include "util/bbop.h"
@@ -253,4 +253,4 @@ namespace Memory
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_UTIL__MEMORY_H
+#endif
diff --git a/engines/ags/shared/util/misc.h b/engines/ags/shared/util/misc.h
index cd97e50379..bac661c35d 100644
--- a/engines/ags/shared/util/misc.h
+++ b/engines/ags/shared/util/misc.h
@@ -49,8 +49,8 @@
   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
 
-#ifndef __MISC_H
-#define __MISC_H
+#ifndef AGS_SHARED_UTIL_MISC_H
+#define AGS_SHARED_UTIL_MISC_H
 
 #include "util/file.h" // TODO: extract filestream mode constants
 
diff --git a/engines/ags/shared/util/multifilelib.h b/engines/ags/shared/util/multifilelib.h
index 5f73e386d4..c7a0eea819 100644
--- a/engines/ags/shared/util/multifilelib.h
+++ b/engines/ags/shared/util/multifilelib.h
@@ -31,8 +31,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_UTIL__MULTIFILELIB_H
-#define __AGS_CN_UTIL__MULTIFILELIB_H
+#ifndef AGS_SHARED_UTIL_MULTIFILELIB_H
+#define AGS_SHARED_UTIL_MULTIFILELIB_H
 
 #include "core/asset.h"
 #include "util/stream.h"
@@ -80,4 +80,4 @@ namespace MFLUtil
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_UTIL__MULTIFILELIB_H
+#endif
diff --git a/engines/ags/shared/util/path.h b/engines/ags/shared/util/path.h
index 9083f5c886..87d1e0596a 100644
--- a/engines/ags/shared/util/path.h
+++ b/engines/ags/shared/util/path.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_UTIL__PATH_H
-#define __AGS_CN_UTIL__PATH_H
+#ifndef AGS_SHARED_UTIL_PATH_H
+#define AGS_SHARED_UTIL_PATH_H
 
 #include "util/string.h"
 
@@ -90,4 +90,4 @@ namespace Path
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_UTIL__PATH_H
+#endif
diff --git a/engines/ags/shared/util/proxystream.h b/engines/ags/shared/util/proxystream.h
index 7587e779f7..cc45cde33a 100644
--- a/engines/ags/shared/util/proxystream.h
+++ b/engines/ags/shared/util/proxystream.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_CN_UTIL__PROXYSTREAM_H
-#define __AGS_CN_UTIL__PROXYSTREAM_H
+#ifndef AGS_SHARED_UTIL_PROXYSTREAM_H
+#define AGS_SHARED_UTIL_PROXYSTREAM_H
 
 #include "util/stream.h"
 
@@ -89,4 +89,4 @@ protected:
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_UTIL__PROXYSTREAM_H
+#endif
diff --git a/engines/ags/shared/util/stdio_compat.h b/engines/ags/shared/util/stdio_compat.h
index 726b809fac..e57dbbba66 100644
--- a/engines/ags/shared/util/stdio_compat.h
+++ b/engines/ags/shared/util/stdio_compat.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_CN_UTIL__STDIOCOMPAT_H
-#define __AGS_CN_UTIL__STDIOCOMPAT_H
+#ifndef AGS_SHARED_UTIL_STDIOCOMPAT_H
+#define AGS_SHARED_UTIL_STDIOCOMPAT_H
 
 #include <stdio.h>
 #include <stdint.h>
@@ -44,4 +44,4 @@ file_off_t ags_file_size(const char *path);
 }
 #endif
 
-#endif // __AGS_CN_UTIL__STDIOCOMPAT_H
+#endif
diff --git a/engines/ags/shared/util/stream.h b/engines/ags/shared/util/stream.h
index 80c25a1df7..e70f9bbfa8 100644
--- a/engines/ags/shared/util/stream.h
+++ b/engines/ags/shared/util/stream.h
@@ -32,8 +32,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_UTIL__STREAM_H
-#define __AGS_CN_UTIL__STREAM_H
+#ifndef AGS_SHARED_UTIL_STREAM_H
+#define AGS_SHARED_UTIL_STREAM_H
 
 #include "api/stream_api.h"
 
@@ -92,4 +92,4 @@ public:
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_UTIL__STREAM_H
+#endif
diff --git a/engines/ags/shared/util/string.h b/engines/ags/shared/util/string.h
index 94a84ab180..9bc56a5045 100644
--- a/engines/ags/shared/util/string.h
+++ b/engines/ags/shared/util/string.h
@@ -43,8 +43,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_UTIL__STRING_H
-#define __AGS_CN_UTIL__STRING_H
+#ifndef AGS_SHARED_UTIL_STRING_H
+#define AGS_SHARED_UTIL_STRING_H
 
 #include <stdarg.h>
 #include <vector>
@@ -386,4 +386,4 @@ private:
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_UTIL__STRING_H
+#endif
diff --git a/engines/ags/shared/util/string_compat.h b/engines/ags/shared/util/string_compat.h
index 48a06f4312..631c6c22a0 100644
--- a/engines/ags/shared/util/string_compat.h
+++ b/engines/ags/shared/util/string_compat.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_CN_UTIL__STRINGCOMPAT_H
-#define __AGS_CN_UTIL__STRINGCOMPAT_H
+#ifndef AGS_SHARED_UTIL_STRINGCOMPAT_H
+#define AGS_SHARED_UTIL_STRINGCOMPAT_H
 
 #include "core/types.h"
 
@@ -39,4 +39,4 @@ char *ags_strdup(const char *s);
 }
 #endif
 
-#endif // __AGS_CN_UTIL__STRINGCOMPAT_H
+#endif
diff --git a/engines/ags/shared/util/string_types.h b/engines/ags/shared/util/string_types.h
index 7359913190..62c81dd157 100644
--- a/engines/ags/shared/util/string_types.h
+++ b/engines/ags/shared/util/string_types.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_CN_UTIL__STRINGTYPES_H
-#define __AGS_CN_UTIL__STRINGTYPES_H
+#ifndef AGS_SHARED_UTIL_STRINGTYPES_H
+#define AGS_SHARED_UTIL_STRINGTYPES_H
 
 #include <cctype>
 #include <functional>
@@ -120,4 +120,4 @@ typedef std::unordered_map<String, String, HashStrNoCase, StrEqNoCase> StringIMa
 } // namespace Common
 } // namespace AGS
 
-#endif //__AGS_CN_UTIL__STRINGTYPES_H
+#endif
diff --git a/engines/ags/shared/util/string_utils.h b/engines/ags/shared/util/string_utils.h
index 95028808c7..440d352161 100644
--- a/engines/ags/shared/util/string_utils.h
+++ b/engines/ags/shared/util/string_utils.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef __AGS_CN_UTIL__STRINGUTILS_H
-#define __AGS_CN_UTIL__STRINGUTILS_H
+#ifndef AGS_SHARED_UTIL_STRING_UTILS_H
+#define AGS_SHARED_UTIL_STRING_UTILS_H
 
 #include "util/string.h"
 
@@ -78,4 +78,4 @@ namespace StrUtil
 } // namespace AGS
 
 
-#endif // __AGS_CN_UTIL__STRINGUTILS_H
+#endif
diff --git a/engines/ags/shared/util/textreader.h b/engines/ags/shared/util/textreader.h
index f8fb7b2390..d5fc20c026 100644
--- a/engines/ags/shared/util/textreader.h
+++ b/engines/ags/shared/util/textreader.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_UTIL__TEXTREADER_H
-#define __AGS_CN_UTIL__TEXTREADER_H
+#ifndef AGS_SHARED_UTIL_TEXTREADER_H
+#define AGS_SHARED_UTIL_TEXTREADER_H
 
 #include "util/string.h"
 
@@ -56,4 +56,4 @@ public:
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_UTIL__TEXTSTREAM_H
+#endif
diff --git a/engines/ags/shared/util/textstreamreader.h b/engines/ags/shared/util/textstreamreader.h
index 8301f5236b..74859a913b 100644
--- a/engines/ags/shared/util/textstreamreader.h
+++ b/engines/ags/shared/util/textstreamreader.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_UTIL__TEXTSTREAMREADER_H
-#define __AGS_CN_UTIL__TEXTSTREAMREADER_H
+#ifndef AGS_SHARED_UTIL_TEXTSTREAMREADER_H
+#define AGS_SHARED_UTIL_TEXTSTREAMREADER_H
 
 #include "util/textreader.h"
 
@@ -68,4 +68,4 @@ private:
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_UTIL__TEXTSTREAM_H
+#endif
diff --git a/engines/ags/shared/util/textstreamwriter.h b/engines/ags/shared/util/textstreamwriter.h
index 72f0fdad1a..58ce4634b8 100644
--- a/engines/ags/shared/util/textstreamwriter.h
+++ b/engines/ags/shared/util/textstreamwriter.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_UTIL__TEXTSTREAMWRITER_H
-#define __AGS_CN_UTIL__TEXTSTREAMWRITER_H
+#ifndef AGS_SHARED_UTIL_TEXTSTREAMWRITER_H
+#define AGS_SHARED_UTIL_TEXTSTREAMWRITER_H
 
 #include "util/textwriter.h"
 
@@ -69,4 +69,4 @@ private:
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_UTIL__TEXTSTREAMWRITER_H
+#endif
diff --git a/engines/ags/shared/util/textwriter.h b/engines/ags/shared/util/textwriter.h
index ce07cb6b91..9f99a8f08e 100644
--- a/engines/ags/shared/util/textwriter.h
+++ b/engines/ags/shared/util/textwriter.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_UTIL__TEXTWRITER_H
-#define __AGS_CN_UTIL__TEXTWRITER_H
+#ifndef AGS_SHARED_UTIL_TEXTWRITER_H
+#define AGS_SHARED_UTIL_TEXTWRITER_H
 
 #include "util/string.h"
 
@@ -57,4 +57,4 @@ public:
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_UTIL__TEXTWRITER_H
+#endif
diff --git a/engines/ags/shared/util/version.h b/engines/ags/shared/util/version.h
index c74ccdd291..09cd6c3624 100644
--- a/engines/ags/shared/util/version.h
+++ b/engines/ags/shared/util/version.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef __AGS_CN_MAIN__VERSION_H
-#define __AGS_CN_MAIN__VERSION_H
+#ifndef AGS_SHARED_UTIL_VERSION_H
+#define AGS_SHARED_UTIL_VERSION_H
 
 #include "util/string.h"
 
@@ -115,4 +115,4 @@ private:
 } // namespace Common
 } // namespace AGS
 
-#endif // __AGS_CN_MAIN__VERSION_H
+#endif
diff --git a/engines/ags/shared/util/wgt2allg.h b/engines/ags/shared/util/wgt2allg.h
index 82e954bdcb..ef8a87f627 100644
--- a/engines/ags/shared/util/wgt2allg.h
+++ b/engines/ags/shared/util/wgt2allg.h
@@ -32,8 +32,8 @@
 
 #define _WGT45_
 
-#ifndef __WGT4_H
-#define __WGT4_H
+#ifndef AGS_SHARED_UTIL_WGT4_H
+#define AGS_SHARED_UTIL_WGT4_H
 
 #include "allegro.h"
 
@@ -85,5 +85,4 @@ extern "C"
 // archive attributes to search for - al_findfirst breaks with 0
 #define FA_SEARCH -1
 
-
-#endif // __WGT4_H
+#endif


Commit: 8f6391bb5b3e7b3788bc4fa39f64a034ea77c030
    https://github.com/scummvm/scummvm/commit/8f6391bb5b3e7b3788bc4fa39f64a034ea77c030
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
COMMON: Added WeakPtr class, refactored SharedPtr

Changed paths:
    common/ptr.h


diff --git a/common/ptr.h b/common/ptr.h
index 802e84d6d0..80173268da 100644
--- a/common/ptr.h
+++ b/common/ptr.h
@@ -38,16 +38,16 @@ namespace Common {
  * @{
  */
 
-class SharedPtrDeletionInternal {
+class BasePtrDeletionInternal {
 public:
-	virtual ~SharedPtrDeletionInternal() {}
+	virtual ~BasePtrDeletionInternal() {}
 };
 
 template<class T>
-class SharedPtrDeletionImpl : public SharedPtrDeletionInternal {
+class BasePtrDeletionImpl : public BasePtrDeletionInternal {
 public:
-	SharedPtrDeletionImpl(T *ptr) : _ptr(ptr) {}
-	~SharedPtrDeletionImpl() {
+	BasePtrDeletionImpl(T *ptr) : _ptr(ptr) {}
+	~BasePtrDeletionImpl() {
 		STATIC_ASSERT(sizeof(T) > 0, SharedPtr_cannot_delete_incomplete_type);
 		delete _ptr;
 	}
@@ -56,15 +56,180 @@ private:
 };
 
 template<class T, class DL>
-class SharedPtrDeletionDeleterImpl : public SharedPtrDeletionInternal {
+class BasePtrDeletionDeleterImpl : public BasePtrDeletionInternal {
 public:
-	SharedPtrDeletionDeleterImpl(T *ptr, DL d) : _ptr(ptr), _deleter(d) {}
-	~SharedPtrDeletionDeleterImpl() { _deleter(_ptr); }
+	BasePtrDeletionDeleterImpl(T *ptr, DL d) : _ptr(ptr), _deleter(d) {}
+	~BasePtrDeletionDeleterImpl() { _deleter(_ptr); }
 private:
 	T *_ptr;
 	DL _deleter;
 };
 
+/**
+ * A base class for both SharedPtr and WeakPtr.
+ *
+ * This base class encapsulates the logic for the reference counter
+ * used by both.
+ */
+template<class T>
+class BasePtr : public SafeBool<BasePtr<T> > {
+#if !defined(__GNUC__) || GCC_ATLEAST(3, 0)
+	template<class T2> friend class BasePtr;
+#endif
+public:
+	typedef int RefValue;
+	typedef T ValueType;
+	typedef T *PointerType;
+	typedef T &ReferenceType;
+
+	BasePtr() : _refCount(nullptr), _deletion(nullptr), _pointer(nullptr) {
+	}
+
+	explicit BasePtr(nullptr_t) : _refCount(nullptr), _deletion(nullptr), _pointer(nullptr) {
+	}
+
+	template<class T2>
+	explicit BasePtr(T2 *p) : _refCount(new RefValue(1)), _deletion(new BasePtrDeletionImpl<T2>(p)), _pointer(p) {
+	}
+
+	template<class T2, class DL>
+	BasePtr(T2 *p, DL d) : _refCount(new RefValue(1)), _deletion(new BasePtrDeletionDeleterImpl<T2, DL>(p, d)), _pointer(p) {
+	}
+
+	BasePtr(const BasePtr &r) : _refCount(r._refCount), _deletion(r._deletion), _pointer(r._pointer) {
+		if (_refCount)
+			++(*_refCount);
+	}
+	template<class T2>
+	BasePtr(const BasePtr<T2> &r) : _refCount(r._refCount), _deletion(r._deletion), _pointer(r._pointer) {
+		if (_refCount) ++(*_refCount);
+	}
+
+	~BasePtr() {
+		decRef();
+	}
+
+	/**
+	 * Implicit conversion operator to bool for convenience, to make
+	 * checks like "if (sharedPtr) ..." possible.
+	 */
+	bool operator_bool() const {
+		return _pointer != nullptr;
+	}
+
+	/**
+	 * Returns the number of references to the assigned pointer.
+	 * This should just be used for debugging purposes.
+	 */
+	RefValue refCount() const {
+		return _refCount ? *_refCount : 0;
+	}
+
+	/**
+	 * Returns whether the referenced object isn't valid
+	 */
+	bool expired() const {
+		return !_refCount;
+	}
+
+	/**
+	 * Checks if the object is the only object refering
+	 * to the assigned pointer. This should just be used for
+	 * debugging purposes.
+	 */
+	bool unique() const {
+		return refCount() == 1;
+	}
+
+	BasePtr &operator=(const BasePtr &r) {
+		reset(r);
+		return *this;
+	}
+
+	template<class T2>
+	BasePtr &operator=(const BasePtr<T2> &r) {
+		reset(r);
+		return *this;
+	}
+
+	/**
+	 * Resets the object to a NULL pointer.
+	 */
+	void reset() {
+		decRef();
+		_deletion = nullptr;
+		_refCount = nullptr;
+		_pointer = nullptr;
+	}
+
+	/**
+	 * Resets the object to the specified pointer
+	 */
+	void reset(const BasePtr &r) {
+		if (r._refCount)
+			++(*r._refCount);
+		decRef();
+
+		_refCount = r._refCount;
+		_deletion = r._deletion;
+		_pointer = r._pointer;
+	}
+
+	/**
+	 * Resets the object to the specified pointer
+	 */
+	template<class T2>
+	void reset(const BasePtr<T2> &r) {
+		if (r._refCount)
+			++(*r._refCount);
+		decRef();
+
+		_refCount = r._refCount;
+		_deletion = r._deletion;
+		_pointer = r._pointer;
+	}
+
+	/**
+	 * Resets the object to the specified pointer
+	 */
+	void reset(T *ptr) {
+		reset(BasePtr<T>(ptr));
+	}
+
+protected:
+	RefValue *_refCount;
+	BasePtrDeletionInternal *_deletion;
+	PointerType _pointer;
+protected:
+	/**
+	 * Decrements the reference count to the stored pointer, and deletes it if
+	 * there are no longer any references to it
+	 */
+	void decRef() {
+		if (_refCount) {
+			--(*_refCount);
+			if (!*_refCount) {
+				delete _refCount;
+				delete _deletion;
+				_deletion = nullptr;
+				_refCount = nullptr;
+				_pointer = nullptr;
+			}
+		}
+	}
+
+	/**
+	 * Increments the reference count to the stored pointer
+	 */
+	void incRef() {
+		if (_refCount)
+			++*_refCount;
+	}
+};
+
+template<class T>
+class WeakPtr;
+
 /**
  * A simple shared pointer implementation modelled after boost.
  *
@@ -84,7 +249,7 @@ private:
  * as for a normal pointer. If you need to access the plain pointer value
  * itself later on use the get method. The class also supplies a operator
  * ->, which does the same as the -> operator on a normal pointer.
- *
+ * 
  * Be sure you are using new to initialize the pointer you want to manage.
  * If you do not use new for allocating, you have to supply a deleter as
  * second parameter when creating a SharedPtr object. The deleter has to
@@ -107,57 +272,37 @@ private:
  * a plain pointer is only possible via SharedPtr::get.
  */
 template<class T>
-class SharedPtr : public SafeBool<SharedPtr<T> > {
-#if !defined(__GNUC__) || GCC_ATLEAST(3, 0)
-	template<class T2> friend class SharedPtr;
-#endif
+class SharedPtr : public BasePtr<T> {
 public:
-	typedef int RefValue;
-	typedef T ValueType;
-	typedef T *PointerType;
-	typedef T &ReferenceType;
+	using ReferenceType = typename BasePtr<T>::ReferenceType;
+	using PointerType = typename BasePtr<T>::PointerType;
 
-	SharedPtr() : _refCount(nullptr), _deletion(nullptr), _pointer(nullptr) {}
-
-	template<class T2>
-	explicit SharedPtr(T2 *p) : _refCount(new RefValue(1)), _deletion(new SharedPtrDeletionImpl<T2>(p)), _pointer(p) {}
+	SharedPtr() : BasePtr<T>() {
+	}
 
-	template<class T2, class DL>
-	SharedPtr(T2 *p, DL d) : _refCount(new RefValue(1)), _deletion(new SharedPtrDeletionDeleterImpl<T2, DL>(p, d)), _pointer(p) {}
+	SharedPtr(nullptr_t) : BasePtr<T>() {
+	}
 
-	SharedPtr(const SharedPtr &r) : _refCount(r._refCount), _deletion(r._deletion), _pointer(r._pointer) { if (_refCount) ++(*_refCount); }
 	template<class T2>
-	SharedPtr(const SharedPtr<T2> &r) : _refCount(r._refCount), _deletion(r._deletion), _pointer(r._pointer) { if (_refCount) ++(*_refCount); }
-
-	~SharedPtr() { decRef(); }
+	explicit SharedPtr(T2 *p) : BasePtr<T>(p) {
+	}
 
-	SharedPtr &operator=(const SharedPtr &r) {
-		if (r._refCount)
-			++(*r._refCount);
-		decRef();
+	template<class T2, class DL>
+	SharedPtr(T2 *p, DL d) : BasePtr<T>(p, d) {
+	}
 
-		_refCount = r._refCount;
-		_deletion = r._deletion;
-		_pointer = r._pointer;
+	SharedPtr(const SharedPtr<T> &r) : BasePtr<T>(r) {
+	}
 
-		return *this;
+	SharedPtr(const WeakPtr<T> &r) : BasePtr<T>(r) {
 	}
 
 	template<class T2>
-	SharedPtr &operator=(const SharedPtr<T2> &r) {
-		if (r._refCount)
-			++(*r._refCount);
-		decRef();
-
-		_refCount = r._refCount;
-		_deletion = r._deletion;
-		_pointer = r._pointer;
-
-		return *this;
+	SharedPtr(const SharedPtr<T2> &r) : BasePtr<T>(r) {
 	}
 
-	ReferenceType operator*() const { assert(_pointer); return *_pointer; }
-	PointerType operator->() const { assert(_pointer); return _pointer; }
+	T &operator*() const { assert(this->_pointer); return *this->_pointer; }
+	T *operator->() const { assert(this->_pointer); return this->_pointer; }
 
 	/**
 	 * Returns the plain pointer value. Be sure you know what you
@@ -165,65 +310,49 @@ public:
 	 *
 	 * @return the pointer the SharedPtr object manages
 	 */
-	PointerType get() const { return _pointer; }
+	PointerType get() const { return this->_pointer; }
 
-	/**
-	 * Implicit conversion operator to bool for convenience, to make
-	 * checks like "if (sharedPtr) ..." possible.
-	 */
-	bool operator_bool() const { return _pointer != nullptr; }
+	template<class T2>
+	bool operator==(const SharedPtr<T2> &r) const {
+		return this->_pointer == r.get();
+	}
 
-	/**
-	 * Checks if the SharedPtr object is the only object refering
-	 * to the assigned pointer. This should just be used for
-	 * debugging purposes.
-	 */
-	bool unique() const { return refCount() == 1; }
+	template<class T2>
+	bool operator!=(const SharedPtr<T2> &r) const {
+		return this->_pointer != r.get();
+	}
+};
 
-	/**
-	 * Resets the SharedPtr object to a NULL pointer.
-	 */
-	void reset() {
-		decRef();
-		_deletion = nullptr;
-		_refCount = nullptr;
-		_pointer = nullptr;
+/**
+ * Implements a smart pointer that holds a non-owning ("weak") refrence to
+ * a pointer. It needs to be converted to a SharedPtr to access it.
+ */
+template<class T>
+class WeakPtr : public BasePtr<T> {
+public:
+	WeakPtr() : BasePtr<T>() {
+	}
+
+	WeakPtr(nullptr_t) : BasePtr<T>() {
 	}
 
 	template<class T2>
-	bool operator==(const SharedPtr<T2> &r) const {
-		return _pointer == r.get();
+	explicit WeakPtr(T2 *p) : BasePtr<T>(p) {
+	}
+
+	WeakPtr(const BasePtr<T> &r) : BasePtr<T>(r) {
 	}
 
 	template<class T2>
-	bool operator!=(const SharedPtr<T2> &r) const {
-		return _pointer != r.get();
+	WeakPtr(const BasePtr<T2> &r) : BasePtr<T>(r) {
 	}
 
 	/**
-	 * Returns the number of references to the assigned pointer.
-	 * This should just be used for debugging purposes.
+	 * Creates a SharedPtr that manages the referenced object
 	 */
-	RefValue refCount() const { return _refCount ? *_refCount : 0; }
-#if !defined(__GNUC__) || GCC_ATLEAST(3, 0)
-private:
-#endif
-	void decRef() {
-		if (_refCount) {
-			--(*_refCount);
-			if (!*_refCount) {
-				delete _refCount;
-				delete _deletion;
-				_deletion = nullptr;
-				_refCount = nullptr;
-				_pointer = nullptr;
-			}
-		}
+	SharedPtr<T> lock() const {
+		return SharedPtr<T>(*this);
 	}
-
-	RefValue *_refCount;
-	SharedPtrDeletionInternal *_deletion;
-	PointerType _pointer;
 };
 
 template <typename T>


Commit: 8026e4bb300b06ad6cc72bf918ee656d9dc52aff
    https://github.com/scummvm/scummvm/commit/8026e4bb300b06ad6cc72bf918ee656d9dc52aff
Author: dreammaster (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Run astyle formatting

Changed paths:
    engines/ags/ags.cpp
    engines/ags/detection.cpp
    engines/ags/engine/ac/asset_helper.h
    engines/ags/engine/ac/audiochannel.cpp
    engines/ags/engine/ac/audiochannel.h
    engines/ags/engine/ac/audioclip.cpp
    engines/ags/engine/ac/audioclip.h
    engines/ags/engine/ac/button.cpp
    engines/ags/engine/ac/button.h
    engines/ags/engine/ac/cdaudio.cpp
    engines/ags/engine/ac/cdaudio.h
    engines/ags/engine/ac/character.cpp
    engines/ags/engine/ac/character.h
    engines/ags/engine/ac/charactercache.h
    engines/ags/engine/ac/characterextras.cpp
    engines/ags/engine/ac/characterextras.h
    engines/ags/engine/ac/characterinfo_engine.cpp
    engines/ags/engine/ac/datetime.cpp
    engines/ags/engine/ac/datetime.h
    engines/ags/engine/ac/dialog.cpp
    engines/ags/engine/ac/dialog.h
    engines/ags/engine/ac/dialogoptionsrendering.cpp
    engines/ags/engine/ac/dialogoptionsrendering.h
    engines/ags/engine/ac/display.cpp
    engines/ags/engine/ac/display.h
    engines/ags/engine/ac/draw.cpp
    engines/ags/engine/ac/draw.h
    engines/ags/engine/ac/draw_software.cpp
    engines/ags/engine/ac/drawingsurface.cpp
    engines/ags/engine/ac/drawingsurface.h
    engines/ags/engine/ac/dynamicsprite.cpp
    engines/ags/engine/ac/dynamicsprite.h
    engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp
    engines/ags/engine/ac/dynobj/cc_agsdynamicobject.h
    engines/ags/engine/ac/dynobj/cc_audiochannel.cpp
    engines/ags/engine/ac/dynobj/cc_audiochannel.h
    engines/ags/engine/ac/dynobj/cc_audioclip.cpp
    engines/ags/engine/ac/dynobj/cc_audioclip.h
    engines/ags/engine/ac/dynobj/cc_character.cpp
    engines/ags/engine/ac/dynobj/cc_character.h
    engines/ags/engine/ac/dynobj/cc_dialog.cpp
    engines/ags/engine/ac/dynobj/cc_dialog.h
    engines/ags/engine/ac/dynobj/cc_dynamicarray.cpp
    engines/ags/engine/ac/dynobj/cc_dynamicarray.h
    engines/ags/engine/ac/dynobj/cc_dynamicobject.cpp
    engines/ags/engine/ac/dynobj/cc_dynamicobject.h
    engines/ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h
    engines/ags/engine/ac/dynobj/cc_gui.cpp
    engines/ags/engine/ac/dynobj/cc_gui.h
    engines/ags/engine/ac/dynobj/cc_guiobject.cpp
    engines/ags/engine/ac/dynobj/cc_guiobject.h
    engines/ags/engine/ac/dynobj/cc_hotspot.cpp
    engines/ags/engine/ac/dynobj/cc_hotspot.h
    engines/ags/engine/ac/dynobj/cc_inventory.cpp
    engines/ags/engine/ac/dynobj/cc_inventory.h
    engines/ags/engine/ac/dynobj/cc_object.cpp
    engines/ags/engine/ac/dynobj/cc_object.h
    engines/ags/engine/ac/dynobj/cc_region.cpp
    engines/ags/engine/ac/dynobj/cc_region.h
    engines/ags/engine/ac/dynobj/cc_serializer.cpp
    engines/ags/engine/ac/dynobj/cc_serializer.h
    engines/ags/engine/ac/dynobj/managedobjectpool.cpp
    engines/ags/engine/ac/dynobj/managedobjectpool.h
    engines/ags/engine/ac/dynobj/scriptaudiochannel.h
    engines/ags/engine/ac/dynobj/scriptcamera.cpp
    engines/ags/engine/ac/dynobj/scriptcamera.h
    engines/ags/engine/ac/dynobj/scriptdatetime.cpp
    engines/ags/engine/ac/dynobj/scriptdatetime.h
    engines/ags/engine/ac/dynobj/scriptdialog.h
    engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.cpp
    engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.h
    engines/ags/engine/ac/dynobj/scriptdict.cpp
    engines/ags/engine/ac/dynobj/scriptdict.h
    engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp
    engines/ags/engine/ac/dynobj/scriptdrawingsurface.h
    engines/ags/engine/ac/dynobj/scriptdynamicsprite.cpp
    engines/ags/engine/ac/dynobj/scriptdynamicsprite.h
    engines/ags/engine/ac/dynobj/scriptfile.cpp
    engines/ags/engine/ac/dynobj/scriptfile.h
    engines/ags/engine/ac/dynobj/scriptgui.h
    engines/ags/engine/ac/dynobj/scripthotspot.h
    engines/ags/engine/ac/dynobj/scriptinvitem.h
    engines/ags/engine/ac/dynobj/scriptmouse.h
    engines/ags/engine/ac/dynobj/scriptobject.h
    engines/ags/engine/ac/dynobj/scriptoverlay.cpp
    engines/ags/engine/ac/dynobj/scriptoverlay.h
    engines/ags/engine/ac/dynobj/scriptregion.h
    engines/ags/engine/ac/dynobj/scriptset.cpp
    engines/ags/engine/ac/dynobj/scriptset.h
    engines/ags/engine/ac/dynobj/scriptstring.cpp
    engines/ags/engine/ac/dynobj/scriptstring.h
    engines/ags/engine/ac/dynobj/scriptsystem.h
    engines/ags/engine/ac/dynobj/scriptuserobject.cpp
    engines/ags/engine/ac/dynobj/scriptuserobject.h
    engines/ags/engine/ac/dynobj/scriptviewframe.cpp
    engines/ags/engine/ac/dynobj/scriptviewframe.h
    engines/ags/engine/ac/dynobj/scriptviewport.cpp
    engines/ags/engine/ac/dynobj/scriptviewport.h
    engines/ags/engine/ac/event.cpp
    engines/ags/engine/ac/event.h
    engines/ags/engine/ac/file.cpp
    engines/ags/engine/ac/file.h
    engines/ags/engine/ac/game.cpp
    engines/ags/engine/ac/game.h
    engines/ags/engine/ac/gamesetup.cpp
    engines/ags/engine/ac/gamesetup.h
    engines/ags/engine/ac/gamestate.cpp
    engines/ags/engine/ac/gamestate.h
    engines/ags/engine/ac/global_api.cpp
    engines/ags/engine/ac/global_audio.cpp
    engines/ags/engine/ac/global_audio.h
    engines/ags/engine/ac/global_button.cpp
    engines/ags/engine/ac/global_button.h
    engines/ags/engine/ac/global_character.cpp
    engines/ags/engine/ac/global_character.h
    engines/ags/engine/ac/global_datetime.cpp
    engines/ags/engine/ac/global_datetime.h
    engines/ags/engine/ac/global_debug.cpp
    engines/ags/engine/ac/global_debug.h
    engines/ags/engine/ac/global_dialog.cpp
    engines/ags/engine/ac/global_dialog.h
    engines/ags/engine/ac/global_display.cpp
    engines/ags/engine/ac/global_display.h
    engines/ags/engine/ac/global_drawingsurface.cpp
    engines/ags/engine/ac/global_drawingsurface.h
    engines/ags/engine/ac/global_dynamicsprite.cpp
    engines/ags/engine/ac/global_file.cpp
    engines/ags/engine/ac/global_file.h
    engines/ags/engine/ac/global_game.cpp
    engines/ags/engine/ac/global_game.h
    engines/ags/engine/ac/global_gui.cpp
    engines/ags/engine/ac/global_gui.h
    engines/ags/engine/ac/global_hotspot.cpp
    engines/ags/engine/ac/global_hotspot.h
    engines/ags/engine/ac/global_inventoryitem.cpp
    engines/ags/engine/ac/global_inventoryitem.h
    engines/ags/engine/ac/global_invwindow.cpp
    engines/ags/engine/ac/global_invwindow.h
    engines/ags/engine/ac/global_label.cpp
    engines/ags/engine/ac/global_label.h
    engines/ags/engine/ac/global_listbox.cpp
    engines/ags/engine/ac/global_listbox.h
    engines/ags/engine/ac/global_mouse.cpp
    engines/ags/engine/ac/global_mouse.h
    engines/ags/engine/ac/global_object.cpp
    engines/ags/engine/ac/global_object.h
    engines/ags/engine/ac/global_overlay.cpp
    engines/ags/engine/ac/global_overlay.h
    engines/ags/engine/ac/global_palette.cpp
    engines/ags/engine/ac/global_palette.h
    engines/ags/engine/ac/global_parser.cpp
    engines/ags/engine/ac/global_parser.h
    engines/ags/engine/ac/global_plugin.h
    engines/ags/engine/ac/global_record.cpp
    engines/ags/engine/ac/global_record.h
    engines/ags/engine/ac/global_region.cpp
    engines/ags/engine/ac/global_region.h
    engines/ags/engine/ac/global_room.cpp
    engines/ags/engine/ac/global_room.h
    engines/ags/engine/ac/global_screen.cpp
    engines/ags/engine/ac/global_screen.h
    engines/ags/engine/ac/global_slider.cpp
    engines/ags/engine/ac/global_slider.h
    engines/ags/engine/ac/global_string.cpp
    engines/ags/engine/ac/global_string.h
    engines/ags/engine/ac/global_textbox.cpp
    engines/ags/engine/ac/global_textbox.h
    engines/ags/engine/ac/global_timer.cpp
    engines/ags/engine/ac/global_timer.h
    engines/ags/engine/ac/global_translation.cpp
    engines/ags/engine/ac/global_translation.h
    engines/ags/engine/ac/global_video.cpp
    engines/ags/engine/ac/global_video.h
    engines/ags/engine/ac/global_viewframe.cpp
    engines/ags/engine/ac/global_viewframe.h
    engines/ags/engine/ac/global_viewport.cpp
    engines/ags/engine/ac/global_viewport.h
    engines/ags/engine/ac/global_walkablearea.cpp
    engines/ags/engine/ac/global_walkablearea.h
    engines/ags/engine/ac/global_walkbehind.cpp
    engines/ags/engine/ac/global_walkbehind.h
    engines/ags/engine/ac/gui.cpp
    engines/ags/engine/ac/gui.h
    engines/ags/engine/ac/guicontrol.cpp
    engines/ags/engine/ac/guicontrol.h
    engines/ags/engine/ac/guiinv.cpp
    engines/ags/engine/ac/hotspot.cpp
    engines/ags/engine/ac/hotspot.h
    engines/ags/engine/ac/interfacebutton.cpp
    engines/ags/engine/ac/interfaceelement.cpp
    engines/ags/engine/ac/inventoryitem.cpp
    engines/ags/engine/ac/inventoryitem.h
    engines/ags/engine/ac/invwindow.cpp
    engines/ags/engine/ac/invwindow.h
    engines/ags/engine/ac/keycode.cpp
    engines/ags/engine/ac/keycode.h
    engines/ags/engine/ac/label.cpp
    engines/ags/engine/ac/label.h
    engines/ags/engine/ac/lipsync.h
    engines/ags/engine/ac/listbox.cpp
    engines/ags/engine/ac/listbox.h
    engines/ags/engine/ac/math.cpp
    engines/ags/engine/ac/math.h
    engines/ags/engine/ac/mouse.cpp
    engines/ags/engine/ac/mouse.h
    engines/ags/engine/ac/movelist.cpp
    engines/ags/engine/ac/movelist.h
    engines/ags/engine/ac/object.cpp
    engines/ags/engine/ac/object.h
    engines/ags/engine/ac/objectcache.h
    engines/ags/engine/ac/overlay.cpp
    engines/ags/engine/ac/overlay.h
    engines/ags/engine/ac/parser.cpp
    engines/ags/engine/ac/parser.h
    engines/ags/engine/ac/path_helper.h
    engines/ags/engine/ac/properties.cpp
    engines/ags/engine/ac/properties.h
    engines/ags/engine/ac/region.cpp
    engines/ags/engine/ac/region.h
    engines/ags/engine/ac/richgamemedia.cpp
    engines/ags/engine/ac/richgamemedia.h
    engines/ags/engine/ac/room.cpp
    engines/ags/engine/ac/room.h
    engines/ags/engine/ac/roomobject.cpp
    engines/ags/engine/ac/roomobject.h
    engines/ags/engine/ac/roomstatus.cpp
    engines/ags/engine/ac/roomstatus.h
    engines/ags/engine/ac/route_finder.cpp
    engines/ags/engine/ac/route_finder.h
    engines/ags/engine/ac/route_finder_impl.cpp
    engines/ags/engine/ac/route_finder_impl.h
    engines/ags/engine/ac/route_finder_impl_legacy.cpp
    engines/ags/engine/ac/route_finder_impl_legacy.h
    engines/ags/engine/ac/runtime_defines.h
    engines/ags/engine/ac/screen.cpp
    engines/ags/engine/ac/screen.h
    engines/ags/engine/ac/screenoverlay.cpp
    engines/ags/engine/ac/screenoverlay.h
    engines/ags/engine/ac/scriptcontainers.cpp
    engines/ags/engine/ac/slider.cpp
    engines/ags/engine/ac/slider.h
    engines/ags/engine/ac/speech.cpp
    engines/ags/engine/ac/speech.h
    engines/ags/engine/ac/sprite.cpp
    engines/ags/engine/ac/sprite.h
    engines/ags/engine/ac/spritecache_engine.cpp
    engines/ags/engine/ac/spritelistentry.h
    engines/ags/engine/ac/statobj/agsstaticobject.cpp
    engines/ags/engine/ac/statobj/agsstaticobject.h
    engines/ags/engine/ac/statobj/staticarray.cpp
    engines/ags/engine/ac/statobj/staticarray.h
    engines/ags/engine/ac/statobj/staticobject.h
    engines/ags/engine/ac/string.cpp
    engines/ags/engine/ac/string.h
    engines/ags/engine/ac/sys_events.cpp
    engines/ags/engine/ac/sys_events.h
    engines/ags/engine/ac/system.cpp
    engines/ags/engine/ac/system.h
    engines/ags/engine/ac/textbox.cpp
    engines/ags/engine/ac/textbox.h
    engines/ags/engine/ac/timer.cpp
    engines/ags/engine/ac/timer.h
    engines/ags/engine/ac/topbarsettings.h
    engines/ags/engine/ac/translation.cpp
    engines/ags/engine/ac/translation.h
    engines/ags/engine/ac/tree_map.cpp
    engines/ags/engine/ac/tree_map.h
    engines/ags/engine/ac/viewframe.cpp
    engines/ags/engine/ac/viewframe.h
    engines/ags/engine/ac/viewport_script.cpp
    engines/ags/engine/ac/walkablearea.cpp
    engines/ags/engine/ac/walkablearea.h
    engines/ags/engine/ac/walkbehind.cpp
    engines/ags/engine/ac/walkbehind.h
    engines/ags/engine/debugging/agseditordebugger.h
    engines/ags/engine/debugging/consoleoutputtarget.cpp
    engines/ags/engine/debugging/consoleoutputtarget.h
    engines/ags/engine/debugging/debug.cpp
    engines/ags/engine/debugging/debug_log.h
    engines/ags/engine/debugging/debugger.h
    engines/ags/engine/debugging/dummyagsdebugger.h
    engines/ags/engine/debugging/filebasedagsdebugger.cpp
    engines/ags/engine/debugging/filebasedagsdebugger.h
    engines/ags/engine/debugging/logfile.cpp
    engines/ags/engine/debugging/logfile.h
    engines/ags/engine/debugging/messagebuffer.cpp
    engines/ags/engine/debugging/messagebuffer.h
    engines/ags/engine/device/mousew32.cpp
    engines/ags/engine/device/mousew32.h
    engines/ags/engine/font/fonts_engine.cpp
    engines/ags/engine/game/game_init.cpp
    engines/ags/engine/game/game_init.h
    engines/ags/engine/game/savegame.cpp
    engines/ags/engine/game/savegame.h
    engines/ags/engine/game/savegame_components.cpp
    engines/ags/engine/game/savegame_components.h
    engines/ags/engine/game/savegame_internal.h
    engines/ags/engine/game/viewport.cpp
    engines/ags/engine/game/viewport.h
    engines/ags/engine/gfx/ali3dexception.h
    engines/ags/engine/gfx/ali3dogl.cpp
    engines/ags/engine/gfx/ali3dogl.h
    engines/ags/engine/gfx/ali3dsw.cpp
    engines/ags/engine/gfx/ali3dsw.h
    engines/ags/engine/gfx/blender.cpp
    engines/ags/engine/gfx/color_engine.cpp
    engines/ags/engine/gfx/ddb.h
    engines/ags/engine/gfx/gfx_util.cpp
    engines/ags/engine/gfx/gfx_util.h
    engines/ags/engine/gfx/gfxdefines.h
    engines/ags/engine/gfx/gfxdriverbase.cpp
    engines/ags/engine/gfx/gfxdriverbase.h
    engines/ags/engine/gfx/gfxdriverfactory.cpp
    engines/ags/engine/gfx/gfxdriverfactory.h
    engines/ags/engine/gfx/gfxdriverfactorybase.h
    engines/ags/engine/gfx/gfxfilter.h
    engines/ags/engine/gfx/gfxfilter_aad3d.cpp
    engines/ags/engine/gfx/gfxfilter_aad3d.h
    engines/ags/engine/gfx/gfxfilter_aaogl.cpp
    engines/ags/engine/gfx/gfxfilter_aaogl.h
    engines/ags/engine/gfx/gfxfilter_allegro.cpp
    engines/ags/engine/gfx/gfxfilter_allegro.h
    engines/ags/engine/gfx/gfxfilter_d3d.cpp
    engines/ags/engine/gfx/gfxfilter_d3d.h
    engines/ags/engine/gfx/gfxfilter_hqx.cpp
    engines/ags/engine/gfx/gfxfilter_hqx.h
    engines/ags/engine/gfx/gfxfilter_ogl.cpp
    engines/ags/engine/gfx/gfxfilter_ogl.h
    engines/ags/engine/gfx/gfxfilter_scaling.cpp
    engines/ags/engine/gfx/gfxfilter_scaling.h
    engines/ags/engine/gfx/gfxmodelist.h
    engines/ags/engine/gfx/graphicsdriver.h
    engines/ags/engine/gfx/hq2x3x.h
    engines/ags/engine/gui/animatingguibutton.cpp
    engines/ags/engine/gui/animatingguibutton.h
    engines/ags/engine/gui/cscidialog.cpp
    engines/ags/engine/gui/cscidialog.h
    engines/ags/engine/gui/gui_engine.cpp
    engines/ags/engine/gui/guidialog.cpp
    engines/ags/engine/gui/guidialog.h
    engines/ags/engine/gui/guidialogdefines.h
    engines/ags/engine/gui/guidialoginternaldefs.h
    engines/ags/engine/gui/mylabel.cpp
    engines/ags/engine/gui/mylabel.h
    engines/ags/engine/gui/mylistbox.cpp
    engines/ags/engine/gui/mylistbox.h
    engines/ags/engine/gui/mypushbutton.cpp
    engines/ags/engine/gui/mypushbutton.h
    engines/ags/engine/gui/mytextbox.cpp
    engines/ags/engine/gui/mytextbox.h
    engines/ags/engine/gui/newcontrol.cpp
    engines/ags/engine/gui/newcontrol.h
    engines/ags/engine/main/config.cpp
    engines/ags/engine/main/config.h
    engines/ags/engine/main/engine.cpp
    engines/ags/engine/main/engine.h
    engines/ags/engine/main/engine_setup.cpp
    engines/ags/engine/main/game_file.cpp
    engines/ags/engine/main/game_run.cpp
    engines/ags/engine/main/game_run.h
    engines/ags/engine/main/game_start.cpp
    engines/ags/engine/main/graphics_mode.cpp
    engines/ags/engine/main/graphics_mode.h
    engines/ags/engine/main/main.cpp
    engines/ags/engine/main/quit.cpp
    engines/ags/engine/main/quit.h
    engines/ags/engine/main/update.cpp
    engines/ags/engine/main/update.h
    engines/ags/engine/media/audio/ambientsound.cpp
    engines/ags/engine/media/audio/ambientsound.h
    engines/ags/engine/media/audio/audio.cpp
    engines/ags/engine/media/audio/audio.h
    engines/ags/engine/media/audio/clip_mydumbmod.cpp
    engines/ags/engine/media/audio/clip_mydumbmod.h
    engines/ags/engine/media/audio/clip_myjgmod.cpp
    engines/ags/engine/media/audio/clip_myjgmod.h
    engines/ags/engine/media/audio/clip_mymidi.cpp
    engines/ags/engine/media/audio/clip_mymidi.h
    engines/ags/engine/media/audio/clip_mymp3.cpp
    engines/ags/engine/media/audio/clip_mymp3.h
    engines/ags/engine/media/audio/clip_myogg.cpp
    engines/ags/engine/media/audio/clip_myogg.h
    engines/ags/engine/media/audio/clip_mystaticmp3.cpp
    engines/ags/engine/media/audio/clip_mystaticmp3.h
    engines/ags/engine/media/audio/clip_mystaticogg.cpp
    engines/ags/engine/media/audio/clip_mystaticogg.h
    engines/ags/engine/media/audio/clip_mywave.cpp
    engines/ags/engine/media/audio/clip_mywave.h
    engines/ags/engine/media/audio/queuedaudioitem.cpp
    engines/ags/engine/media/audio/queuedaudioitem.h
    engines/ags/engine/media/audio/sound.cpp
    engines/ags/engine/media/audio/soundcache.cpp
    engines/ags/engine/media/audio/soundcache.h
    engines/ags/engine/media/audio/soundclip.cpp
    engines/ags/engine/media/audio/soundclip.h
    engines/ags/engine/media/video/VMR9Graph.h
    engines/ags/engine/media/video/video.cpp
    engines/ags/engine/media/video/video.h
    engines/ags/engine/platform/android/acpland.cpp
    engines/ags/engine/platform/base/agsplatformdriver.cpp
    engines/ags/engine/platform/base/agsplatformdriver.h
    engines/ags/engine/platform/ios/acplios.cpp
    engines/ags/engine/platform/linux/acpllnx.cpp
    engines/ags/engine/platform/osx/acplmac.cpp
    engines/ags/engine/platform/util/pe.h
    engines/ags/engine/platform/windows/acplwin.cpp
    engines/ags/engine/platform/windows/debugging/namedpipesagsdebugger.cpp
    engines/ags/engine/platform/windows/debugging/namedpipesagsdebugger.h
    engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
    engines/ags/engine/platform/windows/gfx/ali3dd3d.h
    engines/ags/engine/platform/windows/media/video/acwavi.cpp
    engines/ags/engine/platform/windows/media/video/acwavi3d.cpp
    engines/ags/engine/platform/windows/minidump.cpp
    engines/ags/engine/platform/windows/setup/winsetup.cpp
    engines/ags/engine/platform/windows/setup/winsetup.h
    engines/ags/engine/platform/windows/win_ex_handling.cpp
    engines/ags/engine/plugin/agsplugin.cpp
    engines/ags/engine/plugin/agsplugin.h
    engines/ags/engine/plugin/global_plugin.cpp
    engines/ags/engine/plugin/plugin_builtin.h
    engines/ags/engine/plugin/plugin_engine.h
    engines/ags/engine/plugin/pluginobjectreader.h
    engines/ags/engine/resource/resource.h
    engines/ags/engine/script/cc_instance.cpp
    engines/ags/engine/script/cc_instance.h
    engines/ags/engine/script/executingscript.cpp
    engines/ags/engine/script/executingscript.h
    engines/ags/engine/script/exports.cpp
    engines/ags/engine/script/nonblockingscriptfunction.h
    engines/ags/engine/script/runtimescriptvalue.cpp
    engines/ags/engine/script/runtimescriptvalue.h
    engines/ags/engine/script/script.cpp
    engines/ags/engine/script/script.h
    engines/ags/engine/script/script_api.cpp
    engines/ags/engine/script/script_api.h
    engines/ags/engine/script/script_engine.cpp
    engines/ags/engine/script/script_runtime.cpp
    engines/ags/engine/script/script_runtime.h
    engines/ags/engine/script/systemimports.cpp
    engines/ags/engine/script/systemimports.h
    engines/ags/engine/util/library.h
    engines/ags/engine/util/library_dummy.h
    engines/ags/engine/util/library_posix.h
    engines/ags/engine/util/library_psp.h
    engines/ags/engine/util/library_windows.h
    engines/ags/engine/util/mutex.h
    engines/ags/engine/util/mutex_base.h
    engines/ags/engine/util/mutex_lock.h
    engines/ags/engine/util/mutex_psp.h
    engines/ags/engine/util/mutex_pthread.h
    engines/ags/engine/util/mutex_std.h
    engines/ags/engine/util/mutex_wii.h
    engines/ags/engine/util/mutex_windows.h
    engines/ags/engine/util/scaling.h
    engines/ags/engine/util/thread.h
    engines/ags/engine/util/thread_psp.h
    engines/ags/engine/util/thread_pthread.h
    engines/ags/engine/util/thread_std.h
    engines/ags/engine/util/thread_wii.h
    engines/ags/engine/util/thread_windows.h
    engines/ags/shared/ac/audiocliptype.cpp
    engines/ags/shared/ac/audiocliptype.h
    engines/ags/shared/ac/characterinfo.cpp
    engines/ags/shared/ac/characterinfo.h
    engines/ags/shared/ac/common.cpp
    engines/ags/shared/ac/dialogtopic.cpp
    engines/ags/shared/ac/dialogtopic.h
    engines/ags/shared/ac/dynobj/scriptaudioclip.cpp
    engines/ags/shared/ac/dynobj/scriptaudioclip.h
    engines/ags/shared/ac/game_version.h
    engines/ags/shared/ac/gamesetupstruct.cpp
    engines/ags/shared/ac/gamesetupstruct.h
    engines/ags/shared/ac/gamesetupstructbase.cpp
    engines/ags/shared/ac/gamesetupstructbase.h
    engines/ags/shared/ac/gamestructdefines.h
    engines/ags/shared/ac/interfacebutton.h
    engines/ags/shared/ac/interfaceelement.h
    engines/ags/shared/ac/inventoryiteminfo.cpp
    engines/ags/shared/ac/inventoryiteminfo.h
    engines/ags/shared/ac/mousecursor.cpp
    engines/ags/shared/ac/mousecursor.h
    engines/ags/shared/ac/oldgamesetupstruct.h
    engines/ags/shared/ac/spritecache.cpp
    engines/ags/shared/ac/spritecache.h
    engines/ags/shared/ac/view.cpp
    engines/ags/shared/ac/view.h
    engines/ags/shared/ac/wordsdictionary.cpp
    engines/ags/shared/ac/wordsdictionary.h
    engines/ags/shared/api/stream_api.h
    engines/ags/shared/core/asset.cpp
    engines/ags/shared/core/asset.h
    engines/ags/shared/core/assetmanager.cpp
    engines/ags/shared/core/assetmanager.h
    engines/ags/shared/core/platform.h
    engines/ags/shared/core/types.h
    engines/ags/shared/debugging/debugmanager.cpp
    engines/ags/shared/debugging/debugmanager.h
    engines/ags/shared/debugging/out.h
    engines/ags/shared/debugging/outputhandler.h
    engines/ags/shared/font/agsfontrenderer.h
    engines/ags/shared/font/fonts.cpp
    engines/ags/shared/font/fonts.h
    engines/ags/shared/font/ttffontrenderer.cpp
    engines/ags/shared/font/ttffontrenderer.h
    engines/ags/shared/font/wfnfont.cpp
    engines/ags/shared/font/wfnfont.h
    engines/ags/shared/font/wfnfontrenderer.cpp
    engines/ags/shared/font/wfnfontrenderer.h
    engines/ags/shared/game/customproperties.cpp
    engines/ags/shared/game/customproperties.h
    engines/ags/shared/game/interactions.cpp
    engines/ags/shared/game/interactions.h
    engines/ags/shared/game/main_game_file.cpp
    engines/ags/shared/game/main_game_file.h
    engines/ags/shared/game/plugininfo.h
    engines/ags/shared/game/room_file.cpp
    engines/ags/shared/game/room_file.h
    engines/ags/shared/game/room_file_deprecated.cpp
    engines/ags/shared/game/room_version.h
    engines/ags/shared/game/roomstruct.cpp
    engines/ags/shared/game/roomstruct.h
    engines/ags/shared/gfx/allegrobitmap.cpp
    engines/ags/shared/gfx/allegrobitmap.h
    engines/ags/shared/gfx/bitmap.cpp
    engines/ags/shared/gfx/bitmap.h
    engines/ags/shared/gfx/gfx_def.h
    engines/ags/shared/gui/guibutton.cpp
    engines/ags/shared/gui/guibutton.h
    engines/ags/shared/gui/guidefines.h
    engines/ags/shared/gui/guiinv.cpp
    engines/ags/shared/gui/guiinv.h
    engines/ags/shared/gui/guilabel.cpp
    engines/ags/shared/gui/guilabel.h
    engines/ags/shared/gui/guilistbox.cpp
    engines/ags/shared/gui/guilistbox.h
    engines/ags/shared/gui/guimain.cpp
    engines/ags/shared/gui/guimain.h
    engines/ags/shared/gui/guiobject.cpp
    engines/ags/shared/gui/guiobject.h
    engines/ags/shared/gui/guislider.cpp
    engines/ags/shared/gui/guislider.h
    engines/ags/shared/gui/guitextbox.cpp
    engines/ags/shared/gui/guitextbox.h
    engines/ags/shared/script/cc_error.cpp
    engines/ags/shared/script/cc_options.cpp
    engines/ags/shared/script/cc_script.cpp
    engines/ags/shared/script/cc_script.h
    engines/ags/shared/util/alignedstream.cpp
    engines/ags/shared/util/alignedstream.h
    engines/ags/shared/util/bbop.h
    engines/ags/shared/util/bufferedstream.cpp
    engines/ags/shared/util/bufferedstream.h
    engines/ags/shared/util/compress.cpp
    engines/ags/shared/util/compress.h
    engines/ags/shared/util/datastream.cpp
    engines/ags/shared/util/datastream.h
    engines/ags/shared/util/directory.cpp
    engines/ags/shared/util/directory.h
    engines/ags/shared/util/error.h
    engines/ags/shared/util/file.cpp
    engines/ags/shared/util/file.h
    engines/ags/shared/util/filestream.cpp
    engines/ags/shared/util/filestream.h
    engines/ags/shared/util/geometry.cpp
    engines/ags/shared/util/geometry.h
    engines/ags/shared/util/ini_util.cpp
    engines/ags/shared/util/ini_util.h
    engines/ags/shared/util/inifile.cpp
    engines/ags/shared/util/inifile.h
    engines/ags/shared/util/lzw.cpp
    engines/ags/shared/util/lzw.h
    engines/ags/shared/util/math.h
    engines/ags/shared/util/memory.h
    engines/ags/shared/util/misc.cpp
    engines/ags/shared/util/misc.h
    engines/ags/shared/util/multifilelib.h
    engines/ags/shared/util/mutifilelib.cpp
    engines/ags/shared/util/path.cpp
    engines/ags/shared/util/path.h
    engines/ags/shared/util/proxystream.cpp
    engines/ags/shared/util/proxystream.h
    engines/ags/shared/util/stdio_compat.h
    engines/ags/shared/util/stream.cpp
    engines/ags/shared/util/stream.h
    engines/ags/shared/util/string.cpp
    engines/ags/shared/util/string.h
    engines/ags/shared/util/string_types.h
    engines/ags/shared/util/string_utils.cpp
    engines/ags/shared/util/string_utils.h
    engines/ags/shared/util/textreader.h
    engines/ags/shared/util/textstreamreader.cpp
    engines/ags/shared/util/textstreamreader.h
    engines/ags/shared/util/textstreamwriter.cpp
    engines/ags/shared/util/textstreamwriter.h
    engines/ags/shared/util/textwriter.h
    engines/ags/shared/util/version.cpp
    engines/ags/shared/util/version.h
    engines/ags/shared/util/wgt2allg.cpp
    engines/ags/shared/util/wgt2allg.h
    engines/ags/std/list.h
    engines/ags/std/map.h
    engines/ags/std/set.h
    engines/ags/std/vector.h
    engines/ags/stubs/allegro/base.h
    engines/ags/stubs/allegro/color.h
    engines/ags/stubs/allegro/digi.h
    engines/ags/stubs/allegro/fixed.cpp
    engines/ags/stubs/allegro/gfx.h
    engines/ags/stubs/allegro/midi.h


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index 133e2ec915..ce3961461c 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -35,7 +35,7 @@ AGSEngine *g_vm;
 /*------------------------------------------------------------------*/
 
 AGSEngine::AGSEngine(OSystem *syst, const AGSGameDescription *gameDesc) : Engine(syst),
-		_gameDescription(gameDesc), _randomSource("AGS") {
+	_gameDescription(gameDesc), _randomSource("AGS") {
 	g_vm = this;
 	DebugMan.addDebugChannel(kDebugPath, "Path", "Pathfinding debug level");
 	DebugMan.addDebugChannel(kDebugGraphics, "Graphics", "Graphics debug level");
diff --git a/engines/ags/detection.cpp b/engines/ags/detection.cpp
index 898cc29fb7..7956183a50 100644
--- a/engines/ags/detection.cpp
+++ b/engines/ags/detection.cpp
@@ -25,7 +25,7 @@
 #include "ags/detection_tables.h"
 
 AGSMetaEngineDetection::AGSMetaEngineDetection() : AdvancedMetaEngineDetection(AGS::GAME_DESCRIPTIONS,
-	sizeof(AGS::AGSGameDescription), AGS::AGS_GAMES) {
+	        sizeof(AGS::AGSGameDescription), AGS::AGS_GAMES) {
 	static const char *const DIRECTORY_GLOBS[2] = { "usecode", 0 };
 	_maxScanDepth = 2;
 	_directoryGlobs = DIRECTORY_GLOBS;
diff --git a/engines/ags/engine/ac/asset_helper.h b/engines/ags/engine/ac/asset_helper.h
index bfe4130c31..4efd81efb0 100644
--- a/engines/ags/engine/ac/asset_helper.h
+++ b/engines/ags/engine/ac/asset_helper.h
@@ -33,7 +33,11 @@
 #include <utility>
 #include "util/string.h"
 
-namespace AGS { namespace Common {class Stream;}}
+namespace AGS {
+namespace Common {
+class Stream;
+}
+}
 using AGS::Common::Stream;
 using AGS::Common::String;
 
@@ -45,8 +49,8 @@ String  get_known_assetlib(const String &filename);
 Stream *find_open_asset(const String &filename);
 
 extern "C" {
-    struct PACKFILE; // Allegro 4's own stream type
-    struct DUMBFILE; // DUMB stream type
+	struct PACKFILE; // Allegro 4's own stream type
+	struct DUMBFILE; // DUMB stream type
 }
 
 // AssetPath combines asset library and item names
@@ -62,11 +66,10 @@ AssetPath get_voice_over_assetpath(const String &filename);
 // Custom AGS PACKFILE user object
 // TODO: it is preferrable to let our Stream define custom readable window instead,
 // keeping this as simple as possible for now (we may require a stream classes overhaul).
-struct AGS_PACKFILE_OBJ
-{
-    std::unique_ptr<Stream> stream;
-    size_t asset_size = 0u;
-    size_t remains = 0u;
+struct AGS_PACKFILE_OBJ {
+	std::unique_ptr<Stream> stream;
+	size_t asset_size = 0u;
+	size_t remains = 0u;
 };
 // Creates PACKFILE stream from AGS asset.
 // This function is supposed to be used only when you have to create Allegro
diff --git a/engines/ags/engine/ac/audiochannel.cpp b/engines/ags/engine/ac/audiochannel.cpp
index 3f1190b017..e3898f35a6 100644
--- a/engines/ags/engine/ac/audiochannel.cpp
+++ b/engines/ags/engine/ac/audiochannel.cpp
@@ -35,194 +35,163 @@ extern GameState play;
 extern RoomStruct thisroom;
 extern CCAudioClip ccDynamicAudioClip;
 
-int AudioChannel_GetID(ScriptAudioChannel *channel)
-{
-    return channel->id;
+int AudioChannel_GetID(ScriptAudioChannel *channel) {
+	return channel->id;
 }
 
-int AudioChannel_GetIsPlaying(ScriptAudioChannel *channel)
-{
-    if (play.fast_forward)
-    {
-        return 0;
-    }
+int AudioChannel_GetIsPlaying(ScriptAudioChannel *channel) {
+	if (play.fast_forward) {
+		return 0;
+	}
 
-    return channel_is_playing(channel->id) ? 1 : 0;
+	return channel_is_playing(channel->id) ? 1 : 0;
 }
 
-int AudioChannel_GetPanning(ScriptAudioChannel *channel)
-{
-    AudioChannelsLock lock;
-    auto* ch = lock.GetChannelIfPlaying(channel->id);
+int AudioChannel_GetPanning(ScriptAudioChannel *channel) {
+	AudioChannelsLock lock;
+	auto *ch = lock.GetChannelIfPlaying(channel->id);
 
-    if (ch)
-    {
-        return ch->panningAsPercentage;
-    }
-    return 0;
+	if (ch) {
+		return ch->panningAsPercentage;
+	}
+	return 0;
 }
 
-void AudioChannel_SetPanning(ScriptAudioChannel *channel, int newPanning)
-{
-    if ((newPanning < -100) || (newPanning > 100))
-        quitprintf("!AudioChannel.Panning: panning value must be between -100 and 100 (passed=%d)", newPanning);
+void AudioChannel_SetPanning(ScriptAudioChannel *channel, int newPanning) {
+	if ((newPanning < -100) || (newPanning > 100))
+		quitprintf("!AudioChannel.Panning: panning value must be between -100 and 100 (passed=%d)", newPanning);
 
-    AudioChannelsLock lock;
-    auto* ch = lock.GetChannelIfPlaying(channel->id);
+	AudioChannelsLock lock;
+	auto *ch = lock.GetChannelIfPlaying(channel->id);
 
-    if (ch)
-    {
-        ch->set_panning(((newPanning + 100) * 255) / 200);
-        ch->panningAsPercentage = newPanning;
-    }
+	if (ch) {
+		ch->set_panning(((newPanning + 100) * 255) / 200);
+		ch->panningAsPercentage = newPanning;
+	}
 }
 
-ScriptAudioClip* AudioChannel_GetPlayingClip(ScriptAudioChannel *channel)
-{
-    AudioChannelsLock lock;
-    auto* ch = lock.GetChannelIfPlaying(channel->id);
+ScriptAudioClip *AudioChannel_GetPlayingClip(ScriptAudioChannel *channel) {
+	AudioChannelsLock lock;
+	auto *ch = lock.GetChannelIfPlaying(channel->id);
 
-    if (ch)
-    {
-        return (ScriptAudioClip*)ch->sourceClip;
-    }
-    return nullptr;
+	if (ch) {
+		return (ScriptAudioClip *)ch->sourceClip;
+	}
+	return nullptr;
 }
 
-int AudioChannel_GetPosition(ScriptAudioChannel *channel)
-{
-    AudioChannelsLock lock;
-    auto* ch = lock.GetChannelIfPlaying(channel->id);
+int AudioChannel_GetPosition(ScriptAudioChannel *channel) {
+	AudioChannelsLock lock;
+	auto *ch = lock.GetChannelIfPlaying(channel->id);
 
-    if (ch)
-    {
-        if (play.fast_forward)
-            return 999999999;
+	if (ch) {
+		if (play.fast_forward)
+			return 999999999;
 
-        return ch->get_pos();
-    }
-    return 0;
+		return ch->get_pos();
+	}
+	return 0;
 }
 
-int AudioChannel_GetPositionMs(ScriptAudioChannel *channel)
-{
-    AudioChannelsLock lock;
-    auto* ch = lock.GetChannelIfPlaying(channel->id);
+int AudioChannel_GetPositionMs(ScriptAudioChannel *channel) {
+	AudioChannelsLock lock;
+	auto *ch = lock.GetChannelIfPlaying(channel->id);
 
-    if (ch)
-    {
-        if (play.fast_forward)
-            return 999999999;
+	if (ch) {
+		if (play.fast_forward)
+			return 999999999;
 
-        return ch->get_pos_ms();
-    }
-    return 0;
+		return ch->get_pos_ms();
+	}
+	return 0;
 }
 
-int AudioChannel_GetLengthMs(ScriptAudioChannel *channel)
-{
-    AudioChannelsLock lock;
-    auto* ch = lock.GetChannelIfPlaying(channel->id);
+int AudioChannel_GetLengthMs(ScriptAudioChannel *channel) {
+	AudioChannelsLock lock;
+	auto *ch = lock.GetChannelIfPlaying(channel->id);
 
-    if (ch)
-    {
-        return ch->get_length_ms();
-    }
-    return 0;
+	if (ch) {
+		return ch->get_length_ms();
+	}
+	return 0;
 }
 
-int AudioChannel_GetVolume(ScriptAudioChannel *channel)
-{
-    AudioChannelsLock lock;
-    auto* ch = lock.GetChannelIfPlaying(channel->id);
+int AudioChannel_GetVolume(ScriptAudioChannel *channel) {
+	AudioChannelsLock lock;
+	auto *ch = lock.GetChannelIfPlaying(channel->id);
 
-    if (ch)
-    {
-        return ch->get_volume();
-    }
-    return 0;
+	if (ch) {
+		return ch->get_volume();
+	}
+	return 0;
 }
 
-int AudioChannel_SetVolume(ScriptAudioChannel *channel, int newVolume)
-{
-    if ((newVolume < 0) || (newVolume > 100))
-        quitprintf("!AudioChannel.Volume: new value out of range (supplied: %d, range: 0..100)", newVolume);
+int AudioChannel_SetVolume(ScriptAudioChannel *channel, int newVolume) {
+	if ((newVolume < 0) || (newVolume > 100))
+		quitprintf("!AudioChannel.Volume: new value out of range (supplied: %d, range: 0..100)", newVolume);
 
-    AudioChannelsLock lock;
-    auto* ch = lock.GetChannelIfPlaying(channel->id);
+	AudioChannelsLock lock;
+	auto *ch = lock.GetChannelIfPlaying(channel->id);
 
-    if (ch)
-    {
-        ch->set_volume_percent(newVolume);
-    }
-    return 0;
+	if (ch) {
+		ch->set_volume_percent(newVolume);
+	}
+	return 0;
 }
 
-int AudioChannel_GetSpeed(ScriptAudioChannel *channel)
-{
-    AudioChannelsLock lock;
-    auto* ch = lock.GetChannelIfPlaying(channel->id);
+int AudioChannel_GetSpeed(ScriptAudioChannel *channel) {
+	AudioChannelsLock lock;
+	auto *ch = lock.GetChannelIfPlaying(channel->id);
 
-    if (ch)
-    {
-        return ch->get_speed();
-    }
-    return 0;
+	if (ch) {
+		return ch->get_speed();
+	}
+	return 0;
 }
 
-void AudioChannel_SetSpeed(ScriptAudioChannel *channel, int new_speed)
-{
-    AudioChannelsLock lock;
-    auto* ch = lock.GetChannelIfPlaying(channel->id);
+void AudioChannel_SetSpeed(ScriptAudioChannel *channel, int new_speed) {
+	AudioChannelsLock lock;
+	auto *ch = lock.GetChannelIfPlaying(channel->id);
 
-    if (ch)
-    {
-        ch->set_speed(new_speed);
-    }
+	if (ch) {
+		ch->set_speed(new_speed);
+	}
 }
 
-void AudioChannel_Stop(ScriptAudioChannel *channel)
-{
-    if (channel->id == SCHAN_SPEECH && play.IsNonBlockingVoiceSpeech())
-        stop_voice_nonblocking();
-    else
-        stop_or_fade_out_channel(channel->id, -1, nullptr);
+void AudioChannel_Stop(ScriptAudioChannel *channel) {
+	if (channel->id == SCHAN_SPEECH && play.IsNonBlockingVoiceSpeech())
+		stop_voice_nonblocking();
+	else
+		stop_or_fade_out_channel(channel->id, -1, nullptr);
 }
 
-void AudioChannel_Seek(ScriptAudioChannel *channel, int newPosition)
-{
-    if (newPosition < 0)
-        quitprintf("!AudioChannel.Seek: invalid seek position %d", newPosition);
+void AudioChannel_Seek(ScriptAudioChannel *channel, int newPosition) {
+	if (newPosition < 0)
+		quitprintf("!AudioChannel.Seek: invalid seek position %d", newPosition);
 
-    AudioChannelsLock lock;
-    auto* ch = lock.GetChannelIfPlaying(channel->id);
+	AudioChannelsLock lock;
+	auto *ch = lock.GetChannelIfPlaying(channel->id);
 
-    if (ch)
-    {
-        ch->seek(newPosition);
-    }
+	if (ch) {
+		ch->seek(newPosition);
+	}
 }
 
-void AudioChannel_SetRoomLocation(ScriptAudioChannel *channel, int xPos, int yPos)
-{
-    AudioChannelsLock lock;
-    auto* ch = lock.GetChannelIfPlaying(channel->id);
-
-    if (ch)
-    {
-        int maxDist = ((xPos > thisroom.Width / 2) ? xPos : (thisroom.Width - xPos)) - AMBIENCE_FULL_DIST;
-        ch->xSource = (xPos > 0) ? xPos : -1;
-        ch->ySource = yPos;
-        ch->maximumPossibleDistanceAway = maxDist;
-        if (xPos > 0)
-        {
-            update_directional_sound_vol();
-        }
-        else
-        {
-            ch->apply_directional_modifier(0);
-        }
-    }
+void AudioChannel_SetRoomLocation(ScriptAudioChannel *channel, int xPos, int yPos) {
+	AudioChannelsLock lock;
+	auto *ch = lock.GetChannelIfPlaying(channel->id);
+
+	if (ch) {
+		int maxDist = ((xPos > thisroom.Width / 2) ? xPos : (thisroom.Width - xPos)) - AMBIENCE_FULL_DIST;
+		ch->xSource = (xPos > 0) ? xPos : -1;
+		ch->ySource = yPos;
+		ch->maximumPossibleDistanceAway = maxDist;
+		if (xPos > 0) {
+			update_directional_sound_vol();
+		} else {
+			ch->apply_directional_modifier(0);
+		}
+	}
 }
 
 //=============================================================================
@@ -236,126 +205,110 @@ void AudioChannel_SetRoomLocation(ScriptAudioChannel *channel, int xPos, int yPo
 #include "script/script_runtime.h"
 
 // int | ScriptAudioChannel *channel
-RuntimeScriptValue Sc_AudioChannel_GetID(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(ScriptAudioChannel, AudioChannel_GetID);
+RuntimeScriptValue Sc_AudioChannel_GetID(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(ScriptAudioChannel, AudioChannel_GetID);
 }
 
 // int | ScriptAudioChannel *channel
-RuntimeScriptValue Sc_AudioChannel_GetIsPlaying(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(ScriptAudioChannel, AudioChannel_GetIsPlaying);
+RuntimeScriptValue Sc_AudioChannel_GetIsPlaying(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(ScriptAudioChannel, AudioChannel_GetIsPlaying);
 }
 
 // int | ScriptAudioChannel *channel
-RuntimeScriptValue Sc_AudioChannel_GetPanning(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(ScriptAudioChannel, AudioChannel_GetPanning);
+RuntimeScriptValue Sc_AudioChannel_GetPanning(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(ScriptAudioChannel, AudioChannel_GetPanning);
 }
 
 // void | ScriptAudioChannel *channel, int newPanning
-RuntimeScriptValue Sc_AudioChannel_SetPanning(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(ScriptAudioChannel, AudioChannel_SetPanning);
+RuntimeScriptValue Sc_AudioChannel_SetPanning(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(ScriptAudioChannel, AudioChannel_SetPanning);
 }
 
 // ScriptAudioClip* | ScriptAudioChannel *channel
-RuntimeScriptValue Sc_AudioChannel_GetPlayingClip(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_OBJ(ScriptAudioChannel, ScriptAudioClip, ccDynamicAudioClip, AudioChannel_GetPlayingClip);
+RuntimeScriptValue Sc_AudioChannel_GetPlayingClip(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_OBJ(ScriptAudioChannel, ScriptAudioClip, ccDynamicAudioClip, AudioChannel_GetPlayingClip);
 }
 
 // int | ScriptAudioChannel *channel
-RuntimeScriptValue Sc_AudioChannel_GetPosition(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(ScriptAudioChannel, AudioChannel_GetPosition);
+RuntimeScriptValue Sc_AudioChannel_GetPosition(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(ScriptAudioChannel, AudioChannel_GetPosition);
 }
 
 // int | ScriptAudioChannel *channel
-RuntimeScriptValue Sc_AudioChannel_GetPositionMs(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(ScriptAudioChannel, AudioChannel_GetPositionMs);
+RuntimeScriptValue Sc_AudioChannel_GetPositionMs(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(ScriptAudioChannel, AudioChannel_GetPositionMs);
 }
 
 // int | ScriptAudioChannel *channel
-RuntimeScriptValue Sc_AudioChannel_GetLengthMs(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(ScriptAudioChannel, AudioChannel_GetLengthMs);
+RuntimeScriptValue Sc_AudioChannel_GetLengthMs(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(ScriptAudioChannel, AudioChannel_GetLengthMs);
 }
 
 // int | ScriptAudioChannel *channel
-RuntimeScriptValue Sc_AudioChannel_GetVolume(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(ScriptAudioChannel, AudioChannel_GetVolume);
+RuntimeScriptValue Sc_AudioChannel_GetVolume(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(ScriptAudioChannel, AudioChannel_GetVolume);
 }
 
 // int | ScriptAudioChannel *channel, int newVolume
-RuntimeScriptValue Sc_AudioChannel_SetVolume(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT_PINT(ScriptAudioChannel, AudioChannel_SetVolume);
+RuntimeScriptValue Sc_AudioChannel_SetVolume(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT_PINT(ScriptAudioChannel, AudioChannel_SetVolume);
 }
 
 // void | ScriptAudioChannel *channel
-RuntimeScriptValue Sc_AudioChannel_Stop(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID(ScriptAudioChannel, AudioChannel_Stop);
+RuntimeScriptValue Sc_AudioChannel_Stop(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID(ScriptAudioChannel, AudioChannel_Stop);
 }
 
 // void | ScriptAudioChannel *channel, int newPosition
-RuntimeScriptValue Sc_AudioChannel_Seek(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(ScriptAudioChannel, AudioChannel_Seek);
+RuntimeScriptValue Sc_AudioChannel_Seek(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(ScriptAudioChannel, AudioChannel_Seek);
 }
 
 // void | ScriptAudioChannel *channel, int xPos, int yPos
-RuntimeScriptValue Sc_AudioChannel_SetRoomLocation(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT2(ScriptAudioChannel, AudioChannel_SetRoomLocation);
+RuntimeScriptValue Sc_AudioChannel_SetRoomLocation(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT2(ScriptAudioChannel, AudioChannel_SetRoomLocation);
 }
 
-RuntimeScriptValue Sc_AudioChannel_GetSpeed(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(ScriptAudioChannel, AudioChannel_GetSpeed);
+RuntimeScriptValue Sc_AudioChannel_GetSpeed(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(ScriptAudioChannel, AudioChannel_GetSpeed);
 }
 
-RuntimeScriptValue Sc_AudioChannel_SetSpeed(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(ScriptAudioChannel, AudioChannel_SetSpeed);
+RuntimeScriptValue Sc_AudioChannel_SetSpeed(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(ScriptAudioChannel, AudioChannel_SetSpeed);
 }
 
-void RegisterAudioChannelAPI()
-{
-    ccAddExternalObjectFunction("AudioChannel::Seek^1",             Sc_AudioChannel_Seek);
-    ccAddExternalObjectFunction("AudioChannel::SetRoomLocation^2",  Sc_AudioChannel_SetRoomLocation);
-    ccAddExternalObjectFunction("AudioChannel::Stop^0",             Sc_AudioChannel_Stop);
-    ccAddExternalObjectFunction("AudioChannel::get_ID",             Sc_AudioChannel_GetID);
-    ccAddExternalObjectFunction("AudioChannel::get_IsPlaying",      Sc_AudioChannel_GetIsPlaying);
-    ccAddExternalObjectFunction("AudioChannel::get_LengthMs",       Sc_AudioChannel_GetLengthMs);
-    ccAddExternalObjectFunction("AudioChannel::get_Panning",        Sc_AudioChannel_GetPanning);
-    ccAddExternalObjectFunction("AudioChannel::set_Panning",        Sc_AudioChannel_SetPanning);
-    ccAddExternalObjectFunction("AudioChannel::get_PlayingClip",    Sc_AudioChannel_GetPlayingClip);
-    ccAddExternalObjectFunction("AudioChannel::get_Position",       Sc_AudioChannel_GetPosition);
-    ccAddExternalObjectFunction("AudioChannel::get_PositionMs",     Sc_AudioChannel_GetPositionMs);
-    ccAddExternalObjectFunction("AudioChannel::get_Volume",         Sc_AudioChannel_GetVolume);
-    ccAddExternalObjectFunction("AudioChannel::set_Volume",         Sc_AudioChannel_SetVolume);
-    ccAddExternalObjectFunction("AudioChannel::get_Speed",          Sc_AudioChannel_GetSpeed);
-    ccAddExternalObjectFunction("AudioChannel::set_Speed",          Sc_AudioChannel_SetSpeed);
-    // For compatibility with  Ahmet Kamil's (aka Gord10) custom engine
-    ccAddExternalObjectFunction("AudioChannel::SetSpeed^1",         Sc_AudioChannel_SetSpeed);
-
-    /* ----------------------- Registering unsafe exports for plugins -----------------------*/
-
-    ccAddExternalFunctionForPlugin("AudioChannel::Seek^1",             (void*)AudioChannel_Seek);
-    ccAddExternalFunctionForPlugin("AudioChannel::SetRoomLocation^2",  (void*)AudioChannel_SetRoomLocation);
-    ccAddExternalFunctionForPlugin("AudioChannel::Stop^0",             (void*)AudioChannel_Stop);
-    ccAddExternalFunctionForPlugin("AudioChannel::get_ID",             (void*)AudioChannel_GetID);
-    ccAddExternalFunctionForPlugin("AudioChannel::get_IsPlaying",      (void*)AudioChannel_GetIsPlaying);
-    ccAddExternalFunctionForPlugin("AudioChannel::get_LengthMs",       (void*)AudioChannel_GetLengthMs);
-    ccAddExternalFunctionForPlugin("AudioChannel::get_Panning",        (void*)AudioChannel_GetPanning);
-    ccAddExternalFunctionForPlugin("AudioChannel::set_Panning",        (void*)AudioChannel_SetPanning);
-    ccAddExternalFunctionForPlugin("AudioChannel::get_PlayingClip",    (void*)AudioChannel_GetPlayingClip);
-    ccAddExternalFunctionForPlugin("AudioChannel::get_Position",       (void*)AudioChannel_GetPosition);
-    ccAddExternalFunctionForPlugin("AudioChannel::get_PositionMs",     (void*)AudioChannel_GetPositionMs);
-    ccAddExternalFunctionForPlugin("AudioChannel::get_Volume",         (void*)AudioChannel_GetVolume);
-    ccAddExternalFunctionForPlugin("AudioChannel::set_Volume",         (void*)AudioChannel_SetVolume);
+void RegisterAudioChannelAPI() {
+	ccAddExternalObjectFunction("AudioChannel::Seek^1",             Sc_AudioChannel_Seek);
+	ccAddExternalObjectFunction("AudioChannel::SetRoomLocation^2",  Sc_AudioChannel_SetRoomLocation);
+	ccAddExternalObjectFunction("AudioChannel::Stop^0",             Sc_AudioChannel_Stop);
+	ccAddExternalObjectFunction("AudioChannel::get_ID",             Sc_AudioChannel_GetID);
+	ccAddExternalObjectFunction("AudioChannel::get_IsPlaying",      Sc_AudioChannel_GetIsPlaying);
+	ccAddExternalObjectFunction("AudioChannel::get_LengthMs",       Sc_AudioChannel_GetLengthMs);
+	ccAddExternalObjectFunction("AudioChannel::get_Panning",        Sc_AudioChannel_GetPanning);
+	ccAddExternalObjectFunction("AudioChannel::set_Panning",        Sc_AudioChannel_SetPanning);
+	ccAddExternalObjectFunction("AudioChannel::get_PlayingClip",    Sc_AudioChannel_GetPlayingClip);
+	ccAddExternalObjectFunction("AudioChannel::get_Position",       Sc_AudioChannel_GetPosition);
+	ccAddExternalObjectFunction("AudioChannel::get_PositionMs",     Sc_AudioChannel_GetPositionMs);
+	ccAddExternalObjectFunction("AudioChannel::get_Volume",         Sc_AudioChannel_GetVolume);
+	ccAddExternalObjectFunction("AudioChannel::set_Volume",         Sc_AudioChannel_SetVolume);
+	ccAddExternalObjectFunction("AudioChannel::get_Speed",          Sc_AudioChannel_GetSpeed);
+	ccAddExternalObjectFunction("AudioChannel::set_Speed",          Sc_AudioChannel_SetSpeed);
+	// For compatibility with  Ahmet Kamil's (aka Gord10) custom engine
+	ccAddExternalObjectFunction("AudioChannel::SetSpeed^1",         Sc_AudioChannel_SetSpeed);
+
+	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
+
+	ccAddExternalFunctionForPlugin("AudioChannel::Seek^1", (void *)AudioChannel_Seek);
+	ccAddExternalFunctionForPlugin("AudioChannel::SetRoomLocation^2", (void *)AudioChannel_SetRoomLocation);
+	ccAddExternalFunctionForPlugin("AudioChannel::Stop^0", (void *)AudioChannel_Stop);
+	ccAddExternalFunctionForPlugin("AudioChannel::get_ID", (void *)AudioChannel_GetID);
+	ccAddExternalFunctionForPlugin("AudioChannel::get_IsPlaying", (void *)AudioChannel_GetIsPlaying);
+	ccAddExternalFunctionForPlugin("AudioChannel::get_LengthMs", (void *)AudioChannel_GetLengthMs);
+	ccAddExternalFunctionForPlugin("AudioChannel::get_Panning", (void *)AudioChannel_GetPanning);
+	ccAddExternalFunctionForPlugin("AudioChannel::set_Panning", (void *)AudioChannel_SetPanning);
+	ccAddExternalFunctionForPlugin("AudioChannel::get_PlayingClip", (void *)AudioChannel_GetPlayingClip);
+	ccAddExternalFunctionForPlugin("AudioChannel::get_Position", (void *)AudioChannel_GetPosition);
+	ccAddExternalFunctionForPlugin("AudioChannel::get_PositionMs", (void *)AudioChannel_GetPositionMs);
+	ccAddExternalFunctionForPlugin("AudioChannel::get_Volume", (void *)AudioChannel_GetVolume);
+	ccAddExternalFunctionForPlugin("AudioChannel::set_Volume", (void *)AudioChannel_SetVolume);
 }
diff --git a/engines/ags/engine/ac/audiochannel.h b/engines/ags/engine/ac/audiochannel.h
index e3f4a82853..d130cb8a13 100644
--- a/engines/ags/engine/ac/audiochannel.h
+++ b/engines/ags/engine/ac/audiochannel.h
@@ -30,7 +30,7 @@ int     AudioChannel_GetID(ScriptAudioChannel *channel);
 int     AudioChannel_GetIsPlaying(ScriptAudioChannel *channel);
 int     AudioChannel_GetPanning(ScriptAudioChannel *channel);
 void    AudioChannel_SetPanning(ScriptAudioChannel *channel, int newPanning);
-ScriptAudioClip* AudioChannel_GetPlayingClip(ScriptAudioChannel *channel);
+ScriptAudioClip *AudioChannel_GetPlayingClip(ScriptAudioChannel *channel);
 int     AudioChannel_GetPosition(ScriptAudioChannel *channel);
 int     AudioChannel_GetPositionMs(ScriptAudioChannel *channel);
 int     AudioChannel_GetLengthMs(ScriptAudioChannel *channel);
diff --git a/engines/ags/engine/ac/audioclip.cpp b/engines/ags/engine/ac/audioclip.cpp
index 2a02f1fd95..2653c3aa26 100644
--- a/engines/ags/engine/ac/audioclip.cpp
+++ b/engines/ags/engine/ac/audioclip.cpp
@@ -32,54 +32,44 @@ extern GameSetupStruct game;
 extern ScriptAudioChannel scrAudioChannel[MAX_SOUND_CHANNELS + 1];
 extern CCAudioChannel ccDynamicAudio;
 
-int AudioClip_GetID(ScriptAudioClip *clip)
-{
-    return clip->id;
+int AudioClip_GetID(ScriptAudioClip *clip) {
+	return clip->id;
 }
 
-int AudioClip_GetFileType(ScriptAudioClip *clip)
-{
-    return clip->fileType;
+int AudioClip_GetFileType(ScriptAudioClip *clip) {
+	return clip->fileType;
 }
 
-int AudioClip_GetType(ScriptAudioClip *clip)
-{
-    return clip->type;
+int AudioClip_GetType(ScriptAudioClip *clip) {
+	return clip->type;
 }
-int AudioClip_GetIsAvailable(ScriptAudioClip *clip)
-{
-    return DoesAssetExistInLib(get_audio_clip_assetpath(clip->bundlingType, clip->fileName)) ? 1 : 0;
+int AudioClip_GetIsAvailable(ScriptAudioClip *clip) {
+	return DoesAssetExistInLib(get_audio_clip_assetpath(clip->bundlingType, clip->fileName)) ? 1 : 0;
 }
 
-void AudioClip_Stop(ScriptAudioClip *clip)
-{
-    AudioChannelsLock lock;
-    for (int i = 0; i < MAX_SOUND_CHANNELS; i++)
-    {
-        auto* ch = lock.GetChannelIfPlaying(i);
-        if ((ch != nullptr) && (ch->sourceClip == clip))
-        {
-            AudioChannel_Stop(&scrAudioChannel[i]);
-        }
-    }
+void AudioClip_Stop(ScriptAudioClip *clip) {
+	AudioChannelsLock lock;
+	for (int i = 0; i < MAX_SOUND_CHANNELS; i++) {
+		auto *ch = lock.GetChannelIfPlaying(i);
+		if ((ch != nullptr) && (ch->sourceClip == clip)) {
+			AudioChannel_Stop(&scrAudioChannel[i]);
+		}
+	}
 }
 
-ScriptAudioChannel* AudioClip_Play(ScriptAudioClip *clip, int priority, int repeat)
-{
-    ScriptAudioChannel *sc_ch = play_audio_clip(clip, priority, repeat, 0, false);
-    return sc_ch;
+ScriptAudioChannel *AudioClip_Play(ScriptAudioClip *clip, int priority, int repeat) {
+	ScriptAudioChannel *sc_ch = play_audio_clip(clip, priority, repeat, 0, false);
+	return sc_ch;
 }
 
-ScriptAudioChannel* AudioClip_PlayFrom(ScriptAudioClip *clip, int position, int priority, int repeat)
-{
-    ScriptAudioChannel *sc_ch = play_audio_clip(clip, priority, repeat, position, false);
-    return sc_ch;
+ScriptAudioChannel *AudioClip_PlayFrom(ScriptAudioClip *clip, int position, int priority, int repeat) {
+	ScriptAudioChannel *sc_ch = play_audio_clip(clip, priority, repeat, position, false);
+	return sc_ch;
 }
 
-ScriptAudioChannel* AudioClip_PlayQueued(ScriptAudioClip *clip, int priority, int repeat)
-{
-    ScriptAudioChannel *sc_ch = play_audio_clip(clip, priority, repeat, 0, true);
-    return sc_ch;
+ScriptAudioChannel *AudioClip_PlayQueued(ScriptAudioClip *clip, int priority, int repeat) {
+	ScriptAudioChannel *sc_ch = play_audio_clip(clip, priority, repeat, 0, true);
+	return sc_ch;
 }
 
 //=============================================================================
@@ -92,71 +82,62 @@ ScriptAudioChannel* AudioClip_PlayQueued(ScriptAudioClip *clip, int priority, in
 #include "script/script_api.h"
 #include "script/script_runtime.h"
 
-RuntimeScriptValue Sc_AudioClip_GetID(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(ScriptAudioClip, AudioClip_GetID);
+RuntimeScriptValue Sc_AudioClip_GetID(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(ScriptAudioClip, AudioClip_GetID);
 }
 
 // int | ScriptAudioClip *clip
-RuntimeScriptValue Sc_AudioClip_GetFileType(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(ScriptAudioClip, AudioClip_GetFileType);
+RuntimeScriptValue Sc_AudioClip_GetFileType(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(ScriptAudioClip, AudioClip_GetFileType);
 }
 
 // int | ScriptAudioClip *clip
-RuntimeScriptValue Sc_AudioClip_GetType(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(ScriptAudioClip, AudioClip_GetType);
+RuntimeScriptValue Sc_AudioClip_GetType(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(ScriptAudioClip, AudioClip_GetType);
 }
 
 // int | ScriptAudioClip *clip
-RuntimeScriptValue Sc_AudioClip_GetIsAvailable(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(ScriptAudioClip, AudioClip_GetIsAvailable);
+RuntimeScriptValue Sc_AudioClip_GetIsAvailable(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(ScriptAudioClip, AudioClip_GetIsAvailable);
 }
 
 // void | ScriptAudioClip *clip
-RuntimeScriptValue Sc_AudioClip_Stop(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID(ScriptAudioClip, AudioClip_Stop);
+RuntimeScriptValue Sc_AudioClip_Stop(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID(ScriptAudioClip, AudioClip_Stop);
 }
 
 // ScriptAudioChannel* | ScriptAudioClip *clip, int priority, int repeat
-RuntimeScriptValue Sc_AudioClip_Play(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_OBJ_PINT2(ScriptAudioClip, ScriptAudioChannel, ccDynamicAudio, AudioClip_Play);
+RuntimeScriptValue Sc_AudioClip_Play(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_OBJ_PINT2(ScriptAudioClip, ScriptAudioChannel, ccDynamicAudio, AudioClip_Play);
 }
 
 // ScriptAudioChannel* | ScriptAudioClip *clip, int position, int priority, int repeat
-RuntimeScriptValue Sc_AudioClip_PlayFrom(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_OBJ_PINT3(ScriptAudioClip, ScriptAudioChannel, ccDynamicAudio, AudioClip_PlayFrom);
+RuntimeScriptValue Sc_AudioClip_PlayFrom(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_OBJ_PINT3(ScriptAudioClip, ScriptAudioChannel, ccDynamicAudio, AudioClip_PlayFrom);
 }
 
 // ScriptAudioChannel* | ScriptAudioClip *clip, int priority, int repeat
-RuntimeScriptValue Sc_AudioClip_PlayQueued(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_OBJ_PINT2(ScriptAudioClip, ScriptAudioChannel, ccDynamicAudio, AudioClip_PlayQueued);
-}
-
-void RegisterAudioClipAPI()
-{
-    ccAddExternalObjectFunction("AudioClip::Play^2",            Sc_AudioClip_Play);
-    ccAddExternalObjectFunction("AudioClip::PlayFrom^3",        Sc_AudioClip_PlayFrom);
-    ccAddExternalObjectFunction("AudioClip::PlayQueued^2",      Sc_AudioClip_PlayQueued);
-    ccAddExternalObjectFunction("AudioClip::Stop^0",            Sc_AudioClip_Stop);
-    ccAddExternalObjectFunction("AudioClip::get_ID",            Sc_AudioClip_GetID);
-    ccAddExternalObjectFunction("AudioClip::get_FileType",      Sc_AudioClip_GetFileType);
-    ccAddExternalObjectFunction("AudioClip::get_IsAvailable",   Sc_AudioClip_GetIsAvailable);
-    ccAddExternalObjectFunction("AudioClip::get_Type",          Sc_AudioClip_GetType);
-
-    /* ----------------------- Registering unsafe exports for plugins -----------------------*/
-
-    ccAddExternalFunctionForPlugin("AudioClip::Play^2",            (void*)AudioClip_Play);
-    ccAddExternalFunctionForPlugin("AudioClip::PlayFrom^3",        (void*)AudioClip_PlayFrom);
-    ccAddExternalFunctionForPlugin("AudioClip::PlayQueued^2",      (void*)AudioClip_PlayQueued);
-    ccAddExternalFunctionForPlugin("AudioClip::Stop^0",            (void*)AudioClip_Stop);
-    ccAddExternalFunctionForPlugin("AudioClip::get_FileType",      (void*)AudioClip_GetFileType);
-    ccAddExternalFunctionForPlugin("AudioClip::get_IsAvailable",   (void*)AudioClip_GetIsAvailable);
-    ccAddExternalFunctionForPlugin("AudioClip::get_Type",          (void*)AudioClip_GetType);
+RuntimeScriptValue Sc_AudioClip_PlayQueued(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_OBJ_PINT2(ScriptAudioClip, ScriptAudioChannel, ccDynamicAudio, AudioClip_PlayQueued);
+}
+
+void RegisterAudioClipAPI() {
+	ccAddExternalObjectFunction("AudioClip::Play^2",            Sc_AudioClip_Play);
+	ccAddExternalObjectFunction("AudioClip::PlayFrom^3",        Sc_AudioClip_PlayFrom);
+	ccAddExternalObjectFunction("AudioClip::PlayQueued^2",      Sc_AudioClip_PlayQueued);
+	ccAddExternalObjectFunction("AudioClip::Stop^0",            Sc_AudioClip_Stop);
+	ccAddExternalObjectFunction("AudioClip::get_ID",            Sc_AudioClip_GetID);
+	ccAddExternalObjectFunction("AudioClip::get_FileType",      Sc_AudioClip_GetFileType);
+	ccAddExternalObjectFunction("AudioClip::get_IsAvailable",   Sc_AudioClip_GetIsAvailable);
+	ccAddExternalObjectFunction("AudioClip::get_Type",          Sc_AudioClip_GetType);
+
+	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
+
+	ccAddExternalFunctionForPlugin("AudioClip::Play^2", (void *)AudioClip_Play);
+	ccAddExternalFunctionForPlugin("AudioClip::PlayFrom^3", (void *)AudioClip_PlayFrom);
+	ccAddExternalFunctionForPlugin("AudioClip::PlayQueued^2", (void *)AudioClip_PlayQueued);
+	ccAddExternalFunctionForPlugin("AudioClip::Stop^0", (void *)AudioClip_Stop);
+	ccAddExternalFunctionForPlugin("AudioClip::get_FileType", (void *)AudioClip_GetFileType);
+	ccAddExternalFunctionForPlugin("AudioClip::get_IsAvailable", (void *)AudioClip_GetIsAvailable);
+	ccAddExternalFunctionForPlugin("AudioClip::get_Type", (void *)AudioClip_GetType);
 }
diff --git a/engines/ags/engine/ac/audioclip.h b/engines/ags/engine/ac/audioclip.h
index 7c66b2e057..8cd7514045 100644
--- a/engines/ags/engine/ac/audioclip.h
+++ b/engines/ags/engine/ac/audioclip.h
@@ -30,8 +30,8 @@ int     AudioClip_GetFileType(ScriptAudioClip *clip);
 int     AudioClip_GetType(ScriptAudioClip *clip);
 int     AudioClip_GetIsAvailable(ScriptAudioClip *clip);
 void    AudioClip_Stop(ScriptAudioClip *clip);
-ScriptAudioChannel* AudioClip_Play(ScriptAudioClip *clip, int priority, int repeat);
-ScriptAudioChannel* AudioClip_PlayFrom(ScriptAudioClip *clip, int position, int priority, int repeat);
-ScriptAudioChannel* AudioClip_PlayQueued(ScriptAudioClip *clip, int priority, int repeat);
+ScriptAudioChannel *AudioClip_Play(ScriptAudioClip *clip, int priority, int repeat);
+ScriptAudioChannel *AudioClip_PlayFrom(ScriptAudioClip *clip, int position, int priority, int repeat);
+ScriptAudioChannel *AudioClip_PlayQueued(ScriptAudioClip *clip, int priority, int repeat);
 
 #endif
diff --git a/engines/ags/engine/ac/button.cpp b/engines/ags/engine/ac/button.cpp
index f235292a3a..bf61dd5834 100644
--- a/engines/ags/engine/ac/button.cpp
+++ b/engines/ags/engine/ac/button.cpp
@@ -35,7 +35,7 @@
 using namespace AGS::Common;
 
 extern GameSetupStruct game;
-extern ViewStruct*views;
+extern ViewStruct *views;
 
 // *** BUTTON FUNCTIONS
 
@@ -43,152 +43,150 @@ AnimatingGUIButton animbuts[MAX_ANIMATING_BUTTONS];
 int numAnimButs;
 
 void Button_Animate(GUIButton *butt, int view, int loop, int speed, int repeat) {
-    int guin = butt->ParentId;
-    int objn = butt->Id;
+	int guin = butt->ParentId;
+	int objn = butt->Id;
 
-    if ((view < 1) || (view > game.numviews))
-        quit("!AnimateButton: invalid view specified");
-    view--;
+	if ((view < 1) || (view > game.numviews))
+		quit("!AnimateButton: invalid view specified");
+	view--;
 
-    if ((loop < 0) || (loop >= views[view].numLoops))
-        quit("!AnimateButton: invalid loop specified for view");
+	if ((loop < 0) || (loop >= views[view].numLoops))
+		quit("!AnimateButton: invalid loop specified for view");
 
-    // if it's already animating, stop it
-    FindAndRemoveButtonAnimation(guin, objn);
+	// if it's already animating, stop it
+	FindAndRemoveButtonAnimation(guin, objn);
 
-    if (numAnimButs >= MAX_ANIMATING_BUTTONS)
-        quit("!AnimateButton: too many animating GUI buttons at once");
+	if (numAnimButs >= MAX_ANIMATING_BUTTONS)
+		quit("!AnimateButton: too many animating GUI buttons at once");
 
-    int buttonId = guis[guin].GetControlID(objn);
+	int buttonId = guis[guin].GetControlID(objn);
 
-    guibuts[buttonId].PushedImage = 0;
-    guibuts[buttonId].MouseOverImage = 0;
+	guibuts[buttonId].PushedImage = 0;
+	guibuts[buttonId].MouseOverImage = 0;
 
-    animbuts[numAnimButs].ongui = guin;
-    animbuts[numAnimButs].onguibut = objn;
-    animbuts[numAnimButs].buttonid = buttonId;
-    animbuts[numAnimButs].view = view;
-    animbuts[numAnimButs].loop = loop;
-    animbuts[numAnimButs].speed = speed;
-    animbuts[numAnimButs].repeat = repeat;
-    animbuts[numAnimButs].frame = -1;
-    animbuts[numAnimButs].wait = 0;
-    numAnimButs++;
-    // launch into the first frame
-    if (UpdateAnimatingButton(numAnimButs - 1))
-    {
-        debug_script_warn("AnimateButton: no frames to animate");
-        StopButtonAnimation(numAnimButs - 1);
-    }
+	animbuts[numAnimButs].ongui = guin;
+	animbuts[numAnimButs].onguibut = objn;
+	animbuts[numAnimButs].buttonid = buttonId;
+	animbuts[numAnimButs].view = view;
+	animbuts[numAnimButs].loop = loop;
+	animbuts[numAnimButs].speed = speed;
+	animbuts[numAnimButs].repeat = repeat;
+	animbuts[numAnimButs].frame = -1;
+	animbuts[numAnimButs].wait = 0;
+	numAnimButs++;
+	// launch into the first frame
+	if (UpdateAnimatingButton(numAnimButs - 1)) {
+		debug_script_warn("AnimateButton: no frames to animate");
+		StopButtonAnimation(numAnimButs - 1);
+	}
 }
 
-const char* Button_GetText_New(GUIButton *butt) {
-    return CreateNewScriptString(butt->GetText());
+const char *Button_GetText_New(GUIButton *butt) {
+	return CreateNewScriptString(butt->GetText());
 }
 
 void Button_GetText(GUIButton *butt, char *buffer) {
-    strcpy(buffer, butt->GetText());
+	strcpy(buffer, butt->GetText());
 }
 
 void Button_SetText(GUIButton *butt, const char *newtx) {
-    newtx = get_translation(newtx);
+	newtx = get_translation(newtx);
 
-    if (strcmp(butt->GetText(), newtx)) {
-        guis_need_update = 1;
-        butt->SetText(newtx);
-    }
+	if (strcmp(butt->GetText(), newtx)) {
+		guis_need_update = 1;
+		butt->SetText(newtx);
+	}
 }
 
 void Button_SetFont(GUIButton *butt, int newFont) {
-    if ((newFont < 0) || (newFont >= game.numfonts))
-        quit("!Button.Font: invalid font number.");
+	if ((newFont < 0) || (newFont >= game.numfonts))
+		quit("!Button.Font: invalid font number.");
 
-    if (butt->Font != newFont) {
-        butt->Font = newFont;
-        guis_need_update = 1;
-    }
+	if (butt->Font != newFont) {
+		butt->Font = newFont;
+		guis_need_update = 1;
+	}
 }
 
 int Button_GetFont(GUIButton *butt) {
-    return butt->Font;
+	return butt->Font;
 }
 
 int Button_GetClipImage(GUIButton *butt) {
-    return butt->IsClippingImage() ? 1 : 0;
+	return butt->IsClippingImage() ? 1 : 0;
 }
 
 void Button_SetClipImage(GUIButton *butt, int newval) {
-    if (butt->IsClippingImage() != (newval != 0))
-    {
-        butt->SetClipImage(newval != 0);
-        guis_need_update = 1;
-    }
+	if (butt->IsClippingImage() != (newval != 0)) {
+		butt->SetClipImage(newval != 0);
+		guis_need_update = 1;
+	}
 }
 
 int Button_GetGraphic(GUIButton *butt) {
-    // return currently displayed pic
-    if (butt->CurrentImage < 0)
-        return butt->Image;
-    return butt->CurrentImage;
+	// return currently displayed pic
+	if (butt->CurrentImage < 0)
+		return butt->Image;
+	return butt->CurrentImage;
 }
 
 int Button_GetMouseOverGraphic(GUIButton *butt) {
-    return butt->MouseOverImage;
+	return butt->MouseOverImage;
 }
 
 void Button_SetMouseOverGraphic(GUIButton *guil, int slotn) {
-    debug_script_log("GUI %d Button %d mouseover set to slot %d", guil->ParentId, guil->Id, slotn);
+	debug_script_log("GUI %d Button %d mouseover set to slot %d", guil->ParentId, guil->Id, slotn);
 
-    if ((guil->IsMouseOver != 0) && (guil->IsPushed == 0))
-        guil->CurrentImage = slotn;
-    guil->MouseOverImage = slotn;
+	if ((guil->IsMouseOver != 0) && (guil->IsPushed == 0))
+		guil->CurrentImage = slotn;
+	guil->MouseOverImage = slotn;
 
-    guis_need_update = 1;
-    FindAndRemoveButtonAnimation(guil->ParentId, guil->Id);
+	guis_need_update = 1;
+	FindAndRemoveButtonAnimation(guil->ParentId, guil->Id);
 }
 
 int Button_GetNormalGraphic(GUIButton *butt) {
-    return butt->Image;
+	return butt->Image;
 }
 
 void Button_SetNormalGraphic(GUIButton *guil, int slotn) {
-    debug_script_log("GUI %d Button %d normal set to slot %d", guil->ParentId, guil->Id, slotn);
-    // normal pic - update if mouse is not over, or if there's no MouseOverImage
-    if (((guil->IsMouseOver == 0) || (guil->MouseOverImage < 1)) && (guil->IsPushed == 0))
-        guil->CurrentImage = slotn;
-    guil->Image = slotn;
-    // update the clickable area to the same size as the graphic
-    guil->Width = game.SpriteInfos[slotn].Width;
-    guil->Height = game.SpriteInfos[slotn].Height;
+	debug_script_log("GUI %d Button %d normal set to slot %d", guil->ParentId, guil->Id, slotn);
+	// normal pic - update if mouse is not over, or if there's no MouseOverImage
+	if (((guil->IsMouseOver == 0) || (guil->MouseOverImage < 1)) && (guil->IsPushed == 0))
+		guil->CurrentImage = slotn;
+	guil->Image = slotn;
+	// update the clickable area to the same size as the graphic
+	guil->Width = game.SpriteInfos[slotn].Width;
+	guil->Height = game.SpriteInfos[slotn].Height;
 
-    guis_need_update = 1;
-    FindAndRemoveButtonAnimation(guil->ParentId, guil->Id);
+	guis_need_update = 1;
+	FindAndRemoveButtonAnimation(guil->ParentId, guil->Id);
 }
 
 int Button_GetPushedGraphic(GUIButton *butt) {
-    return butt->PushedImage;
+	return butt->PushedImage;
 }
 
 void Button_SetPushedGraphic(GUIButton *guil, int slotn) {
-    debug_script_log("GUI %d Button %d pushed set to slot %d", guil->ParentId, guil->Id, slotn);
+	debug_script_log("GUI %d Button %d pushed set to slot %d", guil->ParentId, guil->Id, slotn);
 
-    if (guil->IsPushed)
-        guil->CurrentImage = slotn;
-    guil->PushedImage = slotn;
+	if (guil->IsPushed)
+		guil->CurrentImage = slotn;
+	guil->PushedImage = slotn;
 
-    guis_need_update = 1;
-    FindAndRemoveButtonAnimation(guil->ParentId, guil->Id);
+	guis_need_update = 1;
+	FindAndRemoveButtonAnimation(guil->ParentId, guil->Id);
 }
 
 int Button_GetTextColor(GUIButton *butt) {
-    return butt->TextColor;
+	return butt->TextColor;
 }
 
 void Button_SetTextColor(GUIButton *butt, int newcol) {
-    if (butt->TextColor != newcol) {
-        butt->TextColor = newcol;
-        guis_need_update = 1;
-    }
+	if (butt->TextColor != newcol) {
+		butt->TextColor = newcol;
+		guis_need_update = 1;
+	}
 }
 
 extern AnimatingGUIButton animbuts[MAX_ANIMATING_BUTTONS];
@@ -198,114 +196,101 @@ extern int numAnimButs;
 
 // returns 1 if animation finished
 int UpdateAnimatingButton(int bu) {
-    if (animbuts[bu].wait > 0) {
-        animbuts[bu].wait--;
-        return 0;
-    }
-    ViewStruct *tview = &views[animbuts[bu].view];
-
-    animbuts[bu].frame++;
-
-    if (animbuts[bu].frame >= tview->loops[animbuts[bu].loop].numFrames) 
-    {
-        if (tview->loops[animbuts[bu].loop].RunNextLoop()) {
-            // go to next loop
-            animbuts[bu].loop++;
-            animbuts[bu].frame = 0;
-        }
-        else if (animbuts[bu].repeat) {
-            animbuts[bu].frame = 0;
-            // multi-loop anim, go back
-            while ((animbuts[bu].loop > 0) && 
-                (tview->loops[animbuts[bu].loop - 1].RunNextLoop()))
-                animbuts[bu].loop--;
-        }
-        else
-            return 1;
-    }
-
-    CheckViewFrame(animbuts[bu].view, animbuts[bu].loop, animbuts[bu].frame);
-
-    // update the button's image
-    guibuts[animbuts[bu].buttonid].Image = tview->loops[animbuts[bu].loop].frames[animbuts[bu].frame].pic;
-    guibuts[animbuts[bu].buttonid].CurrentImage = guibuts[animbuts[bu].buttonid].Image;
-    guibuts[animbuts[bu].buttonid].PushedImage = 0;
-    guibuts[animbuts[bu].buttonid].MouseOverImage = 0;
-    guis_need_update = 1;
-
-    animbuts[bu].wait = animbuts[bu].speed + tview->loops[animbuts[bu].loop].frames[animbuts[bu].frame].speed;
-    return 0;
+	if (animbuts[bu].wait > 0) {
+		animbuts[bu].wait--;
+		return 0;
+	}
+	ViewStruct *tview = &views[animbuts[bu].view];
+
+	animbuts[bu].frame++;
+
+	if (animbuts[bu].frame >= tview->loops[animbuts[bu].loop].numFrames) {
+		if (tview->loops[animbuts[bu].loop].RunNextLoop()) {
+			// go to next loop
+			animbuts[bu].loop++;
+			animbuts[bu].frame = 0;
+		} else if (animbuts[bu].repeat) {
+			animbuts[bu].frame = 0;
+			// multi-loop anim, go back
+			while ((animbuts[bu].loop > 0) &&
+			        (tview->loops[animbuts[bu].loop - 1].RunNextLoop()))
+				animbuts[bu].loop--;
+		} else
+			return 1;
+	}
+
+	CheckViewFrame(animbuts[bu].view, animbuts[bu].loop, animbuts[bu].frame);
+
+	// update the button's image
+	guibuts[animbuts[bu].buttonid].Image = tview->loops[animbuts[bu].loop].frames[animbuts[bu].frame].pic;
+	guibuts[animbuts[bu].buttonid].CurrentImage = guibuts[animbuts[bu].buttonid].Image;
+	guibuts[animbuts[bu].buttonid].PushedImage = 0;
+	guibuts[animbuts[bu].buttonid].MouseOverImage = 0;
+	guis_need_update = 1;
+
+	animbuts[bu].wait = animbuts[bu].speed + tview->loops[animbuts[bu].loop].frames[animbuts[bu].frame].speed;
+	return 0;
 }
 
 void StopButtonAnimation(int idxn) {
-    numAnimButs--;
-    for (int aa = idxn; aa < numAnimButs; aa++) {
-        animbuts[aa] = animbuts[aa + 1];
-    }
+	numAnimButs--;
+	for (int aa = idxn; aa < numAnimButs; aa++) {
+		animbuts[aa] = animbuts[aa + 1];
+	}
 }
 
 // Returns the index of the AnimatingGUIButton object corresponding to the
 // given button ID; returns -1 if no such animation exists
-int FindAnimatedButton(int guin, int objn)
-{
-    for (int i = 0; i < numAnimButs; ++i)
-    {
-        if (animbuts[i].ongui == guin && animbuts[i].onguibut == objn)
-            return i;
-    }
-    return -1;
-}
-
-void FindAndRemoveButtonAnimation(int guin, int objn)
-{
-    int idx = FindAnimatedButton(guin, objn);
-    if (idx >= 0)
-        StopButtonAnimation(idx);
+int FindAnimatedButton(int guin, int objn) {
+	for (int i = 0; i < numAnimButs; ++i) {
+		if (animbuts[i].ongui == guin && animbuts[i].onguibut == objn)
+			return i;
+	}
+	return -1;
+}
+
+void FindAndRemoveButtonAnimation(int guin, int objn) {
+	int idx = FindAnimatedButton(guin, objn);
+	if (idx >= 0)
+		StopButtonAnimation(idx);
 }
 // ** end animating buttons code
 
-void Button_Click(GUIButton *butt, int mbut)
-{
-    process_interface_click(butt->ParentId, butt->Id, mbut);
+void Button_Click(GUIButton *butt, int mbut) {
+	process_interface_click(butt->ParentId, butt->Id, mbut);
 }
 
-bool Button_IsAnimating(GUIButton *butt)
-{
-    return FindAnimatedButton(butt->ParentId, butt->Id) >= 0;
+bool Button_IsAnimating(GUIButton *butt) {
+	return FindAnimatedButton(butt->ParentId, butt->Id) >= 0;
 }
 
 // NOTE: in correspondance to similar functions for Character & Object,
 // GetView returns (view index + 1), while GetLoop and GetFrame return
 // zero-based index and 0 in case of no animation.
-int Button_GetAnimView(GUIButton *butt)
-{
-    int idx = FindAnimatedButton(butt->ParentId, butt->Id);
-    return idx >= 0 ? animbuts[idx].view + 1 : 0;
+int Button_GetAnimView(GUIButton *butt) {
+	int idx = FindAnimatedButton(butt->ParentId, butt->Id);
+	return idx >= 0 ? animbuts[idx].view + 1 : 0;
 }
 
-int Button_GetAnimLoop(GUIButton *butt)
-{
-    int idx = FindAnimatedButton(butt->ParentId, butt->Id);
-    return idx >= 0 ? animbuts[idx].loop : 0;
+int Button_GetAnimLoop(GUIButton *butt) {
+	int idx = FindAnimatedButton(butt->ParentId, butt->Id);
+	return idx >= 0 ? animbuts[idx].loop : 0;
 }
 
-int Button_GetAnimFrame(GUIButton *butt)
-{
-    int idx = FindAnimatedButton(butt->ParentId, butt->Id);
-    return idx >= 0 ? animbuts[idx].frame : 0;
+int Button_GetAnimFrame(GUIButton *butt) {
+	int idx = FindAnimatedButton(butt->ParentId, butt->Id);
+	return idx >= 0 ? animbuts[idx].frame : 0;
 }
 
-int Button_GetTextAlignment(GUIButton *butt)
-{
-    return butt->TextAlignment;
+int Button_GetTextAlignment(GUIButton *butt) {
+	return butt->TextAlignment;
 }
 
-void Button_SetTextAlignment(GUIButton *butt, int align)
-{
-    if (butt->TextAlignment != align) {
-        butt->TextAlignment = (FrameAlignment)align;
-        guis_need_update = 1;
-    }
+void Button_SetTextAlignment(GUIButton *butt, int align) {
+	if (butt->TextAlignment != align) {
+		butt->TextAlignment = (FrameAlignment)align;
+		guis_need_update = 1;
+	}
 }
 
 //=============================================================================
@@ -322,188 +307,163 @@ void Button_SetTextAlignment(GUIButton *butt, int align)
 extern ScriptString myScriptStringImpl;
 
 // void | GUIButton *butt, int view, int loop, int speed, int repeat
-RuntimeScriptValue Sc_Button_Animate(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT4(GUIButton, Button_Animate);
+RuntimeScriptValue Sc_Button_Animate(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT4(GUIButton, Button_Animate);
 }
 
 // const char* | GUIButton *butt
-RuntimeScriptValue Sc_Button_GetText_New(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_OBJ(GUIButton, const char, myScriptStringImpl, Button_GetText_New);
+RuntimeScriptValue Sc_Button_GetText_New(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_OBJ(GUIButton, const char, myScriptStringImpl, Button_GetText_New);
 }
 
 // void | GUIButton *butt, char *buffer
-RuntimeScriptValue Sc_Button_GetText(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_POBJ(GUIButton, Button_GetText, char);
+RuntimeScriptValue Sc_Button_GetText(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_POBJ(GUIButton, Button_GetText, char);
 }
 
 // void | GUIButton *butt, const char *newtx
-RuntimeScriptValue Sc_Button_SetText(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_POBJ(GUIButton, Button_SetText, const char);
+RuntimeScriptValue Sc_Button_SetText(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_POBJ(GUIButton, Button_SetText, const char);
 }
 
 // void | GUIButton *butt, int newFont
-RuntimeScriptValue Sc_Button_SetFont(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(GUIButton, Button_SetFont);
+RuntimeScriptValue Sc_Button_SetFont(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(GUIButton, Button_SetFont);
 }
 
 // int | GUIButton *butt
-RuntimeScriptValue Sc_Button_GetFont(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(GUIButton, Button_GetFont);
+RuntimeScriptValue Sc_Button_GetFont(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(GUIButton, Button_GetFont);
 }
 
 // int | GUIButton *butt
-RuntimeScriptValue Sc_Button_GetClipImage(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(GUIButton, Button_GetClipImage);
+RuntimeScriptValue Sc_Button_GetClipImage(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(GUIButton, Button_GetClipImage);
 }
 
 // void | GUIButton *butt, int newval
-RuntimeScriptValue Sc_Button_SetClipImage(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(GUIButton, Button_SetClipImage);
+RuntimeScriptValue Sc_Button_SetClipImage(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(GUIButton, Button_SetClipImage);
 }
 
 // int | GUIButton *butt
-RuntimeScriptValue Sc_Button_GetGraphic(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(GUIButton, Button_GetGraphic);
+RuntimeScriptValue Sc_Button_GetGraphic(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(GUIButton, Button_GetGraphic);
 }
 
 // int | GUIButton *butt
-RuntimeScriptValue Sc_Button_GetMouseOverGraphic(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(GUIButton, Button_GetMouseOverGraphic);
+RuntimeScriptValue Sc_Button_GetMouseOverGraphic(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(GUIButton, Button_GetMouseOverGraphic);
 }
 
 // void | GUIButton *guil, int slotn
-RuntimeScriptValue Sc_Button_SetMouseOverGraphic(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(GUIButton, Button_SetMouseOverGraphic);
+RuntimeScriptValue Sc_Button_SetMouseOverGraphic(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(GUIButton, Button_SetMouseOverGraphic);
 }
 
 // int | GUIButton *butt
-RuntimeScriptValue Sc_Button_GetNormalGraphic(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(GUIButton, Button_GetNormalGraphic);
+RuntimeScriptValue Sc_Button_GetNormalGraphic(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(GUIButton, Button_GetNormalGraphic);
 }
 
 // void | GUIButton *guil, int slotn
-RuntimeScriptValue Sc_Button_SetNormalGraphic(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(GUIButton, Button_SetNormalGraphic);
+RuntimeScriptValue Sc_Button_SetNormalGraphic(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(GUIButton, Button_SetNormalGraphic);
 }
 
 // int | GUIButton *butt
-RuntimeScriptValue Sc_Button_GetPushedGraphic(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(GUIButton, Button_GetPushedGraphic);
+RuntimeScriptValue Sc_Button_GetPushedGraphic(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(GUIButton, Button_GetPushedGraphic);
 }
 
 // void | GUIButton *guil, int slotn
-RuntimeScriptValue Sc_Button_SetPushedGraphic(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(GUIButton, Button_SetPushedGraphic);
+RuntimeScriptValue Sc_Button_SetPushedGraphic(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(GUIButton, Button_SetPushedGraphic);
 }
 
 // int | GUIButton *butt
-RuntimeScriptValue Sc_Button_GetTextColor(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(GUIButton, Button_GetTextColor);
+RuntimeScriptValue Sc_Button_GetTextColor(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(GUIButton, Button_GetTextColor);
 }
 
 // void | GUIButton *butt, int newcol
-RuntimeScriptValue Sc_Button_SetTextColor(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(GUIButton, Button_SetTextColor);
-}
-
-RuntimeScriptValue Sc_Button_Click(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(GUIButton, Button_Click);
-}
-
-RuntimeScriptValue Sc_Button_GetAnimating(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_BOOL(GUIButton, Button_IsAnimating);
-}
-
-RuntimeScriptValue Sc_Button_GetTextAlignment(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(GUIButton, Button_GetTextAlignment);
-}
-
-RuntimeScriptValue Sc_Button_SetTextAlignment(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(GUIButton, Button_SetTextAlignment);
-}
-
-RuntimeScriptValue Sc_Button_GetFrame(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(GUIButton, Button_GetAnimFrame);
-}
-
-RuntimeScriptValue Sc_Button_GetLoop(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(GUIButton, Button_GetAnimLoop);
-}
-
-RuntimeScriptValue Sc_Button_GetView(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(GUIButton, Button_GetAnimView);
-}
-
-void RegisterButtonAPI()
-{
-    ccAddExternalObjectFunction("Button::Animate^4",            Sc_Button_Animate);
-    ccAddExternalObjectFunction("Button::Click^1",              Sc_Button_Click);
-    ccAddExternalObjectFunction("Button::GetText^1",            Sc_Button_GetText);
-    ccAddExternalObjectFunction("Button::SetText^1",            Sc_Button_SetText);
-    ccAddExternalObjectFunction("Button::get_TextAlignment",    Sc_Button_GetTextAlignment);
-    ccAddExternalObjectFunction("Button::set_TextAlignment",    Sc_Button_SetTextAlignment);
-    ccAddExternalObjectFunction("Button::get_Animating",        Sc_Button_GetAnimating);
-    ccAddExternalObjectFunction("Button::get_ClipImage",        Sc_Button_GetClipImage);
-    ccAddExternalObjectFunction("Button::set_ClipImage",        Sc_Button_SetClipImage);
-    ccAddExternalObjectFunction("Button::get_Font",             Sc_Button_GetFont);
-    ccAddExternalObjectFunction("Button::set_Font",             Sc_Button_SetFont);
-    ccAddExternalObjectFunction("Button::get_Frame",            Sc_Button_GetFrame);
-    ccAddExternalObjectFunction("Button::get_Graphic",          Sc_Button_GetGraphic);
-    ccAddExternalObjectFunction("Button::get_Loop",             Sc_Button_GetLoop);
-    ccAddExternalObjectFunction("Button::get_MouseOverGraphic", Sc_Button_GetMouseOverGraphic);
-    ccAddExternalObjectFunction("Button::set_MouseOverGraphic", Sc_Button_SetMouseOverGraphic);
-    ccAddExternalObjectFunction("Button::get_NormalGraphic",    Sc_Button_GetNormalGraphic);
-    ccAddExternalObjectFunction("Button::set_NormalGraphic",    Sc_Button_SetNormalGraphic);
-    ccAddExternalObjectFunction("Button::get_PushedGraphic",    Sc_Button_GetPushedGraphic);
-    ccAddExternalObjectFunction("Button::set_PushedGraphic",    Sc_Button_SetPushedGraphic);
-    ccAddExternalObjectFunction("Button::get_Text",             Sc_Button_GetText_New);
-    ccAddExternalObjectFunction("Button::set_Text",             Sc_Button_SetText);
-    ccAddExternalObjectFunction("Button::get_TextColor",        Sc_Button_GetTextColor);
-    ccAddExternalObjectFunction("Button::set_TextColor",        Sc_Button_SetTextColor);
-    ccAddExternalObjectFunction("Button::get_View",             Sc_Button_GetView);
-
-    /* ----------------------- Registering unsafe exports for plugins -----------------------*/
-
-    ccAddExternalFunctionForPlugin("Button::Animate^4",            (void*)Button_Animate);
-    ccAddExternalFunctionForPlugin("Button::GetText^1",            (void*)Button_GetText);
-    ccAddExternalFunctionForPlugin("Button::SetText^1",            (void*)Button_SetText);
-    ccAddExternalFunctionForPlugin("Button::get_ClipImage",        (void*)Button_GetClipImage);
-    ccAddExternalFunctionForPlugin("Button::set_ClipImage",        (void*)Button_SetClipImage);
-    ccAddExternalFunctionForPlugin("Button::get_Font",             (void*)Button_GetFont);
-    ccAddExternalFunctionForPlugin("Button::set_Font",             (void*)Button_SetFont);
-    ccAddExternalFunctionForPlugin("Button::get_Graphic",          (void*)Button_GetGraphic);
-    ccAddExternalFunctionForPlugin("Button::get_MouseOverGraphic", (void*)Button_GetMouseOverGraphic);
-    ccAddExternalFunctionForPlugin("Button::set_MouseOverGraphic", (void*)Button_SetMouseOverGraphic);
-    ccAddExternalFunctionForPlugin("Button::get_NormalGraphic",    (void*)Button_GetNormalGraphic);
-    ccAddExternalFunctionForPlugin("Button::set_NormalGraphic",    (void*)Button_SetNormalGraphic);
-    ccAddExternalFunctionForPlugin("Button::get_PushedGraphic",    (void*)Button_GetPushedGraphic);
-    ccAddExternalFunctionForPlugin("Button::set_PushedGraphic",    (void*)Button_SetPushedGraphic);
-    ccAddExternalFunctionForPlugin("Button::get_Text",             (void*)Button_GetText_New);
-    ccAddExternalFunctionForPlugin("Button::set_Text",             (void*)Button_SetText);
-    ccAddExternalFunctionForPlugin("Button::get_TextColor",        (void*)Button_GetTextColor);
-    ccAddExternalFunctionForPlugin("Button::set_TextColor",        (void*)Button_SetTextColor);
+RuntimeScriptValue Sc_Button_SetTextColor(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(GUIButton, Button_SetTextColor);
+}
+
+RuntimeScriptValue Sc_Button_Click(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(GUIButton, Button_Click);
+}
+
+RuntimeScriptValue Sc_Button_GetAnimating(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_BOOL(GUIButton, Button_IsAnimating);
+}
+
+RuntimeScriptValue Sc_Button_GetTextAlignment(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(GUIButton, Button_GetTextAlignment);
+}
+
+RuntimeScriptValue Sc_Button_SetTextAlignment(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(GUIButton, Button_SetTextAlignment);
+}
+
+RuntimeScriptValue Sc_Button_GetFrame(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(GUIButton, Button_GetAnimFrame);
+}
+
+RuntimeScriptValue Sc_Button_GetLoop(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(GUIButton, Button_GetAnimLoop);
+}
+
+RuntimeScriptValue Sc_Button_GetView(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(GUIButton, Button_GetAnimView);
+}
+
+void RegisterButtonAPI() {
+	ccAddExternalObjectFunction("Button::Animate^4",            Sc_Button_Animate);
+	ccAddExternalObjectFunction("Button::Click^1",              Sc_Button_Click);
+	ccAddExternalObjectFunction("Button::GetText^1",            Sc_Button_GetText);
+	ccAddExternalObjectFunction("Button::SetText^1",            Sc_Button_SetText);
+	ccAddExternalObjectFunction("Button::get_TextAlignment",    Sc_Button_GetTextAlignment);
+	ccAddExternalObjectFunction("Button::set_TextAlignment",    Sc_Button_SetTextAlignment);
+	ccAddExternalObjectFunction("Button::get_Animating",        Sc_Button_GetAnimating);
+	ccAddExternalObjectFunction("Button::get_ClipImage",        Sc_Button_GetClipImage);
+	ccAddExternalObjectFunction("Button::set_ClipImage",        Sc_Button_SetClipImage);
+	ccAddExternalObjectFunction("Button::get_Font",             Sc_Button_GetFont);
+	ccAddExternalObjectFunction("Button::set_Font",             Sc_Button_SetFont);
+	ccAddExternalObjectFunction("Button::get_Frame",            Sc_Button_GetFrame);
+	ccAddExternalObjectFunction("Button::get_Graphic",          Sc_Button_GetGraphic);
+	ccAddExternalObjectFunction("Button::get_Loop",             Sc_Button_GetLoop);
+	ccAddExternalObjectFunction("Button::get_MouseOverGraphic", Sc_Button_GetMouseOverGraphic);
+	ccAddExternalObjectFunction("Button::set_MouseOverGraphic", Sc_Button_SetMouseOverGraphic);
+	ccAddExternalObjectFunction("Button::get_NormalGraphic",    Sc_Button_GetNormalGraphic);
+	ccAddExternalObjectFunction("Button::set_NormalGraphic",    Sc_Button_SetNormalGraphic);
+	ccAddExternalObjectFunction("Button::get_PushedGraphic",    Sc_Button_GetPushedGraphic);
+	ccAddExternalObjectFunction("Button::set_PushedGraphic",    Sc_Button_SetPushedGraphic);
+	ccAddExternalObjectFunction("Button::get_Text",             Sc_Button_GetText_New);
+	ccAddExternalObjectFunction("Button::set_Text",             Sc_Button_SetText);
+	ccAddExternalObjectFunction("Button::get_TextColor",        Sc_Button_GetTextColor);
+	ccAddExternalObjectFunction("Button::set_TextColor",        Sc_Button_SetTextColor);
+	ccAddExternalObjectFunction("Button::get_View",             Sc_Button_GetView);
+
+	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
+
+	ccAddExternalFunctionForPlugin("Button::Animate^4", (void *)Button_Animate);
+	ccAddExternalFunctionForPlugin("Button::GetText^1", (void *)Button_GetText);
+	ccAddExternalFunctionForPlugin("Button::SetText^1", (void *)Button_SetText);
+	ccAddExternalFunctionForPlugin("Button::get_ClipImage", (void *)Button_GetClipImage);
+	ccAddExternalFunctionForPlugin("Button::set_ClipImage", (void *)Button_SetClipImage);
+	ccAddExternalFunctionForPlugin("Button::get_Font", (void *)Button_GetFont);
+	ccAddExternalFunctionForPlugin("Button::set_Font", (void *)Button_SetFont);
+	ccAddExternalFunctionForPlugin("Button::get_Graphic", (void *)Button_GetGraphic);
+	ccAddExternalFunctionForPlugin("Button::get_MouseOverGraphic", (void *)Button_GetMouseOverGraphic);
+	ccAddExternalFunctionForPlugin("Button::set_MouseOverGraphic", (void *)Button_SetMouseOverGraphic);
+	ccAddExternalFunctionForPlugin("Button::get_NormalGraphic", (void *)Button_GetNormalGraphic);
+	ccAddExternalFunctionForPlugin("Button::set_NormalGraphic", (void *)Button_SetNormalGraphic);
+	ccAddExternalFunctionForPlugin("Button::get_PushedGraphic", (void *)Button_GetPushedGraphic);
+	ccAddExternalFunctionForPlugin("Button::set_PushedGraphic", (void *)Button_SetPushedGraphic);
+	ccAddExternalFunctionForPlugin("Button::get_Text", (void *)Button_GetText_New);
+	ccAddExternalFunctionForPlugin("Button::set_Text", (void *)Button_SetText);
+	ccAddExternalFunctionForPlugin("Button::get_TextColor", (void *)Button_GetTextColor);
+	ccAddExternalFunctionForPlugin("Button::set_TextColor", (void *)Button_SetTextColor);
 }
diff --git a/engines/ags/engine/ac/button.h b/engines/ags/engine/ac/button.h
index 47022d8ce1..7f872fcd19 100644
--- a/engines/ags/engine/ac/button.h
+++ b/engines/ags/engine/ac/button.h
@@ -27,26 +27,26 @@
 
 using AGS::Common::GUIButton;
 
-void		Button_Animate(GUIButton *butt, int view, int loop, int speed, int repeat);
-const char* Button_GetText_New(GUIButton *butt);
-void		Button_GetText(GUIButton *butt, char *buffer);
-void		Button_SetText(GUIButton *butt, const char *newtx);
-void		Button_SetFont(GUIButton *butt, int newFont);
-int			Button_GetFont(GUIButton *butt);
-int			Button_GetClipImage(GUIButton *butt);
-void		Button_SetClipImage(GUIButton *butt, int newval);
-int			Button_GetGraphic(GUIButton *butt);
-int			Button_GetMouseOverGraphic(GUIButton *butt);
-void		Button_SetMouseOverGraphic(GUIButton *guil, int slotn);
-int			Button_GetNormalGraphic(GUIButton *butt);
-void		Button_SetNormalGraphic(GUIButton *guil, int slotn);
-int			Button_GetPushedGraphic(GUIButton *butt);
-void		Button_SetPushedGraphic(GUIButton *guil, int slotn);
-int			Button_GetTextColor(GUIButton *butt);
-void		Button_SetTextColor(GUIButton *butt, int newcol);
+void        Button_Animate(GUIButton *butt, int view, int loop, int speed, int repeat);
+const char *Button_GetText_New(GUIButton *butt);
+void        Button_GetText(GUIButton *butt, char *buffer);
+void        Button_SetText(GUIButton *butt, const char *newtx);
+void        Button_SetFont(GUIButton *butt, int newFont);
+int         Button_GetFont(GUIButton *butt);
+int         Button_GetClipImage(GUIButton *butt);
+void        Button_SetClipImage(GUIButton *butt, int newval);
+int         Button_GetGraphic(GUIButton *butt);
+int         Button_GetMouseOverGraphic(GUIButton *butt);
+void        Button_SetMouseOverGraphic(GUIButton *guil, int slotn);
+int         Button_GetNormalGraphic(GUIButton *butt);
+void        Button_SetNormalGraphic(GUIButton *guil, int slotn);
+int         Button_GetPushedGraphic(GUIButton *butt);
+void        Button_SetPushedGraphic(GUIButton *guil, int slotn);
+int         Button_GetTextColor(GUIButton *butt);
+void        Button_SetTextColor(GUIButton *butt, int newcol);
 
-int			UpdateAnimatingButton(int bu);
-void		StopButtonAnimation(int idxn);
-void		FindAndRemoveButtonAnimation(int guin, int objn);
+int         UpdateAnimatingButton(int bu);
+void        StopButtonAnimation(int idxn);
+void        FindAndRemoveButtonAnimation(int guin, int objn);
 
 #endif
diff --git a/engines/ags/engine/ac/cdaudio.cpp b/engines/ags/engine/ac/cdaudio.cpp
index b8f3a1e5ac..99294b49a2 100644
--- a/engines/ags/engine/ac/cdaudio.cpp
+++ b/engines/ags/engine/ac/cdaudio.cpp
@@ -23,25 +23,22 @@
 #include "ac/cdaudio.h"
 #include "platform/base/agsplatformdriver.h"
 
-int use_cdplayer=0;
+int use_cdplayer = 0;
 bool triedToUseCdAudioCommand = false;
-int need_to_stop_cd=0;
+int need_to_stop_cd = 0;
 
-int init_cd_player() 
-{
-    use_cdplayer=0;
-    return platform->InitializeCDPlayer();
+int init_cd_player() {
+	use_cdplayer = 0;
+	return platform->InitializeCDPlayer();
 }
 
-int cd_manager(int cmdd,int datt) 
-{
-    if (!triedToUseCdAudioCommand)
-    {
-        triedToUseCdAudioCommand = true;
-        init_cd_player();
-    }
-    if (cmdd==0) return use_cdplayer;
-    if (use_cdplayer==0) return 0;  // ignore other commands
+int cd_manager(int cmdd, int datt) {
+	if (!triedToUseCdAudioCommand) {
+		triedToUseCdAudioCommand = true;
+		init_cd_player();
+	}
+	if (cmdd == 0) return use_cdplayer;
+	if (use_cdplayer == 0) return 0; // ignore other commands
 
-    return platform->CDPlayerCommand(cmdd, datt);
+	return platform->CDPlayerCommand(cmdd, datt);
 }
diff --git a/engines/ags/engine/ac/cdaudio.h b/engines/ags/engine/ac/cdaudio.h
index 62852277ee..d3598a3904 100644
--- a/engines/ags/engine/ac/cdaudio.h
+++ b/engines/ags/engine/ac/cdaudio.h
@@ -31,6 +31,6 @@
 #define CDS_DRIVEEMPTY   0x0800  // no CD in drive
 
 int     init_cd_player() ;
-int     cd_manager(int cmdd,int datt) ;
+int     cd_manager(int cmdd, int datt) ;
 
 #endif
diff --git a/engines/ags/engine/ac/character.cpp b/engines/ags/engine/ac/character.cpp
index 5338101469..347eb922d2 100644
--- a/engines/ags/engine/ac/character.cpp
+++ b/engines/ags/engine/ac/character.cpp
@@ -74,11 +74,11 @@
 using namespace AGS::Common;
 
 extern GameSetupStruct game;
-extern int displayed_room,starting_room;
+extern int displayed_room, starting_room;
 extern RoomStruct thisroom;
 extern MoveList *mls;
-extern ViewStruct*views;
-extern RoomObject*objs;
+extern ViewStruct *views;
+extern RoomObject *objs;
 extern ScriptInvItem scrInv[MAX_INV];
 extern SpriteCache spriteset;
 extern Bitmap *walkable_areas_temp;
@@ -95,13 +95,13 @@ extern CCInventory ccDynamicInv;
 
 
 CharacterExtras *charextra;
-CharacterInfo*playerchar;
+CharacterInfo *playerchar;
 int32_t _sc_PlayerCharPtr = 0;
 int char_lowest_yp;
 
 // Sierra-style speech settings
-int face_talking=-1,facetalkview=0,facetalkwait=0,facetalkframe=0;
-int facetalkloop=0, facetalkrepeat = 0, facetalkAllowBlink = 1;
+int face_talking = -1, facetalkview = 0, facetalkwait = 0, facetalkframe = 0;
+int facetalkloop = 0, facetalkrepeat = 0, facetalkAllowBlink = 1;
 int facetalkBlinkLoop = 0;
 CharacterInfo *facetalkchar = nullptr;
 // Do override default portrait position during QFG4-style speech overlay update
@@ -118,973 +118,921 @@ int numLipLines = 0, curLipLine = -1, curLipLinePhoneme = 0;
 // **** CHARACTER: FUNCTIONS ****
 
 void Character_AddInventory(CharacterInfo *chaa, ScriptInvItem *invi, int addIndex) {
-    int ee;
-
-    if (invi == nullptr)
-        quit("!AddInventoryToCharacter: invalid invnetory number");
-
-    int inum = invi->id;
-
-    if (chaa->inv[inum] >= 32000)
-        quit("!AddInventory: cannot carry more than 32000 of one inventory item");
-
-    chaa->inv[inum]++;
-
-    int charid = chaa->index_id;
-
-    if (game.options[OPT_DUPLICATEINV] == 0) {
-        // Ensure it is only in the list once
-        for (ee = 0; ee < charextra[charid].invorder_count; ee++) {
-            if (charextra[charid].invorder[ee] == inum) {
-                // They already have the item, so don't add it to the list
-                if (chaa == playerchar)
-                    run_on_event (GE_ADD_INV, RuntimeScriptValue().SetInt32(inum));
-                return;
-            }
-        }
-    }
-    if (charextra[charid].invorder_count >= MAX_INVORDER)
-        quit("!Too many inventory items added, max 500 display at one time");
-
-    if ((addIndex == SCR_NO_VALUE) ||
-        (addIndex >= charextra[charid].invorder_count) ||
-        (addIndex < 0)) {
-            // add new item at end of list
-            charextra[charid].invorder[charextra[charid].invorder_count] = inum;
-    }
-    else {
-        // insert new item at index
-        for (ee = charextra[charid].invorder_count - 1; ee >= addIndex; ee--)
-            charextra[charid].invorder[ee + 1] = charextra[charid].invorder[ee];
-
-        charextra[charid].invorder[addIndex] = inum;
-    }
-    charextra[charid].invorder_count++;
-    guis_need_update = 1;
-    if (chaa == playerchar)
-        run_on_event (GE_ADD_INV, RuntimeScriptValue().SetInt32(inum));
+	int ee;
+
+	if (invi == nullptr)
+		quit("!AddInventoryToCharacter: invalid invnetory number");
+
+	int inum = invi->id;
+
+	if (chaa->inv[inum] >= 32000)
+		quit("!AddInventory: cannot carry more than 32000 of one inventory item");
+
+	chaa->inv[inum]++;
+
+	int charid = chaa->index_id;
+
+	if (game.options[OPT_DUPLICATEINV] == 0) {
+		// Ensure it is only in the list once
+		for (ee = 0; ee < charextra[charid].invorder_count; ee++) {
+			if (charextra[charid].invorder[ee] == inum) {
+				// They already have the item, so don't add it to the list
+				if (chaa == playerchar)
+					run_on_event(GE_ADD_INV, RuntimeScriptValue().SetInt32(inum));
+				return;
+			}
+		}
+	}
+	if (charextra[charid].invorder_count >= MAX_INVORDER)
+		quit("!Too many inventory items added, max 500 display at one time");
+
+	if ((addIndex == SCR_NO_VALUE) ||
+	        (addIndex >= charextra[charid].invorder_count) ||
+	        (addIndex < 0)) {
+		// add new item at end of list
+		charextra[charid].invorder[charextra[charid].invorder_count] = inum;
+	} else {
+		// insert new item at index
+		for (ee = charextra[charid].invorder_count - 1; ee >= addIndex; ee--)
+			charextra[charid].invorder[ee + 1] = charextra[charid].invorder[ee];
+
+		charextra[charid].invorder[addIndex] = inum;
+	}
+	charextra[charid].invorder_count++;
+	guis_need_update = 1;
+	if (chaa == playerchar)
+		run_on_event(GE_ADD_INV, RuntimeScriptValue().SetInt32(inum));
 
 }
 
 void Character_AddWaypoint(CharacterInfo *chaa, int x, int y) {
 
-    if (chaa->room != displayed_room)
-        quit("!MoveCharacterPath: specified character not in current room");
+	if (chaa->room != displayed_room)
+		quit("!MoveCharacterPath: specified character not in current room");
 
-    // not already walking, so just do a normal move
-    if (chaa->walking <= 0) {
-        Character_Walk(chaa, x, y, IN_BACKGROUND, ANYWHERE);
-        return;
-    }
+	// not already walking, so just do a normal move
+	if (chaa->walking <= 0) {
+		Character_Walk(chaa, x, y, IN_BACKGROUND, ANYWHERE);
+		return;
+	}
 
-    MoveList *cmls = &mls[chaa->walking % TURNING_AROUND];
-    if (cmls->numstage >= MAXNEEDSTAGES)
-    {
-        debug_script_warn("Character_AddWaypoint: move is too complex, cannot add any further paths");
-        return;
-    }
+	MoveList *cmls = &mls[chaa->walking % TURNING_AROUND];
+	if (cmls->numstage >= MAXNEEDSTAGES) {
+		debug_script_warn("Character_AddWaypoint: move is too complex, cannot add any further paths");
+		return;
+	}
 
-    cmls->pos[cmls->numstage] = (x << 16) + y;
-    // They're already walking there anyway
-    if (cmls->pos[cmls->numstage] == cmls->pos[cmls->numstage - 1])
-        return;
+	cmls->pos[cmls->numstage] = (x << 16) + y;
+	// They're already walking there anyway
+	if (cmls->pos[cmls->numstage] == cmls->pos[cmls->numstage - 1])
+		return;
 
-    calculate_move_stage (cmls, cmls->numstage-1);
-    cmls->numstage ++;
+	calculate_move_stage(cmls, cmls->numstage - 1);
+	cmls->numstage ++;
 
 }
 
 void Character_AnimateFrom(CharacterInfo *chaa, int loop, int delay, int repeat, int blocking, int direction, int sframe) {
 
-    if (direction == FORWARDS)
-        direction = 0;
-    else if (direction == BACKWARDS)
-        direction = 1;
-    else
-        quit("!Character.Animate: Invalid DIRECTION parameter");
+	if (direction == FORWARDS)
+		direction = 0;
+	else if (direction == BACKWARDS)
+		direction = 1;
+	else
+		quit("!Character.Animate: Invalid DIRECTION parameter");
 
-    animate_character(chaa, loop, delay, repeat, 0, direction, sframe);
+	animate_character(chaa, loop, delay, repeat, 0, direction, sframe);
 
-    if ((blocking == BLOCKING) || (blocking == 1))
-        GameLoopUntilValueIsZero(&chaa->animating);
-    else if ((blocking != IN_BACKGROUND) && (blocking != 0))
-        quit("!Character.Animate: Invalid BLOCKING parameter");
+	if ((blocking == BLOCKING) || (blocking == 1))
+		GameLoopUntilValueIsZero(&chaa->animating);
+	else if ((blocking != IN_BACKGROUND) && (blocking != 0))
+		quit("!Character.Animate: Invalid BLOCKING parameter");
 }
 
 void Character_Animate(CharacterInfo *chaa, int loop, int delay, int repeat, int blocking, int direction) {
-    Character_AnimateFrom(chaa, loop, delay, repeat, blocking, direction, 0);
+	Character_AnimateFrom(chaa, loop, delay, repeat, blocking, direction, 0);
 }
 
-void Character_ChangeRoomAutoPosition(CharacterInfo *chaa, int room, int newPos) 
-{
-    if (chaa->index_id != game.playercharacter) 
-    {
-        quit("!Character.ChangeRoomAutoPosition can only be used with the player character.");
-    }
-
-    new_room_pos = newPos;
-
-    if (new_room_pos == 0) {
-        // auto place on other side of screen
-        if (chaa->x <= thisroom.Edges.Left + 10)
-            new_room_pos = 2000;
-        else if (chaa->x >= thisroom.Edges.Right - 10)
-            new_room_pos = 1000;
-        else if (chaa->y <= thisroom.Edges.Top + 10)
-            new_room_pos = 3000;
-        else if (chaa->y >= thisroom.Edges.Bottom - 10)
-            new_room_pos = 4000;
-
-        if (new_room_pos < 3000)
-            new_room_pos += chaa->y;
-        else
-            new_room_pos += chaa->x;
-    }
-    NewRoom(room);
+void Character_ChangeRoomAutoPosition(CharacterInfo *chaa, int room, int newPos) {
+	if (chaa->index_id != game.playercharacter) {
+		quit("!Character.ChangeRoomAutoPosition can only be used with the player character.");
+	}
+
+	new_room_pos = newPos;
+
+	if (new_room_pos == 0) {
+		// auto place on other side of screen
+		if (chaa->x <= thisroom.Edges.Left + 10)
+			new_room_pos = 2000;
+		else if (chaa->x >= thisroom.Edges.Right - 10)
+			new_room_pos = 1000;
+		else if (chaa->y <= thisroom.Edges.Top + 10)
+			new_room_pos = 3000;
+		else if (chaa->y >= thisroom.Edges.Bottom - 10)
+			new_room_pos = 4000;
+
+		if (new_room_pos < 3000)
+			new_room_pos += chaa->y;
+		else
+			new_room_pos += chaa->x;
+	}
+	NewRoom(room);
 }
 
 void Character_ChangeRoom(CharacterInfo *chaa, int room, int x, int y) {
-    Character_ChangeRoomSetLoop(chaa, room, x, y, SCR_NO_VALUE);
+	Character_ChangeRoomSetLoop(chaa, room, x, y, SCR_NO_VALUE);
 }
 
 void Character_ChangeRoomSetLoop(CharacterInfo *chaa, int room, int x, int y, int direction) {
 
-    if (chaa->index_id != game.playercharacter) {
-        // NewRoomNPC
-        if ((x != SCR_NO_VALUE) && (y != SCR_NO_VALUE)) {
-            chaa->x = x;
-            chaa->y = y;
-			if (direction != SCR_NO_VALUE && direction>=0) chaa->loop = direction;
-        }
-        chaa->prevroom = chaa->room;
-        chaa->room = room;
+	if (chaa->index_id != game.playercharacter) {
+		// NewRoomNPC
+		if ((x != SCR_NO_VALUE) && (y != SCR_NO_VALUE)) {
+			chaa->x = x;
+			chaa->y = y;
+			if (direction != SCR_NO_VALUE && direction >= 0) chaa->loop = direction;
+		}
+		chaa->prevroom = chaa->room;
+		chaa->room = room;
 
 		debug_script_log("%s moved to room %d, location %d,%d, loop %d",
-			chaa->scrname, room, chaa->x, chaa->y, chaa->loop);
-
-        return;
-    }
-
-    if ((x != SCR_NO_VALUE) && (y != SCR_NO_VALUE)) {
-        new_room_pos = 0;
-
-        if (loaded_game_file_version <= kGameVersion_272)
-        {
-            // Set position immediately on 2.x.
-            chaa->x = x;
-            chaa->y = y;
-        }
-        else
-        {
-            // don't check X or Y bounds, so that they can do a
-            // walk-in animation if they want
-            new_room_x = x;
-            new_room_y = y;
+		                 chaa->scrname, room, chaa->x, chaa->y, chaa->loop);
+
+		return;
+	}
+
+	if ((x != SCR_NO_VALUE) && (y != SCR_NO_VALUE)) {
+		new_room_pos = 0;
+
+		if (loaded_game_file_version <= kGameVersion_272) {
+			// Set position immediately on 2.x.
+			chaa->x = x;
+			chaa->y = y;
+		} else {
+			// don't check X or Y bounds, so that they can do a
+			// walk-in animation if they want
+			new_room_x = x;
+			new_room_y = y;
 			if (direction != SCR_NO_VALUE) new_room_loop = direction;
-        }
-    }
+		}
+	}
 
-    NewRoom(room);
+	NewRoom(room);
 }
 
 
 void Character_ChangeView(CharacterInfo *chap, int vii) {
-    vii--;
-
-    if ((vii < 0) || (vii >= game.numviews))
-        quit("!ChangeCharacterView: invalid view number specified");
-
-    // if animating, but not idle view, give warning message
-    if ((chap->flags & CHF_FIXVIEW) && (chap->idleleft >= 0))
-        debug_script_warn("Warning: ChangeCharacterView was used while the view was fixed - call ReleaseCharView first");
-
-    // if the idle animation is playing we should release the view
-    if ( chap->idleleft < 0) {
-      Character_UnlockView(chap);
-      chap->idleleft = chap->idletime;
-    }
-
-    debug_script_log("%s: Change view to %d", chap->scrname, vii+1);
-    chap->defview = vii;
-    chap->view = vii;
-    chap->animating = 0;
-    chap->frame = 0;
-    chap->wait = 0;
-    chap->walkwait = 0;
-    charextra[chap->index_id].animwait = 0;
-    FindReasonableLoopForCharacter(chap);
-}
-
-enum DirectionalLoop
-{
-    kDirLoop_Down      = 0,
-    kDirLoop_Left      = 1,
-    kDirLoop_Right     = 2,
-    kDirLoop_Up        = 3,
-    kDirLoop_DownRight = 4,
-    kDirLoop_UpRight   = 5,
-    kDirLoop_DownLeft  = 6,
-    kDirLoop_UpLeft    = 7,
-
-    kDirLoop_Default        = kDirLoop_Down,
-    kDirLoop_LastOrthogonal = kDirLoop_Up,
-    kDirLoop_Last           = kDirLoop_UpLeft,
+	vii--;
+
+	if ((vii < 0) || (vii >= game.numviews))
+		quit("!ChangeCharacterView: invalid view number specified");
+
+	// if animating, but not idle view, give warning message
+	if ((chap->flags & CHF_FIXVIEW) && (chap->idleleft >= 0))
+		debug_script_warn("Warning: ChangeCharacterView was used while the view was fixed - call ReleaseCharView first");
+
+	// if the idle animation is playing we should release the view
+	if (chap->idleleft < 0) {
+		Character_UnlockView(chap);
+		chap->idleleft = chap->idletime;
+	}
+
+	debug_script_log("%s: Change view to %d", chap->scrname, vii + 1);
+	chap->defview = vii;
+	chap->view = vii;
+	chap->animating = 0;
+	chap->frame = 0;
+	chap->wait = 0;
+	chap->walkwait = 0;
+	charextra[chap->index_id].animwait = 0;
+	FindReasonableLoopForCharacter(chap);
+}
+
+enum DirectionalLoop {
+	kDirLoop_Down      = 0,
+	kDirLoop_Left      = 1,
+	kDirLoop_Right     = 2,
+	kDirLoop_Up        = 3,
+	kDirLoop_DownRight = 4,
+	kDirLoop_UpRight   = 5,
+	kDirLoop_DownLeft  = 6,
+	kDirLoop_UpLeft    = 7,
+
+	kDirLoop_Default        = kDirLoop_Down,
+	kDirLoop_LastOrthogonal = kDirLoop_Up,
+	kDirLoop_Last           = kDirLoop_UpLeft,
 };
 
 // Internal direction-facing functions
 
-DirectionalLoop GetDirectionalLoop(CharacterInfo *chinfo, int x_diff, int y_diff)
-{
-    DirectionalLoop next_loop = kDirLoop_Left; // NOTE: default loop was Left for some reason
-
-    const ViewStruct &chview  = views[chinfo->view];
-    const bool new_version    = loaded_game_file_version > kGameVersion_272;
-    const bool has_down_loop  = ((chview.numLoops > kDirLoop_Down)  && (chview.loops[kDirLoop_Down].numFrames > 0));
-    const bool has_up_loop    = ((chview.numLoops > kDirLoop_Up)    && (chview.loops[kDirLoop_Up].numFrames > 0));
-    // NOTE: 3.+ games required left & right loops to be present at all times
-    const bool has_left_loop  = new_version ||
-                                ((chview.numLoops > kDirLoop_Left)  && (chview.loops[kDirLoop_Left].numFrames > 0));
-    const bool has_right_loop = new_version ||
-                                ((chview.numLoops > kDirLoop_Right) && (chview.loops[kDirLoop_Right].numFrames > 0));
-    const bool has_diagonal_loops = useDiagonal(chinfo) == 0; // NOTE: useDiagonal returns 0 for "true"
-
-    const bool want_horizontal = (abs(y_diff) < abs(x_diff)) ||
-        (new_version && (!has_down_loop || !has_up_loop) )||
-        // NOTE: <= 2.72 games switch to horizontal loops only if both vertical ones are missing
-        (!new_version && (!has_down_loop && !has_up_loop));
-    if (want_horizontal)
-    {
-        const bool want_diagonal = has_diagonal_loops && (abs(y_diff) > abs(x_diff) / 2);
-        if (!has_left_loop && !has_right_loop)
-        {
-            next_loop = kDirLoop_Down;
-        }
-        else if (has_right_loop && (x_diff > 0))
-        {
-            next_loop = want_diagonal ? (y_diff < 0 ? kDirLoop_UpRight : kDirLoop_DownRight) :
-                kDirLoop_Right;
-        }
-        else if (has_left_loop && (x_diff <= 0))
-        {
-            next_loop = want_diagonal ? (y_diff < 0 ? kDirLoop_UpLeft : kDirLoop_DownLeft) :
-                kDirLoop_Left;
-        }
-    }
-    else
-    {
-        const bool want_diagonal = has_diagonal_loops && (abs(x_diff) > abs(y_diff) / 2);
-        if (y_diff > 0 || !has_up_loop)
-        {
-            next_loop = want_diagonal ? (x_diff < 0 ? kDirLoop_DownLeft : kDirLoop_DownRight) :
-                kDirLoop_Down;
-        }
-        else
-        {
-            next_loop = want_diagonal ? (x_diff < 0 ? kDirLoop_UpLeft : kDirLoop_UpRight) :
-                kDirLoop_Up;
-        }
-    }
-    return next_loop;
-}
-
-void FaceDirectionalLoop(CharacterInfo *char1, int direction, int blockingStyle)
-{
-    // Change facing only if the desired direction is different
-    if (direction != char1->loop)
-    {
-        if ((game.options[OPT_TURNTOFACELOC] != 0) &&
-            (in_enters_screen == 0))
-        {
-            const int no_diagonal = useDiagonal (char1);
-            const int highestLoopForTurning = no_diagonal != 1 ? kDirLoop_Last : kDirLoop_LastOrthogonal;
-            if ((char1->loop <= highestLoopForTurning))
-            {
-                // Turn to face new direction
-                Character_StopMoving(char1);
-                if (char1->on == 1)
-                {
-                    // only do the turning if the character is not hidden
-                    // (otherwise GameLoopUntilNotMoving will never return)
-                    start_character_turning (char1, direction, no_diagonal);
-
-                    if ((blockingStyle == BLOCKING) || (blockingStyle == 1))
-                        GameLoopUntilNotMoving(&char1->walking);
-                }
-                else
-                    char1->loop = direction;
-            }
-            else
-                char1->loop = direction;
-        }
-        else
-            char1->loop = direction;
-    }
-
-    char1->frame = 0;
-}
-
-void FaceLocationXY(CharacterInfo *char1, int xx, int yy, int blockingStyle)
-{
-    debug_script_log("%s: Face location %d,%d", char1->scrname, xx, yy);
-
-    const int diffrx = xx - char1->x;
-    const int diffry = yy - char1->y;
-
-    if ((diffrx == 0) && (diffry == 0)) {
-        // FaceLocation called on their current position - do nothing
-        return;
-    }
-
-    FaceDirectionalLoop(char1, GetDirectionalLoop(char1, diffrx, diffry), blockingStyle);
+DirectionalLoop GetDirectionalLoop(CharacterInfo *chinfo, int x_diff, int y_diff) {
+	DirectionalLoop next_loop = kDirLoop_Left; // NOTE: default loop was Left for some reason
+
+	const ViewStruct &chview  = views[chinfo->view];
+	const bool new_version    = loaded_game_file_version > kGameVersion_272;
+	const bool has_down_loop  = ((chview.numLoops > kDirLoop_Down)  && (chview.loops[kDirLoop_Down].numFrames > 0));
+	const bool has_up_loop    = ((chview.numLoops > kDirLoop_Up)    && (chview.loops[kDirLoop_Up].numFrames > 0));
+	// NOTE: 3.+ games required left & right loops to be present at all times
+	const bool has_left_loop  = new_version ||
+	                            ((chview.numLoops > kDirLoop_Left)  && (chview.loops[kDirLoop_Left].numFrames > 0));
+	const bool has_right_loop = new_version ||
+	                            ((chview.numLoops > kDirLoop_Right) && (chview.loops[kDirLoop_Right].numFrames > 0));
+	const bool has_diagonal_loops = useDiagonal(chinfo) == 0; // NOTE: useDiagonal returns 0 for "true"
+
+	const bool want_horizontal = (abs(y_diff) < abs(x_diff)) ||
+	                             (new_version && (!has_down_loop || !has_up_loop)) ||
+	                             // NOTE: <= 2.72 games switch to horizontal loops only if both vertical ones are missing
+	                             (!new_version && (!has_down_loop && !has_up_loop));
+	if (want_horizontal) {
+		const bool want_diagonal = has_diagonal_loops && (abs(y_diff) > abs(x_diff) / 2);
+		if (!has_left_loop && !has_right_loop) {
+			next_loop = kDirLoop_Down;
+		} else if (has_right_loop && (x_diff > 0)) {
+			next_loop = want_diagonal ? (y_diff < 0 ? kDirLoop_UpRight : kDirLoop_DownRight) :
+			            kDirLoop_Right;
+		} else if (has_left_loop && (x_diff <= 0)) {
+			next_loop = want_diagonal ? (y_diff < 0 ? kDirLoop_UpLeft : kDirLoop_DownLeft) :
+			            kDirLoop_Left;
+		}
+	} else {
+		const bool want_diagonal = has_diagonal_loops && (abs(x_diff) > abs(y_diff) / 2);
+		if (y_diff > 0 || !has_up_loop) {
+			next_loop = want_diagonal ? (x_diff < 0 ? kDirLoop_DownLeft : kDirLoop_DownRight) :
+			            kDirLoop_Down;
+		} else {
+			next_loop = want_diagonal ? (x_diff < 0 ? kDirLoop_UpLeft : kDirLoop_UpRight) :
+			            kDirLoop_Up;
+		}
+	}
+	return next_loop;
+}
+
+void FaceDirectionalLoop(CharacterInfo *char1, int direction, int blockingStyle) {
+	// Change facing only if the desired direction is different
+	if (direction != char1->loop) {
+		if ((game.options[OPT_TURNTOFACELOC] != 0) &&
+		        (in_enters_screen == 0)) {
+			const int no_diagonal = useDiagonal(char1);
+			const int highestLoopForTurning = no_diagonal != 1 ? kDirLoop_Last : kDirLoop_LastOrthogonal;
+			if ((char1->loop <= highestLoopForTurning)) {
+				// Turn to face new direction
+				Character_StopMoving(char1);
+				if (char1->on == 1) {
+					// only do the turning if the character is not hidden
+					// (otherwise GameLoopUntilNotMoving will never return)
+					start_character_turning(char1, direction, no_diagonal);
+
+					if ((blockingStyle == BLOCKING) || (blockingStyle == 1))
+						GameLoopUntilNotMoving(&char1->walking);
+				} else
+					char1->loop = direction;
+			} else
+				char1->loop = direction;
+		} else
+			char1->loop = direction;
+	}
+
+	char1->frame = 0;
+}
+
+void FaceLocationXY(CharacterInfo *char1, int xx, int yy, int blockingStyle) {
+	debug_script_log("%s: Face location %d,%d", char1->scrname, xx, yy);
+
+	const int diffrx = xx - char1->x;
+	const int diffry = yy - char1->y;
+
+	if ((diffrx == 0) && (diffry == 0)) {
+		// FaceLocation called on their current position - do nothing
+		return;
+	}
+
+	FaceDirectionalLoop(char1, GetDirectionalLoop(char1, diffrx, diffry), blockingStyle);
 }
 
 // External direction-facing functions with validation
 
-void Character_FaceDirection(CharacterInfo *char1, int direction, int blockingStyle)
-{
-    if (char1 == nullptr)
-        quit("!FaceDirection: invalid character specified");
+void Character_FaceDirection(CharacterInfo *char1, int direction, int blockingStyle) {
+	if (char1 == nullptr)
+		quit("!FaceDirection: invalid character specified");
 
-    if (direction != SCR_NO_VALUE)
-    {
-        if (direction < 0 || direction > kDirLoop_Last)
-            quit("!FaceDirection: invalid direction specified");
+	if (direction != SCR_NO_VALUE) {
+		if (direction < 0 || direction > kDirLoop_Last)
+			quit("!FaceDirection: invalid direction specified");
 
-        FaceDirectionalLoop(char1, direction, blockingStyle);
-    }
+		FaceDirectionalLoop(char1, direction, blockingStyle);
+	}
 }
 
-void Character_FaceLocation(CharacterInfo *char1, int xx, int yy, int blockingStyle)
-{
-    if (char1 == nullptr)
-        quit("!FaceLocation: invalid character specified");
+void Character_FaceLocation(CharacterInfo *char1, int xx, int yy, int blockingStyle) {
+	if (char1 == nullptr)
+		quit("!FaceLocation: invalid character specified");
 
-    FaceLocationXY(char1, xx, yy, blockingStyle);
+	FaceLocationXY(char1, xx, yy, blockingStyle);
 }
 
 void Character_FaceObject(CharacterInfo *char1, ScriptObject *obj, int blockingStyle) {
-    if (obj == nullptr) 
-        quit("!FaceObject: invalid object specified");
+	if (obj == nullptr)
+		quit("!FaceObject: invalid object specified");
 
-    FaceLocationXY(char1, objs[obj->id].x, objs[obj->id].y, blockingStyle);
+	FaceLocationXY(char1, objs[obj->id].x, objs[obj->id].y, blockingStyle);
 }
 
 void Character_FaceCharacter(CharacterInfo *char1, CharacterInfo *char2, int blockingStyle) {
-    if (char2 == nullptr) 
-        quit("!FaceCharacter: invalid character specified");
+	if (char2 == nullptr)
+		quit("!FaceCharacter: invalid character specified");
 
-    if (char1->room != char2->room)
-        quit("!FaceCharacter: characters are in different rooms");
+	if (char1->room != char2->room)
+		quit("!FaceCharacter: characters are in different rooms");
 
-    FaceLocationXY(char1, char2->x, char2->y, blockingStyle);
+	FaceLocationXY(char1, char2->x, char2->y, blockingStyle);
 }
 
 void Character_FollowCharacter(CharacterInfo *chaa, CharacterInfo *tofollow, int distaway, int eagerness) {
 
-    if ((eagerness < 0) || (eagerness > 250))
-        quit("!FollowCharacterEx: invalid eagerness: must be 0-250");
+	if ((eagerness < 0) || (eagerness > 250))
+		quit("!FollowCharacterEx: invalid eagerness: must be 0-250");
 
-    if ((chaa->index_id == game.playercharacter) && (tofollow != nullptr) && 
-        (tofollow->room != chaa->room))
-        quit("!FollowCharacterEx: you cannot tell the player character to follow a character in another room");
+	if ((chaa->index_id == game.playercharacter) && (tofollow != nullptr) &&
+	        (tofollow->room != chaa->room))
+		quit("!FollowCharacterEx: you cannot tell the player character to follow a character in another room");
 
-    if (tofollow != nullptr) {
-        debug_script_log("%s: Start following %s (dist %d, eager %d)", chaa->scrname, tofollow->scrname, distaway, eagerness);
-    }
-    else {
-        debug_script_log("%s: Stop following other character", chaa->scrname);
-    }
+	if (tofollow != nullptr) {
+		debug_script_log("%s: Start following %s (dist %d, eager %d)", chaa->scrname, tofollow->scrname, distaway, eagerness);
+	} else {
+		debug_script_log("%s: Stop following other character", chaa->scrname);
+	}
 
-    if ((chaa->following >= 0) &&
-        (chaa->followinfo == FOLLOW_ALWAYSONTOP)) {
-            // if this character was following always-on-top, its baseline will
-            // have been changed, so release it.
-            chaa->baseline = -1;
-    }
+	if ((chaa->following >= 0) &&
+	        (chaa->followinfo == FOLLOW_ALWAYSONTOP)) {
+		// if this character was following always-on-top, its baseline will
+		// have been changed, so release it.
+		chaa->baseline = -1;
+	}
 
-    if (tofollow == nullptr)
-        chaa->following = -1;
-    else
-        chaa->following = tofollow->index_id;
+	if (tofollow == nullptr)
+		chaa->following = -1;
+	else
+		chaa->following = tofollow->index_id;
 
-    chaa->followinfo=(distaway << 8) | eagerness;
+	chaa->followinfo = (distaway << 8) | eagerness;
 
-    chaa->flags &= ~CHF_BEHINDSHEPHERD;
+	chaa->flags &= ~CHF_BEHINDSHEPHERD;
 
-    // special case for Always On Other Character
-    if (distaway == FOLLOW_ALWAYSONTOP) {
-        chaa->followinfo = FOLLOW_ALWAYSONTOP;
-        if (eagerness == 1)
-            chaa->flags |= CHF_BEHINDSHEPHERD;
-    }
+	// special case for Always On Other Character
+	if (distaway == FOLLOW_ALWAYSONTOP) {
+		chaa->followinfo = FOLLOW_ALWAYSONTOP;
+		if (eagerness == 1)
+			chaa->flags |= CHF_BEHINDSHEPHERD;
+	}
 
-    if (chaa->animating & CHANIM_REPEAT)
-        debug_script_warn("Warning: FollowCharacter called but the sheep is currently animating looped. It may never start to follow.");
+	if (chaa->animating & CHANIM_REPEAT)
+		debug_script_warn("Warning: FollowCharacter called but the sheep is currently animating looped. It may never start to follow.");
 
 }
 
 int Character_IsCollidingWithChar(CharacterInfo *char1, CharacterInfo *char2) {
-    if (char2 == nullptr)
-        quit("!AreCharactersColliding: invalid char2");
+	if (char2 == nullptr)
+		quit("!AreCharactersColliding: invalid char2");
 
-    if (char1->room != char2->room) return 0; // not colliding
+	if (char1->room != char2->room) return 0; // not colliding
 
-    if ((char1->y > char2->y - 5) && (char1->y < char2->y + 5)) ;
-    else return 0;
+	if ((char1->y > char2->y - 5) && (char1->y < char2->y + 5)) ;
+	else return 0;
 
-    int w1 = game_to_data_coord(GetCharacterWidth(char1->index_id));
-    int w2 = game_to_data_coord(GetCharacterWidth(char2->index_id));
+	int w1 = game_to_data_coord(GetCharacterWidth(char1->index_id));
+	int w2 = game_to_data_coord(GetCharacterWidth(char2->index_id));
 
-    int xps1=char1->x - w1/2;
-    int xps2=char2->x - w2/2;
+	int xps1 = char1->x - w1 / 2;
+	int xps2 = char2->x - w2 / 2;
 
-    if ((xps1 >= xps2 - w1) & (xps1 <= xps2 + w2)) return 1;
-    return 0;
+	if ((xps1 >= xps2 - w1) & (xps1 <= xps2 + w2)) return 1;
+	return 0;
 }
 
 int Character_IsCollidingWithObject(CharacterInfo *chin, ScriptObject *objid) {
-    if (objid == nullptr)
-        quit("!AreCharObjColliding: invalid object number");
-
-    if (chin->room != displayed_room)
-        return 0;
-    if (objs[objid->id].on != 1)
-        return 0;
-
-    Bitmap *checkblk = GetObjectImage(objid->id, nullptr);
-    int objWidth = checkblk->GetWidth();
-    int objHeight = checkblk->GetHeight();
-    int o1x = objs[objid->id].x;
-    int o1y = objs[objid->id].y - game_to_data_coord(objHeight);
-
-    Bitmap *charpic = GetCharacterImage(chin->index_id, nullptr);
-
-    int charWidth = charpic->GetWidth();
-    int charHeight = charpic->GetHeight();
-    int o2x = chin->x - game_to_data_coord(charWidth) / 2;
-    int o2y = chin->get_effective_y() - 5;  // only check feet
-
-    if ((o2x >= o1x - game_to_data_coord(charWidth)) &&
-        (o2x <= o1x + game_to_data_coord(objWidth)) &&
-        (o2y >= o1y - 8) &&
-        (o2y <= o1y + game_to_data_coord(objHeight))) {
-            // the character's feet are on the object
-            if (game.options[OPT_PIXPERFECT] == 0)
-                return 1;
-            // check if they're on a transparent bit of the object
-            int stxp = data_to_game_coord(o2x - o1x);
-            int styp = data_to_game_coord(o2y - o1y);
-            int maskcol = checkblk->GetMaskColor ();
-            int maskcolc = charpic->GetMaskColor ();
-            int thispix, thispixc;
-            // check each pixel of the object along the char's feet
-            for (int i = 0; i < charWidth; i += get_fixed_pixel_size(1)) {
-                for (int j = 0; j < get_fixed_pixel_size(6); j += get_fixed_pixel_size(1)) {
-                    thispix = my_getpixel(checkblk, i + stxp, j + styp);
-                    thispixc = my_getpixel(charpic, i, j + (charHeight - get_fixed_pixel_size(5)));
-
-                    if ((thispix != -1) && (thispix != maskcol) &&
-                        (thispixc != -1) && (thispixc != maskcolc))
-                        return 1;
-                }
-            }
-
-    }
-    return 0;
+	if (objid == nullptr)
+		quit("!AreCharObjColliding: invalid object number");
+
+	if (chin->room != displayed_room)
+		return 0;
+	if (objs[objid->id].on != 1)
+		return 0;
+
+	Bitmap *checkblk = GetObjectImage(objid->id, nullptr);
+	int objWidth = checkblk->GetWidth();
+	int objHeight = checkblk->GetHeight();
+	int o1x = objs[objid->id].x;
+	int o1y = objs[objid->id].y - game_to_data_coord(objHeight);
+
+	Bitmap *charpic = GetCharacterImage(chin->index_id, nullptr);
+
+	int charWidth = charpic->GetWidth();
+	int charHeight = charpic->GetHeight();
+	int o2x = chin->x - game_to_data_coord(charWidth) / 2;
+	int o2y = chin->get_effective_y() - 5;  // only check feet
+
+	if ((o2x >= o1x - game_to_data_coord(charWidth)) &&
+	        (o2x <= o1x + game_to_data_coord(objWidth)) &&
+	        (o2y >= o1y - 8) &&
+	        (o2y <= o1y + game_to_data_coord(objHeight))) {
+		// the character's feet are on the object
+		if (game.options[OPT_PIXPERFECT] == 0)
+			return 1;
+		// check if they're on a transparent bit of the object
+		int stxp = data_to_game_coord(o2x - o1x);
+		int styp = data_to_game_coord(o2y - o1y);
+		int maskcol = checkblk->GetMaskColor();
+		int maskcolc = charpic->GetMaskColor();
+		int thispix, thispixc;
+		// check each pixel of the object along the char's feet
+		for (int i = 0; i < charWidth; i += get_fixed_pixel_size(1)) {
+			for (int j = 0; j < get_fixed_pixel_size(6); j += get_fixed_pixel_size(1)) {
+				thispix = my_getpixel(checkblk, i + stxp, j + styp);
+				thispixc = my_getpixel(charpic, i, j + (charHeight - get_fixed_pixel_size(5)));
+
+				if ((thispix != -1) && (thispix != maskcol) &&
+				        (thispixc != -1) && (thispixc != maskcolc))
+					return 1;
+			}
+		}
+
+	}
+	return 0;
 }
 
 bool Character_IsInteractionAvailable(CharacterInfo *cchar, int mood) {
 
-    play.check_interaction_only = 1;
-    RunCharacterInteraction(cchar->index_id, mood);
-    int ciwas = play.check_interaction_only;
-    play.check_interaction_only = 0;
-    return (ciwas == 2);
+	play.check_interaction_only = 1;
+	RunCharacterInteraction(cchar->index_id, mood);
+	int ciwas = play.check_interaction_only;
+	play.check_interaction_only = 0;
+	return (ciwas == 2);
 }
 
 void Character_LockView(CharacterInfo *chap, int vii) {
-    Character_LockViewEx(chap, vii, STOP_MOVING);
+	Character_LockViewEx(chap, vii, STOP_MOVING);
 }
 
 void Character_LockViewEx(CharacterInfo *chap, int vii, int stopMoving) {
 
-    if ((vii < 1) || (vii > game.numviews)) {
-        quitprintf("!SetCharacterView: invalid view number (You said %d, max is %d)", vii, game.numviews);
-    }
-    vii--;
-
-    debug_script_log("%s: View locked to %d", chap->scrname, vii+1);
-    if (chap->idleleft < 0) {
-        Character_UnlockView(chap);
-        chap->idleleft = chap->idletime;
-    }
-    if (stopMoving != KEEP_MOVING)
-    {
-        Character_StopMoving(chap);
-    }
-    chap->view=vii;
-    chap->animating=0;
-    FindReasonableLoopForCharacter(chap);
-    chap->frame=0;
-    chap->wait=0;
-    chap->flags|=CHF_FIXVIEW;
-    chap->pic_xoffs = 0;
-    chap->pic_yoffs = 0;
+	if ((vii < 1) || (vii > game.numviews)) {
+		quitprintf("!SetCharacterView: invalid view number (You said %d, max is %d)", vii, game.numviews);
+	}
+	vii--;
+
+	debug_script_log("%s: View locked to %d", chap->scrname, vii + 1);
+	if (chap->idleleft < 0) {
+		Character_UnlockView(chap);
+		chap->idleleft = chap->idletime;
+	}
+	if (stopMoving != KEEP_MOVING) {
+		Character_StopMoving(chap);
+	}
+	chap->view = vii;
+	chap->animating = 0;
+	FindReasonableLoopForCharacter(chap);
+	chap->frame = 0;
+	chap->wait = 0;
+	chap->flags |= CHF_FIXVIEW;
+	chap->pic_xoffs = 0;
+	chap->pic_yoffs = 0;
 }
 
 void Character_LockViewAligned_Old(CharacterInfo *chap, int vii, int loop, int align) {
-    Character_LockViewAlignedEx(chap, vii, loop, ConvertLegacyScriptAlignment((LegacyScriptAlignment)align), STOP_MOVING);
+	Character_LockViewAlignedEx(chap, vii, loop, ConvertLegacyScriptAlignment((LegacyScriptAlignment)align), STOP_MOVING);
 }
 
 void Character_LockViewAlignedEx_Old(CharacterInfo *chap, int vii, int loop, int align, int stopMoving) {
-    Character_LockViewAlignedEx(chap, vii, loop, ConvertLegacyScriptAlignment((LegacyScriptAlignment)align), stopMoving);
+	Character_LockViewAlignedEx(chap, vii, loop, ConvertLegacyScriptAlignment((LegacyScriptAlignment)align), stopMoving);
 }
 
 void Character_LockViewAligned(CharacterInfo *chap, int vii, int loop, int align) {
-    Character_LockViewAlignedEx(chap, vii, loop, align, STOP_MOVING);
+	Character_LockViewAlignedEx(chap, vii, loop, align, STOP_MOVING);
 }
 
 void Character_LockViewAlignedEx(CharacterInfo *chap, int vii, int loop, int align, int stopMoving) {
-    if (chap->view < 0)
-        quit("!SetCharacterLoop: character has invalid old view number");
+	if (chap->view < 0)
+		quit("!SetCharacterLoop: character has invalid old view number");
 
-    int sppic = views[chap->view].loops[chap->loop].frames[chap->frame].pic;
-    int leftSide = data_to_game_coord(chap->x) - game.SpriteInfos[sppic].Width / 2;
+	int sppic = views[chap->view].loops[chap->loop].frames[chap->frame].pic;
+	int leftSide = data_to_game_coord(chap->x) - game.SpriteInfos[sppic].Width / 2;
 
-    Character_LockViewEx(chap, vii, stopMoving);
+	Character_LockViewEx(chap, vii, stopMoving);
 
-    if ((loop < 0) || (loop >= views[chap->view].numLoops))
-        quit("!SetCharacterViewEx: invalid loop specified");
+	if ((loop < 0) || (loop >= views[chap->view].numLoops))
+		quit("!SetCharacterViewEx: invalid loop specified");
 
-    chap->loop = loop;
-    chap->frame = 0;
-    int newpic = views[chap->view].loops[chap->loop].frames[chap->frame].pic;
-    int newLeft = data_to_game_coord(chap->x) - game.SpriteInfos[newpic].Width / 2;
-    int xdiff = 0;
+	chap->loop = loop;
+	chap->frame = 0;
+	int newpic = views[chap->view].loops[chap->loop].frames[chap->frame].pic;
+	int newLeft = data_to_game_coord(chap->x) - game.SpriteInfos[newpic].Width / 2;
+	int xdiff = 0;
 
-    if (align & kMAlignLeft)
-        xdiff = leftSide - newLeft;
-    else if (align & kMAlignHCenter)
-        xdiff = 0;
-    else if (align & kMAlignRight)
-        xdiff = (leftSide + game.SpriteInfos[sppic].Width) - (newLeft + game.SpriteInfos[newpic].Width);
-    else
-        quit("!SetCharacterViewEx: invalid alignment type specified");
+	if (align & kMAlignLeft)
+		xdiff = leftSide - newLeft;
+	else if (align & kMAlignHCenter)
+		xdiff = 0;
+	else if (align & kMAlignRight)
+		xdiff = (leftSide + game.SpriteInfos[sppic].Width) - (newLeft + game.SpriteInfos[newpic].Width);
+	else
+		quit("!SetCharacterViewEx: invalid alignment type specified");
 
-    chap->pic_xoffs = xdiff;
-    chap->pic_yoffs = 0;
+	chap->pic_xoffs = xdiff;
+	chap->pic_yoffs = 0;
 }
 
 void Character_LockViewFrame(CharacterInfo *chaa, int view, int loop, int frame) {
-    Character_LockViewFrameEx(chaa, view, loop, frame, STOP_MOVING);
+	Character_LockViewFrameEx(chaa, view, loop, frame, STOP_MOVING);
 }
 
 void Character_LockViewFrameEx(CharacterInfo *chaa, int view, int loop, int frame, int stopMoving) {
 
-    Character_LockViewEx(chaa, view, stopMoving);
+	Character_LockViewEx(chaa, view, stopMoving);
 
-    view--;
-    if ((loop < 0) || (loop >= views[view].numLoops))
-        quit("!SetCharacterFrame: invalid loop specified");
-    if ((frame < 0) || (frame >= views[view].loops[loop].numFrames))
-        quit("!SetCharacterFrame: invalid frame specified");
+	view--;
+	if ((loop < 0) || (loop >= views[view].numLoops))
+		quit("!SetCharacterFrame: invalid loop specified");
+	if ((frame < 0) || (frame >= views[view].loops[loop].numFrames))
+		quit("!SetCharacterFrame: invalid frame specified");
 
-    chaa->loop = loop;
-    chaa->frame = frame;
+	chaa->loop = loop;
+	chaa->frame = frame;
 }
 
 void Character_LockViewOffset(CharacterInfo *chap, int vii, int xoffs, int yoffs) {
-    Character_LockViewOffsetEx(chap, vii, xoffs, yoffs, STOP_MOVING);
+	Character_LockViewOffsetEx(chap, vii, xoffs, yoffs, STOP_MOVING);
 }
 
 void Character_LockViewOffsetEx(CharacterInfo *chap, int vii, int xoffs, int yoffs, int stopMoving) {
-    Character_LockViewEx(chap, vii, stopMoving);
+	Character_LockViewEx(chap, vii, stopMoving);
 
-    // This function takes offsets in real game coordinates as opposed to script coordinates
-    defgame_to_finalgame_coords(xoffs, yoffs);
-    chap->pic_xoffs = xoffs;
-    chap->pic_yoffs = yoffs;
+	// This function takes offsets in real game coordinates as opposed to script coordinates
+	defgame_to_finalgame_coords(xoffs, yoffs);
+	chap->pic_xoffs = xoffs;
+	chap->pic_yoffs = yoffs;
 }
 
 void Character_LoseInventory(CharacterInfo *chap, ScriptInvItem *invi) {
 
-    if (invi == nullptr)
-        quit("!LoseInventoryFromCharacter: invalid invnetory number");
+	if (invi == nullptr)
+		quit("!LoseInventoryFromCharacter: invalid invnetory number");
 
-    int inum = invi->id;
+	int inum = invi->id;
 
-    if (chap->inv[inum] > 0)
-        chap->inv[inum]--;
+	if (chap->inv[inum] > 0)
+		chap->inv[inum]--;
 
-    if ((chap->activeinv == inum) & (chap->inv[inum] < 1)) {
-        chap->activeinv = -1;
-        if ((chap == playerchar) && (GetCursorMode() == MODE_USE))
-            set_cursor_mode(0);
-    }
+	if ((chap->activeinv == inum) & (chap->inv[inum] < 1)) {
+		chap->activeinv = -1;
+		if ((chap == playerchar) && (GetCursorMode() == MODE_USE))
+			set_cursor_mode(0);
+	}
 
-    int charid = chap->index_id;
+	int charid = chap->index_id;
 
-    if ((chap->inv[inum] == 0) || (game.options[OPT_DUPLICATEINV] > 0)) {
-        int xx,tt;
-        for (xx = 0; xx < charextra[charid].invorder_count; xx++) {
-            if (charextra[charid].invorder[xx] == inum) {
-                charextra[charid].invorder_count--;
-                for (tt = xx; tt < charextra[charid].invorder_count; tt++)
-                    charextra[charid].invorder[tt] = charextra[charid].invorder[tt+1];
-                break;
-            }
-        }
-    }
-    guis_need_update = 1;
+	if ((chap->inv[inum] == 0) || (game.options[OPT_DUPLICATEINV] > 0)) {
+		int xx, tt;
+		for (xx = 0; xx < charextra[charid].invorder_count; xx++) {
+			if (charextra[charid].invorder[xx] == inum) {
+				charextra[charid].invorder_count--;
+				for (tt = xx; tt < charextra[charid].invorder_count; tt++)
+					charextra[charid].invorder[tt] = charextra[charid].invorder[tt + 1];
+				break;
+			}
+		}
+	}
+	guis_need_update = 1;
 
-    if (chap == playerchar)
-        run_on_event (GE_LOSE_INV, RuntimeScriptValue().SetInt32(inum));
+	if (chap == playerchar)
+		run_on_event(GE_LOSE_INV, RuntimeScriptValue().SetInt32(inum));
 }
 
-void Character_PlaceOnWalkableArea(CharacterInfo *chap) 
-{
-    if (displayed_room < 0)
-        quit("!Character.PlaceOnWalkableArea: no room is currently loaded");
+void Character_PlaceOnWalkableArea(CharacterInfo *chap) {
+	if (displayed_room < 0)
+		quit("!Character.PlaceOnWalkableArea: no room is currently loaded");
 
-    find_nearest_walkable_area(&chap->x, &chap->y);
+	find_nearest_walkable_area(&chap->x, &chap->y);
 }
 
 void Character_RemoveTint(CharacterInfo *chaa) {
 
-    if (chaa->flags & (CHF_HASTINT | CHF_HASLIGHT)) {
-        debug_script_log("Un-tint %s", chaa->scrname);
-        chaa->flags &= ~(CHF_HASTINT | CHF_HASLIGHT);
-    }
-    else {
-        debug_script_warn("Character.RemoveTint called but character was not tinted");
-    }
+	if (chaa->flags & (CHF_HASTINT | CHF_HASLIGHT)) {
+		debug_script_log("Un-tint %s", chaa->scrname);
+		chaa->flags &= ~(CHF_HASTINT | CHF_HASLIGHT);
+	} else {
+		debug_script_warn("Character.RemoveTint called but character was not tinted");
+	}
 }
 
-int Character_GetHasExplicitTint_Old(CharacterInfo *ch)
-{
-    return ch->has_explicit_tint() || ch->has_explicit_light();
+int Character_GetHasExplicitTint_Old(CharacterInfo *ch) {
+	return ch->has_explicit_tint() || ch->has_explicit_light();
 }
 
-int Character_GetHasExplicitTint(CharacterInfo *ch)
-{
-    return ch->has_explicit_tint();
+int Character_GetHasExplicitTint(CharacterInfo *ch) {
+	return ch->has_explicit_tint();
 }
 
 void Character_Say(CharacterInfo *chaa, const char *text) {
-    _DisplaySpeechCore(chaa->index_id, text);
+	_DisplaySpeechCore(chaa->index_id, text);
 }
 
 void Character_SayAt(CharacterInfo *chaa, int x, int y, int width, const char *texx) {
 
-    DisplaySpeechAt(x, y, width, chaa->index_id, (char*)texx);
+	DisplaySpeechAt(x, y, width, chaa->index_id, (char *)texx);
 }
 
-ScriptOverlay* Character_SayBackground(CharacterInfo *chaa, const char *texx) {
+ScriptOverlay *Character_SayBackground(CharacterInfo *chaa, const char *texx) {
 
-    int ovltype = DisplaySpeechBackground(chaa->index_id, (char*)texx);
-    int ovri = find_overlay_of_type(ovltype);
-    if (ovri<0)
-        quit("!SayBackground internal error: no overlay");
+	int ovltype = DisplaySpeechBackground(chaa->index_id, (char *)texx);
+	int ovri = find_overlay_of_type(ovltype);
+	if (ovri < 0)
+		quit("!SayBackground internal error: no overlay");
 
-    // Convert the overlay ID to an Overlay object
-    ScriptOverlay *scOver = new ScriptOverlay();
-    scOver->overlayId = ovltype;
-    scOver->borderHeight = 0;
-    scOver->borderWidth = 0;
-    scOver->isBackgroundSpeech = 1;
-    int handl = ccRegisterManagedObject(scOver, scOver);
-    screenover[ovri].associatedOverlayHandle = handl;
+	// Convert the overlay ID to an Overlay object
+	ScriptOverlay *scOver = new ScriptOverlay();
+	scOver->overlayId = ovltype;
+	scOver->borderHeight = 0;
+	scOver->borderWidth = 0;
+	scOver->isBackgroundSpeech = 1;
+	int handl = ccRegisterManagedObject(scOver, scOver);
+	screenover[ovri].associatedOverlayHandle = handl;
 
-    return scOver;
+	return scOver;
 }
 
 void Character_SetAsPlayer(CharacterInfo *chaa) {
 
-    // Set to same character, so ignore.
-    // But only on versions > 2.61. The relevant entry in the 2.62 changelog is:
-    //  - Fixed SetPlayerCharacter to do nothing at all if you pass the current
-    //    player character to it (previously it was resetting the inventory layout)
-    if ((loaded_game_file_version > kGameVersion_261) && (game.playercharacter == chaa->index_id))
-        return;
+	// Set to same character, so ignore.
+	// But only on versions > 2.61. The relevant entry in the 2.62 changelog is:
+	//  - Fixed SetPlayerCharacter to do nothing at all if you pass the current
+	//    player character to it (previously it was resetting the inventory layout)
+	if ((loaded_game_file_version > kGameVersion_261) && (game.playercharacter == chaa->index_id))
+		return;
 
-    setup_player_character(chaa->index_id);
+	setup_player_character(chaa->index_id);
 
-    //update_invorder();
+	//update_invorder();
 
-    debug_script_log("%s is new player character", playerchar->scrname);
+	debug_script_log("%s is new player character", playerchar->scrname);
 
-    // Within game_start, return now
-    if (displayed_room < 0)
-        return;
+	// Within game_start, return now
+	if (displayed_room < 0)
+		return;
 
-    // Ignore invalid room numbers for the character and just place him in
-    // the current room for 2.x. Following script calls to NewRoom() will
-    // make sure this still works as intended.
-    if ((loaded_game_file_version <= kGameVersion_272) && (playerchar->room < 0))
-        playerchar->room = displayed_room;
+	// Ignore invalid room numbers for the character and just place him in
+	// the current room for 2.x. Following script calls to NewRoom() will
+	// make sure this still works as intended.
+	if ((loaded_game_file_version <= kGameVersion_272) && (playerchar->room < 0))
+		playerchar->room = displayed_room;
 
-    if (displayed_room != playerchar->room)
-        NewRoom(playerchar->room);
-    else   // make sure it doesn't run the region interactions
-        play.player_on_region = GetRegionIDAtRoom(playerchar->x, playerchar->y);
+	if (displayed_room != playerchar->room)
+		NewRoom(playerchar->room);
+	else   // make sure it doesn't run the region interactions
+		play.player_on_region = GetRegionIDAtRoom(playerchar->x, playerchar->y);
 
-    if ((playerchar->activeinv >= 0) && (playerchar->inv[playerchar->activeinv] < 1))
-        playerchar->activeinv = -1;
+	if ((playerchar->activeinv >= 0) && (playerchar->inv[playerchar->activeinv] < 1))
+		playerchar->activeinv = -1;
 
-    // They had inv selected, so change the cursor
-    if (cur_mode == MODE_USE) {
-        if (playerchar->activeinv < 0)
-            SetNextCursor ();
-        else
-            SetActiveInventory (playerchar->activeinv);
-    }
+	// They had inv selected, so change the cursor
+	if (cur_mode == MODE_USE) {
+		if (playerchar->activeinv < 0)
+			SetNextCursor();
+		else
+			SetActiveInventory(playerchar->activeinv);
+	}
 
 }
 
 
 void Character_SetIdleView(CharacterInfo *chaa, int iview, int itime) {
 
-    if (iview == 1) 
-        quit("!SetCharacterIdle: view 1 cannot be used as an idle view, sorry.");
-
-    // if an idle anim is currently playing, release it
-    if (chaa->idleleft < 0)
-        Character_UnlockView(chaa);
-
-    chaa->idleview = iview - 1;
-    // make sure they don't appear idle while idle anim is disabled
-    if (iview < 1)
-        itime = 10;
-    chaa->idletime = itime;
-    chaa->idleleft = itime;
-
-    // if not currently animating, reset the wait counter
-    if ((chaa->animating == 0) && (chaa->walking == 0))
-        chaa->wait = 0;
-
-    if (iview >= 1) {
-        debug_script_log("Set %s idle view to %d (time %d)", chaa->scrname, iview, itime);
-    }
-    else {
-        debug_script_log("%s idle view disabled", chaa->scrname);
-    }
-    if (chaa->flags & CHF_FIXVIEW) {
-        debug_script_warn("SetCharacterIdle called while character view locked with SetCharacterView; idle ignored");
-        debug_script_log("View locked, idle will not kick in until Released");
-    }
-    // if they switch to a swimming animation, kick it off immediately
-    if (itime == 0)
-        charextra[chaa->index_id].process_idle_this_time = 1;
-
-}
-
-bool Character_GetHasExplicitLight(CharacterInfo *ch)
-{
-    return ch->has_explicit_light();
+	if (iview == 1)
+		quit("!SetCharacterIdle: view 1 cannot be used as an idle view, sorry.");
+
+	// if an idle anim is currently playing, release it
+	if (chaa->idleleft < 0)
+		Character_UnlockView(chaa);
+
+	chaa->idleview = iview - 1;
+	// make sure they don't appear idle while idle anim is disabled
+	if (iview < 1)
+		itime = 10;
+	chaa->idletime = itime;
+	chaa->idleleft = itime;
+
+	// if not currently animating, reset the wait counter
+	if ((chaa->animating == 0) && (chaa->walking == 0))
+		chaa->wait = 0;
+
+	if (iview >= 1) {
+		debug_script_log("Set %s idle view to %d (time %d)", chaa->scrname, iview, itime);
+	} else {
+		debug_script_log("%s idle view disabled", chaa->scrname);
+	}
+	if (chaa->flags & CHF_FIXVIEW) {
+		debug_script_warn("SetCharacterIdle called while character view locked with SetCharacterView; idle ignored");
+		debug_script_log("View locked, idle will not kick in until Released");
+	}
+	// if they switch to a swimming animation, kick it off immediately
+	if (itime == 0)
+		charextra[chaa->index_id].process_idle_this_time = 1;
+
 }
 
-int Character_GetLightLevel(CharacterInfo *ch)
-{
-    return ch->has_explicit_light() ? charextra[ch->index_id].tint_light : 0;
+bool Character_GetHasExplicitLight(CharacterInfo *ch) {
+	return ch->has_explicit_light();
 }
 
-void Character_SetLightLevel(CharacterInfo *chaa, int light_level)
-{
-    light_level = Math::Clamp(light_level, -100, 100);
-    
-    charextra[chaa->index_id].tint_light = light_level;
-    chaa->flags &= ~CHF_HASTINT;
-    chaa->flags |= CHF_HASLIGHT;
+int Character_GetLightLevel(CharacterInfo *ch) {
+	return ch->has_explicit_light() ? charextra[ch->index_id].tint_light : 0;
 }
 
-int Character_GetTintRed(CharacterInfo *ch)
-{
-    return ch->has_explicit_tint() ? charextra[ch->index_id].tint_r : 0;
+void Character_SetLightLevel(CharacterInfo *chaa, int light_level) {
+	light_level = Math::Clamp(light_level, -100, 100);
+
+	charextra[chaa->index_id].tint_light = light_level;
+	chaa->flags &= ~CHF_HASTINT;
+	chaa->flags |= CHF_HASLIGHT;
 }
 
-int Character_GetTintGreen(CharacterInfo *ch)
-{
-    return ch->has_explicit_tint() ? charextra[ch->index_id].tint_g : 0;
+int Character_GetTintRed(CharacterInfo *ch) {
+	return ch->has_explicit_tint() ? charextra[ch->index_id].tint_r : 0;
 }
 
-int Character_GetTintBlue(CharacterInfo *ch)
-{
-    return ch->has_explicit_tint() ? charextra[ch->index_id].tint_b : 0;
+int Character_GetTintGreen(CharacterInfo *ch) {
+	return ch->has_explicit_tint() ? charextra[ch->index_id].tint_g : 0;
 }
 
-int Character_GetTintSaturation(CharacterInfo *ch)
-{
-    return ch->has_explicit_tint() ? charextra[ch->index_id].tint_level : 0;
+int Character_GetTintBlue(CharacterInfo *ch) {
+	return ch->has_explicit_tint() ? charextra[ch->index_id].tint_b : 0;
 }
 
-int Character_GetTintLuminance(CharacterInfo *ch)
-{
-    return ch->has_explicit_tint() ? ((charextra[ch->index_id].tint_light * 10) / 25) : 0;
+int Character_GetTintSaturation(CharacterInfo *ch) {
+	return ch->has_explicit_tint() ? charextra[ch->index_id].tint_level : 0;
+}
+
+int Character_GetTintLuminance(CharacterInfo *ch) {
+	return ch->has_explicit_tint() ? ((charextra[ch->index_id].tint_light * 10) / 25) : 0;
 }
 
 void Character_SetOption(CharacterInfo *chaa, int flag, int yesorno) {
 
-    if ((yesorno < 0) || (yesorno > 1))
-        quit("!SetCharacterProperty: last parameter must be 0 or 1");
+	if ((yesorno < 0) || (yesorno > 1))
+		quit("!SetCharacterProperty: last parameter must be 0 or 1");
 
-    if (flag & CHF_MANUALSCALING) {
-        // backwards compatibility fix
-        Character_SetIgnoreScaling(chaa, yesorno);
-    }
-    else {
-        chaa->flags &= ~flag;
-        if (yesorno)
-            chaa->flags |= flag;
-    }
+	if (flag & CHF_MANUALSCALING) {
+		// backwards compatibility fix
+		Character_SetIgnoreScaling(chaa, yesorno);
+	} else {
+		chaa->flags &= ~flag;
+		if (yesorno)
+			chaa->flags |= flag;
+	}
 
 }
 
 void Character_SetSpeed(CharacterInfo *chaa, int xspeed, int yspeed) {
 
-    if ((xspeed == 0) || (xspeed > 50) || (yspeed == 0) || (yspeed > 50))
-        quit("!SetCharacterSpeedEx: invalid speed value");
-    if (chaa->walking)
-    {
-        debug_script_warn("Character_SetSpeed: cannot change speed while walking");
-        return;
-    }
+	if ((xspeed == 0) || (xspeed > 50) || (yspeed == 0) || (yspeed > 50))
+		quit("!SetCharacterSpeedEx: invalid speed value");
+	if (chaa->walking) {
+		debug_script_warn("Character_SetSpeed: cannot change speed while walking");
+		return;
+	}
 
-    chaa->walkspeed = xspeed;
+	chaa->walkspeed = xspeed;
 
-    if (yspeed == xspeed) 
-        chaa->walkspeed_y = UNIFORM_WALK_SPEED;
-    else
-        chaa->walkspeed_y = yspeed;
+	if (yspeed == xspeed)
+		chaa->walkspeed_y = UNIFORM_WALK_SPEED;
+	else
+		chaa->walkspeed_y = yspeed;
 }
 
 
 void Character_StopMoving(CharacterInfo *charp) {
 
-    int chaa = charp->index_id;
-    if (chaa == play.skip_until_char_stops)
-        EndSkippingUntilCharStops();
-
-    if (charextra[chaa].xwas != INVALID_X) {
-        charp->x = charextra[chaa].xwas;
-        charp->y = charextra[chaa].ywas;
-        charextra[chaa].xwas = INVALID_X;
-    }
-    if ((charp->walking > 0) && (charp->walking < TURNING_AROUND)) {
-        // if it's not a MoveCharDirect, make sure they end up on a walkable area
-        if ((mls[charp->walking].direct == 0) && (charp->room == displayed_room))
-            Character_PlaceOnWalkableArea(charp);
-
-        debug_script_log("%s: stop moving", charp->scrname);
-
-        charp->idleleft = charp->idletime;
-        // restart the idle animation straight away
-        charextra[chaa].process_idle_this_time = 1;
-    }
-    if (charp->walking) {
-        // If the character is currently moving, stop them and reset their frame
-        charp->walking = 0;
-        if ((charp->flags & CHF_MOVENOTWALK) == 0)
-            charp->frame = 0;
-    }
+	int chaa = charp->index_id;
+	if (chaa == play.skip_until_char_stops)
+		EndSkippingUntilCharStops();
+
+	if (charextra[chaa].xwas != INVALID_X) {
+		charp->x = charextra[chaa].xwas;
+		charp->y = charextra[chaa].ywas;
+		charextra[chaa].xwas = INVALID_X;
+	}
+	if ((charp->walking > 0) && (charp->walking < TURNING_AROUND)) {
+		// if it's not a MoveCharDirect, make sure they end up on a walkable area
+		if ((mls[charp->walking].direct == 0) && (charp->room == displayed_room))
+			Character_PlaceOnWalkableArea(charp);
+
+		debug_script_log("%s: stop moving", charp->scrname);
+
+		charp->idleleft = charp->idletime;
+		// restart the idle animation straight away
+		charextra[chaa].process_idle_this_time = 1;
+	}
+	if (charp->walking) {
+		// If the character is currently moving, stop them and reset their frame
+		charp->walking = 0;
+		if ((charp->flags & CHF_MOVENOTWALK) == 0)
+			charp->frame = 0;
+	}
 }
 
 void Character_Tint(CharacterInfo *chaa, int red, int green, int blue, int opacity, int luminance) {
-    if ((red < 0) || (green < 0) || (blue < 0) ||
-        (red > 255) || (green > 255) || (blue > 255) ||
-        (opacity < 0) || (opacity > 100) ||
-        (luminance < 0) || (luminance > 100))
-        quit("!Character.Tint: invalid parameter. R,G,B must be 0-255, opacity & luminance 0-100");
+	if ((red < 0) || (green < 0) || (blue < 0) ||
+	        (red > 255) || (green > 255) || (blue > 255) ||
+	        (opacity < 0) || (opacity > 100) ||
+	        (luminance < 0) || (luminance > 100))
+		quit("!Character.Tint: invalid parameter. R,G,B must be 0-255, opacity & luminance 0-100");
 
-    debug_script_log("Set %s tint RGB(%d,%d,%d) %d%%", chaa->scrname, red, green, blue, opacity);
+	debug_script_log("Set %s tint RGB(%d,%d,%d) %d%%", chaa->scrname, red, green, blue, opacity);
 
-    charextra[chaa->index_id].tint_r = red;
-    charextra[chaa->index_id].tint_g = green;
-    charextra[chaa->index_id].tint_b = blue;
-    charextra[chaa->index_id].tint_level = opacity;
-    charextra[chaa->index_id].tint_light = (luminance * 25) / 10;
-    chaa->flags &= ~CHF_HASLIGHT;
-    chaa->flags |= CHF_HASTINT;
+	charextra[chaa->index_id].tint_r = red;
+	charextra[chaa->index_id].tint_g = green;
+	charextra[chaa->index_id].tint_b = blue;
+	charextra[chaa->index_id].tint_level = opacity;
+	charextra[chaa->index_id].tint_light = (luminance * 25) / 10;
+	chaa->flags &= ~CHF_HASLIGHT;
+	chaa->flags |= CHF_HASTINT;
 }
 
 void Character_Think(CharacterInfo *chaa, const char *text) {
-    _DisplayThoughtCore(chaa->index_id, text);
+	_DisplayThoughtCore(chaa->index_id, text);
 }
 
 void Character_UnlockView(CharacterInfo *chaa) {
-    Character_UnlockViewEx(chaa, STOP_MOVING);
+	Character_UnlockViewEx(chaa, STOP_MOVING);
 }
 
 void Character_UnlockViewEx(CharacterInfo *chaa, int stopMoving) {
-    if (chaa->flags & CHF_FIXVIEW) {
-        debug_script_log("%s: Released view back to default", chaa->scrname);
-    }
-    chaa->flags &= ~CHF_FIXVIEW;
-    chaa->view = chaa->defview;
-    chaa->frame = 0;
-    if (stopMoving != KEEP_MOVING)
-    {
-        Character_StopMoving(chaa);
-    }
-    if (chaa->view >= 0) {
-        int maxloop = views[chaa->view].numLoops;
-        if (((chaa->flags & CHF_NODIAGONAL)!=0) && (maxloop > 4))
-            maxloop = 4;
-        FindReasonableLoopForCharacter(chaa);
-    }
-    chaa->animating = 0;
-    chaa->idleleft = chaa->idletime;
-    chaa->pic_xoffs = 0;
-    chaa->pic_yoffs = 0;
-    // restart the idle animation straight away
-    charextra[chaa->index_id].process_idle_this_time = 1;
-
-}
-
-
-void Character_Walk(CharacterInfo *chaa, int x, int y, int blocking, int direct) 
-{
-    walk_or_move_character(chaa, x, y, blocking, direct, true);
+	if (chaa->flags & CHF_FIXVIEW) {
+		debug_script_log("%s: Released view back to default", chaa->scrname);
+	}
+	chaa->flags &= ~CHF_FIXVIEW;
+	chaa->view = chaa->defview;
+	chaa->frame = 0;
+	if (stopMoving != KEEP_MOVING) {
+		Character_StopMoving(chaa);
+	}
+	if (chaa->view >= 0) {
+		int maxloop = views[chaa->view].numLoops;
+		if (((chaa->flags & CHF_NODIAGONAL) != 0) && (maxloop > 4))
+			maxloop = 4;
+		FindReasonableLoopForCharacter(chaa);
+	}
+	chaa->animating = 0;
+	chaa->idleleft = chaa->idletime;
+	chaa->pic_xoffs = 0;
+	chaa->pic_yoffs = 0;
+	// restart the idle animation straight away
+	charextra[chaa->index_id].process_idle_this_time = 1;
+
 }
 
-void Character_Move(CharacterInfo *chaa, int x, int y, int blocking, int direct) 
-{
-    walk_or_move_character(chaa, x, y, blocking, direct, false);
+
+void Character_Walk(CharacterInfo *chaa, int x, int y, int blocking, int direct) {
+	walk_or_move_character(chaa, x, y, blocking, direct, true);
+}
+
+void Character_Move(CharacterInfo *chaa, int x, int y, int blocking, int direct) {
+	walk_or_move_character(chaa, x, y, blocking, direct, false);
 }
 
 void Character_WalkStraight(CharacterInfo *chaa, int xx, int yy, int blocking) {
 
-    if (chaa->room != displayed_room)
-        quit("!MoveCharacterStraight: specified character not in current room");
+	if (chaa->room != displayed_room)
+		quit("!MoveCharacterStraight: specified character not in current room");
 
-    Character_StopMoving(chaa);
-    int movetox = xx, movetoy = yy;
+	Character_StopMoving(chaa);
+	int movetox = xx, movetoy = yy;
 
-    set_wallscreen(prepare_walkable_areas(chaa->index_id));
+	set_wallscreen(prepare_walkable_areas(chaa->index_id));
 
-    int fromXLowres = room_to_mask_coord(chaa->x);
-    int fromYLowres = room_to_mask_coord(chaa->y);
-    int toXLowres = room_to_mask_coord(xx);
-    int toYLowres = room_to_mask_coord(yy);
+	int fromXLowres = room_to_mask_coord(chaa->x);
+	int fromYLowres = room_to_mask_coord(chaa->y);
+	int toXLowres = room_to_mask_coord(xx);
+	int toYLowres = room_to_mask_coord(yy);
 
-    if (!can_see_from(fromXLowres, fromYLowres, toXLowres, toYLowres)) {
-        int lastcx, lastcy;
-        get_lastcpos(lastcx, lastcy);
-        movetox = mask_to_room_coord(lastcx);
-        movetoy = mask_to_room_coord(lastcy);
-    }
+	if (!can_see_from(fromXLowres, fromYLowres, toXLowres, toYLowres)) {
+		int lastcx, lastcy;
+		get_lastcpos(lastcx, lastcy);
+		movetox = mask_to_room_coord(lastcx);
+		movetoy = mask_to_room_coord(lastcy);
+	}
 
-    walk_character(chaa->index_id, movetox, movetoy, 1, true);
+	walk_character(chaa->index_id, movetox, movetoy, 1, true);
 
-    if ((blocking == BLOCKING) || (blocking == 1))
-        GameLoopUntilNotMoving(&chaa->walking);
-    else if ((blocking != IN_BACKGROUND) && (blocking != 0))
-        quit("!Character.Walk: Blocking must be BLOCKING or IN_BACKGRUOND");
+	if ((blocking == BLOCKING) || (blocking == 1))
+		GameLoopUntilNotMoving(&chaa->walking);
+	else if ((blocking != IN_BACKGROUND) && (blocking != 0))
+		quit("!Character.Walk: Blocking must be BLOCKING or IN_BACKGRUOND");
 
 }
 
 void Character_RunInteraction(CharacterInfo *chaa, int mood) {
 
-    RunCharacterInteraction(chaa->index_id, mood);
+	RunCharacterInteraction(chaa->index_id, mood);
 }
 
 
@@ -1093,578 +1041,562 @@ void Character_RunInteraction(CharacterInfo *chaa, int mood) {
 
 int Character_GetProperty(CharacterInfo *chaa, const char *property) {
 
-    return get_int_property(game.charProps[chaa->index_id], play.charProps[chaa->index_id], property);
+	return get_int_property(game.charProps[chaa->index_id], play.charProps[chaa->index_id], property);
 
 }
 void Character_GetPropertyText(CharacterInfo *chaa, const char *property, char *bufer) {
-    get_text_property(game.charProps[chaa->index_id], play.charProps[chaa->index_id], property, bufer);
+	get_text_property(game.charProps[chaa->index_id], play.charProps[chaa->index_id], property, bufer);
 }
-const char* Character_GetTextProperty(CharacterInfo *chaa, const char *property) {
-    return get_text_property_dynamic_string(game.charProps[chaa->index_id], play.charProps[chaa->index_id], property);
+const char *Character_GetTextProperty(CharacterInfo *chaa, const char *property) {
+	return get_text_property_dynamic_string(game.charProps[chaa->index_id], play.charProps[chaa->index_id], property);
 }
 
-bool Character_SetProperty(CharacterInfo *chaa, const char *property, int value)
-{
-    return set_int_property(play.charProps[chaa->index_id], property, value);
+bool Character_SetProperty(CharacterInfo *chaa, const char *property, int value) {
+	return set_int_property(play.charProps[chaa->index_id], property, value);
 }
 
-bool Character_SetTextProperty(CharacterInfo *chaa, const char *property, const char *value)
-{
-    return set_text_property(play.charProps[chaa->index_id], property, value);
+bool Character_SetTextProperty(CharacterInfo *chaa, const char *property, const char *value) {
+	return set_text_property(play.charProps[chaa->index_id], property, value);
 }
 
-ScriptInvItem* Character_GetActiveInventory(CharacterInfo *chaa) {
+ScriptInvItem *Character_GetActiveInventory(CharacterInfo *chaa) {
 
-    if (chaa->activeinv <= 0)
-        return nullptr;
+	if (chaa->activeinv <= 0)
+		return nullptr;
 
-    return &scrInv[chaa->activeinv];
+	return &scrInv[chaa->activeinv];
 }
 
-void Character_SetActiveInventory(CharacterInfo *chaa, ScriptInvItem* iit) {
-    guis_need_update = 1;
+void Character_SetActiveInventory(CharacterInfo *chaa, ScriptInvItem *iit) {
+	guis_need_update = 1;
 
-    if (iit == nullptr) {
-        chaa->activeinv = -1;
+	if (iit == nullptr) {
+		chaa->activeinv = -1;
 
-        if (chaa->index_id == game.playercharacter) {
+		if (chaa->index_id == game.playercharacter) {
 
-            if (GetCursorMode()==MODE_USE)
-                set_cursor_mode(0);
-        }
-        return;
-    }
+			if (GetCursorMode() == MODE_USE)
+				set_cursor_mode(0);
+		}
+		return;
+	}
 
-    if (chaa->inv[iit->id] < 1)
-    {
-        debug_script_warn("SetActiveInventory: character doesn't have any of that inventory");
-        return;
-    }
+	if (chaa->inv[iit->id] < 1) {
+		debug_script_warn("SetActiveInventory: character doesn't have any of that inventory");
+		return;
+	}
 
-    chaa->activeinv = iit->id;
+	chaa->activeinv = iit->id;
 
-    if (chaa->index_id == game.playercharacter) {
-        // if it's the player character, update mouse cursor
-        update_inv_cursor(iit->id);
-        set_cursor_mode(MODE_USE);
-    }
+	if (chaa->index_id == game.playercharacter) {
+		// if it's the player character, update mouse cursor
+		update_inv_cursor(iit->id);
+		set_cursor_mode(MODE_USE);
+	}
 }
 
 int Character_GetAnimating(CharacterInfo *chaa) {
-    if (chaa->animating)
-        return 1;
-    return 0;
+	if (chaa->animating)
+		return 1;
+	return 0;
 }
 
 int Character_GetAnimationSpeed(CharacterInfo *chaa) {
-    return chaa->animspeed;
+	return chaa->animspeed;
 }
 
 void Character_SetAnimationSpeed(CharacterInfo *chaa, int newval) {
 
-    chaa->animspeed = newval;
+	chaa->animspeed = newval;
 }
 
 int Character_GetBaseline(CharacterInfo *chaa) {
 
-    if (chaa->baseline < 1)
-        return 0;
+	if (chaa->baseline < 1)
+		return 0;
 
-    return chaa->baseline;
+	return chaa->baseline;
 }
 
 void Character_SetBaseline(CharacterInfo *chaa, int basel) {
 
-    chaa->baseline = basel;
+	chaa->baseline = basel;
 }
 
 int Character_GetBlinkInterval(CharacterInfo *chaa) {
 
-    return chaa->blinkinterval;
+	return chaa->blinkinterval;
 }
 
 void Character_SetBlinkInterval(CharacterInfo *chaa, int interval) {
 
-    if (interval < 0)
-        quit("!SetCharacterBlinkView: invalid blink interval");
+	if (interval < 0)
+		quit("!SetCharacterBlinkView: invalid blink interval");
 
-    chaa->blinkinterval = interval;
+	chaa->blinkinterval = interval;
 
-    if (chaa->blinktimer > 0)
-        chaa->blinktimer = chaa->blinkinterval;
+	if (chaa->blinktimer > 0)
+		chaa->blinktimer = chaa->blinkinterval;
 }
 
 int Character_GetBlinkView(CharacterInfo *chaa) {
 
-    return chaa->blinkview + 1;
+	return chaa->blinkview + 1;
 }
 
 void Character_SetBlinkView(CharacterInfo *chaa, int vii) {
 
-    if (((vii < 2) || (vii > game.numviews)) && (vii != -1))
-        quit("!SetCharacterBlinkView: invalid view number");
+	if (((vii < 2) || (vii > game.numviews)) && (vii != -1))
+		quit("!SetCharacterBlinkView: invalid view number");
 
-    chaa->blinkview = vii - 1;
+	chaa->blinkview = vii - 1;
 }
 
 int Character_GetBlinkWhileThinking(CharacterInfo *chaa) {
-    if (chaa->flags & CHF_NOBLINKANDTHINK)
-        return 0;
-    return 1;
+	if (chaa->flags & CHF_NOBLINKANDTHINK)
+		return 0;
+	return 1;
 }
 
 void Character_SetBlinkWhileThinking(CharacterInfo *chaa, int yesOrNo) {
-    chaa->flags &= ~CHF_NOBLINKANDTHINK;
-    if (yesOrNo == 0)
-        chaa->flags |= CHF_NOBLINKANDTHINK;
+	chaa->flags &= ~CHF_NOBLINKANDTHINK;
+	if (yesOrNo == 0)
+		chaa->flags |= CHF_NOBLINKANDTHINK;
 }
 
 int Character_GetBlockingHeight(CharacterInfo *chaa) {
 
-    return chaa->blocking_height;
+	return chaa->blocking_height;
 }
 
 void Character_SetBlockingHeight(CharacterInfo *chaa, int hit) {
 
-    chaa->blocking_height = hit;
+	chaa->blocking_height = hit;
 }
 
 int Character_GetBlockingWidth(CharacterInfo *chaa) {
 
-    return chaa->blocking_width;
+	return chaa->blocking_width;
 }
 
 void Character_SetBlockingWidth(CharacterInfo *chaa, int wid) {
 
-    chaa->blocking_width = wid;
+	chaa->blocking_width = wid;
 }
 
 int Character_GetDiagonalWalking(CharacterInfo *chaa) {
 
-    if (chaa->flags & CHF_NODIAGONAL)
-        return 0;
-    return 1;  
+	if (chaa->flags & CHF_NODIAGONAL)
+		return 0;
+	return 1;
 }
 
 void Character_SetDiagonalWalking(CharacterInfo *chaa, int yesorno) {
 
-    chaa->flags &= ~CHF_NODIAGONAL;
-    if (!yesorno)
-        chaa->flags |= CHF_NODIAGONAL;
+	chaa->flags &= ~CHF_NODIAGONAL;
+	if (!yesorno)
+		chaa->flags |= CHF_NODIAGONAL;
 }
 
 int Character_GetClickable(CharacterInfo *chaa) {
 
-    if (chaa->flags & CHF_NOINTERACT)
-        return 0;
-    return 1;
+	if (chaa->flags & CHF_NOINTERACT)
+		return 0;
+	return 1;
 }
 
 void Character_SetClickable(CharacterInfo *chaa, int clik) {
 
-    chaa->flags &= ~CHF_NOINTERACT;
-    // if they don't want it clickable, set the relevant bit
-    if (clik == 0)
-        chaa->flags |= CHF_NOINTERACT;
+	chaa->flags &= ~CHF_NOINTERACT;
+	// if they don't want it clickable, set the relevant bit
+	if (clik == 0)
+		chaa->flags |= CHF_NOINTERACT;
 }
 
 int Character_GetID(CharacterInfo *chaa) {
 
-    return chaa->index_id;
+	return chaa->index_id;
 
 }
 
 int Character_GetFrame(CharacterInfo *chaa) {
-    return chaa->frame;
+	return chaa->frame;
 }
 
 void Character_SetFrame(CharacterInfo *chaa, int newval) {
-    chaa->frame = newval;
+	chaa->frame = newval;
 }
 
 int Character_GetIdleView(CharacterInfo *chaa) {
 
-    if (chaa->idleview < 1)
-        return -1;
+	if (chaa->idleview < 1)
+		return -1;
 
-    return chaa->idleview + 1;
+	return chaa->idleview + 1;
 }
 
 int Character_GetIInventoryQuantity(CharacterInfo *chaa, int index) {
-    if ((index < 1) || (index >= game.numinvitems))
-        quitprintf("!Character.InventoryQuantity: invalid inventory index %d", index);
+	if ((index < 1) || (index >= game.numinvitems))
+		quitprintf("!Character.InventoryQuantity: invalid inventory index %d", index);
 
-    return chaa->inv[index];
+	return chaa->inv[index];
 }
 
-int Character_HasInventory(CharacterInfo *chaa, ScriptInvItem *invi)
-{
-    if (invi == nullptr)
-        quit("!Character.HasInventory: NULL inventory item supplied");
+int Character_HasInventory(CharacterInfo *chaa, ScriptInvItem *invi) {
+	if (invi == nullptr)
+		quit("!Character.HasInventory: NULL inventory item supplied");
 
-    return (chaa->inv[invi->id] > 0) ? 1 : 0;
+	return (chaa->inv[invi->id] > 0) ? 1 : 0;
 }
 
 void Character_SetIInventoryQuantity(CharacterInfo *chaa, int index, int quant) {
-    if ((index < 1) || (index >= game.numinvitems))
-        quitprintf("!Character.InventoryQuantity: invalid inventory index %d", index);
+	if ((index < 1) || (index >= game.numinvitems))
+		quitprintf("!Character.InventoryQuantity: invalid inventory index %d", index);
 
-    if ((quant < 0) || (quant > 32000))
-        quitprintf("!Character.InventoryQuantity: invalid quantity %d", quant);
+	if ((quant < 0) || (quant > 32000))
+		quitprintf("!Character.InventoryQuantity: invalid quantity %d", quant);
 
-    chaa->inv[index] = quant;
+	chaa->inv[index] = quant;
 }
 
 int Character_GetIgnoreLighting(CharacterInfo *chaa) {
 
-    if (chaa->flags & CHF_NOLIGHTING)
-        return 1;
-    return 0;
+	if (chaa->flags & CHF_NOLIGHTING)
+		return 1;
+	return 0;
 }
 
 void Character_SetIgnoreLighting(CharacterInfo *chaa, int yesorno) {
 
-    chaa->flags &= ~CHF_NOLIGHTING;
-    if (yesorno)
-        chaa->flags |= CHF_NOLIGHTING;
+	chaa->flags &= ~CHF_NOLIGHTING;
+	if (yesorno)
+		chaa->flags |= CHF_NOLIGHTING;
 }
 
 int Character_GetIgnoreScaling(CharacterInfo *chaa) {
 
-    if (chaa->flags & CHF_MANUALSCALING)
-        return 1;
-    return 0;  
+	if (chaa->flags & CHF_MANUALSCALING)
+		return 1;
+	return 0;
 }
 
 void Character_SetIgnoreScaling(CharacterInfo *chaa, int yesorno) {
 
-    if (yesorno) {
-        // when setting IgnoreScaling to 1, should reset zoom level
-        // like it used to in pre-2.71
-        charextra[chaa->index_id].zoom = 100;
-    }
-    Character_SetManualScaling(chaa, yesorno);
+	if (yesorno) {
+		// when setting IgnoreScaling to 1, should reset zoom level
+		// like it used to in pre-2.71
+		charextra[chaa->index_id].zoom = 100;
+	}
+	Character_SetManualScaling(chaa, yesorno);
 }
 
 void Character_SetManualScaling(CharacterInfo *chaa, int yesorno) {
 
-    chaa->flags &= ~CHF_MANUALSCALING;
-    if (yesorno)
-        chaa->flags |= CHF_MANUALSCALING;
+	chaa->flags &= ~CHF_MANUALSCALING;
+	if (yesorno)
+		chaa->flags |= CHF_MANUALSCALING;
 }
 
 int Character_GetIgnoreWalkbehinds(CharacterInfo *chaa) {
 
-    if (chaa->flags & CHF_NOWALKBEHINDS)
-        return 1;
-    return 0;
+	if (chaa->flags & CHF_NOWALKBEHINDS)
+		return 1;
+	return 0;
 }
 
 void Character_SetIgnoreWalkbehinds(CharacterInfo *chaa, int yesorno) {
-    if (game.options[OPT_BASESCRIPTAPI] >= kScriptAPI_v350)
-        debug_script_warn("IgnoreWalkbehinds is not recommended for use, consider other solutions");
-    chaa->flags &= ~CHF_NOWALKBEHINDS;
-    if (yesorno)
-        chaa->flags |= CHF_NOWALKBEHINDS;
+	if (game.options[OPT_BASESCRIPTAPI] >= kScriptAPI_v350)
+		debug_script_warn("IgnoreWalkbehinds is not recommended for use, consider other solutions");
+	chaa->flags &= ~CHF_NOWALKBEHINDS;
+	if (yesorno)
+		chaa->flags |= CHF_NOWALKBEHINDS;
 }
 
 int Character_GetMovementLinkedToAnimation(CharacterInfo *chaa) {
 
-    if (chaa->flags & CHF_ANTIGLIDE)
-        return 1;
-    return 0;
+	if (chaa->flags & CHF_ANTIGLIDE)
+		return 1;
+	return 0;
 }
 
 void Character_SetMovementLinkedToAnimation(CharacterInfo *chaa, int yesorno) {
 
-    chaa->flags &= ~CHF_ANTIGLIDE;
-    if (yesorno)
-        chaa->flags |= CHF_ANTIGLIDE;
+	chaa->flags &= ~CHF_ANTIGLIDE;
+	if (yesorno)
+		chaa->flags |= CHF_ANTIGLIDE;
 }
 
 int Character_GetLoop(CharacterInfo *chaa) {
-    return chaa->loop;
+	return chaa->loop;
 }
 
 void Character_SetLoop(CharacterInfo *chaa, int newval) {
-    if ((newval < 0) || (newval >= views[chaa->view].numLoops))
-        quit("!Character.Loop: invalid loop number for this view");
+	if ((newval < 0) || (newval >= views[chaa->view].numLoops))
+		quit("!Character.Loop: invalid loop number for this view");
 
-    chaa->loop = newval;
+	chaa->loop = newval;
 
-    if (chaa->frame >= views[chaa->view].loops[chaa->loop].numFrames)
-        chaa->frame = 0;
+	if (chaa->frame >= views[chaa->view].loops[chaa->loop].numFrames)
+		chaa->frame = 0;
 }
 
 int Character_GetMoving(CharacterInfo *chaa) {
-    if (chaa->walking)
-        return 1;
-    return 0;
+	if (chaa->walking)
+		return 1;
+	return 0;
 }
 
 int Character_GetDestinationX(CharacterInfo *chaa) {
-    if (chaa->walking) {
-        MoveList *cmls = &mls[chaa->walking % TURNING_AROUND];
-        return cmls->pos[cmls->numstage - 1] >> 16;
-    }
-    else
-        return chaa->x;
+	if (chaa->walking) {
+		MoveList *cmls = &mls[chaa->walking % TURNING_AROUND];
+		return cmls->pos[cmls->numstage - 1] >> 16;
+	} else
+		return chaa->x;
 }
 
 int Character_GetDestinationY(CharacterInfo *chaa) {
-    if (chaa->walking) {
-        MoveList *cmls = &mls[chaa->walking % TURNING_AROUND];
-        return cmls->pos[cmls->numstage - 1] & 0xFFFF;
-    }
-    else
-        return chaa->y;
+	if (chaa->walking) {
+		MoveList *cmls = &mls[chaa->walking % TURNING_AROUND];
+		return cmls->pos[cmls->numstage - 1] & 0xFFFF;
+	} else
+		return chaa->y;
 }
 
-const char* Character_GetName(CharacterInfo *chaa) {
-    return CreateNewScriptString(chaa->name);
+const char *Character_GetName(CharacterInfo *chaa) {
+	return CreateNewScriptString(chaa->name);
 }
 
 void Character_SetName(CharacterInfo *chaa, const char *newName) {
-    strncpy(chaa->name, newName, 40);
-    chaa->name[39] = 0;
+	strncpy(chaa->name, newName, 40);
+	chaa->name[39] = 0;
 }
 
 int Character_GetNormalView(CharacterInfo *chaa) {
-    return chaa->defview + 1;
+	return chaa->defview + 1;
 }
 
 int Character_GetPreviousRoom(CharacterInfo *chaa) {
-    return chaa->prevroom;
+	return chaa->prevroom;
 }
 
 int Character_GetRoom(CharacterInfo *chaa) {
-    return chaa->room;
+	return chaa->room;
 }
 
 
 int Character_GetScaleMoveSpeed(CharacterInfo *chaa) {
 
-    if (chaa->flags & CHF_SCALEMOVESPEED)
-        return 1;
-    return 0;  
+	if (chaa->flags & CHF_SCALEMOVESPEED)
+		return 1;
+	return 0;
 }
 
 void Character_SetScaleMoveSpeed(CharacterInfo *chaa, int yesorno) {
 
-    if ((yesorno < 0) || (yesorno > 1))
-        quit("Character.ScaleMoveSpeed: value must be true or false (1 or 0)");
+	if ((yesorno < 0) || (yesorno > 1))
+		quit("Character.ScaleMoveSpeed: value must be true or false (1 or 0)");
 
-    chaa->flags &= ~CHF_SCALEMOVESPEED;
-    if (yesorno)
-        chaa->flags |= CHF_SCALEMOVESPEED;
+	chaa->flags &= ~CHF_SCALEMOVESPEED;
+	if (yesorno)
+		chaa->flags |= CHF_SCALEMOVESPEED;
 }
 
 int Character_GetScaleVolume(CharacterInfo *chaa) {
 
-    if (chaa->flags & CHF_SCALEVOLUME)
-        return 1;
-    return 0;  
+	if (chaa->flags & CHF_SCALEVOLUME)
+		return 1;
+	return 0;
 }
 
 void Character_SetScaleVolume(CharacterInfo *chaa, int yesorno) {
 
-    if ((yesorno < 0) || (yesorno > 1))
-        quit("Character.ScaleVolume: value must be true or false (1 or 0)");
+	if ((yesorno < 0) || (yesorno > 1))
+		quit("Character.ScaleVolume: value must be true or false (1 or 0)");
 
-    chaa->flags &= ~CHF_SCALEVOLUME;
-    if (yesorno)
-        chaa->flags |= CHF_SCALEVOLUME;
+	chaa->flags &= ~CHF_SCALEVOLUME;
+	if (yesorno)
+		chaa->flags |= CHF_SCALEVOLUME;
 }
 
 int Character_GetScaling(CharacterInfo *chaa) {
-    return charextra[chaa->index_id].zoom;
+	return charextra[chaa->index_id].zoom;
 }
 
 void Character_SetScaling(CharacterInfo *chaa, int zoomlevel) {
 
-    if ((chaa->flags & CHF_MANUALSCALING) == 0)
-    {
-        debug_script_warn("Character.Scaling: cannot set property unless ManualScaling is enabled");
-        return;
-    }
-    if ((zoomlevel < 5) || (zoomlevel > 200))
-        quit("!Character.Scaling: scaling level must be between 5 and 200%");
+	if ((chaa->flags & CHF_MANUALSCALING) == 0) {
+		debug_script_warn("Character.Scaling: cannot set property unless ManualScaling is enabled");
+		return;
+	}
+	if ((zoomlevel < 5) || (zoomlevel > 200))
+		quit("!Character.Scaling: scaling level must be between 5 and 200%");
 
-    charextra[chaa->index_id].zoom = zoomlevel;
+	charextra[chaa->index_id].zoom = zoomlevel;
 }
 
 int Character_GetSolid(CharacterInfo *chaa) {
 
-    if (chaa->flags & CHF_NOBLOCKING)
-        return 0;
-    return 1;
+	if (chaa->flags & CHF_NOBLOCKING)
+		return 0;
+	return 1;
 }
 
 void Character_SetSolid(CharacterInfo *chaa, int yesorno) {
 
-    chaa->flags &= ~CHF_NOBLOCKING;
-    if (!yesorno)
-        chaa->flags |= CHF_NOBLOCKING;
+	chaa->flags &= ~CHF_NOBLOCKING;
+	if (!yesorno)
+		chaa->flags |= CHF_NOBLOCKING;
 }
 
 int Character_GetSpeaking(CharacterInfo *chaa) {
-    if (get_character_currently_talking() == chaa->index_id)
-        return 1;
+	if (get_character_currently_talking() == chaa->index_id)
+		return 1;
 
-    return 0;
+	return 0;
 }
 
 int Character_GetSpeechColor(CharacterInfo *chaa) {
 
-    return chaa->talkcolor;
+	return chaa->talkcolor;
 }
 
 void Character_SetSpeechColor(CharacterInfo *chaa, int ncol) {
 
-    chaa->talkcolor = ncol;
+	chaa->talkcolor = ncol;
 }
 
-void Character_SetSpeechAnimationDelay(CharacterInfo *chaa, int newDelay)
-{
-    if (game.options[OPT_GLOBALTALKANIMSPD] != 0)
-    {
-        debug_script_warn("Character.SpeechAnimationDelay cannot be set when global speech animation speed is enabled");
-        return;
-    }
+void Character_SetSpeechAnimationDelay(CharacterInfo *chaa, int newDelay) {
+	if (game.options[OPT_GLOBALTALKANIMSPD] != 0) {
+		debug_script_warn("Character.SpeechAnimationDelay cannot be set when global speech animation speed is enabled");
+		return;
+	}
 
-    chaa->speech_anim_speed = newDelay;
+	chaa->speech_anim_speed = newDelay;
 }
 
 int Character_GetSpeechView(CharacterInfo *chaa) {
 
-    return chaa->talkview + 1;
+	return chaa->talkview + 1;
 }
 
 void Character_SetSpeechView(CharacterInfo *chaa, int vii) {
-    if (vii == -1) {
-        chaa->talkview = -1;
-        return;
-    }
+	if (vii == -1) {
+		chaa->talkview = -1;
+		return;
+	}
 
-    if ((vii < 1) || (vii > game.numviews))
-        quit("!SetCharacterSpeechView: invalid view number");
+	if ((vii < 1) || (vii > game.numviews))
+		quit("!SetCharacterSpeechView: invalid view number");
 
-    chaa->talkview = vii - 1;
+	chaa->talkview = vii - 1;
 }
 
-bool Character_GetThinking(CharacterInfo *chaa)
-{
-    return char_thinking == chaa->index_id;
+bool Character_GetThinking(CharacterInfo *chaa) {
+	return char_thinking == chaa->index_id;
 }
 
-int Character_GetThinkingFrame(CharacterInfo *chaa)
-{
-    if (char_thinking == chaa->index_id)
-        return chaa->thinkview > 0 ? chaa->frame : -1;
+int Character_GetThinkingFrame(CharacterInfo *chaa) {
+	if (char_thinking == chaa->index_id)
+		return chaa->thinkview > 0 ? chaa->frame : -1;
 
-    debug_script_warn("Character.ThinkingFrame: character is not currently thinking");
-    return -1;
+	debug_script_warn("Character.ThinkingFrame: character is not currently thinking");
+	return -1;
 }
 
 int Character_GetThinkView(CharacterInfo *chaa) {
 
-    return chaa->thinkview + 1;
+	return chaa->thinkview + 1;
 }
 
 void Character_SetThinkView(CharacterInfo *chaa, int vii) {
-    if (((vii < 2) || (vii > game.numviews)) && (vii != -1))
-        quit("!SetCharacterThinkView: invalid view number");
+	if (((vii < 2) || (vii > game.numviews)) && (vii != -1))
+		quit("!SetCharacterThinkView: invalid view number");
 
-    chaa->thinkview = vii - 1;
+	chaa->thinkview = vii - 1;
 }
 
 int Character_GetTransparency(CharacterInfo *chaa) {
 
-    return GfxDef::LegacyTrans255ToTrans100(chaa->transparency);
+	return GfxDef::LegacyTrans255ToTrans100(chaa->transparency);
 }
 
 void Character_SetTransparency(CharacterInfo *chaa, int trans) {
 
-    if ((trans < 0) || (trans > 100))
-        quit("!SetCharTransparent: transparency value must be between 0 and 100");
+	if ((trans < 0) || (trans > 100))
+		quit("!SetCharTransparent: transparency value must be between 0 and 100");
 
-    chaa->transparency = GfxDef::Trans100ToLegacyTrans255(trans);
+	chaa->transparency = GfxDef::Trans100ToLegacyTrans255(trans);
 }
 
 int Character_GetTurnBeforeWalking(CharacterInfo *chaa) {
 
-    if (chaa->flags & CHF_NOTURNING)
-        return 0;
-    return 1;  
+	if (chaa->flags & CHF_NOTURNING)
+		return 0;
+	return 1;
 }
 
 void Character_SetTurnBeforeWalking(CharacterInfo *chaa, int yesorno) {
 
-    chaa->flags &= ~CHF_NOTURNING;
-    if (!yesorno)
-        chaa->flags |= CHF_NOTURNING;
+	chaa->flags &= ~CHF_NOTURNING;
+	if (!yesorno)
+		chaa->flags |= CHF_NOTURNING;
 }
 
 int Character_GetView(CharacterInfo *chaa) {
-    return chaa->view + 1;
+	return chaa->view + 1;
 }
 
 int Character_GetWalkSpeedX(CharacterInfo *chaa) {
-    return chaa->walkspeed;
+	return chaa->walkspeed;
 }
 
 int Character_GetWalkSpeedY(CharacterInfo *chaa) {
-    if (chaa->walkspeed_y != UNIFORM_WALK_SPEED)
-        return chaa->walkspeed_y;
+	if (chaa->walkspeed_y != UNIFORM_WALK_SPEED)
+		return chaa->walkspeed_y;
 
-    return chaa->walkspeed;
+	return chaa->walkspeed;
 }
 
 int Character_GetX(CharacterInfo *chaa) {
-    return chaa->x;
+	return chaa->x;
 }
 
 void Character_SetX(CharacterInfo *chaa, int newval) {
-    chaa->x = newval;
+	chaa->x = newval;
 }
 
 int Character_GetY(CharacterInfo *chaa) {
-    return chaa->y;
+	return chaa->y;
 }
 
 void Character_SetY(CharacterInfo *chaa, int newval) {
-    chaa->y = newval;
+	chaa->y = newval;
 }
 
 int Character_GetZ(CharacterInfo *chaa) {
-    return chaa->z;
+	return chaa->z;
 }
 
 void Character_SetZ(CharacterInfo *chaa, int newval) {
-    chaa->z = newval;
+	chaa->z = newval;
 }
 
 extern int char_speaking;
 
 int Character_GetSpeakingFrame(CharacterInfo *chaa) {
 
-    if ((face_talking >= 0) && (facetalkrepeat))
-    {
-        if (facetalkchar->index_id == chaa->index_id)
-        {
-            return facetalkframe;
-        }
-    }
-    else if (char_speaking >= 0)
-    {
-        if (char_speaking == chaa->index_id)
-        {
-            return chaa->frame;
-        }
-    }
-
-    debug_script_warn("Character.SpeakingFrame: character is not currently speaking");
-    return -1;
+	if ((face_talking >= 0) && (facetalkrepeat)) {
+		if (facetalkchar->index_id == chaa->index_id) {
+			return facetalkframe;
+		}
+	} else if (char_speaking >= 0) {
+		if (char_speaking == chaa->index_id) {
+			return chaa->frame;
+		}
+	}
+
+	debug_script_warn("Character.SpeakingFrame: character is not currently speaking");
+	return -1;
 }
 
 //=============================================================================
@@ -1672,1285 +1604,1240 @@ int Character_GetSpeakingFrame(CharacterInfo *chaa) {
 // order of loops to turn character in circle from down to down
 int turnlooporder[8] = {0, 6, 1, 7, 3, 5, 2, 4};
 
-void walk_character(int chac,int tox,int toy,int ignwal, bool autoWalkAnims) {
-    CharacterInfo*chin=&game.chars[chac];
-    if (chin->room!=displayed_room)
-        quit("!MoveCharacter: character not in current room");
-
-    chin->flags &= ~CHF_MOVENOTWALK;
-
-    int toxPassedIn = tox, toyPassedIn = toy;
-    int charX = room_to_mask_coord(chin->x);
-    int charY = room_to_mask_coord(chin->y);
-    tox = room_to_mask_coord(tox);
-    toy = room_to_mask_coord(toy);
-
-    if ((tox == charX) && (toy == charY)) {
-        StopMoving(chac);
-        debug_script_log("%s already at destination, not moving", chin->scrname);
-        return;
-    }
-
-    if ((chin->animating) && (autoWalkAnims))
-        chin->animating = 0;
-
-    if (chin->idleleft < 0) {
-        ReleaseCharacterView(chac);
-        chin->idleleft=chin->idletime;
-    }
-    // stop them to make sure they're on a walkable area
-    // but save their frame first so that if they're already
-    // moving it looks smoother
-    int oldframe = chin->frame;
-    int waitWas = 0, animWaitWas = 0;
-    // if they are currently walking, save the current Wait
-    if (chin->walking)
-    {
-        waitWas = chin->walkwait;
-        animWaitWas = charextra[chac].animwait;
-    }
-
-    StopMoving (chac);
-    chin->frame = oldframe;
-    // use toxPassedIn cached variable so the hi-res co-ordinates
-    // are still displayed as such
-    debug_script_log("%s: Start move to %d,%d", chin->scrname, toxPassedIn, toyPassedIn);
-
-    int move_speed_x = chin->walkspeed;
-    int move_speed_y = chin->walkspeed;
-
-    if (chin->walkspeed_y != UNIFORM_WALK_SPEED)
-        move_speed_y = chin->walkspeed_y;
-
-    if ((move_speed_x == 0) && (move_speed_y == 0)) {
-        debug_script_warn("Warning: MoveCharacter called for '%s' with walk speed 0", chin->name);
-    }
-
-    set_route_move_speed(move_speed_x, move_speed_y);
-    set_color_depth(8);
-    int mslot=find_route(charX, charY, tox, toy, prepare_walkable_areas(chac), chac+CHMLSOFFS, 1, ignwal);
-    set_color_depth(game.GetColorDepth());
-    if (mslot>0) {
-        chin->walking = mslot;
-        mls[mslot].direct = ignwal;
-        convert_move_path_to_room_resolution(&mls[mslot]);
-
-        // cancel any pending waits on current animations
-        // or if they were already moving, keep the current wait - 
-        // this prevents a glitch if MoveCharacter is called when they
-        // are already moving
-        if (autoWalkAnims)
-        {
-            chin->walkwait = waitWas;
-            charextra[chac].animwait = animWaitWas;
-
-            if (mls[mslot].pos[0] != mls[mslot].pos[1]) {
-                fix_player_sprite(&mls[mslot],chin);
-            }
-        }
-        else
-            chin->flags |= CHF_MOVENOTWALK;
-    }
-    else if (autoWalkAnims) // pathfinder couldn't get a route, stand them still
-        chin->frame = 0;
-}
-
-int find_looporder_index (int curloop) {
-    int rr;
-    for (rr = 0; rr < 8; rr++) {
-        if (turnlooporder[rr] == curloop)
-            return rr;
-    }
-    return 0;
+void walk_character(int chac, int tox, int toy, int ignwal, bool autoWalkAnims) {
+	CharacterInfo *chin = &game.chars[chac];
+	if (chin->room != displayed_room)
+		quit("!MoveCharacter: character not in current room");
+
+	chin->flags &= ~CHF_MOVENOTWALK;
+
+	int toxPassedIn = tox, toyPassedIn = toy;
+	int charX = room_to_mask_coord(chin->x);
+	int charY = room_to_mask_coord(chin->y);
+	tox = room_to_mask_coord(tox);
+	toy = room_to_mask_coord(toy);
+
+	if ((tox == charX) && (toy == charY)) {
+		StopMoving(chac);
+		debug_script_log("%s already at destination, not moving", chin->scrname);
+		return;
+	}
+
+	if ((chin->animating) && (autoWalkAnims))
+		chin->animating = 0;
+
+	if (chin->idleleft < 0) {
+		ReleaseCharacterView(chac);
+		chin->idleleft = chin->idletime;
+	}
+	// stop them to make sure they're on a walkable area
+	// but save their frame first so that if they're already
+	// moving it looks smoother
+	int oldframe = chin->frame;
+	int waitWas = 0, animWaitWas = 0;
+	// if they are currently walking, save the current Wait
+	if (chin->walking) {
+		waitWas = chin->walkwait;
+		animWaitWas = charextra[chac].animwait;
+	}
+
+	StopMoving(chac);
+	chin->frame = oldframe;
+	// use toxPassedIn cached variable so the hi-res co-ordinates
+	// are still displayed as such
+	debug_script_log("%s: Start move to %d,%d", chin->scrname, toxPassedIn, toyPassedIn);
+
+	int move_speed_x = chin->walkspeed;
+	int move_speed_y = chin->walkspeed;
+
+	if (chin->walkspeed_y != UNIFORM_WALK_SPEED)
+		move_speed_y = chin->walkspeed_y;
+
+	if ((move_speed_x == 0) && (move_speed_y == 0)) {
+		debug_script_warn("Warning: MoveCharacter called for '%s' with walk speed 0", chin->name);
+	}
+
+	set_route_move_speed(move_speed_x, move_speed_y);
+	set_color_depth(8);
+	int mslot = find_route(charX, charY, tox, toy, prepare_walkable_areas(chac), chac + CHMLSOFFS, 1, ignwal);
+	set_color_depth(game.GetColorDepth());
+	if (mslot > 0) {
+		chin->walking = mslot;
+		mls[mslot].direct = ignwal;
+		convert_move_path_to_room_resolution(&mls[mslot]);
+
+		// cancel any pending waits on current animations
+		// or if they were already moving, keep the current wait -
+		// this prevents a glitch if MoveCharacter is called when they
+		// are already moving
+		if (autoWalkAnims) {
+			chin->walkwait = waitWas;
+			charextra[chac].animwait = animWaitWas;
+
+			if (mls[mslot].pos[0] != mls[mslot].pos[1]) {
+				fix_player_sprite(&mls[mslot], chin);
+			}
+		} else
+			chin->flags |= CHF_MOVENOTWALK;
+	} else if (autoWalkAnims) // pathfinder couldn't get a route, stand them still
+		chin->frame = 0;
+}
+
+int find_looporder_index(int curloop) {
+	int rr;
+	for (rr = 0; rr < 8; rr++) {
+		if (turnlooporder[rr] == curloop)
+			return rr;
+	}
+	return 0;
 }
 
 // returns 0 to use diagonal, 1 to not
-int useDiagonal (CharacterInfo *char1) {
-    if ((views[char1->view].numLoops < 8) || ((char1->flags & CHF_NODIAGONAL)!=0))
-        return 1;
-    // If they have just provided standing frames for loops 4-7, to
-    // provide smoother turning
-    if (views[char1->view].loops[4].numFrames < 2)
-        return 2;
-    return 0;
+int useDiagonal(CharacterInfo *char1) {
+	if ((views[char1->view].numLoops < 8) || ((char1->flags & CHF_NODIAGONAL) != 0))
+		return 1;
+	// If they have just provided standing frames for loops 4-7, to
+	// provide smoother turning
+	if (views[char1->view].loops[4].numFrames < 2)
+		return 2;
+	return 0;
 }
 
 // returns 1 normally, or 0 if they only have horizontal animations
 int hasUpDownLoops(CharacterInfo *char1) {
-    // if no loops in the Down animation
-    // or no loops in the Up animation
-    if ((views[char1->view].loops[0].numFrames < 1) ||
-        (views[char1->view].numLoops < 4) ||
-        (views[char1->view].loops[3].numFrames < 1))
-    {
-        return 0;
-    }
-
-    return 1;
-}
-
-void start_character_turning (CharacterInfo *chinf, int useloop, int no_diagonal) {
-    // work out how far round they have to turn 
-    int fromidx = find_looporder_index (chinf->loop);
-    int toidx = find_looporder_index (useloop);
-    //Display("Curloop: %d, needloop: %d",chinf->loop, useloop);
-    int ii, go_anticlock = 0;
-    // work out whether anticlockwise is quicker or not
-    if ((toidx > fromidx) && ((toidx - fromidx) > 4))
-        go_anticlock = 1;
-    if ((toidx < fromidx) && ((fromidx - toidx) < 4))
-        go_anticlock = 1;
-    // strip any current turning_around stages
-    chinf->walking = chinf->walking % TURNING_AROUND;
-    if (go_anticlock)
-        chinf->walking += TURNING_BACKWARDS;
-    else
-        go_anticlock = -1;
-
-    // Allow the diagonal frames just for turning
-    if (no_diagonal == 2)
-        no_diagonal = 0;
-
-    for (ii = fromidx; ii != toidx; ii -= go_anticlock) {
-        if (ii < 0)
-            ii = 7;
-        if (ii >= 8)
-            ii = 0;
-        if (ii == toidx)
-            break;
-        if ((turnlooporder[ii] >= 4) && (no_diagonal > 0))
-            continue;
-        if (views[chinf->view].loops[turnlooporder[ii]].numFrames < 1)
-            continue;
-        if (turnlooporder[ii] < views[chinf->view].numLoops)
-            chinf->walking += TURNING_AROUND;
-    }
-
-}
-
-void fix_player_sprite(MoveList*cmls,CharacterInfo*chinf) {
-    const fixed xpmove = cmls->xpermove[cmls->onstage];
-    const fixed ypmove = cmls->ypermove[cmls->onstage];
-
-    // if not moving, do nothing
-    if ((xpmove == 0) && (ypmove == 0))
-        return;
-
-    const int useloop = GetDirectionalLoop(chinf, xpmove, ypmove);
-
-    if ((game.options[OPT_ROTATECHARS] == 0) || ((chinf->flags & CHF_NOTURNING) != 0)) {
-        chinf->loop = useloop;
-        return;
-    }
-    if ((chinf->loop > kDirLoop_LastOrthogonal) && ((chinf->flags & CHF_NODIAGONAL)!=0)) {
-        // They've just been playing an animation with an extended loop number,
-        // so don't try and rotate using it
-        chinf->loop = useloop;
-        return;
-    }
-    if ((chinf->loop >= views[chinf->view].numLoops) ||
-        (views[chinf->view].loops[chinf->loop].numFrames < 1) ||
-        (hasUpDownLoops(chinf) == 0)) {
-            // Character is not currently on a valid loop, so don't try to rotate
-            // eg. left/right only view, but current loop 0
-            chinf->loop = useloop;
-            return;
-    }
-    const int no_diagonal = useDiagonal (chinf);
-    start_character_turning (chinf, useloop, no_diagonal);
+	// if no loops in the Down animation
+	// or no loops in the Up animation
+	if ((views[char1->view].loops[0].numFrames < 1) ||
+	        (views[char1->view].numLoops < 4) ||
+	        (views[char1->view].loops[3].numFrames < 1)) {
+		return 0;
+	}
+
+	return 1;
+}
+
+void start_character_turning(CharacterInfo *chinf, int useloop, int no_diagonal) {
+	// work out how far round they have to turn
+	int fromidx = find_looporder_index(chinf->loop);
+	int toidx = find_looporder_index(useloop);
+	//Display("Curloop: %d, needloop: %d",chinf->loop, useloop);
+	int ii, go_anticlock = 0;
+	// work out whether anticlockwise is quicker or not
+	if ((toidx > fromidx) && ((toidx - fromidx) > 4))
+		go_anticlock = 1;
+	if ((toidx < fromidx) && ((fromidx - toidx) < 4))
+		go_anticlock = 1;
+	// strip any current turning_around stages
+	chinf->walking = chinf->walking % TURNING_AROUND;
+	if (go_anticlock)
+		chinf->walking += TURNING_BACKWARDS;
+	else
+		go_anticlock = -1;
+
+	// Allow the diagonal frames just for turning
+	if (no_diagonal == 2)
+		no_diagonal = 0;
+
+	for (ii = fromidx; ii != toidx; ii -= go_anticlock) {
+		if (ii < 0)
+			ii = 7;
+		if (ii >= 8)
+			ii = 0;
+		if (ii == toidx)
+			break;
+		if ((turnlooporder[ii] >= 4) && (no_diagonal > 0))
+			continue;
+		if (views[chinf->view].loops[turnlooporder[ii]].numFrames < 1)
+			continue;
+		if (turnlooporder[ii] < views[chinf->view].numLoops)
+			chinf->walking += TURNING_AROUND;
+	}
+
+}
+
+void fix_player_sprite(MoveList *cmls, CharacterInfo *chinf) {
+	const fixed xpmove = cmls->xpermove[cmls->onstage];
+	const fixed ypmove = cmls->ypermove[cmls->onstage];
+
+	// if not moving, do nothing
+	if ((xpmove == 0) && (ypmove == 0))
+		return;
+
+	const int useloop = GetDirectionalLoop(chinf, xpmove, ypmove);
+
+	if ((game.options[OPT_ROTATECHARS] == 0) || ((chinf->flags & CHF_NOTURNING) != 0)) {
+		chinf->loop = useloop;
+		return;
+	}
+	if ((chinf->loop > kDirLoop_LastOrthogonal) && ((chinf->flags & CHF_NODIAGONAL) != 0)) {
+		// They've just been playing an animation with an extended loop number,
+		// so don't try and rotate using it
+		chinf->loop = useloop;
+		return;
+	}
+	if ((chinf->loop >= views[chinf->view].numLoops) ||
+	        (views[chinf->view].loops[chinf->loop].numFrames < 1) ||
+	        (hasUpDownLoops(chinf) == 0)) {
+		// Character is not currently on a valid loop, so don't try to rotate
+		// eg. left/right only view, but current loop 0
+		chinf->loop = useloop;
+		return;
+	}
+	const int no_diagonal = useDiagonal(chinf);
+	start_character_turning(chinf, useloop, no_diagonal);
 }
 
 // Check whether two characters have walked into each other
 int has_hit_another_character(int sourceChar) {
 
-    // if the character who's moving doesn't Bitmap *, don't bother checking
-    if (game.chars[sourceChar].flags & CHF_NOBLOCKING)
-        return -1;
+	// if the character who's moving doesn't Bitmap *, don't bother checking
+	if (game.chars[sourceChar].flags & CHF_NOBLOCKING)
+		return -1;
 
-    for (int ww = 0; ww < game.numcharacters; ww++) {
-        if (game.chars[ww].on != 1) continue;
-        if (game.chars[ww].room != displayed_room) continue;
-        if (ww == sourceChar) continue;
-        if (game.chars[ww].flags & CHF_NOBLOCKING) continue;
+	for (int ww = 0; ww < game.numcharacters; ww++) {
+		if (game.chars[ww].on != 1) continue;
+		if (game.chars[ww].room != displayed_room) continue;
+		if (ww == sourceChar) continue;
+		if (game.chars[ww].flags & CHF_NOBLOCKING) continue;
 
-        if (is_char_on_another (sourceChar, ww, nullptr, nullptr)) {
-            // we are now overlapping character 'ww'
-            if ((game.chars[ww].walking) && 
-                ((game.chars[ww].flags & CHF_AWAITINGMOVE) == 0))
-                return ww;
-        }
+		if (is_char_on_another(sourceChar, ww, nullptr, nullptr)) {
+			// we are now overlapping character 'ww'
+			if ((game.chars[ww].walking) &&
+			        ((game.chars[ww].flags & CHF_AWAITINGMOVE) == 0))
+				return ww;
+		}
 
-    }
-    return -1;
+	}
+	return -1;
 }
 
 // Does the next move from the character's movelist.
 // Returns 1 if they are now waiting for another char to move,
 // otherwise returns 0
-int doNextCharMoveStep (CharacterInfo *chi, int &char_index, CharacterExtras *chex) {
-    int ntf=0, xwas = chi->x, ywas = chi->y;
-
-    if (do_movelist_move(&chi->walking,&chi->x,&chi->y) == 2) 
-    {
-        if ((chi->flags & CHF_MOVENOTWALK) == 0)
-            fix_player_sprite(&mls[chi->walking], chi);
-    }
-
-    ntf = has_hit_another_character(char_index);
-    if (ntf >= 0) {
-        chi->walkwait = 30;
-        if (game.chars[ntf].walkspeed < 5)
-            chi->walkwait += (5 - game.chars[ntf].walkspeed) * 5;
-        // we are now waiting for the other char to move, so
-        // make sure he doesn't stop for us too
-
-        chi->flags |= CHF_AWAITINGMOVE;
-
-        if ((chi->flags & CHF_MOVENOTWALK) == 0)
-        {
-            chi->frame = 0;
-            chex->animwait = chi->walkwait;
-        }
-
-        if ((chi->walking < 1) || (chi->walking >= TURNING_AROUND)) ;
-        else if (mls[chi->walking].onpart > 0) {
-            mls[chi->walking].onpart --;
-            chi->x = xwas;
-            chi->y = ywas;
-        }
-        debug_script_log("%s: Bumped into %s, waiting for them to move", chi->scrname, game.chars[ntf].scrname);
-        return 1;
-    }
-    return 0;
-}
-
-int find_nearest_walkable_area_within(int *xx, int *yy, int range, int step)
-{
-    int ex, ey, nearest = 99999, thisis, nearx = 0, neary = 0;
-    int startx = 0, starty = 14;
-    int roomWidthLowRes = room_to_mask_coord(thisroom.Width);
-    int roomHeightLowRes = room_to_mask_coord(thisroom.Height);
-    int xwidth = roomWidthLowRes, yheight = roomHeightLowRes;
-
-    int xLowRes = room_to_mask_coord(xx[0]);
-    int yLowRes = room_to_mask_coord(yy[0]);
-    int rightEdge = room_to_mask_coord(thisroom.Edges.Right);
-    int leftEdge = room_to_mask_coord(thisroom.Edges.Left);
-    int topEdge = room_to_mask_coord(thisroom.Edges.Top);
-    int bottomEdge = room_to_mask_coord(thisroom.Edges.Bottom);
-
-    // tweak because people forget to move the edges sometimes
-    // if the player is already over the edge, ignore it
-    if (xLowRes >= rightEdge) rightEdge = roomWidthLowRes;
-    if (xLowRes <= leftEdge) leftEdge = 0;
-    if (yLowRes >= bottomEdge) bottomEdge = roomHeightLowRes;
-    if (yLowRes <= topEdge) topEdge = 0;
-
-    if (range > 0) 
-    {
-        startx = xLowRes - range;
-        starty = yLowRes - range;
-        xwidth = startx + range * 2;
-        yheight = starty + range * 2;
-        if (startx < 0) startx = 0;
-        if (starty < 10) starty = 10;
-        if (xwidth > roomWidthLowRes) xwidth = roomWidthLowRes;
-        if (yheight > roomHeightLowRes) yheight = roomHeightLowRes;
-    }
-
-    for (ex = startx; ex < xwidth; ex += step) {
-        for (ey = starty; ey < yheight; ey += step) {
-            // non-walkalbe, so don't go here
-            if (thisroom.WalkAreaMask->GetPixel(ex,ey) == 0) continue;
-            // off a screen edge, don't move them there
-            if ((ex <= leftEdge) || (ex >= rightEdge) ||
-                (ey <= topEdge) || (ey >= bottomEdge))
-                continue;
-            // otherwise, calculate distance from target
-            thisis=(int) ::sqrt((double)((ex - xLowRes) * (ex - xLowRes) + (ey - yLowRes) * (ey - yLowRes)));
-            if (thisis<nearest) { nearest=thisis; nearx=ex; neary=ey; }
-        }
-    }
-    if (nearest < 90000) 
-    {
-        xx[0] = mask_to_room_coord(nearx);
-        yy[0] = mask_to_room_coord(neary);
-        return 1;
-    }
-
-    return 0;
-}
-
-void find_nearest_walkable_area (int *xx, int *yy) {
-
-    int pixValue = thisroom.WalkAreaMask->GetPixel(room_to_mask_coord(xx[0]), room_to_mask_coord(yy[0]));
-    // only fix this code if the game was built with 2.61 or above
-    if (pixValue == 0 || (loaded_game_file_version >= kGameVersion_261 && pixValue < 1))
-    {
-        // First, check every 2 pixels within immediate area
-        if (!find_nearest_walkable_area_within(xx, yy, 20, 2))
-        {
-            // If not, check whole screen at 5 pixel intervals
-            find_nearest_walkable_area_within(xx, yy, -1, 5);
-        }
-    }
+int doNextCharMoveStep(CharacterInfo *chi, int &char_index, CharacterExtras *chex) {
+	int ntf = 0, xwas = chi->x, ywas = chi->y;
+
+	if (do_movelist_move(&chi->walking, &chi->x, &chi->y) == 2) {
+		if ((chi->flags & CHF_MOVENOTWALK) == 0)
+			fix_player_sprite(&mls[chi->walking], chi);
+	}
+
+	ntf = has_hit_another_character(char_index);
+	if (ntf >= 0) {
+		chi->walkwait = 30;
+		if (game.chars[ntf].walkspeed < 5)
+			chi->walkwait += (5 - game.chars[ntf].walkspeed) * 5;
+		// we are now waiting for the other char to move, so
+		// make sure he doesn't stop for us too
+
+		chi->flags |= CHF_AWAITINGMOVE;
+
+		if ((chi->flags & CHF_MOVENOTWALK) == 0) {
+			chi->frame = 0;
+			chex->animwait = chi->walkwait;
+		}
+
+		if ((chi->walking < 1) || (chi->walking >= TURNING_AROUND)) ;
+		else if (mls[chi->walking].onpart > 0) {
+			mls[chi->walking].onpart --;
+			chi->x = xwas;
+			chi->y = ywas;
+		}
+		debug_script_log("%s: Bumped into %s, waiting for them to move", chi->scrname, game.chars[ntf].scrname);
+		return 1;
+	}
+	return 0;
+}
+
+int find_nearest_walkable_area_within(int *xx, int *yy, int range, int step) {
+	int ex, ey, nearest = 99999, thisis, nearx = 0, neary = 0;
+	int startx = 0, starty = 14;
+	int roomWidthLowRes = room_to_mask_coord(thisroom.Width);
+	int roomHeightLowRes = room_to_mask_coord(thisroom.Height);
+	int xwidth = roomWidthLowRes, yheight = roomHeightLowRes;
+
+	int xLowRes = room_to_mask_coord(xx[0]);
+	int yLowRes = room_to_mask_coord(yy[0]);
+	int rightEdge = room_to_mask_coord(thisroom.Edges.Right);
+	int leftEdge = room_to_mask_coord(thisroom.Edges.Left);
+	int topEdge = room_to_mask_coord(thisroom.Edges.Top);
+	int bottomEdge = room_to_mask_coord(thisroom.Edges.Bottom);
+
+	// tweak because people forget to move the edges sometimes
+	// if the player is already over the edge, ignore it
+	if (xLowRes >= rightEdge) rightEdge = roomWidthLowRes;
+	if (xLowRes <= leftEdge) leftEdge = 0;
+	if (yLowRes >= bottomEdge) bottomEdge = roomHeightLowRes;
+	if (yLowRes <= topEdge) topEdge = 0;
+
+	if (range > 0) {
+		startx = xLowRes - range;
+		starty = yLowRes - range;
+		xwidth = startx + range * 2;
+		yheight = starty + range * 2;
+		if (startx < 0) startx = 0;
+		if (starty < 10) starty = 10;
+		if (xwidth > roomWidthLowRes) xwidth = roomWidthLowRes;
+		if (yheight > roomHeightLowRes) yheight = roomHeightLowRes;
+	}
+
+	for (ex = startx; ex < xwidth; ex += step) {
+		for (ey = starty; ey < yheight; ey += step) {
+			// non-walkalbe, so don't go here
+			if (thisroom.WalkAreaMask->GetPixel(ex, ey) == 0) continue;
+			// off a screen edge, don't move them there
+			if ((ex <= leftEdge) || (ex >= rightEdge) ||
+			        (ey <= topEdge) || (ey >= bottomEdge))
+				continue;
+			// otherwise, calculate distance from target
+			thisis = (int) ::sqrt((double)((ex - xLowRes) * (ex - xLowRes) + (ey - yLowRes) * (ey - yLowRes)));
+			if (thisis < nearest) {
+				nearest = thisis;
+				nearx = ex;
+				neary = ey;
+			}
+		}
+	}
+	if (nearest < 90000) {
+		xx[0] = mask_to_room_coord(nearx);
+		yy[0] = mask_to_room_coord(neary);
+		return 1;
+	}
+
+	return 0;
+}
+
+void find_nearest_walkable_area(int *xx, int *yy) {
+
+	int pixValue = thisroom.WalkAreaMask->GetPixel(room_to_mask_coord(xx[0]), room_to_mask_coord(yy[0]));
+	// only fix this code if the game was built with 2.61 or above
+	if (pixValue == 0 || (loaded_game_file_version >= kGameVersion_261 && pixValue < 1)) {
+		// First, check every 2 pixels within immediate area
+		if (!find_nearest_walkable_area_within(xx, yy, 20, 2)) {
+			// If not, check whole screen at 5 pixel intervals
+			find_nearest_walkable_area_within(xx, yy, -1, 5);
+		}
+	}
 
 }
 
 void FindReasonableLoopForCharacter(CharacterInfo *chap) {
 
-    if (chap->loop >= views[chap->view].numLoops)
-        chap->loop=kDirLoop_Default;
-    if (views[chap->view].numLoops < 1)
-        quitprintf("!View %d does not have any loops", chap->view + 1);
+	if (chap->loop >= views[chap->view].numLoops)
+		chap->loop = kDirLoop_Default;
+	if (views[chap->view].numLoops < 1)
+		quitprintf("!View %d does not have any loops", chap->view + 1);
 
-    // if the current loop has no frames, find one that does
-    if (views[chap->view].loops[chap->loop].numFrames < 1) 
-    {
-        for (int i = 0; i < views[chap->view].numLoops; i++) 
-        {
-            if (views[chap->view].loops[i].numFrames > 0) {
-                chap->loop = i;
-                break;
-            }
-        }
-    }
+	// if the current loop has no frames, find one that does
+	if (views[chap->view].loops[chap->loop].numFrames < 1) {
+		for (int i = 0; i < views[chap->view].numLoops; i++) {
+			if (views[chap->view].loops[i].numFrames > 0) {
+				chap->loop = i;
+				break;
+			}
+		}
+	}
 
 }
 
-void walk_or_move_character(CharacterInfo *chaa, int x, int y, int blocking, int direct, bool isWalk)
-{
-    if (chaa->on != 1)
-    {
-        debug_script_warn("MoveCharacterBlocking: character is turned off and cannot be moved");
-        return;
-    }
+void walk_or_move_character(CharacterInfo *chaa, int x, int y, int blocking, int direct, bool isWalk) {
+	if (chaa->on != 1) {
+		debug_script_warn("MoveCharacterBlocking: character is turned off and cannot be moved");
+		return;
+	}
 
-    if ((direct == ANYWHERE) || (direct == 1))
-        walk_character(chaa->index_id, x, y, 1, isWalk);
-    else if ((direct == WALKABLE_AREAS) || (direct == 0))
-        walk_character(chaa->index_id, x, y, 0, isWalk);
-    else
-        quit("!Character.Walk: Direct must be ANYWHERE or WALKABLE_AREAS");
+	if ((direct == ANYWHERE) || (direct == 1))
+		walk_character(chaa->index_id, x, y, 1, isWalk);
+	else if ((direct == WALKABLE_AREAS) || (direct == 0))
+		walk_character(chaa->index_id, x, y, 0, isWalk);
+	else
+		quit("!Character.Walk: Direct must be ANYWHERE or WALKABLE_AREAS");
 
-    if ((blocking == BLOCKING) || (blocking == 1))
-        GameLoopUntilNotMoving(&chaa->walking);
-    else if ((blocking != IN_BACKGROUND) && (blocking != 0))
-        quit("!Character.Walk: Blocking must be BLOCKING or IN_BACKGRUOND");
+	if ((blocking == BLOCKING) || (blocking == 1))
+		GameLoopUntilNotMoving(&chaa->walking);
+	else if ((blocking != IN_BACKGROUND) && (blocking != 0))
+		quit("!Character.Walk: Blocking must be BLOCKING or IN_BACKGRUOND");
 
 }
 
 int is_valid_character(int newchar) {
-    if ((newchar < 0) || (newchar >= game.numcharacters)) return 0;
-    return 1;
-}
-
-int wantMoveNow (CharacterInfo *chi, CharacterExtras *chex) {
-    // check most likely case first
-    if ((chex->zoom == 100) || ((chi->flags & CHF_SCALEMOVESPEED) == 0))
-        return 1;
-
-    // the % checks don't work when the counter is negative, so once
-    // it wraps round, correct it
-    while (chi->walkwaitcounter < 0) {
-        chi->walkwaitcounter += 12000;
-    }
-
-    // scaling 170-200%, move 175% speed
-    if (chex->zoom >= 170) {
-        if ((chi->walkwaitcounter % 4) >= 1)
-            return 2;
-        else
-            return 1;
-    }
-    // scaling 140-170%, move 150% speed
-    else if (chex->zoom >= 140) {
-        if ((chi->walkwaitcounter % 2) == 1)
-            return 2;
-        else
-            return 1;
-    }
-    // scaling 115-140%, move 125% speed
-    else if (chex->zoom >= 115) {
-        if ((chi->walkwaitcounter % 4) >= 3)
-            return 2;
-        else
-            return 1;
-    }
-    // scaling 80-120%, normal speed
-    else if (chex->zoom >= 80)
-        return 1;
-    // scaling 60-80%, move 75% speed
-    if (chex->zoom >= 60) {
-        if ((chi->walkwaitcounter % 4) >= 1)
-            return -1;
-        else if (chex->xwas != INVALID_X) {
-            // move the second half of the movement to make it smoother
-            chi->x = chex->xwas;
-            chi->y = chex->ywas;
-            chex->xwas = INVALID_X;
-        }
-    }
-    // scaling 30-60%, move 50% speed
-    else if (chex->zoom >= 30) {
-        if ((chi->walkwaitcounter % 2) == 1)
-            return -1;
-        else if (chex->xwas != INVALID_X) {
-            // move the second half of the movement to make it smoother
-            chi->x = chex->xwas;
-            chi->y = chex->ywas;
-            chex->xwas = INVALID_X;
-        }
-    }
-    // scaling 0-30%, move 25% speed
-    else {
-        if ((chi->walkwaitcounter % 4) >= 3)
-            return -1;
-        if (((chi->walkwaitcounter % 4) == 1) && (chex->xwas != INVALID_X)) {
-            // move the second half of the movement to make it smoother
-            chi->x = chex->xwas;
-            chi->y = chex->ywas;
-            chex->xwas = INVALID_X;
-        }
-
-    }
-
-    return 0;
+	if ((newchar < 0) || (newchar >= game.numcharacters)) return 0;
+	return 1;
+}
+
+int wantMoveNow(CharacterInfo *chi, CharacterExtras *chex) {
+	// check most likely case first
+	if ((chex->zoom == 100) || ((chi->flags & CHF_SCALEMOVESPEED) == 0))
+		return 1;
+
+	// the % checks don't work when the counter is negative, so once
+	// it wraps round, correct it
+	while (chi->walkwaitcounter < 0) {
+		chi->walkwaitcounter += 12000;
+	}
+
+	// scaling 170-200%, move 175% speed
+	if (chex->zoom >= 170) {
+		if ((chi->walkwaitcounter % 4) >= 1)
+			return 2;
+		else
+			return 1;
+	}
+	// scaling 140-170%, move 150% speed
+	else if (chex->zoom >= 140) {
+		if ((chi->walkwaitcounter % 2) == 1)
+			return 2;
+		else
+			return 1;
+	}
+	// scaling 115-140%, move 125% speed
+	else if (chex->zoom >= 115) {
+		if ((chi->walkwaitcounter % 4) >= 3)
+			return 2;
+		else
+			return 1;
+	}
+	// scaling 80-120%, normal speed
+	else if (chex->zoom >= 80)
+		return 1;
+	// scaling 60-80%, move 75% speed
+	if (chex->zoom >= 60) {
+		if ((chi->walkwaitcounter % 4) >= 1)
+			return -1;
+		else if (chex->xwas != INVALID_X) {
+			// move the second half of the movement to make it smoother
+			chi->x = chex->xwas;
+			chi->y = chex->ywas;
+			chex->xwas = INVALID_X;
+		}
+	}
+	// scaling 30-60%, move 50% speed
+	else if (chex->zoom >= 30) {
+		if ((chi->walkwaitcounter % 2) == 1)
+			return -1;
+		else if (chex->xwas != INVALID_X) {
+			// move the second half of the movement to make it smoother
+			chi->x = chex->xwas;
+			chi->y = chex->ywas;
+			chex->xwas = INVALID_X;
+		}
+	}
+	// scaling 0-30%, move 25% speed
+	else {
+		if ((chi->walkwaitcounter % 4) >= 3)
+			return -1;
+		if (((chi->walkwaitcounter % 4) == 1) && (chex->xwas != INVALID_X)) {
+			// move the second half of the movement to make it smoother
+			chi->x = chex->xwas;
+			chi->y = chex->ywas;
+			chex->xwas = INVALID_X;
+		}
+
+	}
+
+	return 0;
 }
 
 void setup_player_character(int charid) {
-    game.playercharacter = charid;
-    playerchar = &game.chars[charid];
-    _sc_PlayerCharPtr = ccGetObjectHandleFromAddress((char*)playerchar);
-    if (loaded_game_file_version < kGameVersion_270) {
-        ccAddExternalDynamicObject("player", playerchar, &ccDynamicCharacter);
-    }
-}
-
-void animate_character(CharacterInfo *chap, int loopn,int sppd,int rept, int noidleoverride, int direction, int sframe) {
-
-    if ((chap->view < 0) || (chap->view > game.numviews)) {
-        quitprintf("!AnimateCharacter: you need to set the view number first\n"
-            "(trying to animate '%s' using loop %d. View is currently %d).",chap->name,loopn,chap->view+1);
-    }
-    debug_script_log("%s: Start anim view %d loop %d, spd %d, repeat %d, frame: %d", chap->scrname, chap->view+1, loopn, sppd, rept, sframe);
-    if ((chap->idleleft < 0) && (noidleoverride == 0)) {
-        // if idle view in progress for the character (and this is not the
-        // "start idle animation" animate_character call), stop the idle anim
-        Character_UnlockView(chap);
-        chap->idleleft=chap->idletime;
-    }
-    if ((loopn < 0) || (loopn >= views[chap->view].numLoops))
-        quit("!AnimateCharacter: invalid loop number specified");
-    if ((sframe < 0) || (sframe >= views[chap->view].loops[loopn].numFrames))
-        quit("!AnimateCharacter: invalid starting frame number specified");
-    Character_StopMoving(chap);
-    chap->animating=1;
-    if (rept) chap->animating |= CHANIM_REPEAT;
-    if (direction) chap->animating |= CHANIM_BACKWARDS;
-
-    chap->animating|=((sppd << 8) & 0xff00);
-    chap->loop=loopn;
-    // reverse animation starts at the *previous frame*
-    if (direction) {
-        sframe--;
-        if (sframe < 0)
-            sframe = views[chap->view].loops[loopn].numFrames - (-sframe);
-    }
-    chap->frame = sframe;
-
-    chap->wait = sppd + views[chap->view].loops[loopn].frames[chap->frame].speed;
-    CheckViewFrameForCharacter(chap);
+	game.playercharacter = charid;
+	playerchar = &game.chars[charid];
+	_sc_PlayerCharPtr = ccGetObjectHandleFromAddress((char *)playerchar);
+	if (loaded_game_file_version < kGameVersion_270) {
+		ccAddExternalDynamicObject("player", playerchar, &ccDynamicCharacter);
+	}
+}
+
+void animate_character(CharacterInfo *chap, int loopn, int sppd, int rept, int noidleoverride, int direction, int sframe) {
+
+	if ((chap->view < 0) || (chap->view > game.numviews)) {
+		quitprintf("!AnimateCharacter: you need to set the view number first\n"
+		           "(trying to animate '%s' using loop %d. View is currently %d).", chap->name, loopn, chap->view + 1);
+	}
+	debug_script_log("%s: Start anim view %d loop %d, spd %d, repeat %d, frame: %d", chap->scrname, chap->view + 1, loopn, sppd, rept, sframe);
+	if ((chap->idleleft < 0) && (noidleoverride == 0)) {
+		// if idle view in progress for the character (and this is not the
+		// "start idle animation" animate_character call), stop the idle anim
+		Character_UnlockView(chap);
+		chap->idleleft = chap->idletime;
+	}
+	if ((loopn < 0) || (loopn >= views[chap->view].numLoops))
+		quit("!AnimateCharacter: invalid loop number specified");
+	if ((sframe < 0) || (sframe >= views[chap->view].loops[loopn].numFrames))
+		quit("!AnimateCharacter: invalid starting frame number specified");
+	Character_StopMoving(chap);
+	chap->animating = 1;
+	if (rept) chap->animating |= CHANIM_REPEAT;
+	if (direction) chap->animating |= CHANIM_BACKWARDS;
+
+	chap->animating |= ((sppd << 8) & 0xff00);
+	chap->loop = loopn;
+	// reverse animation starts at the *previous frame*
+	if (direction) {
+		sframe--;
+		if (sframe < 0)
+			sframe = views[chap->view].loops[loopn].numFrames - (-sframe);
+	}
+	chap->frame = sframe;
+
+	chap->wait = sppd + views[chap->view].loops[loopn].frames[chap->frame].speed;
+	CheckViewFrameForCharacter(chap);
 }
 
 void CheckViewFrameForCharacter(CharacterInfo *chi) {
 
-    int soundVolume = SCR_NO_VALUE;
+	int soundVolume = SCR_NO_VALUE;
 
-    if (chi->flags & CHF_SCALEVOLUME) {
-        // adjust the sound volume using the character's zoom level
-        int zoom_level = charextra[chi->index_id].zoom;
-        if (zoom_level == 0)
-            zoom_level = 100;
+	if (chi->flags & CHF_SCALEVOLUME) {
+		// adjust the sound volume using the character's zoom level
+		int zoom_level = charextra[chi->index_id].zoom;
+		if (zoom_level == 0)
+			zoom_level = 100;
 
-        soundVolume = zoom_level;
+		soundVolume = zoom_level;
 
-        if (soundVolume < 0)
-            soundVolume = 0;
-        if (soundVolume > 100)
-            soundVolume = 100;
-    }
+		if (soundVolume < 0)
+			soundVolume = 0;
+		if (soundVolume > 100)
+			soundVolume = 100;
+	}
 
-    CheckViewFrame(chi->view, chi->loop, chi->frame, soundVolume);
+	CheckViewFrame(chi->view, chi->loop, chi->frame, soundVolume);
 }
 
-Bitmap *GetCharacterImage(int charid, int *isFlipped) 
-{
-    if (!gfxDriver->HasAcceleratedTransform())
-    {
-        if (actsps[charid + MAX_ROOM_OBJECTS] != nullptr) 
-        {
-            // the actsps image is pre-flipped, so no longer register the image as such
-            if (isFlipped)
-                *isFlipped = 0;
-            return actsps[charid + MAX_ROOM_OBJECTS];
-        }
-    }
-    CharacterInfo*chin=&game.chars[charid];
-    int sppic = views[chin->view].loops[chin->loop].frames[chin->frame].pic;
-    return spriteset[sppic];
+Bitmap *GetCharacterImage(int charid, int *isFlipped) {
+	if (!gfxDriver->HasAcceleratedTransform()) {
+		if (actsps[charid + MAX_ROOM_OBJECTS] != nullptr) {
+			// the actsps image is pre-flipped, so no longer register the image as such
+			if (isFlipped)
+				*isFlipped = 0;
+			return actsps[charid + MAX_ROOM_OBJECTS];
+		}
+	}
+	CharacterInfo *chin = &game.chars[charid];
+	int sppic = views[chin->view].loops[chin->loop].frames[chin->frame].pic;
+	return spriteset[sppic];
 }
 
 CharacterInfo *GetCharacterAtScreen(int xx, int yy) {
-    int hsnum = GetCharIDAtScreen(xx, yy);
-    if (hsnum < 0)
-        return nullptr;
-    return &game.chars[hsnum];
+	int hsnum = GetCharIDAtScreen(xx, yy);
+	if (hsnum < 0)
+		return nullptr;
+	return &game.chars[hsnum];
 }
 
-CharacterInfo *GetCharacterAtRoom(int x, int y)
-{
-    int hsnum = is_pos_on_character(x, y);
-    if (hsnum < 0)
-        return nullptr;
-    return &game.chars[hsnum];
+CharacterInfo *GetCharacterAtRoom(int x, int y) {
+	int hsnum = is_pos_on_character(x, y);
+	if (hsnum < 0)
+		return nullptr;
+	return &game.chars[hsnum];
 }
 
 extern int char_lowest_yp, obj_lowest_yp;
 
-int is_pos_on_character(int xx,int yy) {
-    int cc,sppic,lowestyp=0,lowestwas=-1;
-    for (cc=0;cc<game.numcharacters;cc++) {
-        if (game.chars[cc].room!=displayed_room) continue;
-        if (game.chars[cc].on==0) continue;
-        if (game.chars[cc].flags & CHF_NOINTERACT) continue;
-        if (game.chars[cc].view < 0) continue;
-        CharacterInfo*chin=&game.chars[cc];
-
-        if ((chin->view < 0) || 
-            (chin->loop >= views[chin->view].numLoops) ||
-            (chin->frame >= views[chin->view].loops[chin->loop].numFrames))
-        {
-            continue;
-        }
-
-        sppic=views[chin->view].loops[chin->loop].frames[chin->frame].pic;
-        int usewid = charextra[cc].width;
-        int usehit = charextra[cc].height;
-        if (usewid==0) usewid=game.SpriteInfos[sppic].Width;
-        if (usehit==0) usehit= game.SpriteInfos[sppic].Height;
-        int xxx = chin->x - game_to_data_coord(usewid) / 2;
-        int yyy = chin->get_effective_y() - game_to_data_coord(usehit);
-
-        int mirrored = views[chin->view].loops[chin->loop].frames[chin->frame].flags & VFLG_FLIPSPRITE;
-        Bitmap *theImage = GetCharacterImage(cc, &mirrored);
-
-        if (is_pos_in_sprite(xx,yy,xxx,yyy, theImage,
-            game_to_data_coord(usewid),
-            game_to_data_coord(usehit), mirrored) == FALSE)
-            continue;
-
-        int use_base = chin->get_baseline();
-        if (use_base < lowestyp) continue;
-        lowestyp=use_base;
-        lowestwas=cc;
-    }
-    char_lowest_yp = lowestyp;
-    return lowestwas;
+int is_pos_on_character(int xx, int yy) {
+	int cc, sppic, lowestyp = 0, lowestwas = -1;
+	for (cc = 0; cc < game.numcharacters; cc++) {
+		if (game.chars[cc].room != displayed_room) continue;
+		if (game.chars[cc].on == 0) continue;
+		if (game.chars[cc].flags & CHF_NOINTERACT) continue;
+		if (game.chars[cc].view < 0) continue;
+		CharacterInfo *chin = &game.chars[cc];
+
+		if ((chin->view < 0) ||
+		        (chin->loop >= views[chin->view].numLoops) ||
+		        (chin->frame >= views[chin->view].loops[chin->loop].numFrames)) {
+			continue;
+		}
+
+		sppic = views[chin->view].loops[chin->loop].frames[chin->frame].pic;
+		int usewid = charextra[cc].width;
+		int usehit = charextra[cc].height;
+		if (usewid == 0) usewid = game.SpriteInfos[sppic].Width;
+		if (usehit == 0) usehit = game.SpriteInfos[sppic].Height;
+		int xxx = chin->x - game_to_data_coord(usewid) / 2;
+		int yyy = chin->get_effective_y() - game_to_data_coord(usehit);
+
+		int mirrored = views[chin->view].loops[chin->loop].frames[chin->frame].flags & VFLG_FLIPSPRITE;
+		Bitmap *theImage = GetCharacterImage(cc, &mirrored);
+
+		if (is_pos_in_sprite(xx, yy, xxx, yyy, theImage,
+		                     game_to_data_coord(usewid),
+		                     game_to_data_coord(usehit), mirrored) == FALSE)
+			continue;
+
+		int use_base = chin->get_baseline();
+		if (use_base < lowestyp) continue;
+		lowestyp = use_base;
+		lowestwas = cc;
+	}
+	char_lowest_yp = lowestyp;
+	return lowestwas;
 }
 
 void get_char_blocking_rect(int charid, int *x1, int *y1, int *width, int *y2) {
-    CharacterInfo *char1 = &game.chars[charid];
-    int cwidth, fromx;
-
-    if (char1->blocking_width < 1)
-        cwidth = game_to_data_coord(GetCharacterWidth(charid)) - 4;
-    else
-        cwidth = char1->blocking_width;
-
-    fromx = char1->x - cwidth/2;
-    if (fromx < 0) {
-        cwidth += fromx;
-        fromx = 0;
-    }
-    if (fromx + cwidth >= mask_to_room_coord(walkable_areas_temp->GetWidth()))
-        cwidth = mask_to_room_coord(walkable_areas_temp->GetWidth()) - fromx;
-
-    if (x1)
-        *x1 = fromx;
-    if (width)
-        *width = cwidth;
-    if (y1)
-        *y1 = char1->get_blocking_top();
-    if (y2)
-        *y2 = char1->get_blocking_bottom();
+	CharacterInfo *char1 = &game.chars[charid];
+	int cwidth, fromx;
+
+	if (char1->blocking_width < 1)
+		cwidth = game_to_data_coord(GetCharacterWidth(charid)) - 4;
+	else
+		cwidth = char1->blocking_width;
+
+	fromx = char1->x - cwidth / 2;
+	if (fromx < 0) {
+		cwidth += fromx;
+		fromx = 0;
+	}
+	if (fromx + cwidth >= mask_to_room_coord(walkable_areas_temp->GetWidth()))
+		cwidth = mask_to_room_coord(walkable_areas_temp->GetWidth()) - fromx;
+
+	if (x1)
+		*x1 = fromx;
+	if (width)
+		*width = cwidth;
+	if (y1)
+		*y1 = char1->get_blocking_top();
+	if (y2)
+		*y2 = char1->get_blocking_bottom();
 }
 
 // Check whether the source char has walked onto character ww
-int is_char_on_another (int sourceChar, int ww, int*fromxptr, int*cwidptr) {
+int is_char_on_another(int sourceChar, int ww, int *fromxptr, int *cwidptr) {
 
-    int fromx, cwidth;
-    int y1, y2;
-    get_char_blocking_rect(ww, &fromx, &y1, &cwidth, &y2);
+	int fromx, cwidth;
+	int y1, y2;
+	get_char_blocking_rect(ww, &fromx, &y1, &cwidth, &y2);
 
-    if (fromxptr)
-        fromxptr[0] = fromx;
-    if (cwidptr)
-        cwidptr[0] = cwidth;
+	if (fromxptr)
+		fromxptr[0] = fromx;
+	if (cwidptr)
+		cwidptr[0] = cwidth;
 
-    // if the character trying to move is already on top of
-    // this char somehow, allow them through
-    if ((sourceChar >= 0) &&
-        // x/width are left and width co-ords, so they need >= and <
-        (game.chars[sourceChar].x >= fromx) &&
-        (game.chars[sourceChar].x < fromx + cwidth) &&
-        // y1/y2 are the top/bottom co-ords, so they need >= / <=
-        (game.chars[sourceChar].y >= y1 ) &&
-        (game.chars[sourceChar].y <= y2 ))
-        return 1;
+	// if the character trying to move is already on top of
+	// this char somehow, allow them through
+	if ((sourceChar >= 0) &&
+	        // x/width are left and width co-ords, so they need >= and <
+	        (game.chars[sourceChar].x >= fromx) &&
+	        (game.chars[sourceChar].x < fromx + cwidth) &&
+	        // y1/y2 are the top/bottom co-ords, so they need >= / <=
+	        (game.chars[sourceChar].y >= y1) &&
+	        (game.chars[sourceChar].y <= y2))
+		return 1;
 
-    return 0;
+	return 0;
 }
 
 int my_getpixel(Bitmap *blk, int x, int y) {
-    if ((x < 0) || (y < 0) || (x >= blk->GetWidth()) || (y >= blk->GetHeight()))
-        return -1;
+	if ((x < 0) || (y < 0) || (x >= blk->GetWidth()) || (y >= blk->GetHeight()))
+		return -1;
 
-    // strip the alpha channel
+	// strip the alpha channel
 	// TODO: is there a way to do this vtable thing with Bitmap?
-	BITMAP *al_bmp = (BITMAP*)blk->GetAllegroBitmap();
-    return al_bmp->vtable->getpixel(al_bmp, x, y) & 0x00ffffff;
+	BITMAP *al_bmp = (BITMAP *)blk->GetAllegroBitmap();
+	return al_bmp->vtable->getpixel(al_bmp, x, y) & 0x00ffffff;
 }
 
-int check_click_on_character(int xx,int yy,int mood) {
-    int lowestwas=is_pos_on_character(xx,yy);
-    if (lowestwas>=0) {
-        RunCharacterInteraction (lowestwas, mood);
-        return 1;
-    }
-    return 0;
+int check_click_on_character(int xx, int yy, int mood) {
+	int lowestwas = is_pos_on_character(xx, yy);
+	if (lowestwas >= 0) {
+		RunCharacterInteraction(lowestwas, mood);
+		return 1;
+	}
+	return 0;
 }
 
 void _DisplaySpeechCore(int chid, const char *displbuf) {
-    if (displbuf[0] == 0) {
-        // no text, just update the current character who's speaking
-        // this allows the portrait side to be switched with an empty
-        // speech line
-        play.swap_portrait_lastchar = chid;
-        return;
-    }
+	if (displbuf[0] == 0) {
+		// no text, just update the current character who's speaking
+		// this allows the portrait side to be switched with an empty
+		// speech line
+		play.swap_portrait_lastchar = chid;
+		return;
+	}
 
-    // adjust timing of text (so that DisplaySpeech("%s", str) pauses
-    // for the length of the string not 2 frames)
-    int len = (int)strlen(displbuf);
-    if (len > source_text_length + 3)
-        source_text_length = len;
+	// adjust timing of text (so that DisplaySpeech("%s", str) pauses
+	// for the length of the string not 2 frames)
+	int len = (int)strlen(displbuf);
+	if (len > source_text_length + 3)
+		source_text_length = len;
 
-    DisplaySpeech(displbuf, chid);
+	DisplaySpeech(displbuf, chid);
 }
 
 void _DisplayThoughtCore(int chid, const char *displbuf) {
-    // adjust timing of text (so that DisplayThought("%s", str) pauses
-    // for the length of the string not 2 frames)
-    int len = (int)strlen(displbuf);
-    if (len > source_text_length + 3)
-        source_text_length = len;
-
-    int xpp = -1, ypp = -1, width = -1;
-
-    if ((game.options[OPT_SPEECHTYPE] == 0) || (game.chars[chid].thinkview <= 0)) {
-        // lucasarts-style, so we want a speech bubble actually above
-        // their head (or if they have no think anim in Sierra-style)
-        width = data_to_game_coord(play.speech_bubble_width);
-        xpp = play.RoomToScreenX(data_to_game_coord(game.chars[chid].x)) - width / 2;
-        if (xpp < 0)
-            xpp = 0;
-        // -1 will automatically put it above the char's head
-        ypp = -1;
-    }
-
-    _displayspeech ((char*)displbuf, chid, xpp, ypp, width, 1);
-}
-
-void _displayspeech(const char*texx, int aschar, int xx, int yy, int widd, int isThought) {
-    if (!is_valid_character(aschar))
-        quit("!DisplaySpeech: invalid character");
-
-    CharacterInfo *speakingChar = &game.chars[aschar];
-    if ((speakingChar->view < 0) || (speakingChar->view >= game.numviews))
-        quit("!DisplaySpeech: character has invalid view");
-
-    if (is_text_overlay > 0)
-    {
-        debug_script_warn("DisplaySpeech: speech was already displayed (nested DisplaySpeech, perhaps room script and global script conflict?)");
-        return;
-    }
-
-    EndSkippingUntilCharStops();
-
-    said_speech_line = 1;
-
-    if (play.bgspeech_stay_on_display == 0) {
-        // remove any background speech
-        for (size_t i = 0; i < screenover.size();) {
-            if (screenover[i].timeout > 0)
-                remove_screen_overlay(screenover[i].type);
-            else
-                i++;
-        }
-    }
-    said_text = 1;
-
-    // the strings are pre-translated
-    //texx = get_translation(texx);
-    our_eip=150;
-
-    int isPause = 1;
-    // if the message is all .'s, don't display anything
-    for (int aa = 0; texx[aa] != 0; aa++) {
-        if (texx[aa] != '.') {
-            isPause = 0;
-            break;
-        }
-    }
-
-    play.messagetime = GetTextDisplayTime(texx);
-    play.speech_in_post_state = false;
-
-    if (isPause) {
-        postpone_scheduled_music_update_by(std::chrono::milliseconds(play.messagetime * 1000 / frames_per_second));
-        GameLoopUntilValueIsNegative(&play.messagetime);
-        return;
-    }
-
-    int textcol = speakingChar->talkcolor;
-
-    // if it's 0, it won't be recognised as speech
-    if (textcol == 0)
-        textcol = 16;
-
-    Rect ui_view = play.GetUIViewport();
-    int allowShrink = 0;
-    int bwidth = widd;
-    if (bwidth < 0)
-        bwidth = ui_view.GetWidth()/2 + ui_view.GetWidth()/4;
-
-    our_eip=151;
-
-    int useview = speakingChar->talkview;
-    if (isThought) {
-        useview = speakingChar->thinkview;
-        // view 0 is not valid for think views
-        if (useview == 0)
-            useview = -1;
-        // speech bubble can shrink to fit
-        allowShrink = 1;
-        if (speakingChar->room != displayed_room) {
-            // not in room, centre it
-            xx = -1;
-            yy = -1;
-        }
-    }
-
-    if (useview >= game.numviews)
-        quitprintf("!Character.Say: attempted to use view %d for animation, but it does not exist", useview + 1);
-
-    int tdxp = xx,tdyp = yy;
-    int oldview=-1, oldloop = -1;
-    int ovr_type = 0;
-
-    text_lips_offset = 0;
-    text_lips_text = texx;
-
-    Bitmap *closeupface=nullptr;
-    // TODO: we always call _display_at later which may also start voice-over;
-    // find out if this may be refactored and voice started only in one place.
-    try_auto_play_speech(texx, texx, aschar, true);
-
-    if (game.options[OPT_SPEECHTYPE] == 3)
-        remove_screen_overlay(OVER_COMPLETE);
-    our_eip=1500;
-
-    if (game.options[OPT_SPEECHTYPE] == 0)
-        allowShrink = 1;
-
-    if (speakingChar->idleleft < 0)  {
-        // if idle anim in progress for the character, stop it
-        ReleaseCharacterView(aschar);
-        //    speakingChar->idleleft = speakingChar->idletime;
-    }
-
-    bool overlayPositionFixed = false;
-    int charFrameWas = 0;
-    int viewWasLocked = 0;
-    if (speakingChar->flags & CHF_FIXVIEW)
-        viewWasLocked = 1;
-
-    /*if ((speakingChar->room == displayed_room) ||
-    ((useview >= 0) && (game.options[OPT_SPEECHTYPE] > 0)) ) {*/
-
-    if (speakingChar->room == displayed_room) {
-        // If the character is in this room, go for it - otherwise
-        // run the "else" clause which  does text in the middle of
-        // the screen.
-        our_eip=1501;
-
-        if (speakingChar->walking)
-            StopMoving(aschar);
-
-        // save the frame we need to go back to
-        // if they were moving, this will be 0 (because we just called
-        // StopMoving); otherwise, it might be a specific animation 
-        // frame which we should return to
-        if (viewWasLocked)
-            charFrameWas = speakingChar->frame;
-
-        // if the current loop doesn't exist in talking view, use loop 0
-        if (speakingChar->loop >= views[speakingChar->view].numLoops)
-            speakingChar->loop = 0;
-
-        if ((speakingChar->view < 0) || 
-            (speakingChar->loop >= views[speakingChar->view].numLoops) ||
-            (views[speakingChar->view].loops[speakingChar->loop].numFrames < 1))
-        {
-            quitprintf("Unable to display speech because the character %s has an invalid view frame (View %d, loop %d, frame %d)", speakingChar->scrname, speakingChar->view + 1, speakingChar->loop, speakingChar->frame);
-        }
-
-        our_eip=1504;
-
-        // Calculate speech position based on character's position on screen
-        auto view = FindNearestViewport(aschar);
-        if (tdxp < 0)
-            tdxp = view->RoomToScreen(data_to_game_coord(speakingChar->x), 0).first.X;
-        if (tdxp < 2)
-            tdxp = 2;
-        tdxp = -tdxp;  // tell it to centre it ([ikm] not sure what's going on here... wrong comment?)
-
-        if (tdyp < 0)
-        {
-            int sppic = views[speakingChar->view].loops[speakingChar->loop].frames[0].pic;
-            int height = (charextra[aschar].height < 1) ? game.SpriteInfos[sppic].Height : height = charextra[aschar].height;
-            tdyp = view->RoomToScreen(0, data_to_game_coord(game.chars[aschar].get_effective_y()) - height).first.Y
-                    - get_fixed_pixel_size(5);
-            if (isThought) // if it's a thought, lift it a bit further up
-                tdyp -= get_fixed_pixel_size(10);
-        }
-        if (tdyp < 5)
-            tdyp = 5;
-
-        our_eip=152;
-
-        if ((useview >= 0) && (game.options[OPT_SPEECHTYPE] > 0)) {
-            // Sierra-style close-up portrait
-
-            if (play.swap_portrait_lastchar != aschar) {
-                // if the portraits are set to Alternate, OR they are
-                // set to Left but swap_portrait has been set to 1 (the old
-                // method for enabling it), then swap them round
-                if ((game.options[OPT_PORTRAITSIDE] == PORTRAIT_ALTERNATE) ||
-                    ((game.options[OPT_PORTRAITSIDE] == 0) &&
-                    (play.swap_portrait_side > 0))) {
-
-                        if (play.swap_portrait_side == 2)
-                            play.swap_portrait_side = 1;
-                        else
-                            play.swap_portrait_side = 2;
-                }
-
-                if (game.options[OPT_PORTRAITSIDE] == PORTRAIT_XPOSITION) {
-                    // Portrait side based on character X-positions
-                    if (play.swap_portrait_lastchar < 0) {
-                        // No previous character been spoken to
-                        // therefore, assume it's the player
-                        if(game.playercharacter != aschar && game.chars[game.playercharacter].room == speakingChar->room && game.chars[game.playercharacter].on == 1)
-                            play.swap_portrait_lastchar = game.playercharacter;
-                        else
-                            // The player's not here. Find another character in this room
-                            // that it could be
-                            for (int ce = 0; ce < game.numcharacters; ce++) {
-                                if ((game.chars[ce].room == speakingChar->room) &&
-                                    (game.chars[ce].on == 1) &&
-                                    (ce != aschar)) {
-                                        play.swap_portrait_lastchar = ce;
-                                        break;
-                                }
-                            }
-                    }
-
-                    if (play.swap_portrait_lastchar >= 0) {
-                        // if this character is right of the one before, put the
-                        // portrait on the right
-                        if (speakingChar->x > game.chars[play.swap_portrait_lastchar].x)
-                            play.swap_portrait_side = -1;
-                        else
-                            play.swap_portrait_side = 0;
-                    }
-                }
-                play.swap_portrait_lastlastchar = play.swap_portrait_lastchar;
-                play.swap_portrait_lastchar = aschar;
-            }
-            else
-                // If the portrait side is based on the character's X position and the same character is
-                // speaking, compare against the previous *previous* character to see where the speech should be
-                if (game.options[OPT_PORTRAITSIDE] == PORTRAIT_XPOSITION && play.swap_portrait_lastlastchar >= 0) {
-                    if (speakingChar->x > game.chars[play.swap_portrait_lastlastchar].x)
-                        play.swap_portrait_side = -1;
-                    else
-                        play.swap_portrait_side = 0;
-                }
-
-            // Determine whether to display the portrait on the left or right
-            int portrait_on_right = 0;
-
-            if (game.options[OPT_SPEECHTYPE] == 3) 
-            { }  // always on left with QFG-style speech
-            else if ((play.swap_portrait_side == 1) ||
-                (play.swap_portrait_side == -1) ||
-                (game.options[OPT_PORTRAITSIDE] == PORTRAIT_RIGHT))
-                portrait_on_right = 1;
-
-
-            int bigx=0,bigy=0,kk;
-            ViewStruct*viptr=&views[useview];
-            for (kk = 0; kk < viptr->loops[0].numFrames; kk++) 
-            {
-                int tw = game.SpriteInfos[viptr->loops[0].frames[kk].pic].Width;
-                if (tw > bigx) bigx=tw;
-                tw = game.SpriteInfos[viptr->loops[0].frames[kk].pic].Height;
-                if (tw > bigy) bigy=tw;
-            }
-
-            // if they accidentally used a large full-screen image as the sierra-style
-            // talk view, correct it
-            if ((game.options[OPT_SPEECHTYPE] != 3) && (bigx > ui_view.GetWidth() - get_fixed_pixel_size(50)))
-                bigx = ui_view.GetWidth() - get_fixed_pixel_size(50);
-
-            if (widd > 0)
-                bwidth = widd - bigx;
-
-            our_eip=153;
-            int ovr_yp = get_fixed_pixel_size(20);
-            int view_frame_x = 0;
-            int view_frame_y = 0;
-            facetalk_qfg4_override_placement_x = false;
-            facetalk_qfg4_override_placement_y = false;
-
-            if (game.options[OPT_SPEECHTYPE] == 3) {
-                // QFG4-style whole screen picture
-                closeupface = BitmapHelper::CreateBitmap(ui_view.GetWidth(), ui_view.GetHeight(), spriteset[viptr->loops[0].frames[0].pic]->GetColorDepth());
-                closeupface->Clear(0);
-                if (xx < 0 && play.speech_portrait_placement)
-                {
-                    facetalk_qfg4_override_placement_x = true;
-                    view_frame_x = play.speech_portrait_x;
-                }
-                if (yy < 0 && play.speech_portrait_placement)
-                {
-                    facetalk_qfg4_override_placement_y = true;
-                    view_frame_y = play.speech_portrait_y;
-                }
-                else
-                {
-                    view_frame_y = ui_view.GetHeight()/2 - game.SpriteInfos[viptr->loops[0].frames[0].pic].Height/2;
-                }
-                bigx = ui_view.GetWidth()/2 - get_fixed_pixel_size(20);
-                ovr_type = OVER_COMPLETE;
-                ovr_yp = 0;
-                tdyp = -1;  // center vertically
-            }
-            else {
-                // KQ6-style close-up face picture
-                if (yy < 0 && play.speech_portrait_placement)
-                {
-                    ovr_yp = play.speech_portrait_y;
-                }
-                else if (yy < 0)
-                    ovr_yp = adjust_y_for_guis (ovr_yp);
-                else
-                    ovr_yp = yy;
-
-                closeupface = BitmapHelper::CreateTransparentBitmap(bigx+1,bigy+1,spriteset[viptr->loops[0].frames[0].pic]->GetColorDepth());
-                ovr_type = OVER_PICTURE;
-
-                if (yy < 0)
-                    tdyp = ovr_yp + get_textwindow_top_border_height(play.speech_textwindow_gui);
-            }
-            const ViewFrame *vf = &viptr->loops[0].frames[0];
-            const bool closeupface_has_alpha = (game.SpriteInfos[vf->pic].Flags & SPF_ALPHACHANNEL) != 0;
-            DrawViewFrame(closeupface, vf, view_frame_x, view_frame_y);
-
-            int overlay_x = get_fixed_pixel_size(10);
-            if (xx < 0) {
-                tdxp = bigx + get_textwindow_border_width(play.speech_textwindow_gui) / 2;
-                if (play.speech_portrait_placement)
-                {
-                    overlay_x = play.speech_portrait_x;
-                    tdxp += overlay_x + get_fixed_pixel_size(6);
-                }
-                else
-                {
-                    tdxp += get_fixed_pixel_size(16);
-                }
-
-                int maxWidth = (ui_view.GetWidth() - tdxp) - get_fixed_pixel_size(5) -
-                    get_textwindow_border_width (play.speech_textwindow_gui) / 2;
-
-                if (bwidth > maxWidth)
-                    bwidth = maxWidth;
-            }
-            else {
-                tdxp = xx + bigx + get_fixed_pixel_size(8);
-                overlay_x = xx;
-            }
-
-            // allow the text box to be shrunk to fit the text
-            allowShrink = 1;
-
-            // if the portrait's on the right, swap it round
-            if (portrait_on_right) {
-                if ((xx < 0) || (widd < 0)) {
-                    tdxp = get_fixed_pixel_size(9);
-                    if (play.speech_portrait_placement)
-                    {
-                        overlay_x = (ui_view.GetWidth() - bigx) - play.speech_portrait_x;
-                        int maxWidth = overlay_x - tdxp - get_fixed_pixel_size(9) - 
-                            get_textwindow_border_width (play.speech_textwindow_gui) / 2;
-                        if (bwidth > maxWidth)
-                            bwidth = maxWidth;
-                    }
-                    else
-                    {
-                        overlay_x = (ui_view.GetWidth() - bigx) - get_fixed_pixel_size(5);
-                    }
-                }
-                else {
-                    overlay_x = (xx + widd - bigx) - get_fixed_pixel_size(5);
-                    tdxp = xx;
-                }
-                tdxp += get_textwindow_border_width(play.speech_textwindow_gui) / 2;
-                allowShrink = 2;
-            }
-            if (game.options[OPT_SPEECHTYPE] == 3)
-                overlay_x = 0;
-            face_talking=add_screen_overlay(overlay_x,ovr_yp,ovr_type,closeupface, closeupface_has_alpha);
-            facetalkframe = 0;
-            facetalkwait = viptr->loops[0].frames[0].speed + GetCharacterSpeechAnimationDelay(speakingChar);
-            facetalkloop = 0;
-            facetalkview = useview;
-            facetalkrepeat = (isThought) ? 0 : 1;
-            facetalkBlinkLoop = 0;
-            facetalkAllowBlink = 1;
-            if ((isThought) && (speakingChar->flags & CHF_NOBLINKANDTHINK))
-                facetalkAllowBlink = 0;
-            facetalkchar = &game.chars[aschar];
-            if (facetalkchar->blinktimer < 0)
-                facetalkchar->blinktimer = facetalkchar->blinkinterval;
-            textcol=-textcol;
-            overlayPositionFixed = true;
-        }
-        else if (useview >= 0) {
-            // Lucasarts-style speech
-            our_eip=154;
-
-            oldview = speakingChar->view;
-            oldloop = speakingChar->loop;
-            speakingChar->animating = 1 | (GetCharacterSpeechAnimationDelay(speakingChar) << 8);
-            // only repeat if speech, not thought
-            if (!isThought)
-                speakingChar->animating |= CHANIM_REPEAT;
-
-            speakingChar->view = useview;
-            speakingChar->frame=0;
-            speakingChar->flags|=CHF_FIXVIEW;
-
-            if (speakingChar->loop >= views[speakingChar->view].numLoops)
-            {
-                // current character loop is outside the normal talking directions
-                speakingChar->loop = 0;
-            }
-
-            facetalkBlinkLoop = speakingChar->loop;
-
-            if (speakingChar->on && // don't bother checking if character is not visible (also fixes 'Trilby's Notes' legacy game)
-                ((speakingChar->loop >= views[speakingChar->view].numLoops) ||
-                (views[speakingChar->view].loops[speakingChar->loop].numFrames < 1)))
-            {
-                quitprintf("!Unable to display speech because the character %s has an invalid speech view (View %d, loop %d, frame %d)", speakingChar->scrname, speakingChar->view + 1, speakingChar->loop, speakingChar->frame);
-            }
-
-            // set up the speed of the first frame
-            speakingChar->wait = GetCharacterSpeechAnimationDelay(speakingChar) + 
-                views[speakingChar->view].loops[speakingChar->loop].frames[0].speed;
-
-            if (widd < 0) {
-                bwidth = ui_view.GetWidth()/2 + ui_view.GetWidth()/6;
-                // If they are close to the screen edge, make the text narrower
-                int relx = play.RoomToScreenX(data_to_game_coord(speakingChar->x));
-                if ((relx < ui_view.GetWidth() / 4) || (relx > ui_view.GetWidth() - (ui_view.GetWidth() / 4)))
-                    bwidth -= ui_view.GetWidth() / 5;
-            }
-            /*   this causes the text to bob up and down as they talk
-            tdxp = OVR_AUTOPLACE;
-            tdyp = aschar;*/
-            if (!isThought)  // set up the lip sync if not thinking
-                char_speaking = aschar;
-
-        }
-    }
-    else
-        allowShrink = 1;
-
-    // it wants the centred position, so make it so
-    if ((xx >= 0) && (tdxp < 0))
-        tdxp -= widd / 2;
-
-    // if they used DisplaySpeechAt, then use the supplied width
-    if ((widd > 0) && (isThought == 0))
-        allowShrink = 0;
-
-    if (isThought)
-        char_thinking = aschar;
-
-    our_eip=155;
-    _display_at(tdxp, tdyp, bwidth, texx, DISPLAYTEXT_SPEECH, textcol, isThought, allowShrink, overlayPositionFixed);
-    our_eip=156;
-    if ((play.in_conversation > 0) && (game.options[OPT_SPEECHTYPE] == 3))
-        closeupface = nullptr;
-    if (closeupface!=nullptr)
-        remove_screen_overlay(ovr_type);
-    mark_screen_dirty();
-    face_talking = -1;
-    facetalkchar = nullptr;
-    our_eip=157;
-    if (oldview>=0) {
-        speakingChar->flags &= ~CHF_FIXVIEW;
-        if (viewWasLocked)
-            speakingChar->flags |= CHF_FIXVIEW;
-        speakingChar->view=oldview;
-
-        // Don't reset the loop in 2.x games
-        if (loaded_game_file_version > kGameVersion_272)
-            speakingChar->loop = oldloop;
-
-        speakingChar->animating=0;
-        speakingChar->frame = charFrameWas;
-        speakingChar->wait=0;
-        speakingChar->idleleft = speakingChar->idletime;
-        // restart the idle animation straight away
-        charextra[aschar].process_idle_this_time = 1;
-    }
-    char_speaking = -1;
-    char_thinking = -1;
-    if (play.IsBlockingVoiceSpeech())
-        stop_voice_speech();
+	// adjust timing of text (so that DisplayThought("%s", str) pauses
+	// for the length of the string not 2 frames)
+	int len = (int)strlen(displbuf);
+	if (len > source_text_length + 3)
+		source_text_length = len;
+
+	int xpp = -1, ypp = -1, width = -1;
+
+	if ((game.options[OPT_SPEECHTYPE] == 0) || (game.chars[chid].thinkview <= 0)) {
+		// lucasarts-style, so we want a speech bubble actually above
+		// their head (or if they have no think anim in Sierra-style)
+		width = data_to_game_coord(play.speech_bubble_width);
+		xpp = play.RoomToScreenX(data_to_game_coord(game.chars[chid].x)) - width / 2;
+		if (xpp < 0)
+			xpp = 0;
+		// -1 will automatically put it above the char's head
+		ypp = -1;
+	}
+
+	_displayspeech((char *)displbuf, chid, xpp, ypp, width, 1);
+}
+
+void _displayspeech(const char *texx, int aschar, int xx, int yy, int widd, int isThought) {
+	if (!is_valid_character(aschar))
+		quit("!DisplaySpeech: invalid character");
+
+	CharacterInfo *speakingChar = &game.chars[aschar];
+	if ((speakingChar->view < 0) || (speakingChar->view >= game.numviews))
+		quit("!DisplaySpeech: character has invalid view");
+
+	if (is_text_overlay > 0) {
+		debug_script_warn("DisplaySpeech: speech was already displayed (nested DisplaySpeech, perhaps room script and global script conflict?)");
+		return;
+	}
+
+	EndSkippingUntilCharStops();
+
+	said_speech_line = 1;
+
+	if (play.bgspeech_stay_on_display == 0) {
+		// remove any background speech
+		for (size_t i = 0; i < screenover.size();) {
+			if (screenover[i].timeout > 0)
+				remove_screen_overlay(screenover[i].type);
+			else
+				i++;
+		}
+	}
+	said_text = 1;
+
+	// the strings are pre-translated
+	//texx = get_translation(texx);
+	our_eip = 150;
+
+	int isPause = 1;
+	// if the message is all .'s, don't display anything
+	for (int aa = 0; texx[aa] != 0; aa++) {
+		if (texx[aa] != '.') {
+			isPause = 0;
+			break;
+		}
+	}
+
+	play.messagetime = GetTextDisplayTime(texx);
+	play.speech_in_post_state = false;
+
+	if (isPause) {
+		postpone_scheduled_music_update_by(std::chrono::milliseconds(play.messagetime * 1000 / frames_per_second));
+		GameLoopUntilValueIsNegative(&play.messagetime);
+		return;
+	}
+
+	int textcol = speakingChar->talkcolor;
+
+	// if it's 0, it won't be recognised as speech
+	if (textcol == 0)
+		textcol = 16;
+
+	Rect ui_view = play.GetUIViewport();
+	int allowShrink = 0;
+	int bwidth = widd;
+	if (bwidth < 0)
+		bwidth = ui_view.GetWidth() / 2 + ui_view.GetWidth() / 4;
+
+	our_eip = 151;
+
+	int useview = speakingChar->talkview;
+	if (isThought) {
+		useview = speakingChar->thinkview;
+		// view 0 is not valid for think views
+		if (useview == 0)
+			useview = -1;
+		// speech bubble can shrink to fit
+		allowShrink = 1;
+		if (speakingChar->room != displayed_room) {
+			// not in room, centre it
+			xx = -1;
+			yy = -1;
+		}
+	}
+
+	if (useview >= game.numviews)
+		quitprintf("!Character.Say: attempted to use view %d for animation, but it does not exist", useview + 1);
+
+	int tdxp = xx, tdyp = yy;
+	int oldview = -1, oldloop = -1;
+	int ovr_type = 0;
+
+	text_lips_offset = 0;
+	text_lips_text = texx;
+
+	Bitmap *closeupface = nullptr;
+	// TODO: we always call _display_at later which may also start voice-over;
+	// find out if this may be refactored and voice started only in one place.
+	try_auto_play_speech(texx, texx, aschar, true);
+
+	if (game.options[OPT_SPEECHTYPE] == 3)
+		remove_screen_overlay(OVER_COMPLETE);
+	our_eip = 1500;
+
+	if (game.options[OPT_SPEECHTYPE] == 0)
+		allowShrink = 1;
+
+	if (speakingChar->idleleft < 0)  {
+		// if idle anim in progress for the character, stop it
+		ReleaseCharacterView(aschar);
+		//    speakingChar->idleleft = speakingChar->idletime;
+	}
+
+	bool overlayPositionFixed = false;
+	int charFrameWas = 0;
+	int viewWasLocked = 0;
+	if (speakingChar->flags & CHF_FIXVIEW)
+		viewWasLocked = 1;
+
+	/*if ((speakingChar->room == displayed_room) ||
+	((useview >= 0) && (game.options[OPT_SPEECHTYPE] > 0)) ) {*/
+
+	if (speakingChar->room == displayed_room) {
+		// If the character is in this room, go for it - otherwise
+		// run the "else" clause which  does text in the middle of
+		// the screen.
+		our_eip = 1501;
+
+		if (speakingChar->walking)
+			StopMoving(aschar);
+
+		// save the frame we need to go back to
+		// if they were moving, this will be 0 (because we just called
+		// StopMoving); otherwise, it might be a specific animation
+		// frame which we should return to
+		if (viewWasLocked)
+			charFrameWas = speakingChar->frame;
+
+		// if the current loop doesn't exist in talking view, use loop 0
+		if (speakingChar->loop >= views[speakingChar->view].numLoops)
+			speakingChar->loop = 0;
+
+		if ((speakingChar->view < 0) ||
+		        (speakingChar->loop >= views[speakingChar->view].numLoops) ||
+		        (views[speakingChar->view].loops[speakingChar->loop].numFrames < 1)) {
+			quitprintf("Unable to display speech because the character %s has an invalid view frame (View %d, loop %d, frame %d)", speakingChar->scrname, speakingChar->view + 1, speakingChar->loop, speakingChar->frame);
+		}
+
+		our_eip = 1504;
+
+		// Calculate speech position based on character's position on screen
+		auto view = FindNearestViewport(aschar);
+		if (tdxp < 0)
+			tdxp = view->RoomToScreen(data_to_game_coord(speakingChar->x), 0).first.X;
+		if (tdxp < 2)
+			tdxp = 2;
+		tdxp = -tdxp;  // tell it to centre it ([ikm] not sure what's going on here... wrong comment?)
+
+		if (tdyp < 0) {
+			int sppic = views[speakingChar->view].loops[speakingChar->loop].frames[0].pic;
+			int height = (charextra[aschar].height < 1) ? game.SpriteInfos[sppic].Height : height = charextra[aschar].height;
+			tdyp = view->RoomToScreen(0, data_to_game_coord(game.chars[aschar].get_effective_y()) - height).first.Y
+			       - get_fixed_pixel_size(5);
+			if (isThought) // if it's a thought, lift it a bit further up
+				tdyp -= get_fixed_pixel_size(10);
+		}
+		if (tdyp < 5)
+			tdyp = 5;
+
+		our_eip = 152;
+
+		if ((useview >= 0) && (game.options[OPT_SPEECHTYPE] > 0)) {
+			// Sierra-style close-up portrait
+
+			if (play.swap_portrait_lastchar != aschar) {
+				// if the portraits are set to Alternate, OR they are
+				// set to Left but swap_portrait has been set to 1 (the old
+				// method for enabling it), then swap them round
+				if ((game.options[OPT_PORTRAITSIDE] == PORTRAIT_ALTERNATE) ||
+				        ((game.options[OPT_PORTRAITSIDE] == 0) &&
+				         (play.swap_portrait_side > 0))) {
+
+					if (play.swap_portrait_side == 2)
+						play.swap_portrait_side = 1;
+					else
+						play.swap_portrait_side = 2;
+				}
+
+				if (game.options[OPT_PORTRAITSIDE] == PORTRAIT_XPOSITION) {
+					// Portrait side based on character X-positions
+					if (play.swap_portrait_lastchar < 0) {
+						// No previous character been spoken to
+						// therefore, assume it's the player
+						if (game.playercharacter != aschar && game.chars[game.playercharacter].room == speakingChar->room && game.chars[game.playercharacter].on == 1)
+							play.swap_portrait_lastchar = game.playercharacter;
+						else
+							// The player's not here. Find another character in this room
+							// that it could be
+							for (int ce = 0; ce < game.numcharacters; ce++) {
+								if ((game.chars[ce].room == speakingChar->room) &&
+								        (game.chars[ce].on == 1) &&
+								        (ce != aschar)) {
+									play.swap_portrait_lastchar = ce;
+									break;
+								}
+							}
+					}
+
+					if (play.swap_portrait_lastchar >= 0) {
+						// if this character is right of the one before, put the
+						// portrait on the right
+						if (speakingChar->x > game.chars[play.swap_portrait_lastchar].x)
+							play.swap_portrait_side = -1;
+						else
+							play.swap_portrait_side = 0;
+					}
+				}
+				play.swap_portrait_lastlastchar = play.swap_portrait_lastchar;
+				play.swap_portrait_lastchar = aschar;
+			} else
+				// If the portrait side is based on the character's X position and the same character is
+				// speaking, compare against the previous *previous* character to see where the speech should be
+				if (game.options[OPT_PORTRAITSIDE] == PORTRAIT_XPOSITION && play.swap_portrait_lastlastchar >= 0) {
+					if (speakingChar->x > game.chars[play.swap_portrait_lastlastchar].x)
+						play.swap_portrait_side = -1;
+					else
+						play.swap_portrait_side = 0;
+				}
+
+			// Determine whether to display the portrait on the left or right
+			int portrait_on_right = 0;
+
+			if (game.options[OPT_SPEECHTYPE] == 3) {
+			}  // always on left with QFG-style speech
+			else if ((play.swap_portrait_side == 1) ||
+			         (play.swap_portrait_side == -1) ||
+			         (game.options[OPT_PORTRAITSIDE] == PORTRAIT_RIGHT))
+				portrait_on_right = 1;
+
+
+			int bigx = 0, bigy = 0, kk;
+			ViewStruct *viptr = &views[useview];
+			for (kk = 0; kk < viptr->loops[0].numFrames; kk++) {
+				int tw = game.SpriteInfos[viptr->loops[0].frames[kk].pic].Width;
+				if (tw > bigx) bigx = tw;
+				tw = game.SpriteInfos[viptr->loops[0].frames[kk].pic].Height;
+				if (tw > bigy) bigy = tw;
+			}
+
+			// if they accidentally used a large full-screen image as the sierra-style
+			// talk view, correct it
+			if ((game.options[OPT_SPEECHTYPE] != 3) && (bigx > ui_view.GetWidth() - get_fixed_pixel_size(50)))
+				bigx = ui_view.GetWidth() - get_fixed_pixel_size(50);
+
+			if (widd > 0)
+				bwidth = widd - bigx;
+
+			our_eip = 153;
+			int ovr_yp = get_fixed_pixel_size(20);
+			int view_frame_x = 0;
+			int view_frame_y = 0;
+			facetalk_qfg4_override_placement_x = false;
+			facetalk_qfg4_override_placement_y = false;
+
+			if (game.options[OPT_SPEECHTYPE] == 3) {
+				// QFG4-style whole screen picture
+				closeupface = BitmapHelper::CreateBitmap(ui_view.GetWidth(), ui_view.GetHeight(), spriteset[viptr->loops[0].frames[0].pic]->GetColorDepth());
+				closeupface->Clear(0);
+				if (xx < 0 && play.speech_portrait_placement) {
+					facetalk_qfg4_override_placement_x = true;
+					view_frame_x = play.speech_portrait_x;
+				}
+				if (yy < 0 && play.speech_portrait_placement) {
+					facetalk_qfg4_override_placement_y = true;
+					view_frame_y = play.speech_portrait_y;
+				} else {
+					view_frame_y = ui_view.GetHeight() / 2 - game.SpriteInfos[viptr->loops[0].frames[0].pic].Height / 2;
+				}
+				bigx = ui_view.GetWidth() / 2 - get_fixed_pixel_size(20);
+				ovr_type = OVER_COMPLETE;
+				ovr_yp = 0;
+				tdyp = -1;  // center vertically
+			} else {
+				// KQ6-style close-up face picture
+				if (yy < 0 && play.speech_portrait_placement) {
+					ovr_yp = play.speech_portrait_y;
+				} else if (yy < 0)
+					ovr_yp = adjust_y_for_guis(ovr_yp);
+				else
+					ovr_yp = yy;
+
+				closeupface = BitmapHelper::CreateTransparentBitmap(bigx + 1, bigy + 1, spriteset[viptr->loops[0].frames[0].pic]->GetColorDepth());
+				ovr_type = OVER_PICTURE;
+
+				if (yy < 0)
+					tdyp = ovr_yp + get_textwindow_top_border_height(play.speech_textwindow_gui);
+			}
+			const ViewFrame *vf = &viptr->loops[0].frames[0];
+			const bool closeupface_has_alpha = (game.SpriteInfos[vf->pic].Flags & SPF_ALPHACHANNEL) != 0;
+			DrawViewFrame(closeupface, vf, view_frame_x, view_frame_y);
+
+			int overlay_x = get_fixed_pixel_size(10);
+			if (xx < 0) {
+				tdxp = bigx + get_textwindow_border_width(play.speech_textwindow_gui) / 2;
+				if (play.speech_portrait_placement) {
+					overlay_x = play.speech_portrait_x;
+					tdxp += overlay_x + get_fixed_pixel_size(6);
+				} else {
+					tdxp += get_fixed_pixel_size(16);
+				}
+
+				int maxWidth = (ui_view.GetWidth() - tdxp) - get_fixed_pixel_size(5) -
+				               get_textwindow_border_width(play.speech_textwindow_gui) / 2;
+
+				if (bwidth > maxWidth)
+					bwidth = maxWidth;
+			} else {
+				tdxp = xx + bigx + get_fixed_pixel_size(8);
+				overlay_x = xx;
+			}
+
+			// allow the text box to be shrunk to fit the text
+			allowShrink = 1;
+
+			// if the portrait's on the right, swap it round
+			if (portrait_on_right) {
+				if ((xx < 0) || (widd < 0)) {
+					tdxp = get_fixed_pixel_size(9);
+					if (play.speech_portrait_placement) {
+						overlay_x = (ui_view.GetWidth() - bigx) - play.speech_portrait_x;
+						int maxWidth = overlay_x - tdxp - get_fixed_pixel_size(9) -
+						               get_textwindow_border_width(play.speech_textwindow_gui) / 2;
+						if (bwidth > maxWidth)
+							bwidth = maxWidth;
+					} else {
+						overlay_x = (ui_view.GetWidth() - bigx) - get_fixed_pixel_size(5);
+					}
+				} else {
+					overlay_x = (xx + widd - bigx) - get_fixed_pixel_size(5);
+					tdxp = xx;
+				}
+				tdxp += get_textwindow_border_width(play.speech_textwindow_gui) / 2;
+				allowShrink = 2;
+			}
+			if (game.options[OPT_SPEECHTYPE] == 3)
+				overlay_x = 0;
+			face_talking = add_screen_overlay(overlay_x, ovr_yp, ovr_type, closeupface, closeupface_has_alpha);
+			facetalkframe = 0;
+			facetalkwait = viptr->loops[0].frames[0].speed + GetCharacterSpeechAnimationDelay(speakingChar);
+			facetalkloop = 0;
+			facetalkview = useview;
+			facetalkrepeat = (isThought) ? 0 : 1;
+			facetalkBlinkLoop = 0;
+			facetalkAllowBlink = 1;
+			if ((isThought) && (speakingChar->flags & CHF_NOBLINKANDTHINK))
+				facetalkAllowBlink = 0;
+			facetalkchar = &game.chars[aschar];
+			if (facetalkchar->blinktimer < 0)
+				facetalkchar->blinktimer = facetalkchar->blinkinterval;
+			textcol = -textcol;
+			overlayPositionFixed = true;
+		} else if (useview >= 0) {
+			// Lucasarts-style speech
+			our_eip = 154;
+
+			oldview = speakingChar->view;
+			oldloop = speakingChar->loop;
+			speakingChar->animating = 1 | (GetCharacterSpeechAnimationDelay(speakingChar) << 8);
+			// only repeat if speech, not thought
+			if (!isThought)
+				speakingChar->animating |= CHANIM_REPEAT;
+
+			speakingChar->view = useview;
+			speakingChar->frame = 0;
+			speakingChar->flags |= CHF_FIXVIEW;
+
+			if (speakingChar->loop >= views[speakingChar->view].numLoops) {
+				// current character loop is outside the normal talking directions
+				speakingChar->loop = 0;
+			}
+
+			facetalkBlinkLoop = speakingChar->loop;
+
+			if (speakingChar->on && // don't bother checking if character is not visible (also fixes 'Trilby's Notes' legacy game)
+			        ((speakingChar->loop >= views[speakingChar->view].numLoops) ||
+			         (views[speakingChar->view].loops[speakingChar->loop].numFrames < 1))) {
+				quitprintf("!Unable to display speech because the character %s has an invalid speech view (View %d, loop %d, frame %d)", speakingChar->scrname, speakingChar->view + 1, speakingChar->loop, speakingChar->frame);
+			}
+
+			// set up the speed of the first frame
+			speakingChar->wait = GetCharacterSpeechAnimationDelay(speakingChar) +
+			                     views[speakingChar->view].loops[speakingChar->loop].frames[0].speed;
+
+			if (widd < 0) {
+				bwidth = ui_view.GetWidth() / 2 + ui_view.GetWidth() / 6;
+				// If they are close to the screen edge, make the text narrower
+				int relx = play.RoomToScreenX(data_to_game_coord(speakingChar->x));
+				if ((relx < ui_view.GetWidth() / 4) || (relx > ui_view.GetWidth() - (ui_view.GetWidth() / 4)))
+					bwidth -= ui_view.GetWidth() / 5;
+			}
+			/*   this causes the text to bob up and down as they talk
+			tdxp = OVR_AUTOPLACE;
+			tdyp = aschar;*/
+			if (!isThought)  // set up the lip sync if not thinking
+				char_speaking = aschar;
+
+		}
+	} else
+		allowShrink = 1;
+
+	// it wants the centred position, so make it so
+	if ((xx >= 0) && (tdxp < 0))
+		tdxp -= widd / 2;
+
+	// if they used DisplaySpeechAt, then use the supplied width
+	if ((widd > 0) && (isThought == 0))
+		allowShrink = 0;
+
+	if (isThought)
+		char_thinking = aschar;
+
+	our_eip = 155;
+	_display_at(tdxp, tdyp, bwidth, texx, DISPLAYTEXT_SPEECH, textcol, isThought, allowShrink, overlayPositionFixed);
+	our_eip = 156;
+	if ((play.in_conversation > 0) && (game.options[OPT_SPEECHTYPE] == 3))
+		closeupface = nullptr;
+	if (closeupface != nullptr)
+		remove_screen_overlay(ovr_type);
+	mark_screen_dirty();
+	face_talking = -1;
+	facetalkchar = nullptr;
+	our_eip = 157;
+	if (oldview >= 0) {
+		speakingChar->flags &= ~CHF_FIXVIEW;
+		if (viewWasLocked)
+			speakingChar->flags |= CHF_FIXVIEW;
+		speakingChar->view = oldview;
+
+		// Don't reset the loop in 2.x games
+		if (loaded_game_file_version > kGameVersion_272)
+			speakingChar->loop = oldloop;
+
+		speakingChar->animating = 0;
+		speakingChar->frame = charFrameWas;
+		speakingChar->wait = 0;
+		speakingChar->idleleft = speakingChar->idletime;
+		// restart the idle animation straight away
+		charextra[aschar].process_idle_this_time = 1;
+	}
+	char_speaking = -1;
+	char_thinking = -1;
+	if (play.IsBlockingVoiceSpeech())
+		stop_voice_speech();
 }
 
 int get_character_currently_talking() {
-    if ((face_talking >= 0) && (facetalkrepeat))
-        return facetalkchar->index_id;
-    else if (char_speaking >= 0)
-        return char_speaking;
+	if ((face_talking >= 0) && (facetalkrepeat))
+		return facetalkchar->index_id;
+	else if (char_speaking >= 0)
+		return char_speaking;
 
-    return -1;
+	return -1;
 }
 
-void DisplaySpeech(const char*texx, int aschar) {
-    _displayspeech (texx, aschar, -1, -1, -1, 0);
+void DisplaySpeech(const char *texx, int aschar) {
+	_displayspeech(texx, aschar, -1, -1, -1, 0);
 }
 
 // Calculate which frame of the loop to use for this character of
 // speech
-int GetLipSyncFrame (const char *curtex, int *stroffs) {
-    /*char *frameletters[MAXLIPSYNCFRAMES] =
-    {"./,/ ", "A", "O", "F/V", "D/N/G/L/R", "B/P/M",
-    "Y/H/K/Q/C", "I/T/E/X/th", "U/W", "S/Z/J/ch", NULL,
-    NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL};*/
-
-    int bestfit_len = 0, bestfit = game.default_lipsync_frame;
-    for (int aa = 0; aa < MAXLIPSYNCFRAMES; aa++) {
-        char *tptr = game.lipSyncFrameLetters[aa];
-        while (tptr[0] != 0) {
-            int lenthisbit = strlen(tptr);
-            if (strchr(tptr, '/'))
-                lenthisbit = strchr(tptr, '/') - tptr;
-
-            if ((ags_strnicmp (curtex, tptr, lenthisbit) == 0) && (lenthisbit > bestfit_len)) {
-                bestfit = aa;
-                bestfit_len = lenthisbit;
-            }
-            tptr += lenthisbit;
-            while (tptr[0] == '/')
-                tptr++;
-        }
-    }
-    // If it's an unknown character, use the default frame
-    if (bestfit_len == 0)
-        bestfit_len = 1;
-    *stroffs += bestfit_len;
-    return bestfit;
+int GetLipSyncFrame(const char *curtex, int *stroffs) {
+	/*char *frameletters[MAXLIPSYNCFRAMES] =
+	{"./,/ ", "A", "O", "F/V", "D/N/G/L/R", "B/P/M",
+	"Y/H/K/Q/C", "I/T/E/X/th", "U/W", "S/Z/J/ch", NULL,
+	NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL};*/
+
+	int bestfit_len = 0, bestfit = game.default_lipsync_frame;
+	for (int aa = 0; aa < MAXLIPSYNCFRAMES; aa++) {
+		char *tptr = game.lipSyncFrameLetters[aa];
+		while (tptr[0] != 0) {
+			int lenthisbit = strlen(tptr);
+			if (strchr(tptr, '/'))
+				lenthisbit = strchr(tptr, '/') - tptr;
+
+			if ((ags_strnicmp(curtex, tptr, lenthisbit) == 0) && (lenthisbit > bestfit_len)) {
+				bestfit = aa;
+				bestfit_len = lenthisbit;
+			}
+			tptr += lenthisbit;
+			while (tptr[0] == '/')
+				tptr++;
+		}
+	}
+	// If it's an unknown character, use the default frame
+	if (bestfit_len == 0)
+		bestfit_len = 1;
+	*stroffs += bestfit_len;
+	return bestfit;
 }
 
 int update_lip_sync(int talkview, int talkloop, int *talkframeptr) {
-    int talkframe = talkframeptr[0];
-    int talkwait = 0;
-
-    // lip-sync speech
-    const char *nowsaying = &text_lips_text[text_lips_offset];
-    // if it's an apostraphe, skip it (we'll, I'll, etc)
-    if (nowsaying[0] == '\'') {
-        text_lips_offset++;
-        nowsaying++;
-    }
-
-    if (text_lips_offset >= (int)strlen(text_lips_text))
-        talkframe = 0;
-    else {
-        talkframe = GetLipSyncFrame (nowsaying, &text_lips_offset);
-        if (talkframe >= views[talkview].loops[talkloop].numFrames)
-            talkframe = 0;
-    }
-
-    talkwait = loops_per_character + views[talkview].loops[talkloop].frames[talkframe].speed;
-
-    talkframeptr[0] = talkframe;
-    return talkwait;
-}
-
-Rect GetCharacterRoomBBox(int charid, bool use_frame_0)
-{
-    int width, height;
-    const CharacterExtras& chex = charextra[charid];
-    const CharacterInfo& chin = game.chars[charid];
-    int frame = use_frame_0 ? 0 : chin.frame;
-    int pic = views[chin.view].loops[chin.loop].frames[frame].pic;
-    scale_sprite_size(pic, chex.zoom, &width, &height);
-    return RectWH(chin.x - width / 2, chin.y - height, width, height);
-}
-
-PViewport FindNearestViewport(int charid)
-{
-    Rect bbox = GetCharacterRoomBBox(charid, true);
-    float min_dist = -1.f;
-    PViewport nearest_view;
-    for (int i = 0; i < play.GetRoomViewportCount(); ++i)
-    {
-        auto view = play.GetRoomViewport(i);
-        if (!view->IsVisible())
-            continue;
-        auto cam = view->GetCamera();
-        if (!cam)
-            continue;
-        Rect camr = cam->GetRect();
-        float dist = DistanceBetween(bbox, camr);
-        if (dist == 0.f)
-            return view;
-        if (min_dist < 0.f || dist < min_dist)
-        {
-            min_dist = dist;
-            nearest_view = view;
-        }
-    }
-    return nearest_view ? nearest_view : play.GetRoomViewport(0);
+	int talkframe = talkframeptr[0];
+	int talkwait = 0;
+
+	// lip-sync speech
+	const char *nowsaying = &text_lips_text[text_lips_offset];
+	// if it's an apostraphe, skip it (we'll, I'll, etc)
+	if (nowsaying[0] == '\'') {
+		text_lips_offset++;
+		nowsaying++;
+	}
+
+	if (text_lips_offset >= (int)strlen(text_lips_text))
+		talkframe = 0;
+	else {
+		talkframe = GetLipSyncFrame(nowsaying, &text_lips_offset);
+		if (talkframe >= views[talkview].loops[talkloop].numFrames)
+			talkframe = 0;
+	}
+
+	talkwait = loops_per_character + views[talkview].loops[talkloop].frames[talkframe].speed;
+
+	talkframeptr[0] = talkframe;
+	return talkwait;
+}
+
+Rect GetCharacterRoomBBox(int charid, bool use_frame_0) {
+	int width, height;
+	const CharacterExtras &chex = charextra[charid];
+	const CharacterInfo &chin = game.chars[charid];
+	int frame = use_frame_0 ? 0 : chin.frame;
+	int pic = views[chin.view].loops[chin.loop].frames[frame].pic;
+	scale_sprite_size(pic, chex.zoom, &width, &height);
+	return RectWH(chin.x - width / 2, chin.y - height, width, height);
+}
+
+PViewport FindNearestViewport(int charid) {
+	Rect bbox = GetCharacterRoomBBox(charid, true);
+	float min_dist = -1.f;
+	PViewport nearest_view;
+	for (int i = 0; i < play.GetRoomViewportCount(); ++i) {
+		auto view = play.GetRoomViewport(i);
+		if (!view->IsVisible())
+			continue;
+		auto cam = view->GetCamera();
+		if (!cam)
+			continue;
+		Rect camr = cam->GetRect();
+		float dist = DistanceBetween(bbox, camr);
+		if (dist == 0.f)
+			return view;
+		if (min_dist < 0.f || dist < min_dist) {
+			min_dist = dist;
+			nearest_view = view;
+		}
+	}
+	return nearest_view ? nearest_view : play.GetRoomViewport(0);
 }
 
 //=============================================================================
@@ -2967,290 +2854,240 @@ PViewport FindNearestViewport(int charid)
 extern ScriptString myScriptStringImpl;
 
 // void | CharacterInfo *chaa, ScriptInvItem *invi, int addIndex
-RuntimeScriptValue Sc_Character_AddInventory(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_POBJ_PINT(CharacterInfo, Character_AddInventory, ScriptInvItem);
+RuntimeScriptValue Sc_Character_AddInventory(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_POBJ_PINT(CharacterInfo, Character_AddInventory, ScriptInvItem);
 }
 
 // void | CharacterInfo *chaa, int x, int y
-RuntimeScriptValue Sc_Character_AddWaypoint(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT2(CharacterInfo, Character_AddWaypoint);
+RuntimeScriptValue Sc_Character_AddWaypoint(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT2(CharacterInfo, Character_AddWaypoint);
 }
 
 // void | CharacterInfo *chaa, int loop, int delay, int repeat, int blocking, int direction
-RuntimeScriptValue Sc_Character_Animate(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT5(CharacterInfo, Character_Animate);
+RuntimeScriptValue Sc_Character_Animate(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT5(CharacterInfo, Character_Animate);
 }
 
-RuntimeScriptValue Sc_Character_AnimateFrom(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT6(CharacterInfo, Character_AnimateFrom);
+RuntimeScriptValue Sc_Character_AnimateFrom(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT6(CharacterInfo, Character_AnimateFrom);
 }
 
 // void | CharacterInfo *chaa, int room, int x, int y
-RuntimeScriptValue Sc_Character_ChangeRoom(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT3(CharacterInfo, Character_ChangeRoom);
+RuntimeScriptValue Sc_Character_ChangeRoom(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT3(CharacterInfo, Character_ChangeRoom);
 }
 
-RuntimeScriptValue Sc_Character_ChangeRoomSetLoop(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT4(CharacterInfo, Character_ChangeRoomSetLoop);
+RuntimeScriptValue Sc_Character_ChangeRoomSetLoop(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT4(CharacterInfo, Character_ChangeRoomSetLoop);
 }
 
 // void | CharacterInfo *chaa, int room, int newPos
-RuntimeScriptValue Sc_Character_ChangeRoomAutoPosition(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT2(CharacterInfo, Character_ChangeRoomAutoPosition);
+RuntimeScriptValue Sc_Character_ChangeRoomAutoPosition(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT2(CharacterInfo, Character_ChangeRoomAutoPosition);
 }
 
 // void | CharacterInfo *chap, int vii
-RuntimeScriptValue Sc_Character_ChangeView(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_ChangeView);
+RuntimeScriptValue Sc_Character_ChangeView(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_ChangeView);
 }
 
 // void | CharacterInfo *char1, CharacterInfo *char2, int blockingStyle
-RuntimeScriptValue Sc_Character_FaceCharacter(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_POBJ_PINT(CharacterInfo, Character_FaceCharacter, CharacterInfo);
+RuntimeScriptValue Sc_Character_FaceCharacter(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_POBJ_PINT(CharacterInfo, Character_FaceCharacter, CharacterInfo);
 }
 
 // void | CharacterInfo *char1, int direction, int blockingStyle
-RuntimeScriptValue Sc_Character_FaceDirection(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT2(CharacterInfo, Character_FaceDirection);
+RuntimeScriptValue Sc_Character_FaceDirection(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT2(CharacterInfo, Character_FaceDirection);
 }
 
 // void | CharacterInfo *char1, int xx, int yy, int blockingStyle
-RuntimeScriptValue Sc_Character_FaceLocation(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT3(CharacterInfo, Character_FaceLocation);
+RuntimeScriptValue Sc_Character_FaceLocation(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT3(CharacterInfo, Character_FaceLocation);
 }
 
 // void | CharacterInfo *char1, ScriptObject *obj, int blockingStyle
-RuntimeScriptValue Sc_Character_FaceObject(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_POBJ_PINT(CharacterInfo, Character_FaceObject, ScriptObject);
+RuntimeScriptValue Sc_Character_FaceObject(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_POBJ_PINT(CharacterInfo, Character_FaceObject, ScriptObject);
 }
 
 // void | CharacterInfo *chaa, CharacterInfo *tofollow, int distaway, int eagerness
-RuntimeScriptValue Sc_Character_FollowCharacter(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_POBJ_PINT2(CharacterInfo, Character_FollowCharacter, CharacterInfo);
+RuntimeScriptValue Sc_Character_FollowCharacter(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_POBJ_PINT2(CharacterInfo, Character_FollowCharacter, CharacterInfo);
 }
 
 // int (CharacterInfo *chaa, const char *property)
-RuntimeScriptValue Sc_Character_GetProperty(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT_POBJ(CharacterInfo, Character_GetProperty, const char);
+RuntimeScriptValue Sc_Character_GetProperty(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT_POBJ(CharacterInfo, Character_GetProperty, const char);
 }
 
 // void (CharacterInfo *chaa, const char *property, char *bufer)
-RuntimeScriptValue Sc_Character_GetPropertyText(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_POBJ2(CharacterInfo, Character_GetPropertyText, const char, char);
+RuntimeScriptValue Sc_Character_GetPropertyText(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_POBJ2(CharacterInfo, Character_GetPropertyText, const char, char);
 }
 
 // const char* (CharacterInfo *chaa, const char *property)
-RuntimeScriptValue Sc_Character_GetTextProperty(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_OBJ_POBJ(CharacterInfo, const char, myScriptStringImpl, Character_GetTextProperty, const char);
+RuntimeScriptValue Sc_Character_GetTextProperty(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_OBJ_POBJ(CharacterInfo, const char, myScriptStringImpl, Character_GetTextProperty, const char);
 }
 
-RuntimeScriptValue Sc_Character_SetProperty(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_BOOL_POBJ_PINT(CharacterInfo, Character_SetProperty, const char);
+RuntimeScriptValue Sc_Character_SetProperty(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_BOOL_POBJ_PINT(CharacterInfo, Character_SetProperty, const char);
 }
 
-RuntimeScriptValue Sc_Character_SetTextProperty(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_BOOL_POBJ2(CharacterInfo, Character_SetTextProperty, const char, const char);
+RuntimeScriptValue Sc_Character_SetTextProperty(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_BOOL_POBJ2(CharacterInfo, Character_SetTextProperty, const char, const char);
 }
 
 // int (CharacterInfo *chaa, ScriptInvItem *invi)
-RuntimeScriptValue Sc_Character_HasInventory(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT_POBJ(CharacterInfo, Character_HasInventory, ScriptInvItem);
+RuntimeScriptValue Sc_Character_HasInventory(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT_POBJ(CharacterInfo, Character_HasInventory, ScriptInvItem);
 }
 
 // int (CharacterInfo *char1, CharacterInfo *char2)
-RuntimeScriptValue Sc_Character_IsCollidingWithChar(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT_POBJ(CharacterInfo, Character_IsCollidingWithChar, CharacterInfo);
+RuntimeScriptValue Sc_Character_IsCollidingWithChar(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT_POBJ(CharacterInfo, Character_IsCollidingWithChar, CharacterInfo);
 }
 
 // int (CharacterInfo *chin, ScriptObject *objid)
-RuntimeScriptValue Sc_Character_IsCollidingWithObject(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT_POBJ(CharacterInfo, Character_IsCollidingWithObject, ScriptObject);
+RuntimeScriptValue Sc_Character_IsCollidingWithObject(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT_POBJ(CharacterInfo, Character_IsCollidingWithObject, ScriptObject);
 }
 
-RuntimeScriptValue Sc_Character_IsInteractionAvailable(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_BOOL_PINT(CharacterInfo, Character_IsInteractionAvailable);
+RuntimeScriptValue Sc_Character_IsInteractionAvailable(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_BOOL_PINT(CharacterInfo, Character_IsInteractionAvailable);
 }
 
 // void (CharacterInfo *chap, int vii)
-RuntimeScriptValue Sc_Character_LockView(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_LockView);
+RuntimeScriptValue Sc_Character_LockView(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_LockView);
 }
 
 // void (CharacterInfo *chap, int vii, int stopMoving)
-RuntimeScriptValue Sc_Character_LockViewEx(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT2(CharacterInfo, Character_LockViewEx);
+RuntimeScriptValue Sc_Character_LockViewEx(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT2(CharacterInfo, Character_LockViewEx);
 }
 
 // void (CharacterInfo *chap, int vii, int loop, int align)
-RuntimeScriptValue Sc_Character_LockViewAligned_Old(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT3(CharacterInfo, Character_LockViewAligned_Old);
+RuntimeScriptValue Sc_Character_LockViewAligned_Old(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT3(CharacterInfo, Character_LockViewAligned_Old);
 }
 
 // void (CharacterInfo *chap, int vii, int loop, int align, int stopMoving)
-RuntimeScriptValue Sc_Character_LockViewAlignedEx_Old(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT4(CharacterInfo, Character_LockViewAlignedEx_Old);
+RuntimeScriptValue Sc_Character_LockViewAlignedEx_Old(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT4(CharacterInfo, Character_LockViewAlignedEx_Old);
 }
 
-RuntimeScriptValue Sc_Character_LockViewAligned(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT3(CharacterInfo, Character_LockViewAligned);
+RuntimeScriptValue Sc_Character_LockViewAligned(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT3(CharacterInfo, Character_LockViewAligned);
 }
 
-RuntimeScriptValue Sc_Character_LockViewAlignedEx(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT4(CharacterInfo, Character_LockViewAlignedEx);
+RuntimeScriptValue Sc_Character_LockViewAlignedEx(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT4(CharacterInfo, Character_LockViewAlignedEx);
 }
 
 // void (CharacterInfo *chaa, int view, int loop, int frame)
-RuntimeScriptValue Sc_Character_LockViewFrame(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT3(CharacterInfo, Character_LockViewFrame);
+RuntimeScriptValue Sc_Character_LockViewFrame(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT3(CharacterInfo, Character_LockViewFrame);
 }
 
 // void (CharacterInfo *chaa, int view, int loop, int frame, int stopMoving)
-RuntimeScriptValue Sc_Character_LockViewFrameEx(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT4(CharacterInfo, Character_LockViewFrameEx);
+RuntimeScriptValue Sc_Character_LockViewFrameEx(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT4(CharacterInfo, Character_LockViewFrameEx);
 }
 
 // void (CharacterInfo *chap, int vii, int xoffs, int yoffs)
-RuntimeScriptValue Sc_Character_LockViewOffset(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT3(CharacterInfo, Character_LockViewOffset);
+RuntimeScriptValue Sc_Character_LockViewOffset(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT3(CharacterInfo, Character_LockViewOffset);
 }
 
 // void (CharacterInfo *chap, int vii, int xoffs, int yoffs, int stopMoving)
-RuntimeScriptValue Sc_Character_LockViewOffsetEx(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT4(CharacterInfo, Character_LockViewOffsetEx);
+RuntimeScriptValue Sc_Character_LockViewOffsetEx(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT4(CharacterInfo, Character_LockViewOffsetEx);
 }
 
 // void (CharacterInfo *chap, ScriptInvItem *invi)
-RuntimeScriptValue Sc_Character_LoseInventory(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_POBJ(CharacterInfo, Character_LoseInventory, ScriptInvItem);
+RuntimeScriptValue Sc_Character_LoseInventory(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_POBJ(CharacterInfo, Character_LoseInventory, ScriptInvItem);
 }
 
-// void (CharacterInfo *chaa, int x, int y, int blocking, int direct) 
-RuntimeScriptValue Sc_Character_Move(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT4(CharacterInfo, Character_Move);
+// void (CharacterInfo *chaa, int x, int y, int blocking, int direct)
+RuntimeScriptValue Sc_Character_Move(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT4(CharacterInfo, Character_Move);
 }
 
-// void (CharacterInfo *chap) 
-RuntimeScriptValue Sc_Character_PlaceOnWalkableArea(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID(CharacterInfo, Character_PlaceOnWalkableArea);
+// void (CharacterInfo *chap)
+RuntimeScriptValue Sc_Character_PlaceOnWalkableArea(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID(CharacterInfo, Character_PlaceOnWalkableArea);
 }
 
 // void (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_RemoveTint(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID(CharacterInfo, Character_RemoveTint);
+RuntimeScriptValue Sc_Character_RemoveTint(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID(CharacterInfo, Character_RemoveTint);
 }
 
 // void (CharacterInfo *chaa, int mood)
-RuntimeScriptValue Sc_Character_RunInteraction(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_RunInteraction);
+RuntimeScriptValue Sc_Character_RunInteraction(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_RunInteraction);
 }
 
 // void (CharacterInfo *chaa, const char *texx, ...)
-RuntimeScriptValue Sc_Character_Say(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_SCRIPT_SPRINTF(Character_Say, 1);
-    Character_Say((CharacterInfo*)self, scsf_buffer);
-    return RuntimeScriptValue((int32_t)0);
+RuntimeScriptValue Sc_Character_Say(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_SCRIPT_SPRINTF(Character_Say, 1);
+	Character_Say((CharacterInfo *)self, scsf_buffer);
+	return RuntimeScriptValue((int32_t)0);
 }
 
 // void (CharacterInfo *chaa, int x, int y, int width, const char *texx)
-RuntimeScriptValue Sc_Character_SayAt(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT3_POBJ(CharacterInfo, Character_SayAt, const char);
+RuntimeScriptValue Sc_Character_SayAt(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT3_POBJ(CharacterInfo, Character_SayAt, const char);
 }
 
 // ScriptOverlay* (CharacterInfo *chaa, const char *texx)
-RuntimeScriptValue Sc_Character_SayBackground(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_OBJAUTO_POBJ(CharacterInfo, ScriptOverlay, Character_SayBackground, const char);
+RuntimeScriptValue Sc_Character_SayBackground(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_OBJAUTO_POBJ(CharacterInfo, ScriptOverlay, Character_SayBackground, const char);
 }
 
 // void (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_SetAsPlayer(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID(CharacterInfo, Character_SetAsPlayer);
+RuntimeScriptValue Sc_Character_SetAsPlayer(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID(CharacterInfo, Character_SetAsPlayer);
 }
 
 // void (CharacterInfo *chaa, int iview, int itime)
-RuntimeScriptValue Sc_Character_SetIdleView(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT2(CharacterInfo, Character_SetIdleView);
+RuntimeScriptValue Sc_Character_SetIdleView(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT2(CharacterInfo, Character_SetIdleView);
 }
 
-RuntimeScriptValue Sc_Character_HasExplicitLight(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_BOOL(CharacterInfo, Character_GetHasExplicitLight);
+RuntimeScriptValue Sc_Character_HasExplicitLight(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_BOOL(CharacterInfo, Character_GetHasExplicitLight);
 }
 
-RuntimeScriptValue Sc_Character_GetLightLevel(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetLightLevel);
+RuntimeScriptValue Sc_Character_GetLightLevel(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetLightLevel);
 }
 
-RuntimeScriptValue Sc_Character_SetLightLevel(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetLightLevel);
+RuntimeScriptValue Sc_Character_SetLightLevel(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetLightLevel);
 }
 
-RuntimeScriptValue Sc_Character_GetTintBlue(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetTintBlue);
+RuntimeScriptValue Sc_Character_GetTintBlue(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetTintBlue);
 }
 
-RuntimeScriptValue Sc_Character_GetTintGreen(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetTintGreen);
+RuntimeScriptValue Sc_Character_GetTintGreen(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetTintGreen);
 }
 
-RuntimeScriptValue Sc_Character_GetTintRed(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetTintRed);
+RuntimeScriptValue Sc_Character_GetTintRed(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetTintRed);
 }
 
-RuntimeScriptValue Sc_Character_GetTintSaturation(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetTintSaturation);
+RuntimeScriptValue Sc_Character_GetTintSaturation(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetTintSaturation);
 }
 
-RuntimeScriptValue Sc_Character_GetTintLuminance(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetTintLuminance);
+RuntimeScriptValue Sc_Character_GetTintLuminance(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetTintLuminance);
 }
 
 /*
@@ -3260,546 +3097,455 @@ RuntimeScriptValue Sc_Character_SetOption(void *self, const RuntimeScriptValue *
 */
 
 // void (CharacterInfo *chaa, int xspeed, int yspeed)
-RuntimeScriptValue Sc_Character_SetSpeed(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT2(CharacterInfo, Character_SetSpeed);
+RuntimeScriptValue Sc_Character_SetSpeed(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT2(CharacterInfo, Character_SetSpeed);
 }
 
 // void (CharacterInfo *charp)
-RuntimeScriptValue Sc_Character_StopMoving(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID(CharacterInfo, Character_StopMoving);
+RuntimeScriptValue Sc_Character_StopMoving(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID(CharacterInfo, Character_StopMoving);
 }
 
 // void (CharacterInfo *chaa, const char *texx, ...)
-RuntimeScriptValue Sc_Character_Think(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_SCRIPT_SPRINTF(Character_Think, 1);
-    Character_Think((CharacterInfo*)self, scsf_buffer);
-    return RuntimeScriptValue((int32_t)0);
+RuntimeScriptValue Sc_Character_Think(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_SCRIPT_SPRINTF(Character_Think, 1);
+	Character_Think((CharacterInfo *)self, scsf_buffer);
+	return RuntimeScriptValue((int32_t)0);
 }
 
 //void (CharacterInfo *chaa, int red, int green, int blue, int opacity, int luminance)
-RuntimeScriptValue Sc_Character_Tint(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT5(CharacterInfo, Character_Tint);
+RuntimeScriptValue Sc_Character_Tint(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT5(CharacterInfo, Character_Tint);
 }
 
 // void (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_UnlockView(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID(CharacterInfo, Character_UnlockView);
+RuntimeScriptValue Sc_Character_UnlockView(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID(CharacterInfo, Character_UnlockView);
 }
 
 // void (CharacterInfo *chaa, int stopMoving)
-RuntimeScriptValue Sc_Character_UnlockViewEx(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_UnlockViewEx);
+RuntimeScriptValue Sc_Character_UnlockViewEx(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_UnlockViewEx);
 }
 
 // void (CharacterInfo *chaa, int x, int y, int blocking, int direct)
-RuntimeScriptValue Sc_Character_Walk(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT4(CharacterInfo, Character_Walk);
+RuntimeScriptValue Sc_Character_Walk(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT4(CharacterInfo, Character_Walk);
 }
 
 // void (CharacterInfo *chaa, int xx, int yy, int blocking)
-RuntimeScriptValue Sc_Character_WalkStraight(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT3(CharacterInfo, Character_WalkStraight);
+RuntimeScriptValue Sc_Character_WalkStraight(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT3(CharacterInfo, Character_WalkStraight);
 }
 
-RuntimeScriptValue Sc_GetCharacterAtRoom(const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_SCALL_OBJ_PINT2(CharacterInfo, ccDynamicCharacter, GetCharacterAtRoom);
+RuntimeScriptValue Sc_GetCharacterAtRoom(const RuntimeScriptValue *params, int32_t param_count) {
+	API_SCALL_OBJ_PINT2(CharacterInfo, ccDynamicCharacter, GetCharacterAtRoom);
 }
 
 // CharacterInfo *(int xx, int yy)
-RuntimeScriptValue Sc_GetCharacterAtScreen(const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_SCALL_OBJ_PINT2(CharacterInfo, ccDynamicCharacter, GetCharacterAtScreen);
+RuntimeScriptValue Sc_GetCharacterAtScreen(const RuntimeScriptValue *params, int32_t param_count) {
+	API_SCALL_OBJ_PINT2(CharacterInfo, ccDynamicCharacter, GetCharacterAtScreen);
 }
 
 // ScriptInvItem* (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetActiveInventory(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_OBJ(CharacterInfo, ScriptInvItem, ccDynamicInv, Character_GetActiveInventory);
+RuntimeScriptValue Sc_Character_GetActiveInventory(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_OBJ(CharacterInfo, ScriptInvItem, ccDynamicInv, Character_GetActiveInventory);
 }
 
 // void (CharacterInfo *chaa, ScriptInvItem* iit)
-RuntimeScriptValue Sc_Character_SetActiveInventory(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_POBJ(CharacterInfo, Character_SetActiveInventory, ScriptInvItem);
+RuntimeScriptValue Sc_Character_SetActiveInventory(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_POBJ(CharacterInfo, Character_SetActiveInventory, ScriptInvItem);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetAnimating(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetAnimating);
+RuntimeScriptValue Sc_Character_GetAnimating(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetAnimating);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetAnimationSpeed(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetAnimationSpeed);
+RuntimeScriptValue Sc_Character_GetAnimationSpeed(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetAnimationSpeed);
 }
 
 // void (CharacterInfo *chaa, int newval)
-RuntimeScriptValue Sc_Character_SetAnimationSpeed(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetAnimationSpeed);
+RuntimeScriptValue Sc_Character_SetAnimationSpeed(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetAnimationSpeed);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetBaseline(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetBaseline);
+RuntimeScriptValue Sc_Character_GetBaseline(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetBaseline);
 }
 
 // void (CharacterInfo *chaa, int basel)
-RuntimeScriptValue Sc_Character_SetBaseline(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetBaseline);
+RuntimeScriptValue Sc_Character_SetBaseline(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetBaseline);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetBlinkInterval(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetBlinkInterval);
+RuntimeScriptValue Sc_Character_GetBlinkInterval(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetBlinkInterval);
 }
 
 // void (CharacterInfo *chaa, int interval)
-RuntimeScriptValue Sc_Character_SetBlinkInterval(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetBlinkInterval);
+RuntimeScriptValue Sc_Character_SetBlinkInterval(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetBlinkInterval);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetBlinkView(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetBlinkView);
+RuntimeScriptValue Sc_Character_GetBlinkView(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetBlinkView);
 }
 
 // void (CharacterInfo *chaa, int vii)
-RuntimeScriptValue Sc_Character_SetBlinkView(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetBlinkView);
+RuntimeScriptValue Sc_Character_SetBlinkView(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetBlinkView);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetBlinkWhileThinking(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetBlinkWhileThinking);
+RuntimeScriptValue Sc_Character_GetBlinkWhileThinking(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetBlinkWhileThinking);
 }
 
 // void (CharacterInfo *chaa, int yesOrNo)
-RuntimeScriptValue Sc_Character_SetBlinkWhileThinking(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetBlinkWhileThinking);
+RuntimeScriptValue Sc_Character_SetBlinkWhileThinking(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetBlinkWhileThinking);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetBlockingHeight(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetBlockingHeight);
+RuntimeScriptValue Sc_Character_GetBlockingHeight(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetBlockingHeight);
 }
 
 // void (CharacterInfo *chaa, int hit)
-RuntimeScriptValue Sc_Character_SetBlockingHeight(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetBlockingHeight);
+RuntimeScriptValue Sc_Character_SetBlockingHeight(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetBlockingHeight);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetBlockingWidth(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetBlockingWidth);
+RuntimeScriptValue Sc_Character_GetBlockingWidth(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetBlockingWidth);
 }
 
 // void (CharacterInfo *chaa, int wid)
-RuntimeScriptValue Sc_Character_SetBlockingWidth(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetBlockingWidth);
+RuntimeScriptValue Sc_Character_SetBlockingWidth(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetBlockingWidth);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetClickable(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetClickable);
+RuntimeScriptValue Sc_Character_GetClickable(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetClickable);
 }
 
 // void (CharacterInfo *chaa, int clik)
-RuntimeScriptValue Sc_Character_SetClickable(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetClickable);
+RuntimeScriptValue Sc_Character_SetClickable(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetClickable);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetDiagonalWalking(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetDiagonalWalking);
+RuntimeScriptValue Sc_Character_GetDiagonalWalking(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetDiagonalWalking);
 }
 
 // void (CharacterInfo *chaa, int yesorno)
-RuntimeScriptValue Sc_Character_SetDiagonalWalking(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetDiagonalWalking);
+RuntimeScriptValue Sc_Character_SetDiagonalWalking(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetDiagonalWalking);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetFrame(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetFrame);
+RuntimeScriptValue Sc_Character_GetFrame(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetFrame);
 }
 
 // void (CharacterInfo *chaa, int newval)
-RuntimeScriptValue Sc_Character_SetFrame(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetFrame);
+RuntimeScriptValue Sc_Character_SetFrame(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetFrame);
 }
 
-RuntimeScriptValue Sc_Character_GetHasExplicitTint_Old(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetHasExplicitTint_Old);
+RuntimeScriptValue Sc_Character_GetHasExplicitTint_Old(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetHasExplicitTint_Old);
 }
 
-RuntimeScriptValue Sc_Character_GetHasExplicitTint(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetHasExplicitTint);
+RuntimeScriptValue Sc_Character_GetHasExplicitTint(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetHasExplicitTint);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetID(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetID);
+RuntimeScriptValue Sc_Character_GetID(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetID);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetIdleView(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetIdleView);
+RuntimeScriptValue Sc_Character_GetIdleView(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetIdleView);
 }
 
 // int (CharacterInfo *chaa, int index)
-RuntimeScriptValue Sc_Character_GetIInventoryQuantity(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT_PINT(CharacterInfo, Character_GetIInventoryQuantity);
+RuntimeScriptValue Sc_Character_GetIInventoryQuantity(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT_PINT(CharacterInfo, Character_GetIInventoryQuantity);
 }
 
 // void (CharacterInfo *chaa, int index, int quant)
-RuntimeScriptValue Sc_Character_SetIInventoryQuantity(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT2(CharacterInfo, Character_SetIInventoryQuantity);
+RuntimeScriptValue Sc_Character_SetIInventoryQuantity(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT2(CharacterInfo, Character_SetIInventoryQuantity);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetIgnoreLighting(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetIgnoreLighting);
+RuntimeScriptValue Sc_Character_GetIgnoreLighting(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetIgnoreLighting);
 }
 
 // void (CharacterInfo *chaa, int yesorno)
-RuntimeScriptValue Sc_Character_SetIgnoreLighting(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetIgnoreLighting);
+RuntimeScriptValue Sc_Character_SetIgnoreLighting(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetIgnoreLighting);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetIgnoreScaling(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetIgnoreScaling);
+RuntimeScriptValue Sc_Character_GetIgnoreScaling(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetIgnoreScaling);
 }
 
 // void (CharacterInfo *chaa, int yesorno)
-RuntimeScriptValue Sc_Character_SetIgnoreScaling(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetIgnoreScaling);
+RuntimeScriptValue Sc_Character_SetIgnoreScaling(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetIgnoreScaling);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetIgnoreWalkbehinds(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetIgnoreWalkbehinds);
+RuntimeScriptValue Sc_Character_GetIgnoreWalkbehinds(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetIgnoreWalkbehinds);
 }
 
 // void (CharacterInfo *chaa, int yesorno)
-RuntimeScriptValue Sc_Character_SetIgnoreWalkbehinds(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetIgnoreWalkbehinds);
+RuntimeScriptValue Sc_Character_SetIgnoreWalkbehinds(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetIgnoreWalkbehinds);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetLoop(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetLoop);
+RuntimeScriptValue Sc_Character_GetLoop(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetLoop);
 }
 
 // void (CharacterInfo *chaa, int newval)
-RuntimeScriptValue Sc_Character_SetLoop(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetLoop);
+RuntimeScriptValue Sc_Character_SetLoop(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetLoop);
 }
 
 // void (CharacterInfo *chaa, int yesorno)
-RuntimeScriptValue Sc_Character_SetManualScaling(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetManualScaling);
+RuntimeScriptValue Sc_Character_SetManualScaling(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetManualScaling);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetMovementLinkedToAnimation(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetMovementLinkedToAnimation);
+RuntimeScriptValue Sc_Character_GetMovementLinkedToAnimation(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetMovementLinkedToAnimation);
 }
 
 // void (CharacterInfo *chaa, int yesorno)
-RuntimeScriptValue Sc_Character_SetMovementLinkedToAnimation(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetMovementLinkedToAnimation);
+RuntimeScriptValue Sc_Character_SetMovementLinkedToAnimation(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetMovementLinkedToAnimation);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetMoving(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetMoving);
+RuntimeScriptValue Sc_Character_GetMoving(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetMoving);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetDestinationX(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetDestinationX);
+RuntimeScriptValue Sc_Character_GetDestinationX(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetDestinationX);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetDestinationY(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetDestinationY);
+RuntimeScriptValue Sc_Character_GetDestinationY(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetDestinationY);
 }
 
 // const char* (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetName(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_OBJ(CharacterInfo, const char, myScriptStringImpl, Character_GetName);
+RuntimeScriptValue Sc_Character_GetName(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_OBJ(CharacterInfo, const char, myScriptStringImpl, Character_GetName);
 }
 
 // void (CharacterInfo *chaa, const char *newName)
-RuntimeScriptValue Sc_Character_SetName(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_POBJ(CharacterInfo, Character_SetName, const char);
+RuntimeScriptValue Sc_Character_SetName(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_POBJ(CharacterInfo, Character_SetName, const char);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetNormalView(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetNormalView);
+RuntimeScriptValue Sc_Character_GetNormalView(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetNormalView);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetPreviousRoom(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetPreviousRoom);
+RuntimeScriptValue Sc_Character_GetPreviousRoom(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetPreviousRoom);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetRoom(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetRoom);
+RuntimeScriptValue Sc_Character_GetRoom(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetRoom);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetScaleMoveSpeed(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetScaleMoveSpeed);
+RuntimeScriptValue Sc_Character_GetScaleMoveSpeed(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetScaleMoveSpeed);
 }
 
 // void (CharacterInfo *chaa, int yesorno)
-RuntimeScriptValue Sc_Character_SetScaleMoveSpeed(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetScaleMoveSpeed);
+RuntimeScriptValue Sc_Character_SetScaleMoveSpeed(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetScaleMoveSpeed);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetScaleVolume(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetScaleVolume);
+RuntimeScriptValue Sc_Character_GetScaleVolume(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetScaleVolume);
 }
 
 // void (CharacterInfo *chaa, int yesorno)
-RuntimeScriptValue Sc_Character_SetScaleVolume(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetScaleVolume);
+RuntimeScriptValue Sc_Character_SetScaleVolume(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetScaleVolume);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetScaling(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetScaling);
+RuntimeScriptValue Sc_Character_GetScaling(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetScaling);
 }
 
 // void (CharacterInfo *chaa, int zoomlevel)
-RuntimeScriptValue Sc_Character_SetScaling(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetScaling);
+RuntimeScriptValue Sc_Character_SetScaling(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetScaling);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetSolid(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetSolid);
+RuntimeScriptValue Sc_Character_GetSolid(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetSolid);
 }
 
 // void (CharacterInfo *chaa, int yesorno)
-RuntimeScriptValue Sc_Character_SetSolid(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetSolid);
+RuntimeScriptValue Sc_Character_SetSolid(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetSolid);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetSpeaking(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetSpeaking);
+RuntimeScriptValue Sc_Character_GetSpeaking(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetSpeaking);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetSpeakingFrame(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetSpeakingFrame);
+RuntimeScriptValue Sc_Character_GetSpeakingFrame(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetSpeakingFrame);
 }
 
 // int (CharacterInfo *cha)
-RuntimeScriptValue Sc_GetCharacterSpeechAnimationDelay(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, GetCharacterSpeechAnimationDelay);
+RuntimeScriptValue Sc_GetCharacterSpeechAnimationDelay(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, GetCharacterSpeechAnimationDelay);
 }
 
 // void (CharacterInfo *chaa, int newDelay)
-RuntimeScriptValue Sc_Character_SetSpeechAnimationDelay(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetSpeechAnimationDelay);
+RuntimeScriptValue Sc_Character_SetSpeechAnimationDelay(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetSpeechAnimationDelay);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetSpeechColor(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetSpeechColor);
+RuntimeScriptValue Sc_Character_GetSpeechColor(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetSpeechColor);
 }
 
 // void (CharacterInfo *chaa, int ncol)
-RuntimeScriptValue Sc_Character_SetSpeechColor(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetSpeechColor);
+RuntimeScriptValue Sc_Character_SetSpeechColor(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetSpeechColor);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetSpeechView(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetSpeechView);
+RuntimeScriptValue Sc_Character_GetSpeechView(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetSpeechView);
 }
 
 // void (CharacterInfo *chaa, int vii)
-RuntimeScriptValue Sc_Character_SetSpeechView(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetSpeechView);
+RuntimeScriptValue Sc_Character_SetSpeechView(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetSpeechView);
 }
 
-RuntimeScriptValue Sc_Character_GetThinking(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_BOOL(CharacterInfo, Character_GetThinking);
+RuntimeScriptValue Sc_Character_GetThinking(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_BOOL(CharacterInfo, Character_GetThinking);
 }
 
-RuntimeScriptValue Sc_Character_GetThinkingFrame(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetThinkingFrame);
+RuntimeScriptValue Sc_Character_GetThinkingFrame(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetThinkingFrame);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetThinkView(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetThinkView);
+RuntimeScriptValue Sc_Character_GetThinkView(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetThinkView);
 }
 
 // void (CharacterInfo *chaa, int vii)
-RuntimeScriptValue Sc_Character_SetThinkView(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetThinkView);
+RuntimeScriptValue Sc_Character_SetThinkView(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetThinkView);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetTransparency(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetTransparency);
+RuntimeScriptValue Sc_Character_GetTransparency(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetTransparency);
 }
 
 // void (CharacterInfo *chaa, int trans)
-RuntimeScriptValue Sc_Character_SetTransparency(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetTransparency);
+RuntimeScriptValue Sc_Character_SetTransparency(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetTransparency);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetTurnBeforeWalking(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetTurnBeforeWalking);
+RuntimeScriptValue Sc_Character_GetTurnBeforeWalking(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetTurnBeforeWalking);
 }
 
 // void (CharacterInfo *chaa, int yesorno)
-RuntimeScriptValue Sc_Character_SetTurnBeforeWalking(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetTurnBeforeWalking);
+RuntimeScriptValue Sc_Character_SetTurnBeforeWalking(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetTurnBeforeWalking);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetView(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetView);
+RuntimeScriptValue Sc_Character_GetView(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetView);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetWalkSpeedX(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetWalkSpeedX);
+RuntimeScriptValue Sc_Character_GetWalkSpeedX(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetWalkSpeedX);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetWalkSpeedY(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetWalkSpeedY);
+RuntimeScriptValue Sc_Character_GetWalkSpeedY(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetWalkSpeedY);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetX(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetX);
+RuntimeScriptValue Sc_Character_GetX(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetX);
 }
 
 // void (CharacterInfo *chaa, int newval)
-RuntimeScriptValue Sc_Character_SetX(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetX);
+RuntimeScriptValue Sc_Character_SetX(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetX);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetY(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetY);
+RuntimeScriptValue Sc_Character_GetY(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetY);
 }
 
 // void (CharacterInfo *chaa, int newval)
-RuntimeScriptValue Sc_Character_SetY(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetY);
+RuntimeScriptValue Sc_Character_SetY(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetY);
 }
 
 // int (CharacterInfo *chaa)
-RuntimeScriptValue Sc_Character_GetZ(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(CharacterInfo, Character_GetZ);
+RuntimeScriptValue Sc_Character_GetZ(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(CharacterInfo, Character_GetZ);
 }
 
 // void (CharacterInfo *chaa, int newval)
-RuntimeScriptValue Sc_Character_SetZ(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetZ);
+RuntimeScriptValue Sc_Character_SetZ(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_VOID_PINT(CharacterInfo, Character_SetZ);
 }
 
 //=============================================================================
@@ -3809,27 +3555,24 @@ RuntimeScriptValue Sc_Character_SetZ(void *self, const RuntimeScriptValue *param
 //=============================================================================
 
 // void (CharacterInfo *chaa, const char *texx, ...)
-void ScPl_Character_Say(CharacterInfo *chaa, const char *texx, ...)
-{
-    API_PLUGIN_SCRIPT_SPRINTF(texx);
-    Character_Say(chaa, scsf_buffer);
+void ScPl_Character_Say(CharacterInfo *chaa, const char *texx, ...) {
+	API_PLUGIN_SCRIPT_SPRINTF(texx);
+	Character_Say(chaa, scsf_buffer);
 }
 
 // void (CharacterInfo *chaa, const char *texx, ...)
-void ScPl_Character_Think(CharacterInfo *chaa, const char *texx, ...)
-{
-    API_PLUGIN_SCRIPT_SPRINTF(texx);
-    Character_Think(chaa, scsf_buffer);
+void ScPl_Character_Think(CharacterInfo *chaa, const char *texx, ...) {
+	API_PLUGIN_SCRIPT_SPRINTF(texx);
+	Character_Think(chaa, scsf_buffer);
 }
 
-void RegisterCharacterAPI(ScriptAPIVersion base_api, ScriptAPIVersion compat_api)
-{
-    ccAddExternalObjectFunction("Character::AddInventory^2",            Sc_Character_AddInventory);
+void RegisterCharacterAPI(ScriptAPIVersion base_api, ScriptAPIVersion compat_api) {
+	ccAddExternalObjectFunction("Character::AddInventory^2",            Sc_Character_AddInventory);
 	ccAddExternalObjectFunction("Character::AddWaypoint^2",             Sc_Character_AddWaypoint);
 	ccAddExternalObjectFunction("Character::Animate^5",                 Sc_Character_Animate);
-    ccAddExternalObjectFunction("Character::Animate^6",                 Sc_Character_AnimateFrom);
+	ccAddExternalObjectFunction("Character::Animate^6",                 Sc_Character_AnimateFrom);
 	ccAddExternalObjectFunction("Character::ChangeRoom^3",              Sc_Character_ChangeRoom);
-    ccAddExternalObjectFunction("Character::ChangeRoom^4",              Sc_Character_ChangeRoomSetLoop);
+	ccAddExternalObjectFunction("Character::ChangeRoom^4",              Sc_Character_ChangeRoomSetLoop);
 	ccAddExternalObjectFunction("Character::ChangeRoomAutoPosition^2",  Sc_Character_ChangeRoomAutoPosition);
 	ccAddExternalObjectFunction("Character::ChangeView^1",              Sc_Character_ChangeView);
 	ccAddExternalObjectFunction("Character::FaceCharacter^2",           Sc_Character_FaceCharacter);
@@ -3840,24 +3583,21 @@ void RegisterCharacterAPI(ScriptAPIVersion base_api, ScriptAPIVersion compat_api
 	ccAddExternalObjectFunction("Character::GetProperty^1",             Sc_Character_GetProperty);
 	ccAddExternalObjectFunction("Character::GetPropertyText^2",         Sc_Character_GetPropertyText);
 	ccAddExternalObjectFunction("Character::GetTextProperty^1",         Sc_Character_GetTextProperty);
-    ccAddExternalObjectFunction("Character::SetProperty^2",             Sc_Character_SetProperty);
-    ccAddExternalObjectFunction("Character::SetTextProperty^2",         Sc_Character_SetTextProperty);
+	ccAddExternalObjectFunction("Character::SetProperty^2",             Sc_Character_SetProperty);
+	ccAddExternalObjectFunction("Character::SetTextProperty^2",         Sc_Character_SetTextProperty);
 	ccAddExternalObjectFunction("Character::HasInventory^1",            Sc_Character_HasInventory);
 	ccAddExternalObjectFunction("Character::IsCollidingWithChar^1",     Sc_Character_IsCollidingWithChar);
 	ccAddExternalObjectFunction("Character::IsCollidingWithObject^1",   Sc_Character_IsCollidingWithObject);
-    ccAddExternalObjectFunction("Character::IsInteractionAvailable^1",  Sc_Character_IsInteractionAvailable);
+	ccAddExternalObjectFunction("Character::IsInteractionAvailable^1",  Sc_Character_IsInteractionAvailable);
 	ccAddExternalObjectFunction("Character::LockView^1",                Sc_Character_LockView);
 	ccAddExternalObjectFunction("Character::LockView^2",                Sc_Character_LockViewEx);
-    if (base_api < kScriptAPI_v350)
-    {
-        ccAddExternalObjectFunction("Character::LockViewAligned^3", Sc_Character_LockViewAligned_Old);
-        ccAddExternalObjectFunction("Character::LockViewAligned^4", Sc_Character_LockViewAlignedEx_Old);
-    }
-    else
-    {
-        ccAddExternalObjectFunction("Character::LockViewAligned^3", Sc_Character_LockViewAligned);
-        ccAddExternalObjectFunction("Character::LockViewAligned^4", Sc_Character_LockViewAlignedEx);
-    }
+	if (base_api < kScriptAPI_v350) {
+		ccAddExternalObjectFunction("Character::LockViewAligned^3", Sc_Character_LockViewAligned_Old);
+		ccAddExternalObjectFunction("Character::LockViewAligned^4", Sc_Character_LockViewAlignedEx_Old);
+	} else {
+		ccAddExternalObjectFunction("Character::LockViewAligned^3", Sc_Character_LockViewAligned);
+		ccAddExternalObjectFunction("Character::LockViewAligned^4", Sc_Character_LockViewAlignedEx);
+	}
 	ccAddExternalObjectFunction("Character::LockViewFrame^3",           Sc_Character_LockViewFrame);
 	ccAddExternalObjectFunction("Character::LockViewFrame^4",           Sc_Character_LockViewFrameEx);
 	ccAddExternalObjectFunction("Character::LockViewOffset^3",          Sc_Character_LockViewOffset);
@@ -3872,7 +3612,7 @@ void RegisterCharacterAPI(ScriptAPIVersion base_api, ScriptAPIVersion compat_api
 	ccAddExternalObjectFunction("Character::SayBackground^1",           Sc_Character_SayBackground);
 	ccAddExternalObjectFunction("Character::SetAsPlayer^0",             Sc_Character_SetAsPlayer);
 	ccAddExternalObjectFunction("Character::SetIdleView^2",             Sc_Character_SetIdleView);
-    ccAddExternalObjectFunction("Character::SetLightLevel^1",           Sc_Character_SetLightLevel);
+	ccAddExternalObjectFunction("Character::SetLightLevel^1",           Sc_Character_SetLightLevel);
 	//ccAddExternalObjectFunction("Character::SetOption^2",             Sc_Character_SetOption);
 	ccAddExternalObjectFunction("Character::SetWalkSpeed^2",            Sc_Character_SetSpeed);
 	ccAddExternalObjectFunction("Character::StopMoving^0",              Sc_Character_StopMoving);
@@ -3883,7 +3623,7 @@ void RegisterCharacterAPI(ScriptAPIVersion base_api, ScriptAPIVersion compat_api
 	ccAddExternalObjectFunction("Character::Walk^4",                    Sc_Character_Walk);
 	ccAddExternalObjectFunction("Character::WalkStraight^3",            Sc_Character_WalkStraight);
 
-    ccAddExternalStaticFunction("Character::GetAtRoomXY^2",             Sc_GetCharacterAtRoom);
+	ccAddExternalStaticFunction("Character::GetAtRoomXY^2",             Sc_GetCharacterAtRoom);
 	ccAddExternalStaticFunction("Character::GetAtScreenXY^2",           Sc_GetCharacterAtScreen);
 
 	ccAddExternalObjectFunction("Character::get_ActiveInventory",       Sc_Character_GetActiveInventory);
@@ -3911,10 +3651,10 @@ void RegisterCharacterAPI(ScriptAPIVersion base_api, ScriptAPIVersion compat_api
 	ccAddExternalObjectFunction("Character::set_DiagonalLoops",         Sc_Character_SetDiagonalWalking);
 	ccAddExternalObjectFunction("Character::get_Frame",                 Sc_Character_GetFrame);
 	ccAddExternalObjectFunction("Character::set_Frame",                 Sc_Character_SetFrame);
-    if (base_api < kScriptAPI_v341)
-        ccAddExternalObjectFunction("Character::get_HasExplicitTint",       Sc_Character_GetHasExplicitTint_Old);
-    else
-	    ccAddExternalObjectFunction("Character::get_HasExplicitTint",       Sc_Character_GetHasExplicitTint);
+	if (base_api < kScriptAPI_v341)
+		ccAddExternalObjectFunction("Character::get_HasExplicitTint",       Sc_Character_GetHasExplicitTint_Old);
+	else
+		ccAddExternalObjectFunction("Character::get_HasExplicitTint",       Sc_Character_GetHasExplicitTint);
 	ccAddExternalObjectFunction("Character::get_ID",                    Sc_Character_GetID);
 	ccAddExternalObjectFunction("Character::get_IdleView",              Sc_Character_GetIdleView);
 	ccAddExternalObjectFunction("Character::geti_InventoryQuantity",    Sc_Character_GetIInventoryQuantity);
@@ -3929,8 +3669,8 @@ void RegisterCharacterAPI(ScriptAPIVersion base_api, ScriptAPIVersion compat_api
 	ccAddExternalObjectFunction("Character::set_Loop",                  Sc_Character_SetLoop);
 	ccAddExternalObjectFunction("Character::get_ManualScaling",         Sc_Character_GetIgnoreScaling);
 	ccAddExternalObjectFunction("Character::set_ManualScaling",         Sc_Character_SetManualScaling);
-	ccAddExternalObjectFunction("Character::get_MovementLinkedToAnimation",Sc_Character_GetMovementLinkedToAnimation);
-	ccAddExternalObjectFunction("Character::set_MovementLinkedToAnimation",Sc_Character_SetMovementLinkedToAnimation);
+	ccAddExternalObjectFunction("Character::get_MovementLinkedToAnimation", Sc_Character_GetMovementLinkedToAnimation);
+	ccAddExternalObjectFunction("Character::set_MovementLinkedToAnimation", Sc_Character_SetMovementLinkedToAnimation);
 	ccAddExternalObjectFunction("Character::get_Moving",                Sc_Character_GetMoving);
 	ccAddExternalObjectFunction("Character::get_Name",                  Sc_Character_GetName);
 	ccAddExternalObjectFunction("Character::set_Name",                  Sc_Character_SetName);
@@ -3953,8 +3693,8 @@ void RegisterCharacterAPI(ScriptAPIVersion base_api, ScriptAPIVersion compat_api
 	ccAddExternalObjectFunction("Character::set_SpeechColor",           Sc_Character_SetSpeechColor);
 	ccAddExternalObjectFunction("Character::get_SpeechView",            Sc_Character_GetSpeechView);
 	ccAddExternalObjectFunction("Character::set_SpeechView",            Sc_Character_SetSpeechView);
-    ccAddExternalObjectFunction("Character::get_Thinking",              Sc_Character_GetThinking);
-    ccAddExternalObjectFunction("Character::get_ThinkingFrame",         Sc_Character_GetThinkingFrame);
+	ccAddExternalObjectFunction("Character::get_Thinking",              Sc_Character_GetThinking);
+	ccAddExternalObjectFunction("Character::get_ThinkingFrame",         Sc_Character_GetThinkingFrame);
 	ccAddExternalObjectFunction("Character::get_ThinkView",             Sc_Character_GetThinkView);
 	ccAddExternalObjectFunction("Character::set_ThinkView",             Sc_Character_SetThinkView);
 	ccAddExternalObjectFunction("Character::get_Transparency",          Sc_Character_GetTransparency);
@@ -3977,156 +3717,153 @@ void RegisterCharacterAPI(ScriptAPIVersion base_api, ScriptAPIVersion compat_api
 	ccAddExternalObjectFunction("Character::get_z",                     Sc_Character_GetZ);
 	ccAddExternalObjectFunction("Character::set_z",                     Sc_Character_SetZ);
 
-    ccAddExternalObjectFunction("Character::get_HasExplicitLight",      Sc_Character_HasExplicitLight);
-    ccAddExternalObjectFunction("Character::get_LightLevel",            Sc_Character_GetLightLevel);
-    ccAddExternalObjectFunction("Character::get_TintBlue",              Sc_Character_GetTintBlue);
-    ccAddExternalObjectFunction("Character::get_TintGreen",             Sc_Character_GetTintGreen);
-    ccAddExternalObjectFunction("Character::get_TintRed",               Sc_Character_GetTintRed);
-    ccAddExternalObjectFunction("Character::get_TintSaturation",        Sc_Character_GetTintSaturation);
-    ccAddExternalObjectFunction("Character::get_TintLuminance",         Sc_Character_GetTintLuminance);
-
-    /* ----------------------- Registering unsafe exports for plugins -----------------------*/
-
-    ccAddExternalFunctionForPlugin("Character::AddInventory^2",            (void*)Character_AddInventory);
-    ccAddExternalFunctionForPlugin("Character::AddWaypoint^2",             (void*)Character_AddWaypoint);
-    ccAddExternalFunctionForPlugin("Character::Animate^5",                 (void*)Character_Animate);
-    ccAddExternalFunctionForPlugin("Character::ChangeRoom^3",              (void*)Character_ChangeRoom);
-    ccAddExternalFunctionForPlugin("Character::ChangeRoomAutoPosition^2",  (void*)Character_ChangeRoomAutoPosition);
-    ccAddExternalFunctionForPlugin("Character::ChangeView^1",              (void*)Character_ChangeView);
-    ccAddExternalFunctionForPlugin("Character::FaceCharacter^2",           (void*)Character_FaceCharacter);
-    ccAddExternalFunctionForPlugin("Character::FaceDirection^2",           (void*)Character_FaceDirection);
-    ccAddExternalFunctionForPlugin("Character::FaceLocation^3",            (void*)Character_FaceLocation);
-    ccAddExternalFunctionForPlugin("Character::FaceObject^2",              (void*)Character_FaceObject);
-    ccAddExternalFunctionForPlugin("Character::FollowCharacter^3",         (void*)Character_FollowCharacter);
-    ccAddExternalFunctionForPlugin("Character::GetProperty^1",             (void*)Character_GetProperty);
-    ccAddExternalFunctionForPlugin("Character::GetPropertyText^2",         (void*)Character_GetPropertyText);
-    ccAddExternalFunctionForPlugin("Character::GetTextProperty^1",         (void*)Character_GetTextProperty);
-    ccAddExternalFunctionForPlugin("Character::HasInventory^1",            (void*)Character_HasInventory);
-    ccAddExternalFunctionForPlugin("Character::IsCollidingWithChar^1",     (void*)Character_IsCollidingWithChar);
-    ccAddExternalFunctionForPlugin("Character::IsCollidingWithObject^1",   (void*)Character_IsCollidingWithObject);
-    ccAddExternalFunctionForPlugin("Character::LockView^1",                (void*)Character_LockView);
-    ccAddExternalFunctionForPlugin("Character::LockView^2",                (void*)Character_LockViewEx);
-    if (base_api < kScriptAPI_v341)
-    {
-        ccAddExternalFunctionForPlugin("Character::LockViewAligned^3", (void*)Character_LockViewAligned_Old);
-        ccAddExternalFunctionForPlugin("Character::LockViewAligned^4", (void*)Character_LockViewAlignedEx_Old);
-    }
-    else
-    {
-        ccAddExternalFunctionForPlugin("Character::LockViewAligned^3", (void*)Character_LockViewAligned);
-        ccAddExternalFunctionForPlugin("Character::LockViewAligned^4", (void*)Character_LockViewAlignedEx);
-    }
-    ccAddExternalFunctionForPlugin("Character::LockViewFrame^3",           (void*)Character_LockViewFrame);
-    ccAddExternalFunctionForPlugin("Character::LockViewFrame^4",           (void*)Character_LockViewFrameEx);
-    ccAddExternalFunctionForPlugin("Character::LockViewOffset^3",          (void*)Character_LockViewOffset);
-    ccAddExternalFunctionForPlugin("Character::LockViewOffset^4",          (void*)Character_LockViewOffset);
-    ccAddExternalFunctionForPlugin("Character::LoseInventory^1",           (void*)Character_LoseInventory);
-    ccAddExternalFunctionForPlugin("Character::Move^4",                    (void*)Character_Move);
-    ccAddExternalFunctionForPlugin("Character::PlaceOnWalkableArea^0",     (void*)Character_PlaceOnWalkableArea);
-    ccAddExternalFunctionForPlugin("Character::RemoveTint^0",              (void*)Character_RemoveTint);
-    ccAddExternalFunctionForPlugin("Character::RunInteraction^1",          (void*)Character_RunInteraction);
-    ccAddExternalFunctionForPlugin("Character::Say^101",                   (void*)ScPl_Character_Say);
-    ccAddExternalFunctionForPlugin("Character::SayAt^4",                   (void*)Character_SayAt);
-    ccAddExternalFunctionForPlugin("Character::SayBackground^1",           (void*)Character_SayBackground);
-    ccAddExternalFunctionForPlugin("Character::SetAsPlayer^0",             (void*)Character_SetAsPlayer);
-    ccAddExternalFunctionForPlugin("Character::SetIdleView^2",             (void*)Character_SetIdleView);
-    //ccAddExternalFunctionForPlugin("Character::SetOption^2",             (void*)Character_SetOption);
-    ccAddExternalFunctionForPlugin("Character::SetWalkSpeed^2",            (void*)Character_SetSpeed);
-    ccAddExternalFunctionForPlugin("Character::StopMoving^0",              (void*)Character_StopMoving);
-    ccAddExternalFunctionForPlugin("Character::Think^101",                 (void*)ScPl_Character_Think);
-    ccAddExternalFunctionForPlugin("Character::Tint^5",                    (void*)Character_Tint);
-    ccAddExternalFunctionForPlugin("Character::UnlockView^0",              (void*)Character_UnlockView);
-    ccAddExternalFunctionForPlugin("Character::UnlockView^1",              (void*)Character_UnlockViewEx);
-    ccAddExternalFunctionForPlugin("Character::Walk^4",                    (void*)Character_Walk);
-    ccAddExternalFunctionForPlugin("Character::WalkStraight^3",            (void*)Character_WalkStraight);
-    ccAddExternalFunctionForPlugin("Character::GetAtRoomXY^2",             (void*)GetCharacterAtRoom);
-    ccAddExternalFunctionForPlugin("Character::GetAtScreenXY^2",           (void*)GetCharacterAtScreen);
-    ccAddExternalFunctionForPlugin("Character::get_ActiveInventory",       (void*)Character_GetActiveInventory);
-    ccAddExternalFunctionForPlugin("Character::set_ActiveInventory",       (void*)Character_SetActiveInventory);
-    ccAddExternalFunctionForPlugin("Character::get_Animating",             (void*)Character_GetAnimating);
-    ccAddExternalFunctionForPlugin("Character::get_AnimationSpeed",        (void*)Character_GetAnimationSpeed);
-    ccAddExternalFunctionForPlugin("Character::set_AnimationSpeed",        (void*)Character_SetAnimationSpeed);
-    ccAddExternalFunctionForPlugin("Character::get_Baseline",              (void*)Character_GetBaseline);
-    ccAddExternalFunctionForPlugin("Character::set_Baseline",              (void*)Character_SetBaseline);
-    ccAddExternalFunctionForPlugin("Character::get_BlinkInterval",         (void*)Character_GetBlinkInterval);
-    ccAddExternalFunctionForPlugin("Character::set_BlinkInterval",         (void*)Character_SetBlinkInterval);
-    ccAddExternalFunctionForPlugin("Character::get_BlinkView",             (void*)Character_GetBlinkView);
-    ccAddExternalFunctionForPlugin("Character::set_BlinkView",             (void*)Character_SetBlinkView);
-    ccAddExternalFunctionForPlugin("Character::get_BlinkWhileThinking",    (void*)Character_GetBlinkWhileThinking);
-    ccAddExternalFunctionForPlugin("Character::set_BlinkWhileThinking",    (void*)Character_SetBlinkWhileThinking);
-    ccAddExternalFunctionForPlugin("Character::get_BlockingHeight",        (void*)Character_GetBlockingHeight);
-    ccAddExternalFunctionForPlugin("Character::set_BlockingHeight",        (void*)Character_SetBlockingHeight);
-    ccAddExternalFunctionForPlugin("Character::get_BlockingWidth",         (void*)Character_GetBlockingWidth);
-    ccAddExternalFunctionForPlugin("Character::set_BlockingWidth",         (void*)Character_SetBlockingWidth);
-    ccAddExternalFunctionForPlugin("Character::get_Clickable",             (void*)Character_GetClickable);
-    ccAddExternalFunctionForPlugin("Character::set_Clickable",             (void*)Character_SetClickable);
-    ccAddExternalFunctionForPlugin("Character::get_DestinationX",          (void*)Character_GetDestinationX);
-    ccAddExternalFunctionForPlugin("Character::get_DestinationY",          (void*)Character_GetDestinationY);
-    ccAddExternalFunctionForPlugin("Character::get_DiagonalLoops",         (void*)Character_GetDiagonalWalking);
-    ccAddExternalFunctionForPlugin("Character::set_DiagonalLoops",         (void*)Character_SetDiagonalWalking);
-    ccAddExternalFunctionForPlugin("Character::get_Frame",                 (void*)Character_GetFrame);
-    ccAddExternalFunctionForPlugin("Character::set_Frame",                 (void*)Character_SetFrame);
-    if (base_api < kScriptAPI_v341)
-        ccAddExternalFunctionForPlugin("Character::get_HasExplicitTint",       (void*)Character_GetHasExplicitTint_Old);
-    else
-        ccAddExternalFunctionForPlugin("Character::get_HasExplicitTint",       (void*)Character_GetHasExplicitTint);
-    ccAddExternalFunctionForPlugin("Character::get_ID",                    (void*)Character_GetID);
-    ccAddExternalFunctionForPlugin("Character::get_IdleView",              (void*)Character_GetIdleView);
-    ccAddExternalFunctionForPlugin("Character::geti_InventoryQuantity",    (void*)Character_GetIInventoryQuantity);
-    ccAddExternalFunctionForPlugin("Character::seti_InventoryQuantity",    (void*)Character_SetIInventoryQuantity);
-    ccAddExternalFunctionForPlugin("Character::get_IgnoreLighting",        (void*)Character_GetIgnoreLighting);
-    ccAddExternalFunctionForPlugin("Character::set_IgnoreLighting",        (void*)Character_SetIgnoreLighting);
-    ccAddExternalFunctionForPlugin("Character::get_IgnoreScaling",         (void*)Character_GetIgnoreScaling);
-    ccAddExternalFunctionForPlugin("Character::set_IgnoreScaling",         (void*)Character_SetIgnoreScaling);
-    ccAddExternalFunctionForPlugin("Character::get_IgnoreWalkbehinds",     (void*)Character_GetIgnoreWalkbehinds);
-    ccAddExternalFunctionForPlugin("Character::set_IgnoreWalkbehinds",     (void*)Character_SetIgnoreWalkbehinds);
-    ccAddExternalFunctionForPlugin("Character::get_Loop",                  (void*)Character_GetLoop);
-    ccAddExternalFunctionForPlugin("Character::set_Loop",                  (void*)Character_SetLoop);
-    ccAddExternalFunctionForPlugin("Character::get_ManualScaling",         (void*)Character_GetIgnoreScaling);
-    ccAddExternalFunctionForPlugin("Character::set_ManualScaling",         (void*)Character_SetManualScaling);
-    ccAddExternalFunctionForPlugin("Character::get_MovementLinkedToAnimation",(void*)Character_GetMovementLinkedToAnimation);
-    ccAddExternalFunctionForPlugin("Character::set_MovementLinkedToAnimation",(void*)Character_SetMovementLinkedToAnimation);
-    ccAddExternalFunctionForPlugin("Character::get_Moving",                (void*)Character_GetMoving);
-    ccAddExternalFunctionForPlugin("Character::get_Name",                  (void*)Character_GetName);
-    ccAddExternalFunctionForPlugin("Character::set_Name",                  (void*)Character_SetName);
-    ccAddExternalFunctionForPlugin("Character::get_NormalView",            (void*)Character_GetNormalView);
-    ccAddExternalFunctionForPlugin("Character::get_PreviousRoom",          (void*)Character_GetPreviousRoom);
-    ccAddExternalFunctionForPlugin("Character::get_Room",                  (void*)Character_GetRoom);
-    ccAddExternalFunctionForPlugin("Character::get_ScaleMoveSpeed",        (void*)Character_GetScaleMoveSpeed);
-    ccAddExternalFunctionForPlugin("Character::set_ScaleMoveSpeed",        (void*)Character_SetScaleMoveSpeed);
-    ccAddExternalFunctionForPlugin("Character::get_ScaleVolume",           (void*)Character_GetScaleVolume);
-    ccAddExternalFunctionForPlugin("Character::set_ScaleVolume",           (void*)Character_SetScaleVolume);
-    ccAddExternalFunctionForPlugin("Character::get_Scaling",               (void*)Character_GetScaling);
-    ccAddExternalFunctionForPlugin("Character::set_Scaling",               (void*)Character_SetScaling);
-    ccAddExternalFunctionForPlugin("Character::get_Solid",                 (void*)Character_GetSolid);
-    ccAddExternalFunctionForPlugin("Character::set_Solid",                 (void*)Character_SetSolid);
-    ccAddExternalFunctionForPlugin("Character::get_Speaking",              (void*)Character_GetSpeaking);
-    ccAddExternalFunctionForPlugin("Character::get_SpeakingFrame",         (void*)Character_GetSpeakingFrame);
-    ccAddExternalFunctionForPlugin("Character::get_SpeechAnimationDelay",  (void*)GetCharacterSpeechAnimationDelay);
-    ccAddExternalFunctionForPlugin("Character::set_SpeechAnimationDelay",  (void*)Character_SetSpeechAnimationDelay);
-    ccAddExternalFunctionForPlugin("Character::get_SpeechColor",           (void*)Character_GetSpeechColor);
-    ccAddExternalFunctionForPlugin("Character::set_SpeechColor",           (void*)Character_SetSpeechColor);
-    ccAddExternalFunctionForPlugin("Character::get_SpeechView",            (void*)Character_GetSpeechView);
-    ccAddExternalFunctionForPlugin("Character::set_SpeechView",            (void*)Character_SetSpeechView);
-    ccAddExternalFunctionForPlugin("Character::get_ThinkView",             (void*)Character_GetThinkView);
-    ccAddExternalFunctionForPlugin("Character::set_ThinkView",             (void*)Character_SetThinkView);
-    ccAddExternalFunctionForPlugin("Character::get_Transparency",          (void*)Character_GetTransparency);
-    ccAddExternalFunctionForPlugin("Character::set_Transparency",          (void*)Character_SetTransparency);
-    ccAddExternalFunctionForPlugin("Character::get_TurnBeforeWalking",     (void*)Character_GetTurnBeforeWalking);
-    ccAddExternalFunctionForPlugin("Character::set_TurnBeforeWalking",     (void*)Character_SetTurnBeforeWalking);
-    ccAddExternalFunctionForPlugin("Character::get_View",                  (void*)Character_GetView);
-    ccAddExternalFunctionForPlugin("Character::get_WalkSpeedX",            (void*)Character_GetWalkSpeedX);
-    ccAddExternalFunctionForPlugin("Character::get_WalkSpeedY",            (void*)Character_GetWalkSpeedY);
-    ccAddExternalFunctionForPlugin("Character::get_X",                     (void*)Character_GetX);
-    ccAddExternalFunctionForPlugin("Character::set_X",                     (void*)Character_SetX);
-    ccAddExternalFunctionForPlugin("Character::get_x",                     (void*)Character_GetX);
-    ccAddExternalFunctionForPlugin("Character::set_x",                     (void*)Character_SetX);
-    ccAddExternalFunctionForPlugin("Character::get_Y",                     (void*)Character_GetY);
-    ccAddExternalFunctionForPlugin("Character::set_Y",                     (void*)Character_SetY);
-    ccAddExternalFunctionForPlugin("Character::get_y",                     (void*)Character_GetY);
-    ccAddExternalFunctionForPlugin("Character::set_y",                     (void*)Character_SetY);
-    ccAddExternalFunctionForPlugin("Character::get_Z",                     (void*)Character_GetZ);
-    ccAddExternalFunctionForPlugin("Character::set_Z",                     (void*)Character_SetZ);
-    ccAddExternalFunctionForPlugin("Character::get_z",                     (void*)Character_GetZ);
-    ccAddExternalFunctionForPlugin("Character::set_z",                     (void*)Character_SetZ);
+	ccAddExternalObjectFunction("Character::get_HasExplicitLight",      Sc_Character_HasExplicitLight);
+	ccAddExternalObjectFunction("Character::get_LightLevel",            Sc_Character_GetLightLevel);
+	ccAddExternalObjectFunction("Character::get_TintBlue",              Sc_Character_GetTintBlue);
+	ccAddExternalObjectFunction("Character::get_TintGreen",             Sc_Character_GetTintGreen);
+	ccAddExternalObjectFunction("Character::get_TintRed",               Sc_Character_GetTintRed);
+	ccAddExternalObjectFunction("Character::get_TintSaturation",        Sc_Character_GetTintSaturation);
+	ccAddExternalObjectFunction("Character::get_TintLuminance",         Sc_Character_GetTintLuminance);
+
+	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
+
+	ccAddExternalFunctionForPlugin("Character::AddInventory^2", (void *)Character_AddInventory);
+	ccAddExternalFunctionForPlugin("Character::AddWaypoint^2", (void *)Character_AddWaypoint);
+	ccAddExternalFunctionForPlugin("Character::Animate^5", (void *)Character_Animate);
+	ccAddExternalFunctionForPlugin("Character::ChangeRoom^3", (void *)Character_ChangeRoom);
+	ccAddExternalFunctionForPlugin("Character::ChangeRoomAutoPosition^2", (void *)Character_ChangeRoomAutoPosition);
+	ccAddExternalFunctionForPlugin("Character::ChangeView^1", (void *)Character_ChangeView);
+	ccAddExternalFunctionForPlugin("Character::FaceCharacter^2", (void *)Character_FaceCharacter);
+	ccAddExternalFunctionForPlugin("Character::FaceDirection^2", (void *)Character_FaceDirection);
+	ccAddExternalFunctionForPlugin("Character::FaceLocation^3", (void *)Character_FaceLocation);
+	ccAddExternalFunctionForPlugin("Character::FaceObject^2", (void *)Character_FaceObject);
+	ccAddExternalFunctionForPlugin("Character::FollowCharacter^3", (void *)Character_FollowCharacter);
+	ccAddExternalFunctionForPlugin("Character::GetProperty^1", (void *)Character_GetProperty);
+	ccAddExternalFunctionForPlugin("Character::GetPropertyText^2", (void *)Character_GetPropertyText);
+	ccAddExternalFunctionForPlugin("Character::GetTextProperty^1", (void *)Character_GetTextProperty);
+	ccAddExternalFunctionForPlugin("Character::HasInventory^1", (void *)Character_HasInventory);
+	ccAddExternalFunctionForPlugin("Character::IsCollidingWithChar^1", (void *)Character_IsCollidingWithChar);
+	ccAddExternalFunctionForPlugin("Character::IsCollidingWithObject^1", (void *)Character_IsCollidingWithObject);
+	ccAddExternalFunctionForPlugin("Character::LockView^1", (void *)Character_LockView);
+	ccAddExternalFunctionForPlugin("Character::LockView^2", (void *)Character_LockViewEx);
+	if (base_api < kScriptAPI_v341) {
+		ccAddExternalFunctionForPlugin("Character::LockViewAligned^3", (void *)Character_LockViewAligned_Old);
+		ccAddExternalFunctionForPlugin("Character::LockViewAligned^4", (void *)Character_LockViewAlignedEx_Old);
+	} else {
+		ccAddExternalFunctionForPlugin("Character::LockViewAligned^3", (void *)Character_LockViewAligned);
+		ccAddExternalFunctionForPlugin("Character::LockViewAligned^4", (void *)Character_LockViewAlignedEx);
+	}
+	ccAddExternalFunctionForPlugin("Character::LockViewFrame^3", (void *)Character_LockViewFrame);
+	ccAddExternalFunctionForPlugin("Character::LockViewFrame^4", (void *)Character_LockViewFrameEx);
+	ccAddExternalFunctionForPlugin("Character::LockViewOffset^3", (void *)Character_LockViewOffset);
+	ccAddExternalFunctionForPlugin("Character::LockViewOffset^4", (void *)Character_LockViewOffset);
+	ccAddExternalFunctionForPlugin("Character::LoseInventory^1", (void *)Character_LoseInventory);
+	ccAddExternalFunctionForPlugin("Character::Move^4", (void *)Character_Move);
+	ccAddExternalFunctionForPlugin("Character::PlaceOnWalkableArea^0", (void *)Character_PlaceOnWalkableArea);
+	ccAddExternalFunctionForPlugin("Character::RemoveTint^0", (void *)Character_RemoveTint);
+	ccAddExternalFunctionForPlugin("Character::RunInteraction^1", (void *)Character_RunInteraction);
+	ccAddExternalFunctionForPlugin("Character::Say^101", (void *)ScPl_Character_Say);
+	ccAddExternalFunctionForPlugin("Character::SayAt^4", (void *)Character_SayAt);
+	ccAddExternalFunctionForPlugin("Character::SayBackground^1", (void *)Character_SayBackground);
+	ccAddExternalFunctionForPlugin("Character::SetAsPlayer^0", (void *)Character_SetAsPlayer);
+	ccAddExternalFunctionForPlugin("Character::SetIdleView^2", (void *)Character_SetIdleView);
+	//ccAddExternalFunctionForPlugin("Character::SetOption^2",             (void*)Character_SetOption);
+	ccAddExternalFunctionForPlugin("Character::SetWalkSpeed^2", (void *)Character_SetSpeed);
+	ccAddExternalFunctionForPlugin("Character::StopMoving^0", (void *)Character_StopMoving);
+	ccAddExternalFunctionForPlugin("Character::Think^101", (void *)ScPl_Character_Think);
+	ccAddExternalFunctionForPlugin("Character::Tint^5", (void *)Character_Tint);
+	ccAddExternalFunctionForPlugin("Character::UnlockView^0", (void *)Character_UnlockView);
+	ccAddExternalFunctionForPlugin("Character::UnlockView^1", (void *)Character_UnlockViewEx);
+	ccAddExternalFunctionForPlugin("Character::Walk^4", (void *)Character_Walk);
+	ccAddExternalFunctionForPlugin("Character::WalkStraight^3", (void *)Character_WalkStraight);
+	ccAddExternalFunctionForPlugin("Character::GetAtRoomXY^2", (void *)GetCharacterAtRoom);
+	ccAddExternalFunctionForPlugin("Character::GetAtScreenXY^2", (void *)GetCharacterAtScreen);
+	ccAddExternalFunctionForPlugin("Character::get_ActiveInventory", (void *)Character_GetActiveInventory);
+	ccAddExternalFunctionForPlugin("Character::set_ActiveInventory", (void *)Character_SetActiveInventory);
+	ccAddExternalFunctionForPlugin("Character::get_Animating", (void *)Character_GetAnimating);
+	ccAddExternalFunctionForPlugin("Character::get_AnimationSpeed", (void *)Character_GetAnimationSpeed);
+	ccAddExternalFunctionForPlugin("Character::set_AnimationSpeed", (void *)Character_SetAnimationSpeed);
+	ccAddExternalFunctionForPlugin("Character::get_Baseline", (void *)Character_GetBaseline);
+	ccAddExternalFunctionForPlugin("Character::set_Baseline", (void *)Character_SetBaseline);
+	ccAddExternalFunctionForPlugin("Character::get_BlinkInterval", (void *)Character_GetBlinkInterval);
+	ccAddExternalFunctionForPlugin("Character::set_BlinkInterval", (void *)Character_SetBlinkInterval);
+	ccAddExternalFunctionForPlugin("Character::get_BlinkView", (void *)Character_GetBlinkView);
+	ccAddExternalFunctionForPlugin("Character::set_BlinkView", (void *)Character_SetBlinkView);
+	ccAddExternalFunctionForPlugin("Character::get_BlinkWhileThinking", (void *)Character_GetBlinkWhileThinking);
+	ccAddExternalFunctionForPlugin("Character::set_BlinkWhileThinking", (void *)Character_SetBlinkWhileThinking);
+	ccAddExternalFunctionForPlugin("Character::get_BlockingHeight", (void *)Character_GetBlockingHeight);
+	ccAddExternalFunctionForPlugin("Character::set_BlockingHeight", (void *)Character_SetBlockingHeight);
+	ccAddExternalFunctionForPlugin("Character::get_BlockingWidth", (void *)Character_GetBlockingWidth);
+	ccAddExternalFunctionForPlugin("Character::set_BlockingWidth", (void *)Character_SetBlockingWidth);
+	ccAddExternalFunctionForPlugin("Character::get_Clickable", (void *)Character_GetClickable);
+	ccAddExternalFunctionForPlugin("Character::set_Clickable", (void *)Character_SetClickable);
+	ccAddExternalFunctionForPlugin("Character::get_DestinationX", (void *)Character_GetDestinationX);
+	ccAddExternalFunctionForPlugin("Character::get_DestinationY", (void *)Character_GetDestinationY);
+	ccAddExternalFunctionForPlugin("Character::get_DiagonalLoops", (void *)Character_GetDiagonalWalking);
+	ccAddExternalFunctionForPlugin("Character::set_DiagonalLoops", (void *)Character_SetDiagonalWalking);
+	ccAddExternalFunctionForPlugin("Character::get_Frame", (void *)Character_GetFrame);
+	ccAddExternalFunctionForPlugin("Character::set_Frame", (void *)Character_SetFrame);
+	if (base_api < kScriptAPI_v341)
+		ccAddExternalFunctionForPlugin("Character::get_HasExplicitTint", (void *)Character_GetHasExplicitTint_Old);
+	else
+		ccAddExternalFunctionForPlugin("Character::get_HasExplicitTint", (void *)Character_GetHasExplicitTint);
+	ccAddExternalFunctionForPlugin("Character::get_ID", (void *)Character_GetID);
+	ccAddExternalFunctionForPlugin("Character::get_IdleView", (void *)Character_GetIdleView);
+	ccAddExternalFunctionForPlugin("Character::geti_InventoryQuantity", (void *)Character_GetIInventoryQuantity);
+	ccAddExternalFunctionForPlugin("Character::seti_InventoryQuantity", (void *)Character_SetIInventoryQuantity);
+	ccAddExternalFunctionForPlugin("Character::get_IgnoreLighting", (void *)Character_GetIgnoreLighting);
+	ccAddExternalFunctionForPlugin("Character::set_IgnoreLighting", (void *)Character_SetIgnoreLighting);
+	ccAddExternalFunctionForPlugin("Character::get_IgnoreScaling", (void *)Character_GetIgnoreScaling);
+	ccAddExternalFunctionForPlugin("Character::set_IgnoreScaling", (void *)Character_SetIgnoreScaling);
+	ccAddExternalFunctionForPlugin("Character::get_IgnoreWalkbehinds", (void *)Character_GetIgnoreWalkbehinds);
+	ccAddExternalFunctionForPlugin("Character::set_IgnoreWalkbehinds", (void *)Character_SetIgnoreWalkbehinds);
+	ccAddExternalFunctionForPlugin("Character::get_Loop", (void *)Character_GetLoop);
+	ccAddExternalFunctionForPlugin("Character::set_Loop", (void *)Character_SetLoop);
+	ccAddExternalFunctionForPlugin("Character::get_ManualScaling", (void *)Character_GetIgnoreScaling);
+	ccAddExternalFunctionForPlugin("Character::set_ManualScaling", (void *)Character_SetManualScaling);
+	ccAddExternalFunctionForPlugin("Character::get_MovementLinkedToAnimation", (void *)Character_GetMovementLinkedToAnimation);
+	ccAddExternalFunctionForPlugin("Character::set_MovementLinkedToAnimation", (void *)Character_SetMovementLinkedToAnimation);
+	ccAddExternalFunctionForPlugin("Character::get_Moving", (void *)Character_GetMoving);
+	ccAddExternalFunctionForPlugin("Character::get_Name", (void *)Character_GetName);
+	ccAddExternalFunctionForPlugin("Character::set_Name", (void *)Character_SetName);
+	ccAddExternalFunctionForPlugin("Character::get_NormalView", (void *)Character_GetNormalView);
+	ccAddExternalFunctionForPlugin("Character::get_PreviousRoom", (void *)Character_GetPreviousRoom);
+	ccAddExternalFunctionForPlugin("Character::get_Room", (void *)Character_GetRoom);
+	ccAddExternalFunctionForPlugin("Character::get_ScaleMoveSpeed", (void *)Character_GetScaleMoveSpeed);
+	ccAddExternalFunctionForPlugin("Character::set_ScaleMoveSpeed", (void *)Character_SetScaleMoveSpeed);
+	ccAddExternalFunctionForPlugin("Character::get_ScaleVolume", (void *)Character_GetScaleVolume);
+	ccAddExternalFunctionForPlugin("Character::set_ScaleVolume", (void *)Character_SetScaleVolume);
+	ccAddExternalFunctionForPlugin("Character::get_Scaling", (void *)Character_GetScaling);
+	ccAddExternalFunctionForPlugin("Character::set_Scaling", (void *)Character_SetScaling);
+	ccAddExternalFunctionForPlugin("Character::get_Solid", (void *)Character_GetSolid);
+	ccAddExternalFunctionForPlugin("Character::set_Solid", (void *)Character_SetSolid);
+	ccAddExternalFunctionForPlugin("Character::get_Speaking", (void *)Character_GetSpeaking);
+	ccAddExternalFunctionForPlugin("Character::get_SpeakingFrame", (void *)Character_GetSpeakingFrame);
+	ccAddExternalFunctionForPlugin("Character::get_SpeechAnimationDelay", (void *)GetCharacterSpeechAnimationDelay);
+	ccAddExternalFunctionForPlugin("Character::set_SpeechAnimationDelay", (void *)Character_SetSpeechAnimationDelay);
+	ccAddExternalFunctionForPlugin("Character::get_SpeechColor", (void *)Character_GetSpeechColor);
+	ccAddExternalFunctionForPlugin("Character::set_SpeechColor", (void *)Character_SetSpeechColor);
+	ccAddExternalFunctionForPlugin("Character::get_SpeechView", (void *)Character_GetSpeechView);
+	ccAddExternalFunctionForPlugin("Character::set_SpeechView", (void *)Character_SetSpeechView);
+	ccAddExternalFunctionForPlugin("Character::get_ThinkView", (void *)Character_GetThinkView);
+	ccAddExternalFunctionForPlugin("Character::set_ThinkView", (void *)Character_SetThinkView);
+	ccAddExternalFunctionForPlugin("Character::get_Transparency", (void *)Character_GetTransparency);
+	ccAddExternalFunctionForPlugin("Character::set_Transparency", (void *)Character_SetTransparency);
+	ccAddExternalFunctionForPlugin("Character::get_TurnBeforeWalking", (void *)Character_GetTurnBeforeWalking);
+	ccAddExternalFunctionForPlugin("Character::set_TurnBeforeWalking", (void *)Character_SetTurnBeforeWalking);
+	ccAddExternalFunctionForPlugin("Character::get_View", (void *)Character_GetView);
+	ccAddExternalFunctionForPlugin("Character::get_WalkSpeedX", (void *)Character_GetWalkSpeedX);
+	ccAddExternalFunctionForPlugin("Character::get_WalkSpeedY", (void *)Character_GetWalkSpeedY);
+	ccAddExternalFunctionForPlugin("Character::get_X", (void *)Character_GetX);
+	ccAddExternalFunctionForPlugin("Character::set_X", (void *)Character_SetX);
+	ccAddExternalFunctionForPlugin("Character::get_x", (void *)Character_GetX);
+	ccAddExternalFunctionForPlugin("Character::set_x", (void *)Character_SetX);
+	ccAddExternalFunctionForPlugin("Character::get_Y", (void *)Character_GetY);
+	ccAddExternalFunctionForPlugin("Character::set_Y", (void *)Character_SetY);
+	ccAddExternalFunctionForPlugin("Character::get_y", (void *)Character_GetY);
+	ccAddExternalFunctionForPlugin("Character::set_y", (void *)Character_SetY);
+	ccAddExternalFunctionForPlugin("Character::get_Z", (void *)Character_GetZ);
+	ccAddExternalFunctionForPlugin("Character::set_Z", (void *)Character_SetZ);
+	ccAddExternalFunctionForPlugin("Character::get_z", (void *)Character_GetZ);
+	ccAddExternalFunctionForPlugin("Character::set_z", (void *)Character_SetZ);
 }
diff --git a/engines/ags/engine/ac/character.h b/engines/ags/engine/ac/character.h
index 948465e554..28a127ad67 100644
--- a/engines/ags/engine/ac/character.h
+++ b/engines/ags/engine/ac/character.h
@@ -62,7 +62,7 @@ void    Character_RemoveTint(CharacterInfo *chaa);
 int     Character_GetHasExplicitTint(CharacterInfo *chaa);
 void    Character_Say(CharacterInfo *chaa, const char *text);
 void    Character_SayAt(CharacterInfo *chaa, int x, int y, int width, const char *texx);
-ScriptOverlay* Character_SayBackground(CharacterInfo *chaa, const char *texx);
+ScriptOverlay *Character_SayBackground(CharacterInfo *chaa, const char *texx);
 void    Character_SetAsPlayer(CharacterInfo *chaa);
 void    Character_SetIdleView(CharacterInfo *chaa, int iview, int itime);
 void    Character_SetOption(CharacterInfo *chaa, int flag, int yesorno);
@@ -82,10 +82,10 @@ void    Character_RunInteraction(CharacterInfo *chaa, int mood);
 
 int Character_GetProperty(CharacterInfo *chaa, const char *property);
 void Character_GetPropertyText(CharacterInfo *chaa, const char *property, char *bufer);
-const char* Character_GetTextProperty(CharacterInfo *chaa, const char *property);
+const char *Character_GetTextProperty(CharacterInfo *chaa, const char *property);
 
-ScriptInvItem* Character_GetActiveInventory(CharacterInfo *chaa);
-void    Character_SetActiveInventory(CharacterInfo *chaa, ScriptInvItem* iit);
+ScriptInvItem *Character_GetActiveInventory(CharacterInfo *chaa);
+void    Character_SetActiveInventory(CharacterInfo *chaa, ScriptInvItem *iit);
 int     Character_GetAnimating(CharacterInfo *chaa);
 int     Character_GetAnimationSpeed(CharacterInfo *chaa);
 void    Character_SetAnimationSpeed(CharacterInfo *chaa, int newval);
@@ -124,7 +124,7 @@ void    Character_SetMovementLinkedToAnimation(CharacterInfo *chaa, int yesorno)
 int     Character_GetLoop(CharacterInfo *chaa);
 void    Character_SetLoop(CharacterInfo *chaa, int newval);
 int     Character_GetMoving(CharacterInfo *chaa);
-const char* Character_GetName(CharacterInfo *chaa);
+const char *Character_GetName(CharacterInfo *chaa);
 void    Character_SetName(CharacterInfo *chaa, const char *newName);
 int     Character_GetNormalView(CharacterInfo *chaa);
 int     Character_GetPreviousRoom(CharacterInfo *chaa);
@@ -163,46 +163,50 @@ int     Character_GetSpeakingFrame(CharacterInfo *chaa);
 //=============================================================================
 
 struct MoveList;
-namespace AGS { namespace Common { class Bitmap; } }
+namespace AGS {
+namespace Common {
+class Bitmap;
+}
+}
 using namespace AGS; // FIXME later
 
-void animate_character(CharacterInfo *chap, int loopn,int sppd,int rept, int noidleoverride = 0, int direction = 0, int sframe = 0);
-void walk_character(int chac,int tox,int toy,int ignwal, bool autoWalkAnims);
-int  find_looporder_index (int curloop);
+void animate_character(CharacterInfo *chap, int loopn, int sppd, int rept, int noidleoverride = 0, int direction = 0, int sframe = 0);
+void walk_character(int chac, int tox, int toy, int ignwal, bool autoWalkAnims);
+int  find_looporder_index(int curloop);
 // returns 0 to use diagonal, 1 to not
-int  useDiagonal (CharacterInfo *char1);
+int  useDiagonal(CharacterInfo *char1);
 // returns 1 normally, or 0 if they only have horizontal animations
 int  hasUpDownLoops(CharacterInfo *char1);
-void start_character_turning (CharacterInfo *chinf, int useloop, int no_diagonal);
-void fix_player_sprite(MoveList*cmls,CharacterInfo*chinf);
+void start_character_turning(CharacterInfo *chinf, int useloop, int no_diagonal);
+void fix_player_sprite(MoveList *cmls, CharacterInfo *chinf);
 // Check whether two characters have walked into each other
 int  has_hit_another_character(int sourceChar);
-int  doNextCharMoveStep (CharacterInfo *chi, int &char_index, CharacterExtras *chex);
+int  doNextCharMoveStep(CharacterInfo *chi, int &char_index, CharacterExtras *chex);
 int  find_nearest_walkable_area_within(int *xx, int *yy, int range, int step);
-void find_nearest_walkable_area (int *xx, int *yy);
-void walk_character(int chac,int tox,int toy,int ignwal, bool autoWalkAnims);
+void find_nearest_walkable_area(int *xx, int *yy);
+void walk_character(int chac, int tox, int toy, int ignwal, bool autoWalkAnims);
 void FindReasonableLoopForCharacter(CharacterInfo *chap);
 void walk_or_move_character(CharacterInfo *chaa, int x, int y, int blocking, int direct, bool isWalk);
 int  is_valid_character(int newchar);
-int  wantMoveNow (CharacterInfo *chi, CharacterExtras *chex);
+int  wantMoveNow(CharacterInfo *chi, CharacterExtras *chex);
 void setup_player_character(int charid);
 void CheckViewFrameForCharacter(CharacterInfo *chi);
 Common::Bitmap *GetCharacterImage(int charid, int *isFlipped);
 CharacterInfo *GetCharacterAtScreen(int xx, int yy);
 // Get character ID at the given room coordinates
-int is_pos_on_character(int xx,int yy);
+int is_pos_on_character(int xx, int yy);
 void get_char_blocking_rect(int charid, int *x1, int *y1, int *width, int *y2);
 // Check whether the source char has walked onto character ww
-int is_char_on_another (int sourceChar, int ww, int*fromxptr, int*cwidptr);
+int is_char_on_another(int sourceChar, int ww, int *fromxptr, int *cwidptr);
 int my_getpixel(Common::Bitmap *blk, int x, int y);
 // X and Y co-ordinates must be in 320x200 format
-int check_click_on_character(int xx,int yy,int mood);
-int is_pos_on_character(int xx,int yy);
+int check_click_on_character(int xx, int yy, int mood);
+int is_pos_on_character(int xx, int yy);
 void _DisplaySpeechCore(int chid, const char *displbuf);
 void _DisplayThoughtCore(int chid, const char *displbuf);
-void _displayspeech(const char*texx, int aschar, int xx, int yy, int widd, int isThought);
+void _displayspeech(const char *texx, int aschar, int xx, int yy, int widd, int isThought);
 int get_character_currently_talking();
-void DisplaySpeech(const char*texx, int aschar);
+void DisplaySpeech(const char *texx, int aschar);
 int update_lip_sync(int talkview, int talkloop, int *talkframeptr);
 
 // Calculates character's bounding box in room coordinates (takes only in-room transform into account)
@@ -213,7 +217,7 @@ Rect GetCharacterRoomBBox(int charid, bool use_frame_0 = false);
 // or the one that is least far away from its camera; calculated as a perpendicular distance between two AABBs.
 PViewport FindNearestViewport(int charid);
 
-extern CharacterInfo*playerchar;
+extern CharacterInfo *playerchar;
 extern CharacterExtras *charextra;
 extern MoveList *mls;
 extern int32_t _sc_PlayerCharPtr;
diff --git a/engines/ags/engine/ac/charactercache.h b/engines/ags/engine/ac/charactercache.h
index 2ba84e66ed..9032c83024 100644
--- a/engines/ags/engine/ac/charactercache.h
+++ b/engines/ags/engine/ac/charactercache.h
@@ -23,18 +23,22 @@
 #ifndef AGS_ENGINE_AC_CHARACTERCACHE_H
 #define AGS_ENGINE_AC_CHARACTERCACHE_H
 
-namespace AGS { namespace Common { class Bitmap; } }
+namespace AGS {
+namespace Common {
+class Bitmap;
+}
+}
 using namespace AGS; // FIXME later
 
 // stores cached info about the character
 struct CharacterCache {
-    Common::Bitmap *image;
-    int sppic;
-    int scaling;
-    int inUse;
-    short tintredwas, tintgrnwas, tintbluwas, tintamntwas;
-    short lightlevwas, tintlightwas;
-    // no mirroredWas is required, since the code inverts the sprite number
+	Common::Bitmap *image;
+	int sppic;
+	int scaling;
+	int inUse;
+	short tintredwas, tintgrnwas, tintbluwas, tintamntwas;
+	short lightlevwas, tintlightwas;
+	// no mirroredWas is required, since the code inverts the sprite number
 };
 
 #endif
diff --git a/engines/ags/engine/ac/characterextras.cpp b/engines/ags/engine/ac/characterextras.cpp
index 211534e075..c76d794c26 100644
--- a/engines/ags/engine/ac/characterextras.cpp
+++ b/engines/ags/engine/ac/characterextras.cpp
@@ -25,40 +25,38 @@
 
 using AGS::Common::Stream;
 
-void CharacterExtras::ReadFromFile(Stream *in)
-{
-    in->ReadArrayOfInt16(invorder, MAX_INVORDER);
-    invorder_count = in->ReadInt16();
-    width = in->ReadInt16();
-    height = in->ReadInt16();
-    zoom = in->ReadInt16();
-    xwas = in->ReadInt16();
-    ywas = in->ReadInt16();
-    tint_r = in->ReadInt16();
-    tint_g = in->ReadInt16();
-    tint_b = in->ReadInt16();
-    tint_level = in->ReadInt16();
-    tint_light = in->ReadInt16();
-    process_idle_this_time = in->ReadInt8();
-    slow_move_counter = in->ReadInt8();
-    animwait = in->ReadInt16();
+void CharacterExtras::ReadFromFile(Stream *in) {
+	in->ReadArrayOfInt16(invorder, MAX_INVORDER);
+	invorder_count = in->ReadInt16();
+	width = in->ReadInt16();
+	height = in->ReadInt16();
+	zoom = in->ReadInt16();
+	xwas = in->ReadInt16();
+	ywas = in->ReadInt16();
+	tint_r = in->ReadInt16();
+	tint_g = in->ReadInt16();
+	tint_b = in->ReadInt16();
+	tint_level = in->ReadInt16();
+	tint_light = in->ReadInt16();
+	process_idle_this_time = in->ReadInt8();
+	slow_move_counter = in->ReadInt8();
+	animwait = in->ReadInt16();
 }
 
-void CharacterExtras::WriteToFile(Stream *out)
-{
-    out->WriteArrayOfInt16(invorder, MAX_INVORDER);
-    out->WriteInt16(invorder_count);
-    out->WriteInt16(width);
-    out->WriteInt16(height);
-    out->WriteInt16(zoom);
-    out->WriteInt16(xwas);
-    out->WriteInt16(ywas);
-    out->WriteInt16(tint_r);
-    out->WriteInt16(tint_g);
-    out->WriteInt16(tint_b);
-    out->WriteInt16(tint_level);
-    out->WriteInt16(tint_light);
-    out->WriteInt8(process_idle_this_time);
-    out->WriteInt8(slow_move_counter);
-    out->WriteInt16(animwait);
+void CharacterExtras::WriteToFile(Stream *out) {
+	out->WriteArrayOfInt16(invorder, MAX_INVORDER);
+	out->WriteInt16(invorder_count);
+	out->WriteInt16(width);
+	out->WriteInt16(height);
+	out->WriteInt16(zoom);
+	out->WriteInt16(xwas);
+	out->WriteInt16(ywas);
+	out->WriteInt16(tint_r);
+	out->WriteInt16(tint_g);
+	out->WriteInt16(tint_b);
+	out->WriteInt16(tint_level);
+	out->WriteInt16(tint_light);
+	out->WriteInt8(process_idle_this_time);
+	out->WriteInt8(slow_move_counter);
+	out->WriteInt16(animwait);
 }
diff --git a/engines/ags/engine/ac/characterextras.h b/engines/ags/engine/ac/characterextras.h
index d5d86dcfe4..526e690374 100644
--- a/engines/ags/engine/ac/characterextras.h
+++ b/engines/ags/engine/ac/characterextras.h
@@ -26,32 +26,36 @@
 #include "ac/runtime_defines.h"
 
 // Forward declaration
-namespace AGS { namespace Common { class Stream; } }
+namespace AGS {
+namespace Common {
+class Stream;
+}
+}
 using namespace AGS; // FIXME later
 
 struct CharacterExtras {
-    // UGLY UGLY UGLY!! The CharacterInfo struct size is fixed because it's
-    // used in the scripts, therefore overflowing stuff has to go here
-    short invorder[MAX_INVORDER];
-    short invorder_count;
-    // TODO: implement full AABB and keep updated, so that engine could rely on these cached values all time;
-    // TODO: consider having both fixed AABB and volatile one that changes with animation frame (unless you change how anims work)
-    short width;
-    short height;
-    short zoom;
-    short xwas;
-    short ywas;
-    short tint_r;
-    short tint_g;
-    short tint_b;
-    short tint_level;
-    short tint_light;
-    char  process_idle_this_time;
-    char  slow_move_counter;
-    short animwait;
+	// UGLY UGLY UGLY!! The CharacterInfo struct size is fixed because it's
+	// used in the scripts, therefore overflowing stuff has to go here
+	short invorder[MAX_INVORDER];
+	short invorder_count;
+	// TODO: implement full AABB and keep updated, so that engine could rely on these cached values all time;
+	// TODO: consider having both fixed AABB and volatile one that changes with animation frame (unless you change how anims work)
+	short width;
+	short height;
+	short zoom;
+	short xwas;
+	short ywas;
+	short tint_r;
+	short tint_g;
+	short tint_b;
+	short tint_level;
+	short tint_light;
+	char  process_idle_this_time;
+	char  slow_move_counter;
+	short animwait;
 
-    void ReadFromFile(Common::Stream *in);
-    void WriteToFile(Common::Stream *out);
+	void ReadFromFile(Common::Stream *in);
+	void WriteToFile(Common::Stream *out);
 };
 
 #endif
diff --git a/engines/ags/engine/ac/characterinfo_engine.cpp b/engines/ags/engine/ac/characterinfo_engine.cpp
index 819b92fc11..44ff6b9696 100644
--- a/engines/ags/engine/ac/characterinfo_engine.cpp
+++ b/engines/ags/engine/ac/characterinfo_engine.cpp
@@ -31,13 +31,13 @@
 #include "ac/viewframe.h"
 #include "debug/debug_log.h"
 #include "game/roomstruct.h"
-#include "main/maindefines_ex.h"	// RETURN_CONTINUE
+#include "main/maindefines_ex.h"    // RETURN_CONTINUE
 #include "main/update.h"
 #include "media/audio/audio_system.h"
 
 using namespace AGS::Common;
 
-extern ViewStruct*views;
+extern ViewStruct *views;
 extern GameSetupStruct game;
 extern int displayed_room;
 extern GameState play;
@@ -48,45 +48,44 @@ extern unsigned int loopcounter;
 #define Random __Rand
 
 int CharacterInfo::get_effective_y() {
-    return y - z;
+	return y - z;
 }
 int CharacterInfo::get_baseline() {
-    if (baseline < 1)
-        return y;
-    return baseline;
+	if (baseline < 1)
+		return y;
+	return baseline;
 }
 int CharacterInfo::get_blocking_top() {
-    if (blocking_height > 0)
-        return y - blocking_height / 2;
-    return y - 2;
+	if (blocking_height > 0)
+		return y - blocking_height / 2;
+	return y - 2;
 }
 int CharacterInfo::get_blocking_bottom() {
-    // the blocking_bottom should be 1 less than the top + height
-    // since the code does <= checks on it rather than < checks
-    if (blocking_height > 0)
-        return (y + (blocking_height + 1) / 2) - 1;
-    return y + 3;
+	// the blocking_bottom should be 1 less than the top + height
+	// since the code does <= checks on it rather than < checks
+	if (blocking_height > 0)
+		return (y + (blocking_height + 1) / 2) - 1;
+	return y + 3;
 }
 
-void CharacterInfo::UpdateMoveAndAnim(int &char_index, CharacterExtras *chex, int &numSheep, int *followingAsSheep)
-{
+void CharacterInfo::UpdateMoveAndAnim(int &char_index, CharacterExtras *chex, int &numSheep, int *followingAsSheep) {
 	int res;
 
 	if (on != 1) return;
-    
+
 	// walking
 	res = update_character_walking(chex);
 	// [IKM] Yes, it should return! upon getting RETURN_CONTINUE here
 	if (res == RETURN_CONTINUE) { // [IKM] now, this is one of those places...
-		return;				      //  must be careful not to screw things up
+		return;                   //  must be careful not to screw things up
 	}
-    
-    // Make sure it doesn't flash up a blue cup
-    if (view < 0) ;
-    else if (loop >= views[view].numLoops)
-      loop = 0;
 
-    int doing_nothing = 1;
+	// Make sure it doesn't flash up a blue cup
+	if (view < 0) ;
+	else if (loop >= views[view].numLoops)
+		loop = 0;
+
+	int doing_nothing = 1;
 
 	update_character_moving(char_index, chex, doing_nothing);
 
@@ -95,422 +94,394 @@ void CharacterInfo::UpdateMoveAndAnim(int &char_index, CharacterExtras *chex, in
 	res = update_character_animating(char_index, doing_nothing);
 	// [IKM] Yes, it should return! upon getting RETURN_CONTINUE here
 	if (res == RETURN_CONTINUE) { // [IKM] now, this is one of those places...
-		return;				      //  must be careful not to screw things up
+		return;                   //  must be careful not to screw things up
 	}
 
 	update_character_follower(char_index, numSheep, followingAsSheep, doing_nothing);
 
 	update_character_idle(chex, doing_nothing);
 
-    chex->process_idle_this_time = 0;
+	chex->process_idle_this_time = 0;
 }
 
-void CharacterInfo::UpdateFollowingExactlyCharacter()
-{
+void CharacterInfo::UpdateFollowingExactlyCharacter() {
 	x = game.chars[following].x;
-    y = game.chars[following].y;
-    z = game.chars[following].z;
-    room = game.chars[following].room;
-    prevroom = game.chars[following].prevroom;
+	y = game.chars[following].y;
+	z = game.chars[following].z;
+	room = game.chars[following].room;
+	prevroom = game.chars[following].prevroom;
 
-    int usebase = game.chars[following].get_baseline();
+	int usebase = game.chars[following].get_baseline();
 
-    if (flags & CHF_BEHINDSHEPHERD)
-      baseline = usebase - 1;
-    else
-      baseline = usebase + 1;
+	if (flags & CHF_BEHINDSHEPHERD)
+		baseline = usebase - 1;
+	else
+		baseline = usebase + 1;
 }
 
-int CharacterInfo::update_character_walking(CharacterExtras *chex)
-{
-    if (walking >= TURNING_AROUND) {
-      // Currently rotating to correct direction
-      if (walkwait > 0) walkwait--;
-      else {
-        // Work out which direction is next
-        int wantloop = find_looporder_index(loop) + 1;
-        // going anti-clockwise, take one before instead
-        if (walking >= TURNING_BACKWARDS)
-          wantloop -= 2;
-        while (1) {
-          if (wantloop >= 8)
-            wantloop = 0;
-          if (wantloop < 0)
-            wantloop = 7;
-          if ((turnlooporder[wantloop] >= views[view].numLoops) ||
-              (views[view].loops[turnlooporder[wantloop]].numFrames < 1) ||
-              ((turnlooporder[wantloop] >= 4) && ((flags & CHF_NODIAGONAL)!=0))) {
-            if (walking >= TURNING_BACKWARDS)
-              wantloop--;
-            else
-              wantloop++;
-          }
-          else break;
-        }
-        loop = turnlooporder[wantloop];
-        walking -= TURNING_AROUND;
-        // if still turning, wait for next frame
-        if (walking % TURNING_BACKWARDS >= TURNING_AROUND)
-          walkwait = animspeed;
-        else
-          walking = walking % TURNING_BACKWARDS;
-        chex->animwait = 0;
-      }
-	  return RETURN_CONTINUE;
-      //continue;
-    }
+int CharacterInfo::update_character_walking(CharacterExtras *chex) {
+	if (walking >= TURNING_AROUND) {
+		// Currently rotating to correct direction
+		if (walkwait > 0) walkwait--;
+		else {
+			// Work out which direction is next
+			int wantloop = find_looporder_index(loop) + 1;
+			// going anti-clockwise, take one before instead
+			if (walking >= TURNING_BACKWARDS)
+				wantloop -= 2;
+			while (1) {
+				if (wantloop >= 8)
+					wantloop = 0;
+				if (wantloop < 0)
+					wantloop = 7;
+				if ((turnlooporder[wantloop] >= views[view].numLoops) ||
+				        (views[view].loops[turnlooporder[wantloop]].numFrames < 1) ||
+				        ((turnlooporder[wantloop] >= 4) && ((flags & CHF_NODIAGONAL) != 0))) {
+					if (walking >= TURNING_BACKWARDS)
+						wantloop--;
+					else
+						wantloop++;
+				} else break;
+			}
+			loop = turnlooporder[wantloop];
+			walking -= TURNING_AROUND;
+			// if still turning, wait for next frame
+			if (walking % TURNING_BACKWARDS >= TURNING_AROUND)
+				walkwait = animspeed;
+			else
+				walking = walking % TURNING_BACKWARDS;
+			chex->animwait = 0;
+		}
+		return RETURN_CONTINUE;
+		//continue;
+	}
 
 	return 0;
 }
 
-void CharacterInfo::update_character_moving(int &char_index, CharacterExtras *chex, int &doing_nothing)
-{
-	if ((walking > 0) && (room == displayed_room))
-    {
-      if (walkwait > 0) walkwait--;
-      else 
-      {
-        flags &= ~CHF_AWAITINGMOVE;
-
-        // Move the character
-        int numSteps = wantMoveNow(this, chex);
-
-        if ((numSteps) && (chex->xwas != INVALID_X)) {
-          // if the zoom level changed mid-move, the walkcounter
-          // might not have come round properly - so sort it out
-          x = chex->xwas;
-          y = chex->ywas;
-          chex->xwas = INVALID_X;
-        }
-
-        int oldxp = x, oldyp = y;
-
-        for (int ff = 0; ff < abs(numSteps); ff++) {
-          if (doNextCharMoveStep (this, char_index, chex))
-            break;
-          if ((walking == 0) || (walking >= TURNING_AROUND))
-            break;
-        }
-
-        if (numSteps < 0) {
-          // very small scaling, intersperse the movement
-          // to stop it being jumpy
-          chex->xwas = x;
-          chex->ywas = y;
-          x = ((x) - oldxp) / 2 + oldxp;
-          y = ((y) - oldyp) / 2 + oldyp;
-        }
-        else if (numSteps > 0)
-          chex->xwas = INVALID_X;
-
-        if ((flags & CHF_ANTIGLIDE) == 0)
-          walkwaitcounter++;
-      }
-
-      if (loop >= views[view].numLoops)
-        quitprintf("Unable to render character %d (%s) because loop %d does not exist in view %d", index_id, name, loop, view + 1);
-
-      // check don't overflow loop
-      int framesInLoop = views[view].loops[loop].numFrames;
-      if (frame > framesInLoop)
-      {
-        frame = 1;
-
-        if (framesInLoop < 2)
-          frame = 0;
-
-        if (framesInLoop < 1)
-          quitprintf("Unable to render character %d (%s) because there are no frames in loop %d", index_id, name, loop);
-      }
-
-      if (walking<1) {
-        chex->process_idle_this_time = 1;
-        doing_nothing=1;
-        walkwait=0;
-        chex->animwait = 0;
-        // use standing pic
-        Character_StopMoving(this);
-        frame = 0;
-        CheckViewFrameForCharacter(this);
-      }
-      else if (chex->animwait > 0) chex->animwait--;
-      else {
-        if (flags & CHF_ANTIGLIDE)
-          walkwaitcounter++;
-
-        if ((flags & CHF_MOVENOTWALK) == 0)
-        {
-          frame++;
-          if (frame >= views[view].loops[loop].numFrames)
-          {
-            // end of loop, so loop back round skipping the standing frame
-            frame = 1;
-
-            if (views[view].loops[loop].numFrames < 2)
-              frame = 0;
-          }
-
-          chex->animwait = views[view].loops[loop].frames[frame].speed + animspeed;
-
-          if (flags & CHF_ANTIGLIDE)
-            walkwait = chex->animwait;
-          else
-            walkwait = 0;
-
-          CheckViewFrameForCharacter(this);
-        }
-      }
-      doing_nothing = 0;
-    }
+void CharacterInfo::update_character_moving(int &char_index, CharacterExtras *chex, int &doing_nothing) {
+	if ((walking > 0) && (room == displayed_room)) {
+		if (walkwait > 0) walkwait--;
+		else {
+			flags &= ~CHF_AWAITINGMOVE;
+
+			// Move the character
+			int numSteps = wantMoveNow(this, chex);
+
+			if ((numSteps) && (chex->xwas != INVALID_X)) {
+				// if the zoom level changed mid-move, the walkcounter
+				// might not have come round properly - so sort it out
+				x = chex->xwas;
+				y = chex->ywas;
+				chex->xwas = INVALID_X;
+			}
+
+			int oldxp = x, oldyp = y;
+
+			for (int ff = 0; ff < abs(numSteps); ff++) {
+				if (doNextCharMoveStep(this, char_index, chex))
+					break;
+				if ((walking == 0) || (walking >= TURNING_AROUND))
+					break;
+			}
+
+			if (numSteps < 0) {
+				// very small scaling, intersperse the movement
+				// to stop it being jumpy
+				chex->xwas = x;
+				chex->ywas = y;
+				x = ((x) - oldxp) / 2 + oldxp;
+				y = ((y) - oldyp) / 2 + oldyp;
+			} else if (numSteps > 0)
+				chex->xwas = INVALID_X;
+
+			if ((flags & CHF_ANTIGLIDE) == 0)
+				walkwaitcounter++;
+		}
+
+		if (loop >= views[view].numLoops)
+			quitprintf("Unable to render character %d (%s) because loop %d does not exist in view %d", index_id, name, loop, view + 1);
+
+		// check don't overflow loop
+		int framesInLoop = views[view].loops[loop].numFrames;
+		if (frame > framesInLoop) {
+			frame = 1;
+
+			if (framesInLoop < 2)
+				frame = 0;
+
+			if (framesInLoop < 1)
+				quitprintf("Unable to render character %d (%s) because there are no frames in loop %d", index_id, name, loop);
+		}
+
+		if (walking < 1) {
+			chex->process_idle_this_time = 1;
+			doing_nothing = 1;
+			walkwait = 0;
+			chex->animwait = 0;
+			// use standing pic
+			Character_StopMoving(this);
+			frame = 0;
+			CheckViewFrameForCharacter(this);
+		} else if (chex->animwait > 0) chex->animwait--;
+		else {
+			if (flags & CHF_ANTIGLIDE)
+				walkwaitcounter++;
+
+			if ((flags & CHF_MOVENOTWALK) == 0) {
+				frame++;
+				if (frame >= views[view].loops[loop].numFrames) {
+					// end of loop, so loop back round skipping the standing frame
+					frame = 1;
+
+					if (views[view].loops[loop].numFrames < 2)
+						frame = 0;
+				}
+
+				chex->animwait = views[view].loops[loop].frames[frame].speed + animspeed;
+
+				if (flags & CHF_ANTIGLIDE)
+					walkwait = chex->animwait;
+				else
+					walkwait = 0;
+
+				CheckViewFrameForCharacter(this);
+			}
+		}
+		doing_nothing = 0;
+	}
 }
 
-int CharacterInfo::update_character_animating(int &aa, int &doing_nothing)
-{
+int CharacterInfo::update_character_animating(int &aa, int &doing_nothing) {
 	// not moving, but animating
-    // idleleft is <0 while idle view is playing (.animating is 0)
-    if (((animating != 0) || (idleleft < 0)) &&
-        ((walking == 0) || ((flags & CHF_MOVENOTWALK) != 0)) &&
-        (room == displayed_room)) 
-    {
-      doing_nothing = 0;
-      // idle anim doesn't count as doing something
-      if (idleleft < 0)
-        doing_nothing = 1;
-
-      if (wait>0) wait--;
-      else if ((char_speaking == aa) && (game.options[OPT_LIPSYNCTEXT] != 0)) {
-        // currently talking with lip-sync speech
-        int fraa = frame;
-        wait = update_lip_sync (view, loop, &fraa) - 1;
-        // closed mouth at end of sentence
-        // NOTE: standard lip-sync is synchronized with text timer, not voice file
-        if (play.speech_in_post_state ||
-            ((play.messagetime >= 0) && (play.messagetime < play.close_mouth_speech_time)))
-          frame = 0;
-
-        if (frame != fraa) {
-          frame = fraa;
-          CheckViewFrameForCharacter(this);
-        }
-        
-        //continue;
-		return RETURN_CONTINUE;
-      }
-      else {
-        int oldframe = frame;
-        if (animating & CHANIM_BACKWARDS) {
-          frame--;
-          if (frame < 0) {
-            // if the previous loop is a Run Next Loop one, go back to it
-            if ((loop > 0) && 
-              (views[view].loops[loop - 1].RunNextLoop())) {
-
-              loop --;
-              frame = views[view].loops[loop].numFrames - 1;
-            }
-            else if (animating & CHANIM_REPEAT) {
-
-              frame = views[view].loops[loop].numFrames - 1;
-
-              while (views[view].loops[loop].RunNextLoop()) {
-                loop++;
-                frame = views[view].loops[loop].numFrames - 1;
-              }
-            }
-            else {
-              frame++;
-              animating = 0;
-            }
-          }
-        }
-        else
-          frame++;
-
-        if ((aa == char_speaking) &&
-             (play.speech_in_post_state ||
-             ((!play.speech_has_voice) &&
-             (play.close_mouth_speech_time > 0) &&
-             (play.messagetime < play.close_mouth_speech_time)))) {
-          // finished talking - stop animation
-          animating = 0;
-          frame = 0;
-        }
-
-        if (frame >= views[view].loops[loop].numFrames) {
-          
-          if (views[view].loops[loop].RunNextLoop()) 
-          {
-            if (loop+1 >= views[view].numLoops)
-              quit("!Animating character tried to overrun last loop in view");
-            loop++;
-            frame=0;
-          }
-          else if ((animating & CHANIM_REPEAT)==0) {
-            animating=0;
-            frame--;
-            // end of idle anim
-            if (idleleft < 0) {
-              // constant anim, reset (need this cos animating==0)
-              if (idletime == 0)
-                frame = 0;
-              // one-off anim, stop
-              else {
-                ReleaseCharacterView(aa);
-                idleleft=idletime;
-              }
-            }
-          }
-          else {
-            frame=0;
-            // if it's a multi-loop animation, go back to start
-            if (play.no_multiloop_repeat == 0) {
-              while ((loop > 0) && 
-                  (views[view].loops[loop - 1].RunNextLoop()))
-                loop--;
-            }
-          }
-        }
-        wait = views[view].loops[loop].frames[frame].speed;
-        // idle anim doesn't have speed stored cos animating==0
-        if (idleleft < 0)
-          wait += animspeed+5;
-        else 
-          wait += (animating >> 8) & 0x00ff;
-
-        if (frame != oldframe)
-          CheckViewFrameForCharacter(this);
-      }
-    }
+	// idleleft is <0 while idle view is playing (.animating is 0)
+	if (((animating != 0) || (idleleft < 0)) &&
+	        ((walking == 0) || ((flags & CHF_MOVENOTWALK) != 0)) &&
+	        (room == displayed_room)) {
+		doing_nothing = 0;
+		// idle anim doesn't count as doing something
+		if (idleleft < 0)
+			doing_nothing = 1;
+
+		if (wait > 0) wait--;
+		else if ((char_speaking == aa) && (game.options[OPT_LIPSYNCTEXT] != 0)) {
+			// currently talking with lip-sync speech
+			int fraa = frame;
+			wait = update_lip_sync(view, loop, &fraa) - 1;
+			// closed mouth at end of sentence
+			// NOTE: standard lip-sync is synchronized with text timer, not voice file
+			if (play.speech_in_post_state ||
+			        ((play.messagetime >= 0) && (play.messagetime < play.close_mouth_speech_time)))
+				frame = 0;
+
+			if (frame != fraa) {
+				frame = fraa;
+				CheckViewFrameForCharacter(this);
+			}
+
+			//continue;
+			return RETURN_CONTINUE;
+		} else {
+			int oldframe = frame;
+			if (animating & CHANIM_BACKWARDS) {
+				frame--;
+				if (frame < 0) {
+					// if the previous loop is a Run Next Loop one, go back to it
+					if ((loop > 0) &&
+					        (views[view].loops[loop - 1].RunNextLoop())) {
+
+						loop --;
+						frame = views[view].loops[loop].numFrames - 1;
+					} else if (animating & CHANIM_REPEAT) {
+
+						frame = views[view].loops[loop].numFrames - 1;
+
+						while (views[view].loops[loop].RunNextLoop()) {
+							loop++;
+							frame = views[view].loops[loop].numFrames - 1;
+						}
+					} else {
+						frame++;
+						animating = 0;
+					}
+				}
+			} else
+				frame++;
+
+			if ((aa == char_speaking) &&
+			        (play.speech_in_post_state ||
+			         ((!play.speech_has_voice) &&
+			          (play.close_mouth_speech_time > 0) &&
+			          (play.messagetime < play.close_mouth_speech_time)))) {
+				// finished talking - stop animation
+				animating = 0;
+				frame = 0;
+			}
+
+			if (frame >= views[view].loops[loop].numFrames) {
+
+				if (views[view].loops[loop].RunNextLoop()) {
+					if (loop + 1 >= views[view].numLoops)
+						quit("!Animating character tried to overrun last loop in view");
+					loop++;
+					frame = 0;
+				} else if ((animating & CHANIM_REPEAT) == 0) {
+					animating = 0;
+					frame--;
+					// end of idle anim
+					if (idleleft < 0) {
+						// constant anim, reset (need this cos animating==0)
+						if (idletime == 0)
+							frame = 0;
+						// one-off anim, stop
+						else {
+							ReleaseCharacterView(aa);
+							idleleft = idletime;
+						}
+					}
+				} else {
+					frame = 0;
+					// if it's a multi-loop animation, go back to start
+					if (play.no_multiloop_repeat == 0) {
+						while ((loop > 0) &&
+						        (views[view].loops[loop - 1].RunNextLoop()))
+							loop--;
+					}
+				}
+			}
+			wait = views[view].loops[loop].frames[frame].speed;
+			// idle anim doesn't have speed stored cos animating==0
+			if (idleleft < 0)
+				wait += animspeed + 5;
+			else
+				wait += (animating >> 8) & 0x00ff;
+
+			if (frame != oldframe)
+				CheckViewFrameForCharacter(this);
+		}
+	}
 
 	return 0;
 }
 
-void CharacterInfo::update_character_follower(int &aa, int &numSheep, int *followingAsSheep, int &doing_nothing)
-{
+void CharacterInfo::update_character_follower(int &aa, int &numSheep, int *followingAsSheep, int &doing_nothing) {
 	if ((following >= 0) && (followinfo == FOLLOW_ALWAYSONTOP)) {
-      // an always-on-top follow
-      if (numSheep >= MAX_SHEEP)
-        quit("too many sheep");
-      followingAsSheep[numSheep] = aa;
-      numSheep++;
-    }
-    // not moving, but should be following another character
-    else if ((following >= 0) && (doing_nothing == 1)) {
-      short distaway=(followinfo >> 8) & 0x00ff;
-      // no character in this room
-      if ((game.chars[following].on == 0) || (on == 0)) ;
-      else if (room < 0) {
-        room ++;
-        if (room == 0) {
-          // appear in the new room
-          room = game.chars[following].room;
-          x = play.entered_at_x;
-          y = play.entered_at_y;
-        }
-      }
-      // wait a bit, so we're not constantly walking
-      else if (Random(100) < (followinfo & 0x00ff)) ;
-      // the followed character has changed room
-      else if ((room != game.chars[following].room)
-            && (game.chars[following].on == 0))
-        ;  // do nothing if the player isn't visible
-      else if (room != game.chars[following].room) {
-        prevroom = room;
-        room = game.chars[following].room;
-
-        if (room == displayed_room) {
-          // only move to the room-entered position if coming into
-          // the current room
-          if (play.entered_at_x > (thisroom.Width - 8)) {
-            x = thisroom.Width+8;
-            y = play.entered_at_y;
-            }
-          else if (play.entered_at_x < 8) {
-            x = -8;
-            y = play.entered_at_y;
-            }
-          else if (play.entered_at_y > (thisroom.Height - 8)) {
-            y = thisroom.Height+8;
-            x = play.entered_at_x;
-            }
-          else if (play.entered_at_y < thisroom.Edges.Top+8) {
-            y = thisroom.Edges.Top+1;
-            x = play.entered_at_x;
-            }
-          else {
-            // not at one of the edges
-            // delay for a few seconds to let the player move
-            room = -play.follow_change_room_timer;
-          }
-          if (room >= 0) {
-            walk_character(aa,play.entered_at_x,play.entered_at_y,1, true);
-            doing_nothing = 0;
-          }
-        }
-      }
-      else if (room != displayed_room) {
-        // if the characetr is following another character and
-        // neither is in the current room, don't try to move
-      }
-      else if ((abs(game.chars[following].x - x) > distaway+30) |
-        (abs(game.chars[following].y - y) > distaway+30) |
-        ((followinfo & 0x00ff) == 0)) {
-        // in same room
-        int goxoffs=(Random(50)-25);
-        // make sure he's not standing on top of the other man
-        if (goxoffs < 0) goxoffs-=distaway;
-        else goxoffs+=distaway;
-        walk_character(aa,game.chars[following].x + goxoffs,
-          game.chars[following].y + (Random(50)-25),0, true);
-        doing_nothing = 0;
-      }
-    }
+		// an always-on-top follow
+		if (numSheep >= MAX_SHEEP)
+			quit("too many sheep");
+		followingAsSheep[numSheep] = aa;
+		numSheep++;
+	}
+	// not moving, but should be following another character
+	else if ((following >= 0) && (doing_nothing == 1)) {
+		short distaway = (followinfo >> 8) & 0x00ff;
+		// no character in this room
+		if ((game.chars[following].on == 0) || (on == 0)) ;
+		else if (room < 0) {
+			room ++;
+			if (room == 0) {
+				// appear in the new room
+				room = game.chars[following].room;
+				x = play.entered_at_x;
+				y = play.entered_at_y;
+			}
+		}
+		// wait a bit, so we're not constantly walking
+		else if (Random(100) < (followinfo & 0x00ff)) ;
+		// the followed character has changed room
+		else if ((room != game.chars[following].room)
+		         && (game.chars[following].on == 0))
+			;  // do nothing if the player isn't visible
+		else if (room != game.chars[following].room) {
+			prevroom = room;
+			room = game.chars[following].room;
+
+			if (room == displayed_room) {
+				// only move to the room-entered position if coming into
+				// the current room
+				if (play.entered_at_x > (thisroom.Width - 8)) {
+					x = thisroom.Width + 8;
+					y = play.entered_at_y;
+				} else if (play.entered_at_x < 8) {
+					x = -8;
+					y = play.entered_at_y;
+				} else if (play.entered_at_y > (thisroom.Height - 8)) {
+					y = thisroom.Height + 8;
+					x = play.entered_at_x;
+				} else if (play.entered_at_y < thisroom.Edges.Top + 8) {
+					y = thisroom.Edges.Top + 1;
+					x = play.entered_at_x;
+				} else {
+					// not at one of the edges
+					// delay for a few seconds to let the player move
+					room = -play.follow_change_room_timer;
+				}
+				if (room >= 0) {
+					walk_character(aa, play.entered_at_x, play.entered_at_y, 1, true);
+					doing_nothing = 0;
+				}
+			}
+		} else if (room != displayed_room) {
+			// if the characetr is following another character and
+			// neither is in the current room, don't try to move
+		} else if ((abs(game.chars[following].x - x) > distaway + 30) |
+		           (abs(game.chars[following].y - y) > distaway + 30) |
+		           ((followinfo & 0x00ff) == 0)) {
+			// in same room
+			int goxoffs = (Random(50) - 25);
+			// make sure he's not standing on top of the other man
+			if (goxoffs < 0) goxoffs -= distaway;
+			else goxoffs += distaway;
+			walk_character(aa, game.chars[following].x + goxoffs,
+			               game.chars[following].y + (Random(50) - 25), 0, true);
+			doing_nothing = 0;
+		}
+	}
 }
 
-void CharacterInfo::update_character_idle(CharacterExtras *chex, int &doing_nothing)
-{
+void CharacterInfo::update_character_idle(CharacterExtras *chex, int &doing_nothing) {
 	// no idle animation, so skip this bit
-    if (idleview < 1) ;
-    // currently playing idle anim
-    else if (idleleft < 0) ;
-    // not in the current room
-    else if (room != displayed_room) ;
-    // they are moving or animating (or the view is locked), so 
-    // reset idle timeout
-    else if ((doing_nothing == 0) || ((flags & CHF_FIXVIEW) != 0))
-      idleleft = idletime;
-    // count idle time
-    else if ((loopcounter%40==0) || (chex->process_idle_this_time == 1)) {
-      idleleft--;
-      if (idleleft == -1) {
-        int useloop=loop;
-        debug_script_log("%s: Now idle (view %d)", scrname, idleview+1);
-		Character_LockView(this, idleview+1);
-        // SetCharView resets it to 0
-        idleleft = -2;
-        int maxLoops = views[idleview].numLoops;
-        // if the char is set to "no diagonal loops", don't try
-        // to use diagonal idle loops either
-        if ((maxLoops > 4) && (useDiagonal(this)))
-          maxLoops = 4;
-        // If it's not a "swimming"-type idleanim, choose a random loop
-        // if there arent enough loops to do the current one.
-        if ((idletime > 0) && (useloop >= maxLoops)) {
-          do {
-            useloop = rand() % maxLoops;
-          // don't select a loop which is a continuation of a previous one
-          } while ((useloop > 0) && (views[idleview].loops[useloop-1].RunNextLoop()));
-        }
-        // Normal idle anim - just reset to loop 0 if not enough to
-        // use the current one
-        else if (useloop >= maxLoops)
-          useloop = 0;
-
-        animate_character(this,useloop,
-          animspeed+5,(idletime == 0) ? 1 : 0, 1);
-
-        // don't set Animating while the idle anim plays
-        animating = 0;
-      }
-    }  // end do idle animation
+	if (idleview < 1) ;
+	// currently playing idle anim
+	else if (idleleft < 0) ;
+	// not in the current room
+	else if (room != displayed_room) ;
+	// they are moving or animating (or the view is locked), so
+	// reset idle timeout
+	else if ((doing_nothing == 0) || ((flags & CHF_FIXVIEW) != 0))
+		idleleft = idletime;
+	// count idle time
+	else if ((loopcounter % 40 == 0) || (chex->process_idle_this_time == 1)) {
+		idleleft--;
+		if (idleleft == -1) {
+			int useloop = loop;
+			debug_script_log("%s: Now idle (view %d)", scrname, idleview + 1);
+			Character_LockView(this, idleview + 1);
+			// SetCharView resets it to 0
+			idleleft = -2;
+			int maxLoops = views[idleview].numLoops;
+			// if the char is set to "no diagonal loops", don't try
+			// to use diagonal idle loops either
+			if ((maxLoops > 4) && (useDiagonal(this)))
+				maxLoops = 4;
+			// If it's not a "swimming"-type idleanim, choose a random loop
+			// if there arent enough loops to do the current one.
+			if ((idletime > 0) && (useloop >= maxLoops)) {
+				do {
+					useloop = rand() % maxLoops;
+					// don't select a loop which is a continuation of a previous one
+				} while ((useloop > 0) && (views[idleview].loops[useloop - 1].RunNextLoop()));
+			}
+			// Normal idle anim - just reset to loop 0 if not enough to
+			// use the current one
+			else if (useloop >= maxLoops)
+				useloop = 0;
+
+			animate_character(this, useloop,
+			                  animspeed + 5, (idletime == 0) ? 1 : 0, 1);
+
+			// don't set Animating while the idle anim plays
+			animating = 0;
+		}
+	}  // end do idle animation
 }
diff --git a/engines/ags/engine/ac/datetime.cpp b/engines/ags/engine/ac/datetime.cpp
index e11d967b74..a4874cb45d 100644
--- a/engines/ags/engine/ac/datetime.cpp
+++ b/engines/ags/engine/ac/datetime.cpp
@@ -25,46 +25,46 @@
 #include "platform/base/agsplatformdriver.h"
 #include "script/runtimescriptvalue.h"
 
-ScriptDateTime* DateTime_Now_Core() {
-    ScriptDateTime *sdt = new ScriptDateTime();
+ScriptDateTime *DateTime_Now_Core() {
+	ScriptDateTime *sdt = new ScriptDateTime();
 
-    platform->GetSystemTime(sdt);
+	platform->GetSystemTime(sdt);
 
-    return sdt;
+	return sdt;
 }
 
-ScriptDateTime* DateTime_Now() {
-    ScriptDateTime *sdt = DateTime_Now_Core();
-    ccRegisterManagedObject(sdt, sdt);
-    return sdt;
+ScriptDateTime *DateTime_Now() {
+	ScriptDateTime *sdt = DateTime_Now_Core();
+	ccRegisterManagedObject(sdt, sdt);
+	return sdt;
 }
 
 int DateTime_GetYear(ScriptDateTime *sdt) {
-    return sdt->year;
+	return sdt->year;
 }
 
 int DateTime_GetMonth(ScriptDateTime *sdt) {
-    return sdt->month;
+	return sdt->month;
 }
 
 int DateTime_GetDayOfMonth(ScriptDateTime *sdt) {
-    return sdt->day;
+	return sdt->day;
 }
 
 int DateTime_GetHour(ScriptDateTime *sdt) {
-    return sdt->hour;
+	return sdt->hour;
 }
 
 int DateTime_GetMinute(ScriptDateTime *sdt) {
-    return sdt->minute;
+	return sdt->minute;
 }
 
 int DateTime_GetSecond(ScriptDateTime *sdt) {
-    return sdt->second;
+	return sdt->second;
 }
 
 int DateTime_GetRawTime(ScriptDateTime *sdt) {
-    return sdt->rawUnixTime;
+	return sdt->rawUnixTime;
 }
 
 //=============================================================================
@@ -78,72 +78,63 @@ int DateTime_GetRawTime(ScriptDateTime *sdt) {
 #include "script/script_runtime.h"
 
 // ScriptDateTime* ()
-RuntimeScriptValue Sc_DateTime_Now(const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_SCALL_OBJAUTO(ScriptDateTime, DateTime_Now);
+RuntimeScriptValue Sc_DateTime_Now(const RuntimeScriptValue *params, int32_t param_count) {
+	API_SCALL_OBJAUTO(ScriptDateTime, DateTime_Now);
 }
 
 // int (ScriptDateTime *sdt)
-RuntimeScriptValue Sc_DateTime_GetYear(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(ScriptDateTime, DateTime_GetYear);
+RuntimeScriptValue Sc_DateTime_GetYear(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(ScriptDateTime, DateTime_GetYear);
 }
 
 // int (ScriptDateTime *sdt)
-RuntimeScriptValue Sc_DateTime_GetMonth(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(ScriptDateTime, DateTime_GetMonth);
+RuntimeScriptValue Sc_DateTime_GetMonth(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(ScriptDateTime, DateTime_GetMonth);
 }
 
 // int (ScriptDateTime *sdt)
-RuntimeScriptValue Sc_DateTime_GetDayOfMonth(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(ScriptDateTime, DateTime_GetDayOfMonth);
+RuntimeScriptValue Sc_DateTime_GetDayOfMonth(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(ScriptDateTime, DateTime_GetDayOfMonth);
 }
 
 // int (ScriptDateTime *sdt)
-RuntimeScriptValue Sc_DateTime_GetHour(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(ScriptDateTime, DateTime_GetHour);
+RuntimeScriptValue Sc_DateTime_GetHour(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(ScriptDateTime, DateTime_GetHour);
 }
 
 // int (ScriptDateTime *sdt)
-RuntimeScriptValue Sc_DateTime_GetMinute(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(ScriptDateTime, DateTime_GetMinute);
+RuntimeScriptValue Sc_DateTime_GetMinute(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(ScriptDateTime, DateTime_GetMinute);
 }
 
 // int (ScriptDateTime *sdt)
-RuntimeScriptValue Sc_DateTime_GetSecond(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(ScriptDateTime, DateTime_GetSecond);
+RuntimeScriptValue Sc_DateTime_GetSecond(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(ScriptDateTime, DateTime_GetSecond);
 }
 
 // int (ScriptDateTime *sdt)
-RuntimeScriptValue Sc_DateTime_GetRawTime(void *self, const RuntimeScriptValue *params, int32_t param_count)
-{
-    API_OBJCALL_INT(ScriptDateTime, DateTime_GetRawTime);
-}
-
-void RegisterDateTimeAPI()
-{
-    ccAddExternalStaticFunction("DateTime::get_Now",        Sc_DateTime_Now);
-    ccAddExternalObjectFunction("DateTime::get_DayOfMonth", Sc_DateTime_GetDayOfMonth);
-    ccAddExternalObjectFunction("DateTime::get_Hour",       Sc_DateTime_GetHour);
-    ccAddExternalObjectFunction("DateTime::get_Minute",     Sc_DateTime_GetMinute);
-    ccAddExternalObjectFunction("DateTime::get_Month",      Sc_DateTime_GetMonth);
-    ccAddExternalObjectFunction("DateTime::get_RawTime",    Sc_DateTime_GetRawTime);
-    ccAddExternalObjectFunction("DateTime::get_Second",     Sc_DateTime_GetSecond);
-    ccAddExternalObjectFunction("DateTime::get_Year",       Sc_DateTime_GetYear);
-
-    /* ----------------------- Registering unsafe exports for plugins -----------------------*/
-
-    ccAddExternalFunctionForPlugin("DateTime::get_Now",        (void*)DateTime_Now);
-    ccAddExternalFunctionForPlugin("DateTime::get_DayOfMonth", (void*)DateTime_GetDayOfMonth);
-    ccAddExternalFunctionForPlugin("DateTime::get_Hour",       (void*)DateTime_GetHour);
-    ccAddExternalFunctionForPlugin("DateTime::get_Minute",     (void*)DateTime_GetMinute);
-    ccAddExternalFunctionForPlugin("DateTime::get_Month",      (void*)DateTime_GetMonth);
-    ccAddExternalFunctionForPlugin("DateTime::get_RawTime",    (void*)DateTime_GetRawTime);
-    ccAddExternalFunctionForPlugin("DateTime::get_Second",     (void*)DateTime_GetSecond);
-    ccAddExternalFunctionForPlugin("DateTime::get_Year",       (void*)DateTime_GetYear);
+RuntimeScriptValue Sc_DateTime_GetRawTime(void *self, const RuntimeScriptValue *params, int32_t param_count) {
+	API_OBJCALL_INT(ScriptDateTime, DateTime_GetRawTime);
+}
+
+void RegisterDateTimeAPI() {
+	ccAddExternalStaticFunction("DateTime::get_Now",        Sc_DateTime_Now);
+	ccAddExternalObjectFunction("DateTime::get_DayOfMonth", Sc_DateTime_GetDayOfMonth);
+	ccAddExternalObjectFunction("DateTime::get_Hour",       Sc_DateTime_GetHour);
+	ccAddExternalObjectFunction("DateTime::get_Minute",     Sc_DateTime_GetMinute);
+	ccAddExternalObjectFunction("DateTime::get_Month",      Sc_DateTime_GetMonth);
+	ccAddExternalObjectFunction("DateTime::get_RawTime",    Sc_DateTime_GetRawTime);
+	ccAddExternalObjectFunction("DateTime::get_Second",     Sc_DateTime_GetSecond);
+	ccAddExternalObjectFunction("DateTime::get_Year",       Sc_DateTime_GetYear);
+
+	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
+
+	ccAddExternalFunctionForPlugin("DateTime::get_Now", (void *)DateTime_Now);
+	ccAddExternalFunctionForPlugin("DateTime::get_DayOfMonth", (void *)DateTime_GetDayOfMonth);
+	ccAddExternalFunctionForPlugin("DateTime::get_Hour", (void *)DateTime_GetHour);
+	ccAddExternalFunctionForPlugin("DateTime::get_Minute", (void *)DateTime_GetMinute);
+	ccAddExternalFunctionForPlugin("DateTime::get_Month", (void *)DateTime_GetMonth);
+	ccAddExternalFunctionForPlugin("DateTime::get_RawTime", (void *)DateTime_GetRawTime);
+	ccAddExternalFunctionForPlugin("DateTime::get_Second", (void *)DateTime_GetSecond);
+	ccAddExternalFunctionForPlugin("DateTime::get_Year", (void *)DateTime_GetYear);
 }
diff --git a/engines/ags/engine/ac/datetime.h b/engines/ags/engine/ac/datetime.h
index 612870825f..96b922a306 100644
--- a/engines/ags/engine/ac/datetime.h
+++ b/engines/ags/engine/ac/datetime.h
@@ -25,8 +25,8 @@
 
 #include "ac/dynobj/scriptdatetime.h"
 
-ScriptDateTime* DateTime_Now_Core();
-ScriptDateTime* DateTime_Now();
+ScriptDateTime *DateTime_Now_Core();
+ScriptDateTime *DateTime_Now();
 int             DateTime_GetYear(ScriptDateTime *sdt);
 int             DateTime_GetMonth(ScriptDateTime *sdt);
 int             DateTime_GetDayOfMonth(ScriptDateTime *sdt);
diff --git a/engines/ags/engine/ac/dialog.cpp b/engines/ags/engine/ac/dialog.cpp
index 4cf2f530bf..5b2a85f675 100644
--- a/engines/ags/engine/ac/dialog.cpp
+++ b/engines/ags/engine/ac/dialog.cpp
@@ -66,15 +66,15 @@ extern GameSetupStruct game;
 extern GameState play;
 extern ccInstance *dialogScriptsInst;
 extern int in_new_room;
-extern CharacterInfo*playerchar;
+extern CharacterInfo *playerchar;
 extern SpriteCache spriteset;
 extern AGSPlatformDriver *platform;
-extern int cur_mode,cur_cursor;
+extern int cur_mode, cur_cursor;
 extern IGraphicsDriver *gfxDriver;
 
 DialogTopic *dialog;
 ScriptDialogOptionsRendering ccDialogOptionsRendering;
-ScriptDrawingSurface* dialogOptionsRenderingSurface;
+ScriptDrawingSurface *dialogOptionsRenderingSurface;
 
 int said_speech_line; // used while in dialog to track whether screen needs updating
 
@@ -89,85 +89,74 @@ int longestline = 0;
 
 
 void Dialog_Start(ScriptDialog *sd) {
-  RunDialog(sd->id);
+	RunDialog(sd->id);
 }
 
 #define CHOSE_TEXTPARSER -3053
 #define SAYCHOSEN_USEFLAG 1
 #define SAYCHOSEN_YES 2
-#define SAYCHOSEN_NO  3 
-
-int Dialog_DisplayOptions(ScriptDialog *sd, int sayChosenOption)
-{
-  if ((sayChosenOption < 1) || (sayChosenOption > 3))
-    quit("!Dialog.DisplayOptions: invalid parameter passed");
-
-  int chose = show_dialog_options(sd->id, sayChosenOption, (game.options[OPT_RUNGAMEDLGOPTS] != 0));
-  if (chose != CHOSE_TEXTPARSER)
-  {
-    chose++;
-  }
-  return chose;
+#define SAYCHOSEN_NO  3
+
+int Dialog_DisplayOptions(ScriptDialog *sd, int sayChosenOption) {
+	if ((sayChosenOption < 1) || (sayChosenOption > 3))
+		quit("!Dialog.DisplayOptions: invalid parameter passed");
+
+	int chose = show_dialog_options(sd->id, sayChosenOption, (game.options[OPT_RUNGAMEDLGOPTS] != 0));
+	if (chose != CHOSE_TEXTPARSER) {
+		chose++;
+	}
+	return chose;
 }
 
 void Dialog_SetOptionState(ScriptDialog *sd, int option, int newState) {
-  SetDialogOption(sd->id, option, newState);
+	SetDialogOption(sd->id, option, newState);
 }
 
 int Dialog_GetOptionState(ScriptDialog *sd, int option) {
-  return GetDialogOption(sd->id, option);
+	return GetDialogOption(sd->id, option);
 }
 
-int Dialog_HasOptionBeenChosen(ScriptDialog *sd, int option)
-{
-  if ((option < 1) || (option > dialog[sd->id].numoptions))
-    quit("!Dialog.HasOptionBeenChosen: Invalid option number specified");
-  option--;
+int Dialog_HasOptionBeenChosen(ScriptDialog *sd, int option) {
+	if ((option < 1) || (option > dialog[sd->id].numoptions))
+		quit("!Dialog.HasOptionBeenChosen: Invalid option number specified");
+	option--;
 
-  if (dialog[sd->id].optionflags[option] & DFLG_HASBEENCHOSEN)
-    return 1;
-  return 0;
+	if (dialog[sd->id].optionflags[option] & DFLG_HASBEENCHOSEN)
+		return 1;
+	return 0;
 }
 
-void Dialog_SetHasOptionBeenChosen(ScriptDialog *sd, int option, bool chosen)
-{
-    if (option < 1 || option > dialog[sd->id].numoptions)
-    {
-        quit("!Dialog.HasOptionBeenChosen: Invalid option number specified");
-    }
-    option--;
-    if (chosen)
-    {
-        dialog[sd->id].optionflags[option] |= DFLG_HASBEENCHOSEN;
-    }
-    else
-    {
-        dialog[sd->id].optionflags[option] &= ~DFLG_HASBEENCHOSEN;
-    }
+void Dialog_SetHasOptionBeenChosen(ScriptDialog *sd, int option, bool chosen) {
+	if (option < 1 || option > dialog[sd->id].numoptions) {
+		quit("!Dialog.HasOptionBeenChosen: Invalid option number specified");
+	}
+	option--;
+	if (chosen) {
+		dialog[sd->id].optionflags[option] |= DFLG_HASBEENCHOSEN;
+	} else {
+		dialog[sd->id].optionflags[option] &= ~DFLG_HASBEENCHOSEN;
+	}
 }
 
-int Dialog_GetOptionCount(ScriptDialog *sd)
-{
-  return dialog[sd->id].numoptions;
+int Dialog_GetOptionCount(ScriptDialog *sd) {
+	return dialog[sd->id].numoptions;
 }
 
-int Dialog_GetShowTextParser(ScriptDialog *sd)
-{
-  return (dialog[sd->id].topicFlags & DTFLG_SHOWPARSER) ? 1 : 0;
+int Dialog_GetShowTextParser(ScriptDialog *sd) {
+	return (dialog[sd->id].topicFlags & DTFLG_SHOWPARSER) ? 1 : 0;
 }
 
-const char* Dialog_GetOptionText(ScriptDialog *sd, int option)
-{
-  if ((option < 1) || (option > dialog[sd->id].numoptions))
-    quit("!Dialog.GetOptionText: Invalid option number specified");
+const char *Dialog_GetOptionText(ScriptDialog *sd, int option) {
+	if ((option < 1) || (option > dialog[sd->id].numoptions))
+		quit("!Dialog.GetOptionText: Invalid option number specified");
 
-  option--;
+	option--;
 
-  return CreateNewScriptString(get_translation(dialog[sd->id].optionnames[option]));
+	return CreateNewScriptString(get_translation(dialog[sd->id].optionnames[option]));
 }
 
 int Dialog_GetID(ScriptDialog *sd) {
-  return sd->id;
+	return sd->id;
 }
 
 //=============================================================================
@@ -177,1056 +166,974 @@ int Dialog_GetID(ScriptDialog *sd) {
 #define RUN_DIALOG_GOTO_PREVIOUS -4
 // dialog manager stuff
 
-void get_dialog_script_parameters(unsigned char* &script, unsigned short* param1, unsigned short* param2)
-{
-  script++;
-  *param1 = *script;
-  script++;
-  *param1 += *script * 256;
-  script++;
-  
-  if (param2)
-  {
-    *param2 = *script;
-    script++;
-    *param2 += *script * 256;
-    script++;
-  }
+void get_dialog_script_parameters(unsigned char *&script, unsigned short *param1, unsigned short *param2) {
+	script++;
+	*param1 = *script;
+	script++;
+	*param1 += *script * 256;
+	script++;
+
+	if (param2) {
+		*param2 = *script;
+		script++;
+		*param2 += *script * 256;
+		script++;
+	}
 }
 
-int run_dialog_script(DialogTopic*dtpp, int dialogID, int offse, int optionIndex) {
-  said_speech_line = 0;
-  int result = RUN_DIALOG_STAY;
-
-  if (dialogScriptsInst)
-  {
-    char funcName[100];
-    sprintf(funcName, "_run_dialog%d", dialogID);
-    RunTextScriptIParam(dialogScriptsInst, funcName, RuntimeScriptValue().SetInt32(optionIndex));
-    result = dialogScriptsInst->returnValue;
-  }
-  else
-  {
-    // old dialog format
-    if (offse == -1)
-      return result;	
-	
-    unsigned char* script = old_dialog_scripts[dialogID].get() + offse;
-
-    unsigned short param1 = 0;
-    unsigned short param2 = 0;
-    bool script_running = true;
-
-    while (script_running)
-    {
-      switch (*script)
-      {
-        case DCMD_SAY:
-          get_dialog_script_parameters(script, &param1, &param2);
-          
-          if (param1 == DCHAR_PLAYER)
-            param1 = game.playercharacter;
-
-          if (param1 == DCHAR_NARRATOR)
-            Display(get_translation(old_speech_lines[param2]));
-          else
-            DisplaySpeech(get_translation(old_speech_lines[param2]), param1);
-
-          said_speech_line = 1;
-          break;
-
-        case DCMD_OPTOFF:
-          get_dialog_script_parameters(script, &param1, nullptr);
-          SetDialogOption(dialogID, param1 + 1, 0, true);
-          break;
-
-        case DCMD_OPTON:
-          get_dialog_script_parameters(script, &param1, nullptr);
-          SetDialogOption(dialogID, param1 + 1, DFLG_ON, true);
-          break;
-
-        case DCMD_RETURN:
-          script_running = false;
-          break;
-
-        case DCMD_STOPDIALOG:
-          result = RUN_DIALOG_STOP_DIALOG;
-          script_running = false;
-          break;
-
-        case DCMD_OPTOFFFOREVER:
-          get_dialog_script_parameters(script, &param1, nullptr);
-          SetDialogOption(dialogID, param1 + 1, DFLG_OFFPERM, true);
-          break;
-
-        case DCMD_RUNTEXTSCRIPT:
-          get_dialog_script_parameters(script, &param1, nullptr);
-          result = run_dialog_request(param1);
-          script_running = (result == RUN_DIALOG_STAY);
-          break;
-
-        case DCMD_GOTODIALOG:
-          get_dialog_script_parameters(script, &param1, nullptr);
-          result = param1;
-          script_running = false;
-          break;
-
-        case DCMD_PLAYSOUND:
-          get_dialog_script_parameters(script, &param1, nullptr);
-          play_sound(param1);
-          break;
-
-        case DCMD_ADDINV:
-          get_dialog_script_parameters(script, &param1, nullptr);
-          add_inventory(param1);
-          break;
-
-        case DCMD_SETSPCHVIEW:
-          get_dialog_script_parameters(script, &param1, &param2);
-          SetCharacterSpeechView(param1, param2);
-          break;
-
-        case DCMD_NEWROOM:
-          get_dialog_script_parameters(script, &param1, nullptr);
-          NewRoom(param1);
-          in_new_room = 1;
-          result = RUN_DIALOG_STOP_DIALOG;
-          script_running = false;
-          break;
-
-        case DCMD_SETGLOBALINT:
-          get_dialog_script_parameters(script, &param1, &param2);
-          SetGlobalInt(param1, param2);
-          break;
-
-        case DCMD_GIVESCORE:
-          get_dialog_script_parameters(script, &param1, nullptr);
-          GiveScore(param1);
-          break;
-
-        case DCMD_GOTOPREVIOUS:
-          result = RUN_DIALOG_GOTO_PREVIOUS;
-          script_running = false;
-          break;
-
-        case DCMD_LOSEINV:
-          get_dialog_script_parameters(script, &param1, nullptr);
-          lose_inventory(param1);
-          break;
-
-        case DCMD_ENDSCRIPT:
-          result = RUN_DIALOG_STOP_DIALOG;
-          script_running = false;
-          break;
-      }
-    }
-  }
-
-  if (in_new_room > 0)
-    return RUN_DIALOG_STOP_DIALOG;
-
-  if (said_speech_line > 0) {
-    // the line below fixes the problem with the close-up face remaining on the
-    // screen after they finish talking; however, it makes the dialog options
-    // area flicker when going between topics.
-    DisableInterface();
-    UpdateGameOnce(); // redraw the screen to make sure it looks right
-    EnableInterface();
-    // if we're not about to abort the dialog, switch back to arrow
-    if (result != RUN_DIALOG_STOP_DIALOG)
-      set_mouse_cursor(CURS_ARROW);
-  }
-
-  return result;
+int run_dialog_script(DialogTopic *dtpp, int dialogID, int offse, int optionIndex) {
+	said_speech_line = 0;
+	int result = RUN_DIALOG_STAY;
+
+	if (dialogScriptsInst) {
+		char funcName[100];
+		sprintf(funcName, "_run_dialog%d", dialogID);
+		RunTextScriptIParam(dialogScriptsInst, funcName, RuntimeScriptValue().SetInt32(optionIndex));
+		result = dialogScriptsInst->returnValue;
+	} else {
+		// old dialog format
+		if (offse == -1)
+			return result;
+
+		unsigned char *script = old_dialog_scripts[dialogID].get() + offse;
+
+		unsigned short param1 = 0;
+		unsigned short param2 = 0;
+		bool script_running = true;
+
+		while (script_running) {
+			switch (*script) {
+			case DCMD_SAY:
+				get_dialog_script_parameters(script, &param1, &param2);
+
+				if (param1 == DCHAR_PLAYER)
+					param1 = game.playercharacter;
+
+				if (param1 == DCHAR_NARRATOR)
+					Display(get_translation(old_speech_lines[param2]));
+				else
+					DisplaySpeech(get_translation(old_speech_lines[param2]), param1);
+
+				said_speech_line = 1;
+				break;
+
+			case DCMD_OPTOFF:
+				get_dialog_script_parameters(script, &param1, nullptr);
+				SetDialogOption(dialogID, param1 + 1, 0, true);
+				break;
+
+			case DCMD_OPTON:
+				get_dialog_script_parameters(script, &param1, nullptr);
+				SetDialogOption(dialogID, param1 + 1, DFLG_ON, true);
+				break;
+
+			case DCMD_RETURN:
+				script_running = false;
+				break;
+
+			case DCMD_STOPDIALOG:
+				result = RUN_DIALOG_STOP_DIALOG;
+				script_running = false;
+				break;
+
+			case DCMD_OPTOFFFOREVER:
+				get_dialog_script_parameters(script, &param1, nullptr);
+				SetDialogOption(dialogID, param1 + 1, DFLG_OFFPERM, true);
+				break;
+
+			case DCMD_RUNTEXTSCRIPT:
+				get_dialog_script_parameters(script, &param1, nullptr);
+				result = run_dialog_request(param1);
+				script_running = (result == RUN_DIALOG_STAY);
+				break;
+
+			case DCMD_GOTODIALOG:
+				get_dialog_script_parameters(script, &param1, nullptr);
+				result = param1;
+				script_running = false;
+				break;
+
+			case DCMD_PLAYSOUND:
+				get_dialog_script_parameters(script, &param1, nullptr);
+				play_sound(param1);
+				break;
+
+			case DCMD_ADDINV:
+				get_dialog_script_parameters(script, &param1, nullptr);
+				add_inventory(param1);
+				break;
+
+			case DCMD_SETSPCHVIEW:
+				get_dialog_script_parameters(script, &param1, &param2);
+				SetCharacterSpeechView(param1, param2);
+				break;
+
+			case DCMD_NEWROOM:
+				get_dialog_script_parameters(script, &param1, nullptr);
+				NewRoom(param1);
+				in_new_room = 1;
+				result = RUN_DIALOG_STOP_DIALOG;
+				script_running = false;
+				break;
+
+			case DCMD_SETGLOBALINT:
+				get_dialog_script_parameters(script, &param1, &param2);
+				SetGlobalInt(param1, param2);
+				break;
+
+			case DCMD_GIVESCORE:
+				get_dialog_script_parameters(script, &param1, nullptr);
+				GiveScore(param1);
+				break;
+
+			case DCMD_GOTOPREVIOUS:
+				result = RUN_DIALOG_GOTO_PREVIOUS;
+				script_running = false;
+				break;
+
+			case DCMD_LOSEINV:
+				get_dialog_script_parameters(script, &param1, nullptr);
+				lose_inventory(param1);
+				break;
+
+			case DCMD_ENDSCRIPT:
+				result = RUN_DIALOG_STOP_DIALOG;
+				script_running = false;
+				break;
+			}
+		}
+	}
+
+	if (in_new_room > 0)
+		return RUN_DIALOG_STOP_DIALOG;
+
+	if (said_speech_line > 0) {
+		// the line below fixes the problem with the close-up face remaining on the
+		// screen after they finish talking; however, it makes the dialog options
+		// area flicker when going between topics.
+		DisableInterface();
+		UpdateGameOnce(); // redraw the screen to make sure it looks right
+		EnableInterface();
+		// if we're not about to abort the dialog, switch back to arrow
+		if (result != RUN_DIALOG_STOP_DIALOG)
+			set_mouse_cursor(CURS_ARROW);
+	}
+
+	return result;
 }
 
 int write_dialog_options(Bitmap *ds, bool ds_has_alpha, int dlgxp, int curyp, int numdisp, int mouseison, int areawid,
-    int bullet_wid, int usingfont, DialogTopic*dtop, char*disporder, short*dispyp,
-    int linespacing, int utextcol, int padding) {
-  int ww;
-
-  color_t text_color;
-  for (ww=0;ww<numdisp;ww++) {
-
-    if ((dtop->optionflags[disporder[ww]] & DFLG_HASBEENCHOSEN) &&
-        (play.read_dialog_option_colour >= 0)) {
-      // 'read' colour
-      text_color = ds->GetCompatibleColor(play.read_dialog_option_colour);
-    }
-    else {
-      // 'unread' colour
-      text_color = ds->GetCompatibleColor(playerchar->talkcolor);
-    }
-
-    if (mouseison==ww) {
-      if (text_color == ds->GetCompatibleColor(utextcol))
-        text_color = ds->GetCompatibleColor(13); // the normal colour is the same as highlight col
-      else text_color = ds->GetCompatibleColor(utextcol);
-    }
-
-    break_up_text_into_lines(get_translation(dtop->optionnames[disporder[ww]]), Lines, areawid-(2*padding+2+bullet_wid), usingfont);
-    dispyp[ww]=curyp;
-    if (game.dialog_bullet > 0)
-    {
-        draw_gui_sprite_v330(ds, game.dialog_bullet, dlgxp, curyp, ds_has_alpha);
-    }
-    if (game.options[OPT_DIALOGNUMBERED] == kDlgOptNumbering) {
-      char tempbfr[20];
-      int actualpicwid = 0;
-      if (game.dialog_bullet > 0)
-        actualpicwid = game.SpriteInfos[game.dialog_bullet].Width+3;
-
-      sprintf (tempbfr, "%d.", ww + 1);
-      wouttext_outline (ds, dlgxp + actualpicwid, curyp, usingfont, text_color, tempbfr);
-    }
-    for (size_t cc=0;cc<Lines.Count();cc++) {
-      wouttext_outline(ds, dlgxp+((cc==0) ? 0 : 9)+bullet_wid, curyp, usingfont, text_color, Lines[cc]);
-      curyp+=linespacing;
-    }
-    if (ww < numdisp-1)
-      curyp += data_to_game_coord(game.options[OPT_DIALOGGAP]);
-  }
-  return curyp;
+                         int bullet_wid, int usingfont, DialogTopic *dtop, char *disporder, short *dispyp,
+                         int linespacing, int utextcol, int padding) {
+	int ww;
+
+	color_t text_color;
+	for (ww = 0; ww < numdisp; ww++) {


Commit: 76a2e9036669144288733df72756f7bdafac02cf
    https://github.com/scummvm/scummvm/commit/76a2e9036669144288733df72756f7bdafac02cf
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Wrapping headers in an AGS3 namespace

Changed paths:
    engines/ags/engine/ac/asset_helper.h
    engines/ags/engine/ac/audiochannel.h
    engines/ags/engine/ac/audioclip.h
    engines/ags/engine/ac/button.h
    engines/ags/engine/ac/cdaudio.h
    engines/ags/engine/ac/character.h
    engines/ags/engine/ac/charactercache.h
    engines/ags/engine/ac/characterextras.h
    engines/ags/engine/ac/datetime.h
    engines/ags/engine/ac/dialog.h
    engines/ags/engine/ac/dialogoptionsrendering.h
    engines/ags/engine/ac/display.h
    engines/ags/engine/ac/draw.h
    engines/ags/engine/ac/draw_software.h
    engines/ags/engine/ac/drawingsurface.h
    engines/ags/engine/ac/dynamicsprite.h
    engines/ags/engine/ac/dynobj/cc_agsdynamicobject.h
    engines/ags/engine/ac/dynobj/cc_audiochannel.h
    engines/ags/engine/ac/dynobj/cc_audioclip.h
    engines/ags/engine/ac/dynobj/cc_character.h
    engines/ags/engine/ac/dynobj/cc_dialog.h
    engines/ags/engine/ac/dynobj/cc_dynamicarray.h
    engines/ags/engine/ac/dynobj/cc_dynamicobject.h
    engines/ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h
    engines/ags/engine/ac/dynobj/cc_gui.h
    engines/ags/engine/ac/dynobj/cc_guiobject.h
    engines/ags/engine/ac/dynobj/cc_hotspot.h
    engines/ags/engine/ac/dynobj/cc_inventory.h
    engines/ags/engine/ac/dynobj/cc_object.h
    engines/ags/engine/ac/dynobj/cc_region.h
    engines/ags/engine/ac/dynobj/cc_serializer.h
    engines/ags/engine/ac/dynobj/managedobjectpool.h
    engines/ags/engine/ac/dynobj/scriptaudiochannel.h
    engines/ags/engine/ac/dynobj/scriptcamera.h
    engines/ags/engine/ac/dynobj/scriptcontainers.h
    engines/ags/engine/ac/dynobj/scriptdatetime.h
    engines/ags/engine/ac/dynobj/scriptdialog.h
    engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.h
    engines/ags/engine/ac/dynobj/scriptdict.h
    engines/ags/engine/ac/dynobj/scriptdrawingsurface.h
    engines/ags/engine/ac/dynobj/scriptdynamicsprite.h
    engines/ags/engine/ac/dynobj/scriptfile.h
    engines/ags/engine/ac/dynobj/scriptgui.h
    engines/ags/engine/ac/dynobj/scripthotspot.h
    engines/ags/engine/ac/dynobj/scriptinvitem.h
    engines/ags/engine/ac/dynobj/scriptmouse.h
    engines/ags/engine/ac/dynobj/scriptobject.h
    engines/ags/engine/ac/dynobj/scriptoverlay.h
    engines/ags/engine/ac/dynobj/scriptregion.h
    engines/ags/engine/ac/dynobj/scriptset.h
    engines/ags/engine/ac/dynobj/scriptstring.h
    engines/ags/engine/ac/dynobj/scriptsystem.h
    engines/ags/engine/ac/dynobj/scriptuserobject.h
    engines/ags/engine/ac/dynobj/scriptviewframe.h
    engines/ags/engine/ac/dynobj/scriptviewport.h
    engines/ags/engine/ac/event.h
    engines/ags/engine/ac/file.h
    engines/ags/engine/ac/game.h
    engines/ags/engine/ac/gamesetup.h
    engines/ags/engine/ac/gamestate.h
    engines/ags/engine/ac/global_audio.h
    engines/ags/engine/ac/global_button.h
    engines/ags/engine/ac/global_character.h
    engines/ags/engine/ac/global_datetime.h
    engines/ags/engine/ac/global_debug.h
    engines/ags/engine/ac/global_dialog.h
    engines/ags/engine/ac/global_display.h
    engines/ags/engine/ac/global_drawingsurface.h
    engines/ags/engine/ac/global_dynamicsprite.h
    engines/ags/engine/ac/global_file.h
    engines/ags/engine/ac/global_game.h
    engines/ags/engine/ac/global_gui.h
    engines/ags/engine/ac/global_hotspot.h
    engines/ags/engine/ac/global_inventoryitem.h
    engines/ags/engine/ac/global_invwindow.h
    engines/ags/engine/ac/global_label.h
    engines/ags/engine/ac/global_listbox.h
    engines/ags/engine/ac/global_mouse.h
    engines/ags/engine/ac/global_object.h
    engines/ags/engine/ac/global_overlay.h
    engines/ags/engine/ac/global_palette.h
    engines/ags/engine/ac/global_parser.h
    engines/ags/engine/ac/global_plugin.h
    engines/ags/engine/ac/global_record.h
    engines/ags/engine/ac/global_region.h
    engines/ags/engine/ac/global_room.h
    engines/ags/engine/ac/global_screen.h
    engines/ags/engine/ac/global_slider.h
    engines/ags/engine/ac/global_string.h
    engines/ags/engine/ac/global_textbox.h
    engines/ags/engine/ac/global_timer.h
    engines/ags/engine/ac/global_translation.h
    engines/ags/engine/ac/global_video.h
    engines/ags/engine/ac/global_viewframe.h
    engines/ags/engine/ac/global_viewport.h
    engines/ags/engine/ac/global_walkablearea.h
    engines/ags/engine/ac/global_walkbehind.h
    engines/ags/engine/ac/gui.h
    engines/ags/engine/ac/guicontrol.h
    engines/ags/engine/ac/hotspot.h
    engines/ags/engine/ac/inventoryitem.h
    engines/ags/engine/ac/invwindow.h
    engines/ags/engine/ac/keycode.h
    engines/ags/engine/ac/label.h
    engines/ags/engine/ac/lipsync.h
    engines/ags/engine/ac/listbox.h
    engines/ags/engine/ac/math.h
    engines/ags/engine/ac/mouse.h
    engines/ags/engine/ac/movelist.h
    engines/ags/engine/ac/object.h
    engines/ags/engine/ac/objectcache.h
    engines/ags/engine/ac/overlay.h
    engines/ags/engine/ac/parser.h
    engines/ags/engine/ac/path_helper.h
    engines/ags/engine/ac/properties.h
    engines/ags/engine/ac/region.h
    engines/ags/engine/ac/richgamemedia.h
    engines/ags/engine/ac/room.h
    engines/ags/engine/ac/roomobject.h
    engines/ags/engine/ac/roomstatus.h
    engines/ags/engine/ac/route_finder.h
    engines/ags/engine/ac/route_finder_impl.h
    engines/ags/engine/ac/route_finder_impl_legacy.h
    engines/ags/engine/ac/runtime_defines.h
    engines/ags/engine/ac/screen.h
    engines/ags/engine/ac/screenoverlay.h
    engines/ags/engine/ac/slider.h
    engines/ags/engine/ac/speech.h
    engines/ags/engine/ac/sprite.h
    engines/ags/engine/ac/spritelistentry.h
    engines/ags/engine/ac/statobj/agsstaticobject.h
    engines/ags/engine/ac/statobj/staticarray.h
    engines/ags/engine/ac/statobj/staticobject.h
    engines/ags/engine/ac/string.h
    engines/ags/engine/ac/sys_events.h
    engines/ags/engine/ac/system.h
    engines/ags/engine/ac/textbox.h
    engines/ags/engine/ac/timer.h
    engines/ags/engine/ac/topbarsettings.h
    engines/ags/engine/ac/translation.h
    engines/ags/engine/ac/tree_map.h
    engines/ags/engine/ac/viewframe.h
    engines/ags/engine/ac/walkablearea.h
    engines/ags/engine/ac/walkbehind.h
    engines/ags/engine/debugging/agseditordebugger.h
    engines/ags/engine/debugging/consoleoutputtarget.h
    engines/ags/engine/debugging/debug_log.h
    engines/ags/engine/debugging/debugger.h
    engines/ags/engine/debugging/dummyagsdebugger.h
    engines/ags/engine/debugging/filebasedagsdebugger.h
    engines/ags/engine/debugging/logfile.h
    engines/ags/engine/debugging/messagebuffer.h
    engines/ags/engine/device/mousew32.h
    engines/ags/engine/game/game_init.h
    engines/ags/engine/game/savegame.h
    engines/ags/engine/game/savegame_components.h
    engines/ags/engine/game/savegame_internal.h
    engines/ags/engine/game/viewport.h
    engines/ags/engine/gfx/ali3dexception.h
    engines/ags/engine/gfx/ali3dogl.h
    engines/ags/engine/gfx/ali3dsw.h
    engines/ags/engine/gfx/blender.h
    engines/ags/engine/gfx/ddb.h
    engines/ags/engine/gfx/gfx_util.h
    engines/ags/engine/gfx/gfxdefines.h
    engines/ags/engine/gfx/gfxdriverbase.h
    engines/ags/engine/gfx/gfxdriverfactory.h
    engines/ags/engine/gfx/gfxdriverfactorybase.h
    engines/ags/engine/gfx/gfxfilter.h
    engines/ags/engine/gfx/gfxfilter_aad3d.h
    engines/ags/engine/gfx/gfxfilter_aaogl.h
    engines/ags/engine/gfx/gfxfilter_allegro.h
    engines/ags/engine/gfx/gfxfilter_d3d.h
    engines/ags/engine/gfx/gfxfilter_hqx.h
    engines/ags/engine/gfx/gfxfilter_ogl.h
    engines/ags/engine/gfx/gfxfilter_scaling.h
    engines/ags/engine/gfx/gfxmodelist.h
    engines/ags/engine/gfx/graphicsdriver.h
    engines/ags/engine/gfx/hq2x3x.h
    engines/ags/engine/gui/animatingguibutton.h
    engines/ags/engine/gui/cscidialog.h
    engines/ags/engine/gui/guidialog.h
    engines/ags/engine/gui/guidialogdefines.h
    engines/ags/engine/gui/guidialoginternaldefs.h
    engines/ags/engine/gui/mylabel.h
    engines/ags/engine/gui/mylistbox.h
    engines/ags/engine/gui/mypushbutton.h
    engines/ags/engine/gui/mytextbox.h
    engines/ags/engine/gui/newcontrol.h
    engines/ags/engine/main/config.h
    engines/ags/engine/main/engine.h
    engines/ags/engine/main/engine_setup.h
    engines/ags/engine/main/game_file.h
    engines/ags/engine/main/game_run.h
    engines/ags/engine/main/game_start.h
    engines/ags/engine/main/graphics_mode.h
    engines/ags/engine/main/main.h
    engines/ags/engine/main/main_allegro.h
    engines/ags/engine/main/mainheader.h
    engines/ags/engine/main/quit.h
    engines/ags/engine/main/update.h
    engines/ags/engine/media/audio/ambientsound.h
    engines/ags/engine/media/audio/audio.h
    engines/ags/engine/media/audio/clip_mydumbmod.h
    engines/ags/engine/media/audio/clip_myjgmod.h
    engines/ags/engine/media/audio/clip_mymidi.h
    engines/ags/engine/media/audio/clip_mymp3.h
    engines/ags/engine/media/audio/clip_myogg.h
    engines/ags/engine/media/audio/clip_mystaticmp3.h
    engines/ags/engine/media/audio/clip_mystaticogg.h
    engines/ags/engine/media/audio/clip_mywave.h
    engines/ags/engine/media/audio/queuedaudioitem.h
    engines/ags/engine/media/audio/sound.h
    engines/ags/engine/media/audio/soundcache.h
    engines/ags/engine/media/audio/soundclip.h
    engines/ags/engine/media/video/VMR9Graph.h
    engines/ags/engine/media/video/video.h
    engines/ags/engine/platform/base/agsplatformdriver.h
    engines/ags/engine/platform/util/pe.h
    engines/ags/engine/platform/windows/debugging/namedpipesagsdebugger.h
    engines/ags/engine/platform/windows/gfx/ali3dd3d.h
    engines/ags/engine/platform/windows/setup/winsetup.h
    engines/ags/engine/platform/windows/win_ex_handling.h
    engines/ags/engine/platform/windows/winapi_exclusive.h
    engines/ags/engine/plugin/agsplugin.h
    engines/ags/engine/plugin/plugin_builtin.h
    engines/ags/engine/plugin/plugin_engine.h
    engines/ags/engine/plugin/pluginobjectreader.h
    engines/ags/engine/script/cc_instance.h
    engines/ags/engine/script/executingscript.h
    engines/ags/engine/script/exports.h
    engines/ags/engine/script/nonblockingscriptfunction.h
    engines/ags/engine/script/runtimescriptvalue.h
    engines/ags/engine/script/script.h
    engines/ags/engine/script/script_api.h
    engines/ags/engine/script/script_runtime.h
    engines/ags/engine/script/systemimports.h
    engines/ags/engine/util/library.h
    engines/ags/engine/util/library_dummy.h
    engines/ags/engine/util/library_posix.h
    engines/ags/engine/util/library_psp.h
    engines/ags/engine/util/library_windows.h
    engines/ags/engine/util/mutex.h
    engines/ags/engine/util/mutex_base.h
    engines/ags/engine/util/mutex_lock.h
    engines/ags/engine/util/mutex_psp.h
    engines/ags/engine/util/mutex_pthread.h
    engines/ags/engine/util/mutex_std.h
    engines/ags/engine/util/mutex_wii.h
    engines/ags/engine/util/mutex_windows.h
    engines/ags/engine/util/scaling.h
    engines/ags/engine/util/thread.h
    engines/ags/engine/util/thread_psp.h
    engines/ags/engine/util/thread_pthread.h
    engines/ags/engine/util/thread_std.h
    engines/ags/engine/util/thread_wii.h
    engines/ags/engine/util/thread_windows.h
    engines/ags/shared/ac/audiocliptype.h
    engines/ags/shared/ac/characterinfo.h
    engines/ags/shared/ac/common.h
    engines/ags/shared/ac/common_defines.h
    engines/ags/shared/ac/dialogtopic.h
    engines/ags/shared/ac/dynobj/scriptaudioclip.h
    engines/ags/shared/ac/game_version.h
    engines/ags/shared/ac/gamesetupstruct.h
    engines/ags/shared/ac/gamesetupstructbase.h
    engines/ags/shared/ac/gamestructdefines.h
    engines/ags/shared/ac/interfacebutton.h
    engines/ags/shared/ac/interfaceelement.h
    engines/ags/shared/ac/inventoryiteminfo.h
    engines/ags/shared/ac/mousecursor.h
    engines/ags/shared/ac/oldgamesetupstruct.h
    engines/ags/shared/ac/spritecache.h
    engines/ags/shared/ac/view.h
    engines/ags/shared/ac/wordsdictionary.h
    engines/ags/shared/api/stream_api.h
    engines/ags/shared/core/asset.h
    engines/ags/shared/core/assetmanager.h
    engines/ags/shared/core/platform.h
    engines/ags/shared/core/types.h
    engines/ags/shared/debugging/debugmanager.h
    engines/ags/shared/debugging/out.h
    engines/ags/shared/debugging/outputhandler.h
    engines/ags/shared/font/agsfontrenderer.h
    engines/ags/shared/font/fonts.h
    engines/ags/shared/font/ttffontrenderer.h
    engines/ags/shared/font/wfnfont.h
    engines/ags/shared/font/wfnfontrenderer.h
    engines/ags/shared/game/customproperties.h
    engines/ags/shared/game/interactions.h
    engines/ags/shared/game/main_game_file.h
    engines/ags/shared/game/plugininfo.h
    engines/ags/shared/game/room_file.h
    engines/ags/shared/game/room_version.h
    engines/ags/shared/game/roomstruct.h
    engines/ags/shared/gfx/allegrobitmap.h
    engines/ags/shared/gfx/bitmap.h
    engines/ags/shared/gfx/gfx_def.h
    engines/ags/shared/gui/guibutton.h
    engines/ags/shared/gui/guidefines.h
    engines/ags/shared/gui/guiinv.h
    engines/ags/shared/gui/guilabel.h
    engines/ags/shared/gui/guilistbox.h
    engines/ags/shared/gui/guimain.h
    engines/ags/shared/gui/guiobject.h
    engines/ags/shared/gui/guislider.h
    engines/ags/shared/gui/guitextbox.h
    engines/ags/shared/script/cc_error.h
    engines/ags/shared/script/cc_options.h
    engines/ags/shared/script/cc_script.h
    engines/ags/shared/script/script_common.h
    engines/ags/shared/util/alignedstream.h
    engines/ags/shared/util/bbop.h
    engines/ags/shared/util/bufferedstream.h
    engines/ags/shared/util/compress.h
    engines/ags/shared/util/datastream.h
    engines/ags/shared/util/directory.h
    engines/ags/shared/util/error.h
    engines/ags/shared/util/file.h
    engines/ags/shared/util/filestream.h
    engines/ags/shared/util/geometry.h
    engines/ags/shared/util/ini_util.h
    engines/ags/shared/util/inifile.h
    engines/ags/shared/util/lzw.h
    engines/ags/shared/util/math.h
    engines/ags/shared/util/memory.h
    engines/ags/shared/util/misc.h
    engines/ags/shared/util/multifilelib.h
    engines/ags/shared/util/path.h
    engines/ags/shared/util/proxystream.h
    engines/ags/shared/util/stdio_compat.h
    engines/ags/shared/util/stream.h
    engines/ags/shared/util/string.h
    engines/ags/shared/util/string_compat.h
    engines/ags/shared/util/string_types.h
    engines/ags/shared/util/string_utils.h
    engines/ags/shared/util/textreader.h
    engines/ags/shared/util/textstreamreader.h
    engines/ags/shared/util/textstreamwriter.h
    engines/ags/shared/util/textwriter.h
    engines/ags/shared/util/version.h
    engines/ags/shared/util/wgt2allg.h


diff --git a/engines/ags/engine/ac/asset_helper.h b/engines/ags/engine/ac/asset_helper.h
index 4efd81efb0..eb5c0e4ffc 100644
--- a/engines/ags/engine/ac/asset_helper.h
+++ b/engines/ags/engine/ac/asset_helper.h
@@ -33,6 +33,8 @@
 #include <utility>
 #include "util/string.h"
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Common {
 class Stream;
@@ -79,4 +81,6 @@ PACKFILE *PackfileFromAsset(const AssetPath &path, size_t &asset_size);
 DUMBFILE *DUMBfileFromAsset(const AssetPath &path, size_t &asset_size);
 bool DoesAssetExistInLib(const AssetPath &assetname);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/audiochannel.h b/engines/ags/engine/ac/audiochannel.h
index d130cb8a13..5cb30e14aa 100644
--- a/engines/ags/engine/ac/audiochannel.h
+++ b/engines/ags/engine/ac/audiochannel.h
@@ -26,6 +26,8 @@
 #include "ac/dynobj/scriptaudioclip.h"
 #include "ac/dynobj/scriptaudiochannel.h"
 
+namespace AGS3 {
+
 int     AudioChannel_GetID(ScriptAudioChannel *channel);
 int     AudioChannel_GetIsPlaying(ScriptAudioChannel *channel);
 int     AudioChannel_GetPanning(ScriptAudioChannel *channel);
@@ -40,4 +42,6 @@ void    AudioChannel_Stop(ScriptAudioChannel *channel);
 void    AudioChannel_Seek(ScriptAudioChannel *channel, int newPosition);
 void    AudioChannel_SetRoomLocation(ScriptAudioChannel *channel, int xPos, int yPos);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/audioclip.h b/engines/ags/engine/ac/audioclip.h
index 8cd7514045..9f8fab8060 100644
--- a/engines/ags/engine/ac/audioclip.h
+++ b/engines/ags/engine/ac/audioclip.h
@@ -26,6 +26,8 @@
 #include "ac/dynobj/scriptaudioclip.h"
 #include "ac/dynobj/scriptaudiochannel.h"
 
+namespace AGS3 {
+
 int     AudioClip_GetFileType(ScriptAudioClip *clip);
 int     AudioClip_GetType(ScriptAudioClip *clip);
 int     AudioClip_GetIsAvailable(ScriptAudioClip *clip);
@@ -34,4 +36,6 @@ ScriptAudioChannel *AudioClip_Play(ScriptAudioClip *clip, int priority, int repe
 ScriptAudioChannel *AudioClip_PlayFrom(ScriptAudioClip *clip, int position, int priority, int repeat);
 ScriptAudioChannel *AudioClip_PlayQueued(ScriptAudioClip *clip, int priority, int repeat);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/button.h b/engines/ags/engine/ac/button.h
index 7f872fcd19..65ef6a42d1 100644
--- a/engines/ags/engine/ac/button.h
+++ b/engines/ags/engine/ac/button.h
@@ -25,6 +25,8 @@
 
 #include "gui/guibutton.h"
 
+namespace AGS3 {
+
 using AGS::Common::GUIButton;
 
 void        Button_Animate(GUIButton *butt, int view, int loop, int speed, int repeat);
@@ -49,4 +51,6 @@ int         UpdateAnimatingButton(int bu);
 void        StopButtonAnimation(int idxn);
 void        FindAndRemoveButtonAnimation(int guin, int objn);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/cdaudio.h b/engines/ags/engine/ac/cdaudio.h
index d3598a3904..ee6763bad4 100644
--- a/engines/ags/engine/ac/cdaudio.h
+++ b/engines/ags/engine/ac/cdaudio.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_AC_CDAUDIO_H
 #define AGS_ENGINE_AC_CDAUDIO_H
 
+namespace AGS3 {
+
 // CD Player functions
 // flags returned with cd_getstatus
 #define CDS_DRIVEOPEN    0x0001  // tray is open
@@ -30,7 +32,9 @@
 #define CDS_AUDIOSUPPORT 0x0010  // supports audio CDs
 #define CDS_DRIVEEMPTY   0x0800  // no CD in drive
 
-int     init_cd_player() ;
-int     cd_manager(int cmdd, int datt) ;
+int     init_cd_player();
+int     cd_manager(int cmdd, int datt);
+
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/ac/character.h b/engines/ags/engine/ac/character.h
index 28a127ad67..9039aaf9ad 100644
--- a/engines/ags/engine/ac/character.h
+++ b/engines/ags/engine/ac/character.h
@@ -31,6 +31,8 @@
 #include "game/viewport.h"
 #include "util/geometry.h"
 
+namespace AGS3 {
+
 // **** CHARACTER: FUNCTIONS ****
 
 void    Character_AddInventory(CharacterInfo *chaa, ScriptInvItem *invi, int addIndex);
@@ -225,4 +227,6 @@ extern int32_t _sc_PlayerCharPtr;
 // order of loops to turn character in circle from down to down
 extern int turnlooporder[8];
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/charactercache.h b/engines/ags/engine/ac/charactercache.h
index 9032c83024..ec6564d113 100644
--- a/engines/ags/engine/ac/charactercache.h
+++ b/engines/ags/engine/ac/charactercache.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_AC_CHARACTERCACHE_H
 #define AGS_ENGINE_AC_CHARACTERCACHE_H
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Common {
 class Bitmap;
@@ -41,4 +43,6 @@ struct CharacterCache {
 	// no mirroredWas is required, since the code inverts the sprite number
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/characterextras.h b/engines/ags/engine/ac/characterextras.h
index 526e690374..3d08847df3 100644
--- a/engines/ags/engine/ac/characterextras.h
+++ b/engines/ags/engine/ac/characterextras.h
@@ -25,6 +25,8 @@
 
 #include "ac/runtime_defines.h"
 
+namespace AGS3 {
+
 // Forward declaration
 namespace AGS {
 namespace Common {
@@ -58,4 +60,6 @@ struct CharacterExtras {
 	void WriteToFile(Common::Stream *out);
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/datetime.h b/engines/ags/engine/ac/datetime.h
index 96b922a306..6febc33f6a 100644
--- a/engines/ags/engine/ac/datetime.h
+++ b/engines/ags/engine/ac/datetime.h
@@ -25,6 +25,8 @@
 
 #include "ac/dynobj/scriptdatetime.h"
 
+namespace AGS3 {
+
 ScriptDateTime *DateTime_Now_Core();
 ScriptDateTime *DateTime_Now();
 int             DateTime_GetYear(ScriptDateTime *sdt);
@@ -35,4 +37,6 @@ int             DateTime_GetMinute(ScriptDateTime *sdt);
 int             DateTime_GetSecond(ScriptDateTime *sdt);
 int             DateTime_GetRawTime(ScriptDateTime *sdt);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dialog.h b/engines/ags/engine/ac/dialog.h
index 717ac31a2c..7436d41466 100644
--- a/engines/ags/engine/ac/dialog.h
+++ b/engines/ags/engine/ac/dialog.h
@@ -26,6 +26,8 @@
 #include <vector>
 #include "ac/dynobj/scriptdialog.h"
 
+namespace AGS3 {
+
 int  Dialog_GetID(ScriptDialog *sd);
 int  Dialog_GetOptionCount(ScriptDialog *sd);
 int  Dialog_GetShowTextParser(ScriptDialog *sd);
@@ -37,8 +39,10 @@ void Dialog_SetOptionState(ScriptDialog *sd, int option, int newState);
 void Dialog_Start(ScriptDialog *sd);
 
 void do_conversation(int dlgnum);
-int  show_dialog_options(int dlgnum, int sayChosenOption, bool runGameLoopsInBackground) ;
+int  show_dialog_options(int dlgnum, int sayChosenOption, bool runGameLoopsInBackground);
 
 extern ScriptDialog *scrDialog;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dialogoptionsrendering.h b/engines/ags/engine/ac/dialogoptionsrendering.h
index d1e741c201..4f8584c271 100644
--- a/engines/ags/engine/ac/dialogoptionsrendering.h
+++ b/engines/ags/engine/ac/dialogoptionsrendering.h
@@ -26,6 +26,8 @@
 #include "ac/dynobj/scriptdialog.h"
 #include "ac/dynobj/scriptdialogoptionsrendering.h"
 
+namespace AGS3 {
+
 int  DialogOptionsRendering_GetX(ScriptDialogOptionsRendering *dlgOptRender);
 void DialogOptionsRendering_SetX(ScriptDialogOptionsRendering *dlgOptRender, int newX);
 int  DialogOptionsRendering_GetY(ScriptDialogOptionsRendering *dlgOptRender);
@@ -47,4 +49,6 @@ ScriptDrawingSurface *DialogOptionsRendering_GetSurface(ScriptDialogOptionsRende
 int  DialogOptionsRendering_GetActiveOptionID(ScriptDialogOptionsRendering *dlgOptRender);
 void DialogOptionsRendering_SetActiveOptionID(ScriptDialogOptionsRendering *dlgOptRender, int activeOptionID);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/display.h b/engines/ags/engine/ac/display.h
index 6ea4cd5e67..35b5f7f13c 100644
--- a/engines/ags/engine/ac/display.h
+++ b/engines/ags/engine/ac/display.h
@@ -25,6 +25,8 @@
 
 #include "gui/guimain.h"
 
+namespace AGS3 {
+
 using AGS::Common::GUIMain;
 
 // options for 'disp_type' parameter
@@ -76,10 +78,12 @@ int get_textwindow_top_border_height(int twgui);
 // Warning!: draw_text_window() and draw_text_window_and_bar() can create new text_window_ds
 void draw_text_window(Common::Bitmap **text_window_ds, bool should_free_ds, int *xins, int *yins, int *xx, int *yy, int *wii, color_t *set_text_color, int ovrheight, int ifnum);
 void draw_text_window_and_bar(Common::Bitmap **text_window_ds, bool should_free_ds,
-                              int *xins, int *yins, int *xx, int *yy, int *wii, color_t *set_text_color, int ovrheight = 0, int ifnum = -1);
+	int *xins, int *yins, int *xx, int *yy, int *wii, color_t *set_text_color, int ovrheight = 0, int ifnum = -1);
 int get_textwindow_padding(int ifnum);
 
 // The efficient length of the last source text prepared for display
 extern int source_text_length;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/draw.h b/engines/ags/engine/ac/draw.h
index 922b557e1b..2613f34357 100644
--- a/engines/ags/engine/ac/draw.h
+++ b/engines/ags/engine/ac/draw.h
@@ -29,6 +29,8 @@
 #include "gfx/gfx_def.h"
 #include "util/wgt2allg.h"
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Common {
 class Bitmap;
@@ -115,9 +117,9 @@ void construct_engine_overlay();
 void add_to_sprite_list(Engine::IDriverDependantBitmap *spp, int xx, int yy, int baseline, int trans, int sprNum, bool isWalkBehind = false);
 void tint_image(Common::Bitmap *g, Common::Bitmap *source, int red, int grn, int blu, int light_level, int luminance = 255);
 void draw_sprite_support_alpha(Common::Bitmap *ds, bool ds_has_alpha, int xpos, int ypos, Common::Bitmap *image, bool src_has_alpha,
-                               Common::BlendMode blend_mode = Common::kBlendMode_Alpha, int alpha = 0xFF);
+	Common::BlendMode blend_mode = Common::kBlendMode_Alpha, int alpha = 0xFF);
 void draw_sprite_slot_support_alpha(Common::Bitmap *ds, bool ds_has_alpha, int xpos, int ypos, int src_slot,
-                                    Common::BlendMode blend_mode = Common::kBlendMode_Alpha, int alpha = 0xFF);
+	Common::BlendMode blend_mode = Common::kBlendMode_Alpha, int alpha = 0xFF);
 void draw_gui_sprite(Common::Bitmap *ds, int pic, int x, int y, bool use_alpha, Common::BlendMode blend_mode);
 void draw_gui_sprite_v330(Common::Bitmap *ds, int pic, int x, int y, bool use_alpha = true, Common::BlendMode blend_mode = Common::kBlendMode_Alpha);
 // Render game on screen
@@ -177,4 +179,6 @@ Common::PBitmap PrepareSpriteForUse(Common::PBitmap bitmap, bool has_alpha);
 // of the requested width and height and game's native color depth.
 Common::Bitmap *CopyScreenIntoBitmap(int width, int height, bool at_native_res = false);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/draw_software.h b/engines/ags/engine/ac/draw_software.h
index b27a8c3412..8d8d20fd4b 100644
--- a/engines/ags/engine/ac/draw_software.h
+++ b/engines/ags/engine/ac/draw_software.h
@@ -34,6 +34,8 @@
 #include "gfx/ddb.h"
 #include "util/geometry.h"
 
+namespace AGS3 {
+
 // Inits dirty rects array for the given room camera/viewport pair
 // View_index indicates the room viewport (>= 0) or the main viewport (-1)
 void init_invalid_regions(int view_index, const Size &surf_size, const Rect &viewport);
@@ -54,4 +56,6 @@ void update_black_invreg_and_reset(AGS::Common::Bitmap *ds);
 // no_transform flag tells the system that the regions should be plain copied to the ds.
 void update_room_invreg_and_reset(int view_index, AGS::Common::Bitmap *ds, AGS::Common::Bitmap *src, bool no_transform);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/drawingsurface.h b/engines/ags/engine/ac/drawingsurface.h
index 5878f2a837..511b73a98b 100644
--- a/engines/ags/engine/ac/drawingsurface.h
+++ b/engines/ags/engine/ac/drawingsurface.h
@@ -25,6 +25,8 @@
 
 #include "ac/dynobj/scriptdrawingsurface.h"
 
+namespace AGS3 {
+
 void    DrawingSurface_Release(ScriptDrawingSurface *sds);
 // convert actual co-ordinate back to what the script is expecting
 ScriptDrawingSurface *DrawingSurface_CreateCopy(ScriptDrawingSurface *sds);
@@ -47,4 +49,6 @@ void    DrawingSurface_DrawLine(ScriptDrawingSurface *sds, int fromx, int fromy,
 void    DrawingSurface_DrawPixel(ScriptDrawingSurface *sds, int x, int y);
 int     DrawingSurface_GetPixel(ScriptDrawingSurface *sds, int x, int y);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynamicsprite.h b/engines/ags/engine/ac/dynamicsprite.h
index 14610057a8..a78b50ee10 100644
--- a/engines/ags/engine/ac/dynamicsprite.h
+++ b/engines/ags/engine/ac/dynamicsprite.h
@@ -26,6 +26,8 @@
 #include "ac/dynobj/scriptdynamicsprite.h"
 #include "ac/dynobj/scriptdrawingsurface.h"
 
+namespace AGS3 {
+
 void    DynamicSprite_Delete(ScriptDynamicSprite *sds);
 ScriptDrawingSurface *DynamicSprite_GetDrawingSurface(ScriptDynamicSprite *dss);
 int     DynamicSprite_GetGraphic(ScriptDynamicSprite *sds);
@@ -53,4 +55,6 @@ ScriptDynamicSprite *DynamicSprite_CreateFromBackground(int frame, int x1, int y
 void    add_dynamic_sprite(int gotSlot, Common::Bitmap *redin, bool hasAlpha = false);
 void    free_dynamic_sprite(int gotSlot);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.h b/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.h
index c141037026..af1263bfb7 100644
--- a/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.h
+++ b/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.h
@@ -25,6 +25,8 @@
 
 #include "ac/dynobj/cc_dynamicobject.h"
 
+namespace AGS3 {
+
 struct AGSCCDynamicObject : ICCDynamicObject {
 protected:
 	virtual ~AGSCCDynamicObject() = default;
@@ -65,4 +67,6 @@ protected:
 
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/cc_audiochannel.h b/engines/ags/engine/ac/dynobj/cc_audiochannel.h
index e36ff25f36..caa77fe331 100644
--- a/engines/ags/engine/ac/dynobj/cc_audiochannel.h
+++ b/engines/ags/engine/ac/dynobj/cc_audiochannel.h
@@ -25,10 +25,14 @@
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
+namespace AGS3 {
+
 struct CCAudioChannel final : AGSCCDynamicObject {
 	const char *GetType() override;
 	int Serialize(const char *address, char *buffer, int bufsize) override;
 	void Unserialize(int index, const char *serializedData, int dataSize) override;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/cc_audioclip.h b/engines/ags/engine/ac/dynobj/cc_audioclip.h
index 3b3f764531..2f9b8bd8fe 100644
--- a/engines/ags/engine/ac/dynobj/cc_audioclip.h
+++ b/engines/ags/engine/ac/dynobj/cc_audioclip.h
@@ -25,10 +25,14 @@
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
+namespace AGS3 {
+
 struct CCAudioClip final : AGSCCDynamicObject {
 	const char *GetType() override;
 	int Serialize(const char *address, char *buffer, int bufsize) override;
 	void Unserialize(int index, const char *serializedData, int dataSize) override;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/cc_character.h b/engines/ags/engine/ac/dynobj/cc_character.h
index e608c281e0..7acb487099 100644
--- a/engines/ags/engine/ac/dynobj/cc_character.h
+++ b/engines/ags/engine/ac/dynobj/cc_character.h
@@ -25,6 +25,8 @@
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
+namespace AGS3 {
+
 struct CCCharacter final : AGSCCDynamicObject {
 
 	// return the type name of the object
@@ -39,4 +41,6 @@ struct CCCharacter final : AGSCCDynamicObject {
 	void WriteInt16(const char *address, intptr_t offset, int16_t val) override;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/cc_dialog.h b/engines/ags/engine/ac/dynobj/cc_dialog.h
index 0ed6030ff7..9fbcdbe654 100644
--- a/engines/ags/engine/ac/dynobj/cc_dialog.h
+++ b/engines/ags/engine/ac/dynobj/cc_dialog.h
@@ -25,6 +25,8 @@
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
+namespace AGS3 {
+
 struct CCDialog final : AGSCCDynamicObject {
 
 	// return the type name of the object
@@ -38,4 +40,6 @@ struct CCDialog final : AGSCCDynamicObject {
 
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicarray.h b/engines/ags/engine/ac/dynobj/cc_dynamicarray.h
index f5febb7e03..e89774ada4 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicarray.h
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicarray.h
@@ -26,6 +26,8 @@
 #include <vector>
 #include "ac/dynobj/cc_dynamicobject.h"   // ICCDynamicObject
 
+namespace AGS3 {
+
 #define CC_DYNAMIC_ARRAY_TYPE_NAME "CCDynamicArray"
 #define ARRAY_MANAGED_TYPE_FLAG    0x80000000
 
@@ -62,4 +64,6 @@ namespace DynamicArrayHelpers {
 DynObjectRef CreateStringArray(const std::vector<const char *>);
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicobject.h b/engines/ags/engine/ac/dynobj/cc_dynamicobject.h
index 39f7a2ffcf..42394dc11c 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicobject.h
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicobject.h
@@ -32,6 +32,8 @@
 #include <utility>
 #include "core/types.h"
 
+namespace AGS3 {
+
 // Forward declaration
 namespace AGS {
 namespace Common {
@@ -75,17 +77,17 @@ struct ICCDynamicObject {
 	// necessary, because byte-code does not contain any distinct operation for this case.
 	// The worst thing here is that with the current byte-code structure we can never tell whether
 	// offset 0 means getting pointer to whole object or a pointer to its first field.
-	virtual const char *GetFieldPtr(const char *address, intptr_t offset)           = 0;
+	virtual const char *GetFieldPtr(const char *address, intptr_t offset) = 0;
 	virtual void    Read(const char *address, intptr_t offset, void *dest, int size) = 0;
-	virtual uint8_t ReadInt8(const char *address, intptr_t offset)                  = 0;
-	virtual int16_t ReadInt16(const char *address, intptr_t offset)                 = 0;
-	virtual int32_t ReadInt32(const char *address, intptr_t offset)                 = 0;
-	virtual float   ReadFloat(const char *address, intptr_t offset)                 = 0;
+	virtual uint8_t ReadInt8(const char *address, intptr_t offset) = 0;
+	virtual int16_t ReadInt16(const char *address, intptr_t offset) = 0;
+	virtual int32_t ReadInt32(const char *address, intptr_t offset) = 0;
+	virtual float   ReadFloat(const char *address, intptr_t offset) = 0;
 	virtual void    Write(const char *address, intptr_t offset, void *src, int size) = 0;
-	virtual void    WriteInt8(const char *address, intptr_t offset, uint8_t val)    = 0;
-	virtual void    WriteInt16(const char *address, intptr_t offset, int16_t val)   = 0;
-	virtual void    WriteInt32(const char *address, intptr_t offset, int32_t val)   = 0;
-	virtual void    WriteFloat(const char *address, intptr_t offset, float val)     = 0;
+	virtual void    WriteInt8(const char *address, intptr_t offset, uint8_t val) = 0;
+	virtual void    WriteInt16(const char *address, intptr_t offset, int16_t val) = 0;
+	virtual void    WriteInt32(const char *address, intptr_t offset, int32_t val) = 0;
+	virtual void    WriteFloat(const char *address, intptr_t offset, float val) = 0;
 
 protected:
 	ICCDynamicObject() = default;
@@ -128,4 +130,6 @@ extern int ccReleaseObjectReference(int32_t handle);
 
 extern ICCStringClass *stringClassImpl;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h b/engines/ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h
index d3a9e5963a..9087334e6b 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h
@@ -26,8 +26,12 @@
 #include "script/runtimescriptvalue.h"
 #include "ac/dynobj/cc_dynamicobject.h"
 
+namespace AGS3 {
+
 extern ScriptValueType ccGetObjectAddressAndManagerFromHandle(
-    int32_t handle, void *&object, ICCDynamicObject *&manager);
+	int32_t handle, void *&object, ICCDynamicObject *&manager);
+
+} // namespace AGS3
 
 #endif
 
diff --git a/engines/ags/engine/ac/dynobj/cc_gui.h b/engines/ags/engine/ac/dynobj/cc_gui.h
index 7a24b76e23..fb0d6974cb 100644
--- a/engines/ags/engine/ac/dynobj/cc_gui.h
+++ b/engines/ags/engine/ac/dynobj/cc_gui.h
@@ -25,6 +25,8 @@
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
+namespace AGS3 {
+
 struct CCGUI final : AGSCCDynamicObject {
 
 	// return the type name of the object
@@ -37,4 +39,6 @@ struct CCGUI final : AGSCCDynamicObject {
 	void Unserialize(int index, const char *serializedData, int dataSize) override;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/cc_guiobject.h b/engines/ags/engine/ac/dynobj/cc_guiobject.h
index d07e6bd645..f56c5589a6 100644
--- a/engines/ags/engine/ac/dynobj/cc_guiobject.h
+++ b/engines/ags/engine/ac/dynobj/cc_guiobject.h
@@ -25,6 +25,8 @@
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
+namespace AGS3 {
+
 struct CCGUIObject final : AGSCCDynamicObject {
 
 	// return the type name of the object
@@ -38,4 +40,6 @@ struct CCGUIObject final : AGSCCDynamicObject {
 
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/cc_hotspot.h b/engines/ags/engine/ac/dynobj/cc_hotspot.h
index 0efb6ed4bd..5b93be4a2d 100644
--- a/engines/ags/engine/ac/dynobj/cc_hotspot.h
+++ b/engines/ags/engine/ac/dynobj/cc_hotspot.h
@@ -25,6 +25,8 @@
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
+namespace AGS3 {
+
 struct CCHotspot final : AGSCCDynamicObject {
 
 	// return the type name of the object
@@ -38,4 +40,6 @@ struct CCHotspot final : AGSCCDynamicObject {
 
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/cc_inventory.h b/engines/ags/engine/ac/dynobj/cc_inventory.h
index 450305d69d..8287600ccc 100644
--- a/engines/ags/engine/ac/dynobj/cc_inventory.h
+++ b/engines/ags/engine/ac/dynobj/cc_inventory.h
@@ -25,6 +25,8 @@
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
+namespace AGS3 {
+
 struct CCInventory final : AGSCCDynamicObject {
 
 	// return the type name of the object
@@ -38,4 +40,6 @@ struct CCInventory final : AGSCCDynamicObject {
 
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/cc_object.h b/engines/ags/engine/ac/dynobj/cc_object.h
index d1da2d7a2b..b74c6ec2fc 100644
--- a/engines/ags/engine/ac/dynobj/cc_object.h
+++ b/engines/ags/engine/ac/dynobj/cc_object.h
@@ -25,6 +25,8 @@
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
+namespace AGS3 {
+
 struct CCObject final : AGSCCDynamicObject {
 
 	// return the type name of the object
@@ -38,4 +40,6 @@ struct CCObject final : AGSCCDynamicObject {
 
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/cc_region.h b/engines/ags/engine/ac/dynobj/cc_region.h
index 7b52c7ae77..2251fe3c05 100644
--- a/engines/ags/engine/ac/dynobj/cc_region.h
+++ b/engines/ags/engine/ac/dynobj/cc_region.h
@@ -25,6 +25,8 @@
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
+namespace AGS3 {
+
 struct CCRegion final : AGSCCDynamicObject {
 
 	// return the type name of the object
@@ -35,7 +37,8 @@ struct CCRegion final : AGSCCDynamicObject {
 	int Serialize(const char *address, char *buffer, int bufsize) override;
 
 	void Unserialize(int index, const char *serializedData, int dataSize) override;
-
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/cc_serializer.h b/engines/ags/engine/ac/dynobj/cc_serializer.h
index 0253eb94f3..5b43321ed4 100644
--- a/engines/ags/engine/ac/dynobj/cc_serializer.h
+++ b/engines/ags/engine/ac/dynobj/cc_serializer.h
@@ -25,6 +25,8 @@
 
 #include "ac/dynobj/cc_dynamicobject.h"
 
+namespace AGS3 {
+
 struct AGSDeSerializer : ICCObjectReader {
 
 	void Unserialize(int index, const char *objectType, const char *serializedData, int dataSize) override;
@@ -32,4 +34,6 @@ struct AGSDeSerializer : ICCObjectReader {
 
 extern AGSDeSerializer ccUnserializer;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/managedobjectpool.h b/engines/ags/engine/ac/dynobj/managedobjectpool.h
index 93cd695b1f..654dcce979 100644
--- a/engines/ags/engine/ac/dynobj/managedobjectpool.h
+++ b/engines/ags/engine/ac/dynobj/managedobjectpool.h
@@ -30,11 +30,13 @@
 #include "script/runtimescriptvalue.h"
 #include "ac/dynobj/cc_dynamicobject.h"   // ICCDynamicObject
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 struct ManagedObjectPool final {
@@ -54,14 +56,16 @@ private:
 		}
 
 		ManagedObject()
-			: obj_type(kScValUndefined), handle(0), addr(nullptr), callback(nullptr), refCount(0) {}
+			: obj_type(kScValUndefined), handle(0), addr(nullptr), callback(nullptr), refCount(0) {
+		}
 		ManagedObject(ScriptValueType obj_type, int32_t handle, const char *addr, ICCDynamicObject *callback)
-			: obj_type(obj_type), handle(handle), addr(addr), callback(callback), refCount(0) {}
+			: obj_type(obj_type), handle(handle), addr(addr), callback(callback), refCount(0) {
+		}
 	};
 
 	int objectCreationCounter;  // used to do garbage collection every so often
 
-	int32_t nextHandle {}; // TODO: manage nextHandle's going over INT32_MAX !
+	int32_t nextHandle{}; // TODO: manage nextHandle's going over INT32_MAX !
 	std::queue<int32_t> available_ids;
 	std::vector<ManagedObject> objects;
 	std::unordered_map<const char *, int32_t> handleByAddress;
@@ -88,7 +92,7 @@ public:
 	void reset();
 	ManagedObjectPool();
 
-	const char *disableDisposeForObject {nullptr};
+	const char *disableDisposeForObject{ nullptr };
 };
 
 extern ManagedObjectPool pool;
@@ -99,4 +103,6 @@ extern ManagedObjectPool pool;
 #define ManagedObjectLog(...)
 #endif
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/scriptaudiochannel.h b/engines/ags/engine/ac/dynobj/scriptaudiochannel.h
index 2358526b2a..52cb3c7d53 100644
--- a/engines/ags/engine/ac/dynobj/scriptaudiochannel.h
+++ b/engines/ags/engine/ac/dynobj/scriptaudiochannel.h
@@ -23,9 +23,13 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTAUDIOCHANNEL_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTAUDIOCHANNEL_H
 
+namespace AGS3 {
+
 struct ScriptAudioChannel {
 	int id;
 	int reserved;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/scriptcamera.h b/engines/ags/engine/ac/dynobj/scriptcamera.h
index c958a78c36..d0ff62acfd 100644
--- a/engines/ags/engine/ac/dynobj/scriptcamera.h
+++ b/engines/ags/engine/ac/dynobj/scriptcamera.h
@@ -25,6 +25,8 @@
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
+namespace AGS3 {
+
 // ScriptCamera keeps a reference to actual room Camera in script.
 struct ScriptCamera final : AGSCCDynamicObject {
 public:
@@ -54,4 +56,6 @@ private:
 // Unserialize camera from the memory stream
 ScriptCamera *Camera_Unserialize(int handle, const char *serializedData, int dataSize);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/scriptcontainers.h b/engines/ags/engine/ac/dynobj/scriptcontainers.h
index f735c6514b..71d3773305 100644
--- a/engines/ags/engine/ac/dynobj/scriptcontainers.h
+++ b/engines/ags/engine/ac/dynobj/scriptcontainers.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTCONTAINERS_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTCONTAINERS_H
 
+namespace AGS3 {
+
 class ScriptDictBase;
 class ScriptSetBase;
 
@@ -35,4 +37,6 @@ ScriptSetBase *Set_Create(bool sorted, bool case_sensitive);
 // Unserialize set from the memory stream
 ScriptSetBase *Set_Unserialize(int index, const char *serializedData, int dataSize);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/scriptdatetime.h b/engines/ags/engine/ac/dynobj/scriptdatetime.h
index 79c755149b..a714ff2cbe 100644
--- a/engines/ags/engine/ac/dynobj/scriptdatetime.h
+++ b/engines/ags/engine/ac/dynobj/scriptdatetime.h
@@ -25,6 +25,8 @@
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
+namespace AGS3 {
+
 struct ScriptDateTime final : AGSCCDynamicObject {
 	int year, month, day;
 	int hour, minute, second;
@@ -38,4 +40,6 @@ struct ScriptDateTime final : AGSCCDynamicObject {
 	ScriptDateTime();
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/scriptdialog.h b/engines/ags/engine/ac/dynobj/scriptdialog.h
index b1bdefd727..92a5de4581 100644
--- a/engines/ags/engine/ac/dynobj/scriptdialog.h
+++ b/engines/ags/engine/ac/dynobj/scriptdialog.h
@@ -23,9 +23,13 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTDIALOG_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTDIALOG_H
 
+namespace AGS3 {
+
 struct ScriptDialog {
 	int id;
 	int reserved;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.h b/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.h
index 88277931ff..00fb395f8a 100644
--- a/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.h
+++ b/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.h
@@ -25,6 +25,8 @@
 
 #include "ac/dynobj/scriptdrawingsurface.h"
 
+namespace AGS3 {
+
 struct ScriptDialogOptionsRendering final : AGSCCDynamicObject {
 	int x, y, width, height;
 	bool hasAlphaChannel;
@@ -51,5 +53,6 @@ struct ScriptDialogOptionsRendering final : AGSCCDynamicObject {
 	ScriptDialogOptionsRendering();
 };
 
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/ac/dynobj/scriptdict.h b/engines/ags/engine/ac/dynobj/scriptdict.h
index 3dc6b86326..4677d33828 100644
--- a/engines/ags/engine/ac/dynobj/scriptdict.h
+++ b/engines/ags/engine/ac/dynobj/scriptdict.h
@@ -43,6 +43,8 @@
 #include "util/string.h"
 #include "util/string_types.h"
 
+namespace AGS3 {
+
 using namespace AGS::Common;
 
 class ScriptDictBase : public AGSCCDynamicObject {
@@ -167,7 +169,7 @@ private:
 			int key_pos = bytesSoFar;
 			bytesSoFar += key_len;
 			size_t value_len = UnserializeInt();
-			if (value_len == (size_t) - 1) {
+			if (value_len == (size_t)-1) {
 				TryAddItem(&serializedData[key_pos], key_len, nullptr, 0);
 			} else {
 				int value_pos = bytesSoFar;
@@ -185,4 +187,6 @@ typedef ScriptDictImpl< std::map<String, String, StrLessNoCase>, true, false > S
 typedef ScriptDictImpl< std::unordered_map<String, String>, false, true > ScriptHashDict;
 typedef ScriptDictImpl< std::unordered_map<String, String, HashStrNoCase, StrEqNoCase>, false, false > ScriptHashDictCI;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/scriptdrawingsurface.h b/engines/ags/engine/ac/dynobj/scriptdrawingsurface.h
index 5a60c3853f..c8033101bc 100644
--- a/engines/ags/engine/ac/dynobj/scriptdrawingsurface.h
+++ b/engines/ags/engine/ac/dynobj/scriptdrawingsurface.h
@@ -26,11 +26,13 @@
 #include "ac/dynobj/cc_agsdynamicobject.h"
 #include "game/roomstruct.h"
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Common {
 class Bitmap;
-}
-}
+} // namespace Shared
+} // namespace AGS
 
 struct ScriptDrawingSurface final : AGSCCDynamicObject {
 	// These numbers and types are used to determine the source of this drawing surface;
@@ -64,4 +66,6 @@ struct ScriptDrawingSurface final : AGSCCDynamicObject {
 	ScriptDrawingSurface();
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/scriptdynamicsprite.h b/engines/ags/engine/ac/dynobj/scriptdynamicsprite.h
index a5ed2909d7..252c2fc8b2 100644
--- a/engines/ags/engine/ac/dynobj/scriptdynamicsprite.h
+++ b/engines/ags/engine/ac/dynobj/scriptdynamicsprite.h
@@ -25,7 +25,9 @@
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
-struct ScriptDynamicSprite final  : AGSCCDynamicObject {
+namespace AGS3 {
+
+struct ScriptDynamicSprite final : AGSCCDynamicObject {
 	int slot;
 
 	int Dispose(const char *address, bool force) override;
@@ -37,4 +39,6 @@ struct ScriptDynamicSprite final  : AGSCCDynamicObject {
 	ScriptDynamicSprite();
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/scriptfile.h b/engines/ags/engine/ac/dynobj/scriptfile.h
index 4aa2e8ccf7..08e636a98b 100644
--- a/engines/ags/engine/ac/dynobj/scriptfile.h
+++ b/engines/ags/engine/ac/dynobj/scriptfile.h
@@ -26,6 +26,8 @@
 #include "ac/dynobj/cc_dynamicobject.h"
 #include "util/file.h"
 
+namespace AGS3 {
+
 using namespace AGS; // FIXME later
 
 #define scFileRead   1
@@ -63,4 +65,6 @@ struct sc_File final : ICCDynamicObject {
 	void    WriteFloat(const char *address, intptr_t offset, float val) override;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/scriptgui.h b/engines/ags/engine/ac/dynobj/scriptgui.h
index 3b6326078d..8f9294d1c2 100644
--- a/engines/ags/engine/ac/dynobj/scriptgui.h
+++ b/engines/ags/engine/ac/dynobj/scriptgui.h
@@ -23,10 +23,14 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTGUI_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTGUI_H
 
+namespace AGS3 {
+
 // 64 bit: This struct must be 8 byte long
 struct ScriptGUI {
 	int id;
 	int __padding;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/scripthotspot.h b/engines/ags/engine/ac/dynobj/scripthotspot.h
index 6b692c3c7c..c11d3828d6 100644
--- a/engines/ags/engine/ac/dynobj/scripthotspot.h
+++ b/engines/ags/engine/ac/dynobj/scripthotspot.h
@@ -23,9 +23,13 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTHOTSPOT_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTHOTSPOT_H
 
+namespace AGS3 {
+
 struct ScriptHotspot {
 	int id;
 	int reserved;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/scriptinvitem.h b/engines/ags/engine/ac/dynobj/scriptinvitem.h
index 2c4b746073..962bf59410 100644
--- a/engines/ags/engine/ac/dynobj/scriptinvitem.h
+++ b/engines/ags/engine/ac/dynobj/scriptinvitem.h
@@ -23,9 +23,13 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTINVITEM_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTINVITEM_H
 
+namespace AGS3 {
+
 struct ScriptInvItem {
 	int id;
 	int reserved;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/scriptmouse.h b/engines/ags/engine/ac/dynobj/scriptmouse.h
index d1a8f56685..d935dbdbb5 100644
--- a/engines/ags/engine/ac/dynobj/scriptmouse.h
+++ b/engines/ags/engine/ac/dynobj/scriptmouse.h
@@ -23,9 +23,13 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTMOUSE_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTMOUSE_H
 
+namespace AGS3 {
+
 // The text script's "mouse" struct
 struct ScriptMouse {
 	int x, y;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/scriptobject.h b/engines/ags/engine/ac/dynobj/scriptobject.h
index b2c06e051c..3eb68dddd6 100644
--- a/engines/ags/engine/ac/dynobj/scriptobject.h
+++ b/engines/ags/engine/ac/dynobj/scriptobject.h
@@ -25,6 +25,8 @@
 
 #include "ac/roomobject.h"
 
+namespace AGS3 {
+
 // 64 bit: Struct size must be 8 byte for scripts to work
 struct ScriptObject {
 	int id;
@@ -32,4 +34,6 @@ struct ScriptObject {
 	int __padding;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/scriptoverlay.h b/engines/ags/engine/ac/dynobj/scriptoverlay.h
index b407f40191..ed1e7d81b2 100644
--- a/engines/ags/engine/ac/dynobj/scriptoverlay.h
+++ b/engines/ags/engine/ac/dynobj/scriptoverlay.h
@@ -25,6 +25,8 @@
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
+namespace AGS3 {
+
 struct ScriptOverlay final : AGSCCDynamicObject {
 	int overlayId;
 	int borderWidth;
@@ -39,4 +41,6 @@ struct ScriptOverlay final : AGSCCDynamicObject {
 	ScriptOverlay();
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/scriptregion.h b/engines/ags/engine/ac/dynobj/scriptregion.h
index bc52441282..743477d65f 100644
--- a/engines/ags/engine/ac/dynobj/scriptregion.h
+++ b/engines/ags/engine/ac/dynobj/scriptregion.h
@@ -23,9 +23,13 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTREGION_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTREGION_H
 
+namespace AGS3 {
+
 struct ScriptRegion {
 	int id;
 	int reserved;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/scriptset.h b/engines/ags/engine/ac/dynobj/scriptset.h
index 165425b104..cdf83af7cc 100644
--- a/engines/ags/engine/ac/dynobj/scriptset.h
+++ b/engines/ags/engine/ac/dynobj/scriptset.h
@@ -42,6 +42,8 @@
 #include "util/string.h"
 #include "util/string_types.h"
 
+namespace AGS3 {
+
 using namespace AGS::Common;
 
 class ScriptSetBase : public AGSCCDynamicObject {
@@ -150,4 +152,6 @@ typedef ScriptSetImpl< std::set<String, StrLessNoCase>, true, false > ScriptSetC
 typedef ScriptSetImpl< std::unordered_set<String>, false, true > ScriptHashSet;
 typedef ScriptSetImpl< std::unordered_set<String, HashStrNoCase, StrEqNoCase>, false, false > ScriptHashSetCI;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/scriptstring.h b/engines/ags/engine/ac/dynobj/scriptstring.h
index 289b1e6d5c..84bff3c322 100644
--- a/engines/ags/engine/ac/dynobj/scriptstring.h
+++ b/engines/ags/engine/ac/dynobj/scriptstring.h
@@ -25,6 +25,8 @@
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
+namespace AGS3 {
+
 struct ScriptString final : AGSCCDynamicObject, ICCStringClass {
 	char *text;
 
@@ -39,4 +41,6 @@ struct ScriptString final : AGSCCDynamicObject, ICCStringClass {
 	ScriptString(const char *fromText);
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/scriptsystem.h b/engines/ags/engine/ac/dynobj/scriptsystem.h
index 4d40079dd8..47b30c4d23 100644
--- a/engines/ags/engine/ac/dynobj/scriptsystem.h
+++ b/engines/ags/engine/ac/dynobj/scriptsystem.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTSYSTEM_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTSYSTEM_H
 
+namespace AGS3 {
+
 // The text script's "system" struct
 struct ScriptSystem {
 	int width, height;
@@ -35,4 +37,6 @@ struct ScriptSystem {
 	int reserved[5];  // so that future scripts don't overwrite data
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/scriptuserobject.h b/engines/ags/engine/ac/dynobj/scriptuserobject.h
index 0e3f0f6b45..ee21880138 100644
--- a/engines/ags/engine/ac/dynobj/scriptuserobject.h
+++ b/engines/ags/engine/ac/dynobj/scriptuserobject.h
@@ -31,6 +31,8 @@
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
+namespace AGS3 {
+
 struct ScriptUserObject final : ICCDynamicObject {
 public:
 	ScriptUserObject();
@@ -71,7 +73,7 @@ private:
 	// need more significant change to program before we could use different
 	// approach.
 	int32_t  _size;
-	char    *_data;
+	char *_data;
 };
 
 
@@ -81,4 +83,6 @@ namespace ScriptStructHelpers {
 ScriptUserObject *CreatePoint(int x, int y);
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/scriptviewframe.h b/engines/ags/engine/ac/dynobj/scriptviewframe.h
index 7b0dc38619..4a4721eb71 100644
--- a/engines/ags/engine/ac/dynobj/scriptviewframe.h
+++ b/engines/ags/engine/ac/dynobj/scriptviewframe.h
@@ -25,6 +25,8 @@
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
+namespace AGS3 {
+
 struct ScriptViewFrame final : AGSCCDynamicObject {
 	int view, loop, frame;
 
@@ -37,4 +39,6 @@ struct ScriptViewFrame final : AGSCCDynamicObject {
 	ScriptViewFrame();
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/dynobj/scriptviewport.h b/engines/ags/engine/ac/dynobj/scriptviewport.h
index a199e6ff38..61ae777aa9 100644
--- a/engines/ags/engine/ac/dynobj/scriptviewport.h
+++ b/engines/ags/engine/ac/dynobj/scriptviewport.h
@@ -25,6 +25,8 @@
 
 #include "ac/dynobj/cc_agsdynamicobject.h"
 
+namespace AGS3 {
+
 // ScriptViewport keeps a reference to actual room Viewport in script.
 struct ScriptViewport final : AGSCCDynamicObject {
 public:
@@ -53,4 +55,6 @@ private:
 // Unserialize viewport from the memory stream
 ScriptViewport *Viewport_Unserialize(int handle, const char *serializedData, int dataSize);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/event.h b/engines/ags/engine/ac/event.h
index 51307ae394..21b265f27b 100644
--- a/engines/ags/engine/ac/event.h
+++ b/engines/ags/engine/ac/event.h
@@ -26,6 +26,8 @@
 #include "ac/runtime_defines.h"
 #include "script/runtimescriptvalue.h"
 
+namespace AGS3 {
+
 // parameters to run_on_event
 #define GE_LEAVE_ROOM 1
 #define GE_ENTER_ROOM 2
@@ -84,4 +86,6 @@ extern int eventClaimed;
 
 extern const char *tsnames[4];
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/file.h b/engines/ags/engine/ac/file.h
index 2ea04e0038..2c3b4feede 100644
--- a/engines/ags/engine/ac/file.h
+++ b/engines/ags/engine/ac/file.h
@@ -31,11 +31,14 @@
 
 #include "ac/dynobj/scriptfile.h"
 #include "ac/runtime_defines.h"
+
+namespace AGS3 {
+
 using AGS::Common::Stream;
 
 int     File_Exists(const char *fnmm);
 int     File_Delete(const char *fnmm);
-void    *sc_OpenFile(const char *fnmm, int mode);
+void *sc_OpenFile(const char *fnmm, int mode);
 void    File_Close(sc_File *fil);
 void    File_WriteString(sc_File *fil, const char *towrite);
 void    File_WriteInt(sc_File *fil, int towrite);
@@ -54,7 +57,7 @@ int     File_GetError(sc_File *fil);
 int     File_GetPosition(sc_File *fil);
 
 struct ScriptFileHandle {
-	Stream  *stream;
+	Stream *stream;
 	int32_t  handle;
 };
 extern ScriptFileHandle valid_handles[MAX_OPEN_SCRIPT_FILES + 1];
@@ -64,4 +67,6 @@ ScriptFileHandle *check_valid_file_handle_ptr(Stream *stream_ptr, const char *op
 ScriptFileHandle *check_valid_file_handle_int32(int32_t handle, const char *operation_name);
 Stream *get_valid_file_stream_from_handle(int32_t handle, const char *operation_name);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/game.h b/engines/ags/engine/ac/game.h
index 5466ead57a..a977f74421 100644
--- a/engines/ags/engine/ac/game.h
+++ b/engines/ags/engine/ac/game.h
@@ -33,13 +33,16 @@
 #include "main/game_file.h"
 #include "util/string.h"
 
+namespace AGS3 {
+
 // Forward declaration
 namespace AGS {
 namespace Common {
 class Bitmap;
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 #define RAGMODE_PRESERVEGLOBALINT 1
@@ -203,4 +206,6 @@ extern unsigned int loopcounter;
 extern void set_loop_counter(unsigned int new_counter);
 extern int game_paused;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/gamesetup.h b/engines/ags/engine/ac/gamesetup.h
index 9bb46ca099..45c3821132 100644
--- a/engines/ags/engine/ac/gamesetup.h
+++ b/engines/ags/engine/ac/gamesetup.h
@@ -26,6 +26,7 @@
 #include "main/graphics_mode.h"
 #include "util/string.h"
 
+namespace AGS3 {
 
 // Mouse control activation type
 enum MouseControlWhen {
@@ -89,4 +90,6 @@ struct GameSetup {
 // Perhaps it makes sense to separate those two group of vars at some point.
 extern GameSetup usetup;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/gamestate.h b/engines/ags/engine/ac/gamestate.h
index a594e5391a..acf3d48452 100644
--- a/engines/ags/engine/ac/gamestate.h
+++ b/engines/ags/engine/ac/gamestate.h
@@ -36,18 +36,22 @@
 #include "util/string.h"
 #include "ac/timer.h"
 
+namespace AGS3 {
+
 // Forward declaration
 namespace AGS {
 namespace Common {
 class Bitmap;
 class Stream;
 typedef std::shared_ptr<Bitmap> PBitmap;
-}
+} // namespace Shared
+
 namespace Engine {
 struct RestoredData;
-}
-}
+} // namespace Engine
+} // namespace AGS
 using namespace AGS; // FIXME later
+
 struct ScriptViewport;
 struct ScriptCamera;
 
@@ -56,14 +60,13 @@ struct ScriptCamera;
 // Savegame data format
 enum GameStateSvgVersion {
 	kGSSvgVersion_OldFormat = -1, // TODO: remove after old save support is dropped
-	kGSSvgVersion_Initial   = 0,
-	kGSSvgVersion_350       = 1,
-	kGSSvgVersion_3509      = 2,
-	kGSSvgVersion_3510      = 3,
+	kGSSvgVersion_Initial = 0,
+	kGSSvgVersion_350 = 1,
+	kGSSvgVersion_3509 = 2,
+	kGSSvgVersion_3510 = 3,
 };
 
 
-
 // Adding to this might need to modify AGSDEFNS.SH and AGSPLUGIN.H
 struct GameState {
 	int  score;      // player's current score
@@ -220,7 +223,7 @@ struct GameState {
 	int   gamma_adjustment;
 	short temporarily_turned_off_character;  // Hide Player Charactr ticked
 	short inv_backwards_compatibility;
-	int  *gui_draw_order;
+	int *gui_draw_order;
 	std::vector<AGS::Common::String> do_once_tokens;
 	int   text_min_display_time_ms;
 	int   ignore_user_input_after_text_timeout_ms;
@@ -354,7 +357,7 @@ struct GameState {
 	void ReadQueuedAudioItems_Aligned(Common::Stream *in);
 	void ReadCustomProperties_v340(Common::Stream *in);
 	void WriteCustomProperties_v340(Common::Stream *out) const;
-	void ReadFromSavegame(Common::Stream *in,  GameStateSvgVersion svg_ver, AGS::Engine::RestoredData &r_data);
+	void ReadFromSavegame(Common::Stream *in, GameStateSvgVersion svg_ver, AGS::Engine::RestoredData &r_data);
 	void WriteForSavegame(Common::Stream *out) const;
 	void FreeProperties();
 	void FreeViewportsAndCameras();
@@ -400,4 +403,6 @@ HorAlignment ReadScriptAlignment(int32_t align);
 
 extern GameState play;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_audio.h b/engines/ags/engine/ac/global_audio.h
index d30be09dbe..4c14d539f5 100644
--- a/engines/ags/engine/ac/global_audio.h
+++ b/engines/ags/engine/ac/global_audio.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_AC_GLOBALAUDIO_H
 #define AGS_ENGINE_AC_GLOBALAUDIO_H
 
+namespace AGS3 {
+
 void    StopAmbientSound(int channel);
 void    PlayAmbientSound(int channel, int sndnum, int vol, int x, int y);
 int     IsChannelPlaying(int chan);
@@ -73,4 +75,6 @@ void    stop_voice_speech();
 // Stop non-blocking voice-over and revert audio volumes if necessary
 void    stop_voice_nonblocking();
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_button.h b/engines/ags/engine/ac/global_button.h
index ee7fb5dbb4..dbda062063 100644
--- a/engines/ags/engine/ac/global_button.h
+++ b/engines/ags/engine/ac/global_button.h
@@ -23,9 +23,13 @@
 #ifndef AGS_ENGINE_AC_GLOBALBUTTON_H
 #define AGS_ENGINE_AC_GLOBALBUTTON_H
 
+namespace AGS3 {
+
 void SetButtonText(int guin, int objn, const char *newtx);
 void AnimateButton(int guin, int objn, int view, int loop, int speed, int repeat);
 int  GetButtonPic(int guin, int objn, int ptype);
 void SetButtonPic(int guin, int objn, int ptype, int slotn);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_character.h b/engines/ags/engine/ac/global_character.h
index 213df919d2..ac9acb19d5 100644
--- a/engines/ags/engine/ac/global_character.h
+++ b/engines/ags/engine/ac/global_character.h
@@ -25,6 +25,8 @@
 
 #include "ac/characterinfo.h"
 
+namespace AGS3 {
+
 void StopMoving(int chaa);
 void ReleaseCharacterView(int chat);
 void MoveToWalkableArea(int charid);
@@ -89,4 +91,6 @@ void __sc_displayspeech(int chid, const char *text);
 void DisplaySpeechAt(int xx, int yy, int wii, int aschar, const char *spch);
 int DisplaySpeechBackground(int charid, const char *speel);
 
+} // nemspace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_datetime.h b/engines/ags/engine/ac/global_datetime.h
index 8997023661..6edcbe2307 100644
--- a/engines/ags/engine/ac/global_datetime.h
+++ b/engines/ags/engine/ac/global_datetime.h
@@ -23,7 +23,11 @@
 #ifndef AGS_ENGINE_AC_GLOBALDATETIME_H
 #define AGS_ENGINE_AC_GLOBALDATETIME_H
 
-int sc_GetTime(int whatti) ;
+namespace AGS3 {
+
+int sc_GetTime(int whatti);
 int GetRawTime();
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_debug.h b/engines/ags/engine/ac/global_debug.h
index 6019593cbd..cf2bc81a2f 100644
--- a/engines/ags/engine/ac/global_debug.h
+++ b/engines/ags/engine/ac/global_debug.h
@@ -26,7 +26,11 @@
 #include <cstdio>
 #include "util/string.h"
 
+namespace AGS3 {
+
 AGS::Common::String GetRuntimeInfo();
 void script_debug(int cmdd, int dataa);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_dialog.h b/engines/ags/engine/ac/global_dialog.h
index b9733d4101..6100bd17f9 100644
--- a/engines/ags/engine/ac/global_dialog.h
+++ b/engines/ags/engine/ac/global_dialog.h
@@ -23,9 +23,13 @@
 #ifndef AGS_ENGINE_AC_GLOBALDIALOG_H
 #define AGS_ENGINE_AC_GLOBALDIALOG_H
 
+namespace AGS3 {
+
 void RunDialog(int tum);
 int GetDialogOption(int dlg, int opt);
 void SetDialogOption(int dlg, int opt, int onoroff, bool dlg_script = false);
 void StopDialog();
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_display.h b/engines/ags/engine/ac/global_display.h
index 8f6f1397ac..29652e893b 100644
--- a/engines/ags/engine/ac/global_display.h
+++ b/engines/ags/engine/ac/global_display.h
@@ -25,6 +25,8 @@
 
 #include "ac/speech.h"
 
+namespace AGS3 {
+
 void Display(const char *texx, ...); // applies translation
 void DisplaySimple(const char *text); // does not apply translation
 void DisplayAt(int xxp, int yyp, int widd, const char *text);
@@ -39,4 +41,6 @@ void SetSpeechStyle(int newstyle);
 void SetSkipSpeech(SkipSpeechStyle newval);
 SkipSpeechStyle GetSkipSpeech();
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_drawingsurface.h b/engines/ags/engine/ac/global_drawingsurface.h
index e9b2626e86..05a1ce7145 100644
--- a/engines/ags/engine/ac/global_drawingsurface.h
+++ b/engines/ags/engine/ac/global_drawingsurface.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_AC_GLOBALDRAWINGSURFACE_H
 #define AGS_ENGINE_AC_GLOBALDRAWINGSURFACE_H
 
+namespace AGS3 {
+
 void RawSaveScreen();
 // RawRestoreScreen: copy backup bitmap back to screen; we
 // deliberately don't free the Common::Bitmap *cos they can multiple restore
@@ -46,4 +48,6 @@ void RawDrawCircle(int xx, int yy, int rad);
 void RawDrawRectangle(int x1, int y1, int x2, int y2);
 void RawDrawTriangle(int x1, int y1, int x2, int y2, int x3, int y3);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_dynamicsprite.h b/engines/ags/engine/ac/global_dynamicsprite.h
index db6fe2d06d..a294804917 100644
--- a/engines/ags/engine/ac/global_dynamicsprite.h
+++ b/engines/ags/engine/ac/global_dynamicsprite.h
@@ -23,6 +23,10 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_DYNAMICSPRITE_H
 #define AGS_ENGINE_AC_GLOBAL_DYNAMICSPRITE_H
 
+namespace AGS3 {
+
 int LoadImageFile(const char *filename);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_file.h b/engines/ags/engine/ac/global_file.h
index 3e58cfdc10..78afe03a0d 100644
--- a/engines/ags/engine/ac/global_file.h
+++ b/engines/ags/engine/ac/global_file.h
@@ -25,11 +25,13 @@
 
 #include "util/file.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 int32_t FileOpen(const char *fnmm, Common::FileOpenMode open_mode, Common::FileWorkMode work_mode);
@@ -47,4 +49,6 @@ char  FileReadRawChar(int32_t handle);
 int   FileReadRawInt(int32_t handle);
 void  FileWriteRawChar(int32_t handle, int chartoWrite);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_game.h b/engines/ags/engine/ac/global_game.h
index d777fafef3..d60b9d8329 100644
--- a/engines/ags/engine/ac/global_game.h
+++ b/engines/ags/engine/ac/global_game.h
@@ -24,6 +24,9 @@
 #define AGS_ENGINE_AC_GLOBAL_GAME_H
 
 #include "util/string.h"
+
+namespace AGS3 {
+
 using namespace AGS; // FIXME later
 
 void GiveScore(int amnt);
@@ -90,4 +93,6 @@ int WaitMouse(int nloops);
 int WaitMouseKey(int nloops);
 void SkipWait();
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_gui.h b/engines/ags/engine/ac/global_gui.h
index 3539a5cf1d..f08863caab 100644
--- a/engines/ags/engine/ac/global_gui.h
+++ b/engines/ags/engine/ac/global_gui.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_GUI_H
 #define AGS_ENGINE_AC_GLOBAL_GUI_H
 
+namespace AGS3 {
+
 // IsGUIOn tells whether GUI is actually displayed on screen right now
 int  IsGUIOn(int guinum);
 // This is an internal script function, and is undocumented.
@@ -56,4 +58,6 @@ int GetGUIObjectAt(int xx, int yy);
 int GetGUIAt(int xx, int yy);
 void SetTextWindowGUI(int guinum);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_hotspot.h b/engines/ags/engine/ac/global_hotspot.h
index 36eb184670..b4b800b758 100644
--- a/engines/ags/engine/ac/global_hotspot.h
+++ b/engines/ags/engine/ac/global_hotspot.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_HOTSPOT_H
 #define AGS_ENGINE_AC_GLOBAL_HOTSPOT_H
 
+namespace AGS3 {
+
 void DisableHotspot(int hsnum);
 void EnableHotspot(int hsnum);
 int  GetHotspotPointX(int hotspot);
@@ -36,5 +38,6 @@ void RunHotspotInteraction(int hotspothere, int mood);
 int  GetHotspotProperty(int hss, const char *property);
 void GetHotspotPropertyText(int item, const char *property, char *bufer);
 
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/ac/global_inventoryitem.h b/engines/ags/engine/ac/global_inventoryitem.h
index 332a59cf06..11c6b9ccfa 100644
--- a/engines/ags/engine/ac/global_inventoryitem.h
+++ b/engines/ags/engine/ac/global_inventoryitem.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_INVENTORYITEM_H
 #define AGS_ENGINE_AC_GLOBAL_INVENTORYITEM_H
 
+namespace AGS3 {
+
 void set_inv_item_pic(int invi, int piccy);
 void SetInvItemName(int invi, const char *newName);
 int  GetInvAt(int xxx, int yyy);
@@ -33,4 +35,6 @@ int  IsInventoryInteractionAvailable(int item, int mood);
 int  GetInvProperty(int item, const char *property);
 void GetInvPropertyText(int item, const char *property, char *bufer);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_invwindow.h b/engines/ags/engine/ac/global_invwindow.h
index 7e952fd0e6..ad79a6c6f3 100644
--- a/engines/ags/engine/ac/global_invwindow.h
+++ b/engines/ags/engine/ac/global_invwindow.h
@@ -23,7 +23,11 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_INVWINDOW_H
 #define AGS_ENGINE_AC_GLOBAL_INVWINDOW_H
 
+namespace AGS3 {
+
 void sc_invscreen();
 void SetInvDimensions(int ww, int hh);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_label.h b/engines/ags/engine/ac/global_label.h
index 5c75f8b08f..7417478504 100644
--- a/engines/ags/engine/ac/global_label.h
+++ b/engines/ags/engine/ac/global_label.h
@@ -23,8 +23,12 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_LABEL_H
 #define AGS_ENGINE_AC_GLOBAL_LABEL_H
 
-void        SetLabelColor(int guin, int objn, int colr);
-void        SetLabelText(int guin, int objn, const char *newtx);
-void        SetLabelFont(int guin, int objn, int fontnum);
+namespace AGS3 {
+
+void SetLabelColor(int guin, int objn, int colr);
+void SetLabelText(int guin, int objn, const char *newtx);
+void SetLabelFont(int guin, int objn, int fontnum);
+
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/ac/global_listbox.h b/engines/ags/engine/ac/global_listbox.h
index 2d781cb425..7ca1b79c36 100644
--- a/engines/ags/engine/ac/global_listbox.h
+++ b/engines/ags/engine/ac/global_listbox.h
@@ -23,15 +23,19 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_LISTBOX_H
 #define AGS_ENGINE_AC_GLOBAL_LISTBOX_H
 
+namespace AGS3 {
+
 void        ListBoxClear(int guin, int objn);
 void        ListBoxAdd(int guin, int objn, const char *newitem);
 void        ListBoxRemove(int guin, int objn, int itemIndex);
 int         ListBoxGetSelected(int guin, int objn);
 int         ListBoxGetNumItems(int guin, int objn);
-char       *ListBoxGetItemText(int guin, int objn, int item, char *buffer);
+char *ListBoxGetItemText(int guin, int objn, int item, char *buffer);
 void        ListBoxSetSelected(int guin, int objn, int newsel);
 void        ListBoxSetTopItem(int guin, int objn, int item);
 int         ListBoxSaveGameList(int guin, int objn);
 void        ListBoxDirList(int guin, int objn, const char *filemask);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_mouse.h b/engines/ags/engine/ac/global_mouse.h
index ecf0162743..6e49d30674 100644
--- a/engines/ags/engine/ac/global_mouse.h
+++ b/engines/ags/engine/ac/global_mouse.h
@@ -23,7 +23,11 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_MOUSE_H
 #define AGS_ENGINE_AC_GLOBAL_MOUSE_H
 
+namespace AGS3 {
+
 void HideMouseCursor();
 void ShowMouseCursor();
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_object.h b/engines/ags/engine/ac/global_object.h
index 9e0e947785..05e521356e 100644
--- a/engines/ags/engine/ac/global_object.h
+++ b/engines/ags/engine/ac/global_object.h
@@ -23,11 +23,13 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_OBJECT_H
 #define AGS_ENGINE_AC_GLOBAL_OBJECT_H
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 class Bitmap;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 // TODO: merge with other Rect declared in bitmap unit
@@ -77,4 +79,6 @@ void GetObjectPropertyText(int item, const char *property, char *bufer);
 
 Common::Bitmap *GetObjectImage(int obj, int *isFlipped);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_overlay.h b/engines/ags/engine/ac/global_overlay.h
index 5b2e9c8439..2b11c972cf 100644
--- a/engines/ags/engine/ac/global_overlay.h
+++ b/engines/ags/engine/ac/global_overlay.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_AC_GLOBALOVERLAY_H
 #define AGS_ENGINE_AC_GLOBALOVERLAY_H
 
+namespace AGS3 {
+
 void RemoveOverlay(int ovrid);
 int  CreateGraphicOverlay(int xx, int yy, int slott, int trans);
 int  CreateTextOverlayCore(int xx, int yy, int wii, int fontid, int text_color, const char *text, int disp_type, int allowShrink);
@@ -31,4 +33,6 @@ void SetTextOverlay(int ovrid, int xx, int yy, int wii, int fontid, int text_col
 void MoveOverlay(int ovrid, int newx, int newy);
 int  IsOverlayValid(int ovrid);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_palette.h b/engines/ags/engine/ac/global_palette.h
index 13ff58ab57..dcfb20b34e 100644
--- a/engines/ags/engine/ac/global_palette.h
+++ b/engines/ags/engine/ac/global_palette.h
@@ -23,8 +23,12 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_PALETTE_H
 #define AGS_ENGINE_AC_GLOBAL_PALETTE_H
 
+namespace AGS3 {
+
 void CyclePalette(int strt, int eend);
 void SetPalRGB(int inndx, int rr, int gg, int bb);
 void UpdatePalette();
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_parser.h b/engines/ags/engine/ac/global_parser.h
index b3e99bd5e4..522b871dd1 100644
--- a/engines/ags/engine/ac/global_parser.h
+++ b/engines/ags/engine/ac/global_parser.h
@@ -23,6 +23,10 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_PARSER_H
 #define AGS_ENGINE_AC_GLOBAL_PARSER_H
 
+namespace AGS3 {
+
 int SaidUnknownWord(char *buffer);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_plugin.h b/engines/ags/engine/ac/global_plugin.h
index 193c1dc99d..308f2f148e 100644
--- a/engines/ags/engine/ac/global_plugin.h
+++ b/engines/ags/engine/ac/global_plugin.h
@@ -23,7 +23,11 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_PLUGIN_H
 #define AGS_ENGINE_AC_GLOBAL_PLUGIN_H
 
+namespace AGS3 {
+
 void PluginSimulateMouseClick(int pluginButtonID);
 bool RegisterPluginStubs(const char *name);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_record.h b/engines/ags/engine/ac/global_record.h
index b459b0c15e..eeaa6849b8 100644
--- a/engines/ags/engine/ac/global_record.h
+++ b/engines/ags/engine/ac/global_record.h
@@ -23,6 +23,10 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_RECORD_H
 #define AGS_ENGINE_AC_GLOBAL_RECORD_H
 
+namespace AGS3 {
+
 void scStartRecording(int keyToStop);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_region.h b/engines/ags/engine/ac/global_region.h
index 205a45f90c..93fec2cb0c 100644
--- a/engines/ags/engine/ac/global_region.h
+++ b/engines/ags/engine/ac/global_region.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_REGION_H
 #define AGS_ENGINE_AC_GLOBAL_REGION_H
 
+namespace AGS3 {
+
 // Gets region ID at the given room coordinates;
 // if region is disabled or non-existing, returns 0 (no area)
 int  GetRegionIDAtRoom(int xxx, int yyy);
@@ -34,4 +36,6 @@ void DisableGroundLevelAreas(int alsoEffects);
 void EnableGroundLevelAreas();
 void RunRegionInteraction(int regnum, int mood);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_room.h b/engines/ags/engine/ac/global_room.h
index 7bf95ed306..178957a73e 100644
--- a/engines/ags/engine/ac/global_room.h
+++ b/engines/ags/engine/ac/global_room.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_ROOM_H
 #define AGS_ENGINE_AC_GLOBAL_ROOM_H
 
+namespace AGS3 {
+
 void SetAmbientTint(int red, int green, int blue, int opacity, int luminance);
 void SetAmbientLightLevel(int light_level);
 void NewRoom(int nrnum);
@@ -35,6 +37,8 @@ int  HasBeenToRoom(int roomnum);
 void GetRoomPropertyText(const char *property, char *bufer);
 
 void SetBackgroundFrame(int frnum);
-int GetBackgroundFrame() ;
+int GetBackgroundFrame();
+
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/ac/global_screen.h b/engines/ags/engine/ac/global_screen.h
index 1807e115f1..feeb90dcc5 100644
--- a/engines/ags/engine/ac/global_screen.h
+++ b/engines/ags/engine/ac/global_screen.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_SCREEN_H
 #define AGS_ENGINE_AC_GLOBAL_SCREEN_H
 
+namespace AGS3 {
+
 void FlipScreen(int amount);
 void ShakeScreen(int severe);
 void ShakeScreenBackground(int delay, int amount, int length);
@@ -33,4 +35,6 @@ void SetNextScreenTransition(int newtrans);
 void SetFadeColor(int red, int green, int blue);
 void FadeIn(int sppd);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_slider.h b/engines/ags/engine/ac/global_slider.h
index bef7247ac0..88fa05f265 100644
--- a/engines/ags/engine/ac/global_slider.h
+++ b/engines/ags/engine/ac/global_slider.h
@@ -23,7 +23,11 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_SLIDER_H
 #define AGS_ENGINE_AC_GLOBAL_SLIDER_H
 
+namespace AGS3 {
+
 void    SetSliderValue(int guin, int objn, int valn);
 int     GetSliderValue(int guin, int objn);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_string.h b/engines/ags/engine/ac/global_string.h
index 88ce8319f0..370acf6c49 100644
--- a/engines/ags/engine/ac/global_string.h
+++ b/engines/ags/engine/ac/global_string.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_STRING_H
 #define AGS_ENGINE_AC_GLOBAL_STRING_H
 
+namespace AGS3 {
+
 int StrGetCharAt(const char *strin, int posn);
 void StrSetCharAt(char *strin, int posn, int nchar);
 void _sc_strcat(char *s1, const char *s2);
@@ -30,4 +32,6 @@ void _sc_strlower(char *desbuf);
 void _sc_strupper(char *desbuf);
 void _sc_strcpy(char *destt, const char *text);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_textbox.h b/engines/ags/engine/ac/global_textbox.h
index bd95b85c4e..c1ecef7399 100644
--- a/engines/ags/engine/ac/global_textbox.h
+++ b/engines/ags/engine/ac/global_textbox.h
@@ -23,8 +23,12 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_TEXTBOX_H
 #define AGS_ENGINE_AC_GLOBAL_TEXTBOX_H
 
+namespace AGS3 {
+
 void SetTextBoxFont(int guin, int objn, int fontnum);
 void GetTextBoxText(int guin, int objn, char *txbuf);
 void SetTextBoxText(int guin, int objn, const char *txbuf);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_timer.h b/engines/ags/engine/ac/global_timer.h
index 17b0b78a04..380573c723 100644
--- a/engines/ags/engine/ac/global_timer.h
+++ b/engines/ags/engine/ac/global_timer.h
@@ -23,7 +23,11 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_TIMER_H
 #define AGS_ENGINE_AC_GLOBAL_TIMER_H
 
+namespace AGS3 {
+
 void script_SetTimer(int tnum, int timeout);
 int  IsTimerExpired(int tnum);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_translation.h b/engines/ags/engine/ac/global_translation.h
index 4c2d7a54eb..8d761d8082 100644
--- a/engines/ags/engine/ac/global_translation.h
+++ b/engines/ags/engine/ac/global_translation.h
@@ -23,8 +23,12 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_TRANSLATION_H
 #define AGS_ENGINE_AC_GLOBAL_TRANSLATION_H
 
+namespace AGS3 {
+
 const char *get_translation(const char *text);
 int IsTranslationAvailable();
 int GetTranslationName(char *buffer);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_video.h b/engines/ags/engine/ac/global_video.h
index 3996ccad9b..907252bdb9 100644
--- a/engines/ags/engine/ac/global_video.h
+++ b/engines/ags/engine/ac/global_video.h
@@ -23,7 +23,11 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_VIDEO_H
 #define AGS_ENGINE_AC_GLOBAL_VIDEO_H
 
+namespace AGS3 {
+
 void scrPlayVideo(const char *name, int skip, int flags);
 void pause_sound_if_necessary_and_play_video(const char *name, int skip, int flags);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_viewframe.h b/engines/ags/engine/ac/global_viewframe.h
index f06119ba9e..b6b221d4b1 100644
--- a/engines/ags/engine/ac/global_viewframe.h
+++ b/engines/ags/engine/ac/global_viewframe.h
@@ -23,6 +23,10 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_VIEWFRAME_H
 #define AGS_ENGINE_AC_GLOBAL_VIEWFRAME_H
 
+namespace AGS3 {
+
 void SetFrameSound(int vii, int loop, int frame, int sound);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_viewport.h b/engines/ags/engine/ac/global_viewport.h
index f8bf12179b..1a5f656bda 100644
--- a/engines/ags/engine/ac/global_viewport.h
+++ b/engines/ags/engine/ac/global_viewport.h
@@ -23,9 +23,13 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_VIEWPORT_H
 #define AGS_ENGINE_AC_GLOBAL_VIEWPORT_H
 
+namespace AGS3 {
+
 void SetViewport(int offsx, int offsy);
 void ReleaseViewport();
 int  GetViewportX();
 int  GetViewportY();
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_walkablearea.h b/engines/ags/engine/ac/global_walkablearea.h
index 837f677fcc..b69cbc1fa6 100644
--- a/engines/ags/engine/ac/global_walkablearea.h
+++ b/engines/ags/engine/ac/global_walkablearea.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_WALKABLEAREA_H
 #define AGS_ENGINE_AC_GLOBAL_WALKABLEAREA_H
 
+namespace AGS3 {
+
 int   GetScalingAt(int x, int y);
 void  SetAreaScaling(int area, int min, int max);
 void  RemoveWalkableArea(int areanum);
@@ -34,4 +36,6 @@ int   GetWalkableAreaAtRoom(int x, int y);
 // if area is disabled or non-existing, returns 0 (no area)
 int   GetWalkableAreaAtScreen(int x, int y);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/global_walkbehind.h b/engines/ags/engine/ac/global_walkbehind.h
index 0243a3a1ee..f36404a7c6 100644
--- a/engines/ags/engine/ac/global_walkbehind.h
+++ b/engines/ags/engine/ac/global_walkbehind.h
@@ -23,6 +23,10 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_WALKBEHIND_H
 #define AGS_ENGINE_AC_GLOBAL_WALKBEHIND_H
 
+namespace AGS3 {
+
 void SetWalkBehindBase(int wa, int bl);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/gui.h b/engines/ags/engine/ac/gui.h
index 9a2eb055cc..1cb7629dfd 100644
--- a/engines/ags/engine/ac/gui.h
+++ b/engines/ags/engine/ac/gui.h
@@ -26,6 +26,8 @@
 #include "ac/dynobj/scriptgui.h"
 #include "gui/guimain.h"
 
+namespace AGS3 {
+
 using AGS::Common::GUIMain;
 using AGS::Common::GUIObject;
 
@@ -90,4 +92,6 @@ extern int ifacepopped;
 extern int ifacepopped;
 extern int mouse_on_iface;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/guicontrol.h b/engines/ags/engine/ac/guicontrol.h
index b0527ebfb5..1f8d60ef3d 100644
--- a/engines/ags/engine/ac/guicontrol.h
+++ b/engines/ags/engine/ac/guicontrol.h
@@ -32,6 +32,8 @@
 #include "gui/guitextbox.h"
 #include "ac/dynobj/scriptgui.h"
 
+namespace AGS3 {
+
 using AGS::Common::GUIObject;
 using AGS::Common::GUIButton;
 using AGS::Common::GUIInvWindow;
@@ -40,7 +42,7 @@ using AGS::Common::GUIListBox;
 using AGS::Common::GUISlider;
 using AGS::Common::GUITextBox;
 
-GUIObject   *GetGUIControlAtLocation(int xx, int yy);
+GUIObject *GetGUIControlAtLocation(int xx, int yy);
 int         GUIControl_GetVisible(GUIObject *guio);
 void        GUIControl_SetVisible(GUIObject *guio, int visible);
 int         GUIControl_GetClickable(GUIObject *guio);
@@ -48,12 +50,12 @@ void        GUIControl_SetClickable(GUIObject *guio, int enabled);
 int         GUIControl_GetEnabled(GUIObject *guio);
 void        GUIControl_SetEnabled(GUIObject *guio, int enabled);
 int         GUIControl_GetID(GUIObject *guio);
-ScriptGUI  *GUIControl_GetOwningGUI(GUIObject *guio);
-GUIButton  *GUIControl_GetAsButton(GUIObject *guio);
+ScriptGUI *GUIControl_GetOwningGUI(GUIObject *guio);
+GUIButton *GUIControl_GetAsButton(GUIObject *guio);
 GUIInvWindow *GUIControl_GetAsInvWindow(GUIObject *guio);
-GUILabel   *GUIControl_GetAsLabel(GUIObject *guio);
+GUILabel *GUIControl_GetAsLabel(GUIObject *guio);
 GUIListBox *GUIControl_GetAsListBox(GUIObject *guio);
-GUISlider  *GUIControl_GetAsSlider(GUIObject *guio);
+GUISlider *GUIControl_GetAsSlider(GUIObject *guio);
 GUITextBox *GUIControl_GetAsTextBox(GUIObject *guio);
 int         GUIControl_GetX(GUIObject *guio);
 void        GUIControl_SetX(GUIObject *guio, int xx);
@@ -70,4 +72,6 @@ void        GUIControl_SetSize(GUIObject *guio, int newwid, int newhit);
 void        GUIControl_SendToBack(GUIObject *guio);
 void        GUIControl_BringToFront(GUIObject *guio);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/hotspot.h b/engines/ags/engine/ac/hotspot.h
index 226ab4ef6d..a495b0df2f 100644
--- a/engines/ags/engine/ac/hotspot.h
+++ b/engines/ags/engine/ac/hotspot.h
@@ -25,6 +25,8 @@
 
 #include "ac/dynobj/scripthotspot.h"
 
+namespace AGS3 {
+
 void    Hotspot_SetEnabled(ScriptHotspot *hss, int newval);
 int     Hotspot_GetEnabled(ScriptHotspot *hss);
 int     Hotspot_GetID(ScriptHotspot *hss);
@@ -44,4 +46,6 @@ const char *Hotspot_GetTextProperty(ScriptHotspot *hss, const char *property);
 // if hotspot is disabled or non-existing, returns 0 (no area)
 int     get_hotspot_at(int xpp, int ypp);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/inventoryitem.h b/engines/ags/engine/ac/inventoryitem.h
index 6159b1e9dd..991526059d 100644
--- a/engines/ags/engine/ac/inventoryitem.h
+++ b/engines/ags/engine/ac/inventoryitem.h
@@ -25,6 +25,8 @@
 
 #include "ac/dynobj/scriptinvitem.h"
 
+namespace AGS3 {
+
 void InventoryItem_SetCursorGraphic(ScriptInvItem *iitem, int newSprite);
 int  InventoryItem_GetCursorGraphic(ScriptInvItem *iitem);
 void InventoryItem_SetGraphic(ScriptInvItem *iitem, int piccy);
@@ -42,4 +44,6 @@ const char *InventoryItem_GetTextProperty(ScriptInvItem *scii, const char *prope
 
 void set_inv_item_cursorpic(int invItemId, int piccy);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/invwindow.h b/engines/ags/engine/ac/invwindow.h
index 4e46eec472..29f9c3ace2 100644
--- a/engines/ags/engine/ac/invwindow.h
+++ b/engines/ags/engine/ac/invwindow.h
@@ -27,10 +27,12 @@
 #include "ac/dynobj/scriptinvitem.h"
 #include "gui/guiinv.h"
 
+namespace AGS3 {
+
 using AGS::Common::GUIInvWindow;
 
 void            InvWindow_SetCharacterToUse(GUIInvWindow *guii, CharacterInfo *chaa);
-CharacterInfo  *InvWindow_GetCharacterToUse(GUIInvWindow *guii);
+CharacterInfo *InvWindow_GetCharacterToUse(GUIInvWindow *guii);
 void            InvWindow_SetItemWidth(GUIInvWindow *guii, int newwidth);
 int             InvWindow_GetItemWidth(GUIInvWindow *guii);
 void            InvWindow_SetItemHeight(GUIInvWindow *guii, int newhit);
@@ -42,7 +44,7 @@ int             InvWindow_GetItemCount(GUIInvWindow *guii);
 int             InvWindow_GetRowCount(GUIInvWindow *guii);
 void            InvWindow_ScrollDown(GUIInvWindow *guii);
 void            InvWindow_ScrollUp(GUIInvWindow *guii);
-ScriptInvItem  *InvWindow_GetItemAtIndex(GUIInvWindow *guii, int index);
+ScriptInvItem *InvWindow_GetItemAtIndex(GUIInvWindow *guii, int index);
 
 //=============================================================================
 
@@ -50,4 +52,6 @@ int             offset_over_inv(GUIInvWindow *inv);
 // NOTE: This function is valid for AGS 2.72 and lower
 int             invscreen();
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/keycode.h b/engines/ags/engine/ac/keycode.h
index 63c944bad8..ddfcf071d6 100644
--- a/engines/ags/engine/ac/keycode.h
+++ b/engines/ags/engine/ac/keycode.h
@@ -25,6 +25,8 @@
 
 #include "core/platform.h"
 
+namespace AGS3 {
+
 #define EXTENDED_KEY_CODE ('\0')
 #define EXTENDED_KEY_CODE_MACOS ('?')
 
@@ -176,4 +178,6 @@ int GetKeyForKeyPressCb(int keycode);
 // Returns -1 if not found.
 int PlatformKeyFromAgsKey(int key);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/label.h b/engines/ags/engine/ac/label.h
index 687c77c0f8..a1102b8d0f 100644
--- a/engines/ags/engine/ac/label.h
+++ b/engines/ags/engine/ac/label.h
@@ -25,6 +25,8 @@
 
 #include "gui/guilabel.h"
 
+namespace AGS3 {
+
 using AGS::Common::GUILabel;
 
 const char *Label_GetText_New(GUILabel *labl);
@@ -35,4 +37,6 @@ void        Label_SetColor(GUILabel *labl, int colr);
 int         Label_GetFont(GUILabel *labl);
 void        Label_SetFont(GUILabel *guil, int fontnum);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/lipsync.h b/engines/ags/engine/ac/lipsync.h
index 6508c6813f..d5ef6e2bbf 100644
--- a/engines/ags/engine/ac/lipsync.h
+++ b/engines/ags/engine/ac/lipsync.h
@@ -23,11 +23,15 @@
 #ifndef AGS_ENGINE_AC_LIPSYNC_H
 #define AGS_ENGINE_AC_LIPSYNC_H
 
+namespace AGS3 {
+
 struct SpeechLipSyncLine {
 	char  filename[14];
-	int  *endtimeoffs;
+	int *endtimeoffs;
 	short *frame;
 	short numPhonemes;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/listbox.h b/engines/ags/engine/ac/listbox.h
index c0243a2277..96267dffd1 100644
--- a/engines/ags/engine/ac/listbox.h
+++ b/engines/ags/engine/ac/listbox.h
@@ -25,6 +25,8 @@
 
 #include "gui/guilistbox.h"
 
+namespace AGS3 {
+
 using AGS::Common::GUIListBox;
 
 int         ListBox_AddItem(GUIListBox *lbb, const char *text);
@@ -34,7 +36,7 @@ void        ListBox_FillDirList(GUIListBox *listbox, const char *filemask);
 int         ListBox_GetSaveGameSlots(GUIListBox *listbox, int index);
 int         ListBox_FillSaveGameList(GUIListBox *listbox);
 int         ListBox_GetItemAtLocation(GUIListBox *listbox, int x, int y);
-char        *ListBox_GetItemText(GUIListBox *listbox, int index, char *buffer);
+char *ListBox_GetItemText(GUIListBox *listbox, int index, char *buffer);
 const char *ListBox_GetItems(GUIListBox *listbox, int index);
 void        ListBox_SetItemText(GUIListBox *listbox, int index, const char *newtext);
 void        ListBox_RemoveItem(GUIListBox *listbox, int itemIndex);
@@ -55,4 +57,6 @@ void        ListBox_ScrollUp(GUIListBox *listbox);
 
 GUIListBox *is_valid_listbox(int guin, int objn);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/math.h b/engines/ags/engine/ac/math.h
index bd3d3f7f1e..07e3ae45b1 100644
--- a/engines/ags/engine/ac/math.h
+++ b/engines/ags/engine/ac/math.h
@@ -25,6 +25,8 @@
 
 #include "core/types.h"
 
+namespace AGS3 {
+
 enum RoundDirections {
 	eRoundDown = 0,
 	eRoundNearest = 1,
@@ -57,4 +59,6 @@ float Math_Sqrt(float value);
 int __Rand(int upto);
 #define Random __Rand
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/mouse.h b/engines/ags/engine/ac/mouse.h
index 02893e2619..455df017f4 100644
--- a/engines/ags/engine/ac/mouse.h
+++ b/engines/ags/engine/ac/mouse.h
@@ -25,6 +25,8 @@
 
 #include "ac/dynobj/scriptmouse.h"
 
+namespace AGS3 {
+
 #define DOMOUSE_UPDATE 0
 #define DOMOUSE_ENABLE 1
 #define DOMOUSE_DISABLE 2
@@ -78,4 +80,6 @@ extern ScriptMouse scmouse;
 extern int cur_mode;
 extern int cur_cursor;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/movelist.h b/engines/ags/engine/ac/movelist.h
index 8bde626f18..4533405518 100644
--- a/engines/ags/engine/ac/movelist.h
+++ b/engines/ags/engine/ac/movelist.h
@@ -26,12 +26,14 @@
 #include "util/wgt2allg.h" // fixed type
 #include "game/savegame.h"
 
+namespace AGS3 {
+
 // Forward declaration
 namespace AGS {
 namespace Common {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
 using namespace AGS; // FIXME later
 
 #define MAXNEEDSTAGES 256
@@ -52,4 +54,6 @@ struct MoveList {
 	void WriteToFile(Common::Stream *out);
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/object.h b/engines/ags/engine/ac/object.h
index 11f5d31b57..fc02fafc89 100644
--- a/engines/ags/engine/ac/object.h
+++ b/engines/ags/engine/ac/object.h
@@ -34,11 +34,14 @@
 #include "ac/common_defines.h"
 #include "ac/dynobj/scriptobject.h"
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Common {
 class Bitmap;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 extern AGS_INLINE int is_valid_object(int obtest);
@@ -100,4 +103,6 @@ int     is_pos_in_sprite(int xx, int yy, int arx, int ary, Common::Bitmap *sprit
 // X and Y are ROOM coordinates
 int     check_click_on_object(int roomx, int roomy, int mood);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/objectcache.h b/engines/ags/engine/ac/objectcache.h
index ba7a323ebe..6621698ed2 100644
--- a/engines/ags/engine/ac/objectcache.h
+++ b/engines/ags/engine/ac/objectcache.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_AC_OBJECTCACHE_H
 #define AGS_ENGINE_AC_OBJECTCACHE_H
 
+namespace AGS3 {
+
 // stores cached object info
 struct ObjectCache {
 	Common::Bitmap *image;
@@ -33,4 +35,6 @@ struct ObjectCache {
 	int   xwas, ywas;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/overlay.h b/engines/ags/engine/ac/overlay.h
index d5628fcc0e..958a8b8f33 100644
--- a/engines/ags/engine/ac/overlay.h
+++ b/engines/ags/engine/ac/overlay.h
@@ -27,11 +27,14 @@
 #include "ac/screenoverlay.h"
 #include "ac/dynobj/scriptoverlay.h"
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Common {
 class Bitmap;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 void Overlay_Remove(ScriptOverlay *sco);
@@ -58,4 +61,6 @@ extern int is_text_overlay; // blocking text overlay on screen
 
 extern std::vector<ScreenOverlay> screenover;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/parser.h b/engines/ags/engine/ac/parser.h
index 2f7431ac07..48b4f77f7b 100644
--- a/engines/ags/engine/ac/parser.h
+++ b/engines/ags/engine/ac/parser.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_AC_PARSER_H
 #define AGS_ENGINE_AC_PARSER_H
 
+namespace AGS3 {
+
 int Parser_FindWordID(const char *wordToFind);
 const char *Parser_SaidUnknownWord();
 void ParseText(const char *text);
@@ -35,4 +37,6 @@ int is_valid_word_char(char theChar);
 int FindMatchingMultiWordWord(char *thisword, const char **text);
 int parse_sentence(const char *src_text, int *numwords, short *wordarray, short *compareto, int comparetonum);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/path_helper.h b/engines/ags/engine/ac/path_helper.h
index 3761f15dac..e8768e936d 100644
--- a/engines/ags/engine/ac/path_helper.h
+++ b/engines/ags/engine/ac/path_helper.h
@@ -31,6 +31,8 @@
 
 #include "util/string.h"
 
+namespace AGS3 {
+
 using AGS::Common::String;
 
 // Filepath tokens, which are replaced by platform-specific directory names
@@ -81,4 +83,6 @@ String  get_audio_install_dir();
 String  get_voice_install_dir();
 void    get_install_dir_path(char *buffer, const char *fileName);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/properties.h b/engines/ags/engine/ac/properties.h
index 44bc30ffb3..ba829662a5 100644
--- a/engines/ags/engine/ac/properties.h
+++ b/engines/ags/engine/ac/properties.h
@@ -25,6 +25,8 @@
 
 #include "game/customproperties.h"
 
+namespace AGS3 {
+
 using AGS::Common::StringIMap;
 
 // Getting a property value requires static and runtime property maps.
@@ -39,4 +41,6 @@ const char *get_text_property_dynamic_string(const StringIMap &st_prop, const St
 bool set_int_property(StringIMap &rt_prop, const char *property, int value);
 bool set_text_property(StringIMap &rt_prop, const char *property, const char *value);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/region.h b/engines/ags/engine/ac/region.h
index 49a9688ed2..a5db946f13 100644
--- a/engines/ags/engine/ac/region.h
+++ b/engines/ags/engine/ac/region.h
@@ -25,6 +25,8 @@
 
 #include "ac/dynobj/scriptregion.h"
 
+namespace AGS3 {
+
 ScriptRegion *GetRegionAtRoom(int xx, int yy);
 void    Region_SetLightLevel(ScriptRegion *ssr, int brightness);
 int     Region_GetLightLevel(ScriptRegion *ssr);
@@ -42,4 +44,6 @@ void    Region_RunInteraction(ScriptRegion *ssr, int mood);
 
 void    generate_light_table();
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/richgamemedia.h b/engines/ags/engine/ac/richgamemedia.h
index faeac1760b..02bc1b1592 100644
--- a/engines/ags/engine/ac/richgamemedia.h
+++ b/engines/ags/engine/ac/richgamemedia.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_AC_RICHGAMEMEDIA_H
 #define AGS_ENGINE_AC_RICHGAMEMEDIA_H
 
+namespace AGS3 {
+
 // Windows Vista Rich Save Games, modified to be platform-agnostic
 
 #define RM_MAXLENGTH    1024
@@ -32,8 +34,9 @@
 namespace AGS {
 namespace Common {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 #pragma pack(push)
@@ -56,4 +59,6 @@ typedef struct _RICH_GAME_MEDIA_HEADER {
 } RICH_GAME_MEDIA_HEADER;
 #pragma pack(pop)
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/room.h b/engines/ags/engine/ac/room.h
index 0c3149e574..4b3e5789d3 100644
--- a/engines/ags/engine/ac/room.h
+++ b/engines/ags/engine/ac/room.h
@@ -28,6 +28,8 @@
 #include "script/runtimescriptvalue.h"
 #include "game/roomstruct.h"
 
+namespace AGS3 {
+
 ScriptDrawingSurface *Room_GetDrawingSurfaceForBackground(int backgroundNumber);
 ScriptDrawingSurface *Room_GetDrawingSurfaceForMask(RoomAreaMask mask);
 int Room_GetObjectCount();
@@ -76,4 +78,6 @@ void convert_move_path_to_room_resolution(MoveList *ml);
 
 extern AGS::Common::RoomStruct thisroom;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/roomobject.h b/engines/ags/engine/ac/roomobject.h
index 22dce65a76..2d8111b99b 100644
--- a/engines/ags/engine/ac/roomobject.h
+++ b/engines/ags/engine/ac/roomobject.h
@@ -25,11 +25,14 @@
 
 #include "ac/common_defines.h"
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Common {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 // IMPORTANT: this struct is restricted by plugin API!
@@ -72,4 +75,6 @@ struct RoomObject {
 	void WriteToFile(Common::Stream *out) const;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/roomstatus.h b/engines/ags/engine/ac/roomstatus.h
index 70e4701865..a00799e05c 100644
--- a/engines/ags/engine/ac/roomstatus.h
+++ b/engines/ags/engine/ac/roomstatus.h
@@ -28,12 +28,15 @@
 #include "game/interactions.h"
 #include "util/string_types.h"
 
+namespace AGS3 {
+
 // Forward declaration
 namespace AGS {
 namespace Common {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using AGS::Common::Stream;
 using AGS::Common::Interaction;
 
@@ -47,8 +50,8 @@ struct RoomStatus {
 	int   tsdatasize;
 	char *tsdata;
 	Interaction intrHotspot[MAX_ROOM_HOTSPOTS];
-	Interaction intrObject [MAX_ROOM_OBJECTS];
-	Interaction intrRegion [MAX_ROOM_REGIONS];
+	Interaction intrObject[MAX_ROOM_OBJECTS];
+	Interaction intrRegion[MAX_ROOM_REGIONS];
 	Interaction intrRoom;
 
 	Common::StringIMap roomProps;
@@ -86,4 +89,6 @@ RoomStatus *getRoomStatus(int room);
 bool isRoomStatusValid(int room);
 void resetRoomStatuses();
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/route_finder.h b/engines/ags/engine/ac/route_finder.h
index 17ee1af0ab..3cef9962fa 100644
--- a/engines/ags/engine/ac/route_finder.h
+++ b/engines/ags/engine/ac/route_finder.h
@@ -25,12 +25,15 @@
 
 #include "ac/game_version.h"
 
+namespace AGS3 {
+
 // Forward declaration
 namespace AGS {
 namespace Common {
 class Bitmap;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 struct MoveList;
 
 void init_pathfinder(GameDataVersion game_file_version);
@@ -46,4 +49,6 @@ void set_route_move_speed(int speed_x, int speed_y);
 int find_route(short srcx, short srcy, short xx, short yy, AGS::Common::Bitmap *onscreen, int movlst, int nocross = 0, int ignore_walls = 0);
 void calculate_move_stage(MoveList *mlsp, int aaa);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/route_finder_impl.h b/engines/ags/engine/ac/route_finder_impl.h
index dcc2a98437..43600c8fe9 100644
--- a/engines/ags/engine/ac/route_finder_impl.h
+++ b/engines/ags/engine/ac/route_finder_impl.h
@@ -25,12 +25,15 @@
 
 #include "ac/game_version.h"
 
+namespace AGS3 {
+
 // Forward declaration
 namespace AGS {
 namespace Common {
 class Bitmap;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 struct MoveList;
 
 namespace AGS {
@@ -53,5 +56,6 @@ void calculate_move_stage(MoveList *mlsp, int aaa);
 } // namespace RouteFinder
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/ac/route_finder_impl_legacy.h b/engines/ags/engine/ac/route_finder_impl_legacy.h
index 4da9d5017f..632038d524 100644
--- a/engines/ags/engine/ac/route_finder_impl_legacy.h
+++ b/engines/ags/engine/ac/route_finder_impl_legacy.h
@@ -23,12 +23,15 @@
 #ifndef AGS_ENGINE_AC_ROUTE_FINDER_IMPL_LEGACY
 #define AGS_ENGINE_AC_ROUTE_FINDER_IMPL_LEGACY
 
+namespace AGS3 {
+
 // Forward declaration
 namespace AGS {
 namespace Common {
 class Bitmap;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 struct MoveList;
 
 namespace AGS {
@@ -51,5 +54,6 @@ void calculate_move_stage(MoveList *mlsp, int aaa);
 } // namespace RouteFinderLegacy
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/ac/runtime_defines.h b/engines/ags/engine/ac/runtime_defines.h
index 806a2f93d9..7e2e9d544b 100644
--- a/engines/ags/engine/ac/runtime_defines.h
+++ b/engines/ags/engine/ac/runtime_defines.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_AC_RUNTIMEDEFINES_H
 #define AGS_ENGINE_AC_RUNTIMEDEFINES_H
 
+namespace AGS3 {
+
 // xalleg.h pulls in an Allegro-internal definition of MAX_TIMERS which
 // conflicts with the definition in runtime_defines.h. Forget it.
 #ifdef MAX_TIMERS
@@ -54,13 +56,13 @@
 
 // Legacy (pre 3.5.0) alignment types used in the script API
 enum LegacyScriptAlignment {
-	kLegacyScAlignLeft      = 1,
-	kLegacyScAlignCentre    = 2,
-	kLegacyScAlignRight     = 3
+	kLegacyScAlignLeft = 1,
+	kLegacyScAlignCentre = 2,
+	kLegacyScAlignRight = 3
 };
 
 const int LegacyMusicMasterVolumeAdjustment = 60;
-const int LegacyRoomVolumeFactor            = 30;
+const int LegacyRoomVolumeFactor = 30;
 
 // These numbers were chosen arbitrarily -- the idea is
 // to make sure that the user gets the parameters the right way round
@@ -155,6 +157,8 @@ const int LegacyRoomVolumeFactor            = 30;
 
 #define MAX_OPEN_SCRIPT_FILES 10
 
+} // namespace AGS3
+
 #include "ac/common_defines.h"
 
 #endif
diff --git a/engines/ags/engine/ac/screen.h b/engines/ags/engine/ac/screen.h
index 4c95fb8065..e38b092050 100644
--- a/engines/ags/engine/ac/screen.h
+++ b/engines/ags/engine/ac/screen.h
@@ -23,16 +23,19 @@
 #ifndef AGS_ENGINE_AC_SCREEN_H
 #define AGS_ENGINE_AC_SCREEN_H
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Common {
 class Bitmap;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 namespace AGS {
 namespace Engine {
 class IDriverDependantBitmap;
-}
-}
+} // namespace Engine
+} // namespace AGS
 
 void my_fade_in(PALETTE p, int speed);
 void current_fade_out_effect();
@@ -41,4 +44,6 @@ AGS::Engine::IDriverDependantBitmap *prepare_screen_for_transition_in();
 // Screenshot made in the last room, used during some of the transition effects
 extern AGS::Common::Bitmap *saved_viewport_bitmap;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/screenoverlay.h b/engines/ags/engine/ac/screenoverlay.h
index 751077a0a5..59ed04a899 100644
--- a/engines/ags/engine/ac/screenoverlay.h
+++ b/engines/ags/engine/ac/screenoverlay.h
@@ -25,18 +25,22 @@
 
 #include <stdint.h>
 
+namespace AGS3 {
+
 // Forward declaration
 namespace AGS {
 namespace Common {
 class Bitmap;
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 namespace AGS {
 namespace Engine {
 class IDriverDependantBitmap;
-}
-}
+} // namespace Engine
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 
@@ -55,4 +59,6 @@ struct ScreenOverlay {
 	void WriteToFile(Common::Stream *out) const;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/slider.h b/engines/ags/engine/ac/slider.h
index 8d0b21dff5..19858cecd3 100644
--- a/engines/ags/engine/ac/slider.h
+++ b/engines/ags/engine/ac/slider.h
@@ -25,6 +25,8 @@
 
 #include "gui/guislider.h"
 
+namespace AGS3 {
+
 using AGS::Common::GUISlider;
 
 void    Slider_SetMax(GUISlider *guisl, int valn);
@@ -40,4 +42,6 @@ void    Slider_SetHandleGraphic(GUISlider *guisl, int newImage);
 int     Slider_GetHandleOffset(GUISlider *guisl);
 void    Slider_SetHandleOffset(GUISlider *guisl, int newOffset);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/speech.h b/engines/ags/engine/ac/speech.h
index e3eea3c030..dd5e3dc1e9 100644
--- a/engines/ags/engine/ac/speech.h
+++ b/engines/ags/engine/ac/speech.h
@@ -23,21 +23,25 @@
 #ifndef AGS_ENGINE_AC_SPEECH_H
 #define AGS_ENGINE_AC_SPEECH_H
 
+namespace AGS3 {
+
 enum SkipSpeechStyle {
-	kSkipSpeechUndefined    = -1,
-	kSkipSpeechKeyMouseTime =  0,
-	kSkipSpeechKeyTime      =  1,
-	kSkipSpeechTime         =  2,
-	kSkipSpeechKeyMouse     =  3,
-	kSkipSpeechMouseTime    =  4,
-	kSkipSpeechKey          =  5,
-	kSkipSpeechMouse        =  6,
+	kSkipSpeechUndefined = -1,
+	kSkipSpeechKeyMouseTime = 0,
+	kSkipSpeechKeyTime = 1,
+	kSkipSpeechTime = 2,
+	kSkipSpeechKeyMouse = 3,
+	kSkipSpeechMouseTime = 4,
+	kSkipSpeechKey = 5,
+	kSkipSpeechMouse = 6,
 
-	kSkipSpeechFirst        = kSkipSpeechKeyMouseTime,
-	kSkipSpeechLast         = kSkipSpeechMouse
+	kSkipSpeechFirst = kSkipSpeechKeyMouseTime,
+	kSkipSpeechLast = kSkipSpeechMouse
 };
 
 int user_to_internal_skip_speech(SkipSpeechStyle userval);
 SkipSpeechStyle internal_skip_speech_to_user(int internal_val);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/sprite.h b/engines/ags/engine/ac/sprite.h
index a5d15f35f1..09f841e005 100644
--- a/engines/ags/engine/ac/sprite.h
+++ b/engines/ags/engine/ac/sprite.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_AC_SPRITE_H
 #define AGS_ENGINE_AC_SPRITE_H
 
+namespace AGS3 {
+
 void get_new_size_for_sprite(int ee, int ww, int hh, int &newwid, int &newhit);
 // set any alpha-transparent pixels in the image to the appropriate
 // RGB mask value so that the ->Blit calls work correctly
@@ -32,4 +34,6 @@ Common::Bitmap *remove_alpha_channel(Common::Bitmap *from);
 void pre_save_sprite(int ee);
 void initialize_sprite(int ee);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/spritelistentry.h b/engines/ags/engine/ac/spritelistentry.h
index 735eaf2d10..8f93274389 100644
--- a/engines/ags/engine/ac/spritelistentry.h
+++ b/engines/ags/engine/ac/spritelistentry.h
@@ -25,6 +25,8 @@
 
 #include "gfx/ddb.h"
 
+namespace AGS3 {
+
 struct SpriteListEntry {
 	AGS::Engine::IDriverDependantBitmap *bmp;
 	AGS::Common::Bitmap *pic;
@@ -37,4 +39,6 @@ struct SpriteListEntry {
 	SpriteListEntry();
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/statobj/agsstaticobject.h b/engines/ags/engine/ac/statobj/agsstaticobject.h
index adcf2411bb..adaddac4ab 100644
--- a/engines/ags/engine/ac/statobj/agsstaticobject.h
+++ b/engines/ags/engine/ac/statobj/agsstaticobject.h
@@ -25,6 +25,8 @@
 
 #include "ac/statobj/staticobject.h"
 
+namespace AGS3 {
+
 struct AGSStaticObject : public ICCStaticObject {
 	~AGSStaticObject() override = default;
 
@@ -50,4 +52,6 @@ struct StaticGame : public AGSStaticObject {
 extern AGSStaticObject GlobalStaticManager;
 extern StaticGame      GameStaticManager;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/statobj/staticarray.h b/engines/ags/engine/ac/statobj/staticarray.h
index 729e7f9bce..1941cc603b 100644
--- a/engines/ags/engine/ac/statobj/staticarray.h
+++ b/engines/ags/engine/ac/statobj/staticarray.h
@@ -25,6 +25,8 @@
 
 #include "ac/statobj/staticobject.h"
 
+namespace AGS3 {
+
 struct ICCDynamicObject;
 
 struct StaticArray : public ICCStaticObject {
@@ -57,11 +59,13 @@ public:
 	void    WriteFloat(const char *address, intptr_t offset, float val) override;
 
 private:
-	ICCStaticObject     *_staticMgr;
-	ICCDynamicObject    *_dynamicMgr;
+	ICCStaticObject *_staticMgr;
+	ICCDynamicObject *_dynamicMgr;
 	int                 _elemLegacySize;
 	int                 _elemRealSize;
 	int                 _elemCount;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/statobj/staticobject.h b/engines/ags/engine/ac/statobj/staticobject.h
index 4e424a02b0..5653222d77 100644
--- a/engines/ags/engine/ac/statobj/staticobject.h
+++ b/engines/ags/engine/ac/statobj/staticobject.h
@@ -33,21 +33,25 @@
 
 #include "core/types.h"
 
+namespace AGS3 {
+
 struct ICCStaticObject {
 	virtual ~ICCStaticObject() = default;
 
 	// Legacy support for reading and writing object values by their relative offset
-	virtual const char *GetFieldPtr(const char *address, intptr_t offset)           = 0;
+	virtual const char *GetFieldPtr(const char *address, intptr_t offset) = 0;
 	virtual void    Read(const char *address, intptr_t offset, void *dest, int size) = 0;
-	virtual uint8_t ReadInt8(const char *address, intptr_t offset)                  = 0;
-	virtual int16_t ReadInt16(const char *address, intptr_t offset)                 = 0;
-	virtual int32_t ReadInt32(const char *address, intptr_t offset)                 = 0;
-	virtual float   ReadFloat(const char *address, intptr_t offset)                 = 0;
+	virtual uint8_t ReadInt8(const char *address, intptr_t offset) = 0;
+	virtual int16_t ReadInt16(const char *address, intptr_t offset) = 0;
+	virtual int32_t ReadInt32(const char *address, intptr_t offset) = 0;
+	virtual float   ReadFloat(const char *address, intptr_t offset) = 0;
 	virtual void    Write(const char *address, intptr_t offset, void *src, int size) = 0;
-	virtual void    WriteInt8(const char *address, intptr_t offset, uint8_t val)    = 0;
-	virtual void    WriteInt16(const char *address, intptr_t offset, int16_t val)   = 0;
-	virtual void    WriteInt32(const char *address, intptr_t offset, int32_t val)   = 0;
-	virtual void    WriteFloat(const char *address, intptr_t offset, float val)     = 0;
+	virtual void    WriteInt8(const char *address, intptr_t offset, uint8_t val) = 0;
+	virtual void    WriteInt16(const char *address, intptr_t offset, int16_t val) = 0;
+	virtual void    WriteInt32(const char *address, intptr_t offset, int32_t val) = 0;
+	virtual void    WriteFloat(const char *address, intptr_t offset, float val) = 0;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/string.h b/engines/ags/engine/ac/string.h
index 43968ed854..e27bd213a4 100644
--- a/engines/ags/engine/ac/string.h
+++ b/engines/ags/engine/ac/string.h
@@ -26,6 +26,8 @@
 #include <stdarg.h>
 #include "ac/dynobj/cc_dynamicobject.h"
 
+namespace AGS3 {
+
 // Check that a supplied buffer from a text script function was not null
 #define VALIDATE_STRING(strin) if ((unsigned long)strin <= 4096) quit("!String argument was null: make sure you pass a string, not an int, as a buffer")
 
@@ -58,4 +60,6 @@ size_t break_up_text_into_lines(const char *todis, SplitLines &lines, int wii, i
 void check_strlen(char *ptt);
 void my_strncpy(char *dest, const char *src, int len);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/sys_events.h b/engines/ags/engine/ac/sys_events.h
index d2e9531930..af50c7d088 100644
--- a/engines/ags/engine/ac/sys_events.h
+++ b/engines/ags/engine/ac/sys_events.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_AC_SYS_EVENTS_H
 #define AGS_ENGINE_AC_SYS_EVENTS_H
 
+namespace AGS3 {
+
 int  ags_getch();
 int  ags_kbhit();
 int  ags_iskeypressed(int keycode);
@@ -38,4 +40,6 @@ void ags_clear_input_buffer();
 // TODO: seriously not a good design, replace with event listening
 void ags_wait_until_keypress();
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/system.h b/engines/ags/engine/ac/system.h
index 7ed12cc875..280ec92ec7 100644
--- a/engines/ags/engine/ac/system.h
+++ b/engines/ags/engine/ac/system.h
@@ -25,6 +25,8 @@
 
 #include "ac/dynobj/scriptaudiochannel.h"
 
+namespace AGS3 {
+
 int     System_GetColorDepth();
 int     System_GetOS();
 int     System_GetScreenWidth();
@@ -49,5 +51,6 @@ int     System_GetVolume();
 void    System_SetVolume(int newvol);
 const char *System_GetRuntimeInfo();
 
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/ac/textbox.h b/engines/ags/engine/ac/textbox.h
index 6720f392a7..8b2a1f23a3 100644
--- a/engines/ags/engine/ac/textbox.h
+++ b/engines/ags/engine/ac/textbox.h
@@ -25,6 +25,8 @@
 
 #include "gui/guitextbox.h"
 
+namespace AGS3 {
+
 using AGS::Common::GUITextBox;
 
 const char *TextBox_GetText_New(GUITextBox *texbox);
@@ -35,4 +37,6 @@ void        TextBox_SetTextColor(GUITextBox *guit, int colr);
 int         TextBox_GetFont(GUITextBox *guit);
 void        TextBox_SetFont(GUITextBox *guit, int fontnum);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/timer.h b/engines/ags/engine/ac/timer.h
index 66363c8d58..fa0ecb8801 100644
--- a/engines/ags/engine/ac/timer.h
+++ b/engines/ags/engine/ac/timer.h
@@ -26,12 +26,14 @@
 #include <type_traits>
 #include <chrono>
 
+namespace AGS3 {
+
 // use high resolution clock only if we know it is monotonic/steady.
 // refer to https://stackoverflow.com/a/38253266/84262
 using AGS_Clock = std::conditional <
-                  std::chrono::high_resolution_clock::is_steady,
-                  std::chrono::high_resolution_clock, std::chrono::steady_clock
-                  >::type;
+	std::chrono::high_resolution_clock::is_steady,
+	std::chrono::high_resolution_clock, std::chrono::steady_clock
+>::type;
 
 extern void WaitForNextFrame();
 
@@ -42,4 +44,6 @@ extern bool isTimerFpsMaxed();
 extern bool waitingForNextTick();  // store last tick time.
 extern void skipMissedTicks();  // if more than N frames, just skip all, start a fresh.
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/topbarsettings.h b/engines/ags/engine/ac/topbarsettings.h
index 4b8e1a660b..0af28b977b 100644
--- a/engines/ags/engine/ac/topbarsettings.h
+++ b/engines/ags/engine/ac/topbarsettings.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_AC_TOPBARSETTINGS_H
 #define AGS_ENGINE_AC_TOPBARSETTINGS_H
 
+namespace AGS3 {
+
 struct TopBarSettings {
 	int wantIt;
 	int height;
@@ -37,4 +39,6 @@ struct TopBarSettings {
 	}
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/translation.h b/engines/ags/engine/ac/translation.h
index 1ee20f9e37..4e5922b575 100644
--- a/engines/ags/engine/ac/translation.h
+++ b/engines/ags/engine/ac/translation.h
@@ -25,9 +25,13 @@
 
 #include "util/string.h"
 
+namespace AGS3 {
+
 using AGS::Common::String;
 
 void close_translation();
 bool init_translation(const String &lang, const String &fallback_lang, bool quit_on_error);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/tree_map.h b/engines/ags/engine/ac/tree_map.h
index f00bb11f5a..6230dd3b9c 100644
--- a/engines/ags/engine/ac/tree_map.h
+++ b/engines/ags/engine/ac/tree_map.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_AC_TREEMAP_H
 #define AGS_ENGINE_AC_TREEMAP_H
 
+namespace AGS3 {
+
 // Binary tree structure for holding translations, allows fast
 // access
 struct TreeMap {
@@ -37,4 +39,6 @@ struct TreeMap {
 	~TreeMap();
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/viewframe.h b/engines/ags/engine/ac/viewframe.h
index 171170ab6c..2bd3049aa9 100644
--- a/engines/ags/engine/ac/viewframe.h
+++ b/engines/ags/engine/ac/viewframe.h
@@ -29,11 +29,14 @@
 #include "ac/dynobj/scriptviewframe.h"
 #include "gfx/bitmap.h"
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Common {
 class Graphics;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 int  ViewFrame_GetFlipped(ScriptViewFrame *svf);
@@ -53,4 +56,6 @@ void CheckViewFrame(int view, int loop, int frame, int sound_volume = SCR_NO_VAL
 // draws a view frame, flipped if appropriate
 void DrawViewFrame(Common::Bitmap *ds, const ViewFrame *vframe, int x, int y, bool alpha_blend = false);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/walkablearea.h b/engines/ags/engine/ac/walkablearea.h
index 5be0c3902e..922f90af10 100644
--- a/engines/ags/engine/ac/walkablearea.h
+++ b/engines/ags/engine/ac/walkablearea.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_AC_WALKABLEAREA_H
 #define AGS_ENGINE_AC_WALKABLEAREA_H
 
+namespace AGS3 {
+
 void  redo_walkable_areas();
 int   get_walkable_area_pixel(int x, int y);
 int   get_area_scaling(int onarea, int xx, int yy);
@@ -33,4 +35,6 @@ Common::Bitmap *prepare_walkable_areas(int sourceChar);
 int   get_walkable_area_at_location(int xx, int yy);
 int   get_walkable_area_at_character(int charnum);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/ac/walkbehind.h b/engines/ags/engine/ac/walkbehind.h
index 2bb80701a1..77bbdfc072 100644
--- a/engines/ags/engine/ac/walkbehind.h
+++ b/engines/ags/engine/ac/walkbehind.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_AC_WALKBEHIND_H
 #define AGS_ENGINE_AC_WALKBEHIND_H
 
+namespace AGS3 {
+
 enum WalkBehindMethodEnum {
 	DrawOverCharSprite,
 	DrawAsSeparateSprite,
@@ -32,4 +34,6 @@ enum WalkBehindMethodEnum {
 void update_walk_behind_images();
 void recache_walk_behinds();
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/debugging/agseditordebugger.h b/engines/ags/engine/debugging/agseditordebugger.h
index 8871a2f5dd..b4bdcfe602 100644
--- a/engines/ags/engine/debugging/agseditordebugger.h
+++ b/engines/ags/engine/debugging/agseditordebugger.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_DEBUGGING_AGSEDITORDEBUGGER_H
 #define AGS_ENGINE_DEBUGGING_AGSEDITORDEBUGGER_H
 
+namespace AGS3 {
+
 struct IAGSEditorDebugger {
 public:
 	virtual ~IAGSEditorDebugger() = default;
@@ -35,4 +37,6 @@ public:
 	virtual char *GetNextMessage() = 0;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/debugging/consoleoutputtarget.h b/engines/ags/engine/debugging/consoleoutputtarget.h
index 9e12ac9739..f35bec3488 100644
--- a/engines/ags/engine/debugging/consoleoutputtarget.h
+++ b/engines/ags/engine/debugging/consoleoutputtarget.h
@@ -32,6 +32,7 @@
 
 #include "debug/outputhandler.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
@@ -46,7 +47,8 @@ public:
 	void PrintMessage(const DebugMessage &msg) override;
 };
 
-}   // namespace Engine
-}   // namespace AGS
+} // namespace Engine
+} // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/debugging/debug_log.h b/engines/ags/engine/debugging/debug_log.h
index f8d07e0383..ea0b955427 100644
--- a/engines/ags/engine/debugging/debug_log.h
+++ b/engines/ags/engine/debugging/debug_log.h
@@ -29,6 +29,8 @@
 #include "platform/base/agsplatformdriver.h"
 #include "util/ini_util.h"
 
+namespace AGS3 {
+
 void init_debug(const AGS::Common::ConfigTree &cfg, bool stderr_only);
 void apply_debug_config(const AGS::Common::ConfigTree &cfg);
 void shutdown_debug();
@@ -45,7 +47,7 @@ void quitprintf(const char *texx, ...);
 bool init_editor_debugging();
 
 // allow LShift to single-step,  RShift to pause flow
-void scriptDebugHook(ccInstance *ccinst, int linenum) ;
+void scriptDebugHook(ccInstance *ccinst, int linenum);
 
 extern AGS::Common::String debug_line[DEBUG_CONSOLE_NUMLINES];
 extern int first_debug_line, last_debug_line, display_console;
@@ -53,4 +55,6 @@ extern int first_debug_line, last_debug_line, display_console;
 
 extern AGSPlatformDriver *platform;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/debugging/debugger.h b/engines/ags/engine/debugging/debugger.h
index 3999526771..39450e9889 100644
--- a/engines/ags/engine/debugging/debugger.h
+++ b/engines/ags/engine/debugging/debugger.h
@@ -25,6 +25,8 @@
 
 #include "util/string.h"
 
+namespace AGS3 {
+
 struct IAGSEditorDebugger;
 struct ScriptPosition;
 
@@ -64,4 +66,6 @@ extern float fps;
 extern FPSDisplayMode display_fps;
 extern int debug_flags;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/debugging/dummyagsdebugger.h b/engines/ags/engine/debugging/dummyagsdebugger.h
index 8ae955bc5b..2845e28a9e 100644
--- a/engines/ags/engine/debugging/dummyagsdebugger.h
+++ b/engines/ags/engine/debugging/dummyagsdebugger.h
@@ -25,13 +25,16 @@
 
 #include "debug/debugger.h"
 
+namespace AGS3 {
+
 struct DummyAGSDebugger : IAGSEditorDebugger {
 public:
 
 	virtual bool Initialize() override {
 		return false;
 	}
-	virtual void Shutdown() override { }
+	virtual void Shutdown() override {
+	}
 	virtual bool SendMessageToEditor(const char *message) override {
 		return false;
 	}
@@ -43,4 +46,6 @@ public:
 	}
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/debugging/filebasedagsdebugger.h b/engines/ags/engine/debugging/filebasedagsdebugger.h
index aebfba868f..3ba6b4acf7 100644
--- a/engines/ags/engine/debugging/filebasedagsdebugger.h
+++ b/engines/ags/engine/debugging/filebasedagsdebugger.h
@@ -25,6 +25,8 @@
 
 #include "debug/agseditordebugger.h"
 
+namespace AGS3 {
+
 struct FileBasedAGSDebugger : IAGSEditorDebugger {
 public:
 
@@ -38,4 +40,6 @@ public:
 
 extern const char *SENT_MESSAGE_FILE_NAME;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/debugging/logfile.h b/engines/ags/engine/debugging/logfile.h
index c0f9a68245..674a097e8c 100644
--- a/engines/ags/engine/debugging/logfile.h
+++ b/engines/ags/engine/debugging/logfile.h
@@ -38,11 +38,12 @@
 #include <memory>
 #include "debug/outputhandler.h"
 
+namespace AGS3 {
 namespace AGS {
 
 namespace Common {
 class Stream;
-}
+} // namespace Shared
 
 namespace Engine {
 
@@ -81,7 +82,8 @@ private:
 	OpenMode              _openMode;
 };
 
-}   // namespace Engine
-}   // namespace AGS
+} // namespace Engine
+} // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/debugging/messagebuffer.h b/engines/ags/engine/debugging/messagebuffer.h
index 1f80ee5494..f704af8fbe 100644
--- a/engines/ags/engine/debugging/messagebuffer.h
+++ b/engines/ags/engine/debugging/messagebuffer.h
@@ -34,6 +34,7 @@
 #include <vector>
 #include "debug/outputhandler.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
@@ -59,7 +60,8 @@ private:
 	size_t          _msgLost;
 };
 
-}   // namespace Engine
-}   // namespace AGS
+} // namespace Engine
+} // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/device/mousew32.h b/engines/ags/engine/device/mousew32.h
index 5bd55bdd62..d5f852eabc 100644
--- a/engines/ags/engine/device/mousew32.h
+++ b/engines/ags/engine/device/mousew32.h
@@ -37,11 +37,13 @@
 
 #include "util/geometry.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 class Bitmap;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 void msetgraphpos(int, int);
@@ -100,3 +102,5 @@ extern int disable_mgetgraphpos;
 extern char currentcursor;
 
 extern Common::Bitmap *mousecurs[MAXCURSORS];
+
+} // namespace AGS3
diff --git a/engines/ags/engine/game/game_init.h b/engines/ags/engine/game/game_init.h
index 0ce363d626..e1921006ef 100644
--- a/engines/ags/engine/game/game_init.h
+++ b/engines/ags/engine/game/game_init.h
@@ -33,6 +33,7 @@
 #include "game/main_game_file.h"
 #include "util/string.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
@@ -60,5 +61,6 @@ HGameInitError  InitGameState(const LoadedGameEntities &ents, GameDataVersion da
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/game/savegame.h b/engines/ags/engine/game/savegame.h
index 838d2122aa..ac605a3ab1 100644
--- a/engines/ags/engine/game/savegame.h
+++ b/engines/ags/engine/game/savegame.h
@@ -28,13 +28,13 @@
 #include "util/error.h"
 #include "util/version.h"
 
+namespace AGS3 {
 
 namespace AGS {
-
 namespace Common {
 class Bitmap;
 class Stream;
-}
+} // namespace Shared
 
 namespace Engine {
 
@@ -55,12 +55,12 @@ typedef std::shared_ptr<Stream> PStream;
 //-----------------------------------------------------------------------------
 enum SavegameVersion {
 	kSvgVersion_Undefined = 0,
-	kSvgVersion_321       = 8,
+	kSvgVersion_321 = 8,
 	kSvgVersion_Components = 9,
 	kSvgVersion_Cmp_64bit = 10,
 	kSvgVersion_350_final = 11,
 	kSvgVersion_350_final2 = 12,
-	kSvgVersion_Current   = kSvgVersion_350_final2,
+	kSvgVersion_Current = kSvgVersion_350_final2,
 	kSvgVersion_LowestSupported = kSvgVersion_321 // change if support dropped
 };
 
@@ -117,11 +117,11 @@ struct SavegameSource {
 // Supported elements of savegame description;
 // these may be used as flags to define valid fields
 enum SavegameDescElem {
-	kSvgDesc_None       = 0,
-	kSvgDesc_EnvInfo    = 0x0001,
-	kSvgDesc_UserText   = 0x0002,
-	kSvgDesc_UserImage  = 0x0004,
-	kSvgDesc_All        = kSvgDesc_EnvInfo | kSvgDesc_UserText | kSvgDesc_UserImage
+	kSvgDesc_None = 0,
+	kSvgDesc_EnvInfo = 0x0001,
+	kSvgDesc_UserText = 0x0002,
+	kSvgDesc_UserImage = 0x0004,
+	kSvgDesc_All = kSvgDesc_EnvInfo | kSvgDesc_UserText | kSvgDesc_UserImage
 };
 
 // SavegameDescription describes savegame with information about the enviroment
@@ -154,7 +154,7 @@ struct SavegameDescription {
 
 // Opens savegame for reading; optionally reads description, if any is provided
 HSaveError     OpenSavegame(const String &filename, SavegameSource &src,
-                            SavegameDescription &desc, SavegameDescElem elems = kSvgDesc_All);
+	SavegameDescription &desc, SavegameDescElem elems = kSvgDesc_All);
 // Opens savegame and reads the savegame description
 HSaveError     OpenSavegame(const String &filename, SavegameDescription &desc, SavegameDescElem elems = kSvgDesc_All);
 
@@ -169,5 +169,6 @@ void           SaveGameState(PStream out);
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/game/savegame_components.h b/engines/ags/engine/game/savegame_components.h
index 77355ee304..32797df54d 100644
--- a/engines/ags/engine/game/savegame_components.h
+++ b/engines/ags/engine/game/savegame_components.h
@@ -26,11 +26,12 @@
 #include "game/savegame.h"
 #include "util/stream.h"
 
+namespace AGS3 {
 namespace AGS {
 
 namespace Common {
 struct Interaction;
-}
+} // namespace Shared
 
 namespace Engine {
 
diff --git a/engines/ags/engine/game/savegame_internal.h b/engines/ags/engine/game/savegame_internal.h
index 9970ecd904..e2dba2fedd 100644
--- a/engines/ags/engine/game/savegame_internal.h
+++ b/engines/ags/engine/game/savegame_internal.h
@@ -29,7 +29,7 @@
 #include "gfx/bitmap.h"
 #include "media/audio/audiodefines.h"
 
-
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
@@ -137,5 +137,6 @@ struct RestoredData {
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/game/viewport.h b/engines/ags/engine/game/viewport.h
index b5b100b532..f39040cfdb 100644
--- a/engines/ags/engine/game/viewport.h
+++ b/engines/ags/engine/game/viewport.h
@@ -34,6 +34,8 @@
 #include "util/geometry.h"
 #include "util/scaling.h"
 
+namespace AGS3 {
+
 class Camera;
 class Viewport;
 
@@ -48,7 +50,7 @@ typedef std::weak_ptr<Viewport> ViewportRef;
 template <typename T>
 bool is_uninitialized(std::weak_ptr<T> const &weak) {
 	using wt = std::weak_ptr<T>;
-	return !weak.owner_before(wt{}) &&!wt{} .owner_before(weak);
+	return !weak.owner_before(wt{}) && !wt{}.owner_before(weak);
 }
 
 
@@ -220,4 +222,6 @@ private:
 	bool _hasChangedVisible = false;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/gfx/ali3dexception.h b/engines/ags/engine/gfx/ali3dexception.h
index 92c40a96e6..48e59a7443 100644
--- a/engines/ags/engine/gfx/ali3dexception.h
+++ b/engines/ags/engine/gfx/ali3dexception.h
@@ -29,6 +29,7 @@
 #ifndef AGS_ENGINE_GFX_ALI3DEXCEPTION_H
 #define AGS_ENGINE_GFX_ALI3DEXCEPTION_H
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
@@ -49,5 +50,6 @@ public:
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/gfx/ali3dogl.h b/engines/ags/engine/gfx/ali3dogl.h
index 38b2c34f19..171817bcdb 100644
--- a/engines/ags/engine/gfx/ali3dogl.h
+++ b/engines/ags/engine/gfx/ali3dogl.h
@@ -39,6 +39,7 @@
 
 #include "ogl_headers.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
@@ -79,7 +80,7 @@ public:
 		_stretchToHeight = height;
 		_useResampler = useResampler;
 	}
-	void SetLightLevel(int lightLevel) override  {
+	void SetLightLevel(int lightLevel) override {
 		_lightLevel = lightLevel;
 	}
 	void SetTint(int red, int green, int blue, int tintSaturation) override {
@@ -202,7 +203,8 @@ public:
 	void Render() override;
 	void Render(int xoff, int yoff, GlobalFlipType flip) override;
 	bool GetCopyOfScreenIntoBitmap(Bitmap *destination, bool at_native_res, GraphicResolution *want_fmt) override;
-	void EnableVsyncBeforeRender(bool enabled) override { }
+	void EnableVsyncBeforeRender(bool enabled) override {
+	}
 	void Vsync() override;
 	void RenderSpritesAtScreenResolution(bool enabled, int supersampling) override;
 	void FadeOut(int speed, int targetColourRed, int targetColourGreen, int targetColourBlue) override;
@@ -316,7 +318,7 @@ private:
 	void CreateTintShader();
 	void CreateLightShader();
 	void CreateShaderProgram(ShaderProgram &prg, const char *name, const char *fragment_shader_src,
-	                         const char *sampler_var, const char *color_var, const char *aux_var);
+		const char *sampler_var, const char *color_var, const char *aux_var);
 	void DeleteShaderProgram(ShaderProgram &prg);
 	void OutputShaderError(GLuint obj_id, const String &obj_name, bool is_shader);
 	// Configure backbuffer texture, that is used in render-to-texture mode
@@ -359,11 +361,11 @@ public:
 	const GfxFilterInfo *GetFilterInfo(size_t index) const override;
 	String               GetDefaultFilterID() const override;
 
-	static OGLGraphicsFactory   *GetFactory();
+	static OGLGraphicsFactory *GetFactory();
 
 private:
-	OGLGraphicsDriver   *EnsureDriverCreated() override;
-	OGLGfxFilter        *CreateFilter(const String &id) override;
+	OGLGraphicsDriver *EnsureDriverCreated() override;
+	OGLGfxFilter *CreateFilter(const String &id) override;
 
 	static OGLGraphicsFactory *_factory;
 };
@@ -371,5 +373,6 @@ private:
 } // namespace OGL
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/gfx/ali3dsw.h b/engines/ags/engine/gfx/ali3dsw.h
index e1d6779340..c382913820 100644
--- a/engines/ags/engine/gfx/ali3dsw.h
+++ b/engines/ags/engine/gfx/ali3dsw.h
@@ -46,6 +46,7 @@
 #include "gfx/gfxdriverfactorybase.h"
 #include "gfx/gfxdriverbase.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 namespace ALSW {
@@ -77,8 +78,10 @@ public:
 	int GetColorDepth() override {
 		return _colDepth;
 	}
-	void SetLightLevel(int lightLevel) override  { }
-	void SetTint(int red, int green, int blue, int tintSaturation) override { }
+	void SetLightLevel(int lightLevel) override {
+	}
+	void SetTint(int red, int green, int blue, int tintSaturation) override {
+	}
 
 	Bitmap *_bmp;
 	int _width, _height;
@@ -191,14 +194,16 @@ public:
 #ifndef AGS_NO_VIDEO_PLAYER
 	bool PlayVideo(const char *filename, bool useAVISound, VideoSkipType skipType, bool stretchToFullScreen) override;
 #endif
-	bool SupportsGammaControl() override ;
+	bool SupportsGammaControl() override;
 	void SetGamma(int newGamma) override;
-	void UseSmoothScaling(bool enabled) override { }
+	void UseSmoothScaling(bool enabled) override {
+	}
 	void EnableVsyncBeforeRender(bool enabled) override {
 		_autoVsync = enabled;
 	}
 	void Vsync() override;
-	void RenderSpritesAtScreenResolution(bool enabled, int supersampling) override { }
+	void RenderSpritesAtScreenResolution(bool enabled, int supersampling) override {
+	}
 	bool RequiresFullRedrawEachFrame() override {
 		return false;
 	}
@@ -262,8 +267,8 @@ private:
 
 	void highcolor_fade_in(Bitmap *vs, void(*draw_callback)(), int offx, int offy, int speed, int targetColourRed, int targetColourGreen, int targetColourBlue);
 	void highcolor_fade_out(Bitmap *vs, void(*draw_callback)(), int offx, int offy, int speed, int targetColourRed, int targetColourGreen, int targetColourBlue);
-	void __fade_from_range(PALETTE source, PALETTE dest, int speed, int from, int to) ;
-	void __fade_out_range(int speed, int from, int to, int targetColourRed, int targetColourGreen, int targetColourBlue) ;
+	void __fade_from_range(PALETTE source, PALETTE dest, int speed, int from, int to);
+	void __fade_out_range(int speed, int from, int to, int targetColourRed, int targetColourGreen, int targetColourBlue);
 	int  GetAllegroGfxDriverID(bool windowed);
 };
 
@@ -280,7 +285,7 @@ public:
 
 private:
 	ALSoftwareGraphicsDriver *EnsureDriverCreated() override;
-	AllegroGfxFilter         *CreateFilter(const String &id) override;
+	AllegroGfxFilter *CreateFilter(const String &id) override;
 
 	static ALSWGraphicsFactory *_factory;
 };
@@ -288,5 +293,6 @@ private:
 } // namespace ALSW
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/gfx/blender.h b/engines/ags/engine/gfx/blender.h
index 2c07ce4009..45b8fa5468 100644
--- a/engines/ags/engine/gfx/blender.h
+++ b/engines/ags/engine/gfx/blender.h
@@ -29,6 +29,8 @@
 #ifndef AGS_ENGINE_GFX_BLENDER_H
 #define AGS_ENGINE_GFX_BLENDER_H
 
+namespace AGS3 {
+
 //
 // Allegro's standard alpha blenders result in:
 // - src and dst RGB are combined proportionally to src alpha
@@ -72,4 +74,6 @@ void set_opaque_alpha_blender();
 // Sets argb2argb for 32-bit mode, and provides appropriate funcs for blending 32-bit onto 15/16/24-bit destination
 void set_argb2any_blender();
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/gfx/ddb.h b/engines/ags/engine/gfx/ddb.h
index 64ab9e2ff6..c6fa1a6a12 100644
--- a/engines/ags/engine/gfx/ddb.h
+++ b/engines/ags/engine/gfx/ddb.h
@@ -29,6 +29,7 @@
 #ifndef AGS_ENGINE_GFX_DDB_H
 #define AGS_ENGINE_GFX_DDB_H
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
@@ -49,5 +50,6 @@ public:
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/gfx/gfx_util.h b/engines/ags/engine/gfx/gfx_util.h
index 5747699ad4..e9b9f17199 100644
--- a/engines/ags/engine/gfx/gfx_util.h
+++ b/engines/ags/engine/gfx/gfx_util.h
@@ -38,6 +38,7 @@
 #include "gfx/bitmap.h"
 #include "gfx/gfx_def.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
@@ -52,7 +53,7 @@ Bitmap *ConvertBitmap(Bitmap *src, int dst_color_depth);
 // or fallbacks to common "magic pink" transparency mode;
 // optionally uses blending alpha (overall image transparency).
 void DrawSpriteBlend(Bitmap *ds, const Point &ds_at, Bitmap *sprite,
-                     Common::BlendMode blend_mode, bool dst_has_alpha = true, bool src_has_alpha = true, int blend_alpha = 0xFF);
+	Common::BlendMode blend_mode, bool dst_has_alpha = true, bool src_has_alpha = true, int blend_alpha = 0xFF);
 
 // Draws a bitmap over another one with given alpha level (0 - 255),
 // takes account of the bitmap's mask color,
@@ -63,5 +64,6 @@ void DrawSpriteWithTransparency(Bitmap *ds, Bitmap *sprite, int x, int y, int al
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/gfx/gfxdefines.h b/engines/ags/engine/gfx/gfxdefines.h
index f3893bda96..cbb4fab496 100644
--- a/engines/ags/engine/gfx/gfxdefines.h
+++ b/engines/ags/engine/gfx/gfxdefines.h
@@ -25,6 +25,7 @@
 
 #include "core/types.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
@@ -81,5 +82,6 @@ struct DisplayMode : public GraphicResolution {
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/gfx/gfxdriverbase.h b/engines/ags/engine/gfx/gfxdriverbase.h
index a8200d85b8..14012a9577 100644
--- a/engines/ags/engine/gfx/gfxdriverbase.h
+++ b/engines/ags/engine/gfx/gfxdriverbase.h
@@ -34,6 +34,7 @@
 #include "gfx/graphicsdriver.h"
 #include "util/scaling.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
@@ -53,9 +54,10 @@ struct SpriteBatchDesc {
 	// Optional bitmap to draw sprites upon. Used exclusively by the software rendering mode.
 	PBitmap                  Surface;
 
-	SpriteBatchDesc() : Flip(kFlip_None) {}
+	SpriteBatchDesc() : Flip(kFlip_None) {
+	}
 	SpriteBatchDesc(const Rect viewport, const SpriteTransform &transform, const Point offset = Point(),
-	                GlobalFlipType flip = kFlip_None, PBitmap surface = nullptr)
+		GlobalFlipType flip = kFlip_None, PBitmap surface = nullptr)
 		: Viewport(viewport)
 		, Transform(transform)
 		, Offset(offset)
@@ -103,7 +105,7 @@ public:
 	Rect        GetRenderDestination() const override;
 
 	void        BeginSpriteBatch(const Rect &viewport, const SpriteTransform &transform,
-	                             const Point offset = Point(), GlobalFlipType flip = kFlip_None, PBitmap surface = nullptr) override;
+		const Point offset = Point(), GlobalFlipType flip = kFlip_None, PBitmap surface = nullptr) override;
 	void        ClearDrawLists() override;
 
 	void        SetCallbackForPolling(GFXDRV_CLIENTCALLBACK callback) override {
@@ -225,10 +227,10 @@ protected:
 
 	// Prepares bitmap to be applied to the texture, copies pixels to the provided buffer
 	void BitmapToVideoMem(const Bitmap *bitmap, const bool has_alpha, const TextureTile *tile, const VideoMemDDB *target,
-	                      char *dst_ptr, const int dst_pitch, const bool usingLinearFiltering);
+		char *dst_ptr, const int dst_pitch, const bool usingLinearFiltering);
 	// Same but optimized for opaque source bitmaps which ignore transparent "mask color"
 	void BitmapToVideoMemOpaque(const Bitmap *bitmap, const bool has_alpha, const TextureTile *tile, const VideoMemDDB *target,
-	                            char *dst_ptr, const int dst_pitch);
+		char *dst_ptr, const int dst_pitch);
 
 	// Stage virtual screen is used to let plugins draw custom graphics
 	// in between render stages (between room and GUI, after GUI, and so on)
@@ -262,5 +264,6 @@ private:
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/gfx/gfxdriverfactory.h b/engines/ags/engine/gfx/gfxdriverfactory.h
index 3fdc220a4d..eb6bae49ee 100644
--- a/engines/ags/engine/gfx/gfxdriverfactory.h
+++ b/engines/ags/engine/gfx/gfxdriverfactory.h
@@ -37,6 +37,7 @@
 #include "util/string.h"
 #include "util/string_types.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
@@ -57,7 +58,7 @@ public:
 	virtual void                 Shutdown() = 0;
 	// Get graphics driver associated with this factory; creates one if
 	// it does not exist.
-	virtual IGraphicsDriver     *GetDriver() = 0;
+	virtual IGraphicsDriver *GetDriver() = 0;
 	// Destroy graphics driver associated with this factory; does nothing
 	// if one was not created yet,
 	virtual void                 DestroyDriver() = 0;
@@ -80,5 +81,6 @@ IGfxDriverFactory *GetGfxDriverFactory(const String id);
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/gfx/gfxdriverfactorybase.h b/engines/ags/engine/gfx/gfxdriverfactorybase.h
index 853fe4c5e4..337901ca80 100644
--- a/engines/ags/engine/gfx/gfxdriverfactorybase.h
+++ b/engines/ags/engine/gfx/gfxdriverfactorybase.h
@@ -37,6 +37,7 @@
 #include "gfx/gfxdriverfactory.h"
 #include "gfx/gfxfilter.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
@@ -98,10 +99,11 @@ protected:
 	virtual TGfxDriverClass *EnsureDriverCreated() = 0;
 	virtual TGfxFilterClass *CreateFilter(const String &id) = 0;
 
-	TGfxDriverClass         *_driver;
+	TGfxDriverClass *_driver;
 };
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/gfx/gfxfilter.h b/engines/ags/engine/gfx/gfxfilter.h
index 25eb03de4b..a8fc9b4da6 100644
--- a/engines/ags/engine/gfx/gfxfilter.h
+++ b/engines/ags/engine/gfx/gfxfilter.h
@@ -33,6 +33,7 @@
 #include "util/geometry.h"
 #include "util/string.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
@@ -73,5 +74,6 @@ typedef std::shared_ptr<IGfxFilter> PGfxFilter;
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/gfx/gfxfilter_aad3d.h b/engines/ags/engine/gfx/gfxfilter_aad3d.h
index 4f5c7de75c..84c376ec07 100644
--- a/engines/ags/engine/gfx/gfxfilter_aad3d.h
+++ b/engines/ags/engine/gfx/gfxfilter_aad3d.h
@@ -31,6 +31,7 @@
 
 #include "gfx/gfxfilter_d3d.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 namespace D3D {
@@ -48,5 +49,6 @@ public:
 } // namespace D3D
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/gfx/gfxfilter_aaogl.h b/engines/ags/engine/gfx/gfxfilter_aaogl.h
index 3ed266331b..3d77922736 100644
--- a/engines/ags/engine/gfx/gfxfilter_aaogl.h
+++ b/engines/ags/engine/gfx/gfxfilter_aaogl.h
@@ -31,6 +31,7 @@
 
 #include "gfx/gfxfilter_ogl.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 namespace OGL {
@@ -48,5 +49,6 @@ public:
 } // namespace OGL
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/gfx/gfxfilter_allegro.h b/engines/ags/engine/gfx/gfxfilter_allegro.h
index c2982344f9..fe2b856c8b 100644
--- a/engines/ags/engine/gfx/gfxfilter_allegro.h
+++ b/engines/ags/engine/gfx/gfxfilter_allegro.h
@@ -33,6 +33,7 @@
 #include "gfx/gfxfilter_scaling.h"
 #include "gfx/gfxdefines.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 namespace ALSW {
@@ -73,5 +74,6 @@ protected:
 } // namespace ALSW
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/gfx/gfxfilter_d3d.h b/engines/ags/engine/gfx/gfxfilter_d3d.h
index 2db3af5d32..ead9ae305e 100644
--- a/engines/ags/engine/gfx/gfxfilter_d3d.h
+++ b/engines/ags/engine/gfx/gfxfilter_d3d.h
@@ -31,6 +31,7 @@
 
 #include "gfx/gfxfilter_scaling.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 namespace D3D {
@@ -48,5 +49,6 @@ public:
 } // namespace D3D
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/gfx/gfxfilter_hqx.h b/engines/ags/engine/gfx/gfxfilter_hqx.h
index b00323a718..232e180520 100644
--- a/engines/ags/engine/gfx/gfxfilter_hqx.h
+++ b/engines/ags/engine/gfx/gfxfilter_hqx.h
@@ -31,6 +31,7 @@
 
 #include "gfx/gfxfilter_allegro.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 namespace ALSW {
@@ -60,5 +61,6 @@ protected:
 } // namespace ALSW
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/gfx/gfxfilter_ogl.h b/engines/ags/engine/gfx/gfxfilter_ogl.h
index 194bf95394..863dc0a5e5 100644
--- a/engines/ags/engine/gfx/gfxfilter_ogl.h
+++ b/engines/ags/engine/gfx/gfxfilter_ogl.h
@@ -31,6 +31,7 @@
 
 #include "gfx/gfxfilter_scaling.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 namespace OGL {
@@ -48,5 +49,6 @@ public:
 } // namespace D3D
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/gfx/gfxfilter_scaling.h b/engines/ags/engine/gfx/gfxfilter_scaling.h
index 85aeb1b5a1..f6be6a1729 100644
--- a/engines/ags/engine/gfx/gfxfilter_scaling.h
+++ b/engines/ags/engine/gfx/gfxfilter_scaling.h
@@ -32,6 +32,7 @@
 #include "gfx/gfxfilter.h"
 #include "util/scaling.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
@@ -49,5 +50,6 @@ protected:
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/gfx/gfxmodelist.h b/engines/ags/engine/gfx/gfxmodelist.h
index 0fc2889621..718ea5ce4f 100644
--- a/engines/ags/engine/gfx/gfxmodelist.h
+++ b/engines/ags/engine/gfx/gfxmodelist.h
@@ -32,6 +32,7 @@
 #include "core/types.h"
 #include "gfx/gfxdefines.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
@@ -44,5 +45,6 @@ public:
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/gfx/graphicsdriver.h b/engines/ags/engine/gfx/graphicsdriver.h
index 0108fad670..70c39574fb 100644
--- a/engines/ags/engine/gfx/graphicsdriver.h
+++ b/engines/ags/engine/gfx/graphicsdriver.h
@@ -34,12 +34,13 @@
 #include "gfx/gfxmodelist.h"
 #include "util/geometry.h"
 
+namespace AGS3 {
 namespace AGS {
 
 namespace Common {
 class Bitmap;
 typedef std::shared_ptr<Common::Bitmap> PBitmap;
-}
+} // namespace Common
 
 namespace Engine {
 
@@ -70,10 +71,12 @@ struct SpriteTransform {
 	float Rotate; // angle, in radians
 
 	SpriteTransform()
-		: X(0), Y(0), ScaleX(1.f), ScaleY(1.f), Rotate(0.f) {}
+		: X(0), Y(0), ScaleX(1.f), ScaleY(1.f), Rotate(0.f) {
+	}
 
 	SpriteTransform(int x, int y, float scalex = 1.0f, float scaley = 1.0f, float rotate = 0.0f)
-		: X(x), Y(y), ScaleX(scalex), ScaleY(scaley), Rotate(rotate) {}
+		: X(x), Y(y), ScaleX(scalex), ScaleY(scaley), Rotate(rotate) {
+	}
 };
 
 typedef void (*GFXDRV_CLIENTCALLBACK)();
@@ -129,7 +132,7 @@ public:
 	// global model transformation; all subsequent calls to DrawSprite will be adding
 	// sprites to this batch's list.
 	virtual void BeginSpriteBatch(const Rect &viewport, const SpriteTransform &transform,
-	                              const Point offset = Point(), GlobalFlipType flip = kFlip_None, PBitmap surface = nullptr) = 0;
+		const Point offset = Point(), GlobalFlipType flip = kFlip_None, PBitmap surface = nullptr) = 0;
 	// Adds sprite to the active batch
 	virtual void DrawSprite(int x, int y, IDriverDependantBitmap *bitmap) = 0;
 	// Adds fade overlay fx to the active batch
@@ -191,5 +194,6 @@ public:
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/gfx/hq2x3x.h b/engines/ags/engine/gfx/hq2x3x.h
index 741c31c0b6..4d679e86f2 100644
--- a/engines/ags/engine/gfx/hq2x3x.h
+++ b/engines/ags/engine/gfx/hq2x3x.h
@@ -25,14 +25,21 @@
 
 #include "core/platform.h"
 
+namespace AGS3 {
+
 #if AGS_PLATFORM_OS_ANDROID
-void InitLUTs() {}
-void hq2x_32(unsigned char *pIn, unsigned char *pOut, int Xres, int Yres, int BpL) {}
-void hq3x_32(unsigned char *pIn, unsigned char *pOut, int Xres, int Yres, int BpL) {}
+void InitLUTs() {
+}
+void hq2x_32(unsigned char *pIn, unsigned char *pOut, int Xres, int Yres, int BpL) {
+}
+void hq3x_32(unsigned char *pIn, unsigned char *pOut, int Xres, int Yres, int BpL) {
+}
 #else
 void InitLUTs();
 void hq2x_32(unsigned char *pIn, unsigned char *pOut, int Xres, int Yres, int BpL);
 void hq3x_32(unsigned char *pIn, unsigned char *pOut, int Xres, int Yres, int BpL);
 #endif
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/gui/animatingguibutton.h b/engines/ags/engine/gui/animatingguibutton.h
index d735d22b0d..0445f1c636 100644
--- a/engines/ags/engine/gui/animatingguibutton.h
+++ b/engines/ags/engine/gui/animatingguibutton.h
@@ -25,6 +25,8 @@
 
 #include "ac/runtime_defines.h"
 
+namespace AGS3 {
+
 // Forward declaration
 namespace AGS {
 namespace Common {
@@ -44,4 +46,6 @@ struct AnimatingGUIButton {
 	void WriteToFile(Common::Stream *out);
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/gui/cscidialog.h b/engines/ags/engine/gui/cscidialog.h
index 0d29309420..47d5c6327d 100644
--- a/engines/ags/engine/gui/cscidialog.h
+++ b/engines/ags/engine/gui/cscidialog.h
@@ -31,6 +31,8 @@
 
 #include "gui/guidialoginternaldefs.h"
 
+namespace AGS3 {
+
 int  CSCIGetVersion();
 int  CSCIDrawWindow(int xx, int yy, int wid, int hit);
 void CSCIEraseWindow(int handl);
@@ -44,4 +46,6 @@ int  checkcontrols();
 int  finddefaultcontrol(int flagmask);
 int  GetBaseWidth();
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/gui/guidialog.h b/engines/ags/engine/gui/guidialog.h
index 883a68009f..16bb1dedff 100644
--- a/engines/ags/engine/gui/guidialog.h
+++ b/engines/ags/engine/gui/guidialog.h
@@ -23,6 +23,7 @@
 #ifndef AGS_ENGINE_GUI_GUIDIALOG_H
 #define AGS_ENGINE_GUI_GUIDIALOG_H
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 class Bitmap;
@@ -50,4 +51,6 @@ int  quitdialog();
 // last string value in gui dialog.
 char *get_gui_dialog_buffer();
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/gui/guidialogdefines.h b/engines/ags/engine/gui/guidialogdefines.h
index 2cbc25fa0b..e605424200 100644
--- a/engines/ags/engine/gui/guidialogdefines.h
+++ b/engines/ags/engine/gui/guidialogdefines.h
@@ -23,6 +23,10 @@
 #ifndef AGS_ENGINE_GUI_GUIDIALOGDEFINES_H
 #define AGS_ENGINE_GUI_GUIDIALOGDEFINES_H
 
+#include "ac/gamesetup.h"
+
+namespace AGS3 {
+
 #define MSG_RESTORE      984
 #define MSG_CANCEL       985    // "Cancel"
 #define MSG_SELECTLOAD   986    // "Select game to restore"
@@ -36,8 +40,6 @@
 #define MSG_PLAYBUTTON   994    // "Play"
 #define MSG_QUITDIALOG   995    // "Do you want to quit?"
 
-#include "ac/gamesetup.h"
-
 /*#define COL251 26
 #define COL252 28
 #define COL253 29
@@ -114,4 +116,6 @@ struct OnScreenWindow {
 	OnScreenWindow();
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/gui/guidialoginternaldefs.h b/engines/ags/engine/gui/guidialoginternaldefs.h
index cb305e884f..fd4e0777f8 100644
--- a/engines/ags/engine/gui/guidialoginternaldefs.h
+++ b/engines/ags/engine/gui/guidialoginternaldefs.h
@@ -25,6 +25,8 @@
 
 #include "gui/guidialogdefines.h"
 
+namespace AGS3 {
+
 #define _export
 #ifdef WINAPI
 #undef WINAPI
@@ -34,4 +36,6 @@ extern int ags_misbuttondown(int but);
 #define mbutrelease(X) (!ags_misbuttondown(X))
 #define TEXT_HT usetup.textheight
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/gui/mylabel.h b/engines/ags/engine/gui/mylabel.h
index 87ed7cb9f7..cb4905cd0b 100644
--- a/engines/ags/engine/gui/mylabel.h
+++ b/engines/ags/engine/gui/mylabel.h
@@ -25,7 +25,9 @@
 
 #include "gui/newcontrol.h"
 
-struct MyLabel: public NewControl {
+namespace AGS3 {
+
+struct MyLabel : public NewControl {
 	char text[150];
 	MyLabel(int xx, int yy, int wii, const char *tee);
 
@@ -36,4 +38,6 @@ struct MyLabel: public NewControl {
 	int processmessage(int mcode, int wParam, long lParam) override;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/gui/mylistbox.h b/engines/ags/engine/gui/mylistbox.h
index b9b599b839..128447bcc0 100644
--- a/engines/ags/engine/gui/mylistbox.h
+++ b/engines/ags/engine/gui/mylistbox.h
@@ -25,10 +25,12 @@
 
 #include "gui/newcontrol.h"
 
+namespace AGS3 {
+
 #define MAXLISTITEM 300
 #define ARROWWIDTH 8
 
-struct MyListBox: public NewControl {
+struct MyListBox : public NewControl {
 	int items, topitem, numonscreen, selected;
 	char *itemnames[MAXLISTITEM];
 	MyListBox(int xx, int yy, int wii, int hii);
@@ -41,4 +43,6 @@ struct MyListBox: public NewControl {
 	int processmessage(int mcode, int wParam, long lParam) override;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/gui/mypushbutton.h b/engines/ags/engine/gui/mypushbutton.h
index 92147b4840..a1870bcc22 100644
--- a/engines/ags/engine/gui/mypushbutton.h
+++ b/engines/ags/engine/gui/mypushbutton.h
@@ -25,7 +25,9 @@
 
 #include "gui/newcontrol.h"
 
-struct MyPushButton: public NewControl {
+namespace AGS3 {
+
+struct MyPushButton : public NewControl {
 	char text[50];
 	MyPushButton(int xx, int yy, int wi, int hi, const char *tex);
 	void draw(Common::Bitmap *ds) override;
@@ -33,4 +35,6 @@ struct MyPushButton: public NewControl {
 	int processmessage(int mcode, int wParam, long lParam) override;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/gui/mytextbox.h b/engines/ags/engine/gui/mytextbox.h
index 97d9b687d0..3a69094d4a 100644
--- a/engines/ags/engine/gui/mytextbox.h
+++ b/engines/ags/engine/gui/mytextbox.h
@@ -25,8 +25,10 @@
 
 #include "gui/newcontrol.h"
 
+namespace AGS3 {
+
 #define TEXTBOX_MAXLEN 49
-struct MyTextBox: public NewControl {
+struct MyTextBox : public NewControl {
 	char text[TEXTBOX_MAXLEN + 1];
 	MyTextBox(int xx, int yy, int wii, const char *tee);
 	void draw(Common::Bitmap *ds) override;
@@ -34,4 +36,6 @@ struct MyTextBox: public NewControl {
 	int processmessage(int mcode, int wParam, long lParam) override;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/gui/newcontrol.h b/engines/ags/engine/gui/newcontrol.h
index e496be3fce..690e93a0e9 100644
--- a/engines/ags/engine/gui/newcontrol.h
+++ b/engines/ags/engine/gui/newcontrol.h
@@ -25,6 +25,8 @@
 
 #include "gfx/bitmap.h"
 
+namespace AGS3 {
+
 using namespace AGS; // FIXME later
 
 struct NewControl {
@@ -43,4 +45,6 @@ struct NewControl {
 	void drawandmouse();
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/main/config.h b/engines/ags/engine/main/config.h
index 4b0c086533..528ce79582 100644
--- a/engines/ags/engine/main/config.h
+++ b/engines/ags/engine/main/config.h
@@ -26,6 +26,8 @@
 #include "main/graphics_mode.h"
 #include "util/ini_util.h"
 
+namespace AGS3 {
+
 using AGS::Common::String;
 using AGS::Common::ConfigTree;
 
@@ -79,5 +81,6 @@ void INIwriteint(ConfigTree &cfg, const String &sectn, const String &item, int v
 void INIwritestring(ConfigTree &cfg, const String &sectn, const String &item, const String &value);
 void INIwriteint(ConfigTree &cfg, const String &sectn, const String &item, int value);
 
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/main/engine.h b/engines/ags/engine/main/engine.h
index 030d48c09e..1efa0ec072 100644
--- a/engines/ags/engine/main/engine.h
+++ b/engines/ags/engine/main/engine.h
@@ -25,6 +25,8 @@
 
 #include "util/ini_util.h"
 
+namespace AGS3 {
+
 const char *get_engine_name();
 const char *get_engine_version();
 void        show_preload();
@@ -62,4 +64,6 @@ extern ResourcePaths ResPaths;
 typedef void (*t_engine_pre_init_callback)(void);
 extern void engine_set_pre_init_callback(t_engine_pre_init_callback callback);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/main/engine_setup.h b/engines/ags/engine/main/engine_setup.h
index 9c4a424517..feca62e0ef 100644
--- a/engines/ags/engine/main/engine_setup.h
+++ b/engines/ags/engine/main/engine_setup.h
@@ -26,6 +26,8 @@
 #include "util/geometry.h"
 #include "gfx/gfxdefines.h"
 
+namespace AGS3 {
+
 // Sets up game viewport and object scaling parameters depending on game.
 // TODO: this is part of the game init, not engine init, move it later
 void engine_init_resolution_settings(const Size game_size);
@@ -38,4 +40,6 @@ void engine_pre_gfxsystem_shutdown();
 // Applies necessary changes after screen<->virtual coordinate transformation has changed
 void on_coordinates_scaling_changed();
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/main/game_file.h b/engines/ags/engine/main/game_file.h
index d63929bff5..f822ed0cfd 100644
--- a/engines/ags/engine/main/game_file.h
+++ b/engines/ags/engine/main/game_file.h
@@ -26,6 +26,8 @@
 #include "util/error.h"
 #include "util/string.h"
 
+namespace AGS3 {
+
 using AGS::Common::HError;
 
 // Preload particular game-describing parameters from the game data header (title, save game dir name, etc)
@@ -34,4 +36,6 @@ HError preload_game_data();
 HError load_game_file();
 void display_game_file_error(HError err);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/main/game_run.h b/engines/ags/engine/main/game_run.h
index e2d8431e6f..52653659bc 100644
--- a/engines/ags/engine/main/game_run.h
+++ b/engines/ags/engine/main/game_run.h
@@ -23,11 +23,14 @@
 #ifndef AGS_ENGINE_MAIN_GAME_RUN_H
 #define AGS_ENGINE_MAIN_GAME_RUN_H
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Engine {
 class IDriverDependantBitmap;
-}
-}
+} // namespace Engine
+} // namespace AGS
+
 using namespace AGS::Engine; // FIXME later
 
 // Loops game frames until certain event takes place (for blocking actions)
@@ -54,4 +57,6 @@ bool run_service_key_controls(int &kgn);
 // otherwise returns true and provides mouse button code.
 bool run_service_mb_controls(int &mbut, int &mwheelz);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/main/game_start.h b/engines/ags/engine/main/game_start.h
index d672229c98..8ca81c2c60 100644
--- a/engines/ags/engine/main/game_start.h
+++ b/engines/ags/engine/main/game_start.h
@@ -23,7 +23,11 @@
 #ifndef AGS_ENGINE_MAIN_GAME_START_H
 #define AGS_ENGINE_MAIN_GAME_START_H
 
+namespace AGS3 {
+
 void start_game();
 void initialize_start_and_play_game(int override_start_room, const char *loadSaveGameOnStartup);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/main/graphics_mode.h b/engines/ags/engine/main/graphics_mode.h
index a75f85f19b..facdea50d8 100644
--- a/engines/ags/engine/main/graphics_mode.h
+++ b/engines/ags/engine/main/graphics_mode.h
@@ -27,6 +27,8 @@
 #include "util/scaling.h"
 #include "util/string.h"
 
+namespace AGS3 {
+
 using AGS::Common::String;
 using AGS::Engine::DisplayMode;
 
@@ -39,8 +41,8 @@ class IGfxModeList;
 }
 }
 bool find_nearest_supported_mode(const AGS::Engine::IGfxModeList &modes, const Size &wanted_size,
-                                 const int color_depth, const Size *ratio_reference, const Size *upper_bound,
-                                 AGS::Engine::DisplayMode &dm, int *mode_index = nullptr);
+	const int color_depth, const Size *ratio_reference, const Size *upper_bound,
+	AGS::Engine::DisplayMode &dm, int *mode_index = nullptr);
 
 
 // The game-to-screen transformation
@@ -119,8 +121,10 @@ struct ColorDepthOption {
 	int     Bits;   // color depth value in bits
 	bool    Forced; // whether the depth should be forced, or driver's recommendation used
 
-	ColorDepthOption() : Bits(0), Forced(false) {}
-	ColorDepthOption(int bits, bool forced = false) : Bits(bits), Forced(forced) {}
+	ColorDepthOption() : Bits(0), Forced(false) {
+	}
+	ColorDepthOption(int bits, bool forced = false) : Bits(bits), Forced(forced) {
+	}
 };
 
 // ActiveDisplaySetting struct merges DisplayMode and GameFrameSetup,
@@ -139,7 +143,7 @@ ActiveDisplaySetting graphics_mode_get_last_setting(bool windowed);
 bool graphics_mode_create_renderer(const String &driver_id);
 // Try to find and initialize compatible display mode as close to given setup as possible
 bool graphics_mode_set_dm_any(const Size &game_size, const DisplayModeSetup &dm_setup,
-                              const ColorDepthOption &color_depth, const GameFrameSetup &frame_setup);
+	const ColorDepthOption &color_depth, const GameFrameSetup &frame_setup);
 // Set the display mode with given parameters
 bool graphics_mode_set_dm(const AGS::Engine::DisplayMode &dm);
 // Set the native image size
@@ -155,4 +159,6 @@ bool graphics_mode_set_filter(const String &filter_id);
 // Releases current graphic mode and shuts down renderer
 void graphics_mode_shutdown();
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/main/main.h b/engines/ags/engine/main/main.h
index cd3a27e9b9..1b15acafc2 100644
--- a/engines/ags/engine/main/main.h
+++ b/engines/ags/engine/main/main.h
@@ -26,6 +26,8 @@
 #include "core/platform.h"
 #include "util/version.h"
 
+namespace AGS3 {
+
 // Current engine version
 extern AGS::Common::Version EngineVersion;
 // Lowest savedgame version, accepted by this engine
@@ -67,4 +69,6 @@ void main_print_help();
 
 int ags_entry_point(int argc, char *argv[]);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/main/main_allegro.h b/engines/ags/engine/main/main_allegro.h
index c6f0d3e7db..1d610d12f8 100644
--- a/engines/ags/engine/main/main_allegro.h
+++ b/engines/ags/engine/main/main_allegro.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_MAIN_MAINALLEGRO_H
 #define AGS_ENGINE_MAIN_MAINALLEGRO_H
 
+namespace AGS3 {
+
 // Gets allegro_error as a const string.
 // Please, use this getter to acquire error text, do not use allegro_error
 // global variable directly.
@@ -33,4 +35,6 @@ const char *get_allegro_error();
 // truncated. Null terminator is always guaranteed.
 const char *set_allegro_error(const char *format, ...);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/main/mainheader.h b/engines/ags/engine/main/mainheader.h
index 406e5c0787..10064e6425 100644
--- a/engines/ags/engine/main/mainheader.h
+++ b/engines/ags/engine/main/mainheader.h
@@ -45,8 +45,13 @@
 #include <sys/stat.h>
 #include <android/log.h>
 
+namespace AGS3 {
+
 extern "C" void selectLatestSavegame();
 extern bool psp_load_latest_savegame;
+
+} // namespace AGS3
+
 #endif
 
 #endif
diff --git a/engines/ags/engine/main/quit.h b/engines/ags/engine/main/quit.h
index cc1fab41e4..849173f814 100644
--- a/engines/ags/engine/main/quit.h
+++ b/engines/ags/engine/main/quit.h
@@ -23,27 +23,31 @@
 #ifndef AGS_ENGINE_MAIN_QUIT_H
 #define AGS_ENGINE_MAIN_QUIT_H
 
+namespace AGS3 {
+
 enum QuitReason {
-	kQuitKind_NormalExit        = 0x01,
-	kQuitKind_DeliberateAbort   = 0x02,
-	kQuitKind_GameException     = 0x04,
-	kQuitKind_EngineException   = 0x08,
+	kQuitKind_NormalExit = 0x01,
+	kQuitKind_DeliberateAbort = 0x02,
+	kQuitKind_GameException = 0x04,
+	kQuitKind_EngineException = 0x08,
 
 	// user closed the window or script command QuitGame was executed
-	kQuit_GameRequest   = kQuitKind_NormalExit | 0x10,
+	kQuit_GameRequest = kQuitKind_NormalExit | 0x10,
 
 	// user pressed abort game key
-	kQuit_UserAbort     = kQuitKind_DeliberateAbort | 0x20,
+	kQuit_UserAbort = kQuitKind_DeliberateAbort | 0x20,
 
 	// script command AbortGame was executed
-	kQuit_ScriptAbort   = kQuitKind_GameException | 0x10,
+	kQuit_ScriptAbort = kQuitKind_GameException | 0x10,
 	// game logic has generated a warning and warnings are treated as error
-	kQuit_GameWarning   = kQuitKind_GameException | 0x20,
+	kQuit_GameWarning = kQuitKind_GameException | 0x20,
 	// game logic has generated an error (often script error)
-	kQuit_GameError     = kQuitKind_GameException | 0x30,
+	kQuit_GameError = kQuitKind_GameException | 0x30,
 
 	// any kind of a fatal engine error
-	kQuit_FatalError    = kQuitKind_EngineException
+	kQuit_FatalError = kQuitKind_EngineException
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/main/update.h b/engines/ags/engine/main/update.h
index 45dd6158b3..8d478685b1 100644
--- a/engines/ags/engine/main/update.h
+++ b/engines/ags/engine/main/update.h
@@ -23,9 +23,13 @@
 #ifndef AGS_ENGINE_MAIN_UPDATE_H
 #define AGS_ENGINE_MAIN_UPDATE_H
 
+namespace AGS3 {
+
 #define MAX_SHEEP 30    // sheep == follower
 
 int do_movelist_move(short *mlnum, int *xx, int *yy);
 void update_stuff();
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/media/audio/ambientsound.h b/engines/ags/engine/media/audio/ambientsound.h
index 3a4fb9dc23..c0f06ca689 100644
--- a/engines/ags/engine/media/audio/ambientsound.h
+++ b/engines/ags/engine/media/audio/ambientsound.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_MEDIA_AUDIO_AMBIENTSOUND_H
 #define AGS_ENGINE_MEDIA_AUDIO_AMBIENTSOUND_H
 
+namespace AGS3 {
+
 // Forward declaration
 namespace AGS {
 namespace Common {
@@ -46,4 +48,6 @@ struct AmbientSound {
 	void WriteToFile(Common::Stream *out);
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/media/audio/audio.h b/engines/ags/engine/media/audio/audio.h
index 32079d8722..b518a0b93a 100644
--- a/engines/ags/engine/media/audio/audio.h
+++ b/engines/ags/engine/media/audio/audio.h
@@ -33,6 +33,8 @@
 #include "util/thread.h"
 #include "ac/timer.h"
 
+namespace AGS3 {
+
 struct SOUNDCLIP;
 
 //controls access to the channels, since that's the main point of synchronization between the streaming thread and the user code
@@ -76,7 +78,7 @@ void        calculate_reserved_channel_count();
 void        update_clip_default_volume(ScriptAudioClip *audioClip);
 void        start_fading_in_new_track_if_applicable(int fadeInChannel, ScriptAudioClip *newSound);
 void        stop_or_fade_out_channel(int fadeOutChannel, int fadeInChannel = -1, ScriptAudioClip *newSound = nullptr);
-SOUNDCLIP  *load_sound_clip(ScriptAudioClip *audioClip, bool repeat);
+SOUNDCLIP *load_sound_clip(ScriptAudioClip *audioClip, bool repeat);
 ScriptAudioChannel *play_audio_clip_on_channel(int channel, ScriptAudioClip *clip, int priority, int repeat, int fromOffset, SOUNDCLIP *cachedClip = nullptr);
 void        remove_clips_of_type_from_queue(int audioType);
 void        update_queued_clips_volume(int audioType, int new_vol);
@@ -156,4 +158,6 @@ extern SOUNDCLIP *cachedQueuedMusic;
 // TODO: double check that ambient sounds array actually needs +1
 extern std::array < AmbientSound, MAX_SOUND_CHANNELS + 1 > ambient;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/media/audio/clip_mydumbmod.h b/engines/ags/engine/media/audio/clip_mydumbmod.h
index 55efab4d1c..50b3cc3c6a 100644
--- a/engines/ags/engine/media/audio/clip_mydumbmod.h
+++ b/engines/ags/engine/media/audio/clip_mydumbmod.h
@@ -26,6 +26,8 @@
 #include "aldumb.h"
 #include "media/audio/soundclip.h"
 
+namespace AGS3 {
+
 #define VOLUME_TO_DUMB_VOL(vol) ((float)vol) / 256.0
 
 void al_duh_set_loop(AL_DUH_PLAYER *dp, int loop);
@@ -73,4 +75,6 @@ protected:
 	int get_real_mod_pos();
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/media/audio/clip_myjgmod.h b/engines/ags/engine/media/audio/clip_myjgmod.h
index 72e6032230..3b6a6f45dc 100644
--- a/engines/ags/engine/media/audio/clip_myjgmod.h
+++ b/engines/ags/engine/media/audio/clip_myjgmod.h
@@ -26,8 +26,10 @@
 #include "jgmod.h"
 #include "media/audio/soundclip.h"
 
+namespace AGS3 {
+
 // MOD/XM (JGMOD)
-struct MYMOD: public SOUNDCLIP {
+struct MYMOD : public SOUNDCLIP {
 	JGMOD *tune;
 
 	int poll();
@@ -53,4 +55,6 @@ struct MYMOD: public SOUNDCLIP {
 	MYMOD();
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/media/audio/clip_mymidi.h b/engines/ags/engine/media/audio/clip_mymidi.h
index e250c346f8..18a2f32046 100644
--- a/engines/ags/engine/media/audio/clip_mymidi.h
+++ b/engines/ags/engine/media/audio/clip_mymidi.h
@@ -25,8 +25,10 @@
 
 #include "media/audio/soundclip.h"
 
+namespace AGS3 {
+
 // MIDI
-struct MYMIDI: public SOUNDCLIP {
+struct MYMIDI : public SOUNDCLIP {
 	MIDI *tune;
 	int lengthInSeconds;
 
@@ -59,4 +61,6 @@ protected:
 	void adjust_volume() override;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/media/audio/clip_mymp3.h b/engines/ags/engine/media/audio/clip_mymp3.h
index d4fafabe98..f658fd5ce6 100644
--- a/engines/ags/engine/media/audio/clip_mymp3.h
+++ b/engines/ags/engine/media/audio/clip_mymp3.h
@@ -26,9 +26,11 @@
 #include "almp3.h"
 #include "media/audio/soundclip.h"
 
+namespace AGS3 {
+
 extern AGS::Engine::Mutex _mp3_mutex;
 
-struct MYMP3: public SOUNDCLIP {
+struct MYMP3 : public SOUNDCLIP {
 	ALMP3_MP3STREAM *stream;
 	PACKFILE *in;
 	size_t filesize;
@@ -54,4 +56,6 @@ private:
 	void adjust_stream();
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/media/audio/clip_myogg.h b/engines/ags/engine/media/audio/clip_myogg.h
index b8fbd0dace..05cd7439a0 100644
--- a/engines/ags/engine/media/audio/clip_myogg.h
+++ b/engines/ags/engine/media/audio/clip_myogg.h
@@ -26,7 +26,9 @@
 #include "alogg.h"
 #include "media/audio/soundclip.h"
 
-struct MYOGG: public SOUNDCLIP {
+namespace AGS3 {
+
+struct MYOGG : public SOUNDCLIP {
 	ALOGG_OGGSTREAM *stream;
 	PACKFILE *in;
 	char *buffer;
@@ -64,4 +66,6 @@ private:
 	void adjust_stream();
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/media/audio/clip_mystaticmp3.h b/engines/ags/engine/media/audio/clip_mystaticmp3.h
index 6492518430..291d20f98e 100644
--- a/engines/ags/engine/media/audio/clip_mystaticmp3.h
+++ b/engines/ags/engine/media/audio/clip_mystaticmp3.h
@@ -26,10 +26,12 @@
 #include "almp3.h"
 #include "media/audio/soundclip.h"
 
+namespace AGS3 {
+
 extern AGS::Engine::Mutex _mp3_mutex;
 
 // pre-loaded (non-streaming) MP3 file
-struct MYSTATICMP3: public SOUNDCLIP {
+struct MYSTATICMP3 : public SOUNDCLIP {
 	ALMP3_MP3 *tune;
 	char *mp3buffer;
 
@@ -61,4 +63,6 @@ private:
 	void adjust_stream();
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/media/audio/clip_mystaticogg.h b/engines/ags/engine/media/audio/clip_mystaticogg.h
index 18972ce79b..bc5f5ea386 100644
--- a/engines/ags/engine/media/audio/clip_mystaticogg.h
+++ b/engines/ags/engine/media/audio/clip_mystaticogg.h
@@ -26,8 +26,10 @@
 #include "alogg.h"
 #include "media/audio/soundclip.h"
 
+namespace AGS3 {
+
 // pre-loaded (non-streaming) OGG file
-struct MYSTATICOGG: public SOUNDCLIP {
+struct MYSTATICOGG : public SOUNDCLIP {
 	ALOGG_OGG *tune;
 	char *mp3buffer;
 	int mp3buffersize;
@@ -67,4 +69,6 @@ private:
 	void adjust_stream();
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/media/audio/clip_mywave.h b/engines/ags/engine/media/audio/clip_mywave.h
index 4c479b4cff..7173367a12 100644
--- a/engines/ags/engine/media/audio/clip_mywave.h
+++ b/engines/ags/engine/media/audio/clip_mywave.h
@@ -25,8 +25,10 @@
 
 #include "media/audio/soundclip.h"
 
+namespace AGS3 {
+
 // My new MP3STREAM wrapper
-struct MYWAVE: public SOUNDCLIP {
+struct MYWAVE : public SOUNDCLIP {
 	SAMPLE *wave;
 	int voice;
 
@@ -54,4 +56,6 @@ protected:
 	void adjust_volume() override;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/media/audio/queuedaudioitem.h b/engines/ags/engine/media/audio/queuedaudioitem.h
index f73fd0de14..99a917c99f 100644
--- a/engines/ags/engine/media/audio/queuedaudioitem.h
+++ b/engines/ags/engine/media/audio/queuedaudioitem.h
@@ -23,13 +23,16 @@
 #ifndef AGS_ENGINE_MEDIA_AUDIO_QUEUEDAUDIOITEM_H
 #define AGS_ENGINE_MEDIA_AUDIO_QUEUEDAUDIOITEM_H
 
+namespace AGS3 {
+
 struct SOUNDCLIP;
 
 namespace AGS {
 namespace Common {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 struct QueuedAudioItem {
@@ -42,4 +45,6 @@ struct QueuedAudioItem {
 	void WriteToFile(Common::Stream *out) const;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/media/audio/sound.h b/engines/ags/engine/media/audio/sound.h
index 0d51ffbeda..e98c4a7f5e 100644
--- a/engines/ags/engine/media/audio/sound.h
+++ b/engines/ags/engine/media/audio/sound.h
@@ -32,6 +32,8 @@
 #include "ac/asset_helper.h"
 #include "media/audio/soundclip.h"
 
+namespace AGS3 {
+
 SOUNDCLIP *my_load_wave(const AssetPath &asset_name, int voll, int loop);
 SOUNDCLIP *my_load_mp3(const AssetPath &asset_name, int voll);
 SOUNDCLIP *my_load_static_mp3(const AssetPath &asset_name, int voll, bool loop);
@@ -42,4 +44,6 @@ SOUNDCLIP *my_load_mod(const AssetPath &asset_name, int repet);
 
 extern int use_extra_sound_offset;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/media/audio/soundcache.h b/engines/ags/engine/media/audio/soundcache.h
index 09e88138a6..09162ba1f7 100644
--- a/engines/ags/engine/media/audio/soundcache.h
+++ b/engines/ags/engine/media/audio/soundcache.h
@@ -25,6 +25,8 @@
 
 #include "ac/asset_helper.h"
 
+namespace AGS3 {
+
 // PSP: A simple sound cache. The size can be configured in the config file.
 // The data rate while reading from disk on the PSP is usually between 500 to 900 kiB/s,
 // caching the last used sound files therefore improves game performance.
@@ -51,5 +53,6 @@ void clear_sound_cache();
 void sound_cache_free(char *buffer, bool is_wave);
 char *get_cached_sound(const AssetPath &asset_name, bool is_wave, size_t &size);
 
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/media/audio/soundclip.h b/engines/ags/engine/media/audio/soundclip.h
index 2158dbac22..48daf5c926 100644
--- a/engines/ags/engine/media/audio/soundclip.h
+++ b/engines/ags/engine/media/audio/soundclip.h
@@ -31,6 +31,8 @@
 
 #include "util/mutex.h"
 
+namespace AGS3 {
+
 // JJS: This is needed for the derieved classes
 extern volatile int psp_audio_multithreaded;
 
@@ -40,7 +42,9 @@ extern volatile int psp_audio_multithreaded;
 // Improving this situation is only possible with massive refactory of
 // sound clip use, taking backwards-compatible audio system in account.
 
-enum SoundClipState { SoundClipInitial, SoundClipPlaying, SoundClipPaused, SoundClipStopped };
+enum SoundClipState {
+	SoundClipInitial, SoundClipPlaying, SoundClipPaused, SoundClipStopped
+};
 
 struct SOUNDCLIP {
 	int priority;
@@ -171,4 +175,6 @@ protected:
 	}
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/media/video/VMR9Graph.h b/engines/ags/engine/media/video/VMR9Graph.h
index e850d6b741..e6a8713355 100644
--- a/engines/ags/engine/media/video/VMR9Graph.h
+++ b/engines/ags/engine/media/video/VMR9Graph.h
@@ -36,6 +36,8 @@
 #include <dshow.h>
 #include <Vmr9.h>
 
+namespace AGS3 {
+
 //#pragma comment( lib, "strmiids.lib" )
 //#pragma comment( lib, "Quartz.lib" )
 //#pragma comment( lib, "d3d9.lib" )
@@ -127,33 +129,35 @@ protected:
 	DWORD                       m_dwRotId;
 	char                        m_pszErrorDescription[1024 + MAX_ERROR_TEXT_LEN];
 	int                         m_nNumberOfStream;
-	const char    *m_pszFileName;
+	const char *m_pszFileName;
 	long m_oldWndProc;
 	// MEDIA WINDOW
 	HWND                        m_hMediaWindow;
 	// SRC interfaces array
-	IBaseFilter                *m_srcFilterArray[10];
+	IBaseFilter *m_srcFilterArray[10];
 	// SOUND interfaces
-	IBaseFilter                *m_pDirectSoundFilter;
+	IBaseFilter *m_pDirectSoundFilter;
 	// GRAPH interfaces
-	IUnknown                   *m_pGraphUnknown;
-	IGraphBuilder              *m_pGraphBuilder;
-	IFilterGraph               *m_pFilterGraph;
-	IFilterGraph2              *m_pFilterGraph2;
-	IMediaControl              *m_pMediaControl;
-	IMediaSeeking                *m_pMediaSeeking;
+	IUnknown *m_pGraphUnknown;
+	IGraphBuilder *m_pGraphBuilder;
+	IFilterGraph *m_pFilterGraph;
+	IFilterGraph2 *m_pFilterGraph2;
+	IMediaControl *m_pMediaControl;
+	IMediaSeeking *m_pMediaSeeking;
 	//IMediaEvent*              m_pMediaEvent;
-	IMediaEventEx              *m_pMediaEventEx;
+	IMediaEventEx *m_pMediaEventEx;
 	// VMR9 interfaces
-	IBaseFilter                *m_pVMRBaseFilter;
-	IVMRFilterConfig9          *m_pVMRFilterConfig;
-	IVMRMixerBitmap9           *m_pVMRMixerBitmap;
-	IVMRMixerControl9          *m_pVMRMixerControl;
-	IVMRMonitorConfig9         *m_pVMRMonitorConfig;
-	IVMRWindowlessControl9     *m_pVMRWindowlessControl;
+	IBaseFilter *m_pVMRBaseFilter;
+	IVMRFilterConfig9 *m_pVMRFilterConfig;
+	IVMRMixerBitmap9 *m_pVMRMixerBitmap;
+	IVMRMixerControl9 *m_pVMRMixerControl;
+	IVMRMonitorConfig9 *m_pVMRMonitorConfig;
+	IVMRWindowlessControl9 *m_pVMRWindowlessControl;
 	// DIRECT3D interfaces
 	//IDirect3DDevice9*         m_pD3DDevice;
-	IDirect3DSurface9          *m_pD3DSurface;
+	IDirect3DSurface9 *m_pD3DSurface;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/media/video/video.h b/engines/ags/engine/media/video/video.h
index 16c037f7da..558189e3f7 100644
--- a/engines/ags/engine/media/video/video.h
+++ b/engines/ags/engine/media/video/video.h
@@ -23,10 +23,14 @@
 #ifndef AGS_ENGINE_MEDIA_VIDEO_VIDEO_H
 #define AGS_ENGINE_MEDIA_VIDEO_VIDEO_H
 
+namespace AGS3 {
+
 void play_theora_video(const char *name, int skip, int flags);
 void play_flc_file(int numb, int playflags);
 
 // Update video playback if the display mode has changed
 void video_on_gfxmode_changed();
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/platform/base/agsplatformdriver.h b/engines/ags/engine/platform/base/agsplatformdriver.h
index 03a7a61416..360d3600df 100644
--- a/engines/ags/engine/platform/base/agsplatformdriver.h
+++ b/engines/ags/engine/platform/base/agsplatformdriver.h
@@ -35,6 +35,8 @@
 #include "debug/outputhandler.h"
 #include "util/ini_util.h"
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Common {
 class Stream;
@@ -62,7 +64,7 @@ enum SetupReturnValue {
 };
 
 struct AGSPlatformDriver
-// be used as a output target for logging system
+	// be used as a output target for logging system
 	: public AGS::Common::IOutputHandler {
 	virtual void AboutToQuitGame();
 	virtual void Delay(int millis);
@@ -84,7 +86,7 @@ struct AGSPlatformDriver
 		return ".";
 	}
 	// Get directory for storing all-games user configuration files
-	virtual const char *GetUserGlobalConfigDirectory()  {
+	virtual const char *GetUserGlobalConfigDirectory() {
 		return ".";
 	}
 	// Get default directory for program output (logs)
@@ -150,7 +152,8 @@ struct AGSPlatformDriver
 	virtual void UnRegisterGameWithGameExplorer();
 	virtual int  ConvertKeycodeToScanCode(int keyCode);
 	// Adjust window size to ensure it is in the supported limits
-	virtual void ValidateWindowSize(int &x, int &y, bool borderless) const {}
+	virtual void ValidateWindowSize(int &x, int &y, bool borderless) const {
+	}
 
 	virtual int  InitializeCDPlayer() = 0;  // return 0 on success
 	virtual int  CDPlayerCommand(int cmdd, int datt) = 0;
@@ -201,4 +204,6 @@ int cd_player_control(int cmdd, int datt);
 // instance by calling AGSPlatformDriver::GetDriver()?
 extern AGSPlatformDriver *platform;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/platform/util/pe.h b/engines/ags/engine/platform/util/pe.h
index f6ab17c910..98bdc2227a 100644
--- a/engines/ags/engine/platform/util/pe.h
+++ b/engines/ags/engine/platform/util/pe.h
@@ -23,20 +23,24 @@
 #ifndef AGS_ENGINE_PLATFORM_UTIL_PE_H
 #define AGS_ENGINE_PLATFORM_UTIL_PE_H
 
+namespace AGS3 {
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-typedef struct {
-	char version[15];
-	char description[100];
-	char internal_name[100];
-} version_info_t;
+	typedef struct {
+		char version[15];
+		char description[100];
+		char internal_name[100];
+	} version_info_t;
 
-int getVersionInformation(char *filename, version_info_t *version_info);
+	int getVersionInformation(char *filename, version_info_t *version_info);
 
 #ifdef __cplusplus
 }
 #endif
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/platform/windows/debugging/namedpipesagsdebugger.h b/engines/ags/engine/platform/windows/debugging/namedpipesagsdebugger.h
index 01a192bdb2..597d091125 100644
--- a/engines/ags/engine/platform/windows/debugging/namedpipesagsdebugger.h
+++ b/engines/ags/engine/platform/windows/debugging/namedpipesagsdebugger.h
@@ -27,6 +27,8 @@
 #include <io.h>
 #include "debug/agseditordebugger.h"
 
+namespace AGS3 {
+
 struct NamedPipesAGSDebugger : IAGSEditorDebugger {
 private:
 	HANDLE _hPipeSending;
@@ -44,4 +46,6 @@ public:
 	virtual char *GetNextMessage() override;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/platform/windows/gfx/ali3dd3d.h b/engines/ags/engine/platform/windows/gfx/ali3dd3d.h
index 622a7f55d2..4a75d322b4 100644
--- a/engines/ags/engine/platform/windows/gfx/ali3dd3d.h
+++ b/engines/ags/engine/platform/windows/gfx/ali3dd3d.h
@@ -46,6 +46,8 @@
 #include "util/library.h"
 #include "util/string.h"
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Engine {
 namespace D3D {
@@ -201,7 +203,8 @@ public:
 	void Render() override;
 	void Render(int xoff, int yoff, GlobalFlipType flip) override;
 	bool GetCopyOfScreenIntoBitmap(Bitmap *destination, bool at_native_res, GraphicResolution *want_fmt) override;
-	void EnableVsyncBeforeRender(bool enabled) override { }
+	void EnableVsyncBeforeRender(bool enabled) override {
+	}
 	void Vsync() override;
 	void RenderSpritesAtScreenResolution(bool enabled, int supersampling) override {
 		_renderSprAtScreenRes = enabled;
@@ -311,14 +314,14 @@ public:
 	const GfxFilterInfo *GetFilterInfo(size_t index) const override;
 	String               GetDefaultFilterID() const override;
 
-	static D3DGraphicsFactory   *GetFactory();
-	static D3DGraphicsDriver    *GetD3DDriver();
+	static D3DGraphicsFactory *GetFactory();
+	static D3DGraphicsDriver *GetD3DDriver();
 
 private:
 	D3DGraphicsFactory();
 
-	D3DGraphicsDriver   *EnsureDriverCreated() override;
-	D3DGfxFilter        *CreateFilter(const String &id) override;
+	D3DGraphicsDriver *EnsureDriverCreated() override;
+	D3DGfxFilter *CreateFilter(const String &id) override;
 
 	bool Init();
 
@@ -341,11 +344,12 @@ private:
 	// TODO: find out if there is better solution.
 	//
 	static Library      _library;
-	IDirect3D9         *_direct3d;
+	IDirect3D9 *_direct3d;
 };
 
 } // namespace D3D
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/platform/windows/setup/winsetup.h b/engines/ags/engine/platform/windows/setup/winsetup.h
index fb14fd7899..87192595fd 100644
--- a/engines/ags/engine/platform/windows/setup/winsetup.h
+++ b/engines/ags/engine/platform/windows/setup/winsetup.h
@@ -31,6 +31,8 @@
 
 #include "util/ini_util.h"
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Engine {
 
@@ -38,9 +40,10 @@ using namespace Common;
 
 void SetWinIcon();
 SetupReturnValue WinSetup(const ConfigTree &cfg_in, ConfigTree &cfg_out,
-                          const String &game_data_dir, const String &version_str);
+	const String &game_data_dir, const String &version_str);
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/platform/windows/win_ex_handling.h b/engines/ags/engine/platform/windows/win_ex_handling.h
index 6caa91b572..c77d4cbf83 100644
--- a/engines/ags/engine/platform/windows/win_ex_handling.h
+++ b/engines/ags/engine/platform/windows/win_ex_handling.h
@@ -25,9 +25,13 @@
 
 #include "util/ini_util.h"
 
+namespace AGS3 {
+
 void setup_malloc_handling();
 int  initialize_engine_with_exception_handling(
-    int (initialize_engine)(const AGS::Common::ConfigTree &startup_opts),
-    const AGS::Common::ConfigTree &startup_opts);
+	int (initialize_engine)(const AGS::Common::ConfigTree &startup_opts),
+	const AGS::Common::ConfigTree &startup_opts);
+
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/platform/windows/winapi_exclusive.h b/engines/ags/engine/platform/windows/winapi_exclusive.h
index 69ac06b83b..dedc890e6a 100644
--- a/engines/ags/engine/platform/windows/winapi_exclusive.h
+++ b/engines/ags/engine/platform/windows/winapi_exclusive.h
@@ -31,6 +31,8 @@
 #ifndef AGS_ENGINE_PLATFORM_WINDOWS_WINAPI_EXCLUSIVE_H
 #define AGS_ENGINE_PLATFORM_WINDOWS_WINAPI_EXCLUSIVE_H
 
+namespace AGS3 {
+
 #ifndef _WINDOWS_ // do not include if windows.h was included first
 #define _WINDOWS_ // there can be only one
 
@@ -59,4 +61,6 @@ typedef int (FAR WINAPI *FARPROC)();
 
 #endif
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/plugin/agsplugin.h b/engines/ags/engine/plugin/agsplugin.h
index 5b1926674c..da60dda284 100644
--- a/engines/ags/engine/plugin/agsplugin.h
+++ b/engines/ags/engine/plugin/agsplugin.h
@@ -31,6 +31,8 @@
 #ifndef AGS_ENGINE_PLUGIN_AGSPLUGIN_H
 #define AGS_ENGINE_PLUGIN_AGSPLUGIN_H
 
+namespace AGS3 {
+
 // If the plugin isn't using DDraw, don't require the headers
 #ifndef DIRECTDRAW_VERSION
 typedef void *LPDIRECTDRAW2;
@@ -284,16 +286,20 @@ public:
 	// return number of bytes used
 	virtual int Serialize(const char *address, char *buffer, int bufsize) = 0;
 protected:
-	IAGSScriptManagedObject() {};
-	~IAGSScriptManagedObject() {};
+	IAGSScriptManagedObject() {
+	};
+	~IAGSScriptManagedObject() {
+	};
 };
 
 class IAGSManagedObjectReader {
 public:
 	virtual void Unserialize(int key, const char *serializedData, int dataSize) = 0;
 protected:
-	IAGSManagedObjectReader() {};
-	~IAGSManagedObjectReader() {};
+	IAGSManagedObjectReader() {
+	};
+	~IAGSManagedObjectReader() {
+	};
 };
 
 class IAGSFontRenderer {
@@ -307,8 +313,10 @@ public:
 	virtual void AdjustYCoordinateForFont(int *ycoord, int fontNumber) = 0;
 	virtual void EnsureTextValidForFont(char *text, int fontNumber) = 0;
 protected:
-	IAGSFontRenderer() {};
-	~IAGSFontRenderer() {};
+	IAGSFontRenderer() {
+	};
+	~IAGSFontRenderer() {
+	};
 };
 
 // The plugin-to-engine interface
@@ -579,4 +587,6 @@ DLLEXPORT int    AGS_PluginV2() {
 
 #endif // THIS_IS_THE_PLUGIN
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/plugin/plugin_builtin.h b/engines/ags/engine/plugin/plugin_builtin.h
index d598609f02..13538f8a60 100644
--- a/engines/ags/engine/plugin/plugin_builtin.h
+++ b/engines/ags/engine/plugin/plugin_builtin.h
@@ -29,6 +29,8 @@
 #ifndef AGS_ENGINE_PLUGIN_PLUGIN_BUILTIN_H
 #define AGS_ENGINE_PLUGIN_PLUGIN_BUILTIN_H
 
+namespace AGS3 {
+
 #define PLUGIN_FILENAME_MAX (49)
 
 class IAGSEngine;
@@ -49,4 +51,6 @@ struct InbuiltPluginDetails {
 // Register a builtin plugin.
 int pl_register_builtin_plugin(InbuiltPluginDetails const &details);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/plugin/plugin_engine.h b/engines/ags/engine/plugin/plugin_engine.h
index 17aef598ca..b988c7544c 100644
--- a/engines/ags/engine/plugin/plugin_engine.h
+++ b/engines/ags/engine/plugin/plugin_engine.h
@@ -33,14 +33,17 @@
 #include "game/game_init.h"
 #include "game/plugininfo.h"
 
+namespace AGS3 {
+
 #define PLUGIN_FILENAME_MAX (49)
 
 class IAGSEngine;
 namespace AGS {
 namespace Common {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 void pl_stop_plugins();
@@ -58,4 +61,6 @@ bool pl_any_want_hook(int event);
 void pl_set_file_handle(long data, AGS::Common::Stream *stream);
 void pl_clear_file_handle();
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/plugin/pluginobjectreader.h b/engines/ags/engine/plugin/pluginobjectreader.h
index e789c91724..3553962786 100644
--- a/engines/ags/engine/plugin/pluginobjectreader.h
+++ b/engines/ags/engine/plugin/pluginobjectreader.h
@@ -23,6 +23,8 @@
 #ifndef AGS_ENGINE_PLUGIN_PLUGINOBJECTREADER_H
 #define AGS_ENGINE_PLUGIN_PLUGINOBJECTREADER_H
 
+namespace AGS3 {
+
 class IAGSManagedObjectReader;
 
 struct PluginObjectReader {
@@ -30,4 +32,6 @@ struct PluginObjectReader {
 	const char *type;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/script/cc_instance.h b/engines/ags/engine/script/cc_instance.h
index 1826feb79d..5784d0aa4e 100644
--- a/engines/ags/engine/script/cc_instance.h
+++ b/engines/ags/engine/script/cc_instance.h
@@ -37,6 +37,8 @@
 #include "script/nonblockingscriptfunction.h"
 #include "util/string.h"
 
+namespace AGS3 {
+
 using namespace AGS;
 
 #define INSTF_SHAREDATA     1
@@ -59,8 +61,8 @@ struct ScriptImport;
 
 struct ScriptInstruction {
 	ScriptInstruction() {
-		Code        = 0;
-		InstanceId  = 0;
+		Code = 0;
+		InstanceId = 0;
 	}
 
 	int32_t Code;
@@ -79,7 +81,7 @@ struct ScriptOperation {
 
 struct ScriptVariable {
 	ScriptVariable() {
-		ScAddress   = -1; // address = 0 is valid one, -1 means undefined
+		ScAddress = -1; // address = 0 is valid one, -1 means undefined
 	}
 
 	int32_t             ScAddress;  // original 32-bit relative data address, written in compiled script;
@@ -144,7 +146,7 @@ public:
 	ccInstance *callStackCodeInst[MAX_CALL_STACK];
 
 	// array of real import indexes used in script
-	int  *resolved_imports;
+	int *resolved_imports;
 	int  numimports;
 
 	char *code_fixups;
@@ -218,4 +220,6 @@ protected:
 	void    PopFromFuncCallStack(FunctionCallStack &func_callstack, int32_t num_entries);
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/script/executingscript.h b/engines/ags/engine/script/executingscript.h
index bcc74128a4..ee4c7dfe65 100644
--- a/engines/ags/engine/script/executingscript.h
+++ b/engines/ags/engine/script/executingscript.h
@@ -25,6 +25,8 @@
 
 #include "script/cc_instance.h"
 
+namespace AGS3 {
+
 enum PostScriptAction {
 	ePSANewRoom,
 	ePSAInvScreen,
@@ -74,4 +76,6 @@ struct ExecutingScript {
 	ExecutingScript();
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/script/exports.h b/engines/ags/engine/script/exports.h
index 81459c6fdc..7132aa3fe7 100644
--- a/engines/ags/engine/script/exports.h
+++ b/engines/ags/engine/script/exports.h
@@ -29,6 +29,10 @@
 #ifndef AGS_ENGINE_SCRIPT_EXPORTS_H
 #define AGS_ENGINE_SCRIPT_EXPORTS_H
 
+namespace AGS3 {
+
 void setup_script_exports(ScriptAPIVersion base_api, ScriptAPIVersion compat_api);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/script/nonblockingscriptfunction.h b/engines/ags/engine/script/nonblockingscriptfunction.h
index 9e5da93df7..ad77689ea5 100644
--- a/engines/ags/engine/script/nonblockingscriptfunction.h
+++ b/engines/ags/engine/script/nonblockingscriptfunction.h
@@ -28,6 +28,8 @@
 
 #include <vector>
 
+namespace AGS3 {
+
 struct NonBlockingScriptFunction {
 	const char *functionName;
 	int numParameters;
@@ -48,4 +50,6 @@ struct NonBlockingScriptFunction {
 	}
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/script/runtimescriptvalue.h b/engines/ags/engine/script/runtimescriptvalue.h
index 91a02368e2..f7840fdee3 100644
--- a/engines/ags/engine/script/runtimescriptvalue.h
+++ b/engines/ags/engine/script/runtimescriptvalue.h
@@ -33,6 +33,8 @@
 #include "util/memory.h"
 #include "ac/dynobj/cc_dynamicobject.h"
 
+namespace AGS3 {
+
 struct ICCStaticObject;
 struct StaticArray;
 
@@ -63,19 +65,19 @@ enum ScriptValueType {
 struct RuntimeScriptValue {
 public:
 	RuntimeScriptValue() {
-		Type        = kScValUndefined;
-		IValue      = 0;
-		Ptr         = nullptr;
-		MgrPtr      = nullptr;
-		Size        = 0;
+		Type = kScValUndefined;
+		IValue = 0;
+		Ptr = nullptr;
+		MgrPtr = nullptr;
+		Size = 0;
 	}
 
 	RuntimeScriptValue(int32_t val) {
-		Type        = kScValInteger;
-		IValue      = val;
-		Ptr         = nullptr;
-		MgrPtr      = nullptr;
-		Size        = 4;
+		Type = kScValInteger;
+		IValue = val;
+		Ptr = nullptr;
+		MgrPtr = nullptr;
+		Size = 4;
 	}
 
 	ScriptValueType Type;
@@ -88,19 +90,19 @@ public:
 	// Pointer is used for storing... pointers - to objects, arrays,
 	// functions and stack entries (other RSV)
 	union {
-		char                *Ptr;   // generic data pointer
-		RuntimeScriptValue  *RValue;// access ptr as a pointer to Runtime Value
-		ScriptAPIFunction   *SPfn;  // access ptr as a pointer to Script API Static Function
+		char *Ptr;   // generic data pointer
+		RuntimeScriptValue *RValue;// access ptr as a pointer to Runtime Value
+		ScriptAPIFunction *SPfn;  // access ptr as a pointer to Script API Static Function
 		ScriptAPIObjectFunction *ObjPfn; // access ptr as a pointer to Script API Object Function
 	};
 	// TODO: separation to Ptr and MgrPtr is only needed so far as there's
 	// a separation between Script*, Dynamic* and game entity classes.
 	// Once those classes are merged, it will no longer be needed.
 	union {
-		void                *MgrPtr;// generic object manager pointer
-		ICCStaticObject     *StcMgr;// static object manager
-		StaticArray         *StcArr;// static array manager
-		ICCDynamicObject    *DynMgr;// dynamic object manager
+		void *MgrPtr;// generic object manager pointer
+		ICCStaticObject *StcMgr;// static object manager
+		StaticArray *StcArr;// static array manager
+		ICCDynamicObject *DynMgr;// dynamic object manager
 	};
 	// The "real" size of data, either one stored in I/FValue,
 	// or the one referenced by Ptr. Used for calculating stack
@@ -125,43 +127,43 @@ public:
 	}
 
 	inline RuntimeScriptValue &Invalidate() {
-		Type    = kScValUndefined;
-		IValue   = 0;
-		Ptr     = nullptr;
-		MgrPtr  = nullptr;
-		Size    = 0;
+		Type = kScValUndefined;
+		IValue = 0;
+		Ptr = nullptr;
+		MgrPtr = nullptr;
+		Size = 0;
 		return *this;
 	}
 	inline RuntimeScriptValue &SetUInt8(uint8_t val) {
-		Type    = kScValInteger;
-		IValue  = val;
-		Ptr     = nullptr;
-		MgrPtr  = nullptr;
-		Size    = 1;
+		Type = kScValInteger;
+		IValue = val;
+		Ptr = nullptr;
+		MgrPtr = nullptr;
+		Size = 1;
 		return *this;
 	}
 	inline RuntimeScriptValue &SetInt16(int16_t val) {
-		Type    = kScValInteger;
-		IValue  = val;
-		Ptr     = nullptr;
-		MgrPtr  = nullptr;
-		Size    = 2;
+		Type = kScValInteger;
+		IValue = val;
+		Ptr = nullptr;
+		MgrPtr = nullptr;
+		Size = 2;
 		return *this;
 	}
 	inline RuntimeScriptValue &SetInt32(int32_t val) {
-		Type    = kScValInteger;
-		IValue  = val;
-		Ptr     = nullptr;
-		MgrPtr  = nullptr;
-		Size    = 4;
+		Type = kScValInteger;
+		IValue = val;
+		Ptr = nullptr;
+		MgrPtr = nullptr;
+		Size = 4;
 		return *this;
 	}
 	inline RuntimeScriptValue &SetFloat(float val) {
-		Type    = kScValFloat;
-		FValue  = val;
-		Ptr     = nullptr;
-		MgrPtr  = nullptr;
-		Size    = 4;
+		Type = kScValFloat;
+		FValue = val;
+		Ptr = nullptr;
+		MgrPtr = nullptr;
+		Size = 4;
 		return *this;
 	}
 	inline RuntimeScriptValue &SetInt32AsBool(bool val) {
@@ -171,108 +173,108 @@ public:
 		return SetFloat(val ? 1.0F : 0.0F);
 	}
 	inline RuntimeScriptValue &SetPluginArgument(int32_t val) {
-		Type    = kScValPluginArg;
-		IValue  = val;
-		Ptr     = nullptr;
-		MgrPtr  = nullptr;
-		Size    = 4;
+		Type = kScValPluginArg;
+		IValue = val;
+		Ptr = nullptr;
+		MgrPtr = nullptr;
+		Size = 4;
 		return *this;
 	}
 	inline RuntimeScriptValue &SetStackPtr(RuntimeScriptValue *stack_entry) {
-		Type    = kScValStackPtr;
-		IValue  = 0;
-		RValue  = stack_entry;
-		MgrPtr  = nullptr;
-		Size    = 4;
+		Type = kScValStackPtr;
+		IValue = 0;
+		RValue = stack_entry;
+		MgrPtr = nullptr;
+		Size = 4;
 		return *this;
 	}
 	inline RuntimeScriptValue &SetData(char *data, int size) {
-		Type    = kScValData;
-		IValue  = 0;
-		Ptr     = data;
-		MgrPtr  = nullptr;
-		Size    = size;
+		Type = kScValData;
+		IValue = 0;
+		Ptr = data;
+		MgrPtr = nullptr;
+		Size = size;
 		return *this;
 	}
 	inline RuntimeScriptValue &SetGlobalVar(RuntimeScriptValue *glvar_value) {
-		Type    = kScValGlobalVar;
-		IValue  = 0;
-		RValue  = glvar_value;
-		MgrPtr  = nullptr;
-		Size    = 4;
+		Type = kScValGlobalVar;
+		IValue = 0;
+		RValue = glvar_value;
+		MgrPtr = nullptr;
+		Size = 4;
 		return *this;
 	}
 	// TODO: size?
 	inline RuntimeScriptValue &SetStringLiteral(const char *str) {
-		Type    = kScValStringLiteral;
-		IValue  = 0;
-		Ptr     = const_cast<char *>(str);
-		MgrPtr  = nullptr;
-		Size    = 4;
+		Type = kScValStringLiteral;
+		IValue = 0;
+		Ptr = const_cast<char *>(str);
+		MgrPtr = nullptr;
+		Size = 4;
 		return *this;
 	}
 	inline RuntimeScriptValue &SetStaticObject(void *object, ICCStaticObject *manager) {
-		Type    = kScValStaticObject;
-		IValue  = 0;
-		Ptr     = (char *)object;
-		StcMgr  = manager;
-		Size    = 4;
+		Type = kScValStaticObject;
+		IValue = 0;
+		Ptr = (char *)object;
+		StcMgr = manager;
+		Size = 4;
 		return *this;
 	}
 	inline RuntimeScriptValue &SetStaticArray(void *object, StaticArray *manager) {
-		Type    = kScValStaticArray;
-		IValue  = 0;
-		Ptr     = (char *)object;
-		StcArr  = manager;
-		Size    = 4;
+		Type = kScValStaticArray;
+		IValue = 0;
+		Ptr = (char *)object;
+		StcArr = manager;
+		Size = 4;
 		return *this;
 	}
 	inline RuntimeScriptValue &SetDynamicObject(void *object, ICCDynamicObject *manager) {
-		Type    = kScValDynamicObject;
-		IValue  = 0;
-		Ptr     = (char *)object;
-		DynMgr  = manager;
-		Size    = 4;
+		Type = kScValDynamicObject;
+		IValue = 0;
+		Ptr = (char *)object;
+		DynMgr = manager;
+		Size = 4;
 		return *this;
 	}
 	inline RuntimeScriptValue &SetPluginObject(void *object, ICCDynamicObject *manager) {
-		Type    = kScValPluginObject;
-		IValue  = 0;
-		Ptr     = (char *)object;
-		DynMgr  = manager;
-		Size    = 4;
+		Type = kScValPluginObject;
+		IValue = 0;
+		Ptr = (char *)object;
+		DynMgr = manager;
+		Size = 4;
 		return *this;
 	}
 	inline RuntimeScriptValue &SetStaticFunction(ScriptAPIFunction *pfn) {
-		Type    = kScValStaticFunction;
-		IValue  = 0;
-		SPfn    = pfn;
-		MgrPtr  = nullptr;
-		Size    = 4;
+		Type = kScValStaticFunction;
+		IValue = 0;
+		SPfn = pfn;
+		MgrPtr = nullptr;
+		Size = 4;
 		return *this;
 	}
 	inline RuntimeScriptValue &SetPluginFunction(void *pfn) {
-		Type    = kScValPluginFunction;
-		IValue  = 0;
-		Ptr     = (char *)pfn;
-		MgrPtr  = nullptr;
-		Size    = 4;
+		Type = kScValPluginFunction;
+		IValue = 0;
+		Ptr = (char *)pfn;
+		MgrPtr = nullptr;
+		Size = 4;
 		return *this;
 	}
 	inline RuntimeScriptValue &SetObjectFunction(ScriptAPIObjectFunction *pfn) {
-		Type    = kScValObjectFunction;
-		IValue  = 0;
-		ObjPfn  = pfn;
-		MgrPtr  = nullptr;
-		Size    = 4;
+		Type = kScValObjectFunction;
+		IValue = 0;
+		ObjPfn = pfn;
+		MgrPtr = nullptr;
+		Size = 4;
 		return *this;
 	}
 	inline RuntimeScriptValue &SetCodePtr(char *ptr) {
-		Type    = kScValCodePtr;
-		IValue  = 0;
-		Ptr     = ptr;
-		MgrPtr  = nullptr;
-		Size    = 4;
+		Type = kScValCodePtr;
+		IValue = 0;
+		Ptr = ptr;
+		MgrPtr = nullptr;
+		Size = 4;
 		return *this;
 	}
 
@@ -293,7 +295,8 @@ public:
 	inline RuntimeScriptValue ReadValue() {
 		RuntimeScriptValue rval;
 		switch (this->Type) {
-		case kScValStackPtr: {
+		case kScValStackPtr:
+		{
 			if (RValue->Type == kScValData) {
 				rval.SetInt32(*(int32_t *)(RValue->GetPtrWithOffset() + this->IValue));
 			} else {
@@ -301,7 +304,8 @@ public:
 			}
 		}
 		break;
-		case kScValGlobalVar: {
+		case kScValGlobalVar:
+		{
 			if (RValue->Type == kScValData) {
 				rval.SetInt32(AGS::Common::Memory::ReadInt32LE(RValue->GetPtrWithOffset() + this->IValue));
 			} else {
@@ -310,15 +314,18 @@ public:
 		}
 		break;
 		case kScValStaticObject:
-		case kScValStaticArray: {
+		case kScValStaticArray:
+		{
 			rval.SetInt32(this->StcMgr->ReadInt32(this->Ptr, this->IValue));
 		}
 		break;
-		case kScValDynamicObject: {
+		case kScValDynamicObject:
+		{
 			rval.SetInt32(this->DynMgr->ReadInt32(this->Ptr, this->IValue));
 		}
 		break;
-		default: {
+		default:
+		{
 			// 64 bit: Memory reads are still 32 bit
 			rval.SetInt32(*(int32_t *)this->GetPtrWithOffset());
 		}
@@ -348,4 +355,6 @@ public:
 	intptr_t           GetDirectPtr() const;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/script/script.h b/engines/ags/engine/script/script.h
index 14d635a2f9..cdcababda4 100644
--- a/engines/ags/engine/script/script.h
+++ b/engines/ags/engine/script/script.h
@@ -33,6 +33,8 @@
 #include "game/interactions.h"
 #include "util/string.h"
 
+namespace AGS3 {
+
 using AGS::Common::Interaction;
 using AGS::Common::InteractionCommandList;
 using AGS::Common::InteractionScripts;
@@ -52,10 +54,10 @@ void    cancel_all_scripts();
 ccInstance *GetScriptInstanceByType(ScriptInstType sc_inst);
 // Queues a script function to be run either called by the engine or from another script
 void    QueueScriptFunction(ScriptInstType sc_inst, const char *fn_name, size_t param_count = 0,
-                            const RuntimeScriptValue &p1 = RuntimeScriptValue(), const RuntimeScriptValue &p2 = RuntimeScriptValue());
+	const RuntimeScriptValue &p1 = RuntimeScriptValue(), const RuntimeScriptValue &p2 = RuntimeScriptValue());
 // Try to run a script function right away
 void    RunScriptFunction(ScriptInstType sc_inst, const char *fn_name, size_t param_count = 0,
-                          const RuntimeScriptValue &p1 = RuntimeScriptValue(), const RuntimeScriptValue &p2 = RuntimeScriptValue());
+	const RuntimeScriptValue &p1 = RuntimeScriptValue(), const RuntimeScriptValue &p2 = RuntimeScriptValue());
 
 int     RunScriptFunctionIfExists(ccInstance *sci, const char *tsname, int numParam, const RuntimeScriptValue *params);
 int     RunTextScript(ccInstance *sci, const char *tsname);
@@ -69,7 +71,7 @@ AGS::Common::String GetScriptName(ccInstance *sci);
 
 //=============================================================================
 
-char   *make_ts_func_name(const char *base, int iii, int subd);
+char *make_ts_func_name(const char *base, int iii, int subd);
 // Performs various updates to the game after script interpreter returns control to the engine.
 // Executes actions and does changes that are not executed immediately at script command, for
 // optimisation and other reasons.
@@ -121,4 +123,6 @@ extern std::vector<AGS::Common::String> characterScriptObjNames;
 extern AGS::Common::String objectScriptObjNames[MAX_ROOM_OBJECTS];
 extern std::vector<AGS::Common::String> guiScriptObjNames;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/script/script_api.h b/engines/ags/engine/script/script_api.h
index 73eca53983..04506a14af 100644
--- a/engines/ags/engine/script/script_api.h
+++ b/engines/ags/engine/script/script_api.h
@@ -36,6 +36,8 @@
 #include "ac/statobj/agsstaticobject.h"
 #include "debug/out.h"
 
+namespace AGS3 {
+
 struct RuntimeScriptValue;
 
 // TODO: replace void* with base object class when possible; also put array class for parameters
@@ -46,7 +48,7 @@ typedef RuntimeScriptValue ScriptAPIObjectFunction(void *self, const RuntimeScri
 // Uses EITHER sc_args/sc_argc or varg_ptr as parameter list, whichever is not
 // NULL, with varg_ptr having HIGHER priority.
 const char *ScriptSprintf(char *buffer, size_t buf_length, const char *format,
-                          const RuntimeScriptValue *sc_args, int32_t sc_argc, va_list *varg_ptr);
+	const RuntimeScriptValue *sc_args, int32_t sc_argc, va_list *varg_ptr);
 // Sprintf that takes script values as arguments
 inline const char *ScriptSprintf(char *buffer, size_t buf_length, const char *format, const RuntimeScriptValue *args, int32_t argc) {
 	return ScriptSprintf(buffer, buf_length, format, args, argc, nullptr);
@@ -556,4 +558,6 @@ inline const char *ScriptVSprintf(char *buffer, size_t buf_length, const char *f
 	RET_CLASS* ret_obj = METHOD((CLASS*)self, (P1CLASS*)params[0].Ptr); \
 	return RuntimeScriptValue().SetDynamicObject(ret_obj, ret_obj)
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/script/script_runtime.h b/engines/ags/engine/script/script_runtime.h
index 5318859002..31e99850a4 100644
--- a/engines/ags/engine/script/script_runtime.h
+++ b/engines/ags/engine/script/script_runtime.h
@@ -40,6 +40,8 @@
 #include "script/cc_script.h"      // ccScript
 #include "script/cc_instance.h"    // ccInstance
 
+namespace AGS3 {
+
 struct ICCStaticObject;
 struct ICCDynamicObject;
 struct StaticArray;
@@ -83,4 +85,6 @@ extern void ccNotifyScriptStillAlive();
 extern int call_function(intptr_t addr, const RuntimeScriptValue *object, int numparm, const RuntimeScriptValue *parms);
 extern void nullfree(void *data); // in script/script_runtime
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/script/systemimports.h b/engines/ags/engine/script/systemimports.h
index ba715d7e4b..ab3c717ddb 100644
--- a/engines/ags/engine/script/systemimports.h
+++ b/engines/ags/engine/script/systemimports.h
@@ -26,6 +26,8 @@
 #include <map>
 #include "script/cc_instance.h"    // ccInstance
 
+namespace AGS3 {
+
 struct ICCDynamicObject;
 struct ICCStaticObject;
 
@@ -38,7 +40,7 @@ struct ScriptImport {
 
 	String              Name;           // import's uid
 	RuntimeScriptValue  Value;
-	ccInstance          *InstancePtr;   // script instance
+	ccInstance *InstancePtr;   // script instance
 };
 
 struct SystemImports {
@@ -65,4 +67,6 @@ extern SystemImports simp;
 // perform old style unsafe function calls
 extern SystemImports simp_for_plugin;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/util/library.h b/engines/ags/engine/util/library.h
index a818248bdb..8c726c5571 100644
--- a/engines/ags/engine/util/library.h
+++ b/engines/ags/engine/util/library.h
@@ -26,6 +26,7 @@
 #include "core/platform.h"
 #include "util/string.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
@@ -47,7 +48,7 @@ public:
 
 } // namespace Engine
 } // namespace AGS
-
+} // namespace AGS3
 
 #if AGS_PLATFORM_OS_WINDOWS
 #include "library_windows.h"
diff --git a/engines/ags/engine/util/library_dummy.h b/engines/ags/engine/util/library_dummy.h
index c9ee518e45..732c474e65 100644
--- a/engines/ags/engine/util/library_dummy.h
+++ b/engines/ags/engine/util/library_dummy.h
@@ -23,10 +23,10 @@
 #ifndef AGS_ENGINE_UTIL_LIBRARY_DUMMY_H
 #define AGS_ENGINE_UTIL_LIBRARY_DUMMY_H
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
-
 class DummyLibrary : BaseLibrary {
 public:
 	DummyLibrary() {
@@ -52,12 +52,10 @@ public:
 	}
 };
 
-
 typedef DummyLibrary Library;
 
-
-
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/util/library_posix.h b/engines/ags/engine/util/library_posix.h
index a9eb850195..89e8e4e1ce 100644
--- a/engines/ags/engine/util/library_posix.h
+++ b/engines/ags/engine/util/library_posix.h
@@ -28,6 +28,8 @@
 #include "util/string.h"
 #include "debug/out.h"
 
+namespace AGS3 {
+
 // FIXME: Replace with a unified way to get the directory which contains the engine binary
 #if AGS_PLATFORM_OS_ANDROID
 extern char android_app_directory[256];
@@ -53,11 +55,11 @@ public:
 	AGS::Common::String BuildFilename(AGS::Common::String libraryName) {
 		return String::FromFormat(
 #if AGS_PLATFORM_OS_MACOS
-		           "lib%s.dylib"
+			"lib%s.dylib"
 #else
-		           "lib%s.so"
+			"lib%s.so"
 #endif
-		           , libraryName.GetCStr());
+			, libraryName.GetCStr());
 	}
 
 	AGS::Common::String BuildPath(const char *path, AGS::Common::String libraryName) {
@@ -131,9 +133,8 @@ private:
 
 typedef PosixLibrary Library;
 
-
-
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/util/library_psp.h b/engines/ags/engine/util/library_psp.h
index 8e5e064042..7d40b01d1d 100644
--- a/engines/ags/engine/util/library_psp.h
+++ b/engines/ags/engine/util/library_psp.h
@@ -27,6 +27,7 @@
 #include "util/string.h"
 #include "debug/out.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
@@ -128,5 +129,6 @@ typedef PSPLibrary Library;
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/util/library_windows.h b/engines/ags/engine/util/library_windows.h
index f439f03828..64882535e9 100644
--- a/engines/ags/engine/util/library_windows.h
+++ b/engines/ags/engine/util/library_windows.h
@@ -27,15 +27,17 @@
 #include "platform/windows/winapi_exclusive.h"
 #include "util/string.h"
 
+namespace AGS3 {
+
 // Because this class may be exposed to generic code in sake of inlining,
 // we should avoid including <windows.h> full of macros with common names.
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-WINBASEAPI BOOL WINAPI FreeLibrary(HMODULE hLibModule);
-WINBASEAPI FARPROC WINAPI GetProcAddress(HMODULE hModule, LPCSTR lpProcName);
-WINBASEAPI HMODULE WINAPI LoadLibraryA(LPCSTR lpLibFileName);
+	WINBASEAPI BOOL WINAPI FreeLibrary(HMODULE hLibModule);
+	WINBASEAPI FARPROC WINAPI GetProcAddress(HMODULE hModule, LPCSTR lpProcName);
+	WINBASEAPI HMODULE WINAPI LoadLibraryA(LPCSTR lpLibFileName);
 
 #ifdef __cplusplus
 } // extern "C"
@@ -99,9 +101,8 @@ private:
 
 typedef WindowsLibrary Library;
 
-
-
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/util/mutex.h b/engines/ags/engine/util/mutex.h
index ea398db9be..e525343638 100644
--- a/engines/ags/engine/util/mutex.h
+++ b/engines/ags/engine/util/mutex.h
@@ -26,6 +26,7 @@
 namespace AGS {
 namespace Engine {
 
+namespace AGS3 {
 
 class BaseMutex {
 public:
@@ -44,7 +45,7 @@ public:
 
 } // namespace Engine
 } // namespace AGS
-
+} // namespace AGS3
 
 #if 0
 // insert platforms here
diff --git a/engines/ags/engine/util/mutex_base.h b/engines/ags/engine/util/mutex_base.h
index 5a0debc9e7..2344dd006d 100644
--- a/engines/ags/engine/util/mutex_base.h
+++ b/engines/ags/engine/util/mutex_base.h
@@ -23,10 +23,10 @@
 #ifndef AGS_ENGINE_UTIL_MUTEX_BASE_H
 #define AGS_ENGINE_UTIL_MUTEX_BASE_H
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
-
 class BaseMutex {
 public:
 	BaseMutex() = 0;
@@ -35,8 +35,8 @@ public:
 	virtual void Unlock() = 0;
 };
 
-
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/util/mutex_lock.h b/engines/ags/engine/util/mutex_lock.h
index 6a4524499b..c772fdb9a5 100644
--- a/engines/ags/engine/util/mutex_lock.h
+++ b/engines/ags/engine/util/mutex_lock.h
@@ -25,10 +25,10 @@
 
 #include "util/mutex.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
-
 class MutexLock {
 private:
 	BaseMutex *_m;
@@ -59,8 +59,8 @@ public:
 	}
 }; // class MutexLock
 
-
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/util/mutex_psp.h b/engines/ags/engine/util/mutex_psp.h
index 83511ee9c3..15cb079d2e 100644
--- a/engines/ags/engine/util/mutex_psp.h
+++ b/engines/ags/engine/util/mutex_psp.h
@@ -27,10 +27,10 @@
 #include <pspkernel.h>
 #include <pspthreadman.h>
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
-
 class PSPMutex : public BaseMutex {
 public:
 	PSPMutex() {
@@ -53,11 +53,10 @@ private:
 	SceUID _mutex;
 };
 
-
 typedef PSPMutex Mutex;
 
-
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/util/mutex_pthread.h b/engines/ags/engine/util/mutex_pthread.h
index ae81f9e671..53efb21759 100644
--- a/engines/ags/engine/util/mutex_pthread.h
+++ b/engines/ags/engine/util/mutex_pthread.h
@@ -25,10 +25,10 @@
 
 #include <pthread.h>
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
-
 class PThreadMutex : public BaseMutex {
 public:
 	inline PThreadMutex() {
@@ -53,8 +53,8 @@ private:
 
 typedef PThreadMutex Mutex;
 
-
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/util/mutex_std.h b/engines/ags/engine/util/mutex_std.h
index 0565db6579..abe1f8f2c3 100644
--- a/engines/ags/engine/util/mutex_std.h
+++ b/engines/ags/engine/util/mutex_std.h
@@ -25,12 +25,14 @@
 
 #include <mutex>
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
 class StdMutex : public BaseMutex {
 public:
-	inline StdMutex() : mutex_() {}
+	inline StdMutex() : mutex_() {
+	}
 	inline ~StdMutex() override = default;
 
 	StdMutex &operator=(const StdMutex &) = delete;
@@ -51,5 +53,6 @@ typedef StdMutex Mutex;
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/util/mutex_wii.h b/engines/ags/engine/util/mutex_wii.h
index 45b935e8a2..1930a32c3c 100644
--- a/engines/ags/engine/util/mutex_wii.h
+++ b/engines/ags/engine/util/mutex_wii.h
@@ -25,10 +25,10 @@
 
 #include <gccore.h>
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
-
 class WiiMutex : public BaseMutex {
 public:
 	inline WiiMutex() {
@@ -51,11 +51,10 @@ private:
 	mutex_t _mutex;
 };
 
-
 typedef WiiMutex Mutex;
 
-
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/util/mutex_windows.h b/engines/ags/engine/util/mutex_windows.h
index 0e27e000bd..7f697a702b 100644
--- a/engines/ags/engine/util/mutex_windows.h
+++ b/engines/ags/engine/util/mutex_windows.h
@@ -23,10 +23,10 @@
 #ifndef AGS_ENGINE_UTIL_MUTEXT_WINDOWS_H
 #define AGS_ENGINE_UTIL_MUTEXT_WINDOWS_H
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
-
 class WindowsMutex : public BaseMutex {
 public:
 	WindowsMutex() {
@@ -57,11 +57,10 @@ private:
 	HANDLE _mutex;
 };
 
-
 typedef WindowsMutex Mutex;
 
-
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/util/scaling.h b/engines/ags/engine/util/scaling.h
index 98881e7b68..b0f980b14d 100644
--- a/engines/ags/engine/util/scaling.h
+++ b/engines/ags/engine/util/scaling.h
@@ -35,6 +35,7 @@
 #include "core/types.h"
 #include "util/geometry.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
@@ -156,5 +157,6 @@ struct PlaneScaling {
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/util/thread.h b/engines/ags/engine/util/thread.h
index 482d3de985..b69a8b7139 100644
--- a/engines/ags/engine/util/thread.h
+++ b/engines/ags/engine/util/thread.h
@@ -23,13 +23,13 @@
 #ifndef AGS_ENGINE_UTIL_THREAD_H
 #define AGS_ENGINE_UTIL_THREAD_H
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
-
 class BaseThread {
 public:
-	typedef void(* AGSThreadEntry)();
+	typedef void(*AGSThreadEntry)();
 
 	BaseThread() = default;
 	virtual ~BaseThread() = default;
@@ -51,6 +51,7 @@ public:
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #if 0
 // insert platforms here
diff --git a/engines/ags/engine/util/thread_psp.h b/engines/ags/engine/util/thread_psp.h
index eab3e5df01..6785275b10 100644
--- a/engines/ags/engine/util/thread_psp.h
+++ b/engines/ags/engine/util/thread_psp.h
@@ -27,10 +27,10 @@
 #include <pspkernel.h>
 #include <pspthreadman.h>
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
-
 class PSPThread : public BaseThread {
 public:
 	PSPThread() {
@@ -98,8 +98,8 @@ private:
 
 typedef PSPThread Thread;
 
-
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/util/thread_pthread.h b/engines/ags/engine/util/thread_pthread.h
index 89e9180f8c..83108f5c6e 100644
--- a/engines/ags/engine/util/thread_pthread.h
+++ b/engines/ags/engine/util/thread_pthread.h
@@ -25,10 +25,10 @@
 
 #include <pthread.h>
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
-
 class PThreadThread : public BaseThread {
 public:
 	PThreadThread() {
@@ -97,8 +97,8 @@ private:
 
 typedef PThreadThread Thread;
 
-
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/util/thread_std.h b/engines/ags/engine/util/thread_std.h
index 24b870b28b..1dcc7432f9 100644
--- a/engines/ags/engine/util/thread_std.h
+++ b/engines/ags/engine/util/thread_std.h
@@ -26,6 +26,7 @@
 #include <system_error>
 #include <thread>
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
@@ -98,5 +99,6 @@ typedef StdThread Thread;
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/util/thread_wii.h b/engines/ags/engine/util/thread_wii.h
index 91a67ef8a4..5b61d5dec9 100644
--- a/engines/ags/engine/util/thread_wii.h
+++ b/engines/ags/engine/util/thread_wii.h
@@ -25,10 +25,10 @@
 
 #include <gccore.h>
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
-
 class WiiThread : public BaseThread {
 public:
 	WiiThread() {
@@ -100,5 +100,6 @@ typedef WiiThread Thread;
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/util/thread_windows.h b/engines/ags/engine/util/thread_windows.h
index e55b243aa3..77e3622b46 100644
--- a/engines/ags/engine/util/thread_windows.h
+++ b/engines/ags/engine/util/thread_windows.h
@@ -23,10 +23,10 @@
 #ifndef AGS_ENGINE_UTIL_THREAD_WINDOWS_H
 #define AGS_ENGINE_UTIL_THREAD_WINDOWS_H
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
-
 class WindowsThread : public BaseThread {
 public:
 	WindowsThread() {
@@ -52,7 +52,7 @@ public:
 		if ((_thread != NULL) && (!_running)) {
 			DWORD result = ResumeThread(_thread);
 
-			_running = (result != (DWORD) - 1);
+			_running = (result != (DWORD)-1);
 			return _running;
 		} else {
 			return false;
@@ -95,11 +95,10 @@ private:
 	}
 };
 
-
 typedef WindowsThread Thread;
 
-
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/ac/audiocliptype.h b/engines/ags/shared/ac/audiocliptype.h
index 8b36ad01dd..9123a56c72 100644
--- a/engines/ags/shared/ac/audiocliptype.h
+++ b/engines/ags/shared/ac/audiocliptype.h
@@ -23,12 +23,15 @@
 #ifndef AGS_SHARED_AC_AUDIOCLIPTYPE_H
 #define AGS_SHARED_AC_AUDIOCLIPTYPE_H
 
+namespace AGS3 {
+
 // Forward declaration
 namespace AGS {
 namespace Common {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 #define AUDIO_CLIP_TYPE_SOUND 1
@@ -45,4 +48,6 @@ struct AudioClipType {
 	void WriteToSavegame(Common::Stream *out) const;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/ac/characterinfo.h b/engines/ags/shared/ac/characterinfo.h
index 4f3cad6ebf..2649887f85 100644
--- a/engines/ags/shared/ac/characterinfo.h
+++ b/engines/ags/shared/ac/characterinfo.h
@@ -25,11 +25,14 @@
 
 #include "ac/common_defines.h" // constants
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Common {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 #define MAX_INV             301
@@ -157,4 +160,6 @@ struct OldCharacterInfo {
 #define COPY_CHAR_VAR(name) ci->name = oci->name
 void ConvertOldCharacterToNew(OldCharacterInfo *oci, CharacterInfo *ci);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/ac/common.h b/engines/ags/shared/ac/common.h
index 2d857485f6..03ef906265 100644
--- a/engines/ags/shared/ac/common.h
+++ b/engines/ags/shared/ac/common.h
@@ -23,6 +23,8 @@
 #ifndef AGS_SHARED_AC_COMMON_H
 #define AGS_SHARED_AC_COMMON_H
 
+namespace AGS3 {
+
 // These are the project-dependent functions, they are defined both in Engine.App and AGS.Native.
 void quit(const char *);
 void quitprintf(const char *fmt, ...);
@@ -32,4 +34,6 @@ int  get_our_eip();
 
 extern const char *game_file_sig;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/ac/common_defines.h b/engines/ags/shared/ac/common_defines.h
index c7b658005e..0311a452fe 100644
--- a/engines/ags/shared/ac/common_defines.h
+++ b/engines/ags/shared/ac/common_defines.h
@@ -25,6 +25,8 @@
 
 #include "core/platform.h"
 
+namespace AGS3 {
+
 #define EXIT_NORMAL 0
 #define EXIT_CRASH  92
 #define EXIT_ERROR  93
@@ -128,4 +130,6 @@
 #define OBJF_LEGACY_LOCKED  0x40  // object position is locked in the editor (OBSOLETE since 3.5.0)
 #define OBJF_HASLIGHT       0x80  // the tint_light is valid and treated as brightness
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/ac/dialogtopic.h b/engines/ags/shared/ac/dialogtopic.h
index dbffaf2a0b..87502041be 100644
--- a/engines/ags/shared/ac/dialogtopic.h
+++ b/engines/ags/shared/ac/dialogtopic.h
@@ -23,11 +23,14 @@
 #ifndef AGS_SHARED_AC_DIALOGTOPIC_H
 #define AGS_SHARED_AC_DIALOGTOPIC_H
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Common {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 // [IKM] This is *conversation* dialog, not *gui* dialog, mind you!
@@ -73,5 +76,6 @@ struct DialogTopic {
 	void WriteToSavegame(Common::Stream *out) const;
 };
 
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/ac/dynobj/scriptaudioclip.h b/engines/ags/shared/ac/dynobj/scriptaudioclip.h
index c8e18fa502..be246866fa 100644
--- a/engines/ags/shared/ac/dynobj/scriptaudioclip.h
+++ b/engines/ags/shared/ac/dynobj/scriptaudioclip.h
@@ -25,11 +25,14 @@
 
 #include "util/string.h"
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Common {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 enum AudioFileType {
@@ -60,4 +63,6 @@ struct ScriptAudioClip {
 	void ReadFromFile(Common::Stream *in);
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/ac/game_version.h b/engines/ags/shared/ac/game_version.h
index 9a11424b56..0a0cbca5fd 100644
--- a/engines/ags/shared/ac/game_version.h
+++ b/engines/ags/shared/ac/game_version.h
@@ -29,6 +29,8 @@
 #ifndef AGS_SHARED_AC_GAMEVERSION_H
 #define AGS_SHARED_AC_GAMEVERSION_H
 
+namespace AGS3 {
+
 /*
 
 Game data versions and changes:
@@ -152,4 +154,6 @@ enum GameDataVersion {
 
 extern GameDataVersion loaded_game_file_version;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/ac/gamesetupstruct.h b/engines/ags/shared/ac/gamesetupstruct.h
index 43d6896022..21e252c3b4 100644
--- a/engines/ags/shared/ac/gamesetupstruct.h
+++ b/engines/ags/shared/ac/gamesetupstruct.h
@@ -33,6 +33,8 @@
 #include "game/customproperties.h"
 #include "game/main_game_file.h" // TODO: constants to separate header or split out reading functions
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Common {
 struct AssetLibInfo;
@@ -40,8 +42,8 @@ struct Interaction;
 struct InteractionScripts;
 typedef std::shared_ptr<Interaction> PInteraction;
 typedef std::shared_ptr<InteractionScripts> PInteractionScripts;
-}
-}
+} // namespace Shared
+} // namespace AGS
 
 using AGS::Common::PInteraction;
 using AGS::Common::PInteractionScripts;
@@ -50,7 +52,7 @@ struct OldGameSetupStruct;
 
 
 // TODO: split GameSetupStruct into struct used to hold loaded game data, and actual runtime object
-struct GameSetupStruct: public GameSetupStructBase {
+struct GameSetupStruct : public GameSetupStructBase {
 	// This array is used only to read data into;
 	// font parameters are then put and queried in the fonts module
 	// TODO: split into installation params (used only when reading) and runtime params
@@ -79,8 +81,8 @@ struct GameSetupStruct: public GameSetupStructBase {
 	char              saveGameFileExtension[MAX_SG_EXT_LENGTH];
 	char              saveGameFolderName[MAX_SG_FOLDER_LEN];
 	int               roomCount;
-	int              *roomNumbers;
-	char            **roomNames;
+	int *roomNumbers;
+	char **roomNames;
 	std::vector<ScriptAudioClip> audioClips;
 	std::vector<AudioClipType> audioClipTypes;
 	// A clip to play when player gains score in game
@@ -155,7 +157,7 @@ struct GameSetupStruct: public GameSetupStructBase {
 
 	// Functions for reading and writing appropriate data from/to save game
 	void ReadFromSaveGame_v321(Common::Stream *in, char *gswas, ccScript *compsc, CharacterInfo *chwas,
-	                           WordsDictionary *olddict, char **mesbk);
+		WordsDictionary *olddict, char **mesbk);
 
 	void ReadFromSavegame(Common::PStream in);
 	void WriteForSavegame(Common::PStream out);
@@ -167,4 +169,6 @@ void ConvertOldGameStruct(OldGameSetupStruct *ogss, GameSetupStruct *gss);
 // Finds an audio clip using legacy convention index
 ScriptAudioClip *GetAudioClipForOldStyleNumber(GameSetupStruct &game, bool is_music, int num);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/ac/gamesetupstructbase.h b/engines/ags/shared/ac/gamesetupstructbase.h
index 70b0818ad3..7edfbbad01 100644
--- a/engines/ags/shared/ac/gamesetupstructbase.h
+++ b/engines/ags/shared/ac/gamesetupstructbase.h
@@ -28,12 +28,15 @@
 #include "util/string.h"
 #include "util/wgt2allg.h" // color (allegro RGB)
 
+namespace AGS3 {
+
 // Forward declaration
 namespace AGS {
 namespace Common {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 struct WordsDictionary;
@@ -244,4 +247,6 @@ private:
 	int _screenUpscaleMult;
 };
 
+// namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/ac/gamestructdefines.h b/engines/ags/shared/ac/gamestructdefines.h
index 705c3bf37a..e865bc296b 100644
--- a/engines/ags/shared/ac/gamestructdefines.h
+++ b/engines/ags/shared/ac/gamestructdefines.h
@@ -26,6 +26,8 @@
 #include "util/geometry.h"
 #include "core/types.h"
 
+namespace AGS3 {
+
 #define PAL_GAMEWIDE        0
 #define PAL_LOCKED          1
 #define PAL_BACKGROUND      2
@@ -117,21 +119,21 @@
 #define MAX_SG_FOLDER_LEN 50
 
 enum GameResolutionType {
-	kGameResolution_Undefined   = -1,
+	kGameResolution_Undefined = -1,
 	// definition of 320x200 in very old versions of the engine (somewhere pre-2.56)
-	kGameResolution_Default     = 0,
-	kGameResolution_320x200     = 1,
-	kGameResolution_320x240     = 2,
-	kGameResolution_640x400     = 3,
-	kGameResolution_640x480     = 4,
-	kGameResolution_800x600     = 5,
-	kGameResolution_1024x768    = 6,
-	kGameResolution_1280x720    = 7,
-	kGameResolution_Custom      = 8,
+	kGameResolution_Default = 0,
+	kGameResolution_320x200 = 1,
+	kGameResolution_320x240 = 2,
+	kGameResolution_640x400 = 3,
+	kGameResolution_640x480 = 4,
+	kGameResolution_800x600 = 5,
+	kGameResolution_1024x768 = 6,
+	kGameResolution_1280x720 = 7,
+	kGameResolution_Custom = 8,
 	kNumGameResolutions,
 
-	kGameResolution_LastLoRes   = kGameResolution_320x240,
-	kGameResolution_FirstHiRes  = kGameResolution_640x400
+	kGameResolution_LastLoRes = kGameResolution_320x240,
+	kGameResolution_FirstHiRes = kGameResolution_640x400
 };
 
 inline bool IsLegacyHiRes(GameResolutionType resolution) {
@@ -143,8 +145,8 @@ Size ResolutionTypeToSize(GameResolutionType resolution, bool letterbox = false)
 // Automatic numbering of dialog options (OPT_DIALOGNUMBERED)
 enum DialogOptionNumbering {
 	kDlgOptNoNumbering = -1,
-	kDlgOptKeysOnly    =  0, // implicit key shortcuts
-	kDlgOptNumbering   =  1  // draw option indices and use key shortcuts
+	kDlgOptKeysOnly = 0, // implicit key shortcuts
+	kDlgOptNumbering = 1  // draw option indices and use key shortcuts
 };
 
 // Version of the script api (OPT_BASESCRIPTAPI and OPT_SCRIPTCOMPATLEV).
@@ -170,9 +172,9 @@ enum ScriptAPIVersion {
 // Determines whether the graphics renderer should scale sprites at the final
 // screen resolution, as opposed to native resolution
 enum RenderAtScreenRes {
-	kRenderAtScreenRes_UserDefined  = 0,
-	kRenderAtScreenRes_Enabled      = 1,
-	kRenderAtScreenRes_Disabled     = 2,
+	kRenderAtScreenRes_UserDefined = 0,
+	kRenderAtScreenRes_Enabled = 1,
+	kRenderAtScreenRes_Disabled = 2,
 };
 
 // Method to use when blending two sprites with alpha channel
@@ -252,4 +254,6 @@ struct FontInfo {
 	FontInfo();
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/ac/interfacebutton.h b/engines/ags/shared/ac/interfacebutton.h
index 3918b8e172..ab599b5912 100644
--- a/engines/ags/shared/ac/interfacebutton.h
+++ b/engines/ags/shared/ac/interfacebutton.h
@@ -23,6 +23,8 @@
 #ifndef AGS_SHARED_AC_INTERFACEBUTTON_H
 #define AGS_SHARED_AC_INTERFACEBUTTON_H
 
+namespace AGS3 {
+
 #define MAXBUTTON       20
 #define IBFLG_ENABLED   1
 #define IBFLG_INVBOX    2
@@ -34,4 +36,6 @@ struct InterfaceButton {
 	void set(int xx, int yy, int picc, int overpicc, int actionn);
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/ac/interfaceelement.h b/engines/ags/shared/ac/interfaceelement.h
index a81a9d6562..1b897de03a 100644
--- a/engines/ags/shared/ac/interfaceelement.h
+++ b/engines/ags/shared/ac/interfaceelement.h
@@ -25,6 +25,8 @@
 
 #include "ac/interfacebutton.h" // InterfaceButton
 
+namespace AGS3 {
+
 // this struct should go in a Game struct, not the room structure.
 struct InterfaceElement {
 	int             x, y, x2, y2;
@@ -56,4 +58,6 @@ button[0].set(0,13,3,-1,0);
 }
 };*/
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/ac/inventoryiteminfo.h b/engines/ags/shared/ac/inventoryiteminfo.h
index dce76e5c10..29adfffaff 100644
--- a/engines/ags/shared/ac/inventoryiteminfo.h
+++ b/engines/ags/shared/ac/inventoryiteminfo.h
@@ -23,11 +23,14 @@
 #ifndef AGS_SHARED_AC_INVENTORYITEMINFO_H
 #define AGS_SHARED_AC_INVENTORYITEMINFO_H
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Common {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 #define IFLG_STARTWITH 1
@@ -44,4 +47,6 @@ struct InventoryItemInfo {
 	void WriteToSavegame(Common::Stream *out) const;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/ac/mousecursor.h b/engines/ags/shared/ac/mousecursor.h
index 72484896ff..2ebaebe9ca 100644
--- a/engines/ags/shared/ac/mousecursor.h
+++ b/engines/ags/shared/ac/mousecursor.h
@@ -23,11 +23,14 @@
 #ifndef AGS_SHARED_AC_MOUSECURSOR_H
 #define AGS_SHARED_AC_MOUSECURSOR_H
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Common {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 #define MCF_ANIMMOVE 1
@@ -49,4 +52,6 @@ struct MouseCursor {
 	void WriteToSavegame(Common::Stream *out) const;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/ac/oldgamesetupstruct.h b/engines/ags/shared/ac/oldgamesetupstruct.h
index ee9f24b291..1ceb6b25c9 100644
--- a/engines/ags/shared/ac/oldgamesetupstruct.h
+++ b/engines/ags/shared/ac/oldgamesetupstruct.h
@@ -33,6 +33,8 @@
 #include "ac/wordsdictionary.h"  // WordsDictionary
 #include "script/cc_script.h"           // ccScript
 
+namespace AGS3 {
+
 struct OriGameSetupStruct {
 	char              gamename[30];
 	char              options[20];
@@ -42,14 +44,14 @@ struct OriGameSetupStruct {
 	int               numiface;
 	int               numviews;
 	MouseCursor       mcurs[10];
-	char              *globalscript;
+	char *globalscript;
 	int               numcharacters;
-	OldCharacterInfo     *chars;
+	OldCharacterInfo *chars;
 #ifdef UNUSED_CODE
 	EventBlock        __charcond[50];   // [IKM] 2012-06-22: does not seem to be used anywhere
 	EventBlock        __invcond[100];   // same
 #endif
-	ccScript          *compiled_script;
+	ccScript *compiled_script;
 	int               playercharacter;
 	unsigned char     __old_spriteflags[2100];
 	int               totalscore;
@@ -65,7 +67,7 @@ struct OriGameSetupStruct {
 	int               reserved[2];
 	short             numlang;
 	char              langcodes[MAXLANGUAGE][3];
-	char              *messages[MAXGLOBALMES];
+	char *messages[MAXGLOBALMES];
 };
 
 struct OriGameSetupStruct2 : public OriGameSetupStruct {
@@ -80,4 +82,6 @@ struct OldGameSetupStruct : public OriGameSetupStruct2 {
 	unsigned char spriteflags[LEGACY_MAX_SPRITES_V25];
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/ac/spritecache.h b/engines/ags/shared/ac/spritecache.h
index 1f11d9e70e..2d8a5a5eaa 100644
--- a/engines/ags/shared/ac/spritecache.h
+++ b/engines/ags/shared/ac/spritecache.h
@@ -50,12 +50,15 @@
 #include "core/platform.h"
 #include "util/error.h"
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Common {
 class Stream;
 class Bitmap;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 typedef AGS::Common::HError HAGSError;
 
@@ -247,4 +250,6 @@ private:
 
 extern SpriteCache spriteset;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/ac/view.h b/engines/ags/shared/ac/view.h
index 824c3c8cde..3fa144444d 100644
--- a/engines/ags/shared/ac/view.h
+++ b/engines/ags/shared/ac/view.h
@@ -25,11 +25,14 @@
 
 #include <vector>
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Common {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 #define VFLG_FLIPSPRITE 1
@@ -87,4 +90,6 @@ struct ViewStruct272 {
 
 void Convert272ViewsToNew(const std::vector<ViewStruct272> &oldv, ViewStruct *newv);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/ac/wordsdictionary.h b/engines/ags/shared/ac/wordsdictionary.h
index 8acf1250f3..ea2fe99908 100644
--- a/engines/ags/shared/ac/wordsdictionary.h
+++ b/engines/ags/shared/ac/wordsdictionary.h
@@ -25,11 +25,14 @@
 
 #include "core/types.h"
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Common {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 #define MAX_PARSER_WORD_LENGTH 30
@@ -64,4 +67,6 @@ extern void encrypt_text(char *toenc);
 extern void write_string_encrypt(Common::Stream *out, const char *s);
 extern void write_dictionary(WordsDictionary *dict, Common::Stream *out);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/api/stream_api.h b/engines/ags/shared/api/stream_api.h
index b0b03dc2f3..738765a513 100644
--- a/engines/ags/shared/api/stream_api.h
+++ b/engines/ags/shared/api/stream_api.h
@@ -38,6 +38,7 @@
 // plugins, and let plugin developers include them manually in plugin sources.
 #include "core/types.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -93,5 +94,6 @@ public:
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/core/asset.h b/engines/ags/shared/core/asset.h
index c5601a266c..0a8f7c4c2c 100644
--- a/engines/ags/shared/core/asset.h
+++ b/engines/ags/shared/core/asset.h
@@ -32,6 +32,7 @@
 #include <vector>
 #include "util/string.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -62,5 +63,6 @@ struct AssetLibInfo {
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/core/assetmanager.h b/engines/ags/shared/core/assetmanager.h
index 70b1c4c596..d2937b661b 100644
--- a/engines/ags/shared/core/assetmanager.h
+++ b/engines/ags/shared/core/assetmanager.h
@@ -46,6 +46,7 @@
 
 #include "util/file.h" // TODO: extract filestream mode constants or introduce generic ones
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -62,10 +63,10 @@ enum AssetSearchPriority {
 };
 
 enum AssetError {
-	kAssetNoError           =  0,
-	kAssetErrNoLibFile      = -1, // library file not found or can't be read
-	kAssetErrLibParse       = -2, // bad library file format or read error
-	kAssetErrNoManager      = -6, // asset manager not initialized
+	kAssetNoError = 0,
+	kAssetErrNoLibFile = -1, // library file not found or can't be read
+	kAssetErrLibParse = -2, // bad library file format or read error
+	kAssetErrNoManager = -6, // asset manager not initialized
 };
 
 // Explicit location of asset data
@@ -111,9 +112,9 @@ public:
 	static bool         GetAssetLocation(const String &asset_name, AssetLocation &loc);
 
 	static bool         DoesAssetExist(const String &asset_name);
-	static Stream       *OpenAsset(const String &asset_name,
-	                               FileOpenMode open_mode = kFile_Open,
-	                               FileWorkMode work_mode = kFile_Read);
+	static Stream *OpenAsset(const String &asset_name,
+		FileOpenMode open_mode = kFile_Open,
+		FileWorkMode work_mode = kFile_Read);
 
 private:
 	AssetManager();
@@ -134,18 +135,18 @@ private:
 
 	bool        _DoesAssetExist(const String &asset_name);
 
-	AssetInfo   *FindAssetByFileName(const String &asset_name);
+	AssetInfo *FindAssetByFileName(const String &asset_name);
 	String      MakeLibraryFileNameForAsset(const AssetInfo *asset);
 
 	bool        GetAssetFromLib(const String &asset_name, AssetLocation &loc, Common::FileOpenMode open_mode, Common::FileWorkMode work_mode);
 	bool        GetAssetFromDir(const String &asset_name, AssetLocation &loc, Common::FileOpenMode open_mode, Common::FileWorkMode work_mode);
 	bool        GetAssetByPriority(const String &asset_name, AssetLocation &loc, Common::FileOpenMode open_mode, Common::FileWorkMode work_mode);
-	Stream      *OpenAssetAsStream(const String &asset_name, FileOpenMode open_mode, FileWorkMode work_mode);
+	Stream *OpenAssetAsStream(const String &asset_name, FileOpenMode open_mode, FileWorkMode work_mode);
 
-	static AssetManager     *_theAssetManager;
+	static AssetManager *_theAssetManager;
 	AssetSearchPriority     _searchPriority;
 
-	AssetLibInfo            &_assetLib;
+	AssetLibInfo &_assetLib;
 	String                  _basePath;          // library's parent path (directory)
 	soff_t                  _lastAssetSize;     // size of asset that was opened last time
 };
@@ -155,5 +156,6 @@ String GetAssetErrorText(AssetError err);
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/core/platform.h b/engines/ags/shared/core/platform.h
index c97ba949cd..40d7cc1754 100644
--- a/engines/ags/shared/core/platform.h
+++ b/engines/ags/shared/core/platform.h
@@ -23,6 +23,8 @@
 #ifndef AGS_SHARED_CORE_PLATFORM_H
 #define AGS_SHARED_CORE_PLATFORM_H
 
+namespace AGS3 {
+
 // platform definitions. Not intended for replacing types or checking for libraries.
 
 // check Android first because sometimes it can get confused with host OS
@@ -124,4 +126,6 @@
 #define AGS_PLATFORM_DEBUG  (0)
 #endif
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/core/types.h b/engines/ags/shared/core/types.h
index 90cf583270..c7d0484462 100644
--- a/engines/ags/shared/core/types.h
+++ b/engines/ags/shared/core/types.h
@@ -34,6 +34,8 @@
 #include <stdlib.h> // for size_t
 #include <limits.h> // for _WORDSIZE
 
+namespace AGS3 {
+
 #ifndef NULL
 #define NULL nullptr
 #endif
@@ -64,8 +66,10 @@ typedef int64_t soff_t;
 
 // TODO: use distinct fixed point class
 enum {
-	kShift    = 16,
-	kUnit     = 1 << kShift
+	kShift = 16,
+	kUnit = 1 << kShift
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/debugging/debugmanager.h b/engines/ags/shared/debugging/debugmanager.h
index 696881b65d..21e733206b 100644
--- a/engines/ags/shared/debugging/debugmanager.h
+++ b/engines/ags/shared/debugging/debugmanager.h
@@ -54,6 +54,7 @@
 #include "util/string.h"
 #include "util/string_types.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -64,8 +65,10 @@ struct DebugGroup {
 	DebugGroupID    UID;
 	String          OutputName;
 
-	DebugGroup() {}
-	DebugGroup(DebugGroupID id, String out_name) : UID(id), OutputName(out_name) {}
+	DebugGroup() {
+	}
+	DebugGroup(DebugGroupID id, String out_name) : UID(id), OutputName(out_name) {
+	}
 };
 
 // DebugOutput is a slot for IOutputHandler with its own group filter
@@ -141,7 +144,8 @@ private:
 		PDebugOutput Target;
 		bool          Suppressed;
 
-		OutputSlot() : Suppressed(false) {}
+		OutputSlot() : Suppressed(false) {
+		}
 	};
 
 	typedef std::vector<DebugGroup> GroupVector;
@@ -161,7 +165,8 @@ private:
 // TODO: move this to the dynamically allocated engine object whenever it is implemented
 extern DebugManager DbgMgr;
 
-}   // namespace Common
-}   // namespace AGS
+} // namespace Common
+} // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/debugging/out.h b/engines/ags/shared/debugging/out.h
index 9f00c411dc..2d7efa27fd 100644
--- a/engines/ags/shared/debugging/out.h
+++ b/engines/ags/shared/debugging/out.h
@@ -79,35 +79,36 @@
 
 #include "util/string.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
 // Message types provide distinction for debug messages by their intent.
 enum MessageType {
-	kDbgMsg_None                = 0,
+	kDbgMsg_None = 0,
 	// Alerts may be informative messages with topmost level of importance,
 	// such as reporting engine startup and shutdown.
-	kDbgMsg_Alert               ,
+	kDbgMsg_Alert,
 	// Fatal errors are ones that make program abort immediately.
-	kDbgMsg_Fatal               ,
+	kDbgMsg_Fatal,
 	// Error messages are about engine not being able to perform requested
 	// operation in a situation when that will affect game playability and
 	// further execution.
-	kDbgMsg_Error               ,
+	kDbgMsg_Error,
 	// Warnings are made when unexpected or non-standart behavior
 	// is detected in program, which is not immediately critical,
 	// but may be a symptom of a bigger problem.
-	kDbgMsg_Warn                ,
+	kDbgMsg_Warn,
 	// General information messages.
-	kDbgMsg_Info                ,
+	kDbgMsg_Info,
 	// Debug reason is for arbitrary information about events and current
 	// game state.
-	kDbgMsg_Debug               ,
+	kDbgMsg_Debug,
 
 
 	// Convenient aliases
-	kDbgMsg_Default             = kDbgMsg_Debug,
-	kDbgMsg_All                 = kDbgMsg_Debug
+	kDbgMsg_Default = kDbgMsg_Debug,
+	kDbgMsg_All = kDbgMsg_Debug
 };
 
 // This enumeration is a list of common hard-coded groups, but more could
@@ -131,9 +132,12 @@ struct DebugGroupID {
 	uint32_t    ID;
 	String      SID;
 
-	DebugGroupID() : ID(kDbgGroup_None) {}
-	DebugGroupID(uint32_t id, const String &sid = "") : ID(id), SID(sid) {}
-	DebugGroupID(const String &sid) : ID(kDbgGroup_None), SID(sid) {}
+	DebugGroupID() : ID(kDbgGroup_None) {
+	}
+	DebugGroupID(uint32_t id, const String &sid = "") : ID(id), SID(sid) {
+	}
+	DebugGroupID(const String &sid) : ID(kDbgGroup_None), SID(sid) {
+	}
 	// Tells if any of the id components is valid
 	bool IsValid() const {
 		return ID != kDbgGroup_None || !SID.IsEmpty();
@@ -155,9 +159,10 @@ void Printf(MessageType mt, const char *fmt, ...);
 // Output formatted message of given group and type
 void Printf(DebugGroupID group_id, MessageType mt, const char *fmt, ...);
 
-}   // namespace Debug
+} // namespace Debug
 
-}   // namespace Common
-}   // namespace AGS
+} // namespace Common
+} // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/debugging/outputhandler.h b/engines/ags/shared/debugging/outputhandler.h
index 8fc4a17171..86ddc57fe6 100644
--- a/engines/ags/shared/debugging/outputhandler.h
+++ b/engines/ags/shared/debugging/outputhandler.h
@@ -33,6 +33,7 @@
 #include "debug/out.h"
 #include "util/string.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -42,7 +43,8 @@ struct DebugMessage {
 	String       GroupName;
 	MessageType  MT;
 
-	DebugMessage() : GroupID(kDbgGroup_None), MT(kDbgMsg_None) {}
+	DebugMessage() : GroupID(kDbgGroup_None), MT(kDbgMsg_None) {
+	}
 	DebugMessage(const String &text, uint32_t group_id, const String &group_name, MessageType mt)
 		: Text(text)
 		, GroupID(group_id)
@@ -60,7 +62,8 @@ public:
 	virtual void PrintMessage(const DebugMessage &msg) = 0;
 };
 
-}   // namespace Common
-}   // namespace AGS
+} // namespace Common
+} // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/font/agsfontrenderer.h b/engines/ags/shared/font/agsfontrenderer.h
index dad4a7a529..be77d82238 100644
--- a/engines/ags/shared/font/agsfontrenderer.h
+++ b/engines/ags/shared/font/agsfontrenderer.h
@@ -23,6 +23,8 @@
 #ifndef AGS_SHARED_FONT_AGSFONTRENDERER_H
 #define AGS_SHARED_FONT_AGSFONTRENDERER_H
 
+namespace AGS3 {
+
 struct BITMAP;
 
 // WARNING: this interface is exposed for plugins and declared for the second time in agsplugin.h
@@ -61,4 +63,6 @@ protected:
 	~IAGSFontRenderer2() = default;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/font/fonts.h b/engines/ags/shared/font/fonts.h
index 81bdc67ef9..37586eba68 100644
--- a/engines/ags/shared/font/fonts.h
+++ b/engines/ags/shared/font/fonts.h
@@ -29,11 +29,13 @@
 
 // TODO: we need to make some kind of TextManager class of this module
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 class Bitmap;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS;
 
 class IAGSFontRenderer;
@@ -131,7 +133,8 @@ size_t split_lines(const char *texx, SplitLines &lines, int width, int fontNumbe
 namespace AGS {
 namespace Common {
 extern SplitLines Lines;
-}
-}
+} // namespace Shared
+} // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/font/ttffontrenderer.h b/engines/ags/shared/font/ttffontrenderer.h
index 6f29bd2490..84326fe49a 100644
--- a/engines/ags/shared/font/ttffontrenderer.h
+++ b/engines/ags/shared/font/ttffontrenderer.h
@@ -26,6 +26,8 @@
 #include <map>
 #include "font/agsfontrenderer.h"
 
+namespace AGS3 {
+
 struct ALFONT_FONT;
 
 class TTFFontRenderer : public IAGSFontRenderer, public IAGSFontRenderer2 {
@@ -38,7 +40,7 @@ public:
 	}
 	int GetTextWidth(const char *text, int fontNumber) override;
 	int GetTextHeight(const char *text, int fontNumber) override;
-	void RenderText(const char *text, int fontNumber, BITMAP *destination, int x, int y, int colour) override ;
+	void RenderText(const char *text, int fontNumber, BITMAP *destination, int x, int y, int colour) override;
 	void AdjustYCoordinateForFont(int *ycoord, int fontNumber) override;
 	void EnsureTextValidForFont(char *text, int fontNumber) override;
 
@@ -48,10 +50,12 @@ public:
 
 private:
 	struct FontData {
-		ALFONT_FONT     *AlFont;
+		ALFONT_FONT *AlFont;
 		FontRenderParams Params;
 	};
 	std::map<int, FontData> _fontData;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/font/wfnfont.h b/engines/ags/shared/font/wfnfont.h
index e5020fe764..ebfb0a4ba0 100644
--- a/engines/ags/shared/font/wfnfont.h
+++ b/engines/ags/shared/font/wfnfont.h
@@ -49,11 +49,13 @@
 #include <vector>
 #include "core/types.h"
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Common {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
 
 enum WFNError {
 	kWFNErr_NoError,
@@ -106,4 +108,6 @@ protected:
 	static const WFNChar        _emptyChar; // a dummy character to substitute bad symbols
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/font/wfnfontrenderer.h b/engines/ags/shared/font/wfnfontrenderer.h
index c2fed50159..ac816f647f 100644
--- a/engines/ags/shared/font/wfnfontrenderer.h
+++ b/engines/ags/shared/font/wfnfontrenderer.h
@@ -26,6 +26,8 @@
 #include <map>
 #include "font/agsfontrenderer.h"
 
+namespace AGS3 {
+
 class WFNFont;
 
 class WFNFontRenderer : public IAGSFontRenderer, public IAGSFontRenderer2 {
@@ -44,10 +46,12 @@ public:
 
 private:
 	struct FontData {
-		WFNFont         *Font;
+		WFNFont *Font;
 		FontRenderParams Params;
 	};
 	std::map<int, FontData> _fontData;
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/game/customproperties.h b/engines/ags/shared/game/customproperties.h
index 51d5464481..cd36b985a0 100644
--- a/engines/ags/shared/game/customproperties.h
+++ b/engines/ags/shared/game/customproperties.h
@@ -40,6 +40,8 @@
 #include "util/string.h"
 #include "util/string_types.h"
 
+namespace AGS3 {
+
 #define LEGACY_MAX_CUSTOM_PROPERTIES                30
 // NOTE: for some reason the property name stored in schema object was limited
 // to only 20 characters, while the custom properties map could hold up to 200.
@@ -102,5 +104,6 @@ void          WriteValues(const StringIMap &map, Stream *out);
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/game/interactions.h b/engines/ags/shared/game/interactions.h
index 61728294cb..02b440f393 100644
--- a/engines/ags/shared/game/interactions.h
+++ b/engines/ags/shared/game/interactions.h
@@ -52,6 +52,8 @@
 #include <memory>
 #include "util/string_types.h"
 
+namespace AGS3 {
+
 #define LOCAL_VARIABLE_OFFSET       10000
 #define MAX_GLOBAL_VARIABLES        100
 #define MAX_ACTION_ARGS             5
@@ -63,9 +65,9 @@ namespace Common {
 
 enum InterValType {
 	kInterValLiteralInt = 1,
-	kInterValVariable   = 2,
-	kInterValBoolean    = 3,
-	kInterValCharnum    = 4
+	kInterValVariable = 2,
+	kInterValBoolean = 3,
+	kInterValCharnum = 4
 };
 
 enum InteractionVersion {
@@ -179,9 +181,9 @@ typedef std::shared_ptr<Interaction> PInteraction;
 
 // Legacy pre-3.0 kind of global and local room variables
 struct InteractionVariable {
-	String Name {};
-	char   Type {'\0'};
-	int    Value {0};
+	String Name{};
+	char   Type{ '\0' };
+	int    Value{ 0 };
 
 	InteractionVariable();
 	InteractionVariable(const String &name, char type, int val);
@@ -209,4 +211,6 @@ typedef std::shared_ptr<InteractionScripts> PInteractionScripts;
 extern AGS::Common::InteractionVariable globalvars[MAX_GLOBAL_VARIABLES];
 extern int numGlobalVars;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/game/main_game_file.h b/engines/ags/shared/game/main_game_file.h
index 31eb11a568..86fd9241a9 100644
--- a/engines/ags/shared/game/main_game_file.h
+++ b/engines/ags/shared/game/main_game_file.h
@@ -42,6 +42,8 @@
 #include "util/string.h"
 #include "util/version.h"
 
+namespace AGS3 {
+
 struct GameSetupStruct;
 struct DialogTopic;
 struct ViewStruct;
@@ -107,9 +109,9 @@ struct MainGameSource {
 // directly. This is temporary solution that has to be resolved by the future
 // code refactoring.
 struct LoadedGameEntities {
-	GameSetupStruct        &Game;
-	DialogTopic           *&Dialogs;
-	ViewStruct            *&Views;
+	GameSetupStruct &Game;
+	DialogTopic *&Dialogs;
+	ViewStruct *&Views;
 	PScript                 GlobalScript;
 	PScript                 DialogScript;
 	std::vector<PScript>    ScriptModules;
@@ -148,5 +150,6 @@ void               FixupSaveDirectory(GameSetupStruct &game);
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/game/plugininfo.h b/engines/ags/shared/game/plugininfo.h
index 53a922689f..a368913e91 100644
--- a/engines/ags/shared/game/plugininfo.h
+++ b/engines/ags/shared/game/plugininfo.h
@@ -32,6 +32,8 @@
 #include <memory>
 #include "util/string.h"
 
+namespace AGS3 {
+
 // TODO: why 10 MB limit?
 #define PLUGIN_SAVEBUFFERSIZE 10247680
 
@@ -45,10 +47,12 @@ struct PluginInfo {
 	std::shared_ptr<char> Data;
 	size_t      DataLen;
 
-	PluginInfo() : DataLen(0) {}
+	PluginInfo() : DataLen(0) {
+	}
 };
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/game/room_file.h b/engines/ags/shared/game/room_file.h
index 0a08f66597..be91dbc519 100644
--- a/engines/ags/shared/game/room_file.h
+++ b/engines/ags/shared/game/room_file.h
@@ -38,6 +38,8 @@
 #include "util/stream.h"
 #include "util/string.h"
 
+namespace AGS3 {
+
 struct SpriteInfo;
 namespace AGS {
 namespace Common {
@@ -94,5 +96,6 @@ HRoomFileError WriteRoomData(const RoomStruct *room, Stream *out, RoomFileVersio
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/game/room_version.h b/engines/ags/shared/game/room_version.h
index 5c099110f8..33d04dc39f 100644
--- a/engines/ags/shared/game/room_version.h
+++ b/engines/ags/shared/game/room_version.h
@@ -29,6 +29,8 @@
 #ifndef AGS_SHARED_GAME_ROOMVERSION_H
 #define AGS_SHARED_GAME_ROOMVERSION_H
 
+namespace AGS3 {
+
 /* room file versions history
 8:  final v1.14 release
 9:  intermediate v2 alpha releases
@@ -92,4 +94,6 @@ enum RoomFileVersion {
 	kRoomVersion_Current = kRoomVersion_3508
 };
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/game/roomstruct.h b/engines/ags/shared/game/roomstruct.h
index 590275c501..1895d689c8 100644
--- a/engines/ags/shared/game/roomstruct.h
+++ b/engines/ags/shared/game/roomstruct.h
@@ -54,6 +54,8 @@
 #include "util/geometry.h"
 #include "util/wgt2allg.h" // color (allegro RGB)
 
+namespace AGS3 {
+
 struct ccScript;
 struct SpriteInfo;
 typedef std::shared_ptr<ccScript> PScript;
@@ -74,18 +76,18 @@ enum RoomAreaMask {
 // Room's audio volume modifier
 enum RoomVolumeMod {
 	kRoomVolumeQuietest = -3,
-	kRoomVolumeQuieter  = -2,
-	kRoomVolumeQuiet    = -1,
-	kRoomVolumeNormal   =  0,
-	kRoomVolumeLoud     =  1,
-	kRoomVolumeLouder   =  2,
-	kRoomVolumeLoudest  =  3,
+	kRoomVolumeQuieter = -2,
+	kRoomVolumeQuiet = -1,
+	kRoomVolumeNormal = 0,
+	kRoomVolumeLoud = 1,
+	kRoomVolumeLouder = 2,
+	kRoomVolumeLoudest = 3,
 	// These two options are only settable at runtime by SetMusicVolume()
-	kRoomVolumeExtra1   =  4,
-	kRoomVolumeExtra2   =  5,
+	kRoomVolumeExtra1 = 4,
+	kRoomVolumeExtra2 = 5,
 
-	kRoomVolumeMin      = kRoomVolumeQuietest,
-	kRoomVolumeMax      = kRoomVolumeExtra2,
+	kRoomVolumeMin = kRoomVolumeQuietest,
+	kRoomVolumeMax = kRoomVolumeExtra2,
 };
 
 // Flag tells that walkable area does not have continious zoom
@@ -302,7 +304,7 @@ public:
 	// Gets region's tint luminance in 0 to 100 range value; returns 0 if region's light level is set
 	int  GetRegionTintLuminance(int id) const;
 
-// TODO: all members are currently public because they are used everywhere; hide them later
+	// TODO: all members are currently public because they are used everywhere; hide them later
 public:
 	// Game's unique ID, corresponds to GameSetupStructBase::uniqueid.
 	// If this field has a valid value and does not match actual game's id,
@@ -384,5 +386,6 @@ PBitmap FixBitmap(PBitmap bmp, int dst_width, int dst_height);
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/gfx/allegrobitmap.h b/engines/ags/shared/gfx/allegrobitmap.h
index 98771376e0..77d0ea83fc 100644
--- a/engines/ags/shared/gfx/allegrobitmap.h
+++ b/engines/ags/shared/gfx/allegrobitmap.h
@@ -36,6 +36,7 @@
 #include "core/types.h"
 #include "gfx/bitmap.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -218,12 +219,11 @@ public:
 	void    SetScanLine(int index, unsigned char *data, int data_size = -1);
 
 private:
-	BITMAP          *_alBitmap;
-	bool            _isDataOwner;
+	BITMAP *_alBitmap;
+	bool _isDataOwner;
 };
 
 
-
 namespace BitmapHelper {
 // TODO: revise those functions later (currently needed in a few very specific cases)
 // NOTE: the resulting object __owns__ bitmap data from now on
@@ -234,5 +234,6 @@ Bitmap *CreateRawBitmapWrapper(BITMAP *al_bmp);
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/gfx/bitmap.h b/engines/ags/shared/gfx/bitmap.h
index 3dac81c1e6..b370c9a004 100644
--- a/engines/ags/shared/gfx/bitmap.h
+++ b/engines/ags/shared/gfx/bitmap.h
@@ -31,6 +31,7 @@
 
 #include "util/geometry.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -87,5 +88,6 @@ void    ReadPixelsFromMemory(Bitmap *dst, const uint8_t *src_buffer, const size_
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/gfx/gfx_def.h b/engines/ags/shared/gfx/gfx_def.h
index 787839fd8d..4e84b51bdd 100644
--- a/engines/ags/shared/gfx/gfx_def.h
+++ b/engines/ags/shared/gfx/gfx_def.h
@@ -29,12 +29,13 @@
 #ifndef AGS_SHARED_GFX_GFXDEF_H
 #define AGS_SHARED_GFX_GFXDEF_H
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
 enum BlendMode {
 	// free blending (ARGB -> ARGB) modes
-	kBlendMode_NoAlpha        = 0, // ignore alpha channel
+	kBlendMode_NoAlpha = 0, // ignore alpha channel
 	kBlendMode_Alpha,              // alpha-blend src to dest, combining src & dest alphas
 	// NOTE: add new modes here
 
@@ -104,5 +105,6 @@ inline int LegacyTrans100ToAlpha255(int legacy_transparency) {
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/gui/guibutton.h b/engines/ags/shared/gui/guibutton.h
index 72315b66bd..f89edce6fd 100644
--- a/engines/ags/shared/gui/guibutton.h
+++ b/engines/ags/shared/gui/guibutton.h
@@ -27,21 +27,23 @@
 #include "gui/guiobject.h"
 #include "util/string.h"
 
+namespace AGS3 {
+
 #define GUIBUTTON_LEGACY_TEXTLENGTH 50
 
 namespace AGS {
 namespace Common {
 
 enum MouseButton {
-	kMouseNone  = -1,
-	kMouseLeft  =  0,
-	kMouseRight =  1,
+	kMouseNone = -1,
+	kMouseLeft = 0,
+	kMouseRight = 1,
 };
 
 enum GUIClickAction {
-	kGUIAction_None       = 0,
-	kGUIAction_SetMode    = 1,
-	kGUIAction_RunScript  = 2,
+	kGUIAction_None = 0,
+	kGUIAction_SetMode = 1,
+	kGUIAction_RunScript = 2,
 };
 
 enum LegacyButtonAlignment {
@@ -80,7 +82,7 @@ public:
 	void ReadFromSavegame(Common::Stream *in, GuiSvgVersion svg_ver) override;
 	void WriteToSavegame(Common::Stream *out) const override;
 
-// TODO: these members are currently public; hide them later
+	// TODO: these members are currently public; hide them later
 public:
 	int32_t     Image;
 	int32_t     MouseOverImage;
@@ -134,4 +136,6 @@ extern int numguibuts;
 int UpdateAnimatingButton(int bu);
 void StopButtonAnimation(int idxn);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/gui/guidefines.h b/engines/ags/shared/gui/guidefines.h
index b2aef37410..8f7f04f74f 100644
--- a/engines/ags/shared/gui/guidefines.h
+++ b/engines/ags/shared/gui/guidefines.h
@@ -23,6 +23,8 @@
 #ifndef AGS_SHARED_GUI_GUIDEFINES_H
 #define AGS_SHARED_GUI_GUIDEFINES_H
 
+namespace AGS3 {
+
 #define GUIMAGIC          0xcafebeef
 #define MAX_GUIOBJ_EVENTS 10
 #define TEXTWINDOW_PADDING_DEFAULT  3
@@ -57,29 +59,29 @@
 
 enum GuiVersion {
 	// TODO: find out all corresponding engine version numbers
-	kGuiVersion_Initial     = 0,
-	kGuiVersion_214         = 100,
-	kGuiVersion_222         = 101,
-	kGuiVersion_230         = 102,
-	kGuiVersion_unkn_103    = 103,
-	kGuiVersion_unkn_104    = 104,
-	kGuiVersion_260         = 105,
-	kGuiVersion_unkn_106    = 106,
-	kGuiVersion_unkn_107    = 107,
-	kGuiVersion_unkn_108    = 108,
-	kGuiVersion_unkn_109    = 109,
-	kGuiVersion_270         = 110,
-	kGuiVersion_272a        = 111,
-	kGuiVersion_272b        = 112,
-	kGuiVersion_272c        = 113,
-	kGuiVersion_272d        = 114,
-	kGuiVersion_272e        = 115,
-
-	kGuiVersion_330         = 116,
-	kGuiVersion_331         = 117,
-	kGuiVersion_340         = 118,
-	kGuiVersion_350         = 119,
-	kGuiVersion_Current     = kGuiVersion_350,
+	kGuiVersion_Initial = 0,
+	kGuiVersion_214 = 100,
+	kGuiVersion_222 = 101,
+	kGuiVersion_230 = 102,
+	kGuiVersion_unkn_103 = 103,
+	kGuiVersion_unkn_104 = 104,
+	kGuiVersion_260 = 105,
+	kGuiVersion_unkn_106 = 106,
+	kGuiVersion_unkn_107 = 107,
+	kGuiVersion_unkn_108 = 108,
+	kGuiVersion_unkn_109 = 109,
+	kGuiVersion_270 = 110,
+	kGuiVersion_272a = 111,
+	kGuiVersion_272b = 112,
+	kGuiVersion_272c = 113,
+	kGuiVersion_272d = 114,
+	kGuiVersion_272e = 115,
+
+	kGuiVersion_330 = 116,
+	kGuiVersion_331 = 117,
+	kGuiVersion_340 = 118,
+	kGuiVersion_350 = 119,
+	kGuiVersion_Current = kGuiVersion_350,
 };
 
 namespace AGS {
@@ -87,14 +89,14 @@ namespace Common {
 
 // GUIMain's style and behavior flags
 enum GUIMainFlags {
-	kGUIMain_Clickable  = 0x0001,
+	kGUIMain_Clickable = 0x0001,
 	kGUIMain_TextWindow = 0x0002,
-	kGUIMain_Visible    = 0x0004,
-	kGUIMain_Concealed  = 0x0008,
+	kGUIMain_Visible = 0x0004,
+	kGUIMain_Concealed = 0x0008,
 
 	// NOTE: currently default state is Visible to keep this backwards compatible;
 	// check later if this is still a wanted behavior
-	kGUIMain_DefFlags   = kGUIMain_Clickable | kGUIMain_Visible,
+	kGUIMain_DefFlags = kGUIMain_Clickable | kGUIMain_Visible,
 	// flags that had inverse meaning in old formats
 	kGUIMain_OldFmtXorMask = kGUIMain_Clickable
 };
@@ -107,42 +109,42 @@ enum GUIMainLegacyFlags {
 // GUIMain's style of getting displayed on screen
 enum GUIPopupStyle {
 	// Normal GUI
-	kGUIPopupNormal           = 0,
+	kGUIPopupNormal = 0,
 	// Shown when the mouse cursor moves to the top of the screen
-	kGUIPopupMouseY           = 1,
+	kGUIPopupMouseY = 1,
 	// Same as Normal, but pauses the game when shown
-	kGUIPopupModal            = 2,
+	kGUIPopupModal = 2,
 	// Same as Normal, but is not removed when interface is off
-	kGUIPopupNoAutoRemove     = 3,
+	kGUIPopupNoAutoRemove = 3,
 	// (legacy option) Normal GUI, initially off
 	// converts to kGUIPopupNormal with Visible = false
-	kGUIPopupLegacyNormalOff  = 4
+	kGUIPopupLegacyNormalOff = 4
 };
 
 // The type of GUIControl
 enum GUIControlType {
 	kGUIControlUndefined = -1,
-	kGUIButton      = 1,
-	kGUILabel       = 2,
-	kGUIInvWindow   = 3,
-	kGUISlider      = 4,
-	kGUITextBox     = 5,
-	kGUIListBox     = 6
+	kGUIButton = 1,
+	kGUILabel = 2,
+	kGUIInvWindow = 3,
+	kGUISlider = 4,
+	kGUITextBox = 5,
+	kGUIListBox = 6
 };
 
 // GUIControl general style and behavior flags
 enum GUIControlFlags {
-	kGUICtrl_Default    = 0x0001, // only button
-	kGUICtrl_Cancel     = 0x0002, // unused
-	kGUICtrl_Enabled    = 0x0004,
-	kGUICtrl_TabStop    = 0x0008, // unused
-	kGUICtrl_Visible    = 0x0010,
-	kGUICtrl_Clip       = 0x0020, // only button
-	kGUICtrl_Clickable  = 0x0040,
+	kGUICtrl_Default = 0x0001, // only button
+	kGUICtrl_Cancel = 0x0002, // unused
+	kGUICtrl_Enabled = 0x0004,
+	kGUICtrl_TabStop = 0x0008, // unused
+	kGUICtrl_Visible = 0x0010,
+	kGUICtrl_Clip = 0x0020, // only button
+	kGUICtrl_Clickable = 0x0040,
 	kGUICtrl_Translated = 0x0080, // 3.3.0.1132
-	kGUICtrl_Deleted    = 0x8000, // unused (probably remains from the old editor?)
+	kGUICtrl_Deleted = 0x8000, // unused (probably remains from the old editor?)
 
-	kGUICtrl_DefFlags   = kGUICtrl_Enabled | kGUICtrl_Visible | kGUICtrl_Clickable,
+	kGUICtrl_DefFlags = kGUICtrl_Enabled | kGUICtrl_Visible | kGUICtrl_Clickable,
 	// flags that had inverse meaning in old formats
 	kGUICtrl_OldFmtXorMask = kGUICtrl_Enabled | kGUICtrl_Visible | kGUICtrl_Clickable
 };
@@ -151,9 +153,9 @@ enum GUIControlFlags {
 enum GUIListBoxFlags {
 	kListBox_ShowBorder = 0x01,
 	kListBox_ShowArrows = 0x02,
-	kListBox_SvgIndex   = 0x04,
+	kListBox_SvgIndex = 0x04,
 
-	kListBox_DefFlags   = kListBox_ShowBorder | kListBox_ShowArrows,
+	kListBox_DefFlags = kListBox_ShowBorder | kListBox_ShowArrows,
 	// flags that had inverse meaning in old formats
 	kListBox_OldFmtXorMask = kListBox_ShowBorder | kListBox_ShowArrows
 };
@@ -162,7 +164,7 @@ enum GUIListBoxFlags {
 enum GUITextBoxFlags {
 	kTextBox_ShowBorder = 0x0001,
 
-	kTextBox_DefFlags   = kTextBox_ShowBorder,
+	kTextBox_DefFlags = kTextBox_ShowBorder,
 	// flags that had inverse meaning in old formats
 	kTextBox_OldFmtXorMask = kTextBox_ShowBorder
 };
@@ -170,8 +172,8 @@ enum GUITextBoxFlags {
 // Savegame data format
 // TODO: move to the engine code
 enum GuiSvgVersion {
-	kGuiSvgVersion_Initial  = 0,
-	kGuiSvgVersion_350      = 1
+	kGuiSvgVersion_Initial = 0,
+	kGuiSvgVersion_350 = 1
 };
 
 } // namespace Common
@@ -179,4 +181,6 @@ enum GuiSvgVersion {
 
 extern int guis_need_update;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/gui/guiinv.h b/engines/ags/shared/gui/guiinv.h
index caf85c703d..f0e6041fac 100644
--- a/engines/ags/shared/gui/guiinv.h
+++ b/engines/ags/shared/gui/guiinv.h
@@ -26,6 +26,7 @@
 #include <vector>
 #include "gui/guiobject.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -52,7 +53,7 @@ public:
 	void ReadFromSavegame(Common::Stream *in, GuiSvgVersion svg_ver) override;
 	void WriteToSavegame(Common::Stream *out) const override;
 
-// TODO: these members are currently public; hide them later
+	// TODO: these members are currently public; hide them later
 public:
 	bool    IsMouseOver;
 	int32_t CharId; // whose inventory (-1 = current player)
@@ -72,4 +73,6 @@ private:
 extern std::vector<AGS::Common::GUIInvWindow> guiinv;
 extern int numguiinv;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/gui/guilabel.h b/engines/ags/shared/gui/guilabel.h
index 745e6bf019..88c2380bcf 100644
--- a/engines/ags/shared/gui/guilabel.h
+++ b/engines/ags/shared/gui/guilabel.h
@@ -27,12 +27,14 @@
 #include "gui/guiobject.h"
 #include "util/string.h"
 
+namespace AGS3 {
+
 class SplitLines;
 
 namespace AGS {
 namespace Common {
 
-class GUILabel: public GUIObject {
+class GUILabel : public GUIObject {
 public:
 	GUILabel();
 
@@ -48,7 +50,7 @@ public:
 	void ReadFromSavegame(Common::Stream *in, GuiSvgVersion svg_ver) override;
 	void WriteToSavegame(Common::Stream *out) const override;
 
-// TODO: these members are currently public; hide them later
+	// TODO: these members are currently public; hide them later
 public:
 	String  Text;
 	int32_t Font;
@@ -69,4 +71,6 @@ private:
 extern std::vector<AGS::Common::GUILabel> guilabels;
 extern int numguilabels;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/gui/guilistbox.h b/engines/ags/shared/gui/guilistbox.h
index 73974415e1..30c55e5e6a 100644
--- a/engines/ags/shared/gui/guilistbox.h
+++ b/engines/ags/shared/gui/guilistbox.h
@@ -27,6 +27,7 @@
 #include "gui/guiobject.h"
 #include "util/string.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -63,7 +64,7 @@ public:
 	void ReadFromSavegame(Common::Stream *in, GuiSvgVersion svg_ver) override;
 	void WriteToSavegame(Common::Stream *out) const override;
 
-// TODO: these members are currently public; hide them later
+	// TODO: these members are currently public; hide them later
 public:
 	int32_t               Font;
 	color_t               TextColor;
@@ -100,4 +101,6 @@ private:
 extern std::vector<AGS::Common::GUIListBox> guilist;
 extern int numguilist;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/gui/guimain.h b/engines/ags/shared/gui/guimain.h
index b56f8f28ec..27d7deee5e 100644
--- a/engines/ags/shared/gui/guimain.h
+++ b/engines/ags/shared/gui/guimain.h
@@ -31,12 +31,15 @@
 #include "util/geometry.h"
 #include "util/string.h"
 
+namespace AGS3 {
+
 // Forward declaration
 namespace AGS {
 namespace Common {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 // There were issues when including header caused conflicts
@@ -55,8 +58,8 @@ namespace Common {
 // Legacy GUIMain visibility state, which combined Visible property and override factor
 enum LegacyGUIVisState {
 	kGUIVisibility_Concealed = -1, // gui is hidden by command
-	kGUIVisibility_Off       =  0, // gui is disabled (won't show up by command)
-	kGUIVisibility_On        =  1  // gui is shown by command
+	kGUIVisibility_Off = 0, // gui is disabled (won't show up by command)
+	kGUIVisibility_On = 1  // gui is shown by command
 };
 
 class Bitmap;
@@ -226,7 +229,7 @@ extern bool is_sprite_alpha(int spr);
 
 // This function has distinct implementations in Engine and Editor
 extern void draw_gui_sprite(Common::Bitmap *ds, int spr, int x, int y, bool use_alpha = true,
-                            Common::BlendMode blend_mode = Common::kBlendMode_Alpha);
+	Common::BlendMode blend_mode = Common::kBlendMode_Alpha);
 
 extern AGS_INLINE int game_to_data_coord(int coord);
 extern AGS_INLINE int data_to_game_coord(int coord);
@@ -235,7 +238,7 @@ extern AGS_INLINE int get_fixed_pixel_size(int pixels);
 
 // Those function have distinct implementations in Engine and Editor
 extern void wouttext_outline(Common::Bitmap *ds, int xxp, int yyp, int usingfont, color_t text_color, const char *texx);
-extern int wgettextwidth_compensate(Common::Bitmap *ds, const char *tex, int font) ;
+extern int wgettextwidth_compensate(Common::Bitmap *ds, const char *tex, int font);
 extern void check_font(int *fontnum);
 
 extern void set_our_eip(int eip);
@@ -245,4 +248,6 @@ extern int get_eip_guiobj();
 
 extern bool outlineGuiObjects;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/gui/guiobject.h b/engines/ags/shared/gui/guiobject.h
index 8f2f5e2620..1dfa517867 100644
--- a/engines/ags/shared/gui/guiobject.h
+++ b/engines/ags/shared/gui/guiobject.h
@@ -28,20 +28,19 @@
 #include "gui/guidefines.h"
 #include "util/string.h"
 
+namespace AGS3 {
+
 #define GUIDIS_GREYOUT   1
 #define GUIDIS_BLACKOUT  2
 #define GUIDIS_UNCHANGED 4
 #define GUIDIS_GUIOFF  0x80
 
-
-
-
 namespace AGS {
 namespace Common {
 
 enum LegacyGUIAlignment {
-	kLegacyGUIAlign_Left   = 0,
-	kLegacyGUIAlign_Right  = 1,
+	kLegacyGUIAlign_Left = 0,
+	kLegacyGUIAlign_Right = 1,
 	kLegacyGUIAlign_Center = 2
 };
 
@@ -64,7 +63,8 @@ public:
 	bool            IsClickable() const;
 
 	// Operations
-	virtual void    Draw(Bitmap *ds) { }
+	virtual void    Draw(Bitmap *ds) {
+	}
 	void            SetClickable(bool on);
 	void            SetEnabled(bool on);
 	void            SetTranslated(bool on);
@@ -72,21 +72,27 @@ public:
 
 	// Events
 	// Key pressed for control
-	virtual void    OnKeyPress(int keycode) { }
+	virtual void    OnKeyPress(int keycode) {
+	}
 	// Mouse button down - return 'True' to lock focus
 	virtual bool    OnMouseDown() {
 		return false;
 	}
 	// Mouse moves onto control
-	virtual void    OnMouseEnter() { }
+	virtual void    OnMouseEnter() {
+	}
 	// Mouse moves off control
-	virtual void    OnMouseLeave() { }
+	virtual void    OnMouseLeave() {
+	}
 	// Mouse moves over control - x,y relative to gui
-	virtual void    OnMouseMove(int x, int y) { }
+	virtual void    OnMouseMove(int x, int y) {
+	}
 	// Mouse button up
-	virtual void    OnMouseUp() { }
+	virtual void    OnMouseUp() {
+	}
 	// Control was resized
-	virtual void    OnResized() { }
+	virtual void    OnResized() {
+	}
 
 	// Serialization
 	virtual void    ReadFromFile(Common::Stream *in, GuiVersion gui_version);
@@ -94,7 +100,7 @@ public:
 	virtual void    ReadFromSavegame(Common::Stream *in, GuiSvgVersion svg_ver);
 	virtual void    WriteToSavegame(Common::Stream *out) const;
 
-// TODO: these members are currently public; hide them later
+	// TODO: these members are currently public; hide them later
 public:
 	int32_t  Id;         // GUI object's identifier
 	int32_t  ParentId;   // id of parent GUI
@@ -131,4 +137,6 @@ inline bool IsGUIEnabled(AGS::Common::GUIObject *g) {
 	return !all_buttons_disabled && g->IsEnabled();
 }
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/gui/guislider.h b/engines/ags/shared/gui/guislider.h
index 95b5721af9..2e5696bed2 100644
--- a/engines/ags/shared/gui/guislider.h
+++ b/engines/ags/shared/gui/guislider.h
@@ -26,6 +26,7 @@
 #include <vector>
 #include "gui/guiobject.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -51,7 +52,7 @@ public:
 	void ReadFromSavegame(Stream *in, GuiSvgVersion svg_ver) override;
 	void WriteToSavegame(Stream *out) const override;
 
-// TODO: these members are currently public; hide them later
+	// TODO: these members are currently public; hide them later
 public:
 	int32_t MinValue;
 	int32_t MaxValue;
@@ -73,4 +74,6 @@ private:
 extern std::vector<AGS::Common::GUISlider> guislider;
 extern int numguislider;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/gui/guitextbox.h b/engines/ags/shared/gui/guitextbox.h
index d78b44787c..79f8ac9be5 100644
--- a/engines/ags/shared/gui/guitextbox.h
+++ b/engines/ags/shared/gui/guitextbox.h
@@ -27,6 +27,7 @@
 #include "gui/guiobject.h"
 #include "util/string.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -49,7 +50,7 @@ public:
 	void ReadFromSavegame(Stream *in, GuiSvgVersion svg_ver) override;
 	void WriteToSavegame(Stream *out) const override;
 
-// TODO: these members are currently public; hide them later
+	// TODO: these members are currently public; hide them later
 public:
 	int32_t Font;
 	String  Text;
@@ -67,4 +68,6 @@ private:
 extern std::vector<AGS::Common::GUITextBox> guitext;
 extern int numguitext;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/script/cc_error.h b/engines/ags/shared/script/cc_error.h
index c3d9591b1e..7dc8c68df9 100644
--- a/engines/ags/shared/script/cc_error.h
+++ b/engines/ags/shared/script/cc_error.h
@@ -31,6 +31,8 @@
 
 #include "util/string.h"
 
+namespace AGS3 {
+
 extern void cc_error(const char *, ...);
 
 // error reporting
@@ -41,4 +43,6 @@ extern AGS::Common::String ccErrorCallStack; // callstack where error happened
 extern bool ccErrorIsUserError;
 extern const char *ccCurScriptName; // name of currently compiling script
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/script/cc_options.h b/engines/ags/shared/script/cc_options.h
index e2ccbb6b7c..095887a9a2 100644
--- a/engines/ags/shared/script/cc_options.h
+++ b/engines/ags/shared/script/cc_options.h
@@ -26,6 +26,8 @@
 //
 //=============================================================================
 
+namespace AGS3 {
+
 #ifndef AGS_SHARED_SCRIPT_CC_OPTIONS_H
 #define AGS_SHARED_SCRIPT_CC_OPTIONS_H
 
@@ -41,4 +43,6 @@
 extern void ccSetOption(int, int);
 extern int ccGetOption(int);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/script/cc_script.h b/engines/ags/shared/script/cc_script.h
index 5cbdd14c94..8821879907 100644
--- a/engines/ags/shared/script/cc_script.h
+++ b/engines/ags/shared/script/cc_script.h
@@ -32,11 +32,14 @@
 #include <memory>
 #include "core/types.h"
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Common {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 struct ccScript {
@@ -85,4 +88,6 @@ protected:
 
 typedef std::shared_ptr<ccScript> PScript;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/script/script_common.h b/engines/ags/shared/script/script_common.h
index 42fbf6991e..3e95067c86 100644
--- a/engines/ags/shared/script/script_common.h
+++ b/engines/ags/shared/script/script_common.h
@@ -29,6 +29,8 @@
 #ifndef AGS_SHARED_SCRIPT_SCRIPT_COMMON_H
 #define AGS_SHARED_SCRIPT_SCRIPT_COMMON_H
 
+namespace AGS3 {
+
 #define SCOM_VERSION 90
 #define SCOM_VERSIONSTR "0.90"
 
@@ -138,4 +140,6 @@ extern int currentline;
 extern const char scfilesig[5];
 #define ENDFILESIG 0xbeefcafe
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/util/alignedstream.h b/engines/ags/shared/util/alignedstream.h
index e74517f24c..f91ab58c83 100644
--- a/engines/ags/shared/util/alignedstream.h
+++ b/engines/ags/shared/util/alignedstream.h
@@ -47,6 +47,7 @@
 
 #include "util/proxystream.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -58,8 +59,8 @@ enum AlignedStreamMode {
 class AlignedStream : public ProxyStream {
 public:
 	AlignedStream(Stream *stream, AlignedStreamMode mode,
-	              ObjectOwnershipPolicy stream_ownership_policy = kReleaseAfterUse,
-	              size_t base_alignment = sizeof(int16_t));
+		ObjectOwnershipPolicy stream_ownership_policy = kReleaseAfterUse,
+		size_t base_alignment = sizeof(int16_t));
 	~AlignedStream() override;
 
 	// Read/Write cumulated padding and reset block counter
@@ -109,5 +110,6 @@ private:
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/util/bbop.h b/engines/ags/shared/util/bbop.h
index f56b3ba50a..32472fa84a 100644
--- a/engines/ags/shared/util/bbop.h
+++ b/engines/ags/shared/util/bbop.h
@@ -36,6 +36,7 @@
 #define BITBYTE_BIG_ENDIAN
 #endif
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -60,8 +61,8 @@ inline int32_t SwapBytesInt32(const int32_t val) {
 
 inline int64_t SwapBytesInt64(const int64_t val) {
 	return ((val >> 56) & 0xFF) | ((val >> 40) & 0xFF00) | ((val >> 24) & 0xFF0000) |
-	       ((val >> 8) & 0xFF000000) | ((val << 8) & 0xFF00000000LL) |
-	       ((val << 24) & 0xFF0000000000LL) | ((val << 40) & 0xFF000000000000LL) | ((val << 56) & 0xFF00000000000000LL);
+		((val >> 8) & 0xFF000000) | ((val << 8) & 0xFF00000000LL) |
+		((val << 24) & 0xFF0000000000LL) | ((val << 40) & 0xFF000000000000LL) | ((val << 56) & 0xFF00000000000000LL);
 }
 
 inline float SwapBytesFloat(const float val) {
@@ -143,10 +144,10 @@ inline float FloatFromBE(const float val) {
 
 
 // Aliases for easier calling
-namespace BBOp  = BitByteOperations;
-
+namespace BBOp = BitByteOperations;
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/util/bufferedstream.h b/engines/ags/shared/util/bufferedstream.h
index 27c938d21e..4e14beb8c5 100644
--- a/engines/ags/shared/util/bufferedstream.h
+++ b/engines/ags/shared/util/bufferedstream.h
@@ -27,6 +27,7 @@
 #include "util/filestream.h"
 #include "util/file.h" // TODO: extract filestream mode constants
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -67,5 +68,6 @@ private:
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/util/compress.h b/engines/ags/shared/util/compress.h
index 783b4a9bb1..8fd7aa630e 100644
--- a/engines/ags/shared/util/compress.h
+++ b/engines/ags/shared/util/compress.h
@@ -25,12 +25,15 @@
 
 #include "util/wgt2allg.h" // color (allegro RGB)
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Common {
 class Stream;
 class Bitmap;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 void csavecompressed(Common::Stream *out, const unsigned char *tobesaved, const color pala[256]);
@@ -50,4 +53,6 @@ void load_lzw(Common::Stream *in, Common::Bitmap **bmm, int dst_bpp, color *pall
 void savecompressed_allegro(Common::Stream *out, const Common::Bitmap *bmpp, const color *pall);
 void loadcompressed_allegro(Common::Stream *in, Common::Bitmap **bimpp, color *pall);
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/util/datastream.h b/engines/ags/shared/util/datastream.h
index 78234a4e1d..da47e40cb7 100644
--- a/engines/ags/shared/util/datastream.h
+++ b/engines/ags/shared/util/datastream.h
@@ -34,6 +34,7 @@
 #include "util/bbop.h"
 #include "util/stream.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -59,17 +60,17 @@ public:
 
 	inline size_t ReadArrayOfInt16(int16_t *buffer, size_t count) override {
 		return MustSwapBytes() ?
-		       ReadAndConvertArrayOfInt16(buffer, count) : ReadArray(buffer, sizeof(int16_t), count);
+			ReadAndConvertArrayOfInt16(buffer, count) : ReadArray(buffer, sizeof(int16_t), count);
 	}
 
 	inline size_t ReadArrayOfInt32(int32_t *buffer, size_t count) override {
 		return MustSwapBytes() ?
-		       ReadAndConvertArrayOfInt32(buffer, count) : ReadArray(buffer, sizeof(int32_t), count);
+			ReadAndConvertArrayOfInt32(buffer, count) : ReadArray(buffer, sizeof(int32_t), count);
 	}
 
 	inline size_t ReadArrayOfInt64(int64_t *buffer, size_t count) override {
 		return MustSwapBytes() ?
-		       ReadAndConvertArrayOfInt64(buffer, count) : ReadArray(buffer, sizeof(int64_t), count);
+			ReadAndConvertArrayOfInt64(buffer, count) : ReadArray(buffer, sizeof(int64_t), count);
 	}
 
 	size_t  WriteInt16(int16_t val) override;
@@ -82,17 +83,17 @@ public:
 
 	inline size_t WriteArrayOfInt16(const int16_t *buffer, size_t count) override {
 		return MustSwapBytes() ?
-		       WriteAndConvertArrayOfInt16(buffer, count) : WriteArray(buffer, sizeof(int16_t), count);
+			WriteAndConvertArrayOfInt16(buffer, count) : WriteArray(buffer, sizeof(int16_t), count);
 	}
 
 	inline size_t WriteArrayOfInt32(const int32_t *buffer, size_t count) override {
 		return MustSwapBytes() ?
-		       WriteAndConvertArrayOfInt32(buffer, count) : WriteArray(buffer, sizeof(int32_t), count);
+			WriteAndConvertArrayOfInt32(buffer, count) : WriteArray(buffer, sizeof(int32_t), count);
 	}
 
 	inline size_t WriteArrayOfInt64(const int64_t *buffer, size_t count) override {
 		return MustSwapBytes() ?
-		       WriteAndConvertArrayOfInt64(buffer, count) : WriteArray(buffer, sizeof(int64_t), count);
+			WriteAndConvertArrayOfInt64(buffer, count) : WriteArray(buffer, sizeof(int64_t), count);
 	}
 
 protected:
@@ -124,5 +125,6 @@ protected:
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/util/directory.h b/engines/ags/shared/util/directory.h
index 078f777b76..55dc4deb0a 100644
--- a/engines/ags/shared/util/directory.h
+++ b/engines/ags/shared/util/directory.h
@@ -32,6 +32,7 @@
 #include "core/platform.h"
 #include "util/string.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -49,5 +50,6 @@ String GetCurrentDirectory();
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/util/error.h b/engines/ags/shared/util/error.h
index 09ae192346..4487484976 100644
--- a/engines/ags/shared/util/error.h
+++ b/engines/ags/shared/util/error.h
@@ -33,6 +33,7 @@
 #include <memory>
 #include "util/string.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -45,10 +46,14 @@ typedef std::shared_ptr<Error> PError;
 //
 class Error {
 public:
-	Error(int code, String general, PError inner_error = PError()) : _code(code), _general(general), _innerError(inner_error) {}
-	Error(int code, String general, String comment, PError inner_error = PError()) : _code(code), _general(general), _comment(comment), _innerError(inner_error) {}
-	Error(String general, PError inner_error = PError()) : _code(0), _general(general), _innerError(inner_error) {}
-	Error(String general, String comment, PError inner_error = PError()) : _code(0), _general(general), _comment(comment), _innerError(inner_error) {}
+	Error(int code, String general, PError inner_error = PError()) : _code(code), _general(general), _innerError(inner_error) {
+	}
+	Error(int code, String general, String comment, PError inner_error = PError()) : _code(code), _general(general), _comment(comment), _innerError(inner_error) {
+	}
+	Error(String general, PError inner_error = PError()) : _code(0), _general(general), _innerError(inner_error) {
+	}
+	Error(String general, String comment, PError inner_error = PError()) : _code(0), _general(general), _comment(comment), _innerError(inner_error) {
+	}
 
 
 	// Error code is a number, defining error subtype. It is not much use to the end-user,
@@ -110,8 +115,10 @@ public:
 	}
 
 	ErrorHandle() = default;
-	ErrorHandle(T *err) : _error(err) {}
-	ErrorHandle(std::shared_ptr<T> err) : _error(err) {}
+	ErrorHandle(T *err) : _error(err) {
+	}
+	ErrorHandle(std::shared_ptr<T> err) : _error(err) {
+	}
 
 	bool HasError() const {
 		return _error.get() != NULL;
@@ -144,9 +151,11 @@ typedef ErrorHandle<Error> HError;
 template <typename CodeType, String(*GetErrorText)(CodeType)>
 class TypedCodeError : public Error {
 public:
-	TypedCodeError(CodeType code, PError inner_error = PError()) : Error(code, GetErrorText(code), inner_error) {}
+	TypedCodeError(CodeType code, PError inner_error = PError()) : Error(code, GetErrorText(code), inner_error) {
+	}
 	TypedCodeError(CodeType code, String comment, PError inner_error = PError()) :
-		Error(code, GetErrorText(code), comment, inner_error) {}
+		Error(code, GetErrorText(code), comment, inner_error) {
+	}
 
 	CodeType Code() const {
 		return (CodeType)Error::Code();
@@ -155,5 +164,6 @@ public:
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/util/file.h b/engines/ags/shared/util/file.h
index e2a9227557..6774a33c07 100644
--- a/engines/ags/shared/util/file.h
+++ b/engines/ags/shared/util/file.h
@@ -32,6 +32,7 @@
 #include "core/platform.h"
 #include "util/string.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -67,7 +68,7 @@ bool        GetFileModesFromCMode(const String &cmode, FileOpenMode &open_mode,
 // Gets C-style file mode from FileOpenMode and FileWorkMode
 String      GetCMode(FileOpenMode open_mode, FileWorkMode work_mode);
 
-Stream      *OpenFile(const String &filename, FileOpenMode open_mode, FileWorkMode work_mode);
+Stream *OpenFile(const String &filename, FileOpenMode open_mode, FileWorkMode work_mode);
 // Convenience helpers
 // Create a totally new file, overwrite existing one
 inline Stream *CreateFile(const String &filename) {
@@ -85,5 +86,6 @@ inline Stream *OpenFileWrite(const String &filename) {
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/util/filestream.h b/engines/ags/shared/util/filestream.h
index 231f42ea7a..8e222b2a37 100644
--- a/engines/ags/shared/util/filestream.h
+++ b/engines/ags/shared/util/filestream.h
@@ -28,6 +28,7 @@
 #include "util/datastream.h"
 #include "util/file.h" // TODO: extract filestream mode constants
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -39,7 +40,7 @@ public:
 	// - there is an issue opening the file (does not exist, locked, permissions, etc)
 	// - the open mode could not be determined
 	FileStream(const String &file_name, FileOpenMode open_mode, FileWorkMode work_mode,
-	           DataEndianess stream_endianess = kLittleEndian);
+		DataEndianess stream_endianess = kLittleEndian);
 	~FileStream() override;
 
 	bool    HasErrors() const override;
@@ -68,12 +69,13 @@ public:
 private:
 	void            Open(const String &file_name, FileOpenMode open_mode, FileWorkMode work_mode);
 
-	FILE                *_file;
+	FILE *_file;
 	const FileOpenMode  _openMode;
 	const FileWorkMode  _workMode;
 };
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/util/geometry.h b/engines/ags/shared/util/geometry.h
index a40b0b475d..058ca377a9 100644
--- a/engines/ags/shared/util/geometry.h
+++ b/engines/ags/shared/util/geometry.h
@@ -31,6 +31,8 @@
 
 #include "util/math.h"
 
+namespace AGS3 {
+
 namespace AGSMath = AGS::Common::Math;
 //namespace AGS
 //{
@@ -44,35 +46,35 @@ enum FrameAlignment {
 	// Alignment options are representing 8 sides of a frame (rectangle);
 	// they are implemented as flags that may be combined together if it
 	// is wanted to define alignment to multiple sides at once.
-	kAlignTopLeft       = 0x0001,
-	kAlignTopCenter     = 0x0002,
-	kAlignTopRight      = 0x0004,
-	kAlignMiddleLeft    = 0x0008,
-	kAlignMiddleCenter  = 0x0010,
-	kAlignMiddleRight   = 0x0020,
-	kAlignBottomLeft    = 0x0040,
-	kAlignBottomCenter  = 0x0080,
-	kAlignBottomRight   = 0x0100,
+	kAlignTopLeft = 0x0001,
+	kAlignTopCenter = 0x0002,
+	kAlignTopRight = 0x0004,
+	kAlignMiddleLeft = 0x0008,
+	kAlignMiddleCenter = 0x0010,
+	kAlignMiddleRight = 0x0020,
+	kAlignBottomLeft = 0x0040,
+	kAlignBottomCenter = 0x0080,
+	kAlignBottomRight = 0x0100,
 
 	// Masks are helping to determine whether alignment parameter contains
 	// particular horizontal or vertical component (for example: left side
 	// or bottom side)
-	kMAlignLeft         = kAlignTopLeft | kAlignMiddleLeft | kAlignBottomLeft,
-	kMAlignRight        = kAlignTopRight | kAlignMiddleRight | kAlignBottomRight,
-	kMAlignTop          = kAlignTopLeft | kAlignTopCenter | kAlignTopRight,
-	kMAlignBottom       = kAlignBottomLeft | kAlignBottomCenter | kAlignBottomRight,
-	kMAlignHCenter      = kAlignTopCenter | kAlignMiddleCenter | kAlignBottomCenter,
-	kMAlignVCenter      = kAlignMiddleLeft | kAlignMiddleCenter | kAlignMiddleRight
+	kMAlignLeft = kAlignTopLeft | kAlignMiddleLeft | kAlignBottomLeft,
+	kMAlignRight = kAlignTopRight | kAlignMiddleRight | kAlignBottomRight,
+	kMAlignTop = kAlignTopLeft | kAlignTopCenter | kAlignTopRight,
+	kMAlignBottom = kAlignBottomLeft | kAlignBottomCenter | kAlignBottomRight,
+	kMAlignHCenter = kAlignTopCenter | kAlignMiddleCenter | kAlignBottomCenter,
+	kMAlignVCenter = kAlignMiddleLeft | kAlignMiddleCenter | kAlignMiddleRight
 };
 
 // Horizontal alignment; based on FrameAlignment, used to restrict alignment
 // setting to left/right/center option, while keeping compatibility with any
 // alignment in case it will be supported in the future.
 enum HorAlignment {
-	kHAlignNone     = kAlignNone,
-	kHAlignLeft     = kAlignTopLeft,
-	kHAlignRight    = kAlignTopRight,
-	kHAlignCenter   = kAlignTopCenter
+	kHAlignNone = kAlignNone,
+	kHAlignLeft = kAlignTopLeft,
+	kHAlignRight = kAlignTopRight,
+	kHAlignCenter = kAlignTopCenter
 };
 
 enum RectPlacement {
@@ -160,7 +162,7 @@ struct Size {
 
 	inline static Size Clamp(const Size &sz, const Size &floor, const Size &ceil) {
 		return Size(AGSMath::Clamp(sz.Width, floor.Width, ceil.Width),
-		            AGSMath::Clamp(sz.Height, floor.Height, ceil.Height));
+			AGSMath::Clamp(sz.Height, floor.Height, ceil.Height));
 	}
 
 	// Indicates if current size exceeds other size by any metric
@@ -211,17 +213,17 @@ struct Rect {
 	int Bottom;
 
 	Rect() {
-		Left    = 0;
-		Top     = 0;
-		Right   = -1;
-		Bottom  = -1;
+		Left = 0;
+		Top = 0;
+		Right = -1;
+		Bottom = -1;
 	}
 
 	Rect(int l, int t, int r, int b) {
-		Left    = l;
-		Top     = t;
-		Right   = r;
-		Bottom  = b;
+		Left = l;
+		Top = t;
+		Right = r;
+		Bottom = b;
 	}
 
 	inline Point GetLT() const {
@@ -361,5 +363,6 @@ Rect ClampToRect(const Rect &place, const Rect &item);
 Rect PlaceInRect(const Rect &place, const Rect &item, const RectPlacement &placement);
 //} // namespace Common
 //} // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/util/ini_util.h b/engines/ags/shared/util/ini_util.h
index 7a837780f4..7e5906bb5e 100644
--- a/engines/ags/shared/util/ini_util.h
+++ b/engines/ags/shared/util/ini_util.h
@@ -33,6 +33,7 @@
 #include <map>
 #include "util/string.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -70,5 +71,6 @@ bool Merge(const String &file, const ConfigTree &tree);
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/util/inifile.h b/engines/ags/shared/util/inifile.h
index 2064dd827e..09709dda14 100644
--- a/engines/ags/shared/util/inifile.h
+++ b/engines/ags/shared/util/inifile.h
@@ -36,6 +36,7 @@
 #include <list>
 #include "util/string.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -101,7 +102,7 @@ public:
 		ItemIterator Begin() {
 			return Items.begin();
 		}
-		ItemIterator End()   {
+		ItemIterator End() {
 			return Items.end();
 		}
 		ConstItemIterator CBegin() const {
@@ -136,7 +137,7 @@ public:
 	SectionIterator Begin() {
 		return _sections.begin();
 	}
-	SectionIterator End()   {
+	SectionIterator End() {
 		return _sections.end();
 	}
 	ConstSectionIterator CBegin() const {
@@ -169,5 +170,6 @@ private:
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/util/lzw.h b/engines/ags/shared/util/lzw.h
index c62c2c8265..236343090c 100644
--- a/engines/ags/shared/util/lzw.h
+++ b/engines/ags/shared/util/lzw.h
@@ -23,11 +23,14 @@
 #ifndef AGS_SHARED_UTIL_LZW_H
 #define AGS_SHARED_UTIL_LZW_H
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Common {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 void lzwcompress(Common::Stream *lzw_in, Common::Stream *out);
@@ -35,4 +38,6 @@ unsigned char *lzwexpand_to_mem(Common::Stream *in);
 
 extern long outbytes, maxsize, putbytes;
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/util/math.h b/engines/ags/shared/util/math.h
index 52d760a506..9053565f8b 100644
--- a/engines/ags/shared/util/math.h
+++ b/engines/ags/shared/util/math.h
@@ -29,6 +29,8 @@
 #ifndef AGS_SHARED_UTIL_MATH_H
 #define AGS_SHARED_UTIL_MATH_H
 
+namespace AGS3 {
+
 #ifndef M_PI
 #define M_PI 3.14159265358979323846
 #endif
@@ -84,5 +86,6 @@ inline float DegreesToRadians(float deg) {
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/util/memory.h b/engines/ags/shared/util/memory.h
index 8ab235a3e9..85defb9cbb 100644
--- a/engines/ags/shared/util/memory.h
+++ b/engines/ags/shared/util/memory.h
@@ -33,6 +33,8 @@
 #include "util/bbop.h"
 #include "util/math.h"
 
+namespace AGS3 {
+
 #if defined (AGS_STRICT_ALIGNMENT) || defined (TEST_STRICT_ALIGNMENT)
 #define MEMORY_STRICT_ALIGNMENT
 #endif
@@ -91,10 +93,10 @@ inline int64_t ReadInt64(const void *ptr) {
 	const uint8_t *b = (const uint8_t *)ptr;
 #if defined (BITBYTE_BIG_ENDIAN)
 	return ((uint64_t)b[0] << 56) | ((uint64_t)b[1] << 48) | ((uint64_t)b[2] << 40) | ((uint64_t)b[3] << 32) |
-	       (b[4] << 24) | (b[5] << 16) | (b[6] << 8) | b[7];
+		(b[4] << 24) | (b[5] << 16) | (b[6] << 8) | b[7];
 #else
 	return ((uint64_t)b[7] << 56) | ((uint64_t)b[6] << 48) | ((uint64_t)b[5] << 40) | ((uint64_t)b[4] << 32) |
-	       (b[3] << 24) | (b[2] << 16) | (b[1] << 8) | b[0];
+		(b[3] << 24) | (b[2] << 16) | (b[1] << 8) | b[0];
 #endif
 #else
 	return *(int64_t *)ptr;
@@ -218,8 +220,8 @@ inline void WriteInt64BE(void *ptr, int64_t value) {
 //-------------------------------------------------------------------------
 // Copies block of 2d data from source into destination.
 inline void BlockCopy(uint8_t *dst, const size_t dst_pitch, const size_t dst_offset,
-                      const uint8_t *src, const size_t src_pitch, const size_t src_offset,
-                      const size_t height) {
+	const uint8_t *src, const size_t src_pitch, const size_t src_offset,
+	const size_t height) {
 	for (size_t y = 0; y < height; ++y, src += src_pitch, dst += dst_pitch)
 		memcpy(dst + dst_offset, src + src_offset, Math::Min(dst_pitch - dst_offset, src_pitch - src_offset));
 }
@@ -228,5 +230,6 @@ inline void BlockCopy(uint8_t *dst, const size_t dst_pitch, const size_t dst_off
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/util/misc.h b/engines/ags/shared/util/misc.h
index e658ebf2bd..8d798e1e7f 100644
--- a/engines/ags/shared/util/misc.h
+++ b/engines/ags/shared/util/misc.h
@@ -54,11 +54,14 @@
 
 #include "util/file.h" // TODO: extract filestream mode constants
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Common {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 // Case-insensitive file lookup functions. On case-insensitive systems
@@ -68,10 +71,11 @@ using namespace AGS; // FIXME later
 // They are used as a system-independent way to open a file when its name
 // case can be ignored.
 Common::Stream *ci_fopen(const char *file_name,
-                         Common::FileOpenMode open_mode = Common::kFile_Open,
-                         Common::FileWorkMode work_mode = Common::kFile_Read);
+	Common::FileOpenMode open_mode = Common::kFile_Open,
+	Common::FileWorkMode work_mode = Common::kFile_Read);
 // TODO: return String object
 char *ci_find_file(const char *dir_name, const char *file_name);
 
+} // namespace AGS3
 
-#endif  // __MISC_H
+#endif
diff --git a/engines/ags/shared/util/multifilelib.h b/engines/ags/shared/util/multifilelib.h
index 5def303436..d7242b667c 100644
--- a/engines/ags/shared/util/multifilelib.h
+++ b/engines/ags/shared/util/multifilelib.h
@@ -37,6 +37,7 @@
 #include "core/asset.h"
 #include "util/stream.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -45,21 +46,21 @@ namespace Common {
 //
 namespace MFLUtil {
 enum MFLError {
-	kMFLNoError           =  0,
-	kMFLErrNoLibSig       = -1, // library signature does not match
-	kMFLErrLibVersion     = -2, // library version unsupported
-	kMFLErrNoLibBase      = -3, // file is not library base (head)
-	kMFLErrLibAssetCount  = -4, // too many assets in library
+	kMFLNoError = 0,
+	kMFLErrNoLibSig = -1, // library signature does not match
+	kMFLErrLibVersion = -2, // library version unsupported
+	kMFLErrNoLibBase = -3, // file is not library base (head)
+	kMFLErrLibAssetCount = -4, // too many assets in library
 };
 
 enum MFLVersion {
-	kMFLVersion_SingleLib   = 6,
-	kMFLVersion_MultiV10    = 10,
-	kMFLVersion_MultiV11    = 11,
-	kMFLVersion_MultiV15    = 15, // unknown differences
-	kMFLVersion_MultiV20    = 20,
-	kMFLVersion_MultiV21    = 21,
-	kMFLVersion_MultiV30    = 30  // 64-bit file support, loose limits
+	kMFLVersion_SingleLib = 6,
+	kMFLVersion_MultiV10 = 10,
+	kMFLVersion_MultiV11 = 11,
+	kMFLVersion_MultiV15 = 15, // unknown differences
+	kMFLVersion_MultiV20 = 20,
+	kMFLVersion_MultiV21 = 21,
+	kMFLVersion_MultiV30 = 30  // 64-bit file support, loose limits
 };
 
 // Maximal number of the data files in one library chain (1-byte index)
@@ -74,5 +75,6 @@ void     WriteEnder(soff_t lib_offset, MFLVersion lib_index, Stream *out);
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/util/path.h b/engines/ags/shared/util/path.h
index 6b4da1924f..41a62c406b 100644
--- a/engines/ags/shared/util/path.h
+++ b/engines/ags/shared/util/path.h
@@ -31,6 +31,7 @@
 
 #include "util/string.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -86,5 +87,6 @@ String  GetCmdLinePathInASCII(const char *arg, int arg_index);
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/util/proxystream.h b/engines/ags/shared/util/proxystream.h
index 70e4761745..8c0758cd1d 100644
--- a/engines/ags/shared/util/proxystream.h
+++ b/engines/ags/shared/util/proxystream.h
@@ -25,6 +25,7 @@
 
 #include "util/stream.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -78,11 +79,12 @@ public:
 	bool    Seek(soff_t offset, StreamSeek origin) override;
 
 protected:
-	Stream                  *_stream;
+	Stream *_stream;
 	ObjectOwnershipPolicy   _streamOwnershipPolicy;
 };
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/util/stdio_compat.h b/engines/ags/shared/util/stdio_compat.h
index 203d600c3c..289d23b6e3 100644
--- a/engines/ags/shared/util/stdio_compat.h
+++ b/engines/ags/shared/util/stdio_compat.h
@@ -26,22 +26,26 @@
 #include <stdio.h>
 #include <stdint.h>
 
+namespace AGS3 {
+
 typedef int64_t file_off_t;
 
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-int  ags_fseek(FILE *stream, file_off_t offset, int whence);
-file_off_t   ags_ftell(FILE *stream);
+	int  ags_fseek(FILE *stream, file_off_t offset, int whence);
+	file_off_t   ags_ftell(FILE *stream);
 
-int ags_file_exists(const char *path);
-int ags_directory_exists(const char *path);
-int ags_path_exists(const char *path);
-file_off_t ags_file_size(const char *path);
+	int ags_file_exists(const char *path);
+	int ags_directory_exists(const char *path);
+	int ags_path_exists(const char *path);
+	file_off_t ags_file_size(const char *path);
 
 #ifdef __cplusplus
 }
 #endif
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/util/stream.h b/engines/ags/shared/util/stream.h
index d97cd26621..d9cafba202 100644
--- a/engines/ags/shared/util/stream.h
+++ b/engines/ags/shared/util/stream.h
@@ -37,6 +37,7 @@
 
 #include "api/stream_api.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -84,5 +85,6 @@ public:
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/util/string.h b/engines/ags/shared/util/string.h
index 0272468e0d..8d8a02f893 100644
--- a/engines/ags/shared/util/string.h
+++ b/engines/ags/shared/util/string.h
@@ -52,6 +52,7 @@
 #include "core/types.h"
 #include "debug/assert.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -158,7 +159,7 @@ public:
 	// This also means that there's always at least one section in any string,
 	// even if there are no separating chars.
 	bool    FindSection(char separator, size_t first, size_t last, bool exclude_first_sep, bool exclude_last_sep,
-	                    size_t &from, size_t &to) const;
+		size_t &from, size_t &to) const;
 
 	// Get Nth character with bounds check (as opposed to subscript operator)
 	inline char GetAt(size_t index) const {
@@ -209,7 +210,7 @@ public:
 	String  RightSection(char separator, bool exclude_separator = true) const;
 	// Extract the range of Xth to Yth fields, separated by the given character
 	String  Section(char separator, size_t first, size_t last,
-	                bool exclude_first_sep = true, bool exclude_last_sep = true) const;
+		bool exclude_first_sep = true, bool exclude_last_sep = true) const;
 	// Splits the string into segments divided by the instances of a given character,
 	// including empty segments e.g. if separators follow each other;
 	// returns at least one segment (equal to full string if no separator was found)
@@ -247,7 +248,7 @@ public:
 	void    ClipRightSection(char separator, bool include_separator = true);
 	// Cuts out the range of Xth to Yth fields separated by the given character
 	void    ClipSection(char separator, size_t first, size_t last,
-	                    bool include_first_sep = true, bool include_last_sep = true);
+		bool include_first_sep = true, bool include_last_sep = true);
 	// Sets string length to zero
 	void    Empty();
 	// Makes a new string by filling N chars with certain value
@@ -304,7 +305,7 @@ public:
 	// Truncate the string to range of Xth to Yth fields separated by the
 	// given character
 	void    TruncateToSection(char separator, size_t first, size_t last,
-	                          bool exclude_first_sep = true, bool exclude_last_sep = true);
+		bool exclude_first_sep = true, bool exclude_last_sep = true);
 	// Wraps the given string buffer without owning it, won't count references,
 	// won't delete it at destruction. Can be used with string literals.
 	void    Wrap(const char *cstr);
@@ -348,7 +349,7 @@ private:
 	// or after the current string data
 	void    ReserveAndShift(bool left, size_t more_length);
 
-	char    *_cstr;  // pointer to actual string data
+	char *_cstr;  // pointer to actual string data
 	size_t  _len;    // valid string length, in characters, excluding null-term
 
 	// Header of a reference-counted buffer
@@ -359,12 +360,13 @@ private:
 
 	// Union that groups mutually exclusive data (currently only ref counted buffer)
 	union {
-		char      *_buf;     // reference-counted data (raw ptr)
+		char *_buf;     // reference-counted data (raw ptr)
 		BufHeader *_bufHead; // the header of a reference-counted data
 	};
 };
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/util/string_compat.h b/engines/ags/shared/util/string_compat.h
index 631c6c22a0..3931eae1f5 100644
--- a/engines/ags/shared/util/string_compat.h
+++ b/engines/ags/shared/util/string_compat.h
@@ -25,18 +25,22 @@
 
 #include "core/types.h"
 
+namespace AGS3 {
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-char *ags_strlwr(char *s);
-char *ags_strupr(char *s);
-int ags_stricmp(const char *, const char *);
-int ags_strnicmp(const char *, const char *, size_t);
-char *ags_strdup(const char *s);
+	char *ags_strlwr(char *s);
+	char *ags_strupr(char *s);
+	int ags_stricmp(const char *, const char *);
+	int ags_strnicmp(const char *, const char *, size_t);
+	char *ags_strdup(const char *s);
 
 #ifdef __cplusplus
 }
 #endif
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/shared/util/string_types.h b/engines/ags/shared/util/string_types.h
index 28989aa446..c0871acc26 100644
--- a/engines/ags/shared/util/string_types.h
+++ b/engines/ags/shared/util/string_types.h
@@ -30,6 +30,7 @@
 #include <vector>
 #include "util/string.h"
 
+namespace AGS3 {
 namespace FNV {
 
 const uint32_t PRIME_NUMBER = 2166136261U;
@@ -104,5 +105,6 @@ typedef std::unordered_map<String, String, HashStrNoCase, StrEqNoCase> StringIMa
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/util/string_utils.h b/engines/ags/shared/util/string_utils.h
index 305deb5231..34a33e37bf 100644
--- a/engines/ags/shared/util/string_utils.h
+++ b/engines/ags/shared/util/string_utils.h
@@ -25,11 +25,14 @@
 
 #include "util/string.h"
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Common {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 //=============================================================================
@@ -76,6 +79,6 @@ void            WriteCStr(const String &s, Stream *out);
 }
 } // namespace Common
 } // namespace AGS
-
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/util/textreader.h b/engines/ags/shared/util/textreader.h
index fb1c7b3eaf..3cfe2b6463 100644
--- a/engines/ags/shared/util/textreader.h
+++ b/engines/ags/shared/util/textreader.h
@@ -31,6 +31,7 @@
 
 #include "util/string.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -38,19 +39,20 @@ class TextReader {
 public:
 	virtual ~TextReader() = default;
 
-	virtual bool IsValid() const            = 0;
+	virtual bool IsValid() const = 0;
 
 	// Read single character
-	virtual char    ReadChar()              = 0;
+	virtual char    ReadChar() = 0;
 	// Read defined number of characters
 	virtual String  ReadString(size_t length) = 0;
 	// Read till line break
-	virtual String  ReadLine()              = 0;
+	virtual String  ReadLine() = 0;
 	// Read till end of available data
-	virtual String  ReadAll()               = 0;
+	virtual String  ReadAll() = 0;
 };
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/util/textstreamreader.h b/engines/ags/shared/util/textstreamreader.h
index 943ccf4d55..50360d619e 100644
--- a/engines/ags/shared/util/textstreamreader.h
+++ b/engines/ags/shared/util/textstreamreader.h
@@ -31,6 +31,7 @@
 
 #include "util/textreader.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -43,7 +44,7 @@ public:
 	~TextStreamReader() override;
 
 	bool    IsValid() const override;
-	const Stream   *GetStream() const;
+	const Stream *GetStream() const;
 	// TODO: use shared ptr instead
 	void            ReleaseStream();
 
@@ -64,5 +65,6 @@ private:
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/util/textstreamwriter.h b/engines/ags/shared/util/textstreamwriter.h
index 3ece10881d..bf7df09112 100644
--- a/engines/ags/shared/util/textstreamwriter.h
+++ b/engines/ags/shared/util/textstreamwriter.h
@@ -31,6 +31,7 @@
 
 #include "util/textwriter.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -43,7 +44,7 @@ public:
 	~TextStreamWriter() override;
 
 	bool    IsValid() const override;
-	const Stream   *GetStream() const;
+	const Stream *GetStream() const;
 	// TODO: use shared ptr instead
 	void            ReleaseStream();
 
@@ -65,5 +66,6 @@ private:
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/util/textwriter.h b/engines/ags/shared/util/textwriter.h
index 64b4f292df..9140f43832 100644
--- a/engines/ags/shared/util/textwriter.h
+++ b/engines/ags/shared/util/textwriter.h
@@ -31,6 +31,7 @@
 
 #include "util/string.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -38,20 +39,21 @@ class TextWriter {
 public:
 	virtual ~TextWriter() = default;
 
-	virtual bool    IsValid() const                         = 0;
+	virtual bool    IsValid() const = 0;
 
 	// Write single character
-	virtual void    WriteChar(char c)                       = 0;
+	virtual void    WriteChar(char c) = 0;
 	// Write string as a plain text (without null-terminator)
-	virtual void    WriteString(const String &str)          = 0;
+	virtual void    WriteString(const String &str) = 0;
 	// Write string and add line break at the end
-	virtual void    WriteLine(const String &str)            = 0;
+	virtual void    WriteLine(const String &str) = 0;
 	// Write formatted string (see *printf)
-	virtual void    WriteFormat(const char *fmt, ...)       = 0;
-	virtual void    WriteLineBreak()                        = 0;
+	virtual void    WriteFormat(const char *fmt, ...) = 0;
+	virtual void    WriteLineBreak() = 0;
 };
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/util/version.h b/engines/ags/shared/util/version.h
index 865280e0fd..ed91b13323 100644
--- a/engines/ags/shared/util/version.h
+++ b/engines/ags/shared/util/version.h
@@ -31,6 +31,7 @@
 
 #include "util/string.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Common {
 
@@ -102,5 +103,6 @@ private:
 
 } // namespace Common
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/util/wgt2allg.h b/engines/ags/shared/util/wgt2allg.h
index 22ce298acb..3e4f81ca2f 100644
--- a/engines/ags/shared/util/wgt2allg.h
+++ b/engines/ags/shared/util/wgt2allg.h
@@ -37,11 +37,14 @@
 
 #include "allegro.h"
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Common {
 class Bitmap;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 
@@ -61,23 +64,23 @@ extern "C"
 {
 #endif
 
-extern void wsetrgb(int coll, int r, int g, int b, color *pall);
-extern void wcolrotate(unsigned char start, unsigned char finish, int dir, color *pall);
+	extern void wsetrgb(int coll, int r, int g, int b, color *pall);
+	extern void wcolrotate(unsigned char start, unsigned char finish, int dir, color *pall);
 
-extern Common::Bitmap *wnewblock(Common::Bitmap *src, int x1, int y1, int x2, int y2);
+	extern Common::Bitmap *wnewblock(Common::Bitmap *src, int x1, int y1, int x2, int y2);
 
-extern int wloadsprites(color *pall, char *filnam, Common::Bitmap **sarray, int strt, int eend);
+	extern int wloadsprites(color *pall, char *filnam, Common::Bitmap **sarray, int strt, int eend);
 
-extern void wputblock(Common::Bitmap *ds, int xx, int yy, Common::Bitmap *bll, int xray);
-// CHECKME: temporary solution for plugin system
-extern void wputblock_raw(Common::Bitmap *ds, int xx, int yy, BITMAP *bll, int xray);
-extern const int col_lookups[32];
+	extern void wputblock(Common::Bitmap *ds, int xx, int yy, Common::Bitmap *bll, int xray);
+	// CHECKME: temporary solution for plugin system
+	extern void wputblock_raw(Common::Bitmap *ds, int xx, int yy, BITMAP *bll, int xray);
+	extern const int col_lookups[32];
 
-//extern void wsetcolor(int nval);
+	//extern void wsetcolor(int nval);
 
-extern int __wremap_keep_transparent;
-extern void wremap(color *pal1, Common::Bitmap *picc, color *pal2);
-extern void wremapall(color *pal1, Common::Bitmap *picc, color *pal2);
+	extern int __wremap_keep_transparent;
+	extern void wremap(color *pal1, Common::Bitmap *picc, color *pal2);
+	extern void wremapall(color *pal1, Common::Bitmap *picc, color *pal2);
 
 #ifdef __cplusplus
 }
@@ -89,4 +92,6 @@ extern void wremapall(color *pal1, Common::Bitmap *picc, color *pal2);
 // archive attributes to search for - al_findfirst breaks with 0
 #define FA_SEARCH -1
 
+} // namespace AGS3
+
 #endif


Commit: d8e471b03c31e646b675e1ea7b417f8ec6b7673c
    https://github.com/scummvm/scummvm/commit/d8e471b03c31e646b675e1ea7b417f8ec6b7673c
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Changing Common namespace to Shared

Changed paths:
    engines/ags/engine/ac/asset_helper.h
    engines/ags/engine/ac/audiochannel.cpp
    engines/ags/engine/ac/button.cpp
    engines/ags/engine/ac/button.h
    engines/ags/engine/ac/character.cpp
    engines/ags/engine/ac/character.h
    engines/ags/engine/ac/charactercache.h
    engines/ags/engine/ac/characterextras.cpp
    engines/ags/engine/ac/characterextras.h
    engines/ags/engine/ac/characterinfo_engine.cpp
    engines/ags/engine/ac/dialog.cpp
    engines/ags/engine/ac/display.cpp
    engines/ags/engine/ac/display.h
    engines/ags/engine/ac/draw.cpp
    engines/ags/engine/ac/draw.h
    engines/ags/engine/ac/draw_software.cpp
    engines/ags/engine/ac/draw_software.h
    engines/ags/engine/ac/drawingsurface.cpp
    engines/ags/engine/ac/dynamicsprite.cpp
    engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp
    engines/ags/engine/ac/dynobj/cc_dynamicobject.cpp
    engines/ags/engine/ac/dynobj/cc_dynamicobject.h
    engines/ags/engine/ac/dynobj/cc_guiobject.cpp
    engines/ags/engine/ac/dynobj/managedobjectpool.cpp
    engines/ags/engine/ac/dynobj/managedobjectpool.h
    engines/ags/engine/ac/dynobj/scriptcamera.cpp
    engines/ags/engine/ac/dynobj/scriptdict.h
    engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp
    engines/ags/engine/ac/dynobj/scriptdrawingsurface.h
    engines/ags/engine/ac/dynobj/scriptset.h
    engines/ags/engine/ac/dynobj/scriptviewport.cpp
    engines/ags/engine/ac/event.cpp
    engines/ags/engine/ac/file.cpp
    engines/ags/engine/ac/file.h
    engines/ags/engine/ac/game.cpp
    engines/ags/engine/ac/game.h
    engines/ags/engine/ac/gamesetup.h
    engines/ags/engine/ac/gamestate.cpp
    engines/ags/engine/ac/gamestate.h
    engines/ags/engine/ac/global_audio.cpp
    engines/ags/engine/ac/global_button.cpp
    engines/ags/engine/ac/global_character.cpp
    engines/ags/engine/ac/global_debug.cpp
    engines/ags/engine/ac/global_debug.h
    engines/ags/engine/ac/global_dialog.cpp
    engines/ags/engine/ac/global_display.cpp
    engines/ags/engine/ac/global_drawingsurface.cpp
    engines/ags/engine/ac/global_dynamicsprite.cpp
    engines/ags/engine/ac/global_file.cpp
    engines/ags/engine/ac/global_file.h
    engines/ags/engine/ac/global_game.cpp
    engines/ags/engine/ac/global_gui.cpp
    engines/ags/engine/ac/global_hotspot.cpp
    engines/ags/engine/ac/global_inventoryitem.cpp
    engines/ags/engine/ac/global_label.cpp
    engines/ags/engine/ac/global_object.cpp
    engines/ags/engine/ac/global_object.h
    engines/ags/engine/ac/global_overlay.cpp
    engines/ags/engine/ac/global_region.cpp
    engines/ags/engine/ac/global_room.cpp
    engines/ags/engine/ac/global_screen.cpp
    engines/ags/engine/ac/global_slider.cpp
    engines/ags/engine/ac/global_textbox.cpp
    engines/ags/engine/ac/global_translation.cpp
    engines/ags/engine/ac/global_walkablearea.cpp
    engines/ags/engine/ac/gui.cpp
    engines/ags/engine/ac/gui.h
    engines/ags/engine/ac/guicontrol.cpp
    engines/ags/engine/ac/guicontrol.h
    engines/ags/engine/ac/guiinv.cpp
    engines/ags/engine/ac/hotspot.cpp
    engines/ags/engine/ac/invwindow.cpp
    engines/ags/engine/ac/invwindow.h
    engines/ags/engine/ac/label.h
    engines/ags/engine/ac/listbox.cpp
    engines/ags/engine/ac/listbox.h
    engines/ags/engine/ac/mouse.cpp
    engines/ags/engine/ac/movelist.cpp
    engines/ags/engine/ac/movelist.h
    engines/ags/engine/ac/object.cpp
    engines/ags/engine/ac/object.h
    engines/ags/engine/ac/overlay.cpp
    engines/ags/engine/ac/overlay.h
    engines/ags/engine/ac/parser.cpp
    engines/ags/engine/ac/path_helper.h
    engines/ags/engine/ac/properties.cpp
    engines/ags/engine/ac/properties.h
    engines/ags/engine/ac/region.cpp
    engines/ags/engine/ac/richgamemedia.cpp
    engines/ags/engine/ac/richgamemedia.h
    engines/ags/engine/ac/room.cpp
    engines/ags/engine/ac/room.h
    engines/ags/engine/ac/roomobject.cpp
    engines/ags/engine/ac/roomobject.h
    engines/ags/engine/ac/roomstatus.cpp
    engines/ags/engine/ac/roomstatus.h
    engines/ags/engine/ac/route_finder.cpp
    engines/ags/engine/ac/route_finder.h
    engines/ags/engine/ac/route_finder_impl.cpp
    engines/ags/engine/ac/route_finder_impl.h
    engines/ags/engine/ac/route_finder_impl_legacy.cpp
    engines/ags/engine/ac/route_finder_impl_legacy.h
    engines/ags/engine/ac/screen.cpp
    engines/ags/engine/ac/screen.h
    engines/ags/engine/ac/screenoverlay.cpp
    engines/ags/engine/ac/screenoverlay.h
    engines/ags/engine/ac/slider.h
    engines/ags/engine/ac/sprite.cpp
    engines/ags/engine/ac/spritelistentry.h
    engines/ags/engine/ac/sys_events.cpp
    engines/ags/engine/ac/system.cpp
    engines/ags/engine/ac/textbox.h
    engines/ags/engine/ac/translation.cpp
    engines/ags/engine/ac/translation.h
    engines/ags/engine/ac/viewframe.cpp
    engines/ags/engine/ac/viewframe.h
    engines/ags/engine/ac/viewport_script.cpp
    engines/ags/engine/ac/walkablearea.cpp
    engines/ags/engine/ac/walkbehind.cpp
    engines/ags/engine/debugging/consoleoutputtarget.h
    engines/ags/engine/debugging/debug.cpp
    engines/ags/engine/debugging/debug_log.h
    engines/ags/engine/debugging/debugger.h
    engines/ags/engine/debugging/filebasedagsdebugger.cpp
    engines/ags/engine/debugging/logfile.cpp
    engines/ags/engine/debugging/logfile.h
    engines/ags/engine/debugging/messagebuffer.cpp
    engines/ags/engine/debugging/messagebuffer.h
    engines/ags/engine/device/mousew32.cpp
    engines/ags/engine/device/mousew32.h
    engines/ags/engine/game/game_init.cpp
    engines/ags/engine/game/game_init.h
    engines/ags/engine/game/savegame.cpp
    engines/ags/engine/game/savegame.h
    engines/ags/engine/game/savegame_components.cpp
    engines/ags/engine/game/savegame_components.h
    engines/ags/engine/game/savegame_internal.h
    engines/ags/engine/game/viewport.cpp
    engines/ags/engine/gfx/ali3dogl.cpp
    engines/ags/engine/gfx/ali3dsw.cpp
    engines/ags/engine/gfx/ali3dsw.h
    engines/ags/engine/gfx/gfx_util.cpp
    engines/ags/engine/gfx/gfxdriverbase.cpp
    engines/ags/engine/gfx/gfxfilter_allegro.cpp
    engines/ags/engine/gfx/gfxfilter_hqx.cpp
    engines/ags/engine/gfx/graphicsdriver.h
    engines/ags/engine/gui/animatingguibutton.cpp
    engines/ags/engine/gui/animatingguibutton.h
    engines/ags/engine/gui/cscidialog.cpp
    engines/ags/engine/gui/gui_engine.cpp
    engines/ags/engine/gui/guidialog.cpp
    engines/ags/engine/gui/guidialog.h
    engines/ags/engine/gui/guidialogdefines.h
    engines/ags/engine/gui/mylabel.cpp
    engines/ags/engine/gui/mylistbox.cpp
    engines/ags/engine/gui/mypushbutton.cpp
    engines/ags/engine/gui/mytextbox.cpp
    engines/ags/engine/main/config.cpp
    engines/ags/engine/main/config.h
    engines/ags/engine/main/engine.cpp
    engines/ags/engine/main/engine.h
    engines/ags/engine/main/engine_setup.cpp
    engines/ags/engine/main/game_file.cpp
    engines/ags/engine/main/game_file.h
    engines/ags/engine/main/game_run.cpp
    engines/ags/engine/main/game_start.cpp
    engines/ags/engine/main/graphics_mode.cpp
    engines/ags/engine/main/graphics_mode.h
    engines/ags/engine/main/main.cpp
    engines/ags/engine/main/main.h
    engines/ags/engine/main/quit.cpp
    engines/ags/engine/main/update.cpp
    engines/ags/engine/media/audio/ambientsound.cpp
    engines/ags/engine/media/audio/ambientsound.h
    engines/ags/engine/media/audio/audio.cpp
    engines/ags/engine/media/audio/queuedaudioitem.cpp
    engines/ags/engine/media/audio/queuedaudioitem.h
    engines/ags/engine/media/audio/soundcache.cpp
    engines/ags/engine/media/video/video.cpp
    engines/ags/engine/platform/android/acpland.cpp
    engines/ags/engine/platform/base/agsplatformdriver.cpp
    engines/ags/engine/platform/base/agsplatformdriver.h
    engines/ags/engine/platform/ios/acplios.cpp
    engines/ags/engine/platform/linux/acpllnx.cpp
    engines/ags/engine/platform/osx/acplmac.cpp
    engines/ags/engine/platform/windows/acplwin.cpp
    engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
    engines/ags/engine/platform/windows/gfx/ali3dd3d.h
    engines/ags/engine/platform/windows/media/video/acwavi.cpp
    engines/ags/engine/platform/windows/setup/winsetup.cpp
    engines/ags/engine/platform/windows/setup/winsetup.h
    engines/ags/engine/platform/windows/win_ex_handling.cpp
    engines/ags/engine/platform/windows/win_ex_handling.h
    engines/ags/engine/plugin/agsplugin.cpp
    engines/ags/engine/plugin/plugin_engine.h
    engines/ags/engine/script/cc_instance.cpp
    engines/ags/engine/script/runtimescriptvalue.cpp
    engines/ags/engine/script/runtimescriptvalue.h
    engines/ags/engine/script/script.cpp
    engines/ags/engine/script/script.h
    engines/ags/engine/script/script_api.cpp
    engines/ags/engine/script/script_engine.cpp
    engines/ags/engine/script/script_runtime.h
    engines/ags/engine/script/systemimports.h
    engines/ags/engine/util/library.h
    engines/ags/engine/util/library_dummy.h
    engines/ags/engine/util/library_posix.h
    engines/ags/engine/util/library_psp.h
    engines/ags/engine/util/library_windows.h
    engines/ags/engine/util/mutex_base.h
    engines/ags/shared/ac/audiocliptype.cpp
    engines/ags/shared/ac/audiocliptype.h
    engines/ags/shared/ac/characterinfo.cpp
    engines/ags/shared/ac/characterinfo.h
    engines/ags/shared/ac/common.cpp
    engines/ags/shared/ac/dialogtopic.cpp
    engines/ags/shared/ac/dialogtopic.h
    engines/ags/shared/ac/dynobj/scriptaudioclip.cpp
    engines/ags/shared/ac/dynobj/scriptaudioclip.h
    engines/ags/shared/ac/gamesetupstruct.cpp
    engines/ags/shared/ac/gamesetupstruct.h
    engines/ags/shared/ac/gamesetupstructbase.cpp
    engines/ags/shared/ac/gamesetupstructbase.h
    engines/ags/shared/ac/inventoryiteminfo.cpp
    engines/ags/shared/ac/inventoryiteminfo.h
    engines/ags/shared/ac/mousecursor.cpp
    engines/ags/shared/ac/mousecursor.h
    engines/ags/shared/ac/spritecache.cpp
    engines/ags/shared/ac/spritecache.h
    engines/ags/shared/ac/view.cpp
    engines/ags/shared/ac/view.h
    engines/ags/shared/ac/wordsdictionary.cpp
    engines/ags/shared/ac/wordsdictionary.h
    engines/ags/shared/api/stream_api.h
    engines/ags/shared/core/asset.cpp
    engines/ags/shared/core/asset.h
    engines/ags/shared/core/assetmanager.cpp
    engines/ags/shared/core/assetmanager.h
    engines/ags/shared/debugging/debugmanager.cpp
    engines/ags/shared/debugging/debugmanager.h
    engines/ags/shared/debugging/out.h
    engines/ags/shared/debugging/outputhandler.h
    engines/ags/shared/font/fonts.cpp
    engines/ags/shared/font/fonts.h
    engines/ags/shared/font/ttffontrenderer.cpp
    engines/ags/shared/font/wfnfont.cpp
    engines/ags/shared/font/wfnfont.h
    engines/ags/shared/font/wfnfontrenderer.cpp
    engines/ags/shared/game/customproperties.cpp
    engines/ags/shared/game/customproperties.h
    engines/ags/shared/game/interactions.cpp
    engines/ags/shared/game/interactions.h
    engines/ags/shared/game/main_game_file.cpp
    engines/ags/shared/game/main_game_file.h
    engines/ags/shared/game/plugininfo.h
    engines/ags/shared/game/room_file.cpp
    engines/ags/shared/game/room_file.h
    engines/ags/shared/game/room_file_deprecated.cpp
    engines/ags/shared/game/roomstruct.cpp
    engines/ags/shared/game/roomstruct.h
    engines/ags/shared/gfx/allegrobitmap.cpp
    engines/ags/shared/gfx/allegrobitmap.h
    engines/ags/shared/gfx/bitmap.cpp
    engines/ags/shared/gfx/bitmap.h
    engines/ags/shared/gfx/gfx_def.h
    engines/ags/shared/gui/guibutton.cpp
    engines/ags/shared/gui/guibutton.h
    engines/ags/shared/gui/guidefines.h
    engines/ags/shared/gui/guiinv.cpp
    engines/ags/shared/gui/guiinv.h
    engines/ags/shared/gui/guilabel.cpp
    engines/ags/shared/gui/guilabel.h
    engines/ags/shared/gui/guilistbox.cpp
    engines/ags/shared/gui/guilistbox.h
    engines/ags/shared/gui/guimain.cpp
    engines/ags/shared/gui/guimain.h
    engines/ags/shared/gui/guiobject.cpp
    engines/ags/shared/gui/guiobject.h
    engines/ags/shared/gui/guislider.cpp
    engines/ags/shared/gui/guislider.h
    engines/ags/shared/gui/guitextbox.cpp
    engines/ags/shared/gui/guitextbox.h
    engines/ags/shared/script/cc_error.cpp
    engines/ags/shared/script/cc_error.h
    engines/ags/shared/script/cc_script.cpp
    engines/ags/shared/script/cc_script.h
    engines/ags/shared/util/alignedstream.cpp
    engines/ags/shared/util/alignedstream.h
    engines/ags/shared/util/bbop.h
    engines/ags/shared/util/bufferedstream.cpp
    engines/ags/shared/util/bufferedstream.h
    engines/ags/shared/util/compress.cpp
    engines/ags/shared/util/compress.h
    engines/ags/shared/util/datastream.cpp
    engines/ags/shared/util/datastream.h
    engines/ags/shared/util/directory.cpp
    engines/ags/shared/util/directory.h
    engines/ags/shared/util/error.h
    engines/ags/shared/util/file.cpp
    engines/ags/shared/util/file.h
    engines/ags/shared/util/filestream.cpp
    engines/ags/shared/util/filestream.h
    engines/ags/shared/util/geometry.cpp
    engines/ags/shared/util/geometry.h
    engines/ags/shared/util/ini_util.cpp
    engines/ags/shared/util/ini_util.h
    engines/ags/shared/util/inifile.cpp
    engines/ags/shared/util/inifile.h
    engines/ags/shared/util/lzw.cpp
    engines/ags/shared/util/lzw.h
    engines/ags/shared/util/math.h
    engines/ags/shared/util/memory.h
    engines/ags/shared/util/misc.cpp
    engines/ags/shared/util/misc.h
    engines/ags/shared/util/multifilelib.h
    engines/ags/shared/util/mutifilelib.cpp
    engines/ags/shared/util/path.cpp
    engines/ags/shared/util/path.h
    engines/ags/shared/util/proxystream.cpp
    engines/ags/shared/util/proxystream.h
    engines/ags/shared/util/stream.cpp
    engines/ags/shared/util/stream.h
    engines/ags/shared/util/string.cpp
    engines/ags/shared/util/string.h
    engines/ags/shared/util/string_types.h
    engines/ags/shared/util/string_utils.cpp
    engines/ags/shared/util/string_utils.h
    engines/ags/shared/util/textreader.h
    engines/ags/shared/util/textstreamreader.cpp
    engines/ags/shared/util/textstreamreader.h
    engines/ags/shared/util/textstreamwriter.cpp
    engines/ags/shared/util/textstreamwriter.h
    engines/ags/shared/util/textwriter.h
    engines/ags/shared/util/version.cpp
    engines/ags/shared/util/version.h
    engines/ags/shared/util/wgt2allg.cpp
    engines/ags/shared/util/wgt2allg.h


diff --git a/engines/ags/engine/ac/asset_helper.h b/engines/ags/engine/ac/asset_helper.h
index eb5c0e4ffc..f617444960 100644
--- a/engines/ags/engine/ac/asset_helper.h
+++ b/engines/ags/engine/ac/asset_helper.h
@@ -36,12 +36,12 @@
 namespace AGS3 {
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 }
 }
-using AGS::Common::Stream;
-using AGS::Common::String;
+using AGS::Shared::Stream;
+using AGS::Shared::String;
 
 // Looks for valid asset library everywhere and returns path, or empty string if failed
 String  find_assetlib(const String &filename);
diff --git a/engines/ags/engine/ac/audiochannel.cpp b/engines/ags/engine/ac/audiochannel.cpp
index e3898f35a6..e793a87cf6 100644
--- a/engines/ags/engine/ac/audiochannel.cpp
+++ b/engines/ags/engine/ac/audiochannel.cpp
@@ -29,7 +29,7 @@
 #include "script/runtimescriptvalue.h"
 #include "media/audio/audio_system.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern GameState play;
 extern RoomStruct thisroom;
diff --git a/engines/ags/engine/ac/button.cpp b/engines/ags/engine/ac/button.cpp
index bf61dd5834..91f24fa8c6 100644
--- a/engines/ags/engine/ac/button.cpp
+++ b/engines/ags/engine/ac/button.cpp
@@ -32,7 +32,7 @@
 #include "gui/animatingguibutton.h"
 #include "gui/guimain.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern GameSetupStruct game;
 extern ViewStruct *views;
diff --git a/engines/ags/engine/ac/button.h b/engines/ags/engine/ac/button.h
index 65ef6a42d1..f8293b4056 100644
--- a/engines/ags/engine/ac/button.h
+++ b/engines/ags/engine/ac/button.h
@@ -27,7 +27,7 @@
 
 namespace AGS3 {
 
-using AGS::Common::GUIButton;
+using AGS::Shared::GUIButton;
 
 void        Button_Animate(GUIButton *butt, int view, int loop, int speed, int repeat);
 const char *Button_GetText_New(GUIButton *butt);
diff --git a/engines/ags/engine/ac/character.cpp b/engines/ags/engine/ac/character.cpp
index 347eb922d2..d1ef4162f6 100644
--- a/engines/ags/engine/ac/character.cpp
+++ b/engines/ags/engine/ac/character.cpp
@@ -71,7 +71,7 @@
 #include "media/audio/audio_system.h"
 #include "ac/movelist.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern GameSetupStruct game;
 extern int displayed_room, starting_room;
diff --git a/engines/ags/engine/ac/character.h b/engines/ags/engine/ac/character.h
index 9039aaf9ad..c275cfd237 100644
--- a/engines/ags/engine/ac/character.h
+++ b/engines/ags/engine/ac/character.h
@@ -166,7 +166,7 @@ int     Character_GetSpeakingFrame(CharacterInfo *chaa);
 
 struct MoveList;
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Bitmap;
 }
 }
diff --git a/engines/ags/engine/ac/charactercache.h b/engines/ags/engine/ac/charactercache.h
index ec6564d113..4d44bfeffd 100644
--- a/engines/ags/engine/ac/charactercache.h
+++ b/engines/ags/engine/ac/charactercache.h
@@ -26,7 +26,7 @@
 namespace AGS3 {
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Bitmap;
 }
 }
diff --git a/engines/ags/engine/ac/characterextras.cpp b/engines/ags/engine/ac/characterextras.cpp
index c76d794c26..42c48cb39c 100644
--- a/engines/ags/engine/ac/characterextras.cpp
+++ b/engines/ags/engine/ac/characterextras.cpp
@@ -23,7 +23,7 @@
 #include "ac/characterextras.h"
 #include "util/stream.h"
 
-using AGS::Common::Stream;
+using AGS::Shared::Stream;
 
 void CharacterExtras::ReadFromFile(Stream *in) {
 	in->ReadArrayOfInt16(invorder, MAX_INVORDER);
diff --git a/engines/ags/engine/ac/characterextras.h b/engines/ags/engine/ac/characterextras.h
index 3d08847df3..a94ef18b43 100644
--- a/engines/ags/engine/ac/characterextras.h
+++ b/engines/ags/engine/ac/characterextras.h
@@ -29,7 +29,7 @@ namespace AGS3 {
 
 // Forward declaration
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 }
 }
diff --git a/engines/ags/engine/ac/characterinfo_engine.cpp b/engines/ags/engine/ac/characterinfo_engine.cpp
index 44ff6b9696..d404c382a8 100644
--- a/engines/ags/engine/ac/characterinfo_engine.cpp
+++ b/engines/ags/engine/ac/characterinfo_engine.cpp
@@ -35,7 +35,7 @@
 #include "main/update.h"
 #include "media/audio/audio_system.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern ViewStruct *views;
 extern GameSetupStruct game;
diff --git a/engines/ags/engine/ac/dialog.cpp b/engines/ags/engine/ac/dialog.cpp
index 5b2a85f675..c5f60cc601 100644
--- a/engines/ags/engine/ac/dialog.cpp
+++ b/engines/ags/engine/ac/dialog.cpp
@@ -60,7 +60,7 @@
 #include "ac/mouse.h"
 #include "media/audio/audio_system.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern GameSetupStruct game;
 extern GameState play;
diff --git a/engines/ags/engine/ac/display.cpp b/engines/ags/engine/ac/display.cpp
index ddb918fae7..20255b1e92 100644
--- a/engines/ags/engine/ac/display.cpp
+++ b/engines/ags/engine/ac/display.cpp
@@ -55,8 +55,8 @@
 #include "media/audio/audio_system.h"
 #include "ac/timer.h"
 
-using namespace AGS::Common;
-using namespace AGS::Common::BitmapHelper;
+using namespace AGS::Shared;
+using namespace AGS::Shared::BitmapHelper;
 
 extern GameState play;
 extern GameSetupStruct game;
diff --git a/engines/ags/engine/ac/display.h b/engines/ags/engine/ac/display.h
index 35b5f7f13c..44a0df2479 100644
--- a/engines/ags/engine/ac/display.h
+++ b/engines/ags/engine/ac/display.h
@@ -27,7 +27,7 @@
 
 namespace AGS3 {
 
-using AGS::Common::GUIMain;
+using AGS::Shared::GUIMain;
 
 // options for 'disp_type' parameter
 #define DISPLAYTEXT_SPEECH        0
diff --git a/engines/ags/engine/ac/draw.cpp b/engines/ags/engine/ac/draw.cpp
index e5e80f3ac5..b6ed493c2d 100644
--- a/engines/ags/engine/ac/draw.cpp
+++ b/engines/ags/engine/ac/draw.cpp
@@ -71,7 +71,7 @@
 #include "media/audio/audio_system.h"
 #include "ac/game.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 #if AGS_PLATFORM_OS_ANDROID
diff --git a/engines/ags/engine/ac/draw.h b/engines/ags/engine/ac/draw.h
index 2613f34357..e100230c9b 100644
--- a/engines/ags/engine/ac/draw.h
+++ b/engines/ags/engine/ac/draw.h
@@ -32,7 +32,7 @@
 namespace AGS3 {
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Bitmap;
 typedef std::shared_ptr<Common::Bitmap> PBitmap;
 }
diff --git a/engines/ags/engine/ac/draw_software.cpp b/engines/ags/engine/ac/draw_software.cpp
index fb62af5e06..46bb1a1298 100644
--- a/engines/ags/engine/ac/draw_software.cpp
+++ b/engines/ags/engine/ac/draw_software.cpp
@@ -52,7 +52,7 @@
 #include "gfx/bitmap.h"
 #include "util/scaling.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 // TODO: choose these values depending on game resolution?
diff --git a/engines/ags/engine/ac/draw_software.h b/engines/ags/engine/ac/draw_software.h
index 8d8d20fd4b..aee7079dde 100644
--- a/engines/ags/engine/ac/draw_software.h
+++ b/engines/ags/engine/ac/draw_software.h
@@ -51,10 +51,10 @@ void invalidate_all_rects();
 void invalidate_all_camera_rects(int view_index);
 void invalidate_rect_ds(int x1, int y1, int x2, int y2, bool in_room);
 // Paints the black screen background in the regions marked as dirty
-void update_black_invreg_and_reset(AGS::Common::Bitmap *ds);
+void update_black_invreg_and_reset(AGS::Shared::Bitmap *ds);
 // Copies the room regions marked as dirty from source (src) to destination (ds) with the given offset (x, y)
 // no_transform flag tells the system that the regions should be plain copied to the ds.
-void update_room_invreg_and_reset(int view_index, AGS::Common::Bitmap *ds, AGS::Common::Bitmap *src, bool no_transform);
+void update_room_invreg_and_reset(int view_index, AGS::Shared::Bitmap *ds, AGS::Shared::Bitmap *src, bool no_transform);
 
 } // namespace AGS3
 
diff --git a/engines/ags/engine/ac/drawingsurface.cpp b/engines/ags/engine/ac/drawingsurface.cpp
index 329e312974..c6a8cfacd2 100644
--- a/engines/ags/engine/ac/drawingsurface.cpp
+++ b/engines/ags/engine/ac/drawingsurface.cpp
@@ -42,7 +42,7 @@
 #include "gfx/gfx_def.h"
 #include "gfx/gfx_util.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern GameSetupStruct game;
diff --git a/engines/ags/engine/ac/dynamicsprite.cpp b/engines/ags/engine/ac/dynamicsprite.cpp
index a6143bf6ae..ef798801bf 100644
--- a/engines/ags/engine/ac/dynamicsprite.cpp
+++ b/engines/ags/engine/ac/dynamicsprite.cpp
@@ -41,7 +41,7 @@
 #include "gfx/graphicsdriver.h"
 #include "script/runtimescriptvalue.h"
 
-using namespace Common;
+using namespace Shared;
 using namespace Engine;
 
 extern GameSetupStruct game;
diff --git a/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp b/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp
index ea692ed531..bdc815dd96 100644
--- a/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp
@@ -26,7 +26,7 @@
 #include "ac/common.h"               // quit()
 #include "util/bbop.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 // *** The script serialization routines for built-in types
 
diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicobject.cpp b/engines/ags/engine/ac/dynobj/cc_dynamicobject.cpp
index 09fb15af7c..9794f02646 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicobject.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicobject.cpp
@@ -45,7 +45,7 @@
 #include "script/script_common.h"
 #include "util/stream.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 ICCStringClass *stringClassImpl = nullptr;
 
diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicobject.h b/engines/ags/engine/ac/dynobj/cc_dynamicobject.h
index 42394dc11c..9fc61a4518 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicobject.h
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicobject.h
@@ -36,7 +36,7 @@ namespace AGS3 {
 
 // Forward declaration
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 }
 }
diff --git a/engines/ags/engine/ac/dynobj/cc_guiobject.cpp b/engines/ags/engine/ac/dynobj/cc_guiobject.cpp
index df0e23233d..6898ffb963 100644
--- a/engines/ags/engine/ac/dynobj/cc_guiobject.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_guiobject.cpp
@@ -25,7 +25,7 @@
 #include "gui/guimain.h"
 #include "gui/guiobject.h"
 
-using AGS::Common::GUIObject;
+using AGS::Shared::GUIObject;
 
 // return the type name of the object
 const char *CCGUIObject::GetType() {
diff --git a/engines/ags/engine/ac/dynobj/managedobjectpool.cpp b/engines/ags/engine/ac/dynobj/managedobjectpool.cpp
index a5ab383717..f6e837f52d 100644
--- a/engines/ags/engine/ac/dynobj/managedobjectpool.cpp
+++ b/engines/ags/engine/ac/dynobj/managedobjectpool.cpp
@@ -30,7 +30,7 @@
 #include "script/script_common.h"
 #include "util/stream.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 const auto OBJECT_CACHE_MAGIC_NUMBER = 0xa30b;
 const auto SERIALIZE_BUFFER_SIZE = 10240;
diff --git a/engines/ags/engine/ac/dynobj/managedobjectpool.h b/engines/ags/engine/ac/dynobj/managedobjectpool.h
index 654dcce979..e40ead0ac2 100644
--- a/engines/ags/engine/ac/dynobj/managedobjectpool.h
+++ b/engines/ags/engine/ac/dynobj/managedobjectpool.h
@@ -32,7 +32,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 } // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/engine/ac/dynobj/scriptcamera.cpp b/engines/ags/engine/ac/dynobj/scriptcamera.cpp
index 138464e29c..e8d434ee68 100644
--- a/engines/ags/engine/ac/dynobj/scriptcamera.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptcamera.cpp
@@ -24,7 +24,7 @@
 #include "ac/gamestate.h"
 #include "util/bbop.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 ScriptCamera::ScriptCamera(int id) : _id(id) {}
 
diff --git a/engines/ags/engine/ac/dynobj/scriptdict.h b/engines/ags/engine/ac/dynobj/scriptdict.h
index 4677d33828..ce1fe13b15 100644
--- a/engines/ags/engine/ac/dynobj/scriptdict.h
+++ b/engines/ags/engine/ac/dynobj/scriptdict.h
@@ -45,7 +45,7 @@
 
 namespace AGS3 {
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 class ScriptDictBase : public AGSCCDynamicObject {
 public:
diff --git a/engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp b/engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp
index 08e1bbc591..6b2e240239 100644
--- a/engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp
@@ -30,7 +30,7 @@
 #include "game/roomstruct.h"
 #include "gfx/bitmap.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern RoomStruct thisroom;
 extern SpriteCache spriteset;
diff --git a/engines/ags/engine/ac/dynobj/scriptdrawingsurface.h b/engines/ags/engine/ac/dynobj/scriptdrawingsurface.h
index c8033101bc..9d224c0bab 100644
--- a/engines/ags/engine/ac/dynobj/scriptdrawingsurface.h
+++ b/engines/ags/engine/ac/dynobj/scriptdrawingsurface.h
@@ -29,7 +29,7 @@
 namespace AGS3 {
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Bitmap;
 } // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/engine/ac/dynobj/scriptset.h b/engines/ags/engine/ac/dynobj/scriptset.h
index cdf83af7cc..ca7ecbc154 100644
--- a/engines/ags/engine/ac/dynobj/scriptset.h
+++ b/engines/ags/engine/ac/dynobj/scriptset.h
@@ -44,7 +44,7 @@
 
 namespace AGS3 {
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 class ScriptSetBase : public AGSCCDynamicObject {
 public:
diff --git a/engines/ags/engine/ac/dynobj/scriptviewport.cpp b/engines/ags/engine/ac/dynobj/scriptviewport.cpp
index 54bb03e849..c090db39bd 100644
--- a/engines/ags/engine/ac/dynobj/scriptviewport.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptviewport.cpp
@@ -24,7 +24,7 @@
 #include "ac/gamestate.h"
 #include "util/bbop.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 ScriptViewport::ScriptViewport(int id) : _id(id) {}
 
diff --git a/engines/ags/engine/ac/event.cpp b/engines/ags/engine/ac/event.cpp
index e977adde54..fec319880e 100644
--- a/engines/ags/engine/ac/event.cpp
+++ b/engines/ags/engine/ac/event.cpp
@@ -42,7 +42,7 @@
 #include "media/audio/audio_system.h"
 #include "ac/timer.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern GameSetupStruct game;
diff --git a/engines/ags/engine/ac/file.cpp b/engines/ags/engine/ac/file.cpp
index d6ae484206..c1128f960f 100644
--- a/engines/ags/engine/ac/file.cpp
+++ b/engines/ags/engine/ac/file.cpp
@@ -46,7 +46,7 @@
 #include "util/string.h"
 #include "util/string_utils.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern GameSetup usetup;
 extern GameSetupStruct game;
diff --git a/engines/ags/engine/ac/file.h b/engines/ags/engine/ac/file.h
index 2c3b4feede..c3e52dfbef 100644
--- a/engines/ags/engine/ac/file.h
+++ b/engines/ags/engine/ac/file.h
@@ -34,7 +34,7 @@
 
 namespace AGS3 {
 
-using AGS::Common::Stream;
+using AGS::Shared::Stream;
 
 int     File_Exists(const char *fnmm);
 int     File_Delete(const char *fnmm);
diff --git a/engines/ags/engine/ac/game.cpp b/engines/ags/engine/ac/game.cpp
index 5fc5e57d00..f71b1a9309 100644
--- a/engines/ags/engine/ac/game.cpp
+++ b/engines/ags/engine/ac/game.cpp
@@ -98,7 +98,7 @@
 #include "util/string_utils.h"
 #include "ac/keycode.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern ScriptAudioChannel scrAudioChannel[MAX_SOUND_CHANNELS + 1];
diff --git a/engines/ags/engine/ac/game.h b/engines/ags/engine/ac/game.h
index a977f74421..15cb70ffe3 100644
--- a/engines/ags/engine/ac/game.h
+++ b/engines/ags/engine/ac/game.h
@@ -37,7 +37,7 @@ namespace AGS3 {
 
 // Forward declaration
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Bitmap;
 class Stream;
 } // namespace Shared
diff --git a/engines/ags/engine/ac/gamesetup.h b/engines/ags/engine/ac/gamesetup.h
index 45c3821132..5f1f48ad7c 100644
--- a/engines/ags/engine/ac/gamesetup.h
+++ b/engines/ags/engine/ac/gamesetup.h
@@ -43,7 +43,7 @@ enum MouseSpeedDef {
 	kNumMouseSpeedDefs
 };
 
-using AGS::Common::String;
+using AGS::Shared::String;
 
 // TODO: reconsider the purpose of this struct.
 // Earlier I was trying to remove the uses of this struct from the engine
diff --git a/engines/ags/engine/ac/gamestate.cpp b/engines/ags/engine/ac/gamestate.cpp
index 2837ec9202..73c0d7cf93 100644
--- a/engines/ags/engine/ac/gamestate.cpp
+++ b/engines/ags/engine/ac/gamestate.cpp
@@ -39,7 +39,7 @@
 #include "util/alignedstream.h"
 #include "util/string_utils.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern GameSetupStruct game;
diff --git a/engines/ags/engine/ac/gamestate.h b/engines/ags/engine/ac/gamestate.h
index acf3d48452..617153b51b 100644
--- a/engines/ags/engine/ac/gamestate.h
+++ b/engines/ags/engine/ac/gamestate.h
@@ -40,7 +40,7 @@ namespace AGS3 {
 
 // Forward declaration
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Bitmap;
 class Stream;
 typedef std::shared_ptr<Bitmap> PBitmap;
@@ -224,14 +224,14 @@ struct GameState {
 	short temporarily_turned_off_character;  // Hide Player Charactr ticked
 	short inv_backwards_compatibility;
 	int *gui_draw_order;
-	std::vector<AGS::Common::String> do_once_tokens;
+	std::vector<AGS::Shared::String> do_once_tokens;
 	int   text_min_display_time_ms;
 	int   ignore_user_input_after_text_timeout_ms;
 	int   default_audio_type_volumes[MAX_AUDIO_TYPES];
 
 	// Dynamic custom property values for characters and items
-	std::vector<AGS::Common::StringIMap> charProps;
-	AGS::Common::StringIMap invProps[MAX_INV];
+	std::vector<AGS::Shared::StringIMap> charProps;
+	AGS::Shared::StringIMap invProps[MAX_INV];
 
 	// Dynamic speech state
 	//
diff --git a/engines/ags/engine/ac/global_audio.cpp b/engines/ags/engine/ac/global_audio.cpp
index b9154a9686..5f83560d30 100644
--- a/engines/ags/engine/ac/global_audio.cpp
+++ b/engines/ags/engine/ac/global_audio.cpp
@@ -36,7 +36,7 @@
 #include "ac/timer.h"
 #include "util/string_compat.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern GameSetup usetup;
 extern GameState play;
diff --git a/engines/ags/engine/ac/global_button.cpp b/engines/ags/engine/ac/global_button.cpp
index 26a46dad62..f6aa71a5b2 100644
--- a/engines/ags/engine/ac/global_button.cpp
+++ b/engines/ags/engine/ac/global_button.cpp
@@ -28,7 +28,7 @@
 #include "gui/guimain.h"
 #include "gui/guibutton.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern GameSetupStruct game;
 
diff --git a/engines/ags/engine/ac/global_character.cpp b/engines/ags/engine/ac/global_character.cpp
index 874aa92d24..389efea22d 100644
--- a/engines/ags/engine/ac/global_character.cpp
+++ b/engines/ags/engine/ac/global_character.cpp
@@ -47,7 +47,7 @@
 #include "main/game_run.h"
 #include "script/script.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 
 extern GameSetupStruct game;
diff --git a/engines/ags/engine/ac/global_debug.cpp b/engines/ags/engine/ac/global_debug.cpp
index 4131c1834f..be28d50e1f 100644
--- a/engines/ags/engine/ac/global_debug.cpp
+++ b/engines/ags/engine/ac/global_debug.cpp
@@ -47,7 +47,7 @@
 #include "gfx/graphicsdriver.h"
 #include "main/graphics_mode.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern GameSetupStruct game;
diff --git a/engines/ags/engine/ac/global_debug.h b/engines/ags/engine/ac/global_debug.h
index cf2bc81a2f..bd60f9340b 100644
--- a/engines/ags/engine/ac/global_debug.h
+++ b/engines/ags/engine/ac/global_debug.h
@@ -28,7 +28,7 @@
 
 namespace AGS3 {
 
-AGS::Common::String GetRuntimeInfo();
+AGS::Shared::String GetRuntimeInfo();
 void script_debug(int cmdd, int dataa);
 
 } // namespace AGS3
diff --git a/engines/ags/engine/ac/global_dialog.cpp b/engines/ags/engine/ac/global_dialog.cpp
index 0acc1f5fee..ff9240615b 100644
--- a/engines/ags/engine/ac/global_dialog.cpp
+++ b/engines/ags/engine/ac/global_dialog.cpp
@@ -31,7 +31,7 @@
 #include "debug/out.h"
 #include "script/script.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern GameSetupStruct game;
 extern GameState play;
diff --git a/engines/ags/engine/ac/global_display.cpp b/engines/ags/engine/ac/global_display.cpp
index 08b821051a..1ac54d54ff 100644
--- a/engines/ags/engine/ac/global_display.cpp
+++ b/engines/ags/engine/ac/global_display.cpp
@@ -41,7 +41,7 @@
 #include "game/roomstruct.h"
 #include "main/game_run.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern TopBarSettings topBar;
 extern GameState play;
diff --git a/engines/ags/engine/ac/global_drawingsurface.cpp b/engines/ags/engine/ac/global_drawingsurface.cpp
index 5fe00fdacd..f5556e7a07 100644
--- a/engines/ags/engine/ac/global_drawingsurface.cpp
+++ b/engines/ags/engine/ac/global_drawingsurface.cpp
@@ -37,7 +37,7 @@
 #include "gfx/gfx_def.h"
 #include "gfx/gfx_util.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern Bitmap *raw_saved_screen;
diff --git a/engines/ags/engine/ac/global_dynamicsprite.cpp b/engines/ags/engine/ac/global_dynamicsprite.cpp
index 4ecd20bf5d..d5380a1993 100644
--- a/engines/ags/engine/ac/global_dynamicsprite.cpp
+++ b/engines/ags/engine/ac/global_dynamicsprite.cpp
@@ -30,7 +30,7 @@
 #include "gfx/graphicsdriver.h"
 #include "gfx/bitmap.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern SpriteCache spriteset;
diff --git a/engines/ags/engine/ac/global_file.cpp b/engines/ags/engine/ac/global_file.cpp
index 47670c712a..9b29b396d9 100644
--- a/engines/ags/engine/ac/global_file.cpp
+++ b/engines/ags/engine/ac/global_file.cpp
@@ -32,7 +32,7 @@
 #include "util/path.h"
 #include "util/stream.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 int32_t FileOpenCMode(const char *fnmm, const char *cmode) {
 	Common::FileOpenMode open_mode;
diff --git a/engines/ags/engine/ac/global_file.h b/engines/ags/engine/ac/global_file.h
index 78afe03a0d..be068bf1cf 100644
--- a/engines/ags/engine/ac/global_file.h
+++ b/engines/ags/engine/ac/global_file.h
@@ -27,7 +27,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 } // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/engine/ac/global_game.cpp b/engines/ags/engine/ac/global_game.cpp
index afeea81d3b..306a63832a 100644
--- a/engines/ags/engine/ac/global_game.cpp
+++ b/engines/ags/engine/ac/global_game.cpp
@@ -69,7 +69,7 @@
 #include "util/string_utils.h"
 #include "media/audio/audio_system.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 #define ALLEGRO_KEYBOARD_HANDLER
 
diff --git a/engines/ags/engine/ac/global_gui.cpp b/engines/ags/engine/ac/global_gui.cpp
index 63b659d0ec..d8a0cdc010 100644
--- a/engines/ags/engine/ac/global_gui.cpp
+++ b/engines/ags/engine/ac/global_gui.cpp
@@ -36,7 +36,7 @@
 #include "script/runtimescriptvalue.h"
 #include "util/string_compat.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern GameSetupStruct game;
 extern ScriptGUI *scrGui;
diff --git a/engines/ags/engine/ac/global_hotspot.cpp b/engines/ags/engine/ac/global_hotspot.cpp
index c24917104f..a145d74bd8 100644
--- a/engines/ags/engine/ac/global_hotspot.cpp
+++ b/engines/ags/engine/ac/global_hotspot.cpp
@@ -37,7 +37,7 @@
 #include "game/roomstruct.h"
 #include "script/script.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern RoomStruct thisroom;
 extern RoomStatus *croom;
diff --git a/engines/ags/engine/ac/global_inventoryitem.cpp b/engines/ags/engine/ac/global_inventoryitem.cpp
index 117a52492a..7de499ee5b 100644
--- a/engines/ags/engine/ac/global_inventoryitem.cpp
+++ b/engines/ags/engine/ac/global_inventoryitem.cpp
@@ -34,7 +34,7 @@
 #include "ac/event.h"
 #include "ac/gamestate.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern GameSetupStruct game;
 extern GameState play;
diff --git a/engines/ags/engine/ac/global_label.cpp b/engines/ags/engine/ac/global_label.cpp
index 2943089f9c..5561a7a63a 100644
--- a/engines/ags/engine/ac/global_label.cpp
+++ b/engines/ags/engine/ac/global_label.cpp
@@ -27,7 +27,7 @@
 #include "ac/string.h"
 #include "gui/guimain.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern GameSetupStruct game;
 
diff --git a/engines/ags/engine/ac/global_object.cpp b/engines/ags/engine/ac/global_object.cpp
index ec7c793e31..53cae9bb3d 100644
--- a/engines/ags/engine/ac/global_object.cpp
+++ b/engines/ags/engine/ac/global_object.cpp
@@ -45,7 +45,7 @@
 #include "gfx/bitmap.h"
 #include "gfx/gfx_def.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 #define OVERLAPPING_OBJECT 1000
 
diff --git a/engines/ags/engine/ac/global_object.h b/engines/ags/engine/ac/global_object.h
index 05e521356e..4d192b82a9 100644
--- a/engines/ags/engine/ac/global_object.h
+++ b/engines/ags/engine/ac/global_object.h
@@ -25,7 +25,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Bitmap;
 } // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/engine/ac/global_overlay.cpp b/engines/ags/engine/ac/global_overlay.cpp
index bd10c5e7d4..572a71cba5 100644
--- a/engines/ags/engine/ac/global_overlay.cpp
+++ b/engines/ags/engine/ac/global_overlay.cpp
@@ -35,7 +35,7 @@
 #include "ac/system.h"
 #include "gfx/bitmap.h"
 
-using namespace Common;
+using namespace Shared;
 using namespace Engine;
 
 extern SpriteCache spriteset;
diff --git a/engines/ags/engine/ac/global_region.cpp b/engines/ags/engine/ac/global_region.cpp
index 46c79ade00..e02e28e582 100644
--- a/engines/ags/engine/ac/global_region.cpp
+++ b/engines/ags/engine/ac/global_region.cpp
@@ -32,7 +32,7 @@
 #include "script/script.h"
 
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern RoomStruct thisroom;
 extern RoomStatus *croom;
diff --git a/engines/ags/engine/ac/global_room.cpp b/engines/ags/engine/ac/global_room.cpp
index e07db97dfe..1b55d8f42e 100644
--- a/engines/ags/engine/ac/global_room.cpp
+++ b/engines/ags/engine/ac/global_room.cpp
@@ -39,7 +39,7 @@
 #include "script/script.h"
 #include "util/math.h"
 
-using namespace Common;
+using namespace Shared;
 
 extern GameState play;
 extern GameSetupStruct game;
diff --git a/engines/ags/engine/ac/global_screen.cpp b/engines/ags/engine/ac/global_screen.cpp
index 5e77dbb647..c8cb0f04d9 100644
--- a/engines/ags/engine/ac/global_screen.cpp
+++ b/engines/ags/engine/ac/global_screen.cpp
@@ -35,7 +35,7 @@
 #include "gfx/graphicsdriver.h"
 #include "gfx/bitmap.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern GameSetup usetup;
diff --git a/engines/ags/engine/ac/global_slider.cpp b/engines/ags/engine/ac/global_slider.cpp
index 290b864e51..512af4c99d 100644
--- a/engines/ags/engine/ac/global_slider.cpp
+++ b/engines/ags/engine/ac/global_slider.cpp
@@ -27,7 +27,7 @@
 #include "gui/guimain.h"
 #include "gui/guislider.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern GameSetupStruct game;
 
diff --git a/engines/ags/engine/ac/global_textbox.cpp b/engines/ags/engine/ac/global_textbox.cpp
index fec358f98b..8cdbe69b2e 100644
--- a/engines/ags/engine/ac/global_textbox.cpp
+++ b/engines/ags/engine/ac/global_textbox.cpp
@@ -28,7 +28,7 @@
 #include "gui/guimain.h"
 #include "gui/guitextbox.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern GameSetupStruct game;
 
diff --git a/engines/ags/engine/ac/global_translation.cpp b/engines/ags/engine/ac/global_translation.cpp
index 5e6230810b..d2a7b90d23 100644
--- a/engines/ags/engine/ac/global_translation.cpp
+++ b/engines/ags/engine/ac/global_translation.cpp
@@ -33,7 +33,7 @@
 #include "util/memory.h"
 #include "core/types.h"
 
-using namespace AGS::Common::Memory;
+using namespace AGS::Shared::Memory;
 
 extern GameState play;
 extern AGSPlatformDriver *platform;
diff --git a/engines/ags/engine/ac/global_walkablearea.cpp b/engines/ags/engine/ac/global_walkablearea.cpp
index 7dc5c7ec2a..bd57d417f7 100644
--- a/engines/ags/engine/ac/global_walkablearea.cpp
+++ b/engines/ags/engine/ac/global_walkablearea.cpp
@@ -28,7 +28,7 @@
 #include "debug/debug_log.h"
 #include "game/roomstruct.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern RoomStruct thisroom;
 
diff --git a/engines/ags/engine/ac/gui.cpp b/engines/ags/engine/ac/gui.cpp
index 479060c578..060914d468 100644
--- a/engines/ags/engine/ac/gui.cpp
+++ b/engines/ags/engine/ac/gui.cpp
@@ -56,7 +56,7 @@
 #include "util/string_compat.h"
 
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 
diff --git a/engines/ags/engine/ac/gui.h b/engines/ags/engine/ac/gui.h
index 1cb7629dfd..e8e179f9f2 100644
--- a/engines/ags/engine/ac/gui.h
+++ b/engines/ags/engine/ac/gui.h
@@ -28,8 +28,8 @@
 
 namespace AGS3 {
 
-using AGS::Common::GUIMain;
-using AGS::Common::GUIObject;
+using AGS::Shared::GUIMain;
+using AGS::Shared::GUIObject;
 
 ScriptGUI *GUI_AsTextWindow(ScriptGUI *tehgui);
 int     GUI_GetPopupStyle(ScriptGUI *tehgui);
@@ -71,7 +71,7 @@ ScriptGUI *GetGUIAtLocation(int xx, int yy);
 
 void    remove_popup_interface(int ifacenum);
 void    process_interface_click(int ifce, int btn, int mbut);
-void    replace_macro_tokens(const char *text, AGS::Common::String &fixed_text);
+void    replace_macro_tokens(const char *text, AGS::Shared::String &fixed_text);
 void    update_gui_zorder();
 void    export_gui_controls(int ee);
 void    unexport_gui_controls(int ee);
diff --git a/engines/ags/engine/ac/guicontrol.cpp b/engines/ags/engine/ac/guicontrol.cpp
index cc182c4db8..edb96d95cd 100644
--- a/engines/ags/engine/ac/guicontrol.cpp
+++ b/engines/ags/engine/ac/guicontrol.cpp
@@ -35,7 +35,7 @@
 #include "ac/dynobj/cc_gui.h"
 #include "ac/dynobj/cc_guiobject.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern ScriptGUI *scrGui;
 extern CCGUI ccDynamicGUI;
diff --git a/engines/ags/engine/ac/guicontrol.h b/engines/ags/engine/ac/guicontrol.h
index 1f8d60ef3d..1159917394 100644
--- a/engines/ags/engine/ac/guicontrol.h
+++ b/engines/ags/engine/ac/guicontrol.h
@@ -34,13 +34,13 @@
 
 namespace AGS3 {
 
-using AGS::Common::GUIObject;
-using AGS::Common::GUIButton;
-using AGS::Common::GUIInvWindow;
-using AGS::Common::GUILabel;
-using AGS::Common::GUIListBox;
-using AGS::Common::GUISlider;
-using AGS::Common::GUITextBox;
+using AGS::Shared::GUIObject;
+using AGS::Shared::GUIButton;
+using AGS::Shared::GUIInvWindow;
+using AGS::Shared::GUILabel;
+using AGS::Shared::GUIListBox;
+using AGS::Shared::GUISlider;
+using AGS::Shared::GUITextBox;
 
 GUIObject *GetGUIControlAtLocation(int xx, int yy);
 int         GUIControl_GetVisible(GUIObject *guio);
diff --git a/engines/ags/engine/ac/guiinv.cpp b/engines/ags/engine/ac/guiinv.cpp
index 7bda0b6a5a..ef3608d34e 100644
--- a/engines/ags/engine/ac/guiinv.cpp
+++ b/engines/ags/engine/ac/guiinv.cpp
@@ -38,7 +38,7 @@ extern SpriteCache spriteset;
 
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 int GUIInvWindow::GetCharacterId() const {
 	if (CharId < 0)
@@ -91,5 +91,5 @@ void GUIInvWindow::Draw(Bitmap *ds) {
 	}
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/engine/ac/hotspot.cpp b/engines/ags/engine/ac/hotspot.cpp
index 01c4d74bcc..a57a57a458 100644
--- a/engines/ags/engine/ac/hotspot.cpp
+++ b/engines/ags/engine/ac/hotspot.cpp
@@ -33,7 +33,7 @@
 #include "gfx/bitmap.h"
 #include "script/runtimescriptvalue.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern RoomStruct thisroom;
 extern RoomStatus *croom;
diff --git a/engines/ags/engine/ac/invwindow.cpp b/engines/ags/engine/ac/invwindow.cpp
index eafc35680f..ed8ba69464 100644
--- a/engines/ags/engine/ac/invwindow.cpp
+++ b/engines/ags/engine/ac/invwindow.cpp
@@ -45,7 +45,7 @@
 #include "media/audio/audio_system.h"
 #include "ac/timer.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern GameSetupStruct game;
 extern GameState play;
diff --git a/engines/ags/engine/ac/invwindow.h b/engines/ags/engine/ac/invwindow.h
index 29f9c3ace2..ebb7fc8822 100644
--- a/engines/ags/engine/ac/invwindow.h
+++ b/engines/ags/engine/ac/invwindow.h
@@ -29,7 +29,7 @@
 
 namespace AGS3 {
 
-using AGS::Common::GUIInvWindow;
+using AGS::Shared::GUIInvWindow;
 
 void            InvWindow_SetCharacterToUse(GUIInvWindow *guii, CharacterInfo *chaa);
 CharacterInfo *InvWindow_GetCharacterToUse(GUIInvWindow *guii);
diff --git a/engines/ags/engine/ac/label.h b/engines/ags/engine/ac/label.h
index a1102b8d0f..27453a5bcd 100644
--- a/engines/ags/engine/ac/label.h
+++ b/engines/ags/engine/ac/label.h
@@ -27,7 +27,7 @@
 
 namespace AGS3 {
 
-using AGS::Common::GUILabel;
+using AGS::Shared::GUILabel;
 
 const char *Label_GetText_New(GUILabel *labl);
 void        Label_GetText(GUILabel *labl, char *buffer);
diff --git a/engines/ags/engine/ac/listbox.cpp b/engines/ags/engine/ac/listbox.cpp
index ca42a539fb..57635d104d 100644
--- a/engines/ags/engine/ac/listbox.cpp
+++ b/engines/ags/engine/ac/listbox.cpp
@@ -32,7 +32,7 @@
 #include "gui/guimain.h"
 #include "debug/debug_log.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern GameState play;
 extern GameSetupStruct game;
diff --git a/engines/ags/engine/ac/listbox.h b/engines/ags/engine/ac/listbox.h
index 96267dffd1..7642a9dfba 100644
--- a/engines/ags/engine/ac/listbox.h
+++ b/engines/ags/engine/ac/listbox.h
@@ -27,7 +27,7 @@
 
 namespace AGS3 {
 
-using AGS::Common::GUIListBox;
+using AGS::Shared::GUIListBox;
 
 int         ListBox_AddItem(GUIListBox *lbb, const char *text);
 int         ListBox_InsertItemAt(GUIListBox *lbb, int index, const char *text);
diff --git a/engines/ags/engine/ac/mouse.cpp b/engines/ags/engine/ac/mouse.cpp
index 0675719825..9b6f65c89c 100644
--- a/engines/ags/engine/ac/mouse.cpp
+++ b/engines/ags/engine/ac/mouse.cpp
@@ -42,7 +42,7 @@
 #include "gfx/graphicsdriver.h"
 #include "gfx/gfxfilter.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern GameSetupStruct game;
diff --git a/engines/ags/engine/ac/movelist.cpp b/engines/ags/engine/ac/movelist.cpp
index 8f8d034d7a..b2402618b3 100644
--- a/engines/ags/engine/ac/movelist.cpp
+++ b/engines/ags/engine/ac/movelist.cpp
@@ -24,7 +24,7 @@
 #include "ac/common.h"
 #include "util/stream.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 void MoveList::ReadFromFile_Legacy(Stream *in) {
diff --git a/engines/ags/engine/ac/movelist.h b/engines/ags/engine/ac/movelist.h
index 4533405518..06aa462fc3 100644
--- a/engines/ags/engine/ac/movelist.h
+++ b/engines/ags/engine/ac/movelist.h
@@ -30,7 +30,7 @@ namespace AGS3 {
 
 // Forward declaration
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 } // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/engine/ac/object.cpp b/engines/ags/engine/ac/object.cpp
index 6cedba484f..399f4bbbc9 100644
--- a/engines/ags/engine/ac/object.cpp
+++ b/engines/ags/engine/ac/object.cpp
@@ -46,7 +46,7 @@
 #include "ac/dynobj/cc_object.h"
 #include "ac/movelist.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 
 extern ScriptObject scrObj[MAX_ROOM_OBJECTS];
diff --git a/engines/ags/engine/ac/object.h b/engines/ags/engine/ac/object.h
index fc02fafc89..39b3126ae9 100644
--- a/engines/ags/engine/ac/object.h
+++ b/engines/ags/engine/ac/object.h
@@ -37,7 +37,7 @@
 namespace AGS3 {
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Bitmap;
 } // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/engine/ac/overlay.cpp b/engines/ags/engine/ac/overlay.cpp
index 3d1b5bcc26..8f6fe78dc7 100644
--- a/engines/ags/engine/ac/overlay.cpp
+++ b/engines/ags/engine/ac/overlay.cpp
@@ -38,7 +38,7 @@
 #include "gfx/bitmap.h"
 #include "script/runtimescriptvalue.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern GameSetupStruct game;
diff --git a/engines/ags/engine/ac/overlay.h b/engines/ags/engine/ac/overlay.h
index 958a8b8f33..683f9a489e 100644
--- a/engines/ags/engine/ac/overlay.h
+++ b/engines/ags/engine/ac/overlay.h
@@ -30,7 +30,7 @@
 namespace AGS3 {
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Bitmap;
 } // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/engine/ac/parser.cpp b/engines/ags/engine/ac/parser.cpp
index 4ec35d8794..c966d4d9fd 100644
--- a/engines/ags/engine/ac/parser.cpp
+++ b/engines/ags/engine/ac/parser.cpp
@@ -32,7 +32,7 @@
 #include "util/string.h"
 #include "util/string_compat.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern GameSetupStruct game;
 extern GameState play;
diff --git a/engines/ags/engine/ac/path_helper.h b/engines/ags/engine/ac/path_helper.h
index e8768e936d..8630e82351 100644
--- a/engines/ags/engine/ac/path_helper.h
+++ b/engines/ags/engine/ac/path_helper.h
@@ -33,7 +33,7 @@
 
 namespace AGS3 {
 
-using AGS::Common::String;
+using AGS::Shared::String;
 
 // Filepath tokens, which are replaced by platform-specific directory names
 extern const String UserSavedgamesRootToken;
diff --git a/engines/ags/engine/ac/properties.cpp b/engines/ags/engine/ac/properties.cpp
index aae559baac..e68c908cbd 100644
--- a/engines/ags/engine/ac/properties.cpp
+++ b/engines/ags/engine/ac/properties.cpp
@@ -28,7 +28,7 @@
 #include "script/runtimescriptvalue.h"
 #include "util/string_utils.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern GameSetupStruct game;
 extern ScriptString myScriptStringImpl;
diff --git a/engines/ags/engine/ac/properties.h b/engines/ags/engine/ac/properties.h
index ba829662a5..aa877441da 100644
--- a/engines/ags/engine/ac/properties.h
+++ b/engines/ags/engine/ac/properties.h
@@ -27,7 +27,7 @@
 
 namespace AGS3 {
 
-using AGS::Common::StringIMap;
+using AGS::Shared::StringIMap;
 
 // Getting a property value requires static and runtime property maps.
 // Key is first searched in runtime map, if not found - static map is taken,
diff --git a/engines/ags/engine/ac/region.cpp b/engines/ags/engine/ac/region.cpp
index a9755ed88d..27a3d05ea5 100644
--- a/engines/ags/engine/ac/region.cpp
+++ b/engines/ags/engine/ac/region.cpp
@@ -32,7 +32,7 @@
 #include "game/roomstruct.h"
 #include "script/runtimescriptvalue.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern ScriptRegion scrRegion[MAX_ROOM_REGIONS];
 extern RoomStruct thisroom;
diff --git a/engines/ags/engine/ac/richgamemedia.cpp b/engines/ags/engine/ac/richgamemedia.cpp
index 7e0888c2c0..3bf8e2c68c 100644
--- a/engines/ags/engine/ac/richgamemedia.cpp
+++ b/engines/ags/engine/ac/richgamemedia.cpp
@@ -23,7 +23,7 @@
 #include "ac/richgamemedia.h"
 #include "util/stream.h"
 
-using AGS::Common::Stream;
+using AGS::Shared::Stream;
 
 void RICH_GAME_MEDIA_HEADER::ReadFromFile(Stream *in) {
 	dwMagicNumber = in->ReadInt32();
diff --git a/engines/ags/engine/ac/richgamemedia.h b/engines/ags/engine/ac/richgamemedia.h
index 02bc1b1592..420903aacb 100644
--- a/engines/ags/engine/ac/richgamemedia.h
+++ b/engines/ags/engine/ac/richgamemedia.h
@@ -32,7 +32,7 @@ namespace AGS3 {
 
 // Forward declaration
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 } // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/engine/ac/room.cpp b/engines/ags/engine/ac/room.cpp
index e77929b863..d2055e6049 100644
--- a/engines/ags/engine/ac/room.cpp
+++ b/engines/ags/engine/ac/room.cpp
@@ -77,7 +77,7 @@
 #include "util/math.h"
 #include "media/audio/audio_system.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern GameSetup usetup;
diff --git a/engines/ags/engine/ac/room.h b/engines/ags/engine/ac/room.h
index 4b3e5789d3..05f36efe87 100644
--- a/engines/ags/engine/ac/room.h
+++ b/engines/ags/engine/ac/room.h
@@ -76,7 +76,7 @@ struct MoveList;
 // Convert move path from room's mask resolution to room resolution
 void convert_move_path_to_room_resolution(MoveList *ml);
 
-extern AGS::Common::RoomStruct thisroom;
+extern AGS::Shared::RoomStruct thisroom;
 
 } // namespace AGS3
 
diff --git a/engines/ags/engine/ac/roomobject.cpp b/engines/ags/engine/ac/roomobject.cpp
index b4a8d4de4f..ac9a7b05e4 100644
--- a/engines/ags/engine/ac/roomobject.cpp
+++ b/engines/ags/engine/ac/roomobject.cpp
@@ -30,7 +30,7 @@
 #include "main/update.h"
 #include "util/stream.h"
 
-using AGS::Common::Stream;
+using AGS::Shared::Stream;
 
 extern ViewStruct *views;
 extern GameState play;
diff --git a/engines/ags/engine/ac/roomobject.h b/engines/ags/engine/ac/roomobject.h
index 2d8111b99b..b78f9a80d5 100644
--- a/engines/ags/engine/ac/roomobject.h
+++ b/engines/ags/engine/ac/roomobject.h
@@ -28,7 +28,7 @@
 namespace AGS3 {
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 } // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/engine/ac/roomstatus.cpp b/engines/ags/engine/ac/roomstatus.cpp
index 96e036b72f..368875d0bf 100644
--- a/engines/ags/engine/ac/roomstatus.cpp
+++ b/engines/ags/engine/ac/roomstatus.cpp
@@ -29,7 +29,7 @@
 #include "game/savegame_components.h"
 #include "util/alignedstream.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 RoomStatus::RoomStatus() {
diff --git a/engines/ags/engine/ac/roomstatus.h b/engines/ags/engine/ac/roomstatus.h
index a00799e05c..f23e71dfd8 100644
--- a/engines/ags/engine/ac/roomstatus.h
+++ b/engines/ags/engine/ac/roomstatus.h
@@ -32,13 +32,13 @@ namespace AGS3 {
 
 // Forward declaration
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 } // namespace Shared
 } // namespace AGS
 
-using AGS::Common::Stream;
-using AGS::Common::Interaction;
+using AGS::Shared::Stream;
+using AGS::Shared::Interaction;
 
 // This struct is saved in the save games - it contains everything about
 // a room that could change
diff --git a/engines/ags/engine/ac/route_finder.cpp b/engines/ags/engine/ac/route_finder.cpp
index 60be1c042f..5de75a3e04 100644
--- a/engines/ags/engine/ac/route_finder.cpp
+++ b/engines/ags/engine/ac/route_finder.cpp
@@ -27,7 +27,7 @@
 
 #include "debug/out.h"
 
-using AGS::Common::Bitmap;
+using AGS::Shared::Bitmap;
 
 class IRouteFinder {
 public:
@@ -101,10 +101,10 @@ static IRouteFinder *route_finder_impl = nullptr;
 
 void init_pathfinder(GameDataVersion game_file_version) {
 	if (game_file_version >= kGameVersion_350) {
-		AGS::Common::Debug::Printf(AGS::Common::MessageType::kDbgMsg_Info, "Initialize path finder library");
+		AGS::Shared::Debug::Printf(AGS::Shared::MessageType::kDbgMsg_Info, "Initialize path finder library");
 		route_finder_impl = new AGSRouteFinder();
 	} else {
-		AGS::Common::Debug::Printf(AGS::Common::MessageType::kDbgMsg_Info, "Initialize legacy path finder library");
+		AGS::Shared::Debug::Printf(AGS::Shared::MessageType::kDbgMsg_Info, "Initialize legacy path finder library");
 		route_finder_impl = new AGSLegacyRouteFinder();
 	}
 
diff --git a/engines/ags/engine/ac/route_finder.h b/engines/ags/engine/ac/route_finder.h
index 3cef9962fa..5759034843 100644
--- a/engines/ags/engine/ac/route_finder.h
+++ b/engines/ags/engine/ac/route_finder.h
@@ -29,7 +29,7 @@ namespace AGS3 {
 
 // Forward declaration
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Bitmap;
 } // namespace Shared
 } // namespace AGS
@@ -39,14 +39,14 @@ struct MoveList;
 void init_pathfinder(GameDataVersion game_file_version);
 void shutdown_pathfinder();
 
-void set_wallscreen(AGS::Common::Bitmap *wallscreen);
+void set_wallscreen(AGS::Shared::Bitmap *wallscreen);
 
 int can_see_from(int x1, int y1, int x2, int y2);
 void get_lastcpos(int &lastcx, int &lastcy);
 // NOTE: pathfinder implementation mostly needs to know proportion between x and y speed
 void set_route_move_speed(int speed_x, int speed_y);
 
-int find_route(short srcx, short srcy, short xx, short yy, AGS::Common::Bitmap *onscreen, int movlst, int nocross = 0, int ignore_walls = 0);
+int find_route(short srcx, short srcy, short xx, short yy, AGS::Shared::Bitmap *onscreen, int movlst, int nocross = 0, int ignore_walls = 0);
 void calculate_move_stage(MoveList *mlsp, int aaa);
 
 } // namespace AGS3
diff --git a/engines/ags/engine/ac/route_finder_impl.cpp b/engines/ags/engine/ac/route_finder_impl.cpp
index 24a9587044..66970fb31f 100644
--- a/engines/ags/engine/ac/route_finder_impl.cpp
+++ b/engines/ags/engine/ac/route_finder_impl.cpp
@@ -41,7 +41,7 @@
 
 extern MoveList *mls;
 
-using AGS::Common::Bitmap;
+using AGS::Shared::Bitmap;
 
 // #define DEBUG_PATHFINDER
 
@@ -238,14 +238,14 @@ int find_route(short srcx, short srcy, short xx, short yy, Bitmap *onscreen, int
 	assert(num_navpoints <= MAXNAVPOINTS);
 
 #ifdef DEBUG_PATHFINDER
-	AGS::Common::Debug::Printf("Route from %d,%d to %d,%d - %d stages", srcx, srcy, xx, yy, num_navpoints);
+	AGS::Shared::Debug::Printf("Route from %d,%d to %d,%d - %d stages", srcx, srcy, xx, yy, num_navpoints);
 #endif
 
 	int mlist = movlst;
 	mls[mlist].numstage = num_navpoints;
 	memcpy(&mls[mlist].pos[0], &navpoints[0], sizeof(int) * num_navpoints);
 #ifdef DEBUG_PATHFINDER
-	AGS::Common::Debug::Printf("stages: %d\n", num_navpoints);
+	AGS::Shared::Debug::Printf("stages: %d\n", num_navpoints);
 #endif
 
 	for (i = 0; i < num_navpoints - 1; i++)
diff --git a/engines/ags/engine/ac/route_finder_impl.h b/engines/ags/engine/ac/route_finder_impl.h
index 43600c8fe9..cfd44228e0 100644
--- a/engines/ags/engine/ac/route_finder_impl.h
+++ b/engines/ags/engine/ac/route_finder_impl.h
@@ -29,7 +29,7 @@ namespace AGS3 {
 
 // Forward declaration
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Bitmap;
 } // namespace Shared
 } // namespace AGS
@@ -43,14 +43,14 @@ namespace RouteFinder {
 void init_pathfinder();
 void shutdown_pathfinder();
 
-void set_wallscreen(AGS::Common::Bitmap *wallscreen);
+void set_wallscreen(AGS::Shared::Bitmap *wallscreen);
 
 int can_see_from(int x1, int y1, int x2, int y2);
 void get_lastcpos(int &lastcx, int &lastcy);
 
 void set_route_move_speed(int speed_x, int speed_y);
 
-int find_route(short srcx, short srcy, short xx, short yy, AGS::Common::Bitmap *onscreen, int movlst, int nocross = 0, int ignore_walls = 0);
+int find_route(short srcx, short srcy, short xx, short yy, AGS::Shared::Bitmap *onscreen, int movlst, int nocross = 0, int ignore_walls = 0);
 void calculate_move_stage(MoveList *mlsp, int aaa);
 
 } // namespace RouteFinder
diff --git a/engines/ags/engine/ac/route_finder_impl_legacy.cpp b/engines/ags/engine/ac/route_finder_impl_legacy.cpp
index c7cb82fefa..4bbe4c35e6 100644
--- a/engines/ags/engine/ac/route_finder_impl_legacy.cpp
+++ b/engines/ags/engine/ac/route_finder_impl_legacy.cpp
@@ -43,8 +43,8 @@ extern void update_polled_stuff_if_runtime();
 
 extern MoveList *mls;
 
-using AGS::Common::Bitmap;
-namespace BitmapHelper = AGS::Common::BitmapHelper;
+using AGS::Shared::Bitmap;
+namespace BitmapHelper = AGS::Shared::BitmapHelper;
 
 // #define DEBUG_PATHFINDER
 
@@ -231,7 +231,7 @@ static int is_route_possible(int fromx, int fromy, int tox, int toy, Bitmap *wss
 			walk_area_granularity[dd] = MAX_GRANULARITY;
 
 #ifdef DEBUG_PATHFINDER
-		AGS::Common::Debug::Printf("area %d: Gran %d", dd, walk_area_granularity[dd]);
+		AGS::Shared::Debug::Printf("area %d: Gran %d", dd, walk_area_granularity[dd]);
 #endif
 	}
 	walk_area_granularity[0] = MAX_GRANULARITY;
@@ -323,7 +323,7 @@ try_again:
 	iterations++;
 	if (iterations > 5) {
 #ifdef DEBUG_PATHFINDER
-		AGS::Common::Debug::Printf("not found: %d,%d  beenhere 0x%X\n", srcx, srcy, beenhere[srcy][srcx]);
+		AGS::Shared::Debug::Printf("not found: %d,%d  beenhere 0x%X\n", srcx, srcy, beenhere[srcy][srcx]);
 #endif
 		nesting--;
 		return 0;
@@ -733,7 +733,7 @@ void calculate_move_stage(MoveList *mlsp, int aaa) {
 	mlsp->ypermove[aaa] = newymove;
 
 #ifdef DEBUG_PATHFINDER
-	AGS::Common::Debug::Printf("stage %d from %d,%d to %d,%d Xpermove:%X Ypm:%X", aaa, ourx, oury, destx, desty, newxmove, newymove);
+	AGS::Shared::Debug::Printf("stage %d from %d,%d to %d,%d Xpermove:%X Ypm:%X", aaa, ourx, oury, destx, desty, newxmove, newymove);
 	// wtextcolor(14);
 	// wgtprintf((reallyneed[aaa] >> 16) & 0x000ffff, reallyneed[aaa] & 0x000ffff, cbuttfont, "%d", aaa);
 #endif
@@ -807,7 +807,7 @@ stage_again:
 		// find the furthest point that can be seen from this stage
 		for (aaa = pathbackstage - 1; aaa >= 0; aaa--) {
 #ifdef DEBUG_PATHFINDER
-			AGS::Common::Debug::Printf("stage %2d: %2d,%2d\n", aaa, pathbackx[aaa], pathbacky[aaa]);
+			AGS::Shared::Debug::Printf("stage %2d: %2d,%2d\n", aaa, pathbackx[aaa], pathbacky[aaa]);
 #endif
 			if (can_see_from(srcx, srcy, pathbackx[aaa], pathbacky[aaa])) {
 				nearestpos = MAKE_INTCOORD(pathbackx[aaa], pathbacky[aaa]);
@@ -831,7 +831,7 @@ stage_again:
 			srcx = (nearestpos >> 16) & 0x000ffff;
 			srcy = nearestpos & 0x000ffff;
 #ifdef DEBUG_PATHFINDER
-			AGS::Common::Debug::Printf("Added: %d, %d pbs:%d", srcx, srcy, pathbackstage);
+			AGS::Shared::Debug::Printf("Added: %d, %d pbs:%d", srcx, srcy, pathbackstage);
 #endif
 			lastpbs = pathbackstage;
 			pathbackstage = nearestindx;
@@ -853,13 +853,13 @@ stage_again:
 			return 0;
 		}
 #ifdef DEBUG_PATHFINDER
-		AGS::Common::Debug::Printf("Route from %d,%d to %d,%d - %d stage, %d stages", orisrcx, orisrcy, xx, yy, pathbackstage, numstages);
+		AGS::Shared::Debug::Printf("Route from %d,%d to %d,%d - %d stage, %d stages", orisrcx, orisrcy, xx, yy, pathbackstage, numstages);
 #endif
 		int mlist = movlst;
 		mls[mlist].numstage = numstages;
 		memcpy(&mls[mlist].pos[0], &reallyneed[0], sizeof(int) * numstages);
 #ifdef DEBUG_PATHFINDER
-		AGS::Common::Debug::Printf("stages: %d\n", numstages);
+		AGS::Shared::Debug::Printf("stages: %d\n", numstages);
 #endif
 
 		for (aaa = 0; aaa < numstages - 1; aaa++) {
diff --git a/engines/ags/engine/ac/route_finder_impl_legacy.h b/engines/ags/engine/ac/route_finder_impl_legacy.h
index 632038d524..d61cf03c74 100644
--- a/engines/ags/engine/ac/route_finder_impl_legacy.h
+++ b/engines/ags/engine/ac/route_finder_impl_legacy.h
@@ -27,7 +27,7 @@ namespace AGS3 {
 
 // Forward declaration
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Bitmap;
 } // namespace Shared
 } // namespace AGS
@@ -41,14 +41,14 @@ namespace RouteFinderLegacy {
 void init_pathfinder();
 void shutdown_pathfinder();
 
-void set_wallscreen(AGS::Common::Bitmap *wallscreen);
+void set_wallscreen(AGS::Shared::Bitmap *wallscreen);
 
 int can_see_from(int x1, int y1, int x2, int y2);
 void get_lastcpos(int &lastcx, int &lastcy);
 
 void set_route_move_speed(int speed_x, int speed_y);
 
-int find_route(short srcx, short srcy, short xx, short yy, AGS::Common::Bitmap *onscreen, int movlst, int nocross = 0, int ignore_walls = 0);
+int find_route(short srcx, short srcy, short xx, short yy, AGS::Shared::Bitmap *onscreen, int movlst, int nocross = 0, int ignore_walls = 0);
 void calculate_move_stage(MoveList *mlsp, int aaa);
 
 } // namespace RouteFinderLegacy
diff --git a/engines/ags/engine/ac/screen.cpp b/engines/ags/engine/ac/screen.cpp
index 39faca6496..299fb1d63f 100644
--- a/engines/ags/engine/ac/screen.cpp
+++ b/engines/ags/engine/ac/screen.cpp
@@ -36,7 +36,7 @@
 #include "gfx/bitmap.h"
 #include "gfx/graphicsdriver.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern GameSetupStruct game;
diff --git a/engines/ags/engine/ac/screen.h b/engines/ags/engine/ac/screen.h
index e38b092050..ef1ecba60c 100644
--- a/engines/ags/engine/ac/screen.h
+++ b/engines/ags/engine/ac/screen.h
@@ -26,7 +26,7 @@
 namespace AGS3 {
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Bitmap;
 } // namespace Shared
 } // namespace AGS
@@ -42,7 +42,7 @@ void current_fade_out_effect();
 AGS::Engine::IDriverDependantBitmap *prepare_screen_for_transition_in();
 
 // Screenshot made in the last room, used during some of the transition effects
-extern AGS::Common::Bitmap *saved_viewport_bitmap;
+extern AGS::Shared::Bitmap *saved_viewport_bitmap;
 
 } // namespace AGS3
 
diff --git a/engines/ags/engine/ac/screenoverlay.cpp b/engines/ags/engine/ac/screenoverlay.cpp
index c90e3bc77e..59926bbc87 100644
--- a/engines/ags/engine/ac/screenoverlay.cpp
+++ b/engines/ags/engine/ac/screenoverlay.cpp
@@ -23,7 +23,7 @@
 #include "screenoverlay.h"
 #include "util/stream.h"
 
-using AGS::Common::Stream;
+using AGS::Shared::Stream;
 
 void ScreenOverlay::ReadFromFile(Stream *in, int32_t cmp_ver) {
 	// Skipping bmp and pic pointer values
diff --git a/engines/ags/engine/ac/screenoverlay.h b/engines/ags/engine/ac/screenoverlay.h
index 59ed04a899..64a04906bf 100644
--- a/engines/ags/engine/ac/screenoverlay.h
+++ b/engines/ags/engine/ac/screenoverlay.h
@@ -29,7 +29,7 @@ namespace AGS3 {
 
 // Forward declaration
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Bitmap;
 class Stream;
 } // namespace Shared
diff --git a/engines/ags/engine/ac/slider.h b/engines/ags/engine/ac/slider.h
index 19858cecd3..d5d8af96d4 100644
--- a/engines/ags/engine/ac/slider.h
+++ b/engines/ags/engine/ac/slider.h
@@ -27,7 +27,7 @@
 
 namespace AGS3 {
 
-using AGS::Common::GUISlider;
+using AGS::Shared::GUISlider;
 
 void    Slider_SetMax(GUISlider *guisl, int valn);
 int     Slider_GetMax(GUISlider *guisl);
diff --git a/engines/ags/engine/ac/sprite.cpp b/engines/ags/engine/ac/sprite.cpp
index c34bc4dfa9..562b89719e 100644
--- a/engines/ags/engine/ac/sprite.cpp
+++ b/engines/ags/engine/ac/sprite.cpp
@@ -32,7 +32,7 @@
 #include "gfx/bitmap.h"
 #include "gfx/graphicsdriver.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern GameSetupStruct game;
diff --git a/engines/ags/engine/ac/spritelistentry.h b/engines/ags/engine/ac/spritelistentry.h
index 8f93274389..cbf0a049be 100644
--- a/engines/ags/engine/ac/spritelistentry.h
+++ b/engines/ags/engine/ac/spritelistentry.h
@@ -29,7 +29,7 @@ namespace AGS3 {
 
 struct SpriteListEntry {
 	AGS::Engine::IDriverDependantBitmap *bmp;
-	AGS::Common::Bitmap *pic;
+	AGS::Shared::Bitmap *pic;
 	int baseline;
 	int x, y;
 	int transparent;
diff --git a/engines/ags/engine/ac/sys_events.cpp b/engines/ags/engine/ac/sys_events.cpp
index 9c0d029b65..37306e004a 100644
--- a/engines/ags/engine/ac/sys_events.cpp
+++ b/engines/ags/engine/ac/sys_events.cpp
@@ -31,7 +31,7 @@
 #include "platform/base/agsplatformdriver.h"
 #include "ac/timer.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern GameSetupStruct game;
diff --git a/engines/ags/engine/ac/system.cpp b/engines/ags/engine/ac/system.cpp
index e4936cb9e3..667c75e6b6 100644
--- a/engines/ags/engine/ac/system.cpp
+++ b/engines/ags/engine/ac/system.cpp
@@ -41,7 +41,7 @@
 #include "media/audio/audio_system.h"
 #include "util/string_compat.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern GameSetupStruct game;
diff --git a/engines/ags/engine/ac/textbox.h b/engines/ags/engine/ac/textbox.h
index 8b2a1f23a3..45271c0d67 100644
--- a/engines/ags/engine/ac/textbox.h
+++ b/engines/ags/engine/ac/textbox.h
@@ -27,7 +27,7 @@
 
 namespace AGS3 {
 
-using AGS::Common::GUITextBox;
+using AGS::Shared::GUITextBox;
 
 const char *TextBox_GetText_New(GUITextBox *texbox);
 void        TextBox_GetText(GUITextBox *texbox, char *buffer);
diff --git a/engines/ags/engine/ac/translation.cpp b/engines/ags/engine/ac/translation.cpp
index 85e64f45ab..c7b3df4a28 100644
--- a/engines/ags/engine/ac/translation.cpp
+++ b/engines/ags/engine/ac/translation.cpp
@@ -36,7 +36,7 @@
 #include "util/stream.h"
 #include "core/assetmanager.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern GameSetup usetup;
 extern GameSetupStruct game;
diff --git a/engines/ags/engine/ac/translation.h b/engines/ags/engine/ac/translation.h
index 4e5922b575..30e638befe 100644
--- a/engines/ags/engine/ac/translation.h
+++ b/engines/ags/engine/ac/translation.h
@@ -27,7 +27,7 @@
 
 namespace AGS3 {
 
-using AGS::Common::String;
+using AGS::Shared::String;
 
 void close_translation();
 bool init_translation(const String &lang, const String &fallback_lang, bool quit_on_error);
diff --git a/engines/ags/engine/ac/viewframe.cpp b/engines/ags/engine/ac/viewframe.cpp
index 81605b5d02..4d7f0543a2 100644
--- a/engines/ags/engine/ac/viewframe.cpp
+++ b/engines/ags/engine/ac/viewframe.cpp
@@ -31,8 +31,8 @@
 #include "ac/game_version.h"
 #include "media/audio/audio_system.h"
 
-using AGS::Common::Bitmap;
-using AGS::Common::Graphics;
+using AGS::Shared::Bitmap;
+using AGS::Shared::Graphics;
 
 extern GameSetupStruct game;
 extern ViewStruct *views;
diff --git a/engines/ags/engine/ac/viewframe.h b/engines/ags/engine/ac/viewframe.h
index 2bd3049aa9..7e2c4edbf5 100644
--- a/engines/ags/engine/ac/viewframe.h
+++ b/engines/ags/engine/ac/viewframe.h
@@ -32,7 +32,7 @@
 namespace AGS3 {
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Graphics;
 } // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/engine/ac/viewport_script.cpp b/engines/ags/engine/ac/viewport_script.cpp
index ae83413e88..b6fb314f53 100644
--- a/engines/ags/engine/ac/viewport_script.cpp
+++ b/engines/ags/engine/ac/viewport_script.cpp
@@ -35,7 +35,7 @@
 #include "script/script_api.h"
 #include "script/script_runtime.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 //=============================================================================
 //
diff --git a/engines/ags/engine/ac/walkablearea.cpp b/engines/ags/engine/ac/walkablearea.cpp
index 8b16f635b8..d129b3e138 100644
--- a/engines/ags/engine/ac/walkablearea.cpp
+++ b/engines/ags/engine/ac/walkablearea.cpp
@@ -33,7 +33,7 @@
 #include "game/roomstruct.h"
 #include "gfx/bitmap.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern RoomStruct thisroom;
 extern GameState play;
diff --git a/engines/ags/engine/ac/walkbehind.cpp b/engines/ags/engine/ac/walkbehind.cpp
index ab1cc69554..7ad1b0e2ed 100644
--- a/engines/ags/engine/ac/walkbehind.cpp
+++ b/engines/ags/engine/ac/walkbehind.cpp
@@ -27,7 +27,7 @@
 #include "gfx/graphicsdriver.h"
 #include "gfx/bitmap.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern RoomStruct thisroom;
diff --git a/engines/ags/engine/debugging/consoleoutputtarget.h b/engines/ags/engine/debugging/consoleoutputtarget.h
index f35bec3488..7772d45de0 100644
--- a/engines/ags/engine/debugging/consoleoutputtarget.h
+++ b/engines/ags/engine/debugging/consoleoutputtarget.h
@@ -39,7 +39,7 @@ namespace Engine {
 using Common::String;
 using Common::DebugMessage;
 
-class ConsoleOutputTarget : public AGS::Common::IOutputHandler {
+class ConsoleOutputTarget : public AGS::Shared::IOutputHandler {
 public:
 	ConsoleOutputTarget();
 	virtual ~ConsoleOutputTarget();
diff --git a/engines/ags/engine/debugging/debug.cpp b/engines/ags/engine/debugging/debug.cpp
index e180cad5c2..997add89ef 100644
--- a/engines/ags/engine/debugging/debug.cpp
+++ b/engines/ags/engine/debugging/debug.cpp
@@ -48,7 +48,7 @@
 #include <winalleg.h>
 #endif
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern char check_dynamic_sprites_at_exit;
diff --git a/engines/ags/engine/debugging/debug_log.h b/engines/ags/engine/debugging/debug_log.h
index ea0b955427..729fafabac 100644
--- a/engines/ags/engine/debugging/debug_log.h
+++ b/engines/ags/engine/debugging/debug_log.h
@@ -31,8 +31,8 @@
 
 namespace AGS3 {
 
-void init_debug(const AGS::Common::ConfigTree &cfg, bool stderr_only);
-void apply_debug_config(const AGS::Common::ConfigTree &cfg);
+void init_debug(const AGS::Shared::ConfigTree &cfg, bool stderr_only);
+void apply_debug_config(const AGS::Shared::ConfigTree &cfg);
 void shutdown_debug();
 
 void debug_set_console(bool enable);
@@ -49,7 +49,7 @@ bool init_editor_debugging();
 // allow LShift to single-step,  RShift to pause flow
 void scriptDebugHook(ccInstance *ccinst, int linenum);
 
-extern AGS::Common::String debug_line[DEBUG_CONSOLE_NUMLINES];
+extern AGS::Shared::String debug_line[DEBUG_CONSOLE_NUMLINES];
 extern int first_debug_line, last_debug_line, display_console;
 
 
diff --git a/engines/ags/engine/debugging/debugger.h b/engines/ags/engine/debugging/debugger.h
index 39450e9889..5f97124f5e 100644
--- a/engines/ags/engine/debugging/debugger.h
+++ b/engines/ags/engine/debugging/debugger.h
@@ -40,7 +40,7 @@ int check_for_messages_from_editor();
 bool send_message_to_editor(const char *msg);
 bool send_exception_to_editor(const char *qmsg);
 // Returns current script's location and callstack
-AGS::Common::String get_cur_script(int numberOfLinesOfCallStack);
+AGS::Shared::String get_cur_script(int numberOfLinesOfCallStack);
 bool get_script_position(ScriptPosition &script_pos);
 void check_debug_keys();
 
diff --git a/engines/ags/engine/debugging/filebasedagsdebugger.cpp b/engines/ags/engine/debugging/filebasedagsdebugger.cpp
index 22d2ce218c..a95700ba4f 100644
--- a/engines/ags/engine/debugging/filebasedagsdebugger.cpp
+++ b/engines/ags/engine/debugging/filebasedagsdebugger.cpp
@@ -28,8 +28,8 @@
 #include "util/wgt2allg.h"              // exists()
 #include "platform/base/agsplatformdriver.h"
 
-using AGS::Common::Stream;
-using AGS::Common::TextStreamWriter;
+using AGS::Shared::Stream;
+using AGS::Shared::TextStreamWriter;
 
 const char *SENT_MESSAGE_FILE_NAME = "dbgrecv.tmp";
 
diff --git a/engines/ags/engine/debugging/logfile.cpp b/engines/ags/engine/debugging/logfile.cpp
index 444b880bb3..ab1639991a 100644
--- a/engines/ags/engine/debugging/logfile.cpp
+++ b/engines/ags/engine/debugging/logfile.cpp
@@ -29,7 +29,7 @@
 namespace AGS {
 namespace Engine {
 
-using namespace Common;
+using namespace Shared;
 
 LogFile::LogFile()
 	: _openMode(kLogFile_Overwrite) {
diff --git a/engines/ags/engine/debugging/logfile.h b/engines/ags/engine/debugging/logfile.h
index 674a097e8c..45298067d1 100644
--- a/engines/ags/engine/debugging/logfile.h
+++ b/engines/ags/engine/debugging/logfile.h
@@ -41,7 +41,7 @@
 namespace AGS3 {
 namespace AGS {
 
-namespace Common {
+namespace Shared {
 class Stream;
 } // namespace Shared
 
@@ -51,7 +51,7 @@ using Common::DebugMessage;
 using Common::Stream;
 using Common::String;
 
-class LogFile : public AGS::Common::IOutputHandler {
+class LogFile : public AGS::Shared::IOutputHandler {
 public:
 	enum OpenMode {
 		kLogFile_Overwrite,
diff --git a/engines/ags/engine/debugging/messagebuffer.cpp b/engines/ags/engine/debugging/messagebuffer.cpp
index 3ae8f42799..3413aa5b26 100644
--- a/engines/ags/engine/debugging/messagebuffer.cpp
+++ b/engines/ags/engine/debugging/messagebuffer.cpp
@@ -26,7 +26,7 @@
 namespace AGS {
 namespace Engine {
 
-using namespace Common;
+using namespace Shared;
 
 MessageBuffer::MessageBuffer(size_t buffer_limit)
 	: _bufferLimit(buffer_limit)
diff --git a/engines/ags/engine/debugging/messagebuffer.h b/engines/ags/engine/debugging/messagebuffer.h
index f704af8fbe..4c5d822e3e 100644
--- a/engines/ags/engine/debugging/messagebuffer.h
+++ b/engines/ags/engine/debugging/messagebuffer.h
@@ -41,7 +41,7 @@ namespace Engine {
 using Common::String;
 using Common::DebugMessage;
 
-class MessageBuffer : public AGS::Common::IOutputHandler {
+class MessageBuffer : public AGS::Shared::IOutputHandler {
 public:
 	MessageBuffer(size_t buffer_limit = 1024);
 
diff --git a/engines/ags/engine/device/mousew32.cpp b/engines/ags/engine/device/mousew32.cpp
index 66b0b147c3..d15a133573 100644
--- a/engines/ags/engine/device/mousew32.cpp
+++ b/engines/ags/engine/device/mousew32.cpp
@@ -60,7 +60,7 @@
 #include "ac/sys_events.h" // j for ags_iskeypressed
 #endif
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 
diff --git a/engines/ags/engine/device/mousew32.h b/engines/ags/engine/device/mousew32.h
index d5f852eabc..128782ea04 100644
--- a/engines/ags/engine/device/mousew32.h
+++ b/engines/ags/engine/device/mousew32.h
@@ -39,7 +39,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Bitmap;
 } // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/engine/game/game_init.cpp b/engines/ags/engine/game/game_init.cpp
index f2b37d1ac0..8ba060cfa6 100644
--- a/engines/ags/engine/game/game_init.cpp
+++ b/engines/ags/engine/game/game_init.cpp
@@ -51,7 +51,7 @@
 #include "util/string_utils.h"
 #include "media/audio/audio_system.h"
 
-using namespace Common;
+using namespace Shared;
 using namespace Engine;
 
 extern GameSetupStruct game;
diff --git a/engines/ags/engine/game/game_init.h b/engines/ags/engine/game/game_init.h
index e1921006ef..ec905d981e 100644
--- a/engines/ags/engine/game/game_init.h
+++ b/engines/ags/engine/game/game_init.h
@@ -37,7 +37,7 @@ namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
-using namespace Common;
+using namespace Shared;
 
 // Error codes for initializing the game
 enum GameInitErrorType {
diff --git a/engines/ags/engine/game/savegame.cpp b/engines/ags/engine/game/savegame.cpp
index fcafebf060..693794a957 100644
--- a/engines/ags/engine/game/savegame.cpp
+++ b/engines/ags/engine/game/savegame.cpp
@@ -62,7 +62,7 @@
 #include "util/string_utils.h"
 #include "media/audio/audio_system.h"
 
-using namespace Common;
+using namespace Shared;
 using namespace Engine;
 
 // function is currently implemented in game.cpp
diff --git a/engines/ags/engine/game/savegame.h b/engines/ags/engine/game/savegame.h
index ac605a3ab1..1445d07907 100644
--- a/engines/ags/engine/game/savegame.h
+++ b/engines/ags/engine/game/savegame.h
@@ -31,7 +31,7 @@
 namespace AGS3 {
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Bitmap;
 class Stream;
 } // namespace Shared
diff --git a/engines/ags/engine/game/savegame_components.cpp b/engines/ags/engine/game/savegame_components.cpp
index 8c69ecb3c8..b716e1db4d 100644
--- a/engines/ags/engine/game/savegame_components.cpp
+++ b/engines/ags/engine/game/savegame_components.cpp
@@ -60,7 +60,7 @@
 #include "util/filestream.h" // TODO: needed only because plugins expect file handle
 #include "media/audio/audio_system.h"
 
-using namespace Common;
+using namespace Shared;
 
 extern GameSetupStruct game;
 extern color palette[256];
diff --git a/engines/ags/engine/game/savegame_components.h b/engines/ags/engine/game/savegame_components.h
index 32797df54d..009516e505 100644
--- a/engines/ags/engine/game/savegame_components.h
+++ b/engines/ags/engine/game/savegame_components.h
@@ -29,7 +29,7 @@
 namespace AGS3 {
 namespace AGS {
 
-namespace Common {
+namespace Shared {
 struct Interaction;
 } // namespace Shared
 
diff --git a/engines/ags/engine/game/savegame_internal.h b/engines/ags/engine/game/savegame_internal.h
index e2dba2fedd..11cdd70762 100644
--- a/engines/ags/engine/game/savegame_internal.h
+++ b/engines/ags/engine/game/savegame_internal.h
@@ -33,7 +33,7 @@ namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
-using AGS::Common::Bitmap;
+using AGS::Shared::Bitmap;
 
 typedef std::shared_ptr<Bitmap> PBitmap;
 
diff --git a/engines/ags/engine/game/viewport.cpp b/engines/ags/engine/game/viewport.cpp
index 30390da8e7..6bb62c5952 100644
--- a/engines/ags/engine/game/viewport.cpp
+++ b/engines/ags/engine/game/viewport.cpp
@@ -26,7 +26,7 @@
 #include "game/roomstruct.h"
 #include "game/viewport.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern RoomStruct thisroom;
 
diff --git a/engines/ags/engine/gfx/ali3dogl.cpp b/engines/ags/engine/gfx/ali3dogl.cpp
index 68102c6b0b..406449cc23 100644
--- a/engines/ags/engine/gfx/ali3dogl.cpp
+++ b/engines/ags/engine/gfx/ali3dogl.cpp
@@ -124,7 +124,7 @@ namespace AGS {
 namespace Engine {
 namespace OGL {
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 void ogl_dummy_vsync() { }
 
diff --git a/engines/ags/engine/gfx/ali3dsw.cpp b/engines/ags/engine/gfx/ali3dsw.cpp
index c0f7836b05..3ade745800 100644
--- a/engines/ags/engine/gfx/ali3dsw.cpp
+++ b/engines/ags/engine/gfx/ali3dsw.cpp
@@ -60,7 +60,7 @@ namespace AGS {
 namespace Engine {
 namespace ALSW {
 
-using namespace Common;
+using namespace Shared;
 
 bool ALSoftwareGfxModeList::GetMode(int index, DisplayMode &mode) const {
 	if (_gfxModeList && index >= 0 && index < _gfxModeList->num_modes) {
diff --git a/engines/ags/engine/gfx/ali3dsw.h b/engines/ags/engine/gfx/ali3dsw.h
index c382913820..0788549a2d 100644
--- a/engines/ags/engine/gfx/ali3dsw.h
+++ b/engines/ags/engine/gfx/ali3dsw.h
@@ -52,7 +52,7 @@ namespace Engine {
 namespace ALSW {
 
 class AllegroGfxFilter;
-using AGS::Common::Bitmap;
+using AGS::Shared::Bitmap;
 
 class ALSoftwareBitmap : public IDriverDependantBitmap {
 public:
diff --git a/engines/ags/engine/gfx/gfx_util.cpp b/engines/ags/engine/gfx/gfx_util.cpp
index 8fc9629b83..314c2c6d8a 100644
--- a/engines/ags/engine/gfx/gfx_util.cpp
+++ b/engines/ags/engine/gfx/gfx_util.cpp
@@ -32,7 +32,7 @@ extern int psp_gfx_renderer;
 namespace AGS {
 namespace Engine {
 
-using namespace Common;
+using namespace Shared;
 
 namespace GfxUtil {
 
diff --git a/engines/ags/engine/gfx/gfxdriverbase.cpp b/engines/ags/engine/gfx/gfxdriverbase.cpp
index 2081c75be9..1a10be6b83 100644
--- a/engines/ags/engine/gfx/gfxdriverbase.cpp
+++ b/engines/ags/engine/gfx/gfxdriverbase.cpp
@@ -27,7 +27,7 @@
 #include "gfx/gfxdriverbase.h"
 #include "gfx/gfx_util.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 namespace AGS {
 namespace Engine {
diff --git a/engines/ags/engine/gfx/gfxfilter_allegro.cpp b/engines/ags/engine/gfx/gfxfilter_allegro.cpp
index 47ac6efb2d..94177683c2 100644
--- a/engines/ags/engine/gfx/gfxfilter_allegro.cpp
+++ b/engines/ags/engine/gfx/gfxfilter_allegro.cpp
@@ -26,7 +26,7 @@ namespace AGS {
 namespace Engine {
 namespace ALSW {
 
-using namespace Common;
+using namespace Shared;
 
 const GfxFilterInfo AllegroGfxFilter::FilterInfo = GfxFilterInfo("StdScale", "Nearest-neighbour");
 
diff --git a/engines/ags/engine/gfx/gfxfilter_hqx.cpp b/engines/ags/engine/gfx/gfxfilter_hqx.cpp
index 082fc906a7..9bee9d28af 100644
--- a/engines/ags/engine/gfx/gfxfilter_hqx.cpp
+++ b/engines/ags/engine/gfx/gfxfilter_hqx.cpp
@@ -28,7 +28,7 @@ namespace AGS {
 namespace Engine {
 namespace ALSW {
 
-using namespace Common;
+using namespace Shared;
 
 const GfxFilterInfo HqxGfxFilter::FilterInfo = GfxFilterInfo("Hqx", "Hqx (High Quality)", 2, 3);
 
diff --git a/engines/ags/engine/gfx/graphicsdriver.h b/engines/ags/engine/gfx/graphicsdriver.h
index 70c39574fb..4af864a39b 100644
--- a/engines/ags/engine/gfx/graphicsdriver.h
+++ b/engines/ags/engine/gfx/graphicsdriver.h
@@ -37,10 +37,10 @@
 namespace AGS3 {
 namespace AGS {
 
-namespace Common {
+namespace Shared {
 class Bitmap;
 typedef std::shared_ptr<Common::Bitmap> PBitmap;
-} // namespace Common
+} // namespace Shared
 
 namespace Engine {
 
diff --git a/engines/ags/engine/gui/animatingguibutton.cpp b/engines/ags/engine/gui/animatingguibutton.cpp
index 68e7ad1f66..a5fcb1aa05 100644
--- a/engines/ags/engine/gui/animatingguibutton.cpp
+++ b/engines/ags/engine/gui/animatingguibutton.cpp
@@ -23,7 +23,7 @@
 #include "gui/animatingguibutton.h"
 #include "util/stream.h"
 
-using AGS::Common::Stream;
+using AGS::Shared::Stream;
 
 void AnimatingGUIButton::ReadFromFile(Stream *in) {
 	buttonid = in->ReadInt16();
diff --git a/engines/ags/engine/gui/animatingguibutton.h b/engines/ags/engine/gui/animatingguibutton.h
index 0445f1c636..f0610f8d62 100644
--- a/engines/ags/engine/gui/animatingguibutton.h
+++ b/engines/ags/engine/gui/animatingguibutton.h
@@ -29,7 +29,7 @@ namespace AGS3 {
 
 // Forward declaration
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 }
 }
diff --git a/engines/ags/engine/gui/cscidialog.cpp b/engines/ags/engine/gui/cscidialog.cpp
index 6bd1de8894..6c6cac7523 100644
--- a/engines/ags/engine/gui/cscidialog.cpp
+++ b/engines/ags/engine/gui/cscidialog.cpp
@@ -43,8 +43,8 @@
 #include "platform/base/agsplatformdriver.h"
 #include "ac/timer.h"
 
-using AGS::Common::Bitmap;
-namespace BitmapHelper = AGS::Common::BitmapHelper;
+using AGS::Shared::Bitmap;
+namespace BitmapHelper = AGS::Shared::BitmapHelper;
 
 extern char ignore_bounds; // from mousew32
 extern IGraphicsDriver *gfxDriver;
diff --git a/engines/ags/engine/gui/gui_engine.cpp b/engines/ags/engine/gui/gui_engine.cpp
index 154db1160f..e19c753eea 100644
--- a/engines/ags/engine/gui/gui_engine.cpp
+++ b/engines/ags/engine/gui/gui_engine.cpp
@@ -44,7 +44,7 @@
 #include "gfx/bitmap.h"
 #include "gfx/blender.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 // For engine these are defined in ac.cpp
 extern int eip_guiobj;
@@ -109,7 +109,7 @@ int get_eip_guiobj() {
 bool outlineGuiObjects = false;
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 bool GUIObject::IsClickable() const {
 	return (Flags & kGUICtrl_Clickable) != 0;
@@ -156,5 +156,5 @@ void GUIButton::PrepareTextToDraw() {
 		_textToDraw = _text;
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/engine/gui/guidialog.cpp b/engines/ags/engine/gui/guidialog.cpp
index dde29885dc..cc9b7c977a 100644
--- a/engines/ags/engine/gui/guidialog.cpp
+++ b/engines/ags/engine/gui/guidialog.cpp
@@ -34,7 +34,7 @@
 #include "gfx/graphicsdriver.h"
 #include "debug/debug_log.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern IGraphicsDriver *gfxDriver;
diff --git a/engines/ags/engine/gui/guidialog.h b/engines/ags/engine/gui/guidialog.h
index 16bb1dedff..dcca3af214 100644
--- a/engines/ags/engine/gui/guidialog.h
+++ b/engines/ags/engine/gui/guidialog.h
@@ -25,15 +25,15 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Bitmap;
 }
 }
 
 // Functions for handling hard-coded GUIs
 // Prepares GUI bitmaps which will be passed to the renderer's draw chain
-AGS::Common::Bitmap *prepare_gui_screen(int x, int y, int width, int height, bool opaque);
-AGS::Common::Bitmap *get_gui_screen();
+AGS::Shared::Bitmap *prepare_gui_screen(int x, int y, int width, int height, bool opaque);
+AGS::Shared::Bitmap *get_gui_screen();
 // Deletes GUI bitmaps
 void clear_gui_screen();
 // Draws virtual screen contents on the GUI bitmaps and assignes them to
diff --git a/engines/ags/engine/gui/guidialogdefines.h b/engines/ags/engine/gui/guidialogdefines.h
index e605424200..3b92cf62e8 100644
--- a/engines/ags/engine/gui/guidialogdefines.h
+++ b/engines/ags/engine/gui/guidialogdefines.h
@@ -88,7 +88,7 @@ namespace AGS3 {
 #define CTB_KEYPRESS 91
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Bitmap;
 }
 }
diff --git a/engines/ags/engine/gui/mylabel.cpp b/engines/ags/engine/gui/mylabel.cpp
index 5068358f17..ce173d589d 100644
--- a/engines/ags/engine/gui/mylabel.cpp
+++ b/engines/ags/engine/gui/mylabel.cpp
@@ -29,7 +29,7 @@
 #include "gui/mylabel.h"
 #include "gui/guidialoginternaldefs.h"
 
-using namespace Common;
+using namespace Shared;
 
 extern GameSetup usetup;
 
diff --git a/engines/ags/engine/gui/mylistbox.cpp b/engines/ags/engine/gui/mylistbox.cpp
index cee6e3bf1c..95a1f2d2ee 100644
--- a/engines/ags/engine/gui/mylistbox.cpp
+++ b/engines/ags/engine/gui/mylistbox.cpp
@@ -30,7 +30,7 @@
 #include "gui/guidialoginternaldefs.h"
 #include "gui/mylistbox.h"
 
-using AGS::Common::Bitmap;
+using AGS::Shared::Bitmap;
 
 extern GameSetup usetup;
 extern int numcurso, hotx, hoty;
diff --git a/engines/ags/engine/gui/mypushbutton.cpp b/engines/ags/engine/gui/mypushbutton.cpp
index f9432db1ac..8aa7ff69db 100644
--- a/engines/ags/engine/gui/mypushbutton.cpp
+++ b/engines/ags/engine/gui/mypushbutton.cpp
@@ -33,7 +33,7 @@
 #include "platform/base/agsplatformdriver.h"
 #include "ac/timer.h"
 
-using AGS::Common::Bitmap;
+using AGS::Shared::Bitmap;
 
 extern int windowbackgroundcolor, pushbuttondarkcolor;
 extern int pushbuttonlightcolor;
diff --git a/engines/ags/engine/gui/mytextbox.cpp b/engines/ags/engine/gui/mytextbox.cpp
index 5f23f9fd54..fe545e917a 100644
--- a/engines/ags/engine/gui/mytextbox.cpp
+++ b/engines/ags/engine/gui/mytextbox.cpp
@@ -27,7 +27,7 @@
 #include "gui/guidialoginternaldefs.h"
 #include "gfx/bitmap.h"
 
-using AGS::Common::Bitmap;
+using AGS::Shared::Bitmap;
 
 extern GameSetup usetup;
 
diff --git a/engines/ags/engine/main/config.cpp b/engines/ags/engine/main/config.cpp
index 54b76d84ca..9a6c5e4936 100644
--- a/engines/ags/engine/main/config.cpp
+++ b/engines/ags/engine/main/config.cpp
@@ -46,7 +46,7 @@
 #include "media/audio/audio_system.h"
 
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern GameSetupStruct game;
@@ -310,7 +310,7 @@ void read_game_data_location(const ConfigTree &cfg) {
 	if (!usetup.data_files_dir.IsEmpty()) {
 		// strip any trailing slash
 		// TODO: move this to Path namespace later
-		AGS::Common::Path::FixupPath(usetup.data_files_dir);
+		AGS::Shared::Path::FixupPath(usetup.data_files_dir);
 #if AGS_PLATFORM_OS_WINDOWS
 		// if the path is just x:\ don't strip the slash
 		if (!(usetup.data_files_dir.GetLength() == 3 && usetup.data_files_dir[1u] == ':')) {
diff --git a/engines/ags/engine/main/config.h b/engines/ags/engine/main/config.h
index 528ce79582..62ff8c98fb 100644
--- a/engines/ags/engine/main/config.h
+++ b/engines/ags/engine/main/config.h
@@ -28,8 +28,8 @@
 
 namespace AGS3 {
 
-using AGS::Common::String;
-using AGS::Common::ConfigTree;
+using AGS::Shared::String;
+using AGS::Shared::ConfigTree;
 
 // Set up default config settings
 void config_defaults();
@@ -40,7 +40,7 @@ String find_user_global_cfg_file();
 // Find and game-specific user configuration file (located into writable user directory)
 String find_user_cfg_file();
 // Read optional data file name and location from config
-void read_game_data_location(const AGS::Common::ConfigTree &cfg);
+void read_game_data_location(const AGS::Shared::ConfigTree &cfg);
 // Apply overriding values from the external config (e.g. for mobile ports)
 void override_config_ext(ConfigTree &cfg);
 // Setup game using final config tree
diff --git a/engines/ags/engine/main/engine.cpp b/engines/ags/engine/main/engine.cpp
index 46ce312bd1..89f3d3bf58 100644
--- a/engines/ags/engine/main/engine.cpp
+++ b/engines/ags/engine/main/engine.cpp
@@ -79,7 +79,7 @@
 #include "util/misc.h"
 #include "util/path.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern char check_dynamic_sprites_at_exit;
diff --git a/engines/ags/engine/main/engine.h b/engines/ags/engine/main/engine.h
index 1efa0ec072..d27e4fe89d 100644
--- a/engines/ags/engine/main/engine.h
+++ b/engines/ags/engine/main/engine.h
@@ -31,7 +31,7 @@ const char *get_engine_name();
 const char *get_engine_version();
 void        show_preload();
 void        engine_init_game_settings();
-int         initialize_engine(const AGS::Common::ConfigTree &startup_opts);
+int         initialize_engine(const AGS::Shared::ConfigTree &startup_opts);
 
 struct ScreenSetup;
 // Try to set new graphics mode deduced from given configuration;
@@ -44,7 +44,7 @@ bool        engine_try_switch_windowed_gfxmode();
 // Shutdown graphics mode (used before shutting down tha application)
 void        engine_shutdown_gfxmode();
 
-using AGS::Common::String;
+using AGS::Shared::String;
 // Defines a package file location
 struct PackLocation {
 	String Name; // filename, for the reference or to use as an ID
diff --git a/engines/ags/engine/main/engine_setup.cpp b/engines/ags/engine/main/engine_setup.cpp
index f29f5bb399..22ae40663a 100644
--- a/engines/ags/engine/main/engine_setup.cpp
+++ b/engines/ags/engine/main/engine_setup.cpp
@@ -44,7 +44,7 @@
 #include "media/video/video.h"
 #include "platform/base/agsplatformdriver.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern GameSetupStruct game;
diff --git a/engines/ags/engine/main/game_file.cpp b/engines/ags/engine/main/game_file.cpp
index e97e634910..857f80880a 100644
--- a/engines/ags/engine/main/game_file.cpp
+++ b/engines/ags/engine/main/game_file.cpp
@@ -53,7 +53,7 @@
 #include "plugin/agsplugin.h"
 #include "script/script.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern int ifacepopped;
diff --git a/engines/ags/engine/main/game_file.h b/engines/ags/engine/main/game_file.h
index f822ed0cfd..d1487c9a64 100644
--- a/engines/ags/engine/main/game_file.h
+++ b/engines/ags/engine/main/game_file.h
@@ -28,7 +28,7 @@
 
 namespace AGS3 {
 
-using AGS::Common::HError;
+using AGS::Shared::HError;
 
 // Preload particular game-describing parameters from the game data header (title, save game dir name, etc)
 HError preload_game_data();
diff --git a/engines/ags/engine/main/game_run.cpp b/engines/ags/engine/main/game_run.cpp
index 589a6b78be..1532bf611f 100644
--- a/engines/ags/engine/main/game_run.cpp
+++ b/engines/ags/engine/main/game_run.cpp
@@ -66,7 +66,7 @@
 #include "ac/timer.h"
 #include "ac/keycode.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern AnimatingGUIButton animbuts[MAX_ANIMATING_BUTTONS];
 extern int numAnimButs;
diff --git a/engines/ags/engine/main/game_start.cpp b/engines/ags/engine/main/game_start.cpp
index 0b4c609c6b..aad1e43195 100644
--- a/engines/ags/engine/main/game_start.cpp
+++ b/engines/ags/engine/main/game_start.cpp
@@ -44,7 +44,7 @@
 #include "media/audio/audio_system.h"
 #include "ac/timer.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern int our_eip, displayed_room;
diff --git a/engines/ags/engine/main/graphics_mode.cpp b/engines/ags/engine/main/graphics_mode.cpp
index c99ac6096c..986b332414 100644
--- a/engines/ags/engine/main/graphics_mode.cpp
+++ b/engines/ags/engine/main/graphics_mode.cpp
@@ -45,7 +45,7 @@
 #define USE_SIMPLE_GFX_INIT
 #endif
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern int proper_exit;
diff --git a/engines/ags/engine/main/graphics_mode.h b/engines/ags/engine/main/graphics_mode.h
index facdea50d8..26c377f04f 100644
--- a/engines/ags/engine/main/graphics_mode.h
+++ b/engines/ags/engine/main/graphics_mode.h
@@ -29,7 +29,7 @@
 
 namespace AGS3 {
 
-using AGS::Common::String;
+using AGS::Shared::String;
 using AGS::Engine::DisplayMode;
 
 Size get_desktop_size();
diff --git a/engines/ags/engine/main/main.cpp b/engines/ags/engine/main/main.cpp
index 4ed51f38e0..d41abba506 100644
--- a/engines/ags/engine/main/main.cpp
+++ b/engines/ags/engine/main/main.cpp
@@ -63,7 +63,7 @@
 #define USE_CUSTOM_EXCEPTION_HANDLER
 #endif
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 String appDirectory; // Needed for library loading
@@ -140,11 +140,11 @@ void main_create_platform_driver() {
 #define SVG_VERSION_FWCOMPAT_REVISION   1111
 
 // Current engine version
-AGS::Common::Version EngineVersion;
+AGS::Shared::Version EngineVersion;
 // Lowest savedgame version, accepted by this engine
-AGS::Common::Version SavedgameLowestBackwardCompatVersion;
+AGS::Shared::Version SavedgameLowestBackwardCompatVersion;
 // Lowest engine version, which would accept current savedgames
-AGS::Common::Version SavedgameLowestForwardCompatVersion;
+AGS::Shared::Version SavedgameLowestForwardCompatVersion;
 
 void main_init(int argc, char *argv[]) {
 	EngineVersion = Version(ACI_VERSION_STR " " SPECIAL_VERSION);
diff --git a/engines/ags/engine/main/main.h b/engines/ags/engine/main/main.h
index 1b15acafc2..a3da94db6a 100644
--- a/engines/ags/engine/main/main.h
+++ b/engines/ags/engine/main/main.h
@@ -29,22 +29,22 @@
 namespace AGS3 {
 
 // Current engine version
-extern AGS::Common::Version EngineVersion;
+extern AGS::Shared::Version EngineVersion;
 // Lowest savedgame version, accepted by this engine
-extern AGS::Common::Version SavedgameLowestBackwardCompatVersion;
+extern AGS::Shared::Version SavedgameLowestBackwardCompatVersion;
 // Lowest engine version, which would accept current savedgames
-extern AGS::Common::Version SavedgameLowestForwardCompatVersion;
+extern AGS::Shared::Version SavedgameLowestForwardCompatVersion;
 
 //=============================================================================
 
 extern char **global_argv;
 
 // Location of the engine executable
-extern AGS::Common::String appDirectory;
+extern AGS::Shared::String appDirectory;
 // Game path from the startup options (before reading config)
-extern AGS::Common::String cmdGameDataPath;
+extern AGS::Shared::String cmdGameDataPath;
 
-AGS::Common::String GetPathFromCmdArg(int arg_index);
+AGS::Shared::String GetPathFromCmdArg(int arg_index);
 
 // Startup flags, set from parameters to engine
 extern int force_window;
diff --git a/engines/ags/engine/main/quit.cpp b/engines/ags/engine/main/quit.cpp
index 45f7036d3b..5412b7d9a1 100644
--- a/engines/ags/engine/main/quit.cpp
+++ b/engines/ags/engine/main/quit.cpp
@@ -47,7 +47,7 @@
 #include "plugin/plugin_engine.h"
 #include "media/audio/audio_system.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern GameSetupStruct game;
diff --git a/engines/ags/engine/main/update.cpp b/engines/ags/engine/main/update.cpp
index 48ad214c2c..54a54daff2 100644
--- a/engines/ags/engine/main/update.cpp
+++ b/engines/ags/engine/main/update.cpp
@@ -49,7 +49,7 @@
 #include "main/game_run.h"
 #include "ac/movelist.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern MoveList *mls;
diff --git a/engines/ags/engine/media/audio/ambientsound.cpp b/engines/ags/engine/media/audio/ambientsound.cpp
index a2676a85c7..ce89b44cc1 100644
--- a/engines/ags/engine/media/audio/ambientsound.cpp
+++ b/engines/ags/engine/media/audio/ambientsound.cpp
@@ -25,7 +25,7 @@
 #include "media/audio/soundclip.h"
 #include "util/stream.h"
 
-using AGS::Common::Stream;
+using AGS::Shared::Stream;
 
 bool AmbientSound::IsPlaying() {
 	if (channel <= 0)
diff --git a/engines/ags/engine/media/audio/ambientsound.h b/engines/ags/engine/media/audio/ambientsound.h
index c0f06ca689..5c5d8955a0 100644
--- a/engines/ags/engine/media/audio/ambientsound.h
+++ b/engines/ags/engine/media/audio/ambientsound.h
@@ -27,7 +27,7 @@ namespace AGS3 {
 
 // Forward declaration
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 }
 }
diff --git a/engines/ags/engine/media/audio/audio.cpp b/engines/ags/engine/media/audio/audio.cpp
index 12f8188824..ffc2ba392d 100644
--- a/engines/ags/engine/media/audio/audio.cpp
+++ b/engines/ags/engine/media/audio/audio.cpp
@@ -47,7 +47,7 @@
 #include "ac/timer.h"
 #include "main/game_run.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 //-----------------------
diff --git a/engines/ags/engine/media/audio/queuedaudioitem.cpp b/engines/ags/engine/media/audio/queuedaudioitem.cpp
index d2b9330240..66be4bf249 100644
--- a/engines/ags/engine/media/audio/queuedaudioitem.cpp
+++ b/engines/ags/engine/media/audio/queuedaudioitem.cpp
@@ -24,7 +24,7 @@
 #include "ac/common_defines.h"
 #include "util/stream.h"
 
-using AGS::Common::Stream;
+using AGS::Shared::Stream;
 
 // [IKM] 2012-07-02: these functions are used during load/save game,
 // and read/written as-is, hence cachedClip pointer should be serialized
diff --git a/engines/ags/engine/media/audio/queuedaudioitem.h b/engines/ags/engine/media/audio/queuedaudioitem.h
index 99a917c99f..14907e6559 100644
--- a/engines/ags/engine/media/audio/queuedaudioitem.h
+++ b/engines/ags/engine/media/audio/queuedaudioitem.h
@@ -28,7 +28,7 @@ namespace AGS3 {
 struct SOUNDCLIP;
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 } // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/engine/media/audio/soundcache.cpp b/engines/ags/engine/media/audio/soundcache.cpp
index fed227a0ff..fdeae5cbde 100644
--- a/engines/ags/engine/media/audio/soundcache.cpp
+++ b/engines/ags/engine/media/audio/soundcache.cpp
@@ -31,7 +31,7 @@
 #include "util/string.h"
 #include "debug/out.h"
 
-using namespace Common;
+using namespace Shared;
 
 sound_cache_entry_t *sound_cache_entries = nullptr;
 unsigned int sound_cache_counter = 0;
diff --git a/engines/ags/engine/media/video/video.cpp b/engines/ags/engine/media/video/video.cpp
index e1930078d6..b26b41321c 100644
--- a/engines/ags/engine/media/video/video.cpp
+++ b/engines/ags/engine/media/video/video.cpp
@@ -50,7 +50,7 @@
 #include "util/stream.h"
 #include "media/audio/audio_system.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 
diff --git a/engines/ags/engine/platform/android/acpland.cpp b/engines/ags/engine/platform/android/acpland.cpp
index 640691c5f8..83d3136bda 100644
--- a/engines/ags/engine/platform/android/acpland.cpp
+++ b/engines/ags/engine/platform/android/acpland.cpp
@@ -41,7 +41,7 @@
 #include <jni.h>
 #include <android/log.h>
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 #define ANDROID_CONFIG_FILENAME "android.cfg"
 
diff --git a/engines/ags/engine/platform/base/agsplatformdriver.cpp b/engines/ags/engine/platform/base/agsplatformdriver.cpp
index 3c64c6759a..79db1193d7 100644
--- a/engines/ags/engine/platform/base/agsplatformdriver.cpp
+++ b/engines/ags/engine/platform/base/agsplatformdriver.cpp
@@ -38,7 +38,7 @@
 #include "ac/timer.h"
 #include "media/audio/audio_system.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 #if defined (AGS_HAS_CD_AUDIO)
diff --git a/engines/ags/engine/platform/base/agsplatformdriver.h b/engines/ags/engine/platform/base/agsplatformdriver.h
index 360d3600df..863af0f525 100644
--- a/engines/ags/engine/platform/base/agsplatformdriver.h
+++ b/engines/ags/engine/platform/base/agsplatformdriver.h
@@ -38,7 +38,7 @@
 namespace AGS3 {
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 }
 namespace Engine {
@@ -65,7 +65,7 @@ enum SetupReturnValue {
 
 struct AGSPlatformDriver
 	// be used as a output target for logging system
-	: public AGS::Common::IOutputHandler {
+	: public AGS::Shared::IOutputHandler {
 	virtual void AboutToQuitGame();
 	virtual void Delay(int millis);
 	virtual void DisplayAlert(const char *, ...) = 0;
@@ -178,7 +178,7 @@ struct AGSPlatformDriver
 	// IOutputHandler implementation
 	//-----------------------------------------------
 	// Writes to the standard platform's output, prepending "AGS: " prefix to the message
-	void PrintMessage(const AGS::Common::DebugMessage &msg) override;
+	void PrintMessage(const AGS::Shared::DebugMessage &msg) override;
 
 protected:
 	// TODO: this is a quick solution for IOutputHandler implementation
diff --git a/engines/ags/engine/platform/ios/acplios.cpp b/engines/ags/engine/platform/ios/acplios.cpp
index 6d545dc316..672a3b1a20 100644
--- a/engines/ags/engine/platform/ios/acplios.cpp
+++ b/engines/ags/engine/platform/ios/acplios.cpp
@@ -36,7 +36,7 @@
 #include "plugin/agsplugin.h"
 #include "util/string_utils.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 #define IOS_CONFIG_FILENAME "ios.cfg"
 
diff --git a/engines/ags/engine/platform/linux/acpllnx.cpp b/engines/ags/engine/platform/linux/acpllnx.cpp
index 06491c2fa3..9c0ce818da 100644
--- a/engines/ags/engine/platform/linux/acpllnx.cpp
+++ b/engines/ags/engine/platform/linux/acpllnx.cpp
@@ -39,7 +39,7 @@
 #include <pwd.h>
 #include <sys/stat.h>
 
-using AGS::Common::String;
+using AGS::Shared::String;
 
 
 // Replace the default Allegro icon. The original defintion is in the
diff --git a/engines/ags/engine/platform/osx/acplmac.cpp b/engines/ags/engine/platform/osx/acplmac.cpp
index 1fb3489c13..ef815cb945 100644
--- a/engines/ags/engine/platform/osx/acplmac.cpp
+++ b/engines/ags/engine/platform/osx/acplmac.cpp
@@ -70,7 +70,7 @@ AGSMac::AGSMac() {
 	AGSMacInitPaths(psp_game_file_name, libraryApplicationSupport);
 
 	snprintf(commonDataPath, PATH_MAX, "%s/uk.co.adventuregamestudio", libraryApplicationSupport);
-	AGS::Common::Directory::CreateDirectory(commonDataPath);
+	AGS::Shared::Directory::CreateDirectory(commonDataPath);
 
 	strcpy(psp_translation, "default");
 }
diff --git a/engines/ags/engine/platform/windows/acplwin.cpp b/engines/ags/engine/platform/windows/acplwin.cpp
index 0d330d5959..a0097e2793 100644
--- a/engines/ags/engine/platform/windows/acplwin.cpp
+++ b/engines/ags/engine/platform/windows/acplwin.cpp
@@ -55,7 +55,7 @@ extern void dxmedia_resume_video();
 extern char lastError[200];
 #endif
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern GameSetupStruct game;
diff --git a/engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp b/engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
index 70d176d594..2cfa9e0909 100644
--- a/engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
+++ b/engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
@@ -50,7 +50,7 @@ extern int dxmedia_play_video_3d(const char *filename, IDirect3DDevice9 *device,
 extern void dxmedia_shutdown_3d();
 #endif
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 // Necessary to update textures from 8-bit bitmaps
 extern RGB palette[256];
@@ -128,7 +128,7 @@ namespace AGS {
 namespace Engine {
 namespace D3D {
 
-using namespace Common;
+using namespace Shared;
 
 void D3DBitmap::Dispose() {
 	if (_tiles != NULL) {
diff --git a/engines/ags/engine/platform/windows/gfx/ali3dd3d.h b/engines/ags/engine/platform/windows/gfx/ali3dd3d.h
index 4a75d322b4..2833ef7ae8 100644
--- a/engines/ags/engine/platform/windows/gfx/ali3dd3d.h
+++ b/engines/ags/engine/platform/windows/gfx/ali3dd3d.h
@@ -52,8 +52,8 @@ namespace AGS {
 namespace Engine {
 namespace D3D {
 
-using AGS::Common::Bitmap;
-using AGS::Common::String;
+using AGS::Shared::Bitmap;
+using AGS::Shared::String;
 class D3DGfxFilter;
 
 struct D3DTextureTile : public TextureTile {
diff --git a/engines/ags/engine/platform/windows/media/video/acwavi.cpp b/engines/ags/engine/platform/windows/media/video/acwavi.cpp
index 56e7f1fc71..071b942b5f 100644
--- a/engines/ags/engine/platform/windows/media/video/acwavi.cpp
+++ b/engines/ags/engine/platform/windows/media/video/acwavi.cpp
@@ -47,7 +47,7 @@
 #include "main/game_run.h"
 #include "platform/base/agsplatformdriver.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 //link with the following libraries under project/settings/link...
diff --git a/engines/ags/engine/platform/windows/setup/winsetup.cpp b/engines/ags/engine/platform/windows/setup/winsetup.cpp
index bb9b49a421..87a4344067 100644
--- a/engines/ags/engine/platform/windows/setup/winsetup.cpp
+++ b/engines/ags/engine/platform/windows/setup/winsetup.cpp
@@ -68,7 +68,7 @@ extern "C"
 namespace AGS {
 namespace Engine {
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 //=============================================================================
 //
diff --git a/engines/ags/engine/platform/windows/setup/winsetup.h b/engines/ags/engine/platform/windows/setup/winsetup.h
index 87192595fd..b07ec14fe7 100644
--- a/engines/ags/engine/platform/windows/setup/winsetup.h
+++ b/engines/ags/engine/platform/windows/setup/winsetup.h
@@ -36,7 +36,7 @@ namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
-using namespace Common;
+using namespace Shared;
 
 void SetWinIcon();
 SetupReturnValue WinSetup(const ConfigTree &cfg_in, ConfigTree &cfg_out,
diff --git a/engines/ags/engine/platform/windows/win_ex_handling.cpp b/engines/ags/engine/platform/windows/win_ex_handling.cpp
index e27e30aaa0..7cf8f76889 100644
--- a/engines/ags/engine/platform/windows/win_ex_handling.cpp
+++ b/engines/ags/engine/platform/windows/win_ex_handling.cpp
@@ -37,7 +37,7 @@
 #define USE_CUSTOM_EXCEPTION_HANDLER
 #endif
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern int our_eip;
 extern int eip_guinum;
@@ -66,7 +66,7 @@ static void DisplayException() {
 }
 
 int initialize_engine_with_exception_handling(
-    int (initialize_engine)(const AGS::Common::ConfigTree &startup_opts),
+    int (initialize_engine)(const AGS::Shared::ConfigTree &startup_opts),
     const ConfigTree &startup_opts) {
 	__try {
 		Debug::Printf(kDbgMsg_Info, "Installing exception handler");
diff --git a/engines/ags/engine/platform/windows/win_ex_handling.h b/engines/ags/engine/platform/windows/win_ex_handling.h
index c77d4cbf83..e1559a0bb6 100644
--- a/engines/ags/engine/platform/windows/win_ex_handling.h
+++ b/engines/ags/engine/platform/windows/win_ex_handling.h
@@ -29,8 +29,8 @@ namespace AGS3 {
 
 void setup_malloc_handling();
 int  initialize_engine_with_exception_handling(
-	int (initialize_engine)(const AGS::Common::ConfigTree &startup_opts),
-	const AGS::Common::ConfigTree &startup_opts);
+	int (initialize_engine)(const AGS::Shared::ConfigTree &startup_opts),
+	const AGS::Shared::ConfigTree &startup_opts);
 
 } // namespace AGS3
 
diff --git a/engines/ags/engine/plugin/agsplugin.cpp b/engines/ags/engine/plugin/agsplugin.cpp
index 82bcc771fa..ee10afb532 100644
--- a/engines/ags/engine/plugin/agsplugin.cpp
+++ b/engines/ags/engine/plugin/agsplugin.cpp
@@ -74,8 +74,8 @@
 #include "util/filestream.h"
 #include "media/audio/audio_system.h"
 
-using namespace AGS::Common;
-using namespace AGS::Common::Memory;
+using namespace AGS::Shared;
+using namespace AGS::Shared::Memory;
 using namespace AGS::Engine;
 
 
@@ -1010,7 +1010,7 @@ Engine::GameInitError pl_register_plugins(const std::vector<Common::PluginInfo>
 
 		String expect_filename = apl->library.GetFilenameForLib(apl->filename);
 		if (apl->library.Load(apl->filename)) {
-			AGS::Common::Debug::Printf(kDbgMsg_Info, "Plugin '%s' loaded as '%s', resolving imports...", apl->filename, expect_filename.GetCStr());
+			AGS::Shared::Debug::Printf(kDbgMsg_Info, "Plugin '%s' loaded as '%s', resolving imports...", apl->filename, expect_filename.GetCStr());
 
 			if (apl->library.GetFunctionAddress("AGS_PluginV2") == nullptr) {
 				quitprintf("Plugin '%s' is an old incompatible version.", apl->filename);
@@ -1025,16 +1025,16 @@ Engine::GameInitError pl_register_plugins(const std::vector<Common::PluginInfo>
 			apl->debugHook = (int(*)(const char *, int, int))apl->library.GetFunctionAddress("AGS_EngineDebugHook");
 			apl->initGfxHook = (void(*)(const char *, void *))apl->library.GetFunctionAddress("AGS_EngineInitGfx");
 		} else {
-			AGS::Common::Debug::Printf(kDbgMsg_Info, "Plugin '%s' could not be loaded (expected '%s'), trying built-in plugins...",
+			AGS::Shared::Debug::Printf(kDbgMsg_Info, "Plugin '%s' could not be loaded (expected '%s'), trying built-in plugins...",
 			                           apl->filename, expect_filename.GetCStr());
 			if (pl_use_builtin_plugin(apl)) {
-				AGS::Common::Debug::Printf(kDbgMsg_Info, "Build-in plugin '%s' found and being used.", apl->filename);
+				AGS::Shared::Debug::Printf(kDbgMsg_Info, "Build-in plugin '%s' found and being used.", apl->filename);
 			} else {
 				// Plugin loading has failed at this point, try using built-in plugin function stubs
 				if (RegisterPluginStubs((const char *)apl->filename))
-					AGS::Common::Debug::Printf(kDbgMsg_Info, "Placeholder functions for the plugin '%s' found.", apl->filename);
+					AGS::Shared::Debug::Printf(kDbgMsg_Info, "Placeholder functions for the plugin '%s' found.", apl->filename);
 				else
-					AGS::Common::Debug::Printf(kDbgMsg_Info, "No placeholder functions for the plugin '%s' found. The game might fail to load!", apl->filename);
+					AGS::Shared::Debug::Printf(kDbgMsg_Info, "No placeholder functions for the plugin '%s' found. The game might fail to load!", apl->filename);
 				continue;
 			}
 		}
diff --git a/engines/ags/engine/plugin/plugin_engine.h b/engines/ags/engine/plugin/plugin_engine.h
index b988c7544c..2c3e52aed4 100644
--- a/engines/ags/engine/plugin/plugin_engine.h
+++ b/engines/ags/engine/plugin/plugin_engine.h
@@ -39,7 +39,7 @@ namespace AGS3 {
 
 class IAGSEngine;
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 } // namespace Shared
 } // namespace AGS
@@ -58,7 +58,7 @@ bool pl_is_plugin_loaded(const char *pl_name);
 //returns whether _any_ plugins want a particular event
 bool pl_any_want_hook(int event);
 
-void pl_set_file_handle(long data, AGS::Common::Stream *stream);
+void pl_set_file_handle(long data, AGS::Shared::Stream *stream);
 void pl_clear_file_handle();
 
 } // namespace AGS3
diff --git a/engines/ags/engine/script/cc_instance.cpp b/engines/ags/engine/script/cc_instance.cpp
index 9a7055135b..88038dc312 100644
--- a/engines/ags/engine/script/cc_instance.cpp
+++ b/engines/ags/engine/script/cc_instance.cpp
@@ -46,8 +46,8 @@
 #include "util/memory.h"
 #include "util/string_utils.h" // linux strnicmp definition
 
-using namespace AGS::Common;
-using namespace AGS::Common::Memory;
+using namespace AGS::Shared;
+using namespace AGS::Shared::Memory;
 
 extern ccInstance *loadedInstances[MAX_LOADED_INSTANCES]; // in script/script_runtime
 extern int gameHasBeenRestored; // in ac/game
diff --git a/engines/ags/engine/script/runtimescriptvalue.cpp b/engines/ags/engine/script/runtimescriptvalue.cpp
index dac99d5a09..ebcac94e8f 100644
--- a/engines/ags/engine/script/runtimescriptvalue.cpp
+++ b/engines/ags/engine/script/runtimescriptvalue.cpp
@@ -28,7 +28,7 @@
 
 #include <string.h> // for memcpy()
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 //
 // NOTE to future optimizers: I am using 'this' ptr here to better
diff --git a/engines/ags/engine/script/runtimescriptvalue.h b/engines/ags/engine/script/runtimescriptvalue.h
index f7840fdee3..41ae8a5f40 100644
--- a/engines/ags/engine/script/runtimescriptvalue.h
+++ b/engines/ags/engine/script/runtimescriptvalue.h
@@ -307,7 +307,7 @@ public:
 		case kScValGlobalVar:
 		{
 			if (RValue->Type == kScValData) {
-				rval.SetInt32(AGS::Common::Memory::ReadInt32LE(RValue->GetPtrWithOffset() + this->IValue));
+				rval.SetInt32(AGS::Shared::Memory::ReadInt32LE(RValue->GetPtrWithOffset() + this->IValue));
 			} else {
 				rval = *RValue;
 			}
diff --git a/engines/ags/engine/script/script.cpp b/engines/ags/engine/script/script.cpp
index 92c4a3a943..ec59cc6a77 100644
--- a/engines/ags/engine/script/script.cpp
+++ b/engines/ags/engine/script/script.cpp
@@ -608,7 +608,7 @@ void quit_with_script_error(const char *functionName) {
 }
 
 int get_nivalue(InteractionCommandList *nic, int idx, int parm) {
-	if (nic->Cmds[idx].Data[parm].Type == AGS::Common::kInterValVariable) {
+	if (nic->Cmds[idx].Data[parm].Type == AGS::Shared::kInterValVariable) {
 		// return the value of the variable
 		return get_interaction_variable(nic->Cmds[idx].Data[parm].Value)->Value;
 	}
diff --git a/engines/ags/engine/script/script.h b/engines/ags/engine/script/script.h
index cdcababda4..c61f3a357d 100644
--- a/engines/ags/engine/script/script.h
+++ b/engines/ags/engine/script/script.h
@@ -35,10 +35,10 @@
 
 namespace AGS3 {
 
-using AGS::Common::Interaction;
-using AGS::Common::InteractionCommandList;
-using AGS::Common::InteractionScripts;
-using AGS::Common::InteractionVariable;
+using AGS::Shared::Interaction;
+using AGS::Shared::InteractionCommandList;
+using AGS::Shared::InteractionScripts;
+using AGS::Shared::InteractionVariable;
 
 #define LATE_REP_EXEC_ALWAYS_NAME "late_repeatedly_execute_always"
 #define REP_EXEC_ALWAYS_NAME "repeatedly_execute_always"
@@ -67,7 +67,7 @@ int     RunTextScript2IParam(ccInstance *sci, const char *tsname, const RuntimeS
 int     PrepareTextScript(ccInstance *sci, const char **tsname);
 bool    DoRunScriptFuncCantBlock(ccInstance *sci, NonBlockingScriptFunction *funcToRun, bool hasTheFunc);
 
-AGS::Common::String GetScriptName(ccInstance *sci);
+AGS::Shared::String GetScriptName(ccInstance *sci);
 
 //=============================================================================
 
@@ -119,9 +119,9 @@ extern int numScriptModules;
 
 // TODO: find out if these extra arrays are really necessary. This may be remains from the
 // time when the symbol import table was holding raw pointers to char array.
-extern std::vector<AGS::Common::String> characterScriptObjNames;
-extern AGS::Common::String objectScriptObjNames[MAX_ROOM_OBJECTS];
-extern std::vector<AGS::Common::String> guiScriptObjNames;
+extern std::vector<AGS::Shared::String> characterScriptObjNames;
+extern AGS::Shared::String objectScriptObjNames[MAX_ROOM_OBJECTS];
+extern std::vector<AGS::Shared::String> guiScriptObjNames;
 
 } // namespace AGS3
 
diff --git a/engines/ags/engine/script/script_api.cpp b/engines/ags/engine/script/script_api.cpp
index 99c01cd45a..411da69bb3 100644
--- a/engines/ags/engine/script/script_api.cpp
+++ b/engines/ags/engine/script/script_api.cpp
@@ -28,7 +28,7 @@
 #include "script/script_api.h"
 #include "util/math.h"
 
-namespace Math = AGS::Common::Math;
+namespace Math = AGS::Shared::Math;
 
 enum FormatParseResult {
 	kFormatParseNone,
diff --git a/engines/ags/engine/script/script_engine.cpp b/engines/ags/engine/script/script_engine.cpp
index c84c9546c0..3d22a27aad 100644
--- a/engines/ags/engine/script/script_engine.cpp
+++ b/engines/ags/engine/script/script_engine.cpp
@@ -38,11 +38,11 @@
 #include "util/stream.h"
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class RoomStruct;
 }
 }
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 extern void quit(const char *);
 extern int currentline; // in script/script_common
diff --git a/engines/ags/engine/script/script_runtime.h b/engines/ags/engine/script/script_runtime.h
index 31e99850a4..059f0dd6c5 100644
--- a/engines/ags/engine/script/script_runtime.h
+++ b/engines/ags/engine/script/script_runtime.h
@@ -46,8 +46,8 @@ struct ICCStaticObject;
 struct ICCDynamicObject;
 struct StaticArray;
 
-using AGS::Common::String;
-using AGS::Common::String;
+using AGS::Shared::String;
+using AGS::Shared::String;
 
 // ************ SCRIPT LOADING AND RUNNING FUNCTIONS ************
 
diff --git a/engines/ags/engine/script/systemimports.h b/engines/ags/engine/script/systemimports.h
index ab3c717ddb..aef575091d 100644
--- a/engines/ags/engine/script/systemimports.h
+++ b/engines/ags/engine/script/systemimports.h
@@ -31,7 +31,7 @@ namespace AGS3 {
 struct ICCDynamicObject;
 struct ICCStaticObject;
 
-using AGS::Common::String;
+using AGS::Shared::String;
 
 struct ScriptImport {
 	ScriptImport() {
diff --git a/engines/ags/engine/util/library.h b/engines/ags/engine/util/library.h
index 8c726c5571..4745bf1b43 100644
--- a/engines/ags/engine/util/library.h
+++ b/engines/ags/engine/util/library.h
@@ -36,13 +36,13 @@ public:
 
 	virtual ~BaseLibrary() = default;
 
-	virtual AGS::Common::String GetFilenameForLib(AGS::Common::String libraryName) = 0;
+	virtual AGS::Shared::String GetFilenameForLib(AGS::Shared::String libraryName) = 0;
 
-	virtual bool Load(AGS::Common::String libraryName) = 0;
+	virtual bool Load(AGS::Shared::String libraryName) = 0;
 
 	virtual bool Unload() = 0;
 
-	virtual void *GetFunctionAddress(AGS::Common::String functionName) = 0;
+	virtual void *GetFunctionAddress(AGS::Shared::String functionName) = 0;
 };
 
 
diff --git a/engines/ags/engine/util/library_dummy.h b/engines/ags/engine/util/library_dummy.h
index 732c474e65..0972228b30 100644
--- a/engines/ags/engine/util/library_dummy.h
+++ b/engines/ags/engine/util/library_dummy.h
@@ -35,11 +35,11 @@ public:
 	~DummyLibrary() override {
 	};
 
-	AGS::Common::String GetFilenameForLib(AGS::Common::String libraryName) override {
+	AGS::Shared::String GetFilenameForLib(AGS::Shared::String libraryName) override {
 		return libraryName;
 	}
 
-	bool Load(AGS::Common::String libraryName) override {
+	bool Load(AGS::Shared::String libraryName) override {
 		return false;
 	}
 
@@ -47,7 +47,7 @@ public:
 		return true;
 	}
 
-	void *GetFunctionAddress(AGS::Common::String functionName) override {
+	void *GetFunctionAddress(AGS::Shared::String functionName) override {
 		return NULL;
 	}
 };
diff --git a/engines/ags/engine/util/library_posix.h b/engines/ags/engine/util/library_posix.h
index 89e8e4e1ce..40220c6c8f 100644
--- a/engines/ags/engine/util/library_posix.h
+++ b/engines/ags/engine/util/library_posix.h
@@ -34,7 +34,7 @@ namespace AGS3 {
 #if AGS_PLATFORM_OS_ANDROID
 extern char android_app_directory[256];
 #else
-extern AGS::Common::String appDirectory;
+extern AGS::Shared::String appDirectory;
 #endif
 
 
@@ -52,7 +52,7 @@ public:
 		Unload();
 	};
 
-	AGS::Common::String BuildFilename(AGS::Common::String libraryName) {
+	AGS::Shared::String BuildFilename(AGS::Shared::String libraryName) {
 		return String::FromFormat(
 #if AGS_PLATFORM_OS_MACOS
 			"lib%s.dylib"
@@ -62,28 +62,28 @@ public:
 			, libraryName.GetCStr());
 	}
 
-	AGS::Common::String BuildPath(const char *path, AGS::Common::String libraryName) {
-		AGS::Common::String platformLibraryName = "";
+	AGS::Shared::String BuildPath(const char *path, AGS::Shared::String libraryName) {
+		AGS::Shared::String platformLibraryName = "";
 		if (path) {
 			platformLibraryName = path;
 			platformLibraryName.Append("/");
 		}
 		platformLibraryName.Append(BuildFilename(libraryName));
 
-		AGS::Common::Debug::Printf("Built library path: %s", platformLibraryName.GetCStr());
+		AGS::Shared::Debug::Printf("Built library path: %s", platformLibraryName.GetCStr());
 		return platformLibraryName;
 	}
 
-	AGS::Common::String GetFilenameForLib(AGS::Common::String libraryName) override {
+	AGS::Shared::String GetFilenameForLib(AGS::Shared::String libraryName) override {
 		return BuildFilename(libraryName);
 	}
 
-	bool Load(AGS::Common::String libraryName) override {
+	bool Load(AGS::Shared::String libraryName) override {
 		Unload();
 
 		// Try rpath first
 		_library = dlopen(BuildPath(nullptr, libraryName).GetCStr(), RTLD_LAZY);
-		AGS::Common::Debug::Printf("dlopen returned: %s", dlerror());
+		AGS::Shared::Debug::Printf("dlopen returned: %s", dlerror());
 		if (_library != nullptr) {
 			return true;
 		}
@@ -91,7 +91,7 @@ public:
 		// Try current path
 		_library = dlopen(BuildPath(".", libraryName).GetCStr(), RTLD_LAZY);
 
-		AGS::Common::Debug::Printf("dlopen returned: %s", dlerror());
+		AGS::Shared::Debug::Printf("dlopen returned: %s", dlerror());
 
 		if (_library == nullptr) {
 			// Try the engine directory
@@ -104,7 +104,7 @@ public:
 			_library = dlopen(BuildPath(appDirectory, libraryName).GetCStr(), RTLD_LAZY);
 #endif
 
-			AGS::Common::Debug::Printf("dlopen returned: %s", dlerror());
+			AGS::Shared::Debug::Printf("dlopen returned: %s", dlerror());
 		}
 
 		return (_library != nullptr);
@@ -118,7 +118,7 @@ public:
 		}
 	}
 
-	void *GetFunctionAddress(AGS::Common::String functionName) override {
+	void *GetFunctionAddress(AGS::Shared::String functionName) override {
 		if (_library) {
 			return dlsym(_library, functionName.GetCStr());
 		} else {
diff --git a/engines/ags/engine/util/library_psp.h b/engines/ags/engine/util/library_psp.h
index 7d40b01d1d..b8098bbabc 100644
--- a/engines/ags/engine/util/library_psp.h
+++ b/engines/ags/engine/util/library_psp.h
@@ -41,17 +41,17 @@ public:
 		Unload();
 	};
 
-	AGS::Common::String BuildPath(char *path, AGS::Common::String libraryName) {
-		AGS::Common::String platformLibraryName = path;
+	AGS::Shared::String BuildPath(char *path, AGS::Shared::String libraryName) {
+		AGS::Shared::String platformLibraryName = path;
 		platformLibraryName.Append(libraryName);
 		platformLibraryName.Append(".prx");
 
-		AGS::Common::Debug::Printf("Built library path: %s", platformLibraryName.GetCStr());
+		AGS::Shared::Debug::Printf("Built library path: %s", platformLibraryName.GetCStr());
 
 		return platformLibraryName;
 	}
 
-	bool Load(AGS::Common::String libraryName) {
+	bool Load(AGS::Shared::String libraryName) {
 		Unload();
 
 		// Try current path
@@ -66,7 +66,7 @@ public:
 		_moduleName = libraryName;
 		_moduleName.MakeLower();
 
-		AGS::Common::Debug::Printf("Result is %s %d", _moduleName.GetCStr(), _library);
+		AGS::Shared::Debug::Printf("Result is %s %d", _moduleName.GetCStr(), _library);
 
 		return (_library > -1);
 	}
@@ -79,7 +79,7 @@ public:
 		}
 	}
 
-	void *GetFunctionAddress(AGS::Common::String functionName) {
+	void *GetFunctionAddress(AGS::Shared::String functionName) {
 		if (_library > -1) {
 			// On the PSP functions are identified by an ID that is the first 4 byte of the SHA1 of the name.
 			int functionId;
@@ -99,7 +99,7 @@ public:
 			} else if (functionName == "AGS_EngineInitGfx") {
 				functionId = 0xA428D254;
 			} else {
-				AGS::Common::Debug::Printf("Function ID not found: %s", functionName.GetCStr());
+				AGS::Shared::Debug::Printf("Function ID not found: %s", functionName.GetCStr());
 				functionId = -1;
 			}
 #else
@@ -121,7 +121,7 @@ public:
 
 private:
 	SceUID _library;
-	AGS::Common::String _moduleName;
+	AGS::Shared::String _moduleName;
 };
 
 
diff --git a/engines/ags/engine/util/library_windows.h b/engines/ags/engine/util/library_windows.h
index 64882535e9..7695c93fd9 100644
--- a/engines/ags/engine/util/library_windows.h
+++ b/engines/ags/engine/util/library_windows.h
@@ -58,23 +58,23 @@ public:
 		Unload();
 	};
 
-	AGS::Common::String BuildFilename(AGS::Common::String libraryName) {
+	AGS::Shared::String BuildFilename(AGS::Shared::String libraryName) {
 		return String::FromFormat("%s.dll", libraryName.GetCStr());
 	}
 
-	AGS::Common::String BuildPath(AGS::Common::String libraryName) {
-		AGS::Common::String platformLibraryName = BuildFilename(libraryName);
+	AGS::Shared::String BuildPath(AGS::Shared::String libraryName) {
+		AGS::Shared::String platformLibraryName = BuildFilename(libraryName);
 
-		AGS::Common::Debug::Printf("Built library path: %s", platformLibraryName.GetCStr());
+		AGS::Shared::Debug::Printf("Built library path: %s", platformLibraryName.GetCStr());
 
 		return platformLibraryName;
 	}
 
-	AGS::Common::String GetFilenameForLib(AGS::Common::String libraryName) override {
+	AGS::Shared::String GetFilenameForLib(AGS::Shared::String libraryName) override {
 		return BuildFilename(libraryName);
 	}
 
-	bool Load(AGS::Common::String libraryName) {
+	bool Load(AGS::Shared::String libraryName) {
 		Unload();
 
 		_library = LoadLibraryA(BuildPath(libraryName).GetCStr());
@@ -90,7 +90,7 @@ public:
 		}
 	}
 
-	void *GetFunctionAddress(AGS::Common::String functionName) {
+	void *GetFunctionAddress(AGS::Shared::String functionName) {
 		return GetProcAddress(_library, functionName.GetCStr());
 	}
 
diff --git a/engines/ags/engine/util/mutex_base.h b/engines/ags/engine/util/mutex_base.h
index 2344dd006d..5c5339cf30 100644
--- a/engines/ags/engine/util/mutex_base.h
+++ b/engines/ags/engine/util/mutex_base.h
@@ -25,7 +25,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 class BaseMutex {
 public:
@@ -35,7 +35,7 @@ public:
 	virtual void Unlock() = 0;
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/ac/audiocliptype.cpp b/engines/ags/shared/ac/audiocliptype.cpp
index d33ccfad84..f668c6b40b 100644
--- a/engines/ags/shared/ac/audiocliptype.cpp
+++ b/engines/ags/shared/ac/audiocliptype.cpp
@@ -23,7 +23,7 @@
 #include "ac/audiocliptype.h"
 #include "util/stream.h"
 
-using AGS::Common::Stream;
+using AGS::Shared::Stream;
 
 void AudioClipType::ReadFromFile(Stream *in) {
 	id = in->ReadInt32();
diff --git a/engines/ags/shared/ac/audiocliptype.h b/engines/ags/shared/ac/audiocliptype.h
index 9123a56c72..9871c5e294 100644
--- a/engines/ags/shared/ac/audiocliptype.h
+++ b/engines/ags/shared/ac/audiocliptype.h
@@ -27,7 +27,7 @@ namespace AGS3 {
 
 // Forward declaration
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 } // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/ac/characterinfo.cpp b/engines/ags/shared/ac/characterinfo.cpp
index 9ec843cf6c..6a3deb6a73 100644
--- a/engines/ags/shared/ac/characterinfo.cpp
+++ b/engines/ags/shared/ac/characterinfo.cpp
@@ -24,7 +24,7 @@
 #include "ac/characterinfo.h"
 #include "util/stream.h"
 
-using AGS::Common::Stream;
+using AGS::Shared::Stream;
 
 
 void CharacterInfo::ReadFromFile(Stream *in) {
diff --git a/engines/ags/shared/ac/characterinfo.h b/engines/ags/shared/ac/characterinfo.h
index 2649887f85..4a448299ff 100644
--- a/engines/ags/shared/ac/characterinfo.h
+++ b/engines/ags/shared/ac/characterinfo.h
@@ -28,7 +28,7 @@
 namespace AGS3 {
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 } // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/ac/common.cpp b/engines/ags/shared/ac/common.cpp
index d7a2b148a3..156703bf19 100644
--- a/engines/ags/shared/ac/common.cpp
+++ b/engines/ags/shared/ac/common.cpp
@@ -23,7 +23,7 @@
 #include "ac/common.h"
 #include "util/string.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 const char *game_file_sig = "Adventure Creator Game File v2";
 
diff --git a/engines/ags/shared/ac/dialogtopic.cpp b/engines/ags/shared/ac/dialogtopic.cpp
index 7ae5189ddf..f4ffdc0797 100644
--- a/engines/ags/shared/ac/dialogtopic.cpp
+++ b/engines/ags/shared/ac/dialogtopic.cpp
@@ -23,7 +23,7 @@
 #include "ac/dialogtopic.h"
 #include "util/stream.h"
 
-using AGS::Common::Stream;
+using AGS::Shared::Stream;
 
 void DialogTopic::ReadFromFile(Stream *in) {
 	in->ReadArray(optionnames, 150 * sizeof(char), MAXTOPICOPTIONS);
diff --git a/engines/ags/shared/ac/dialogtopic.h b/engines/ags/shared/ac/dialogtopic.h
index 87502041be..e23d534f0f 100644
--- a/engines/ags/shared/ac/dialogtopic.h
+++ b/engines/ags/shared/ac/dialogtopic.h
@@ -26,7 +26,7 @@
 namespace AGS3 {
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 } // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/ac/dynobj/scriptaudioclip.cpp b/engines/ags/shared/ac/dynobj/scriptaudioclip.cpp
index e858f0d63f..a2b90d6f7b 100644
--- a/engines/ags/shared/ac/dynobj/scriptaudioclip.cpp
+++ b/engines/ags/shared/ac/dynobj/scriptaudioclip.cpp
@@ -23,7 +23,7 @@
 #include "ac/dynobj/scriptaudioclip.h"
 #include "util/stream.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 void ScriptAudioClip::ReadFromFile(Stream *in) {
 	id = in->ReadInt32();
diff --git a/engines/ags/shared/ac/dynobj/scriptaudioclip.h b/engines/ags/shared/ac/dynobj/scriptaudioclip.h
index be246866fa..7167a38d4f 100644
--- a/engines/ags/shared/ac/dynobj/scriptaudioclip.h
+++ b/engines/ags/shared/ac/dynobj/scriptaudioclip.h
@@ -28,7 +28,7 @@
 namespace AGS3 {
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 } // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/ac/gamesetupstruct.cpp b/engines/ags/shared/ac/gamesetupstruct.cpp
index 872c7c933d..e94ac5e416 100644
--- a/engines/ags/shared/ac/gamesetupstruct.cpp
+++ b/engines/ags/shared/ac/gamesetupstruct.cpp
@@ -28,7 +28,7 @@
 #include "game/interactions.h"
 #include "util/alignedstream.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 GameSetupStruct::GameSetupStruct()
 	: filever(0)
diff --git a/engines/ags/shared/ac/gamesetupstruct.h b/engines/ags/shared/ac/gamesetupstruct.h
index 21e252c3b4..951bcfbf47 100644
--- a/engines/ags/shared/ac/gamesetupstruct.h
+++ b/engines/ags/shared/ac/gamesetupstruct.h
@@ -39,15 +39,15 @@ namespace AGS {
 namespace Common {
 struct AssetLibInfo;
 struct Interaction;
-struct InteractionScripts;
+namespace SharedonScripts;
 typedef std::shared_ptr<Interaction> PInteraction;
 typedef std::shared_ptr<InteractionScripts> PInteractionScripts;
 } // namespace Shared
 } // namespace AGS
 
-using AGS::Common::PInteraction;
-using AGS::Common::PInteractionScripts;
-using AGS::Common::HGameFileError;
+using AGS::Shared::PInteraction;
+using AGS::Shared::PInteractionScripts;
+using AGS::Shared::HGameFileError;
 struct OldGameSetupStruct;
 
 
@@ -68,9 +68,9 @@ struct GameSetupStruct : public GameSetupStructBase {
 	int               filever;  // just used by editor
 	Common::String    compiled_with; // version of AGS this data was created by
 	char              lipSyncFrameLetters[MAXLIPSYNCFRAMES][50];
-	AGS::Common::PropertySchema propSchema;
-	std::vector<AGS::Common::StringIMap> charProps;
-	AGS::Common::StringIMap invProps[MAX_INV];
+	AGS::Shared::PropertySchema propSchema;
+	std::vector<AGS::Shared::StringIMap> charProps;
+	AGS::Shared::StringIMap invProps[MAX_INV];
 	// NOTE: although the view names are stored in game data, they are never
 	// used, nor registered as script exports; numeric IDs are used to
 	// reference views instead.
diff --git a/engines/ags/shared/ac/gamesetupstructbase.cpp b/engines/ags/shared/ac/gamesetupstructbase.cpp
index 810697592d..cd1caef360 100644
--- a/engines/ags/shared/ac/gamesetupstructbase.cpp
+++ b/engines/ags/shared/ac/gamesetupstructbase.cpp
@@ -27,7 +27,7 @@
 #include "script/cc_script.h"
 #include "util/stream.h"
 
-using AGS::Common::Stream;
+using AGS::Shared::Stream;
 
 GameSetupStructBase::GameSetupStructBase()
 	: numviews(0)
diff --git a/engines/ags/shared/ac/gamesetupstructbase.h b/engines/ags/shared/ac/gamesetupstructbase.h
index 7edfbbad01..fc9ee3cbfd 100644
--- a/engines/ags/shared/ac/gamesetupstructbase.h
+++ b/engines/ags/shared/ac/gamesetupstructbase.h
@@ -32,7 +32,7 @@ namespace AGS3 {
 
 // Forward declaration
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 } // namespace Shared
 } // namespace AGS
@@ -214,7 +214,7 @@ struct GameSetupStructBase {
 	}
 
 	// Returns the expected filename of a digital audio package
-	inline AGS::Common::String GetAudioVOXName() const {
+	inline AGS::Shared::String GetAudioVOXName() const {
 		return IsLegacyAudioSystem() ? "music.vox" : "audio.vox";
 	}
 
diff --git a/engines/ags/shared/ac/inventoryiteminfo.cpp b/engines/ags/shared/ac/inventoryiteminfo.cpp
index 89f9d17842..0a34dbaa8f 100644
--- a/engines/ags/shared/ac/inventoryiteminfo.cpp
+++ b/engines/ags/shared/ac/inventoryiteminfo.cpp
@@ -24,7 +24,7 @@
 #include "util/stream.h"
 #include "util/string_utils.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 void InventoryItemInfo::ReadFromFile(Stream *in) {
 	in->Read(name, 25);
diff --git a/engines/ags/shared/ac/inventoryiteminfo.h b/engines/ags/shared/ac/inventoryiteminfo.h
index 29adfffaff..e3f1ab5779 100644
--- a/engines/ags/shared/ac/inventoryiteminfo.h
+++ b/engines/ags/shared/ac/inventoryiteminfo.h
@@ -26,7 +26,7 @@
 namespace AGS3 {
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 } // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/ac/mousecursor.cpp b/engines/ags/shared/ac/mousecursor.cpp
index 2f5e4d80d2..86548b2972 100644
--- a/engines/ags/shared/ac/mousecursor.cpp
+++ b/engines/ags/shared/ac/mousecursor.cpp
@@ -23,7 +23,7 @@
 #include "ac/mousecursor.h"
 #include "util/stream.h"
 
-using AGS::Common::Stream;
+using AGS::Shared::Stream;
 
 MouseCursor::MouseCursor() {
 	pic = 2054;
diff --git a/engines/ags/shared/ac/mousecursor.h b/engines/ags/shared/ac/mousecursor.h
index 2ebaebe9ca..7ae0ef406d 100644
--- a/engines/ags/shared/ac/mousecursor.h
+++ b/engines/ags/shared/ac/mousecursor.h
@@ -29,7 +29,7 @@ namespace AGS {
 namespace Common {
 class Stream;
 } // namespace Shared
-} // namespace AGS
+namespace SharedGS
 
 using namespace AGS; // FIXME later
 
diff --git a/engines/ags/shared/ac/spritecache.cpp b/engines/ags/shared/ac/spritecache.cpp
index 79d79f713b..178d9ebf65 100644
--- a/engines/ags/shared/ac/spritecache.cpp
+++ b/engines/ags/shared/ac/spritecache.cpp
@@ -42,7 +42,7 @@
 #include "util/file.h"
 #include "util/stream.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 // [IKM] We have to forward-declare these because their implementations are in the Engine
 extern void initialize_sprite(int);
@@ -732,7 +732,7 @@ HError SpriteCache::InitFile(const char *filename, const char *sprindex_filename
 	return RebuildSpriteIndex(_stream.get(), topmost, vers);
 }
 
-HError SpriteCache::RebuildSpriteIndex(AGS::Common::Stream *in, sprkey_t topmost, SpriteFileVersion vers) {
+HError SpriteCache::RebuildSpriteIndex(AGS::Shared::Stream *in, sprkey_t topmost, SpriteFileVersion vers) {
 	for (sprkey_t i = 0; i <= topmost; ++i) {
 		_spriteData[i].Offset = in->GetPosition();
 		_spriteData[i].Flags = 0;
diff --git a/engines/ags/shared/ac/spritecache.h b/engines/ags/shared/ac/spritecache.h
index 2d8a5a5eaa..d7a2eb3593 100644
--- a/engines/ags/shared/ac/spritecache.h
+++ b/engines/ags/shared/ac/spritecache.h
@@ -53,14 +53,14 @@
 namespace AGS3 {
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 class Bitmap;
 } // namespace Shared
 } // namespace AGS
 
 using namespace AGS; // FIXME later
-typedef AGS::Common::HError HAGSError;
+typedef AGS::Shared::HError HAGSError;
 
 struct SpriteInfo;
 
@@ -238,7 +238,7 @@ private:
 	// Loads sprite index file
 	bool        LoadSpriteIndexFile(const char *filename, int expectedFileID, soff_t spr_initial_offs, sprkey_t topmost);
 	// Rebuilds sprite index from the main sprite file
-	HAGSError   RebuildSpriteIndex(AGS::Common::Stream *in, sprkey_t topmost, SpriteFileVersion vers);
+	HAGSError   RebuildSpriteIndex(AGS::Shared::Stream *in, sprkey_t topmost, SpriteFileVersion vers);
 	// Writes compressed sprite to the stream
 	void        CompressSprite(Common::Bitmap *sprite, Common::Stream *out);
 	// Uncompresses sprite from stream into the given bitmap
diff --git a/engines/ags/shared/ac/view.cpp b/engines/ags/shared/ac/view.cpp
index c464989f55..e6299ebf54 100644
--- a/engines/ags/shared/ac/view.cpp
+++ b/engines/ags/shared/ac/view.cpp
@@ -24,8 +24,8 @@
 #include "ac/view.h"
 #include "util/alignedstream.h"
 
-using AGS::Common::AlignedStream;
-using AGS::Common::Stream;
+using AGS::Shared::AlignedStream;
+using AGS::Shared::Stream;
 
 ViewFrame::ViewFrame()
 	: pic(0)
diff --git a/engines/ags/shared/ac/view.h b/engines/ags/shared/ac/view.h
index 3fa144444d..f8dc1fc0e5 100644
--- a/engines/ags/shared/ac/view.h
+++ b/engines/ags/shared/ac/view.h
@@ -28,7 +28,7 @@
 namespace AGS3 {
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 } // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/ac/wordsdictionary.cpp b/engines/ags/shared/ac/wordsdictionary.cpp
index 3621794819..2cddfd73b5 100644
--- a/engines/ags/shared/ac/wordsdictionary.cpp
+++ b/engines/ags/shared/ac/wordsdictionary.cpp
@@ -26,7 +26,7 @@
 #include "util/stream.h"
 #include "util/string_compat.h"
 
-using AGS::Common::Stream;
+using AGS::Shared::Stream;
 
 WordsDictionary::WordsDictionary()
 	: num_words(0)
diff --git a/engines/ags/shared/ac/wordsdictionary.h b/engines/ags/shared/ac/wordsdictionary.h
index ea2fe99908..fba3277de8 100644
--- a/engines/ags/shared/ac/wordsdictionary.h
+++ b/engines/ags/shared/ac/wordsdictionary.h
@@ -28,7 +28,7 @@
 namespace AGS3 {
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 } // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/api/stream_api.h b/engines/ags/shared/api/stream_api.h
index 738765a513..9bd209b434 100644
--- a/engines/ags/shared/api/stream_api.h
+++ b/engines/ags/shared/api/stream_api.h
@@ -40,7 +40,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 enum StreamSeek {
 	kSeekBegin,
@@ -92,7 +92,7 @@ public:
 	virtual bool        Seek(soff_t offset, StreamSeek origin = kSeekCurrent) = 0;
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/core/asset.cpp b/engines/ags/shared/core/asset.cpp
index 24f988be44..ce99ec5615 100644
--- a/engines/ags/shared/core/asset.cpp
+++ b/engines/ags/shared/core/asset.cpp
@@ -23,7 +23,7 @@
 #include "core/asset.h"
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 AssetInfo::AssetInfo()
 	: LibUid(0)
@@ -37,5 +37,5 @@ void AssetLibInfo::Unload() {
 	AssetInfos.clear();
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/core/asset.h b/engines/ags/shared/core/asset.h
index 0a8f7c4c2c..a531f8c94e 100644
--- a/engines/ags/shared/core/asset.h
+++ b/engines/ags/shared/core/asset.h
@@ -34,7 +34,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 // Information on single asset
 struct AssetInfo {
@@ -61,7 +61,7 @@ struct AssetLibInfo {
 	void Unload();
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/core/assetmanager.cpp b/engines/ags/shared/core/assetmanager.cpp
index de80f63d5e..1fe72e4797 100644
--- a/engines/ags/shared/core/assetmanager.cpp
+++ b/engines/ags/shared/core/assetmanager.cpp
@@ -28,7 +28,7 @@
 
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 AssetLocation::AssetLocation()
 	: Offset(0)
@@ -367,5 +367,5 @@ String GetAssetErrorText(AssetError err) {
 	return "Unknown error.";
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/core/assetmanager.h b/engines/ags/shared/core/assetmanager.h
index d2937b661b..bf942bdfa0 100644
--- a/engines/ags/shared/core/assetmanager.h
+++ b/engines/ags/shared/core/assetmanager.h
@@ -48,7 +48,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 class Stream;
 struct MultiFileLib;
@@ -154,7 +154,7 @@ private:
 
 String GetAssetErrorText(AssetError err);
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/debugging/debugmanager.cpp b/engines/ags/shared/debugging/debugmanager.cpp
index afddfdee2f..180e06c97f 100644
--- a/engines/ags/shared/debugging/debugmanager.cpp
+++ b/engines/ags/shared/debugging/debugmanager.cpp
@@ -25,7 +25,7 @@
 #include "util/string_types.h"
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 DebugOutput::DebugOutput(const String &id, IOutputHandler *handler, MessageType def_verbosity, bool enabled)
 	: _id(id)
@@ -224,5 +224,5 @@ void Printf(DebugGroupID group, MessageType mt, const char *fmt, ...) {
 
 } // namespace Debug
 
-}   // namespace Common
+}   // namespace Shared
 }   // namespace AGS
diff --git a/engines/ags/shared/debugging/debugmanager.h b/engines/ags/shared/debugging/debugmanager.h
index 21e733206b..8390311257 100644
--- a/engines/ags/shared/debugging/debugmanager.h
+++ b/engines/ags/shared/debugging/debugmanager.h
@@ -56,7 +56,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 // DebugGroup is a message sender definition, identified by DebugGroupID
 // and providing OutputName that could be used when printing its messages.
@@ -165,7 +165,7 @@ private:
 // TODO: move this to the dynamically allocated engine object whenever it is implemented
 extern DebugManager DbgMgr;
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/debugging/out.h b/engines/ags/shared/debugging/out.h
index 2d7efa27fd..c25eb655a0 100644
--- a/engines/ags/shared/debugging/out.h
+++ b/engines/ags/shared/debugging/out.h
@@ -81,7 +81,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 // Message types provide distinction for debug messages by their intent.
 enum MessageType {
@@ -161,7 +161,7 @@ void Printf(DebugGroupID group_id, MessageType mt, const char *fmt, ...);
 
 } // namespace Debug
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/debugging/outputhandler.h b/engines/ags/shared/debugging/outputhandler.h
index 86ddc57fe6..9d071b1755 100644
--- a/engines/ags/shared/debugging/outputhandler.h
+++ b/engines/ags/shared/debugging/outputhandler.h
@@ -39,7 +39,7 @@ namespace Common {
 
 struct DebugMessage {
 	String       Text;
-	uint32_t     GroupID;
+namespace SharedoupID;
 	String       GroupName;
 	MessageType  MT;
 
diff --git a/engines/ags/shared/font/fonts.cpp b/engines/ags/shared/font/fonts.cpp
index 0763bad8c6..77493dd202 100644
--- a/engines/ags/shared/font/fonts.cpp
+++ b/engines/ags/shared/font/fonts.cpp
@@ -34,10 +34,10 @@
 
 #define STD_BUFFER_SIZE 3000
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 struct Font {
 	IAGSFontRenderer   *Renderer;
@@ -189,7 +189,7 @@ bool use_default_linespacing(size_t fontNumber) {
 extern int wgettextwidth_compensate(const char *tex, int font);
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 SplitLines Lines;
 }
 }
diff --git a/engines/ags/shared/font/fonts.h b/engines/ags/shared/font/fonts.h
index 37586eba68..29a8b35e94 100644
--- a/engines/ags/shared/font/fonts.h
+++ b/engines/ags/shared/font/fonts.h
@@ -33,7 +33,7 @@ namespace AGS3 {
 namespace AGS {
 namespace Common {
 class Bitmap;
-} // namespace Shared
+namespace Sharedhared
 } // namespace AGS
 
 using namespace AGS;
@@ -133,7 +133,7 @@ size_t split_lines(const char *texx, SplitLines &lines, int width, int fontNumbe
 namespace AGS {
 namespace Common {
 extern SplitLines Lines;
-} // namespace Shared
+namespace Sharedhared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/font/ttffontrenderer.cpp b/engines/ags/shared/font/ttffontrenderer.cpp
index 54d32ffb09..73ec388d23 100644
--- a/engines/ags/shared/font/ttffontrenderer.cpp
+++ b/engines/ags/shared/font/ttffontrenderer.cpp
@@ -34,7 +34,7 @@
 #include "font/fonts.h"
 #endif
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 // project-specific implementation
 extern bool ShouldAntiAliasText();
diff --git a/engines/ags/shared/font/wfnfont.cpp b/engines/ags/shared/font/wfnfont.cpp
index 6825805b4e..b891aff8cf 100644
--- a/engines/ags/shared/font/wfnfont.cpp
+++ b/engines/ags/shared/font/wfnfont.cpp
@@ -26,7 +26,7 @@
 #include "util/memory.h"
 #include "util/stream.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 static const char   *WFN_FILE_SIGNATURE  = "WGT Font File  ";
 static const size_t  WFN_FILE_SIG_LENGTH = 15;
diff --git a/engines/ags/shared/font/wfnfont.h b/engines/ags/shared/font/wfnfont.h
index ebfb0a4ba0..6abe424268 100644
--- a/engines/ags/shared/font/wfnfont.h
+++ b/engines/ags/shared/font/wfnfont.h
@@ -52,7 +52,7 @@
 namespace AGS3 {
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 } // namespace Shared
 } // namespace AGS
@@ -98,7 +98,7 @@ public:
 	void Clear();
 	// Reads WFNFont object, using data_size bytes from stream; if data_size = 0,
 	// the available stream's length is used instead. Returns error code.
-	WFNError ReadFromFile(AGS::Common::Stream *in, const soff_t data_size = 0);
+	WFNError ReadFromFile(AGS::Shared::Stream *in, const soff_t data_size = 0);
 
 protected:
 	std::vector<const WFNChar *> _refs;     // reference array, contains pointers to elements of _items
diff --git a/engines/ags/shared/font/wfnfontrenderer.cpp b/engines/ags/shared/font/wfnfontrenderer.cpp
index 3db79fe0ee..559e88a2e4 100644
--- a/engines/ags/shared/font/wfnfontrenderer.cpp
+++ b/engines/ags/shared/font/wfnfontrenderer.cpp
@@ -28,7 +28,7 @@
 #include "gfx/bitmap.h"
 #include "util/stream.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 static unsigned char GetCharCode(unsigned char wanted_code, const WFNFont *font) {
 	return wanted_code < font->GetCharCount() ? wanted_code : '?';
diff --git a/engines/ags/shared/game/customproperties.cpp b/engines/ags/shared/game/customproperties.cpp
index 61232af84c..96440c7739 100644
--- a/engines/ags/shared/game/customproperties.cpp
+++ b/engines/ags/shared/game/customproperties.cpp
@@ -25,7 +25,7 @@
 #include "util/string_utils.h"
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 PropertyDesc::PropertyDesc() {
 	Type = kPropertyBoolean;
@@ -117,5 +117,5 @@ void WriteValues(const StringIMap &map, Stream *out) {
 
 } // namespace Properties
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/game/customproperties.h b/engines/ags/shared/game/customproperties.h
index cd36b985a0..7908829e2d 100644
--- a/engines/ags/shared/game/customproperties.h
+++ b/engines/ags/shared/game/customproperties.h
@@ -52,7 +52,7 @@ namespace AGS3 {
 #define LEGACY_MAX_CUSTOM_PROP_VALUE_LENGTH         500
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 enum PropertyVersion {
 	kPropertyVersion_Initial = 1,
@@ -102,7 +102,7 @@ void          WriteValues(const StringIMap &map, Stream *out);
 
 } // namespace Properties
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/game/interactions.cpp b/engines/ags/shared/game/interactions.cpp
index 7b8c2508c6..6c53f14a00 100644
--- a/engines/ags/shared/game/interactions.cpp
+++ b/engines/ags/shared/game/interactions.cpp
@@ -26,13 +26,13 @@
 #include "util/alignedstream.h"
 #include "util/math.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 InteractionVariable globalvars[MAX_GLOBAL_VARIABLES] = {InteractionVariable("Global 1", 0, 0)};
 int numGlobalVars = 1;
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 InteractionValue::InteractionValue() {
 	Type = kInterValLiteralInt;
@@ -372,5 +372,5 @@ InteractionScripts *InteractionScripts::CreateFromStream(Stream *in) {
 	return scripts;
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/game/interactions.h b/engines/ags/shared/game/interactions.h
index 02b440f393..c325ee6ebd 100644
--- a/engines/ags/shared/game/interactions.h
+++ b/engines/ags/shared/game/interactions.h
@@ -61,7 +61,7 @@ namespace AGS3 {
 #define MAX_COMMANDS_PER_LIST       40
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 enum InterValType {
 	kInterValLiteralInt = 1,
@@ -204,11 +204,11 @@ struct InteractionScripts {
 
 typedef std::shared_ptr<InteractionScripts> PInteractionScripts;
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 
 // Legacy global variables
-extern AGS::Common::InteractionVariable globalvars[MAX_GLOBAL_VARIABLES];
+extern AGS::Shared::InteractionVariable globalvars[MAX_GLOBAL_VARIABLES];
 extern int numGlobalVars;
 
 } // namespace AGS3
diff --git a/engines/ags/shared/game/main_game_file.cpp b/engines/ags/shared/game/main_game_file.cpp
index 48dd4a26c9..f02e9c10f1 100644
--- a/engines/ags/shared/game/main_game_file.cpp
+++ b/engines/ags/shared/game/main_game_file.cpp
@@ -40,7 +40,7 @@
 #include "font/fonts.h"
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 const String MainGameSource::DefaultFilename_v3 = "game28.dta";
 const String MainGameSource::DefaultFilename_v2 = "ac2game.dta";
@@ -733,5 +733,5 @@ HGameFileError UpdateGameData(LoadedGameEntities &ents, GameDataVersion data_ver
 	return HGameFileError::None();
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/game/main_game_file.h b/engines/ags/shared/game/main_game_file.h
index 86fd9241a9..8bb36b7ff0 100644
--- a/engines/ags/shared/game/main_game_file.h
+++ b/engines/ags/shared/game/main_game_file.h
@@ -49,7 +49,7 @@ struct DialogTopic;
 struct ViewStruct;
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 // Error codes for main game file reading
 enum MainGameFileErrorType {
@@ -148,7 +148,7 @@ HGameFileError     UpdateGameData(LoadedGameEntities &ents, GameDataVersion data
 // Ensures that the game saves directory path is valid
 void               FixupSaveDirectory(GameSetupStruct &game);
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/game/plugininfo.h b/engines/ags/shared/game/plugininfo.h
index a368913e91..eac9f6e072 100644
--- a/engines/ags/shared/game/plugininfo.h
+++ b/engines/ags/shared/game/plugininfo.h
@@ -38,7 +38,7 @@ namespace AGS3 {
 #define PLUGIN_SAVEBUFFERSIZE 10247680
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 struct PluginInfo {
 	// (File)name of plugin
@@ -51,7 +51,7 @@ struct PluginInfo {
 	}
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/game/room_file.cpp b/engines/ags/shared/game/room_file.cpp
index c2c3996c8b..ce69890ed4 100644
--- a/engines/ags/shared/game/room_file.cpp
+++ b/engines/ags/shared/game/room_file.cpp
@@ -45,7 +45,7 @@
 #define LEGACY_TINT_IS_ENABLED 0x80000000
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 RoomDataSource::RoomDataSource()
 	: DataVersion(kRoomVersion_Undefined) {
@@ -881,5 +881,5 @@ HRoomFileError WriteRoomData(const RoomStruct *room, Stream *out, RoomFileVersio
 	return HRoomFileError::None();
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/game/room_file.h b/engines/ags/shared/game/room_file.h
index be91dbc519..6276cb352a 100644
--- a/engines/ags/shared/game/room_file.h
+++ b/engines/ags/shared/game/room_file.h
@@ -42,7 +42,7 @@ namespace AGS3 {
 
 struct SpriteInfo;
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 class RoomStruct;
 
@@ -94,7 +94,7 @@ HRoomFileError ExtractScriptText(String &script, Stream *in, RoomFileVersion dat
 
 HRoomFileError WriteRoomData(const RoomStruct *room, Stream *out, RoomFileVersion data_ver);
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/game/room_file_deprecated.cpp b/engines/ags/shared/game/room_file_deprecated.cpp
index 7fdae6e1f5..4b0a6457a1 100644
--- a/engines/ags/shared/game/room_file_deprecated.cpp
+++ b/engines/ags/shared/game/room_file_deprecated.cpp
@@ -33,7 +33,7 @@
 #include "ac/common.h"
 #include "util/stream.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 #define AE_WAITFLAG   0x80000000
 #define MAXANIMSTAGES 10
@@ -70,7 +70,7 @@ struct PolyPoints {
 		numpoints = 0;
 	}
 
-	void Read(AGS::Common::Stream *in);
+	void Read(AGS::Shared::Stream *in);
 };
 
 
diff --git a/engines/ags/shared/game/roomstruct.cpp b/engines/ags/shared/game/roomstruct.cpp
index 91bb1b2e5b..4a9ddc26ef 100644
--- a/engines/ags/shared/game/roomstruct.cpp
+++ b/engines/ags/shared/game/roomstruct.cpp
@@ -26,7 +26,7 @@
 #include "gfx/bitmap.h"
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 RoomOptions::RoomOptions()
 	: StartupMusic(0)
@@ -298,5 +298,5 @@ void FixRoomMasks(RoomStruct *room) {
 	room->WalkAreaMask = FixBitmap(room->WalkAreaMask, low_width, low_height);
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/game/roomstruct.h b/engines/ags/shared/game/roomstruct.h
index 1895d689c8..b9d48742e1 100644
--- a/engines/ags/shared/game/roomstruct.h
+++ b/engines/ags/shared/game/roomstruct.h
@@ -60,7 +60,7 @@ struct ccScript;
 struct SpriteInfo;
 typedef std::shared_ptr<ccScript> PScript;
 
-// TODO: move the following enums under AGS::Common namespace
+// TODO: move the following enums under AGS::Shared namespace
 // later, when more engine source is put in AGS namespace and
 // refactored.
 
@@ -110,7 +110,7 @@ enum RoomVolumeMod {
 
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 class Bitmap;
 class Stream;
@@ -384,7 +384,7 @@ void FixRoomMasks(RoomStruct *room);
 // Adjusts bitmap size if necessary and returns either new or old bitmap.
 PBitmap FixBitmap(PBitmap bmp, int dst_width, int dst_height);
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/gfx/allegrobitmap.cpp b/engines/ags/shared/gfx/allegrobitmap.cpp
index 75284d19b6..d84072b90c 100644
--- a/engines/ags/shared/gfx/allegrobitmap.cpp
+++ b/engines/ags/shared/gfx/allegrobitmap.cpp
@@ -27,7 +27,7 @@
 extern void __my_setcolor(int *ctset, int newcol, int wantColDep);
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 Bitmap::Bitmap()
 	: _alBitmap(nullptr)
@@ -411,5 +411,5 @@ Bitmap *CreateRawBitmapWrapper(BITMAP *al_bmp) {
 } // namespace BitmapHelper
 
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/gfx/allegrobitmap.h b/engines/ags/shared/gfx/allegrobitmap.h
index 77d0ea83fc..3a5092cc97 100644
--- a/engines/ags/shared/gfx/allegrobitmap.h
+++ b/engines/ags/shared/gfx/allegrobitmap.h
@@ -38,7 +38,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 class Bitmap {
 public:
@@ -232,7 +232,7 @@ Bitmap *CreateRawBitmapOwner(BITMAP *al_bmp);
 Bitmap *CreateRawBitmapWrapper(BITMAP *al_bmp);
 } // namespace BitmapHelper
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/gfx/bitmap.cpp b/engines/ags/shared/gfx/bitmap.cpp
index 85b22374ca..98447e2c47 100644
--- a/engines/ags/shared/gfx/bitmap.cpp
+++ b/engines/ags/shared/gfx/bitmap.cpp
@@ -24,7 +24,7 @@
 #include "util/memory.h"
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 // TODO: revise this construction later
 namespace BitmapHelper {
@@ -169,5 +169,5 @@ void ReadPixelsFromMemory(Bitmap *dst, const uint8_t *src_buffer, const size_t s
 
 } // namespace BitmapHelper
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/gfx/bitmap.h b/engines/ags/shared/gfx/bitmap.h
index b370c9a004..91a4d15b07 100644
--- a/engines/ags/shared/gfx/bitmap.h
+++ b/engines/ags/shared/gfx/bitmap.h
@@ -33,7 +33,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 // Mask option for blitting one bitmap on another
 enum BitmapMaskOption {
@@ -49,7 +49,7 @@ enum BitmapFlip {
 	kBitmap_HVFlip
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 
 
@@ -57,7 +57,7 @@ enum BitmapFlip {
 #include "gfx/allegrobitmap.h"
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 class Bitmap;
 
@@ -86,7 +86,7 @@ void    CopyTransparency(Bitmap *dst, const Bitmap *mask, bool dst_has_alpha, bo
 void    ReadPixelsFromMemory(Bitmap *dst, const uint8_t *src_buffer, const size_t src_pitch, const size_t src_px_offset = 0);
 } // namespace BitmapHelper
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/gfx/gfx_def.h b/engines/ags/shared/gfx/gfx_def.h
index 4e84b51bdd..51a583e47d 100644
--- a/engines/ags/shared/gfx/gfx_def.h
+++ b/engines/ags/shared/gfx/gfx_def.h
@@ -31,7 +31,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 enum BlendMode {
 	// free blending (ARGB -> ARGB) modes
@@ -103,7 +103,7 @@ inline int LegacyTrans100ToAlpha255(int legacy_transparency) {
 }
 } // namespace GfxDef
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/gui/guibutton.cpp b/engines/ags/shared/gui/guibutton.cpp
index 9859e4e312..502aeb0367 100644
--- a/engines/ags/shared/gui/guibutton.cpp
+++ b/engines/ags/shared/gui/guibutton.cpp
@@ -26,11 +26,11 @@
 #include "util/stream.h"
 #include "util/string_utils.h"
 
-std::vector<AGS::Common::GUIButton> guibuts;
+std::vector<AGS::Shared::GUIButton> guibuts;
 int numguibuts = 0;
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 FrameAlignment ConvertLegacyButtonAlignment(LegacyButtonAlignment align) {
 	switch (align) {
@@ -346,5 +346,5 @@ void GUIButton::DrawTextButton(Bitmap *ds, bool draw_disabled) {
 	DrawText(ds, draw_disabled);
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/gui/guibutton.h b/engines/ags/shared/gui/guibutton.h
index f89edce6fd..f5ac628a03 100644
--- a/engines/ags/shared/gui/guibutton.h
+++ b/engines/ags/shared/gui/guibutton.h
@@ -32,7 +32,7 @@ namespace AGS3 {
 #define GUIBUTTON_LEGACY_TEXTLENGTH 50
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 enum MouseButton {
 	kMouseNone = -1,
@@ -127,10 +127,10 @@ private:
 	String _textToDraw;
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 
-extern std::vector<AGS::Common::GUIButton> guibuts;
+extern std::vector<AGS::Shared::GUIButton> guibuts;
 extern int numguibuts;
 
 int UpdateAnimatingButton(int bu);
diff --git a/engines/ags/shared/gui/guidefines.h b/engines/ags/shared/gui/guidefines.h
index 8f7f04f74f..1086132e9e 100644
--- a/engines/ags/shared/gui/guidefines.h
+++ b/engines/ags/shared/gui/guidefines.h
@@ -85,7 +85,7 @@ enum GuiVersion {
 };
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 // GUIMain's style and behavior flags
 enum GUIMainFlags {
@@ -176,7 +176,7 @@ enum GuiSvgVersion {
 	kGuiSvgVersion_350 = 1
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 
 extern int guis_need_update;
diff --git a/engines/ags/shared/gui/guiinv.cpp b/engines/ags/shared/gui/guiinv.cpp
index 368d0beca3..6feaf6c188 100644
--- a/engines/ags/shared/gui/guiinv.cpp
+++ b/engines/ags/shared/gui/guiinv.cpp
@@ -26,11 +26,11 @@
 #include "gui/guimain.h"
 #include "util/stream.h"
 
-std::vector<AGS::Common::GUIInvWindow> guiinv;
+std::vector<AGS::Shared::GUIInvWindow> guiinv;
 int numguiinv = 0;
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 GUIInvWindow::GUIInvWindow() {
 	IsMouseOver = false;
@@ -127,5 +127,5 @@ void GUIInvWindow::CalculateNumCells() {
 	}
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/gui/guiinv.h b/engines/ags/shared/gui/guiinv.h
index f0e6041fac..8c358dc0b8 100644
--- a/engines/ags/shared/gui/guiinv.h
+++ b/engines/ags/shared/gui/guiinv.h
@@ -28,7 +28,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 class GUIInvWindow : public GUIObject {
 public:
@@ -67,10 +67,10 @@ private:
 	void CalculateNumCells();
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 
-extern std::vector<AGS::Common::GUIInvWindow> guiinv;
+extern std::vector<AGS::Shared::GUIInvWindow> guiinv;
 extern int numguiinv;
 
 } // namespace AGS3
diff --git a/engines/ags/shared/gui/guilabel.cpp b/engines/ags/shared/gui/guilabel.cpp
index 480c6acb08..7891b5d66a 100644
--- a/engines/ags/shared/gui/guilabel.cpp
+++ b/engines/ags/shared/gui/guilabel.cpp
@@ -27,13 +27,13 @@
 #include "util/stream.h"
 #include "util/string_utils.h"
 
-std::vector<AGS::Common::GUILabel> guilabels;
+std::vector<AGS::Shared::GUILabel> guilabels;
 int numguilabels = 0;
 
 #define GUILABEL_TEXTLENGTH_PRE272 200
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 GUILabel::GUILabel() {
 	Font = 0;
@@ -121,5 +121,5 @@ void GUILabel::WriteToSavegame(Stream *out) const {
 	out->WriteInt32(TextAlignment);
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/gui/guilabel.h b/engines/ags/shared/gui/guilabel.h
index 88c2380bcf..ff11472571 100644
--- a/engines/ags/shared/gui/guilabel.h
+++ b/engines/ags/shared/gui/guilabel.h
@@ -32,7 +32,7 @@ namespace AGS3 {
 class SplitLines;
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 class GUILabel : public GUIObject {
 public:
@@ -65,10 +65,10 @@ private:
 	String _textToDraw;
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 
-extern std::vector<AGS::Common::GUILabel> guilabels;
+extern std::vector<AGS::Shared::GUILabel> guilabels;
 extern int numguilabels;
 
 } // namespace AGS3
diff --git a/engines/ags/shared/gui/guilistbox.cpp b/engines/ags/shared/gui/guilistbox.cpp
index 5cb14fe264..f629615ef2 100644
--- a/engines/ags/shared/gui/guilistbox.cpp
+++ b/engines/ags/shared/gui/guilistbox.cpp
@@ -26,11 +26,11 @@
 #include "util/stream.h"
 #include "util/string_utils.h"
 
-std::vector<AGS::Common::GUIListBox> guilist;
+std::vector<AGS::Shared::GUIListBox> guilist;
 int numguilist = 0;
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 GUIListBox::GUIListBox() {
 	ItemCount = 0;
@@ -390,5 +390,5 @@ void GUIListBox::WriteToSavegame(Stream *out) const {
 	out->WriteInt32(SelectedItem);
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/gui/guilistbox.h b/engines/ags/shared/gui/guilistbox.h
index 30c55e5e6a..f3910c1074 100644
--- a/engines/ags/shared/gui/guilistbox.h
+++ b/engines/ags/shared/gui/guilistbox.h
@@ -29,7 +29,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 class GUIListBox : public GUIObject {
 public:
@@ -95,10 +95,10 @@ private:
 	String _textToDraw;
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 
-extern std::vector<AGS::Common::GUIListBox> guilist;
+extern std::vector<AGS::Shared::GUIListBox> guilist;
 extern int numguilist;
 
 } // namespace AGS3
diff --git a/engines/ags/shared/gui/guimain.cpp b/engines/ags/shared/gui/guimain.cpp
index d71a9c8e38..dfade96d2f 100644
--- a/engines/ags/shared/gui/guimain.cpp
+++ b/engines/ags/shared/gui/guimain.cpp
@@ -35,7 +35,7 @@
 #include "util/stream.h"
 #include "util/string_utils.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 #define MOVER_MOUSEDOWNLOCKED -4000
 
@@ -44,7 +44,7 @@ int all_buttons_disabled = 0, gui_inv_pic = -1;
 int gui_disabled_style = 0;
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 /* static */ String GUIMain::FixupGUIName(const String &name) {
 	if (name.GetLength() > 0 && name[0u] != 'g')
@@ -816,5 +816,5 @@ void ApplyLegacyVisibility(GUIMain &gui, LegacyGUIVisState vis) {
 
 } // namespace GUI
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/gui/guimain.h b/engines/ags/shared/gui/guimain.h
index 27d7deee5e..004f3b226a 100644
--- a/engines/ags/shared/gui/guimain.h
+++ b/engines/ags/shared/gui/guimain.h
@@ -35,7 +35,7 @@ namespace AGS3 {
 
 // Forward declaration
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 } // namespace Shared
 } // namespace AGS
@@ -53,7 +53,7 @@ struct GameSetupStruct;
 #define GUIMAIN_LEGACY_TW_FLAGS_SIZE       4
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 // Legacy GUIMain visibility state, which combined Visible property and override factor
 enum LegacyGUIVisState {
@@ -214,7 +214,7 @@ void WriteGUI(const std::vector<GUIMain> &guis, Stream *out);
 void ApplyLegacyVisibility(GUIMain &gui, LegacyGUIVisState vis);
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 
 extern std::vector<Common::GUIMain> guis;
diff --git a/engines/ags/shared/gui/guiobject.cpp b/engines/ags/shared/gui/guiobject.cpp
index 8f278025f1..82d5bde791 100644
--- a/engines/ags/shared/gui/guiobject.cpp
+++ b/engines/ags/shared/gui/guiobject.cpp
@@ -26,7 +26,7 @@
 #include "util/stream.h"
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 GUIObject::GUIObject() {
 	Id          = 0;
@@ -194,5 +194,5 @@ HorAlignment ConvertLegacyGUIAlignment(LegacyGUIAlignment align) {
 	return kHAlignNone;
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/gui/guiobject.h b/engines/ags/shared/gui/guiobject.h
index 1dfa517867..9dc698050d 100644
--- a/engines/ags/shared/gui/guiobject.h
+++ b/engines/ags/shared/gui/guiobject.h
@@ -36,7 +36,7 @@ namespace AGS3 {
 #define GUIDIS_GUIOFF  0x80
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 enum LegacyGUIAlignment {
 	kLegacyGUIAlign_Left = 0,
@@ -127,13 +127,13 @@ protected:
 // Converts legacy alignment type used in GUI Label/ListBox data (only left/right/center)
 HorAlignment ConvertLegacyGUIAlignment(LegacyGUIAlignment align);
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 
 // Tells if all controls are disabled
 extern int all_buttons_disabled;
 // Tells if the given control is considered enabled, taking global flag into account
-inline bool IsGUIEnabled(AGS::Common::GUIObject *g) {
+inline bool IsGUIEnabled(AGS::Shared::GUIObject *g) {
 	return !all_buttons_disabled && g->IsEnabled();
 }
 
diff --git a/engines/ags/shared/gui/guislider.cpp b/engines/ags/shared/gui/guislider.cpp
index fee93194a2..d58e52a286 100644
--- a/engines/ags/shared/gui/guislider.cpp
+++ b/engines/ags/shared/gui/guislider.cpp
@@ -25,11 +25,11 @@
 #include "gui/guislider.h"
 #include "util/stream.h"
 
-std::vector<AGS::Common::GUISlider> guislider;
+std::vector<AGS::Shared::GUISlider> guislider;
 int numguislider = 0;
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 GUISlider::GUISlider() {
 	MinValue = 0;
@@ -240,5 +240,5 @@ void GUISlider::WriteToSavegame(Stream *out) const {
 	out->WriteInt32(Value);
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/gui/guislider.h b/engines/ags/shared/gui/guislider.h
index 2e5696bed2..338dc7124f 100644
--- a/engines/ags/shared/gui/guislider.h
+++ b/engines/ags/shared/gui/guislider.h
@@ -28,7 +28,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 class GUISlider : public GUIObject {
 public:
@@ -68,10 +68,10 @@ private:
 	Rect    _cachedHandle;
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 
-extern std::vector<AGS::Common::GUISlider> guislider;
+extern std::vector<AGS::Shared::GUISlider> guislider;
 extern int numguislider;
 
 } // namespace AGS3
diff --git a/engines/ags/shared/gui/guitextbox.cpp b/engines/ags/shared/gui/guitextbox.cpp
index 307ce31bd9..9722612a25 100644
--- a/engines/ags/shared/gui/guitextbox.cpp
+++ b/engines/ags/shared/gui/guitextbox.cpp
@@ -28,11 +28,11 @@
 
 #define GUITEXTBOX_LEGACY_TEXTLEN 200
 
-std::vector<AGS::Common::GUITextBox> guitext;
+std::vector<AGS::Shared::GUITextBox> guitext;
 int numguitext = 0;
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 GUITextBox::GUITextBox() {
 	Font = 0;
@@ -135,5 +135,5 @@ void GUITextBox::WriteToSavegame(Stream *out) const {
 	out->WriteInt32(TextBoxFlags);
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/gui/guitextbox.h b/engines/ags/shared/gui/guitextbox.h
index 79f8ac9be5..9a69cd4c62 100644
--- a/engines/ags/shared/gui/guitextbox.h
+++ b/engines/ags/shared/gui/guitextbox.h
@@ -29,7 +29,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 class GUITextBox : public GUIObject {
 public:
@@ -62,10 +62,10 @@ private:
 	void DrawTextBoxContents(Bitmap *ds, color_t text_color);
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 
-extern std::vector<AGS::Common::GUITextBox> guitext;
+extern std::vector<AGS::Shared::GUITextBox> guitext;
 extern int numguitext;
 
 } // namespace AGS3
diff --git a/engines/ags/shared/script/cc_error.cpp b/engines/ags/shared/script/cc_error.cpp
index 71f328df98..a97da16d8b 100644
--- a/engines/ags/shared/script/cc_error.cpp
+++ b/engines/ags/shared/script/cc_error.cpp
@@ -25,7 +25,7 @@
 #include "script/script_common.h"  // current_line
 #include "util/string.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 // Returns full script error message and callstack (if possible)
 extern std::pair<String, String> cc_error_at_line(const char *error_msg);
diff --git a/engines/ags/shared/script/cc_error.h b/engines/ags/shared/script/cc_error.h
index 7dc8c68df9..d211af6fbf 100644
--- a/engines/ags/shared/script/cc_error.h
+++ b/engines/ags/shared/script/cc_error.h
@@ -38,8 +38,8 @@ extern void cc_error(const char *, ...);
 // error reporting
 extern int ccError;             // set to non-zero if error occurs
 extern int ccErrorLine;         // line number of the error
-extern AGS::Common::String ccErrorString; // description of the error
-extern AGS::Common::String ccErrorCallStack; // callstack where error happened
+extern AGS::Shared::String ccErrorString; // description of the error
+extern AGS::Shared::String ccErrorCallStack; // callstack where error happened
 extern bool ccErrorIsUserError;
 extern const char *ccCurScriptName; // name of currently compiling script
 
diff --git a/engines/ags/shared/script/cc_script.cpp b/engines/ags/shared/script/cc_script.cpp
index bd5c5b81f8..2f6a567304 100644
--- a/engines/ags/shared/script/cc_script.cpp
+++ b/engines/ags/shared/script/cc_script.cpp
@@ -28,7 +28,7 @@
 #include "util/stream.h"
 #include "util/string_compat.h"
 
-using AGS::Common::Stream;
+using AGS::Shared::Stream;
 
 // currently executed line
 int currentline;
diff --git a/engines/ags/shared/script/cc_script.h b/engines/ags/shared/script/cc_script.h
index 8821879907..e1390caa8c 100644
--- a/engines/ags/shared/script/cc_script.h
+++ b/engines/ags/shared/script/cc_script.h
@@ -35,7 +35,7 @@
 namespace AGS3 {
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 } // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/util/alignedstream.cpp b/engines/ags/shared/util/alignedstream.cpp
index d1a760a593..aa0a190963 100644
--- a/engines/ags/shared/util/alignedstream.cpp
+++ b/engines/ags/shared/util/alignedstream.cpp
@@ -25,7 +25,7 @@
 #include "util/math.h"
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 AlignedStream::AlignedStream(Stream *stream, AlignedStreamMode mode, ObjectOwnershipPolicy stream_ownership_policy,
                              size_t base_alignment)
@@ -328,5 +328,5 @@ void AlignedStream::FinalizeBlock() {
 	_block = 0;
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/util/alignedstream.h b/engines/ags/shared/util/alignedstream.h
index f91ab58c83..8d9d90a42a 100644
--- a/engines/ags/shared/util/alignedstream.h
+++ b/engines/ags/shared/util/alignedstream.h
@@ -49,7 +49,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 enum AlignedStreamMode {
 	kAligned_Read,
@@ -108,7 +108,7 @@ private:
 	int64_t             _block;
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/util/bbop.h b/engines/ags/shared/util/bbop.h
index 32472fa84a..c8cb850ed8 100644
--- a/engines/ags/shared/util/bbop.h
+++ b/engines/ags/shared/util/bbop.h
@@ -38,7 +38,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 enum DataEndianess {
 	kBigEndian,
@@ -146,7 +146,7 @@ inline float FloatFromBE(const float val) {
 // Aliases for easier calling
 namespace BBOp = BitByteOperations;
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/util/bufferedstream.cpp b/engines/ags/shared/util/bufferedstream.cpp
index a1a8f0dd06..34a569501a 100644
--- a/engines/ags/shared/util/bufferedstream.cpp
+++ b/engines/ags/shared/util/bufferedstream.cpp
@@ -28,7 +28,7 @@
 #include "util/string.h"
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 BufferedStream::BufferedStream(const String &file_name, FileOpenMode open_mode, FileWorkMode work_mode, DataEndianess stream_endianess)
 	: FileStream(file_name, open_mode, work_mode, stream_endianess), _buffer(BufferStreamSize), _bufferPosition(0), _position(0) {
@@ -137,5 +137,5 @@ bool BufferedStream::Seek(soff_t offset, StreamSeek origin) {
 	return _position == want_pos;
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/util/bufferedstream.h b/engines/ags/shared/util/bufferedstream.h
index 4e14beb8c5..1f4bb3a22f 100644
--- a/engines/ags/shared/util/bufferedstream.h
+++ b/engines/ags/shared/util/bufferedstream.h
@@ -29,7 +29,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 // Needs tuning depending on the platform.
 const auto BufferStreamSize = 8 * 1024;
@@ -66,7 +66,7 @@ private:
 	void FillBufferFromPosition(soff_t position);
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/util/compress.cpp b/engines/ags/shared/util/compress.cpp
index cb0cf21e8c..9c5270ee76 100644
--- a/engines/ags/shared/util/compress.cpp
+++ b/engines/ags/shared/util/compress.cpp
@@ -37,7 +37,7 @@
 #include "util/bbop.h"
 #endif
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 void cpackbitl(const uint8_t *line, int size, Stream *out) {
 	int cnt = 0;                  // bytes encoded
diff --git a/engines/ags/shared/util/compress.h b/engines/ags/shared/util/compress.h
index 8fd7aa630e..0c4b8016a8 100644
--- a/engines/ags/shared/util/compress.h
+++ b/engines/ags/shared/util/compress.h
@@ -28,7 +28,7 @@
 namespace AGS3 {
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 class Bitmap;
 } // namespace Shared
diff --git a/engines/ags/shared/util/datastream.cpp b/engines/ags/shared/util/datastream.cpp
index ff170d184c..ad41bfe4e2 100644
--- a/engines/ags/shared/util/datastream.cpp
+++ b/engines/ags/shared/util/datastream.cpp
@@ -23,7 +23,7 @@
 #include "util/datastream.h"
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 DataStream::DataStream(DataEndianess stream_endianess)
 	: _streamEndianess(stream_endianess) {
@@ -151,5 +151,5 @@ size_t DataStream::WriteAndConvertArrayOfInt64(const int64_t *buffer, size_t cou
 	return elem;
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/util/datastream.h b/engines/ags/shared/util/datastream.h
index da47e40cb7..16322fd4aa 100644
--- a/engines/ags/shared/util/datastream.h
+++ b/engines/ags/shared/util/datastream.h
@@ -36,7 +36,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 class DataStream : public Stream {
 public:
@@ -123,7 +123,7 @@ protected:
 	}
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/util/directory.cpp b/engines/ags/shared/util/directory.cpp
index fa58dfc3eb..ba0c39b740 100644
--- a/engines/ags/shared/util/directory.cpp
+++ b/engines/ags/shared/util/directory.cpp
@@ -33,7 +33,7 @@
 #include "stdio_compat.h"
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 namespace Directory {
 
@@ -81,5 +81,5 @@ String GetCurrentDirectory() {
 
 } // namespace Directory
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/util/directory.h b/engines/ags/shared/util/directory.h
index 55dc4deb0a..07f5cac469 100644
--- a/engines/ags/shared/util/directory.h
+++ b/engines/ags/shared/util/directory.h
@@ -34,7 +34,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 namespace Directory {
 // Creates new directory (if it does not exist)
@@ -48,7 +48,7 @@ String SetCurrentDirectory(const String &path);
 String GetCurrentDirectory();
 } // namespace Directory
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/util/error.h b/engines/ags/shared/util/error.h
index 4487484976..f404b44ae3 100644
--- a/engines/ags/shared/util/error.h
+++ b/engines/ags/shared/util/error.h
@@ -35,7 +35,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 class Error;
 typedef std::shared_ptr<Error> PError;
@@ -162,7 +162,7 @@ public:
 	}
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/util/file.cpp b/engines/ags/shared/util/file.cpp
index 3b597748de..0b4adcd784 100644
--- a/engines/ags/shared/util/file.cpp
+++ b/engines/ags/shared/util/file.cpp
@@ -30,7 +30,7 @@
 #include "util/bufferedstream.h"
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 soff_t File::GetFileSize(const String &filename) {
 	return ags_file_size(filename.GetCStr());
@@ -151,5 +151,5 @@ Stream *File::OpenFile(const String &filename, FileOpenMode open_mode, FileWorkM
 	return fs;
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/util/file.h b/engines/ags/shared/util/file.h
index 6774a33c07..73f21201cd 100644
--- a/engines/ags/shared/util/file.h
+++ b/engines/ags/shared/util/file.h
@@ -34,7 +34,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 // Forward declarations
 class Stream;
@@ -84,7 +84,7 @@ inline Stream *OpenFileWrite(const String &filename) {
 }
 } // namespace File
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/util/filestream.cpp b/engines/ags/shared/util/filestream.cpp
index aa08fa407a..25956eb400 100644
--- a/engines/ags/shared/util/filestream.cpp
+++ b/engines/ags/shared/util/filestream.cpp
@@ -27,7 +27,7 @@
 #include "util/string.h"
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 FileStream::FileStream(const String &file_name, FileOpenMode open_mode, FileWorkMode work_mode,
                        DataEndianess stream_endianess)
@@ -160,5 +160,5 @@ void FileStream::Open(const String &file_name, FileOpenMode open_mode, FileWorkM
 		throw std::runtime_error("Error opening file.");
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/util/filestream.h b/engines/ags/shared/util/filestream.h
index 8e222b2a37..77aae7dac1 100644
--- a/engines/ags/shared/util/filestream.h
+++ b/engines/ags/shared/util/filestream.h
@@ -30,7 +30,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 class FileStream : public DataStream {
 public:
@@ -74,7 +74,7 @@ private:
 	const FileWorkMode  _workMode;
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/util/geometry.cpp b/engines/ags/shared/util/geometry.cpp
index c4e4c9a893..254f2dd301 100644
--- a/engines/ags/shared/util/geometry.cpp
+++ b/engines/ags/shared/util/geometry.cpp
@@ -26,7 +26,7 @@
 
 //namespace AGS
 //{
-//namespace Common
+//namespace Shared
 //{
 
 bool AreRectsIntersecting(const Rect &r1, const Rect &r2) {
@@ -125,5 +125,5 @@ Rect PlaceInRect(const Rect &place, const Rect &item, const RectPlacement &place
 	}
 }
 
-//} // namespace Common
+//} // namespace Shared
 //} // namespace AGS
diff --git a/engines/ags/shared/util/geometry.h b/engines/ags/shared/util/geometry.h
index 058ca377a9..570868df7c 100644
--- a/engines/ags/shared/util/geometry.h
+++ b/engines/ags/shared/util/geometry.h
@@ -33,10 +33,10 @@
 
 namespace AGS3 {
 
-namespace AGSMath = AGS::Common::Math;
+namespace AGSMath = AGS::Shared::Math;
 //namespace AGS
 //{
-//namespace Common
+//namespace Shared
 //{
 
 // Type of alignment of a geometric item of rectangular boundaries.
@@ -361,7 +361,7 @@ Rect OffsetRect(const Rect &r, const Point off);
 Rect CenterInRect(const Rect &place, const Rect &item);
 Rect ClampToRect(const Rect &place, const Rect &item);
 Rect PlaceInRect(const Rect &place, const Rect &item, const RectPlacement &placement);
-//} // namespace Common
+//} // namespace Shared
 //} // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/util/ini_util.cpp b/engines/ags/shared/util/ini_util.cpp
index b18321f256..b5b773f9af 100644
--- a/engines/ags/shared/util/ini_util.cpp
+++ b/engines/ags/shared/util/ini_util.cpp
@@ -28,7 +28,7 @@
 #include "util/textstreamwriter.h"
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 typedef std::unique_ptr<Stream>       UStream;
 typedef IniFile::SectionIterator      SectionIterator;
@@ -179,5 +179,5 @@ bool IniUtil::Merge(const String &file, const ConfigTree &tree) {
 	return true;
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/util/ini_util.h b/engines/ags/shared/util/ini_util.h
index 7e5906bb5e..6a127f3652 100644
--- a/engines/ags/shared/util/ini_util.h
+++ b/engines/ags/shared/util/ini_util.h
@@ -35,7 +35,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 typedef std::map<String, String>         StringOrderMap;
 typedef StringOrderMap::const_iterator   StrStrOIter;
@@ -69,7 +69,7 @@ void WriteToString(String &s, const ConfigTree &tree);
 bool Merge(const String &file, const ConfigTree &tree);
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/util/inifile.cpp b/engines/ags/shared/util/inifile.cpp
index 0e39d95863..3841e2e3c4 100644
--- a/engines/ags/shared/util/inifile.cpp
+++ b/engines/ags/shared/util/inifile.cpp
@@ -34,7 +34,7 @@ inline int isblank(int ch) {
 } // std
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 inline static void ReplaceSubString(String &line, IniFile::StrPos &sub_pos, const String &new_sub) {
 	line.ReplaceMid(sub_pos.first, sub_pos.second - sub_pos.first, new_sub);
@@ -266,5 +266,5 @@ void IniFile::Write(Stream *out) const {
 	writer.ReleaseStream();
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/util/inifile.h b/engines/ags/shared/util/inifile.h
index 09709dda14..eaa490c368 100644
--- a/engines/ags/shared/util/inifile.h
+++ b/engines/ags/shared/util/inifile.h
@@ -38,7 +38,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 class IniFile {
 public:
@@ -168,7 +168,7 @@ private:
 	LSections _sections;
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/util/lzw.cpp b/engines/ags/shared/util/lzw.cpp
index d6667f1bf5..be39388a6e 100644
--- a/engines/ags/shared/util/lzw.cpp
+++ b/engines/ags/shared/util/lzw.cpp
@@ -30,7 +30,7 @@
 #include "ac/common.h" // quit
 #include "util/stream.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 #ifdef _MANAGED
 // ensure this doesn't get compiled to .NET IL
diff --git a/engines/ags/shared/util/lzw.h b/engines/ags/shared/util/lzw.h
index 236343090c..25171da1d3 100644
--- a/engines/ags/shared/util/lzw.h
+++ b/engines/ags/shared/util/lzw.h
@@ -26,7 +26,7 @@
 namespace AGS3 {
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 } // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/util/math.h b/engines/ags/shared/util/math.h
index 9053565f8b..b7737facc1 100644
--- a/engines/ags/shared/util/math.h
+++ b/engines/ags/shared/util/math.h
@@ -36,7 +36,7 @@ namespace AGS3 {
 #endif
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 namespace Math {
 template <class T>
@@ -84,7 +84,7 @@ inline float DegreesToRadians(float deg) {
 }
 } // namespace Math
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/util/memory.h b/engines/ags/shared/util/memory.h
index 85defb9cbb..3b6a0f3c4e 100644
--- a/engines/ags/shared/util/memory.h
+++ b/engines/ags/shared/util/memory.h
@@ -40,7 +40,7 @@ namespace AGS3 {
 #endif
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 namespace Memory {
 //-------------------------------------------------------------------------
@@ -228,7 +228,7 @@ inline void BlockCopy(uint8_t *dst, const size_t dst_pitch, const size_t dst_off
 
 } // namespace Memory
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/util/misc.cpp b/engines/ags/shared/util/misc.cpp
index a2210e8ae8..65b730665b 100644
--- a/engines/ags/shared/util/misc.cpp
+++ b/engines/ags/shared/util/misc.cpp
@@ -63,7 +63,7 @@
 #include "util/stream.h"
 
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 #if !defined (AGS_CASE_SENSITIVE_FILESYSTEM)
 #include <string.h>
diff --git a/engines/ags/shared/util/misc.h b/engines/ags/shared/util/misc.h
index 8d798e1e7f..1cd6e6efc3 100644
--- a/engines/ags/shared/util/misc.h
+++ b/engines/ags/shared/util/misc.h
@@ -57,7 +57,7 @@
 namespace AGS3 {
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 } // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/util/multifilelib.h b/engines/ags/shared/util/multifilelib.h
index d7242b667c..49dad28c69 100644
--- a/engines/ags/shared/util/multifilelib.h
+++ b/engines/ags/shared/util/multifilelib.h
@@ -39,7 +39,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 //
 // MultiFileLib utilities: (de)serialization of asset library in MFL format
@@ -73,7 +73,7 @@ void     WriteHeader(const AssetLibInfo &lib, MFLVersion lib_version, int lib_in
 void     WriteEnder(soff_t lib_offset, MFLVersion lib_index, Stream *out);
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/util/mutifilelib.cpp b/engines/ags/shared/util/mutifilelib.cpp
index 490d3ba1f4..03ff460569 100644
--- a/engines/ags/shared/util/mutifilelib.cpp
+++ b/engines/ags/shared/util/mutifilelib.cpp
@@ -26,7 +26,7 @@
 #include "util/string_utils.h"
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 namespace MFLUtil {
 const String HeadSig = "CLIB\x1a";
@@ -401,7 +401,7 @@ int32_t MFLUtil::ReadEncInt32(Stream *in, int &rand_val) {
 	int val;
 	ReadEncArray(&val, sizeof(int32_t), 1, in, rand_val);
 #if AGS_PLATFORM_ENDIAN_BIG
-	AGS::Common::BitByteOperations::SwapBytesInt32(val);
+	AGS::Shared::BitByteOperations::SwapBytesInt32(val);
 #endif
 	return val;
 }
@@ -418,4 +418,4 @@ void MFLUtil::ReadEncString(char *buffer, size_t max_len, Stream *in, int &rand_
 }
 
 } // namespace AGS
-} // namespace Common
+} // namespace Shared
diff --git a/engines/ags/shared/util/path.cpp b/engines/ags/shared/util/path.cpp
index 2b75fe8943..a3b88923a7 100644
--- a/engines/ags/shared/util/path.cpp
+++ b/engines/ags/shared/util/path.cpp
@@ -34,7 +34,7 @@
 #endif
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 namespace Path {
 
@@ -241,5 +241,5 @@ String GetCmdLinePathInASCII(const char *arg, int arg_index) {
 
 } // namespace Path
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/util/path.h b/engines/ags/shared/util/path.h
index 41a62c406b..0901c6d57b 100644
--- a/engines/ags/shared/util/path.h
+++ b/engines/ags/shared/util/path.h
@@ -33,7 +33,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 namespace Path {
 // Tells if the given path is a directory
@@ -85,7 +85,7 @@ String  GetPathInASCII(const String &path);
 String  GetCmdLinePathInASCII(const char *arg, int arg_index);
 } // namespace Path
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/util/proxystream.cpp b/engines/ags/shared/util/proxystream.cpp
index cdd979569d..71fe5a17a5 100644
--- a/engines/ags/shared/util/proxystream.cpp
+++ b/engines/ags/shared/util/proxystream.cpp
@@ -23,7 +23,7 @@
 #include "util/proxystream.h"
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 ProxyStream::ProxyStream(Stream *stream, ObjectOwnershipPolicy stream_ownership_policy)
 	: _stream(stream)
@@ -152,5 +152,5 @@ bool ProxyStream::Seek(soff_t offset, StreamSeek origin) {
 	return _stream ? _stream->Seek(offset, origin) : false;
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/util/proxystream.h b/engines/ags/shared/util/proxystream.h
index 8c0758cd1d..ef40dd10c4 100644
--- a/engines/ags/shared/util/proxystream.h
+++ b/engines/ags/shared/util/proxystream.h
@@ -27,7 +27,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 // TODO: replace with std::shared_ptr!!!
 enum ObjectOwnershipPolicy {
@@ -83,7 +83,7 @@ protected:
 	ObjectOwnershipPolicy   _streamOwnershipPolicy;
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/util/stream.cpp b/engines/ags/shared/util/stream.cpp
index 737496ec43..33b7177874 100644
--- a/engines/ags/shared/util/stream.cpp
+++ b/engines/ags/shared/util/stream.cpp
@@ -23,7 +23,7 @@
 #include "util/stream.h"
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 size_t Stream::WriteByteCount(uint8_t b, size_t count) {
 	if (!CanWrite())
@@ -36,5 +36,5 @@ size_t Stream::WriteByteCount(uint8_t b, size_t count) {
 	return size;
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/util/stream.h b/engines/ags/shared/util/stream.h
index d9cafba202..90cb0011e5 100644
--- a/engines/ags/shared/util/stream.h
+++ b/engines/ags/shared/util/stream.h
@@ -39,7 +39,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 class Stream : public IAGSStream {
 public:
@@ -83,7 +83,7 @@ public:
 	size_t WriteByteCount(uint8_t b, size_t count);
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/util/string.cpp b/engines/ags/shared/util/string.cpp
index c6f9eb85d0..21e10d1f28 100644
--- a/engines/ags/shared/util/string.cpp
+++ b/engines/ags/shared/util/string.cpp
@@ -29,7 +29,7 @@
 #include "util/string_compat.h"
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 String::String()
 	: _cstr(nullptr)
@@ -846,5 +846,5 @@ void String::ReserveAndShift(bool left, size_t more_length) {
 	}
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/util/string.h b/engines/ags/shared/util/string.h
index 8d8a02f893..c2ecec93fb 100644
--- a/engines/ags/shared/util/string.h
+++ b/engines/ags/shared/util/string.h
@@ -54,7 +54,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 class Stream;
 
@@ -365,7 +365,7 @@ private:
 	};
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/util/string_types.h b/engines/ags/shared/util/string_types.h
index c0871acc26..60fe83f991 100644
--- a/engines/ags/shared/util/string_types.h
+++ b/engines/ags/shared/util/string_types.h
@@ -60,8 +60,8 @@ namespace tr1 {
 #endif
 // std::hash for String object
 template<>
-struct hash<AGS::Common::String> : public unary_function<AGS::Common::String, size_t> {
-	size_t operator()(const AGS::Common::String &key) const {
+struct hash<AGS::Shared::String> : public unary_function<AGS::Shared::String, size_t> {
+	size_t operator()(const AGS::Shared::String &key) const {
 		return FNV::Hash(key.GetCStr(), key.GetLength());
 	}
 };
@@ -72,7 +72,7 @@ struct hash<AGS::Common::String> : public unary_function<AGS::Common::String, si
 
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 //
 // Various comparison functors
@@ -103,7 +103,7 @@ typedef std::vector<String> StringV;
 typedef std::unordered_map<String, String> StringMap;
 typedef std::unordered_map<String, String, HashStrNoCase, StrEqNoCase> StringIMap;
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/util/string_utils.cpp b/engines/ags/shared/util/string_utils.cpp
index 5278966534..e624738f1a 100644
--- a/engines/ags/shared/util/string_utils.cpp
+++ b/engines/ags/shared/util/string_utils.cpp
@@ -27,7 +27,7 @@
 #include "util/string_utils.h"
 #include "util/stream.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 String cbuf_to_string_and_free(char *char_buf) {
 	String s = char_buf;
@@ -37,7 +37,7 @@ String cbuf_to_string_and_free(char *char_buf) {
 
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 String StrUtil::IntToString(int d) {
 	return String::FromFormat("%d", d);
@@ -156,5 +156,5 @@ void StrUtil::WriteCStr(const String &s, Stream *out) {
 	out->Write(s.GetCStr(), s.GetLength() + 1);
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/util/string_utils.h b/engines/ags/shared/util/string_utils.h
index 34a33e37bf..fc4ebd8f6b 100644
--- a/engines/ags/shared/util/string_utils.h
+++ b/engines/ags/shared/util/string_utils.h
@@ -28,7 +28,7 @@
 namespace AGS3 {
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 } // namespace Shared
 } // namespace AGS
@@ -42,7 +42,7 @@ using namespace AGS; // FIXME later
 Common::String cbuf_to_string_and_free(char *char_buf);
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 namespace StrUtil {
 enum ConversionError {
 	kNoError,   // conversion successful
@@ -77,7 +77,7 @@ void            SkipCStr(Stream *in);
 void            WriteCStr(const char *cstr, Stream *out);
 void            WriteCStr(const String &s, Stream *out);
 }
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/util/textreader.h b/engines/ags/shared/util/textreader.h
index 3cfe2b6463..78a507c5a9 100644
--- a/engines/ags/shared/util/textreader.h
+++ b/engines/ags/shared/util/textreader.h
@@ -33,7 +33,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 class TextReader {
 public:
@@ -51,7 +51,7 @@ public:
 	virtual String  ReadAll() = 0;
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/util/textstreamreader.cpp b/engines/ags/shared/util/textstreamreader.cpp
index 5b974e838c..ec619da206 100644
--- a/engines/ags/shared/util/textstreamreader.cpp
+++ b/engines/ags/shared/util/textstreamreader.cpp
@@ -25,7 +25,7 @@
 #include "util/textstreamreader.h"
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 TextStreamReader::TextStreamReader(Stream *stream)
 	: _stream(stream) {
@@ -132,5 +132,5 @@ String TextStreamReader::ReadAll() {
 	return "";
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/util/textstreamreader.h b/engines/ags/shared/util/textstreamreader.h
index 50360d619e..9c527dcc23 100644
--- a/engines/ags/shared/util/textstreamreader.h
+++ b/engines/ags/shared/util/textstreamreader.h
@@ -33,7 +33,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 class Stream;
 
@@ -63,7 +63,7 @@ private:
 	Stream *_stream;
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/util/textstreamwriter.cpp b/engines/ags/shared/util/textstreamwriter.cpp
index edf2f8588e..2e2eb97301 100644
--- a/engines/ags/shared/util/textstreamwriter.cpp
+++ b/engines/ags/shared/util/textstreamwriter.cpp
@@ -27,7 +27,7 @@
 #include "util/stream.h"
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 #if AGS_PLATFORM_OS_WINDOWS
 static const char Endl[2] = {'\r', '\n'};
@@ -108,5 +108,5 @@ void TextStreamWriter::WriteLineBreak() {
 		_stream->Write(Endl, sizeof(Endl));
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/util/textstreamwriter.h b/engines/ags/shared/util/textstreamwriter.h
index bf7df09112..ef15320996 100644
--- a/engines/ags/shared/util/textstreamwriter.h
+++ b/engines/ags/shared/util/textstreamwriter.h
@@ -33,7 +33,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 class Stream;
 
@@ -64,7 +64,7 @@ private:
 	Stream *_stream;
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/util/textwriter.h b/engines/ags/shared/util/textwriter.h
index 9140f43832..42c735c371 100644
--- a/engines/ags/shared/util/textwriter.h
+++ b/engines/ags/shared/util/textwriter.h
@@ -33,7 +33,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 class TextWriter {
 public:
@@ -52,7 +52,7 @@ public:
 	virtual void    WriteLineBreak() = 0;
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/util/version.cpp b/engines/ags/shared/util/version.cpp
index 613ab12a3a..6b1a273f52 100644
--- a/engines/ags/shared/util/version.cpp
+++ b/engines/ags/shared/util/version.cpp
@@ -24,7 +24,7 @@
 #include "util/version.h"
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 const Version Version::LastOldFormatVersion(3, 2, 2, 1120);
 
@@ -132,5 +132,5 @@ void Version::MakeString() {
 	ShortString.Format("%d.%d", Major, Minor);
 }
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/util/version.h b/engines/ags/shared/util/version.h
index ed91b13323..95dad1377a 100644
--- a/engines/ags/shared/util/version.h
+++ b/engines/ags/shared/util/version.h
@@ -33,7 +33,7 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 using Common::String;
 
@@ -101,7 +101,7 @@ private:
 	void MakeString();
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/util/wgt2allg.cpp b/engines/ags/shared/util/wgt2allg.cpp
index 436481eb39..4a37ce5b83 100644
--- a/engines/ags/shared/util/wgt2allg.cpp
+++ b/engines/ags/shared/util/wgt2allg.cpp
@@ -25,7 +25,7 @@
 #include "util/stream.h"
 #include "util/wgt2allg.h"
 
-using namespace AGS::Common;
+using namespace AGS::Shared;
 
 #ifdef __cplusplus
 extern "C"
diff --git a/engines/ags/shared/util/wgt2allg.h b/engines/ags/shared/util/wgt2allg.h
index 3e4f81ca2f..b9624c53bb 100644
--- a/engines/ags/shared/util/wgt2allg.h
+++ b/engines/ags/shared/util/wgt2allg.h
@@ -40,7 +40,7 @@
 namespace AGS3 {
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Bitmap;
 } // namespace Shared
 } // namespace AGS


Commit: a7a9ca05433b2707dad9954dfc32fc26dcdf3b1b
    https://github.com/scummvm/scummvm/commit/a7a9ca05433b2707dad9954dfc32fc26dcdf3b1b
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Adding AGS3 namespace to cpp files

Changed paths:
  R engines/ags/engine/script/cc_error_engine.cpp
    engines/ags/engine/ac/audiochannel.cpp
    engines/ags/engine/ac/audioclip.cpp
    engines/ags/engine/ac/button.cpp
    engines/ags/engine/ac/cdaudio.cpp
    engines/ags/engine/ac/character.cpp
    engines/ags/engine/ac/characterextras.cpp
    engines/ags/engine/ac/characterinfo_engine.cpp
    engines/ags/engine/ac/datetime.cpp
    engines/ags/engine/ac/dialog.cpp
    engines/ags/engine/ac/dialogoptionsrendering.cpp
    engines/ags/engine/ac/display.cpp
    engines/ags/engine/ac/draw.cpp
    engines/ags/engine/ac/draw_software.cpp
    engines/ags/engine/ac/drawingsurface.cpp
    engines/ags/engine/ac/dynamicsprite.cpp
    engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp
    engines/ags/engine/ac/dynobj/cc_audiochannel.cpp
    engines/ags/engine/ac/dynobj/cc_audioclip.cpp
    engines/ags/engine/ac/dynobj/cc_character.cpp
    engines/ags/engine/ac/dynobj/cc_dialog.cpp
    engines/ags/engine/ac/dynobj/cc_dynamicarray.cpp
    engines/ags/engine/ac/dynobj/cc_dynamicobject.cpp
    engines/ags/engine/ac/dynobj/cc_gui.cpp
    engines/ags/engine/ac/dynobj/cc_guiobject.cpp
    engines/ags/engine/ac/dynobj/cc_hotspot.cpp
    engines/ags/engine/ac/dynobj/cc_inventory.cpp
    engines/ags/engine/ac/dynobj/cc_object.cpp
    engines/ags/engine/ac/dynobj/cc_region.cpp
    engines/ags/engine/ac/dynobj/cc_serializer.cpp
    engines/ags/engine/ac/dynobj/managedobjectpool.cpp
    engines/ags/engine/ac/dynobj/scriptcamera.cpp
    engines/ags/engine/ac/dynobj/scriptdatetime.cpp
    engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.cpp
    engines/ags/engine/ac/dynobj/scriptdict.cpp
    engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp
    engines/ags/engine/ac/dynobj/scriptdynamicsprite.cpp
    engines/ags/engine/ac/dynobj/scriptfile.cpp
    engines/ags/engine/ac/dynobj/scriptoverlay.cpp
    engines/ags/engine/ac/dynobj/scriptset.cpp
    engines/ags/engine/ac/dynobj/scriptstring.cpp
    engines/ags/engine/ac/dynobj/scriptuserobject.cpp
    engines/ags/engine/ac/dynobj/scriptviewframe.cpp
    engines/ags/engine/ac/dynobj/scriptviewport.cpp
    engines/ags/engine/ac/event.cpp
    engines/ags/engine/ac/file.cpp
    engines/ags/engine/ac/game.cpp
    engines/ags/engine/ac/gamesetup.cpp
    engines/ags/engine/ac/gamestate.cpp
    engines/ags/engine/ac/global_api.cpp
    engines/ags/engine/ac/global_audio.cpp
    engines/ags/engine/ac/global_button.cpp
    engines/ags/engine/ac/global_character.cpp
    engines/ags/engine/ac/global_datetime.cpp
    engines/ags/engine/ac/global_debug.cpp
    engines/ags/engine/ac/global_dialog.cpp
    engines/ags/engine/ac/global_display.cpp
    engines/ags/engine/ac/global_drawingsurface.cpp
    engines/ags/engine/ac/global_dynamicsprite.cpp
    engines/ags/engine/ac/global_file.cpp
    engines/ags/engine/ac/global_game.cpp
    engines/ags/engine/ac/global_gui.cpp
    engines/ags/engine/ac/global_hotspot.cpp
    engines/ags/engine/ac/global_inventoryitem.cpp
    engines/ags/engine/ac/global_invwindow.cpp
    engines/ags/engine/ac/global_label.cpp
    engines/ags/engine/ac/global_listbox.cpp
    engines/ags/engine/ac/global_mouse.cpp
    engines/ags/engine/ac/global_object.cpp
    engines/ags/engine/ac/global_overlay.cpp
    engines/ags/engine/ac/global_palette.cpp
    engines/ags/engine/ac/global_parser.cpp
    engines/ags/engine/ac/global_record.cpp
    engines/ags/engine/ac/global_region.cpp
    engines/ags/engine/ac/global_room.cpp
    engines/ags/engine/ac/global_screen.cpp
    engines/ags/engine/ac/global_slider.cpp
    engines/ags/engine/ac/global_string.cpp
    engines/ags/engine/ac/global_textbox.cpp
    engines/ags/engine/ac/global_timer.cpp
    engines/ags/engine/ac/global_translation.cpp
    engines/ags/engine/ac/global_video.cpp
    engines/ags/engine/ac/global_viewframe.cpp
    engines/ags/engine/ac/global_viewport.cpp
    engines/ags/engine/ac/global_walkablearea.cpp
    engines/ags/engine/ac/global_walkbehind.cpp
    engines/ags/engine/ac/gui.cpp
    engines/ags/engine/ac/guicontrol.cpp
    engines/ags/engine/ac/guiinv.cpp
    engines/ags/engine/ac/hotspot.cpp
    engines/ags/engine/ac/interfacebutton.cpp
    engines/ags/engine/ac/interfaceelement.cpp
    engines/ags/engine/ac/inventoryitem.cpp
    engines/ags/engine/ac/invwindow.cpp
    engines/ags/engine/ac/keycode.cpp
    engines/ags/engine/ac/label.cpp
    engines/ags/engine/ac/listbox.cpp
    engines/ags/engine/ac/math.cpp
    engines/ags/engine/ac/mouse.cpp
    engines/ags/engine/ac/movelist.cpp
    engines/ags/engine/ac/object.cpp
    engines/ags/engine/ac/overlay.cpp
    engines/ags/engine/ac/parser.cpp
    engines/ags/engine/ac/properties.cpp
    engines/ags/engine/ac/region.cpp
    engines/ags/engine/ac/richgamemedia.cpp
    engines/ags/engine/ac/room.cpp
    engines/ags/engine/ac/roomobject.cpp
    engines/ags/engine/ac/roomstatus.cpp
    engines/ags/engine/ac/route_finder.cpp
    engines/ags/engine/ac/route_finder_impl.cpp
    engines/ags/engine/ac/route_finder_impl_legacy.cpp
    engines/ags/engine/ac/screen.cpp
    engines/ags/engine/ac/screenoverlay.cpp
    engines/ags/engine/ac/scriptcontainers.cpp
    engines/ags/engine/ac/slider.cpp
    engines/ags/engine/ac/speech.cpp
    engines/ags/engine/ac/sprite.cpp
    engines/ags/engine/ac/spritecache_engine.cpp
    engines/ags/engine/ac/statobj/agsstaticobject.cpp
    engines/ags/engine/ac/statobj/staticarray.cpp
    engines/ags/engine/ac/string.cpp
    engines/ags/engine/ac/sys_events.cpp
    engines/ags/engine/ac/system.cpp
    engines/ags/engine/ac/textbox.cpp
    engines/ags/engine/ac/timer.cpp
    engines/ags/engine/ac/translation.cpp
    engines/ags/engine/ac/tree_map.cpp
    engines/ags/engine/ac/viewframe.cpp
    engines/ags/engine/ac/viewport_script.cpp
    engines/ags/engine/ac/walkablearea.cpp
    engines/ags/engine/ac/walkbehind.cpp
    engines/ags/engine/debugging/consoleoutputtarget.cpp
    engines/ags/engine/debugging/debug.cpp
    engines/ags/engine/debugging/filebasedagsdebugger.cpp
    engines/ags/engine/debugging/logfile.cpp
    engines/ags/engine/debugging/messagebuffer.cpp
    engines/ags/engine/device/mousew32.cpp
    engines/ags/engine/font/fonts_engine.cpp
    engines/ags/engine/game/game_init.cpp
    engines/ags/engine/game/savegame.cpp
    engines/ags/engine/game/savegame_components.cpp
    engines/ags/engine/game/viewport.cpp
    engines/ags/engine/gfx/ali3dogl.cpp
    engines/ags/engine/gfx/ali3dsw.cpp
    engines/ags/engine/gfx/blender.cpp
    engines/ags/engine/gfx/color_engine.cpp
    engines/ags/engine/gfx/gfx_util.cpp
    engines/ags/engine/gfx/gfxdriverbase.cpp
    engines/ags/engine/gfx/gfxdriverfactory.cpp
    engines/ags/engine/gfx/gfxfilter_aad3d.cpp
    engines/ags/engine/gfx/gfxfilter_aaogl.cpp
    engines/ags/engine/gfx/gfxfilter_allegro.cpp
    engines/ags/engine/gfx/gfxfilter_d3d.cpp
    engines/ags/engine/gfx/gfxfilter_hqx.cpp
    engines/ags/engine/gfx/gfxfilter_ogl.cpp
    engines/ags/engine/gfx/gfxfilter_scaling.cpp
    engines/ags/engine/gui/animatingguibutton.cpp
    engines/ags/engine/gui/cscidialog.cpp
    engines/ags/engine/gui/gui_engine.cpp
    engines/ags/engine/gui/guidialog.cpp
    engines/ags/engine/gui/mylabel.cpp
    engines/ags/engine/gui/mylistbox.cpp
    engines/ags/engine/gui/mypushbutton.cpp
    engines/ags/engine/gui/mytextbox.cpp
    engines/ags/engine/gui/newcontrol.cpp
    engines/ags/engine/main/config.cpp
    engines/ags/engine/main/engine.cpp
    engines/ags/engine/main/engine_setup.cpp
    engines/ags/engine/main/game_file.cpp
    engines/ags/engine/main/game_run.cpp
    engines/ags/engine/main/game_start.cpp
    engines/ags/engine/main/graphics_mode.cpp
    engines/ags/engine/main/main.cpp
    engines/ags/engine/main/quit.cpp
    engines/ags/engine/main/update.cpp
    engines/ags/engine/media/audio/ambientsound.cpp
    engines/ags/engine/media/audio/audio.cpp
    engines/ags/engine/media/audio/clip_mydumbmod.cpp
    engines/ags/engine/media/audio/clip_myjgmod.cpp
    engines/ags/engine/media/audio/clip_mymidi.cpp
    engines/ags/engine/media/audio/clip_mymp3.cpp
    engines/ags/engine/media/audio/clip_myogg.cpp
    engines/ags/engine/media/audio/clip_mystaticmp3.cpp
    engines/ags/engine/media/audio/clip_mystaticogg.cpp
    engines/ags/engine/media/audio/clip_mywave.cpp
    engines/ags/engine/media/audio/queuedaudioitem.cpp
    engines/ags/engine/media/audio/sound.cpp
    engines/ags/engine/media/audio/soundcache.cpp
    engines/ags/engine/media/audio/soundclip.cpp
    engines/ags/engine/media/video/video.cpp
    engines/ags/engine/platform/android/acpland.cpp
    engines/ags/engine/platform/base/agsplatformdriver.cpp
    engines/ags/engine/platform/ios/acplios.cpp
    engines/ags/engine/platform/linux/acpllnx.cpp
    engines/ags/engine/platform/osx/acplmac.cpp
    engines/ags/engine/platform/windows/acplwin.cpp
    engines/ags/engine/platform/windows/debugging/namedpipesagsdebugger.cpp
    engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
    engines/ags/engine/platform/windows/media/video/acwavi.cpp
    engines/ags/engine/platform/windows/media/video/acwavi3d.cpp
    engines/ags/engine/platform/windows/minidump.cpp
    engines/ags/engine/platform/windows/setup/winsetup.cpp
    engines/ags/engine/platform/windows/win_ex_handling.cpp
    engines/ags/engine/plugin/agsplugin.cpp
    engines/ags/engine/plugin/global_plugin.cpp
    engines/ags/engine/plugin/pluginobjectreader.cpp
    engines/ags/engine/script/cc_instance.cpp
    engines/ags/engine/script/executingscript.cpp
    engines/ags/engine/script/exports.cpp
    engines/ags/engine/script/runtimescriptvalue.cpp
    engines/ags/engine/script/script.cpp
    engines/ags/engine/script/script_api.cpp
    engines/ags/engine/script/script_engine.cpp
    engines/ags/engine/script/script_runtime.cpp
    engines/ags/engine/script/systemimports.cpp
    engines/ags/shared/ac/audiocliptype.cpp
    engines/ags/shared/ac/characterinfo.cpp
    engines/ags/shared/ac/common.cpp
    engines/ags/shared/ac/dialogtopic.cpp
    engines/ags/shared/ac/dynobj/scriptaudioclip.cpp
    engines/ags/shared/ac/gamesetupstruct.cpp
    engines/ags/shared/ac/gamesetupstructbase.cpp
    engines/ags/shared/ac/inventoryiteminfo.cpp
    engines/ags/shared/ac/mousecursor.cpp
    engines/ags/shared/ac/spritecache.cpp
    engines/ags/shared/ac/view.cpp
    engines/ags/shared/ac/wordsdictionary.cpp
    engines/ags/shared/core/asset.cpp
    engines/ags/shared/core/assetmanager.cpp
    engines/ags/shared/debugging/debugmanager.cpp
    engines/ags/shared/font/fonts.cpp
    engines/ags/shared/font/ttffontrenderer.cpp
    engines/ags/shared/font/wfnfont.cpp
    engines/ags/shared/font/wfnfontrenderer.cpp
    engines/ags/shared/game/customproperties.cpp
    engines/ags/shared/game/interactions.cpp
    engines/ags/shared/game/main_game_file.cpp
    engines/ags/shared/game/room_file.cpp
    engines/ags/shared/game/room_file_deprecated.cpp
    engines/ags/shared/game/roomstruct.cpp
    engines/ags/shared/gfx/allegrobitmap.cpp
    engines/ags/shared/gfx/bitmap.cpp
    engines/ags/shared/gui/guibutton.cpp
    engines/ags/shared/gui/guiinv.cpp
    engines/ags/shared/gui/guilabel.cpp
    engines/ags/shared/gui/guilistbox.cpp
    engines/ags/shared/gui/guimain.cpp
    engines/ags/shared/gui/guiobject.cpp
    engines/ags/shared/gui/guislider.cpp
    engines/ags/shared/gui/guitextbox.cpp
    engines/ags/shared/script/cc_error.cpp
    engines/ags/shared/script/cc_options.cpp
    engines/ags/shared/script/cc_script.cpp
    engines/ags/shared/util/alignedstream.cpp
    engines/ags/shared/util/bufferedstream.cpp
    engines/ags/shared/util/compress.cpp
    engines/ags/shared/util/datastream.cpp
    engines/ags/shared/util/directory.cpp
    engines/ags/shared/util/file.cpp
    engines/ags/shared/util/filestream.cpp
    engines/ags/shared/util/geometry.cpp
    engines/ags/shared/util/ini_util.cpp
    engines/ags/shared/util/inifile.cpp
    engines/ags/shared/util/lzw.cpp
    engines/ags/shared/util/misc.cpp
    engines/ags/shared/util/mutifilelib.cpp
    engines/ags/shared/util/path.cpp
    engines/ags/shared/util/proxystream.cpp
    engines/ags/shared/util/stream.cpp
    engines/ags/shared/util/string.cpp
    engines/ags/shared/util/string_utils.cpp
    engines/ags/shared/util/textstreamreader.cpp
    engines/ags/shared/util/textstreamwriter.cpp
    engines/ags/shared/util/version.cpp
    engines/ags/shared/util/wgt2allg.cpp


diff --git a/engines/ags/engine/ac/audiochannel.cpp b/engines/ags/engine/ac/audiochannel.cpp
index e793a87cf6..5d41da4340 100644
--- a/engines/ags/engine/ac/audiochannel.cpp
+++ b/engines/ags/engine/ac/audiochannel.cpp
@@ -29,6 +29,8 @@
 #include "script/runtimescriptvalue.h"
 #include "media/audio/audio_system.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern GameState play;
@@ -278,23 +280,23 @@ RuntimeScriptValue Sc_AudioChannel_SetSpeed(void *self, const RuntimeScriptValue
 }
 
 void RegisterAudioChannelAPI() {
-	ccAddExternalObjectFunction("AudioChannel::Seek^1",             Sc_AudioChannel_Seek);
-	ccAddExternalObjectFunction("AudioChannel::SetRoomLocation^2",  Sc_AudioChannel_SetRoomLocation);
-	ccAddExternalObjectFunction("AudioChannel::Stop^0",             Sc_AudioChannel_Stop);
-	ccAddExternalObjectFunction("AudioChannel::get_ID",             Sc_AudioChannel_GetID);
-	ccAddExternalObjectFunction("AudioChannel::get_IsPlaying",      Sc_AudioChannel_GetIsPlaying);
-	ccAddExternalObjectFunction("AudioChannel::get_LengthMs",       Sc_AudioChannel_GetLengthMs);
-	ccAddExternalObjectFunction("AudioChannel::get_Panning",        Sc_AudioChannel_GetPanning);
-	ccAddExternalObjectFunction("AudioChannel::set_Panning",        Sc_AudioChannel_SetPanning);
-	ccAddExternalObjectFunction("AudioChannel::get_PlayingClip",    Sc_AudioChannel_GetPlayingClip);
-	ccAddExternalObjectFunction("AudioChannel::get_Position",       Sc_AudioChannel_GetPosition);
-	ccAddExternalObjectFunction("AudioChannel::get_PositionMs",     Sc_AudioChannel_GetPositionMs);
-	ccAddExternalObjectFunction("AudioChannel::get_Volume",         Sc_AudioChannel_GetVolume);
-	ccAddExternalObjectFunction("AudioChannel::set_Volume",         Sc_AudioChannel_SetVolume);
-	ccAddExternalObjectFunction("AudioChannel::get_Speed",          Sc_AudioChannel_GetSpeed);
-	ccAddExternalObjectFunction("AudioChannel::set_Speed",          Sc_AudioChannel_SetSpeed);
+	ccAddExternalObjectFunction("AudioChannel::Seek^1", Sc_AudioChannel_Seek);
+	ccAddExternalObjectFunction("AudioChannel::SetRoomLocation^2", Sc_AudioChannel_SetRoomLocation);
+	ccAddExternalObjectFunction("AudioChannel::Stop^0", Sc_AudioChannel_Stop);
+	ccAddExternalObjectFunction("AudioChannel::get_ID", Sc_AudioChannel_GetID);
+	ccAddExternalObjectFunction("AudioChannel::get_IsPlaying", Sc_AudioChannel_GetIsPlaying);
+	ccAddExternalObjectFunction("AudioChannel::get_LengthMs", Sc_AudioChannel_GetLengthMs);
+	ccAddExternalObjectFunction("AudioChannel::get_Panning", Sc_AudioChannel_GetPanning);
+	ccAddExternalObjectFunction("AudioChannel::set_Panning", Sc_AudioChannel_SetPanning);
+	ccAddExternalObjectFunction("AudioChannel::get_PlayingClip", Sc_AudioChannel_GetPlayingClip);
+	ccAddExternalObjectFunction("AudioChannel::get_Position", Sc_AudioChannel_GetPosition);
+	ccAddExternalObjectFunction("AudioChannel::get_PositionMs", Sc_AudioChannel_GetPositionMs);
+	ccAddExternalObjectFunction("AudioChannel::get_Volume", Sc_AudioChannel_GetVolume);
+	ccAddExternalObjectFunction("AudioChannel::set_Volume", Sc_AudioChannel_SetVolume);
+	ccAddExternalObjectFunction("AudioChannel::get_Speed", Sc_AudioChannel_GetSpeed);
+	ccAddExternalObjectFunction("AudioChannel::set_Speed", Sc_AudioChannel_SetSpeed);
 	// For compatibility with  Ahmet Kamil's (aka Gord10) custom engine
-	ccAddExternalObjectFunction("AudioChannel::SetSpeed^1",         Sc_AudioChannel_SetSpeed);
+	ccAddExternalObjectFunction("AudioChannel::SetSpeed^1", Sc_AudioChannel_SetSpeed);
 
 	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
 
@@ -312,3 +314,5 @@ void RegisterAudioChannelAPI() {
 	ccAddExternalFunctionForPlugin("AudioChannel::get_Volume", (void *)AudioChannel_GetVolume);
 	ccAddExternalFunctionForPlugin("AudioChannel::set_Volume", (void *)AudioChannel_SetVolume);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/audioclip.cpp b/engines/ags/engine/ac/audioclip.cpp
index 2653c3aa26..993b72b1c6 100644
--- a/engines/ags/engine/ac/audioclip.cpp
+++ b/engines/ags/engine/ac/audioclip.cpp
@@ -28,6 +28,8 @@
 #include "ac/dynobj/cc_audiochannel.h"
 #include "media/audio/audio_system.h"
 
+namespace AGS3 {
+
 extern GameSetupStruct game;
 extern ScriptAudioChannel scrAudioChannel[MAX_SOUND_CHANNELS + 1];
 extern CCAudioChannel ccDynamicAudio;
@@ -122,14 +124,14 @@ RuntimeScriptValue Sc_AudioClip_PlayQueued(void *self, const RuntimeScriptValue
 }
 
 void RegisterAudioClipAPI() {
-	ccAddExternalObjectFunction("AudioClip::Play^2",            Sc_AudioClip_Play);
-	ccAddExternalObjectFunction("AudioClip::PlayFrom^3",        Sc_AudioClip_PlayFrom);
-	ccAddExternalObjectFunction("AudioClip::PlayQueued^2",      Sc_AudioClip_PlayQueued);
-	ccAddExternalObjectFunction("AudioClip::Stop^0",            Sc_AudioClip_Stop);
-	ccAddExternalObjectFunction("AudioClip::get_ID",            Sc_AudioClip_GetID);
-	ccAddExternalObjectFunction("AudioClip::get_FileType",      Sc_AudioClip_GetFileType);
-	ccAddExternalObjectFunction("AudioClip::get_IsAvailable",   Sc_AudioClip_GetIsAvailable);
-	ccAddExternalObjectFunction("AudioClip::get_Type",          Sc_AudioClip_GetType);
+	ccAddExternalObjectFunction("AudioClip::Play^2", Sc_AudioClip_Play);
+	ccAddExternalObjectFunction("AudioClip::PlayFrom^3", Sc_AudioClip_PlayFrom);
+	ccAddExternalObjectFunction("AudioClip::PlayQueued^2", Sc_AudioClip_PlayQueued);
+	ccAddExternalObjectFunction("AudioClip::Stop^0", Sc_AudioClip_Stop);
+	ccAddExternalObjectFunction("AudioClip::get_ID", Sc_AudioClip_GetID);
+	ccAddExternalObjectFunction("AudioClip::get_FileType", Sc_AudioClip_GetFileType);
+	ccAddExternalObjectFunction("AudioClip::get_IsAvailable", Sc_AudioClip_GetIsAvailable);
+	ccAddExternalObjectFunction("AudioClip::get_Type", Sc_AudioClip_GetType);
 
 	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
 
@@ -141,3 +143,5 @@ void RegisterAudioClipAPI() {
 	ccAddExternalFunctionForPlugin("AudioClip::get_IsAvailable", (void *)AudioClip_GetIsAvailable);
 	ccAddExternalFunctionForPlugin("AudioClip::get_Type", (void *)AudioClip_GetType);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/button.cpp b/engines/ags/engine/ac/button.cpp
index 91f24fa8c6..469414fbeb 100644
--- a/engines/ags/engine/ac/button.cpp
+++ b/engines/ags/engine/ac/button.cpp
@@ -32,6 +32,8 @@
 #include "gui/animatingguibutton.h"
 #include "gui/guimain.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern GameSetupStruct game;
@@ -213,7 +215,7 @@ int UpdateAnimatingButton(int bu) {
 			animbuts[bu].frame = 0;
 			// multi-loop anim, go back
 			while ((animbuts[bu].loop > 0) &&
-			        (tview->loops[animbuts[bu].loop - 1].RunNextLoop()))
+				(tview->loops[animbuts[bu].loop - 1].RunNextLoop()))
 				animbuts[bu].loop--;
 		} else
 			return 1;
@@ -420,31 +422,31 @@ RuntimeScriptValue Sc_Button_GetView(void *self, const RuntimeScriptValue *param
 }
 
 void RegisterButtonAPI() {
-	ccAddExternalObjectFunction("Button::Animate^4",            Sc_Button_Animate);
-	ccAddExternalObjectFunction("Button::Click^1",              Sc_Button_Click);
-	ccAddExternalObjectFunction("Button::GetText^1",            Sc_Button_GetText);
-	ccAddExternalObjectFunction("Button::SetText^1",            Sc_Button_SetText);
-	ccAddExternalObjectFunction("Button::get_TextAlignment",    Sc_Button_GetTextAlignment);
-	ccAddExternalObjectFunction("Button::set_TextAlignment",    Sc_Button_SetTextAlignment);
-	ccAddExternalObjectFunction("Button::get_Animating",        Sc_Button_GetAnimating);
-	ccAddExternalObjectFunction("Button::get_ClipImage",        Sc_Button_GetClipImage);
-	ccAddExternalObjectFunction("Button::set_ClipImage",        Sc_Button_SetClipImage);
-	ccAddExternalObjectFunction("Button::get_Font",             Sc_Button_GetFont);
-	ccAddExternalObjectFunction("Button::set_Font",             Sc_Button_SetFont);
-	ccAddExternalObjectFunction("Button::get_Frame",            Sc_Button_GetFrame);
-	ccAddExternalObjectFunction("Button::get_Graphic",          Sc_Button_GetGraphic);
-	ccAddExternalObjectFunction("Button::get_Loop",             Sc_Button_GetLoop);
+	ccAddExternalObjectFunction("Button::Animate^4", Sc_Button_Animate);
+	ccAddExternalObjectFunction("Button::Click^1", Sc_Button_Click);
+	ccAddExternalObjectFunction("Button::GetText^1", Sc_Button_GetText);
+	ccAddExternalObjectFunction("Button::SetText^1", Sc_Button_SetText);
+	ccAddExternalObjectFunction("Button::get_TextAlignment", Sc_Button_GetTextAlignment);
+	ccAddExternalObjectFunction("Button::set_TextAlignment", Sc_Button_SetTextAlignment);
+	ccAddExternalObjectFunction("Button::get_Animating", Sc_Button_GetAnimating);
+	ccAddExternalObjectFunction("Button::get_ClipImage", Sc_Button_GetClipImage);
+	ccAddExternalObjectFunction("Button::set_ClipImage", Sc_Button_SetClipImage);
+	ccAddExternalObjectFunction("Button::get_Font", Sc_Button_GetFont);
+	ccAddExternalObjectFunction("Button::set_Font", Sc_Button_SetFont);
+	ccAddExternalObjectFunction("Button::get_Frame", Sc_Button_GetFrame);
+	ccAddExternalObjectFunction("Button::get_Graphic", Sc_Button_GetGraphic);
+	ccAddExternalObjectFunction("Button::get_Loop", Sc_Button_GetLoop);
 	ccAddExternalObjectFunction("Button::get_MouseOverGraphic", Sc_Button_GetMouseOverGraphic);
 	ccAddExternalObjectFunction("Button::set_MouseOverGraphic", Sc_Button_SetMouseOverGraphic);
-	ccAddExternalObjectFunction("Button::get_NormalGraphic",    Sc_Button_GetNormalGraphic);
-	ccAddExternalObjectFunction("Button::set_NormalGraphic",    Sc_Button_SetNormalGraphic);
-	ccAddExternalObjectFunction("Button::get_PushedGraphic",    Sc_Button_GetPushedGraphic);
-	ccAddExternalObjectFunction("Button::set_PushedGraphic",    Sc_Button_SetPushedGraphic);
-	ccAddExternalObjectFunction("Button::get_Text",             Sc_Button_GetText_New);
-	ccAddExternalObjectFunction("Button::set_Text",             Sc_Button_SetText);
-	ccAddExternalObjectFunction("Button::get_TextColor",        Sc_Button_GetTextColor);
-	ccAddExternalObjectFunction("Button::set_TextColor",        Sc_Button_SetTextColor);
-	ccAddExternalObjectFunction("Button::get_View",             Sc_Button_GetView);
+	ccAddExternalObjectFunction("Button::get_NormalGraphic", Sc_Button_GetNormalGraphic);
+	ccAddExternalObjectFunction("Button::set_NormalGraphic", Sc_Button_SetNormalGraphic);
+	ccAddExternalObjectFunction("Button::get_PushedGraphic", Sc_Button_GetPushedGraphic);
+	ccAddExternalObjectFunction("Button::set_PushedGraphic", Sc_Button_SetPushedGraphic);
+	ccAddExternalObjectFunction("Button::get_Text", Sc_Button_GetText_New);
+	ccAddExternalObjectFunction("Button::set_Text", Sc_Button_SetText);
+	ccAddExternalObjectFunction("Button::get_TextColor", Sc_Button_GetTextColor);
+	ccAddExternalObjectFunction("Button::set_TextColor", Sc_Button_SetTextColor);
+	ccAddExternalObjectFunction("Button::get_View", Sc_Button_GetView);
 
 	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
 
@@ -467,3 +469,5 @@ void RegisterButtonAPI() {
 	ccAddExternalFunctionForPlugin("Button::get_TextColor", (void *)Button_GetTextColor);
 	ccAddExternalFunctionForPlugin("Button::set_TextColor", (void *)Button_SetTextColor);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/cdaudio.cpp b/engines/ags/engine/ac/cdaudio.cpp
index 99294b49a2..04feb2c3bc 100644
--- a/engines/ags/engine/ac/cdaudio.cpp
+++ b/engines/ags/engine/ac/cdaudio.cpp
@@ -23,6 +23,8 @@
 #include "ac/cdaudio.h"
 #include "platform/base/agsplatformdriver.h"
 
+namespace AGS3 {
+
 int use_cdplayer = 0;
 bool triedToUseCdAudioCommand = false;
 int need_to_stop_cd = 0;
@@ -42,3 +44,5 @@ int cd_manager(int cmdd, int datt) {
 
 	return platform->CDPlayerCommand(cmdd, datt);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/character.cpp b/engines/ags/engine/ac/character.cpp
index d1ef4162f6..34890ee440 100644
--- a/engines/ags/engine/ac/character.cpp
+++ b/engines/ags/engine/ac/character.cpp
@@ -71,6 +71,8 @@
 #include "media/audio/audio_system.h"
 #include "ac/movelist.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern GameSetupStruct game;
@@ -3867,3 +3869,5 @@ void RegisterCharacterAPI(ScriptAPIVersion base_api, ScriptAPIVersion compat_api
 	ccAddExternalFunctionForPlugin("Character::get_z", (void *)Character_GetZ);
 	ccAddExternalFunctionForPlugin("Character::set_z", (void *)Character_SetZ);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/characterextras.cpp b/engines/ags/engine/ac/characterextras.cpp
index 42c48cb39c..6915dca2bc 100644
--- a/engines/ags/engine/ac/characterextras.cpp
+++ b/engines/ags/engine/ac/characterextras.cpp
@@ -23,6 +23,8 @@
 #include "ac/characterextras.h"
 #include "util/stream.h"
 
+namespace AGS3 {
+
 using AGS::Shared::Stream;
 
 void CharacterExtras::ReadFromFile(Stream *in) {
@@ -60,3 +62,5 @@ void CharacterExtras::WriteToFile(Stream *out) {
 	out->WriteInt8(slow_move_counter);
 	out->WriteInt16(animwait);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/characterinfo_engine.cpp b/engines/ags/engine/ac/characterinfo_engine.cpp
index d404c382a8..e9e2bcff84 100644
--- a/engines/ags/engine/ac/characterinfo_engine.cpp
+++ b/engines/ags/engine/ac/characterinfo_engine.cpp
@@ -35,6 +35,8 @@
 #include "main/update.h"
 #include "media/audio/audio_system.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern ViewStruct *views;
@@ -81,7 +83,7 @@ void CharacterInfo::UpdateMoveAndAnim(int &char_index, CharacterExtras *chex, in
 	}
 
 	// Make sure it doesn't flash up a blue cup
-	if (view < 0) ;
+	if (view < 0);
 	else if (loop >= views[view].numLoops)
 		loop = 0;
 
@@ -135,8 +137,8 @@ int CharacterInfo::update_character_walking(CharacterExtras *chex) {
 				if (wantloop < 0)
 					wantloop = 7;
 				if ((turnlooporder[wantloop] >= views[view].numLoops) ||
-				        (views[view].loops[turnlooporder[wantloop]].numFrames < 1) ||
-				        ((turnlooporder[wantloop] >= 4) && ((flags & CHF_NODIAGONAL) != 0))) {
+					(views[view].loops[turnlooporder[wantloop]].numFrames < 1) ||
+					((turnlooporder[wantloop] >= 4) && ((flags & CHF_NODIAGONAL) != 0))) {
 					if (walking >= TURNING_BACKWARDS)
 						wantloop--;
 					else
@@ -190,8 +192,8 @@ void CharacterInfo::update_character_moving(int &char_index, CharacterExtras *ch
 				// to stop it being jumpy
 				chex->xwas = x;
 				chex->ywas = y;
-				x = ((x) - oldxp) / 2 + oldxp;
-				y = ((y) - oldyp) / 2 + oldyp;
+				x = ((x)-oldxp) / 2 + oldxp;
+				y = ((y)-oldyp) / 2 + oldyp;
 			} else if (numSteps > 0)
 				chex->xwas = INVALID_X;
 
@@ -256,8 +258,8 @@ int CharacterInfo::update_character_animating(int &aa, int &doing_nothing) {
 	// not moving, but animating
 	// idleleft is <0 while idle view is playing (.animating is 0)
 	if (((animating != 0) || (idleleft < 0)) &&
-	        ((walking == 0) || ((flags & CHF_MOVENOTWALK) != 0)) &&
-	        (room == displayed_room)) {
+		((walking == 0) || ((flags & CHF_MOVENOTWALK) != 0)) &&
+		(room == displayed_room)) {
 		doing_nothing = 0;
 		// idle anim doesn't count as doing something
 		if (idleleft < 0)
@@ -271,7 +273,7 @@ int CharacterInfo::update_character_animating(int &aa, int &doing_nothing) {
 			// closed mouth at end of sentence
 			// NOTE: standard lip-sync is synchronized with text timer, not voice file
 			if (play.speech_in_post_state ||
-			        ((play.messagetime >= 0) && (play.messagetime < play.close_mouth_speech_time)))
+				((play.messagetime >= 0) && (play.messagetime < play.close_mouth_speech_time)))
 				frame = 0;
 
 			if (frame != fraa) {
@@ -288,9 +290,9 @@ int CharacterInfo::update_character_animating(int &aa, int &doing_nothing) {
 				if (frame < 0) {
 					// if the previous loop is a Run Next Loop one, go back to it
 					if ((loop > 0) &&
-					        (views[view].loops[loop - 1].RunNextLoop())) {
+						(views[view].loops[loop - 1].RunNextLoop())) {
 
-						loop --;
+						loop--;
 						frame = views[view].loops[loop].numFrames - 1;
 					} else if (animating & CHANIM_REPEAT) {
 
@@ -309,10 +311,10 @@ int CharacterInfo::update_character_animating(int &aa, int &doing_nothing) {
 				frame++;
 
 			if ((aa == char_speaking) &&
-			        (play.speech_in_post_state ||
-			         ((!play.speech_has_voice) &&
-			          (play.close_mouth_speech_time > 0) &&
-			          (play.messagetime < play.close_mouth_speech_time)))) {
+				(play.speech_in_post_state ||
+				((!play.speech_has_voice) &&
+					(play.close_mouth_speech_time > 0) &&
+					(play.messagetime < play.close_mouth_speech_time)))) {
 				// finished talking - stop animation
 				animating = 0;
 				frame = 0;
@@ -344,7 +346,7 @@ int CharacterInfo::update_character_animating(int &aa, int &doing_nothing) {
 					// if it's a multi-loop animation, go back to start
 					if (play.no_multiloop_repeat == 0) {
 						while ((loop > 0) &&
-						        (views[view].loops[loop - 1].RunNextLoop()))
+							(views[view].loops[loop - 1].RunNextLoop()))
 							loop--;
 					}
 				}
@@ -376,9 +378,9 @@ void CharacterInfo::update_character_follower(int &aa, int &numSheep, int *follo
 	else if ((following >= 0) && (doing_nothing == 1)) {
 		short distaway = (followinfo >> 8) & 0x00ff;
 		// no character in this room
-		if ((game.chars[following].on == 0) || (on == 0)) ;
+		if ((game.chars[following].on == 0) || (on == 0));
 		else if (room < 0) {
-			room ++;
+			room++;
 			if (room == 0) {
 				// appear in the new room
 				room = game.chars[following].room;
@@ -387,10 +389,10 @@ void CharacterInfo::update_character_follower(int &aa, int &numSheep, int *follo
 			}
 		}
 		// wait a bit, so we're not constantly walking
-		else if (Random(100) < (followinfo & 0x00ff)) ;
+		else if (Random(100) < (followinfo & 0x00ff));
 		// the followed character has changed room
 		else if ((room != game.chars[following].room)
-		         && (game.chars[following].on == 0))
+			&& (game.chars[following].on == 0))
 			;  // do nothing if the player isn't visible
 		else if (room != game.chars[following].room) {
 			prevroom = room;
@@ -425,15 +427,15 @@ void CharacterInfo::update_character_follower(int &aa, int &numSheep, int *follo
 			// if the characetr is following another character and
 			// neither is in the current room, don't try to move
 		} else if ((abs(game.chars[following].x - x) > distaway + 30) |
-		           (abs(game.chars[following].y - y) > distaway + 30) |
-		           ((followinfo & 0x00ff) == 0)) {
+			(abs(game.chars[following].y - y) > distaway + 30) |
+			((followinfo & 0x00ff) == 0)) {
 			// in same room
 			int goxoffs = (Random(50) - 25);
 			// make sure he's not standing on top of the other man
 			if (goxoffs < 0) goxoffs -= distaway;
 			else goxoffs += distaway;
 			walk_character(aa, game.chars[following].x + goxoffs,
-			               game.chars[following].y + (Random(50) - 25), 0, true);
+				game.chars[following].y + (Random(50) - 25), 0, true);
 			doing_nothing = 0;
 		}
 	}
@@ -441,11 +443,11 @@ void CharacterInfo::update_character_follower(int &aa, int &numSheep, int *follo
 
 void CharacterInfo::update_character_idle(CharacterExtras *chex, int &doing_nothing) {
 	// no idle animation, so skip this bit
-	if (idleview < 1) ;
+	if (idleview < 1);
 	// currently playing idle anim
-	else if (idleleft < 0) ;
+	else if (idleleft < 0);
 	// not in the current room
-	else if (room != displayed_room) ;
+	else if (room != displayed_room);
 	// they are moving or animating (or the view is locked), so
 	// reset idle timeout
 	else if ((doing_nothing == 0) || ((flags & CHF_FIXVIEW) != 0))
@@ -478,10 +480,12 @@ void CharacterInfo::update_character_idle(CharacterExtras *chex, int &doing_noth
 				useloop = 0;
 
 			animate_character(this, useloop,
-			                  animspeed + 5, (idletime == 0) ? 1 : 0, 1);
+				animspeed + 5, (idletime == 0) ? 1 : 0, 1);
 
 			// don't set Animating while the idle anim plays
 			animating = 0;
 		}
 	}  // end do idle animation
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/datetime.cpp b/engines/ags/engine/ac/datetime.cpp
index a4874cb45d..9821802720 100644
--- a/engines/ags/engine/ac/datetime.cpp
+++ b/engines/ags/engine/ac/datetime.cpp
@@ -25,6 +25,8 @@
 #include "platform/base/agsplatformdriver.h"
 #include "script/runtimescriptvalue.h"
 
+namespace AGS3 {
+
 ScriptDateTime *DateTime_Now_Core() {
 	ScriptDateTime *sdt = new ScriptDateTime();
 
@@ -118,14 +120,14 @@ RuntimeScriptValue Sc_DateTime_GetRawTime(void *self, const RuntimeScriptValue *
 }
 
 void RegisterDateTimeAPI() {
-	ccAddExternalStaticFunction("DateTime::get_Now",        Sc_DateTime_Now);
+	ccAddExternalStaticFunction("DateTime::get_Now", Sc_DateTime_Now);
 	ccAddExternalObjectFunction("DateTime::get_DayOfMonth", Sc_DateTime_GetDayOfMonth);
-	ccAddExternalObjectFunction("DateTime::get_Hour",       Sc_DateTime_GetHour);
-	ccAddExternalObjectFunction("DateTime::get_Minute",     Sc_DateTime_GetMinute);
-	ccAddExternalObjectFunction("DateTime::get_Month",      Sc_DateTime_GetMonth);
-	ccAddExternalObjectFunction("DateTime::get_RawTime",    Sc_DateTime_GetRawTime);
-	ccAddExternalObjectFunction("DateTime::get_Second",     Sc_DateTime_GetSecond);
-	ccAddExternalObjectFunction("DateTime::get_Year",       Sc_DateTime_GetYear);
+	ccAddExternalObjectFunction("DateTime::get_Hour", Sc_DateTime_GetHour);
+	ccAddExternalObjectFunction("DateTime::get_Minute", Sc_DateTime_GetMinute);
+	ccAddExternalObjectFunction("DateTime::get_Month", Sc_DateTime_GetMonth);
+	ccAddExternalObjectFunction("DateTime::get_RawTime", Sc_DateTime_GetRawTime);
+	ccAddExternalObjectFunction("DateTime::get_Second", Sc_DateTime_GetSecond);
+	ccAddExternalObjectFunction("DateTime::get_Year", Sc_DateTime_GetYear);
 
 	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
 
@@ -138,3 +140,5 @@ void RegisterDateTimeAPI() {
 	ccAddExternalFunctionForPlugin("DateTime::get_Second", (void *)DateTime_GetSecond);
 	ccAddExternalFunctionForPlugin("DateTime::get_Year", (void *)DateTime_GetYear);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dialog.cpp b/engines/ags/engine/ac/dialog.cpp
index c5f60cc601..6d1f3e98b0 100644
--- a/engines/ags/engine/ac/dialog.cpp
+++ b/engines/ags/engine/ac/dialog.cpp
@@ -60,6 +60,8 @@
 #include "ac/mouse.h"
 #include "media/audio/audio_system.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern GameSetupStruct game;
@@ -1226,3 +1228,5 @@ void RegisterDialogAPI() {
 	ccAddExternalFunctionForPlugin("Dialog::SetOptionState^2", (void *)Dialog_SetOptionState);
 	ccAddExternalFunctionForPlugin("Dialog::Start^0", (void *)Dialog_Start);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dialogoptionsrendering.cpp b/engines/ags/engine/ac/dialogoptionsrendering.cpp
index 499ed2104f..39b2b2c466 100644
--- a/engines/ags/engine/ac/dialogoptionsrendering.cpp
+++ b/engines/ags/engine/ac/dialogoptionsrendering.cpp
@@ -28,6 +28,8 @@
 #include "script/runtimescriptvalue.h"
 #include "ac/dynobj/cc_dialog.h"
 
+namespace AGS3 {
+
 extern DialogTopic *dialog;
 extern CCDialog ccDynamicDialog;
 
@@ -248,28 +250,28 @@ RuntimeScriptValue Sc_DialogOptionsRendering_SetHasAlphaChannel(void *self, cons
 
 
 void RegisterDialogOptionsRenderingAPI() {
-	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::Update^0",             Sc_DialogOptionsRendering_Update);
-	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::RunActiveOption^0",    Sc_DialogOptionsRendering_RunActiveOption);
-	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_ActiveOptionID",   Sc_DialogOptionsRendering_GetActiveOptionID);
-	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::set_ActiveOptionID",   Sc_DialogOptionsRendering_SetActiveOptionID);
-	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_DialogToRender",   Sc_DialogOptionsRendering_GetDialogToRender);
-	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_Height",           Sc_DialogOptionsRendering_GetHeight);
-	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::set_Height",           Sc_DialogOptionsRendering_SetHeight);
-	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_ParserTextBoxX",   Sc_DialogOptionsRendering_GetParserTextboxX);
-	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::set_ParserTextBoxX",   Sc_DialogOptionsRendering_SetParserTextboxX);
-	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_ParserTextBoxY",   Sc_DialogOptionsRendering_GetParserTextboxY);
-	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::set_ParserTextBoxY",   Sc_DialogOptionsRendering_SetParserTextboxY);
+	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::Update^0", Sc_DialogOptionsRendering_Update);
+	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::RunActiveOption^0", Sc_DialogOptionsRendering_RunActiveOption);
+	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_ActiveOptionID", Sc_DialogOptionsRendering_GetActiveOptionID);
+	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::set_ActiveOptionID", Sc_DialogOptionsRendering_SetActiveOptionID);
+	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_DialogToRender", Sc_DialogOptionsRendering_GetDialogToRender);
+	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_Height", Sc_DialogOptionsRendering_GetHeight);
+	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::set_Height", Sc_DialogOptionsRendering_SetHeight);
+	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_ParserTextBoxX", Sc_DialogOptionsRendering_GetParserTextboxX);
+	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::set_ParserTextBoxX", Sc_DialogOptionsRendering_SetParserTextboxX);
+	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_ParserTextBoxY", Sc_DialogOptionsRendering_GetParserTextboxY);
+	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::set_ParserTextBoxY", Sc_DialogOptionsRendering_SetParserTextboxY);
 	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_ParserTextBoxWidth", Sc_DialogOptionsRendering_GetParserTextboxWidth);
 	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::set_ParserTextBoxWidth", Sc_DialogOptionsRendering_SetParserTextboxWidth);
-	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_Surface",          Sc_DialogOptionsRendering_GetSurface);
-	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_Width",            Sc_DialogOptionsRendering_GetWidth);
-	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::set_Width",            Sc_DialogOptionsRendering_SetWidth);
-	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_X",                Sc_DialogOptionsRendering_GetX);
-	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::set_X",                Sc_DialogOptionsRendering_SetX);
-	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_Y",                Sc_DialogOptionsRendering_GetY);
-	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::set_Y",                Sc_DialogOptionsRendering_SetY);
-	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_HasAlphaChannel",  Sc_DialogOptionsRendering_GetHasAlphaChannel);
-	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::set_HasAlphaChannel",  Sc_DialogOptionsRendering_SetHasAlphaChannel);
+	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_Surface", Sc_DialogOptionsRendering_GetSurface);
+	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_Width", Sc_DialogOptionsRendering_GetWidth);
+	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::set_Width", Sc_DialogOptionsRendering_SetWidth);
+	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_X", Sc_DialogOptionsRendering_GetX);
+	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::set_X", Sc_DialogOptionsRendering_SetX);
+	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_Y", Sc_DialogOptionsRendering_GetY);
+	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::set_Y", Sc_DialogOptionsRendering_SetY);
+	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::get_HasAlphaChannel", Sc_DialogOptionsRendering_GetHasAlphaChannel);
+	ccAddExternalObjectFunction("DialogOptionsRenderingInfo::set_HasAlphaChannel", Sc_DialogOptionsRendering_SetHasAlphaChannel);
 
 	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
 
@@ -292,3 +294,5 @@ void RegisterDialogOptionsRenderingAPI() {
 	ccAddExternalFunctionForPlugin("DialogOptionsRenderingInfo::get_Y", (void *)DialogOptionsRendering_GetY);
 	ccAddExternalFunctionForPlugin("DialogOptionsRenderingInfo::set_Y", (void *)DialogOptionsRendering_SetY);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/display.cpp b/engines/ags/engine/ac/display.cpp
index 20255b1e92..017c573034 100644
--- a/engines/ags/engine/ac/display.cpp
+++ b/engines/ags/engine/ac/display.cpp
@@ -55,6 +55,8 @@
 #include "media/audio/audio_system.h"
 #include "ac/timer.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Shared::BitmapHelper;
 
@@ -134,7 +136,7 @@ int _display_main(int xx, int yy, int wii, const char *text, int disp_type, int
 	}
 
 	const Rect &ui_view = play.GetUIViewport();
-	if (xx == OVR_AUTOPLACE) ;
+	if (xx == OVR_AUTOPLACE);
 	// centre text in middle of screen
 	else if (yy < 0) yy = ui_view.GetHeight() / 2 - disp.fulltxtheight / 2 - padding;
 	// speech, so it wants to be above the character's head
@@ -185,7 +187,7 @@ int _display_main(int xx, int yy, int wii, const char *text, int disp_type, int
 	int adjustedXX = xx;
 	int adjustedYY = yy;
 
-	if ((strlen(todis) < 1) || (strcmp(todis, "  ") == 0) || (wii == 0)) ;
+	if ((strlen(todis) < 1) || (strcmp(todis, "  ") == 0) || (wii == 0));
 	// if it's an empty speech line, don't draw anything
 	else if (asspch) { //text_color = ds->GetCompatibleColor(12);
 		int ttxleft = 0, ttxtop = paddingScaled, oriwid = wii - padding * 2;
@@ -215,7 +217,7 @@ int _display_main(int xx, int yy, int wii, const char *text, int disp_type, int
 			// centre the text
 			if (asspch < 0) {
 				if ((usingGui >= 0) &&
-				        ((game.options[OPT_SPEECHTYPE] >= 2) || (isThought)))
+					((game.options[OPT_SPEECHTYPE] >= 2) || (isThought)))
 					text_color = text_window_ds->GetCompatibleColor(guis[usingGui].FgColor);
 				else
 					text_color = text_window_ds->GetCompatibleColor(-asspch);
@@ -451,10 +453,10 @@ void wouttextxy_AutoOutline_Semitransparent2Opaque(Bitmap *map) {
 			int const transparency = geta(px);
 			if (0 < transparency && transparency < 255)
 				px = makeacol32(
-				         getr32(px),
-				         getg32(px),
-				         getb32(px),
-				         std::min(85 + transparency * 2, 255));
+					getr32(px),
+					getg32(px),
+					getb32(px),
+					std::min(85 + transparency * 2, 255));
 		}
 	}
 }
@@ -488,7 +490,7 @@ void wouttextxy_AutoOutline(Bitmap *ds, size_t font, int32_t color, const char *
 	wouttextxy_AutoOutline_Semitransparent2Opaque(texx_stencil);
 #endif
 
-	void(Bitmap::*pfn_drawstencil)(Bitmap * src, int dst_x, int dst_y);
+	void(Bitmap:: * pfn_drawstencil)(Bitmap * src, int dst_x, int dst_y);
 	if (antialias) {
 		// NOTE: we must set out blender AFTER wouttextxy, or it will be overidden
 		set_argb2any_blender();
@@ -512,8 +514,8 @@ void wouttextxy_AutoOutline(Bitmap *ds, size_t font, int32_t color, const char *
 
 		// extend the outline stencil to the top and bottom
 		for (int y_diff = largest_y_diff_reached_so_far + 1;
-		        y_diff <= thickness && y_diff * y_diff  <= y_term_limit;
-		        y_diff++) {
+			y_diff <= thickness && y_diff * y_diff <= y_term_limit;
+			y_diff++) {
 			(outline_stencil.*pfn_drawstencil)(&texx_stencil, 0, thickness - y_diff);
 			if (y_diff > 0)
 				(outline_stencil.*pfn_drawstencil)(&texx_stencil, 0, thickness + y_diff);
@@ -568,8 +570,8 @@ int getfontheight_outlined(int font) {
 
 int getfontspacing_outlined(int font) {
 	return use_default_linespacing(font) ?
-	       getfontheight_outlined(font) :
-	       getfontlinespacing(font);
+		getfontheight_outlined(font) :
+		getfontlinespacing(font);
 }
 
 int getfontlinegap(int font) {
@@ -629,9 +631,9 @@ void draw_button_background(Bitmap *ds, int xx1, int yy1, int xx2, int yy2, GUIM
 		int topBottomHeight = game.SpriteInfos[get_but_pic(iep, 6)].Height;
 		if (iep->BgImage > 0) {
 			if ((loaded_game_file_version <= kGameVersion_272) // 2.xx
-			        && (spriteset[iep->BgImage]->GetWidth() == 1)
-			        && (spriteset[iep->BgImage]->GetHeight() == 1)
-			        && (*((unsigned int *)spriteset[iep->BgImage]->GetData()) == 0x00FF00FF)) {
+				&& (spriteset[iep->BgImage]->GetWidth() == 1)
+				&& (spriteset[iep->BgImage]->GetHeight() == 1)
+				&& (*((unsigned int *)spriteset[iep->BgImage]->GetData()) == 0x00FF00FF)) {
 				// Don't draw fully transparent dummy GUI backgrounds
 			} else {
 				// offset the background image and clip it so that it is drawn
@@ -681,7 +683,7 @@ int get_textwindow_border_width(int twgui) {
 		quit("!GUI set as text window but is not actually a text window GUI");
 
 	int borwid = game.SpriteInfos[get_but_pic(&guis[twgui], 4)].Width +
-	             game.SpriteInfos[get_but_pic(&guis[twgui], 5)].Width;
+		game.SpriteInfos[get_but_pic(&guis[twgui], 5)].Width;
 
 	return borwid;
 }
@@ -713,7 +715,7 @@ int get_textwindow_padding(int ifnum) {
 }
 
 void draw_text_window(Bitmap **text_window_ds, bool should_free_ds,
-                      int *xins, int *yins, int *xx, int *yy, int *wii, color_t *set_text_color, int ovrheight, int ifnum) {
+	int *xins, int *yins, int *xx, int *yy, int *wii, color_t *set_text_color, int ovrheight, int ifnum) {
 
 	Bitmap *ds = *text_window_ds;
 	if (ifnum < 0)
@@ -756,7 +758,7 @@ void draw_text_window(Bitmap **text_window_ds, bool should_free_ds,
 }
 
 void draw_text_window_and_bar(Bitmap **text_window_ds, bool should_free_ds,
-                              int *xins, int *yins, int *xx, int *yy, int *wii, color_t *set_text_color, int ovrheight, int ifnum) {
+	int *xins, int *yins, int *xx, int *yy, int *wii, color_t *set_text_color, int ovrheight, int ifnum) {
 
 	draw_text_window(text_window_ds, should_free_ds, xins, yins, xx, yy, wii, set_text_color, ovrheight, ifnum);
 
@@ -792,3 +794,5 @@ void draw_text_window_and_bar(Bitmap **text_window_ds, bool should_free_ds,
 	} else if (topBar.wantIt)
 		topBar.wantIt = 0;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/draw.cpp b/engines/ags/engine/ac/draw.cpp
index b6ed493c2d..374c218ba7 100644
--- a/engines/ags/engine/ac/draw.cpp
+++ b/engines/ags/engine/ac/draw.cpp
@@ -71,6 +71,8 @@
 #include "media/audio/audio_system.h"
 #include "ac/game.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -2333,3 +2335,5 @@ void render_graphics(IDriverDependantBitmap *extraBitmap, int extraX, int extraY
 
 	screen_is_dirty = false;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/draw_software.cpp b/engines/ags/engine/ac/draw_software.cpp
index 46bb1a1298..917b4cd0ea 100644
--- a/engines/ags/engine/ac/draw_software.cpp
+++ b/engines/ags/engine/ac/draw_software.cpp
@@ -52,6 +52,8 @@
 #include "gfx/bitmap.h"
 #include "util/scaling.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -444,3 +446,5 @@ void update_room_invreg_and_reset(int view_index, Bitmap *ds, Bitmap *src, bool
 	update_invalid_region(ds, src, RoomCamRects[view_index], no_transform);
 	RoomCamRects[view_index].Reset();
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/drawingsurface.cpp b/engines/ags/engine/ac/drawingsurface.cpp
index c6a8cfacd2..d4fb8cd14b 100644
--- a/engines/ags/engine/ac/drawingsurface.cpp
+++ b/engines/ags/engine/ac/drawingsurface.cpp
@@ -42,6 +42,8 @@
 #include "gfx/gfx_def.h"
 #include "gfx/gfx_util.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -90,7 +92,7 @@ void DrawingSurface_Release(ScriptDrawingSurface *sds) {
 			}
 			for (tt = 0; tt < game.numgui; tt++) {
 				if ((guis[tt].BgImage == sds->dynamicSpriteNumber) &&
-				        (guis[tt].IsDisplayed())) {
+					(guis[tt].IsDisplayed())) {
 					guis_need_update = 1;
 					break;
 				}
@@ -143,7 +145,7 @@ ScriptDrawingSurface *DrawingSurface_CreateCopy(ScriptDrawingSurface *sds) {
 }
 
 void DrawingSurface_DrawImageImpl(ScriptDrawingSurface *sds, Bitmap *src, int dst_x, int dst_y, int trans, int dst_width, int dst_height,
-                                  int src_x, int src_y, int src_width, int src_height, int sprite_id, bool src_has_alpha) {
+	int src_x, int src_y, int src_width, int src_height, int sprite_id, bool src_has_alpha) {
 	Bitmap *ds = sds->GetBitmapSurface();
 	if (src == ds)
 		quit("!DrawingSurface.DrawImage: cannot draw onto itself");
@@ -186,7 +188,7 @@ void DrawingSurface_DrawImageImpl(ScriptDrawingSurface *sds, Bitmap *src, int ds
 	}
 
 	if (dst_x >= ds->GetWidth() || dst_x + dst_width <= 0 || dst_y >= ds->GetHeight() || dst_y + dst_height <= 0 ||
-	        src_x >= src->GetWidth() || src_x + src_width <= 0 || src_y >= src->GetHeight() || src_y + src_height <= 0)
+		src_x >= src->GetWidth() || src_x + src_width <= 0 || src_y >= src->GetHeight() || src_y + src_height <= 0)
 		return; // source or destination rects lie completely off surface
 	// Clamp the source rect to the valid limits to prevent exceptions (ignore dest, bitmap drawing deals with that)
 	Math::ClampLength(src_x, src_width, 0, src->GetWidth());
@@ -196,12 +198,12 @@ void DrawingSurface_DrawImageImpl(ScriptDrawingSurface *sds, Bitmap *src, int ds
 	// if simplier blit/draw_sprite could be called (no translucency with alpha channel).
 	bool needToFreeBitmap = false;
 	if (dst_width != src->GetWidth() || dst_height != src->GetHeight() ||
-	        src_width != src->GetWidth() || src_height != src->GetHeight()) {
+		src_width != src->GetWidth() || src_height != src->GetHeight()) {
 		// Resize and/or partial copy specified
 		Bitmap *newPic = BitmapHelper::CreateBitmap(dst_width, dst_height, src->GetColorDepth());
 		newPic->StretchBlt(src,
-		                   RectWH(src_x, src_y, src_width, src_height),
-		                   RectWH(0, 0, dst_width, dst_height));
+			RectWH(src_x, src_y, src_width, src_height),
+			RectWH(0, 0, dst_width, dst_height));
 
 		src = newPic;
 		needToFreeBitmap = true;
@@ -219,7 +221,7 @@ void DrawingSurface_DrawImageImpl(ScriptDrawingSurface *sds, Bitmap *src, int ds
 	}
 
 	draw_sprite_support_alpha(ds, sds->hasAlphaChannel != 0, dst_x, dst_y, src, src_has_alpha,
-	                          kBlendMode_Alpha, GfxDef::Trans100ToAlpha255(trans));
+		kBlendMode_Alpha, GfxDef::Trans100ToAlpha255(trans));
 
 	sds->FinishedDrawing();
 
@@ -228,11 +230,11 @@ void DrawingSurface_DrawImageImpl(ScriptDrawingSurface *sds, Bitmap *src, int ds
 }
 
 void DrawingSurface_DrawImageEx(ScriptDrawingSurface *sds, int dst_x, int dst_y, int slot, int trans, int dst_width, int dst_height,
-                                int src_x, int src_y, int src_width, int src_height) {
+	int src_x, int src_y, int src_width, int src_height) {
 	if ((slot < 0) || (spriteset[slot] == nullptr))
 		quit("!DrawingSurface.DrawImage: invalid sprite slot number specified");
 	DrawingSurface_DrawImageImpl(sds, spriteset[slot], dst_x, dst_y, trans, dst_width, dst_height,
-	                             src_x, src_y, src_width, src_height, slot, (game.SpriteInfos[slot].Flags & SPF_ALPHACHANNEL) != 0);
+		src_x, src_y, src_width, src_height, slot, (game.SpriteInfos[slot].Flags & SPF_ALPHACHANNEL) != 0);
 }
 
 void DrawingSurface_DrawImage(ScriptDrawingSurface *sds, int xx, int yy, int slot, int trans, int width, int height) {
@@ -240,10 +242,10 @@ void DrawingSurface_DrawImage(ScriptDrawingSurface *sds, int xx, int yy, int slo
 }
 
 void DrawingSurface_DrawSurfaceEx(ScriptDrawingSurface *target, ScriptDrawingSurface *source, int trans,
-                                  int dst_x, int dst_y, int dst_width, int dst_height,
-                                  int src_x, int src_y, int src_width, int src_height) {
+	int dst_x, int dst_y, int dst_width, int dst_height,
+	int src_x, int src_y, int src_width, int src_height) {
 	DrawingSurface_DrawImageImpl(target, source->GetBitmapSurface(), dst_x, dst_y, trans, dst_width, dst_height,
-	                             src_x, src_y, src_width, src_height, -1, source->hasAlphaChannel);
+		src_x, src_y, src_width, src_height, -1, source->hasAlphaChannel);
 }
 
 void DrawingSurface_DrawSurface(ScriptDrawingSurface *target, ScriptDrawingSurface *source, int trans) {
@@ -472,7 +474,7 @@ RuntimeScriptValue Sc_DrawingSurface_DrawImage_6(void *self, const RuntimeScript
 RuntimeScriptValue Sc_DrawingSurface_DrawImage(void *self, const RuntimeScriptValue *params, int32_t param_count) {
 	ASSERT_OBJ_PARAM_COUNT(METHOD, 10);
 	DrawingSurface_DrawImageEx((ScriptDrawingSurface *)self, params[0].IValue, params[1].IValue, params[2].IValue, params[3].IValue, params[4].IValue, params[5].IValue,
-	                           params[6].IValue, params[7].IValue, params[8].IValue, params[9].IValue);
+		params[6].IValue, params[7].IValue, params[8].IValue, params[9].IValue);
 	return RuntimeScriptValue((int32_t)0);
 }
 
@@ -520,8 +522,8 @@ RuntimeScriptValue Sc_DrawingSurface_DrawSurface_2(void *self, const RuntimeScri
 RuntimeScriptValue Sc_DrawingSurface_DrawSurface(void *self, const RuntimeScriptValue *params, int32_t param_count) {
 	ASSERT_OBJ_PARAM_COUNT(METHOD, 10);
 	DrawingSurface_DrawSurfaceEx((ScriptDrawingSurface *)self, (ScriptDrawingSurface *)params[0].Ptr,
-	                             params[1].IValue, params[2].IValue, params[3].IValue, params[4].IValue, params[5].IValue,
-	                             params[6].IValue, params[7].IValue, params[8].IValue, params[9].IValue);
+		params[1].IValue, params[2].IValue, params[3].IValue, params[4].IValue, params[5].IValue,
+		params[6].IValue, params[7].IValue, params[8].IValue, params[9].IValue);
 	return RuntimeScriptValue((int32_t)0);
 }
 
@@ -583,31 +585,31 @@ void ScPl_DrawingSurface_DrawString(ScriptDrawingSurface *sds, int xx, int yy, i
 }
 
 void RegisterDrawingSurfaceAPI(ScriptAPIVersion base_api, ScriptAPIVersion compat_api) {
-	ccAddExternalObjectFunction("DrawingSurface::Clear^1",              Sc_DrawingSurface_Clear);
-	ccAddExternalObjectFunction("DrawingSurface::CreateCopy^0",         Sc_DrawingSurface_CreateCopy);
-	ccAddExternalObjectFunction("DrawingSurface::DrawCircle^3",         Sc_DrawingSurface_DrawCircle);
-	ccAddExternalObjectFunction("DrawingSurface::DrawImage^6",          Sc_DrawingSurface_DrawImage_6);
-	ccAddExternalObjectFunction("DrawingSurface::DrawImage^10",         Sc_DrawingSurface_DrawImage);
-	ccAddExternalObjectFunction("DrawingSurface::DrawLine^5",           Sc_DrawingSurface_DrawLine);
+	ccAddExternalObjectFunction("DrawingSurface::Clear^1", Sc_DrawingSurface_Clear);
+	ccAddExternalObjectFunction("DrawingSurface::CreateCopy^0", Sc_DrawingSurface_CreateCopy);
+	ccAddExternalObjectFunction("DrawingSurface::DrawCircle^3", Sc_DrawingSurface_DrawCircle);
+	ccAddExternalObjectFunction("DrawingSurface::DrawImage^6", Sc_DrawingSurface_DrawImage_6);
+	ccAddExternalObjectFunction("DrawingSurface::DrawImage^10", Sc_DrawingSurface_DrawImage);
+	ccAddExternalObjectFunction("DrawingSurface::DrawLine^5", Sc_DrawingSurface_DrawLine);
 	ccAddExternalObjectFunction("DrawingSurface::DrawMessageWrapped^5", Sc_DrawingSurface_DrawMessageWrapped);
-	ccAddExternalObjectFunction("DrawingSurface::DrawPixel^2",          Sc_DrawingSurface_DrawPixel);
-	ccAddExternalObjectFunction("DrawingSurface::DrawRectangle^4",      Sc_DrawingSurface_DrawRectangle);
-	ccAddExternalObjectFunction("DrawingSurface::DrawString^104",       Sc_DrawingSurface_DrawString);
+	ccAddExternalObjectFunction("DrawingSurface::DrawPixel^2", Sc_DrawingSurface_DrawPixel);
+	ccAddExternalObjectFunction("DrawingSurface::DrawRectangle^4", Sc_DrawingSurface_DrawRectangle);
+	ccAddExternalObjectFunction("DrawingSurface::DrawString^104", Sc_DrawingSurface_DrawString);
 	if (base_api < kScriptAPI_v350)
 		ccAddExternalObjectFunction("DrawingSurface::DrawStringWrapped^6", Sc_DrawingSurface_DrawStringWrapped_Old);
 	else
 		ccAddExternalObjectFunction("DrawingSurface::DrawStringWrapped^6", Sc_DrawingSurface_DrawStringWrapped);
-	ccAddExternalObjectFunction("DrawingSurface::DrawSurface^2",        Sc_DrawingSurface_DrawSurface_2);
-	ccAddExternalObjectFunction("DrawingSurface::DrawSurface^10",       Sc_DrawingSurface_DrawSurface);
-	ccAddExternalObjectFunction("DrawingSurface::DrawTriangle^6",       Sc_DrawingSurface_DrawTriangle);
-	ccAddExternalObjectFunction("DrawingSurface::GetPixel^2",           Sc_DrawingSurface_GetPixel);
-	ccAddExternalObjectFunction("DrawingSurface::Release^0",            Sc_DrawingSurface_Release);
-	ccAddExternalObjectFunction("DrawingSurface::get_DrawingColor",     Sc_DrawingSurface_GetDrawingColor);
-	ccAddExternalObjectFunction("DrawingSurface::set_DrawingColor",     Sc_DrawingSurface_SetDrawingColor);
-	ccAddExternalObjectFunction("DrawingSurface::get_Height",           Sc_DrawingSurface_GetHeight);
+	ccAddExternalObjectFunction("DrawingSurface::DrawSurface^2", Sc_DrawingSurface_DrawSurface_2);
+	ccAddExternalObjectFunction("DrawingSurface::DrawSurface^10", Sc_DrawingSurface_DrawSurface);
+	ccAddExternalObjectFunction("DrawingSurface::DrawTriangle^6", Sc_DrawingSurface_DrawTriangle);
+	ccAddExternalObjectFunction("DrawingSurface::GetPixel^2", Sc_DrawingSurface_GetPixel);
+	ccAddExternalObjectFunction("DrawingSurface::Release^0", Sc_DrawingSurface_Release);
+	ccAddExternalObjectFunction("DrawingSurface::get_DrawingColor", Sc_DrawingSurface_GetDrawingColor);
+	ccAddExternalObjectFunction("DrawingSurface::set_DrawingColor", Sc_DrawingSurface_SetDrawingColor);
+	ccAddExternalObjectFunction("DrawingSurface::get_Height", Sc_DrawingSurface_GetHeight);
 	ccAddExternalObjectFunction("DrawingSurface::get_UseHighResCoordinates", Sc_DrawingSurface_GetUseHighResCoordinates);
 	ccAddExternalObjectFunction("DrawingSurface::set_UseHighResCoordinates", Sc_DrawingSurface_SetUseHighResCoordinates);
-	ccAddExternalObjectFunction("DrawingSurface::get_Width",            Sc_DrawingSurface_GetWidth);
+	ccAddExternalObjectFunction("DrawingSurface::get_Width", Sc_DrawingSurface_GetWidth);
 
 	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
 
@@ -635,3 +637,5 @@ void RegisterDrawingSurfaceAPI(ScriptAPIVersion base_api, ScriptAPIVersion compa
 	ccAddExternalFunctionForPlugin("DrawingSurface::set_UseHighResCoordinates", (void *)DrawingSurface_SetUseHighResCoordinates);
 	ccAddExternalFunctionForPlugin("DrawingSurface::get_Width", (void *)DrawingSurface_GetWidth);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynamicsprite.cpp b/engines/ags/engine/ac/dynamicsprite.cpp
index ef798801bf..1e1a37db21 100644
--- a/engines/ags/engine/ac/dynamicsprite.cpp
+++ b/engines/ags/engine/ac/dynamicsprite.cpp
@@ -41,6 +41,8 @@
 #include "gfx/graphicsdriver.h"
 #include "script/runtimescriptvalue.h"
 
+namespace AGS3 {
+
 using namespace Shared;
 using namespace Engine;
 
@@ -114,8 +116,8 @@ void DynamicSprite_Resize(ScriptDynamicSprite *sds, int width, int height) {
 	// resize the sprite to the requested size
 	Bitmap *newPic = BitmapHelper::CreateBitmap(width, height, spriteset[sds->slot]->GetColorDepth());
 	newPic->StretchBlt(spriteset[sds->slot],
-	                   RectWH(0, 0, game.SpriteInfos[sds->slot].Width, game.SpriteInfos[sds->slot].Height),
-	                   RectWH(0, 0, width, height));
+		RectWH(0, 0, game.SpriteInfos[sds->slot].Width, game.SpriteInfos[sds->slot].Height),
+		RectWH(0, 0, width, height));
 
 	delete spriteset[sds->slot];
 
@@ -150,7 +152,7 @@ void DynamicSprite_CopyTransparencyMask(ScriptDynamicSprite *sds, int sourceSpri
 		quit("!DynamicSprite.CopyTransparencyMask: sprite has been deleted");
 
 	if ((game.SpriteInfos[sds->slot].Width != game.SpriteInfos[sourceSprite].Width) ||
-	        (game.SpriteInfos[sds->slot].Height != game.SpriteInfos[sourceSprite].Height)) {
+		(game.SpriteInfos[sds->slot].Height != game.SpriteInfos[sourceSprite].Height)) {
 		quit("!DynamicSprite.CopyTransparencyMask: sprites are not the same size");
 	}
 
@@ -246,7 +248,7 @@ void DynamicSprite_Rotate(ScriptDynamicSprite *sds, int angle, int width, int he
 	// rotate the sprite about its centre
 	// (+ width%2 fixes one pixel offset problem)
 	newPic->RotateBlt(spriteset[sds->slot], width / 2 + width % 2, height / 2,
-	                  game.SpriteInfos[sds->slot].Width / 2, game.SpriteInfos[sds->slot].Height / 2, itofix(angle));
+		game.SpriteInfos[sds->slot].Width / 2, game.SpriteInfos[sds->slot].Height / 2, itofix(angle));
 
 	delete spriteset[sds->slot];
 
@@ -413,7 +415,7 @@ ScriptDynamicSprite *DynamicSprite_CreateFromBackground(int frame, int x1, int y
 		width = play.room_width;
 		height = play.room_height;
 	} else if ((x1 < 0) || (y1 < 0) || (width < 1) || (height < 1) ||
-	           (x1 + width > play.room_width) || (y1 + height > play.room_height))
+		(x1 + width > play.room_width) || (y1 + height > play.room_height))
 		quit("!DynamicSprite.CreateFromBackground: invalid co-ordinates specified");
 
 	data_to_game_coords(&x1, &y1);
@@ -618,28 +620,28 @@ RuntimeScriptValue Sc_DynamicSprite_CreateFromScreenShot(const RuntimeScriptValu
 
 
 void RegisterDynamicSpriteAPI() {
-	ccAddExternalObjectFunction("DynamicSprite::ChangeCanvasSize^4",        Sc_DynamicSprite_ChangeCanvasSize);
-	ccAddExternalObjectFunction("DynamicSprite::CopyTransparencyMask^1",    Sc_DynamicSprite_CopyTransparencyMask);
-	ccAddExternalObjectFunction("DynamicSprite::Crop^4",                    Sc_DynamicSprite_Crop);
-	ccAddExternalObjectFunction("DynamicSprite::Delete",                    Sc_DynamicSprite_Delete);
-	ccAddExternalObjectFunction("DynamicSprite::Flip^1",                    Sc_DynamicSprite_Flip);
-	ccAddExternalObjectFunction("DynamicSprite::GetDrawingSurface^0",       Sc_DynamicSprite_GetDrawingSurface);
-	ccAddExternalObjectFunction("DynamicSprite::Resize^2",                  Sc_DynamicSprite_Resize);
-	ccAddExternalObjectFunction("DynamicSprite::Rotate^3",                  Sc_DynamicSprite_Rotate);
-	ccAddExternalObjectFunction("DynamicSprite::SaveToFile^1",              Sc_DynamicSprite_SaveToFile);
-	ccAddExternalObjectFunction("DynamicSprite::Tint^5",                    Sc_DynamicSprite_Tint);
-	ccAddExternalObjectFunction("DynamicSprite::get_ColorDepth",            Sc_DynamicSprite_GetColorDepth);
-	ccAddExternalObjectFunction("DynamicSprite::get_Graphic",               Sc_DynamicSprite_GetGraphic);
-	ccAddExternalObjectFunction("DynamicSprite::get_Height",                Sc_DynamicSprite_GetHeight);
-	ccAddExternalObjectFunction("DynamicSprite::get_Width",                 Sc_DynamicSprite_GetWidth);
-	ccAddExternalStaticFunction("DynamicSprite::Create^3",                  Sc_DynamicSprite_Create);
-	ccAddExternalStaticFunction("DynamicSprite::CreateFromBackground",      Sc_DynamicSprite_CreateFromBackground);
+	ccAddExternalObjectFunction("DynamicSprite::ChangeCanvasSize^4", Sc_DynamicSprite_ChangeCanvasSize);
+	ccAddExternalObjectFunction("DynamicSprite::CopyTransparencyMask^1", Sc_DynamicSprite_CopyTransparencyMask);
+	ccAddExternalObjectFunction("DynamicSprite::Crop^4", Sc_DynamicSprite_Crop);
+	ccAddExternalObjectFunction("DynamicSprite::Delete", Sc_DynamicSprite_Delete);
+	ccAddExternalObjectFunction("DynamicSprite::Flip^1", Sc_DynamicSprite_Flip);
+	ccAddExternalObjectFunction("DynamicSprite::GetDrawingSurface^0", Sc_DynamicSprite_GetDrawingSurface);
+	ccAddExternalObjectFunction("DynamicSprite::Resize^2", Sc_DynamicSprite_Resize);
+	ccAddExternalObjectFunction("DynamicSprite::Rotate^3", Sc_DynamicSprite_Rotate);
+	ccAddExternalObjectFunction("DynamicSprite::SaveToFile^1", Sc_DynamicSprite_SaveToFile);
+	ccAddExternalObjectFunction("DynamicSprite::Tint^5", Sc_DynamicSprite_Tint);
+	ccAddExternalObjectFunction("DynamicSprite::get_ColorDepth", Sc_DynamicSprite_GetColorDepth);
+	ccAddExternalObjectFunction("DynamicSprite::get_Graphic", Sc_DynamicSprite_GetGraphic);
+	ccAddExternalObjectFunction("DynamicSprite::get_Height", Sc_DynamicSprite_GetHeight);
+	ccAddExternalObjectFunction("DynamicSprite::get_Width", Sc_DynamicSprite_GetWidth);
+	ccAddExternalStaticFunction("DynamicSprite::Create^3", Sc_DynamicSprite_Create);
+	ccAddExternalStaticFunction("DynamicSprite::CreateFromBackground", Sc_DynamicSprite_CreateFromBackground);
 	ccAddExternalStaticFunction("DynamicSprite::CreateFromDrawingSurface^5", Sc_DynamicSprite_CreateFromDrawingSurface);
 	ccAddExternalStaticFunction("DynamicSprite::CreateFromExistingSprite^1", Sc_DynamicSprite_CreateFromExistingSprite_Old);
 	ccAddExternalStaticFunction("DynamicSprite::CreateFromExistingSprite^2", Sc_DynamicSprite_CreateFromExistingSprite);
-	ccAddExternalStaticFunction("DynamicSprite::CreateFromFile",            Sc_DynamicSprite_CreateFromFile);
-	ccAddExternalStaticFunction("DynamicSprite::CreateFromSaveGame",        Sc_DynamicSprite_CreateFromSaveGame);
-	ccAddExternalStaticFunction("DynamicSprite::CreateFromScreenShot",      Sc_DynamicSprite_CreateFromScreenShot);
+	ccAddExternalStaticFunction("DynamicSprite::CreateFromFile", Sc_DynamicSprite_CreateFromFile);
+	ccAddExternalStaticFunction("DynamicSprite::CreateFromSaveGame", Sc_DynamicSprite_CreateFromSaveGame);
+	ccAddExternalStaticFunction("DynamicSprite::CreateFromScreenShot", Sc_DynamicSprite_CreateFromScreenShot);
 
 	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
 
@@ -666,3 +668,5 @@ void RegisterDynamicSpriteAPI() {
 	ccAddExternalFunctionForPlugin("DynamicSprite::CreateFromSaveGame", (void *)DynamicSprite_CreateFromSaveGame);
 	ccAddExternalFunctionForPlugin("DynamicSprite::CreateFromScreenShot", (void *)DynamicSprite_CreateFromScreenShot);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp b/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp
index bdc815dd96..fe3f70cb6d 100644
--- a/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp
@@ -26,6 +26,8 @@
 #include "ac/common.h"               // quit()
 #include "util/bbop.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 // *** The script serialization routines for built-in types
@@ -125,3 +127,5 @@ void AGSCCDynamicObject::WriteInt32(const char *address, intptr_t offset, int32_
 void AGSCCDynamicObject::WriteFloat(const char *address, intptr_t offset, float val) {
 	*(float *)(address + offset) = val;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/cc_audiochannel.cpp b/engines/ags/engine/ac/dynobj/cc_audiochannel.cpp
index b8463f2f33..e5e89d620b 100644
--- a/engines/ags/engine/ac/dynobj/cc_audiochannel.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_audiochannel.cpp
@@ -24,6 +24,8 @@
 #include "ac/dynobj/scriptaudiochannel.h"
 #include "media/audio/audio_system.h"
 
+namespace AGS3 {
+
 extern ScriptAudioChannel scrAudioChannel[MAX_SOUND_CHANNELS + 1];
 
 const char *CCAudioChannel::GetType() {
@@ -42,3 +44,5 @@ void CCAudioChannel::Unserialize(int index, const char *serializedData, int data
 	int id = UnserializeInt();
 	ccRegisterUnserializedObject(index, &scrAudioChannel[id], this);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/cc_audioclip.cpp b/engines/ags/engine/ac/dynobj/cc_audioclip.cpp
index 06a70867d3..edcde5d34a 100644
--- a/engines/ags/engine/ac/dynobj/cc_audioclip.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_audioclip.cpp
@@ -24,6 +24,8 @@
 #include "ac/dynobj/scriptaudioclip.h"
 #include "ac/gamesetupstruct.h"
 
+namespace AGS3 {
+
 extern GameSetupStruct game;
 
 const char *CCAudioClip::GetType() {
@@ -42,3 +44,5 @@ void CCAudioClip::Unserialize(int index, const char *serializedData, int dataSiz
 	int id = UnserializeInt();
 	ccRegisterUnserializedObject(index, &game.audioClips[id], this);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/cc_character.cpp b/engines/ags/engine/ac/dynobj/cc_character.cpp
index 07658e367d..d00b9cea5a 100644
--- a/engines/ags/engine/ac/dynobj/cc_character.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_character.cpp
@@ -26,6 +26,8 @@
 #include "ac/gamesetupstruct.h"
 #include "ac/game_version.h"
 
+namespace AGS3 {
+
 extern GameSetupStruct game;
 
 // return the type name of the object
@@ -61,3 +63,5 @@ void CCCharacter::WriteInt16(const char *address, intptr_t offset, int16_t val)
 		}
 	}
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/cc_dialog.cpp b/engines/ags/engine/ac/dynobj/cc_dialog.cpp
index 47bcefca76..bfd8e835fa 100644
--- a/engines/ags/engine/ac/dynobj/cc_dialog.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_dialog.cpp
@@ -25,6 +25,8 @@
 #include "ac/dialogtopic.h"
 #include "ac/gamestructdefines.h"
 
+namespace AGS3 {
+
 // return the type name of the object
 const char *CCDialog::GetType() {
 	return "Dialog";
@@ -44,3 +46,5 @@ void CCDialog::Unserialize(int index, const char *serializedData, int dataSize)
 	int num = UnserializeInt();
 	ccRegisterUnserializedObject(index, &scrDialog[num], this);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicarray.cpp b/engines/ags/engine/ac/dynobj/cc_dynamicarray.cpp
index 0a66cccc50..d64343865e 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicarray.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicarray.cpp
@@ -23,6 +23,8 @@
 #include <string.h>
 #include "cc_dynamicarray.h"
 
+namespace AGS3 {
+
 // return the type name of the object
 const char *CCDynamicArray::GetType() {
 	return CC_DYNAMIC_ARRAY_TYPE_NAME;
@@ -147,3 +149,5 @@ DynObjectRef DynamicArrayHelpers::CreateStringArray(const std::vector<const char
 	}
 	return arr;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicobject.cpp b/engines/ags/engine/ac/dynobj/cc_dynamicobject.cpp
index 9794f02646..725545ed9f 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicobject.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicobject.cpp
@@ -45,6 +45,8 @@
 #include "script/script_common.h"
 #include "util/stream.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 ICCStringClass *stringClassImpl = nullptr;
@@ -60,7 +62,7 @@ int32_t ccRegisterManagedObject(const void *object, ICCDynamicObject *callback,
 	int32_t handl = pool.AddObject((const char *)object, callback, plugin_object);
 
 	ManagedObjectLog("Register managed object type '%s' handle=%d addr=%08X",
-	                 ((callback == NULL) ? "(unknown)" : callback->GetType()), handl, object);
+		((callback == NULL) ? "(unknown)" : callback->GetType()), handl, object);
 
 	return handl;
 }
@@ -158,3 +160,5 @@ int ccReleaseObjectReference(int32_t handle) {
 
 	return pool.SubRef(handle);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/cc_gui.cpp b/engines/ags/engine/ac/dynobj/cc_gui.cpp
index 300883cff8..3ef3e51fe9 100644
--- a/engines/ags/engine/ac/dynobj/cc_gui.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_gui.cpp
@@ -23,6 +23,8 @@
 #include "ac/dynobj/cc_gui.h"
 #include "ac/dynobj/scriptgui.h"
 
+namespace AGS3 {
+
 extern ScriptGUI *scrGui;
 
 // return the type name of the object
@@ -44,3 +46,5 @@ void CCGUI::Unserialize(int index, const char *serializedData, int dataSize) {
 	int num = UnserializeInt();
 	ccRegisterUnserializedObject(index, &scrGui[num], this);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/cc_guiobject.cpp b/engines/ags/engine/ac/dynobj/cc_guiobject.cpp
index 6898ffb963..8d344c7a7f 100644
--- a/engines/ags/engine/ac/dynobj/cc_guiobject.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_guiobject.cpp
@@ -25,6 +25,8 @@
 #include "gui/guimain.h"
 #include "gui/guiobject.h"
 
+namespace AGS3 {
+
 using AGS::Shared::GUIObject;
 
 // return the type name of the object
@@ -48,3 +50,5 @@ void CCGUIObject::Unserialize(int index, const char *serializedData, int dataSiz
 	int objnum = UnserializeInt();
 	ccRegisterUnserializedObject(index, guis[guinum].GetControl(objnum), this);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/cc_hotspot.cpp b/engines/ags/engine/ac/dynobj/cc_hotspot.cpp
index 310a1ad06d..8425c39eee 100644
--- a/engines/ags/engine/ac/dynobj/cc_hotspot.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_hotspot.cpp
@@ -25,6 +25,8 @@
 #include "ac/common_defines.h"
 #include "game/roomstruct.h"
 
+namespace AGS3 {
+
 extern ScriptHotspot scrHotspot[MAX_ROOM_HOTSPOTS];
 
 // return the type name of the object
@@ -46,3 +48,5 @@ void CCHotspot::Unserialize(int index, const char *serializedData, int dataSize)
 	int num = UnserializeInt();
 	ccRegisterUnserializedObject(index, &scrHotspot[num], this);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/cc_inventory.cpp b/engines/ags/engine/ac/dynobj/cc_inventory.cpp
index 1e3045348b..732a4da44b 100644
--- a/engines/ags/engine/ac/dynobj/cc_inventory.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_inventory.cpp
@@ -24,6 +24,8 @@
 #include "ac/dynobj/scriptinvitem.h"
 #include "ac/characterinfo.h"
 
+namespace AGS3 {
+
 extern ScriptInvItem scrInv[MAX_INV];
 
 // return the type name of the object
@@ -45,3 +47,5 @@ void CCInventory::Unserialize(int index, const char *serializedData, int dataSiz
 	int num = UnserializeInt();
 	ccRegisterUnserializedObject(index, &scrInv[num], this);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/cc_object.cpp b/engines/ags/engine/ac/dynobj/cc_object.cpp
index 1f695146f3..99c0d6f41b 100644
--- a/engines/ags/engine/ac/dynobj/cc_object.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_object.cpp
@@ -25,6 +25,8 @@
 #include "ac/common_defines.h"
 #include "game/roomstruct.h"
 
+namespace AGS3 {
+
 extern ScriptObject scrObj[MAX_ROOM_OBJECTS];
 
 // return the type name of the object
@@ -46,3 +48,5 @@ void CCObject::Unserialize(int index, const char *serializedData, int dataSize)
 	int num = UnserializeInt();
 	ccRegisterUnserializedObject(index, &scrObj[num], this);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/cc_region.cpp b/engines/ags/engine/ac/dynobj/cc_region.cpp
index a1de49619b..fb140013f6 100644
--- a/engines/ags/engine/ac/dynobj/cc_region.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_region.cpp
@@ -25,6 +25,8 @@
 #include "ac/common_defines.h"
 #include "game/roomstruct.h"
 
+namespace AGS3 {
+
 extern ScriptRegion scrRegion[MAX_ROOM_REGIONS];
 
 // return the type name of the object
@@ -46,3 +48,5 @@ void CCRegion::Unserialize(int index, const char *serializedData, int dataSize)
 	int num = UnserializeInt();
 	ccRegisterUnserializedObject(index, &scrRegion[num], this);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/cc_serializer.cpp b/engines/ags/engine/ac/dynobj/cc_serializer.cpp
index 90ae3bad28..53d6f42f87 100644
--- a/engines/ags/engine/ac/dynobj/cc_serializer.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_serializer.cpp
@@ -34,6 +34,8 @@
 #include "plugin/agsplugin.h"
 #include "plugin/pluginobjectreader.h"
 
+namespace AGS3 {
+
 extern CCGUIObject ccDynamicGUIObject;
 extern CCCharacter ccDynamicCharacter;
 extern CCHotspot   ccDynamicHotspot;
@@ -122,3 +124,4 @@ void AGSDeSerializer::Unserialize(int index, const char *objectType, const char
 
 AGSDeSerializer ccUnserializer;
 
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/managedobjectpool.cpp b/engines/ags/engine/ac/dynobj/managedobjectpool.cpp
index f6e837f52d..be2f46b4d2 100644
--- a/engines/ags/engine/ac/dynobj/managedobjectpool.cpp
+++ b/engines/ags/engine/ac/dynobj/managedobjectpool.cpp
@@ -30,6 +30,8 @@
 #include "script/script_common.h"
 #include "util/stream.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 const auto OBJECT_CACHE_MAGIC_NUMBER = 0xa30b;
@@ -199,7 +201,7 @@ int ManagedObjectPool::AddObject(const char *address, ICCDynamicObject *callback
 
 	o = ManagedObject(plugin_object ? kScValPluginObject : kScValDynamicObject, handle, address, callback);
 
-	handleByAddress.insert({address, o.handle});
+	handleByAddress.insert({ address, o.handle });
 	objectCreationCounter++;
 	ManagedObjectLog("Allocated managed object handle=%d, type=%s", handle, callback->GetType());
 	return o.handle;
@@ -223,7 +225,7 @@ int ManagedObjectPool::AddUnserializedObject(const char *address, ICCDynamicObje
 
 	o = ManagedObject(plugin_object ? kScValPluginObject : kScValDynamicObject, handle, address, callback);
 
-	handleByAddress.insert({address, o.handle});
+	handleByAddress.insert({ address, o.handle });
 	ManagedObjectLog("Allocated unserialized managed object handle=%d, type=%s", o.handle, callback->GetType());
 	return o.handle;
 }
@@ -287,7 +289,8 @@ int ManagedObjectPool::ReadFromDisk(Stream *in, ICCObjectReader *reader) {
 	auto version = in->ReadInt32();
 
 	switch (version) {
-	case 1: {
+	case 1:
+	{
 		// IMPORTANT: numObjs is "nextHandleId", which is why we iterate from 1 to numObjs-1
 		int numObjs = in->ReadInt32();
 		for (int i = 1; i < numObjs; i++) {
@@ -309,7 +312,8 @@ int ManagedObjectPool::ReadFromDisk(Stream *in, ICCObjectReader *reader) {
 		}
 	}
 	break;
-	case 2: {
+	case 2:
+	{
 		// This is actually number of objects written.
 		int objectsSize = in->ReadInt32();
 		for (int i = 0; i < objectsSize; i++) {
@@ -377,3 +381,5 @@ ManagedObjectPool::ManagedObjectPool() : objectCreationCounter(0), nextHandle(1)
 }
 
 ManagedObjectPool pool;
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/scriptcamera.cpp b/engines/ags/engine/ac/dynobj/scriptcamera.cpp
index e8d434ee68..f5c079d216 100644
--- a/engines/ags/engine/ac/dynobj/scriptcamera.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptcamera.cpp
@@ -24,9 +24,12 @@
 #include "ac/gamestate.h"
 #include "util/bbop.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
-ScriptCamera::ScriptCamera(int id) : _id(id) {}
+ScriptCamera::ScriptCamera(int id) : _id(id) {
+}
 
 const char *ScriptCamera::GetType() {
 	return "Camera2";
@@ -64,3 +67,5 @@ ScriptCamera *Camera_Unserialize(int handle, const char *serializedData, int dat
 	}
 	return new ScriptCamera(-1); // make invalid reference
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/scriptdatetime.cpp b/engines/ags/engine/ac/dynobj/scriptdatetime.cpp
index 19c0abcd91..83b71cd889 100644
--- a/engines/ags/engine/ac/dynobj/scriptdatetime.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptdatetime.cpp
@@ -22,6 +22,8 @@
 
 #include "ac/dynobj/scriptdatetime.h"
 
+namespace AGS3 {
+
 int ScriptDateTime::Dispose(const char *address, bool force) {
 	// always dispose a DateTime
 	delete this;
@@ -61,3 +63,5 @@ ScriptDateTime::ScriptDateTime() {
 	hour = minute = second = 0;
 	rawUnixTime = 0;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.cpp b/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.cpp
index 7414e3a81c..1dcc21a77d 100644
--- a/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.cpp
@@ -22,6 +22,8 @@
 
 #include "ac/dynobj/scriptdialogoptionsrendering.h"
 
+namespace AGS3 {
+
 // return the type name of the object
 const char *ScriptDialogOptionsRendering::GetType() {
 	return "DialogOptionsRendering";
@@ -57,3 +59,5 @@ void ScriptDialogOptionsRendering::Reset() {
 ScriptDialogOptionsRendering::ScriptDialogOptionsRendering() {
 	Reset();
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/scriptdict.cpp b/engines/ags/engine/ac/dynobj/scriptdict.cpp
index 8dbb901265..94dbb00cf9 100644
--- a/engines/ags/engine/ac/dynobj/scriptdict.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptdict.cpp
@@ -22,6 +22,8 @@
 
 #include "ac/dynobj/scriptdict.h"
 
+namespace AGS3 {
+
 int ScriptDictBase::Dispose(const char *address, bool force) {
 	Clear();
 	delete this;
@@ -34,7 +36,7 @@ const char *ScriptDictBase::GetType() {
 
 int ScriptDictBase::Serialize(const char *address, char *buffer, int bufsize) {
 	size_t total_sz = CalcSerializeSize() + sizeof(int32_t) * 2;
-	if (bufsize < 0 || total_sz > (size_t)bufsize) {
+	if (bufsize < 0 || total_sz >(size_t)bufsize) {
 		// buffer not big enough, ask for a bigger one
 		return -((int)total_sz);
 	}
@@ -52,3 +54,5 @@ void ScriptDictBase::Unserialize(int index, const char *serializedData, int data
 	UnserializeContainer(serializedData);
 	ccRegisterUnserializedObject(index, this, this);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp b/engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp
index 6b2e240239..703120f836 100644
--- a/engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp
@@ -30,6 +30,8 @@
 #include "game/roomstruct.h"
 #include "gfx/bitmap.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern RoomStruct thisroom;
@@ -129,3 +131,5 @@ ScriptDrawingSurface::ScriptDrawingSurface() {
 		highResCoordinates = 1;
 	}
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/scriptdynamicsprite.cpp b/engines/ags/engine/ac/dynobj/scriptdynamicsprite.cpp
index 817d77b6fe..69b7390540 100644
--- a/engines/ags/engine/ac/dynobj/scriptdynamicsprite.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptdynamicsprite.cpp
@@ -23,6 +23,8 @@
 #include "ac/dynobj/scriptdynamicsprite.h"
 #include "ac/dynamicsprite.h"
 
+namespace AGS3 {
+
 int ScriptDynamicSprite::Dispose(const char *address, bool force) {
 	// always dispose
 	if ((slot) && (!force))
@@ -56,3 +58,5 @@ ScriptDynamicSprite::ScriptDynamicSprite(int theSlot) {
 ScriptDynamicSprite::ScriptDynamicSprite() {
 	slot = 0;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/scriptfile.cpp b/engines/ags/engine/ac/dynobj/scriptfile.cpp
index 122ab0a8cf..203c94f0b0 100644
--- a/engines/ags/engine/ac/dynobj/scriptfile.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptfile.cpp
@@ -23,11 +23,13 @@
 #include "ac/dynobj/scriptfile.h"
 #include "ac/global_file.h"
 
+namespace AGS3 {
+
 // CHECKME: actually NULLs here will be equal to kFile_Open & kFile_Read
 const Common::FileOpenMode sc_File::fopenModes[] =
-{Common::kFile_Open/*CHECKME, was undefined*/, Common::kFile_Open, Common::kFile_CreateAlways, Common::kFile_Create};
+{ Common::kFile_Open/*CHECKME, was undefined*/, Common::kFile_Open, Common::kFile_CreateAlways, Common::kFile_Create };
 const Common::FileWorkMode sc_File::fworkModes[] =
-{Common::kFile_Read/*CHECKME, was undefined*/, Common::kFile_Read, Common::kFile_Write, Common::kFile_Write};
+{ Common::kFile_Read/*CHECKME, was undefined*/, Common::kFile_Read, Common::kFile_Write, Common::kFile_Write };
 
 int sc_File::Dispose(const char *address, bool force) {
 	Close();
@@ -100,3 +102,5 @@ void sc_File::WriteInt32(const char *address, intptr_t offset, int32_t val) {
 
 void sc_File::WriteFloat(const char *address, intptr_t offset, float val) {
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/scriptoverlay.cpp b/engines/ags/engine/ac/dynobj/scriptoverlay.cpp
index ba8954b948..3beedc5c3a 100644
--- a/engines/ags/engine/ac/dynobj/scriptoverlay.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptoverlay.cpp
@@ -26,6 +26,8 @@
 #include "ac/runtime_defines.h"
 #include "ac/screenoverlay.h"
 
+namespace AGS3 {
+
 int ScriptOverlay::Dispose(const char *address, bool force) {
 	// since the managed object is being deleted, remove the
 	// reference so it doesn't try and dispose something else
@@ -84,3 +86,5 @@ ScriptOverlay::ScriptOverlay() {
 	borderHeight = 0;
 	isBackgroundSpeech = 0;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/scriptset.cpp b/engines/ags/engine/ac/dynobj/scriptset.cpp
index db1e733f50..626ce882c7 100644
--- a/engines/ags/engine/ac/dynobj/scriptset.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptset.cpp
@@ -22,6 +22,8 @@
 
 #include "ac/dynobj/scriptset.h"
 
+namespace AGS3 {
+
 int ScriptSetBase::Dispose(const char *address, bool force) {
 	Clear();
 	delete this;
@@ -34,7 +36,7 @@ const char *ScriptSetBase::GetType() {
 
 int ScriptSetBase::Serialize(const char *address, char *buffer, int bufsize) {
 	size_t total_sz = CalcSerializeSize() + sizeof(int32_t) * 2;
-	if (bufsize < 0 || total_sz > (size_t)bufsize) {
+	if (bufsize < 0 || total_sz >(size_t)bufsize) {
 		// buffer not big enough, ask for a bigger one
 		return -((int)total_sz);
 	}
@@ -52,3 +54,5 @@ void ScriptSetBase::Unserialize(int index, const char *serializedData, int dataS
 	UnserializeContainer(serializedData);
 	ccRegisterUnserializedObject(index, this, this);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/scriptstring.cpp b/engines/ags/engine/ac/dynobj/scriptstring.cpp
index 637de80e35..e752f3e97f 100644
--- a/engines/ags/engine/ac/dynobj/scriptstring.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptstring.cpp
@@ -25,6 +25,8 @@
 #include <stdlib.h>
 #include <string.h>
 
+namespace AGS3 {
+
 DynObjectRef ScriptString::CreateString(const char *fromText) {
 	return CreateNewScriptStringObj(fromText);
 }
@@ -72,3 +74,5 @@ ScriptString::ScriptString(const char *fromText) {
 	text = (char *)malloc(strlen(fromText) + 1);
 	strcpy(text, fromText);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/scriptuserobject.cpp b/engines/ags/engine/ac/dynobj/scriptuserobject.cpp
index b519bb17f8..55e2baa04a 100644
--- a/engines/ags/engine/ac/dynobj/scriptuserobject.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptuserobject.cpp
@@ -23,6 +23,8 @@
 #include <memory.h>
 #include "scriptuserobject.h"
 
+namespace AGS3 {
+
 // return the type name of the object
 const char *ScriptUserObject::GetType() {
 	return "UserObject";
@@ -34,7 +36,7 @@ ScriptUserObject::ScriptUserObject()
 }
 
 ScriptUserObject::~ScriptUserObject() {
-	delete [] _data;
+	delete[] _data;
 }
 
 /* static */ ScriptUserObject *ScriptUserObject::CreateManaged(size_t size) {
@@ -45,7 +47,7 @@ ScriptUserObject::~ScriptUserObject() {
 }
 
 void ScriptUserObject::Create(const char *data, size_t size) {
-	delete [] _data;
+	delete[] _data;
 	_data = nullptr;
 
 	_size = size;
@@ -129,3 +131,5 @@ ScriptUserObject *ScriptStructHelpers::CreatePoint(int x, int y) {
 	suo->WriteInt32((const char *)suo, sizeof(int32_t), y);
 	return suo;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/scriptviewframe.cpp b/engines/ags/engine/ac/dynobj/scriptviewframe.cpp
index d3f6ccd317..9a727afa60 100644
--- a/engines/ags/engine/ac/dynobj/scriptviewframe.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptviewframe.cpp
@@ -22,6 +22,8 @@
 
 #include "ac/dynobj/scriptviewframe.h"
 
+namespace AGS3 {
+
 int ScriptViewFrame::Dispose(const char *address, bool force) {
 	// always dispose a ViewFrame
 	delete this;
@@ -59,3 +61,5 @@ ScriptViewFrame::ScriptViewFrame() {
 	loop = -1;
 	frame = -1;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/scriptviewport.cpp b/engines/ags/engine/ac/dynobj/scriptviewport.cpp
index c090db39bd..7bca084f19 100644
--- a/engines/ags/engine/ac/dynobj/scriptviewport.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptviewport.cpp
@@ -24,9 +24,12 @@
 #include "ac/gamestate.h"
 #include "util/bbop.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
-ScriptViewport::ScriptViewport(int id) : _id(id) {}
+ScriptViewport::ScriptViewport(int id) : _id(id) {
+}
 
 const char *ScriptViewport::GetType() {
 	return "Viewport2";
@@ -64,3 +67,5 @@ ScriptViewport *Viewport_Unserialize(int handle, const char *serializedData, int
 	}
 	return new ScriptViewport(-1); // make invalid reference
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/event.cpp b/engines/ags/engine/ac/event.cpp
index fec319880e..e7415dfe09 100644
--- a/engines/ags/engine/ac/event.cpp
+++ b/engines/ags/engine/ac/event.cpp
@@ -42,6 +42,8 @@
 #include "media/audio/audio_system.h"
 #include "ac/timer.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -67,7 +69,7 @@ int evblocknum;
 int inside_processevent = 0;
 int eventClaimed = EVENT_NONE;
 
-const char *tsnames[4] = {nullptr, REP_EXEC_NAME, "on_key_press", "on_mouse_click"};
+const char *tsnames[4] = { nullptr, REP_EXEC_NAME, "on_key_press", "on_mouse_click" };
 
 
 int run_claimable_event(const char *tsname, bool includeRoom, int numParams, const RuntimeScriptValue *params, bool *eventWasClaimed) {
@@ -186,7 +188,7 @@ void process_event(EventHappened *evp) {
 
 			evblockbasename = "room";
 			if (evp->data3 == 5) {
-				in_enters_screen ++;
+				in_enters_screen++;
 				run_on_event(GE_ENTER_ROOM, RuntimeScriptValue().SetInt32(displayed_room));
 
 			}
@@ -204,7 +206,7 @@ void process_event(EventHappened *evp) {
 		evblocknum = oldblocknum;
 
 		if ((evp->data3 == 5) && (evp->data1 == EVB_ROOM))
-			in_enters_screen --;
+			in_enters_screen--;
 	} else if (evp->type == EV_FADEIN) {
 		// if they change the transition type before the fadein, make
 		// sure the screen doesn't freeze up
@@ -227,7 +229,7 @@ void process_event(EventHappened *evp) {
 
 		const bool ignore_transition = (play.screen_tint > 0);
 		if (((theTransition == FADE_CROSSFADE) || (theTransition == FADE_DISSOLVE)) &&
-		        (saved_viewport_bitmap == nullptr) && !ignore_transition) {
+			(saved_viewport_bitmap == nullptr) && !ignore_transition) {
 			// transition type was not crossfade/dissolve when the screen faded out,
 			// but it is now when the screen fades in (Eg. a save game was restored
 			// with a different setting). Therefore just fade normally.
@@ -272,7 +274,7 @@ void process_event(EventHappened *evp) {
 					int lyp = viewport.GetHeight() / 2 - boxhit / 2;
 					gfxDriver->Vsync();
 					temp_scr->Blit(saved_backbuf, lxp, lyp, lxp, lyp,
-					               boxwid, boxhit);
+						boxwid, boxhit);
 					render_to_screen();
 					update_polled_mp3();
 					WaitForNextFrame();
@@ -312,7 +314,7 @@ void process_event(EventHappened *evp) {
 			set_palette_range(palette, 0, 255, 0);
 			gfxDriver->DestroyDDB(ddb);
 		} else if (theTransition == FADE_DISSOLVE) {
-			int pattern[16] = {0, 4, 14, 9, 5, 11, 2, 8, 10, 3, 12, 7, 15, 6, 13, 1};
+			int pattern[16] = { 0, 4, 14, 9, 5, 11, 2, 8, 10, 3, 12, 7, 15, 6, 13, 1 };
 			int aa, bb, cc;
 			color interpal[256];
 
@@ -401,3 +403,5 @@ void ClaimEvent() {
 
 	eventClaimed = EVENT_CLAIMED;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/file.cpp b/engines/ags/engine/ac/file.cpp
index c1128f960f..459e46dea9 100644
--- a/engines/ags/engine/ac/file.cpp
+++ b/engines/ags/engine/ac/file.cpp
@@ -46,6 +46,8 @@
 #include "util/string.h"
 #include "util/string_utils.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern GameSetup usetup;
@@ -210,10 +212,10 @@ int File_GetPosition(sc_File *fil) {
 //=============================================================================
 
 
-const String GameInstallRootToken    = "$INSTALLDIR$";
+const String GameInstallRootToken = "$INSTALLDIR$";
 const String UserSavedgamesRootToken = "$MYDOCS$";
-const String GameSavedgamesDirToken  = "$SAVEGAMEDIR$";
-const String GameDataDirToken        = "$APPDATADIR$";
+const String GameSavedgamesDirToken = "$SAVEGAMEDIR$";
+const String GameDataDirToken = "$APPDATADIR$";
 
 void FixupFilename(char *filename) {
 	const char *illegal = platform->GetIllegalFileChars();
@@ -234,7 +236,7 @@ void FixupFilename(char *filename) {
 // Returns TRUE if the new string was created, and FALSE if the path was good.
 bool FixSlashAfterToken(const String &path, const String &token, String &new_path) {
 	if (path.CompareLeft(token) == 0 && path.GetLength() > token.GetLength() &&
-	        path[token.GetLength()] != '/') {
+		path[token.GetLength()] != '/') {
 		new_path = String::FromFormat("%s/%s", token.GetCStr(), path.Mid(token.GetLength()).GetCStr());
 		return true;
 	}
@@ -244,10 +246,10 @@ bool FixSlashAfterToken(const String &path, const String &token, String &new_pat
 String FixSlashAfterToken(const String &path) {
 	String fixed_path = path;
 	Path::FixupPath(fixed_path);
-	if (FixSlashAfterToken(fixed_path, GameInstallRootToken,    fixed_path) ||
-	        FixSlashAfterToken(fixed_path, UserSavedgamesRootToken, fixed_path) ||
-	        FixSlashAfterToken(fixed_path, GameSavedgamesDirToken,  fixed_path) ||
-	        FixSlashAfterToken(fixed_path, GameDataDirToken,        fixed_path))
+	if (FixSlashAfterToken(fixed_path, GameInstallRootToken, fixed_path) ||
+		FixSlashAfterToken(fixed_path, UserSavedgamesRootToken, fixed_path) ||
+		FixSlashAfterToken(fixed_path, GameSavedgamesDirToken, fixed_path) ||
+		FixSlashAfterToken(fixed_path, GameDataDirToken, fixed_path))
 		return fixed_path;
 	return path;
 }
@@ -293,7 +295,7 @@ bool ResolveScriptPath(const String &orig_sc_path, bool read_only, ResolvedPath
 	if (sc_path.CompareLeft(GameInstallRootToken, GameInstallRootToken.GetLength()) == 0) {
 		if (!read_only) {
 			debug_script_warn("Attempt to access file '%s' denied (cannot write to game installation directory)",
-			                  sc_path.GetCStr());
+				sc_path.GetCStr());
 			return false;
 		}
 		parent_dir = get_install_dir();
@@ -327,7 +329,7 @@ bool ResolveScriptPath(const String &orig_sc_path, bool read_only, ResolvedPath
 		// if the unsafe path is used for write operation
 		if (!read_only && game.options[OPT_SAFEFILEPATHS]) {
 			debug_script_warn("Attempt to access file '%s' denied (cannot write to game installation directory);\nPath will be remapped to the app data directory: '%s'",
-			                  sc_path.GetCStr(), parent_dir.GetCStr());
+				sc_path.GetCStr(), parent_dir.GetCStr());
 		}
 	}
 
@@ -713,25 +715,25 @@ RuntimeScriptValue Sc_File_GetPosition(void *self, const RuntimeScriptValue *par
 
 
 void RegisterFileAPI() {
-	ccAddExternalStaticFunction("File::Delete^1",           Sc_File_Delete);
-	ccAddExternalStaticFunction("File::Exists^1",           Sc_File_Exists);
-	ccAddExternalStaticFunction("File::Open^2",             Sc_sc_OpenFile);
-	ccAddExternalObjectFunction("File::Close^0",            Sc_File_Close);
-	ccAddExternalObjectFunction("File::ReadInt^0",          Sc_File_ReadInt);
-	ccAddExternalObjectFunction("File::ReadRawChar^0",      Sc_File_ReadRawChar);
-	ccAddExternalObjectFunction("File::ReadRawInt^0",       Sc_File_ReadRawInt);
-	ccAddExternalObjectFunction("File::ReadRawLine^1",      Sc_File_ReadRawLine);
-	ccAddExternalObjectFunction("File::ReadRawLineBack^0",  Sc_File_ReadRawLineBack);
-	ccAddExternalObjectFunction("File::ReadString^1",       Sc_File_ReadString);
-	ccAddExternalObjectFunction("File::ReadStringBack^0",   Sc_File_ReadStringBack);
-	ccAddExternalObjectFunction("File::WriteInt^1",         Sc_File_WriteInt);
-	ccAddExternalObjectFunction("File::WriteRawChar^1",     Sc_File_WriteRawChar);
-	ccAddExternalObjectFunction("File::WriteRawLine^1",     Sc_File_WriteRawLine);
-	ccAddExternalObjectFunction("File::WriteString^1",      Sc_File_WriteString);
-	ccAddExternalObjectFunction("File::Seek^2",             Sc_File_Seek);
-	ccAddExternalObjectFunction("File::get_EOF",            Sc_File_GetEOF);
-	ccAddExternalObjectFunction("File::get_Error",          Sc_File_GetError);
-	ccAddExternalObjectFunction("File::get_Position",       Sc_File_GetPosition);
+	ccAddExternalStaticFunction("File::Delete^1", Sc_File_Delete);
+	ccAddExternalStaticFunction("File::Exists^1", Sc_File_Exists);
+	ccAddExternalStaticFunction("File::Open^2", Sc_sc_OpenFile);
+	ccAddExternalObjectFunction("File::Close^0", Sc_File_Close);
+	ccAddExternalObjectFunction("File::ReadInt^0", Sc_File_ReadInt);
+	ccAddExternalObjectFunction("File::ReadRawChar^0", Sc_File_ReadRawChar);
+	ccAddExternalObjectFunction("File::ReadRawInt^0", Sc_File_ReadRawInt);
+	ccAddExternalObjectFunction("File::ReadRawLine^1", Sc_File_ReadRawLine);
+	ccAddExternalObjectFunction("File::ReadRawLineBack^0", Sc_File_ReadRawLineBack);
+	ccAddExternalObjectFunction("File::ReadString^1", Sc_File_ReadString);
+	ccAddExternalObjectFunction("File::ReadStringBack^0", Sc_File_ReadStringBack);
+	ccAddExternalObjectFunction("File::WriteInt^1", Sc_File_WriteInt);
+	ccAddExternalObjectFunction("File::WriteRawChar^1", Sc_File_WriteRawChar);
+	ccAddExternalObjectFunction("File::WriteRawLine^1", Sc_File_WriteRawLine);
+	ccAddExternalObjectFunction("File::WriteString^1", Sc_File_WriteString);
+	ccAddExternalObjectFunction("File::Seek^2", Sc_File_Seek);
+	ccAddExternalObjectFunction("File::get_EOF", Sc_File_GetEOF);
+	ccAddExternalObjectFunction("File::get_Error", Sc_File_GetError);
+	ccAddExternalObjectFunction("File::get_Position", Sc_File_GetPosition);
 
 	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
 
@@ -753,3 +755,5 @@ void RegisterFileAPI() {
 	ccAddExternalFunctionForPlugin("File::get_EOF", (void *)File_GetEOF);
 	ccAddExternalFunctionForPlugin("File::get_Error", (void *)File_GetError);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/game.cpp b/engines/ags/engine/ac/game.cpp
index f71b1a9309..da01664b11 100644
--- a/engines/ags/engine/ac/game.cpp
+++ b/engines/ags/engine/ac/game.cpp
@@ -98,6 +98,8 @@
 #include "util/string_utils.h"
 #include "ac/keycode.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -2317,3 +2319,5 @@ void RegisterStaticObjects() {
 	ccAddExternalStaticObject("system", &scsystem, &GlobalStaticManager);
 	ccAddExternalStaticObject("savegameindex", &play.filenumbers[0], &GlobalStaticManager);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/gamesetup.cpp b/engines/ags/engine/ac/gamesetup.cpp
index d33d4739e3..8f197591b5 100644
--- a/engines/ags/engine/ac/gamesetup.cpp
+++ b/engines/ags/engine/ac/gamesetup.cpp
@@ -23,6 +23,8 @@
 #include "util/wgt2allg.h" // DIGI_AUTODETECT & MIDI_AUTODETECT
 #include "ac/gamesetup.h"
 
+namespace AGS3 {
+
 GameSetup::GameSetup() {
 	digicard = DIGI_AUTODETECT;
 	midicard = MIDI_AUTODETECT;
@@ -50,3 +52,5 @@ GameSetup::GameSetup() {
 	Screen.FsGameFrame = GameFrameSetup(kFrame_MaxProportional);
 	Screen.WinGameFrame = GameFrameSetup(kFrame_MaxRound);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/gamestate.cpp b/engines/ags/engine/ac/gamestate.cpp
index 73c0d7cf93..aa1d3749d2 100644
--- a/engines/ags/engine/ac/gamestate.cpp
+++ b/engines/ags/engine/ac/gamestate.cpp
@@ -39,6 +39,8 @@
 #include "util/alignedstream.h"
 #include "util/string_utils.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -367,7 +369,7 @@ bool GameState::IsNonBlockingVoiceSpeech() const {
 
 bool GameState::ShouldPlayVoiceSpeech() const {
 	return !play.fast_forward &&
-	       (play.want_speech >= 1) && (!ResPaths.SpeechPak.Name.IsEmpty());
+		(play.want_speech >= 1) && (!ResPaths.SpeechPak.Name.IsEmpty());
 }
 
 void GameState::ReadFromSavegame(Common::Stream *in, GameStateSvgVersion svg_ver, RestoredData &r_data) {
@@ -848,6 +850,8 @@ HorAlignment ConvertLegacyScriptAlignment(LegacyScriptAlignment align) {
 // Alignment constants in the Script API and still support old version.
 HorAlignment ReadScriptAlignment(int32_t align) {
 	return game.options[OPT_BASESCRIPTAPI] < kScriptAPI_v350 ?
-	       ConvertLegacyScriptAlignment((LegacyScriptAlignment)align) :
-	       (HorAlignment)align;
+		ConvertLegacyScriptAlignment((LegacyScriptAlignment)align) :
+		(HorAlignment)align;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_api.cpp b/engines/ags/engine/ac/global_api.cpp
index 1f6a96790c..5a36bf5de6 100644
--- a/engines/ags/engine/ac/global_api.cpp
+++ b/engines/ags/engine/ac/global_api.cpp
@@ -81,6 +81,9 @@
 #include "media/audio/audio_system.h"
 
 #include "ac/dynobj/scriptstring.h"
+
+namespace AGS3 {
+
 extern ScriptString myScriptStringImpl;
 
 // void (char*texx, ...)
@@ -2691,3 +2694,5 @@ void RegisterGlobalAPI() {
 	ccAddExternalFunctionForPlugin("WaitKey", (void *)WaitKey);
 	ccAddExternalFunctionForPlugin("WaitMouseKey", (void *)WaitMouseKey);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_audio.cpp b/engines/ags/engine/ac/global_audio.cpp
index 5f83560d30..06de369d83 100644
--- a/engines/ags/engine/ac/global_audio.cpp
+++ b/engines/ags/engine/ac/global_audio.cpp
@@ -36,6 +36,8 @@
 #include "ac/timer.h"
 #include "util/string_compat.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern GameSetup usetup;
@@ -69,7 +71,7 @@ void PlayAmbientSound(int channel, int sndnum, int vol, int x, int y) {
 
 	// only play the sound if it's not already playing
 	if ((ambient[channel].channel < 1) || (!channel_is_playing(ambient[channel].channel)) ||
-	        (ambient[channel].num != sndnum)) {
+		(ambient[channel].num != sndnum)) {
 
 		StopAmbientSound(channel);
 		// in case a normal non-ambient sound was playing, stop it too
@@ -241,7 +243,7 @@ int PlayMusicQueued(int musnum) {
 	}
 
 	if ((play.music_queue_size > 0) &&
-	        (play.music_queue[play.music_queue_size - 1] >= QUEUED_MUSIC_REPEAT)) {
+		(play.music_queue[play.music_queue_size - 1] >= QUEUED_MUSIC_REPEAT)) {
 		debug_script_warn("PlayMusicQueued: cannot queue music after a repeating tune has been queued");
 		return 0;
 	}
@@ -325,7 +327,7 @@ void SetMusicVolume(int newvol) {
 
 void SetMusicMasterVolume(int newvol) {
 	const int min_volume = loaded_game_file_version < kGameVersion_330 ? 0 :
-	                       -LegacyMusicMasterVolumeAdjustment - (kRoomVolumeMax * LegacyRoomVolumeFactor);
+		-LegacyMusicMasterVolumeAdjustment - (kRoomVolumeMax * LegacyRoomVolumeFactor);
 	if ((newvol < min_volume) | (newvol > 100))
 		quitprintf("!SetMusicMasterVolume: invalid volume - must be from %d to %d", min_volume, 100);
 	play.music_master_volume = newvol + LegacyMusicMasterVolumeAdjustment;
@@ -667,3 +669,5 @@ void stop_voice_nonblocking() {
 		play.speech_voice_blocking = false;
 	}
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_button.cpp b/engines/ags/engine/ac/global_button.cpp
index f6aa71a5b2..5e78ed739a 100644
--- a/engines/ags/engine/ac/global_button.cpp
+++ b/engines/ags/engine/ac/global_button.cpp
@@ -28,6 +28,8 @@
 #include "gui/guimain.h"
 #include "gui/guibutton.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern GameSetupStruct game;
@@ -100,3 +102,5 @@ void SetButtonPic(int guin, int objn, int ptype, int slotn) {
 		Button_SetPushedGraphic(guil, slotn);
 	}
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_character.cpp b/engines/ags/engine/ac/global_character.cpp
index 389efea22d..e5098d258e 100644
--- a/engines/ags/engine/ac/global_character.cpp
+++ b/engines/ags/engine/ac/global_character.cpp
@@ -47,6 +47,8 @@
 #include "main/game_run.h"
 #include "script/script.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 
@@ -115,8 +117,8 @@ int GetCharacterWidth(int ww) {
 
 	if (charextra[ww].width < 1) {
 		if ((char1->view < 0) ||
-		        (char1->loop >= views[char1->view].numLoops) ||
-		        (char1->frame >= views[char1->view].loops[char1->loop].numFrames)) {
+			(char1->loop >= views[char1->view].numLoops) ||
+			(char1->frame >= views[char1->view].loops[char1->loop].numFrames)) {
 			debug_script_warn("GetCharacterWidth: Character %s has invalid frame: view %d, loop %d, frame %d", char1->scrname, char1->view + 1, char1->loop, char1->frame);
 			return data_to_game_coord(4);
 		}
@@ -131,8 +133,8 @@ int GetCharacterHeight(int charid) {
 
 	if (charextra[charid].height < 1) {
 		if ((char1->view < 0) ||
-		        (char1->loop >= views[char1->view].numLoops) ||
-		        (char1->frame >= views[char1->view].loops[char1->loop].numFrames)) {
+			(char1->loop >= views[char1->view].numLoops) ||
+			(char1->frame >= views[char1->view].loops[char1->loop].numFrames)) {
 			debug_script_warn("GetCharacterHeight: Character %s has invalid frame: view %d, loop %d, frame %d", char1->scrname, char1->view + 1, char1->loop, char1->frame);
 			return data_to_game_coord(2);
 		}
@@ -555,10 +557,12 @@ int DisplaySpeechBackground(int charid, const char *speel) {
 	}
 
 	int ovrl = CreateTextOverlay(OVR_AUTOPLACE, charid, play.GetUIViewport().GetWidth() / 2, FONT_SPEECH,
-	                             -game.chars[charid].talkcolor, get_translation(speel), DISPLAYTEXT_NORMALOVERLAY);
+		-game.chars[charid].talkcolor, get_translation(speel), DISPLAYTEXT_NORMALOVERLAY);
 
 	int scid = find_overlay_of_type(ovrl);
 	screenover[scid].bgSpeechForChar = charid;
 	screenover[scid].timeout = GetTextDisplayTime(speel, 1);
 	return ovrl;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_datetime.cpp b/engines/ags/engine/ac/global_datetime.cpp
index 619e678a47..11db83ec94 100644
--- a/engines/ags/engine/ac/global_datetime.cpp
+++ b/engines/ags/engine/ac/global_datetime.cpp
@@ -25,6 +25,8 @@
 #include "ac/datetime.h"
 #include "ac/common.h"
 
+namespace AGS3 {
+
 int sc_GetTime(int whatti) {
 	ScriptDateTime *sdt = DateTime_Now_Core();
 	int returnVal = 0;
@@ -46,3 +48,5 @@ int GetRawTime() {
 	// TODO: we might need to modify script API to support larger time type
 	return static_cast<int>(time(nullptr));
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_debug.cpp b/engines/ags/engine/ac/global_debug.cpp
index be28d50e1f..87f13bddf2 100644
--- a/engines/ags/engine/ac/global_debug.cpp
+++ b/engines/ags/engine/ac/global_debug.cpp
@@ -47,6 +47,8 @@
 #include "gfx/graphicsdriver.h"
 #include "main/graphics_mode.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -69,16 +71,16 @@ String GetRuntimeInfo() {
 	Rect render_frame = gfxDriver->GetRenderDestination();
 	PGfxFilter filter = gfxDriver->GetGraphicsFilter();
 	String runtimeInfo = String::FromFormat(
-	                         "Adventure Game Studio run-time engine[ACI version %s"
-	                         "[Game resolution %d x %d (%d-bit)"
-	                         "[Running %d x %d at %d-bit%s%s[GFX: %s; %s[Draw frame %d x %d["
-	                         "Sprite cache size: %d KB (limit %d KB; %d locked)",
-	                         EngineVersion.LongString.GetCStr(), game.GetGameRes().Width, game.GetGameRes().Height, game.GetColorDepth(),
-	                         mode.Width, mode.Height, mode.ColorDepth, (convert_16bit_bgr) ? " BGR" : "",
-	                         mode.Windowed ? " W" : "",
-	                         gfxDriver->GetDriverName(), filter->GetInfo().Name.GetCStr(),
-	                         render_frame.GetWidth(), render_frame.GetHeight(),
-	                         spriteset.GetCacheSize() / 1024, spriteset.GetMaxCacheSize() / 1024, spriteset.GetLockedSize() / 1024);
+		"Adventure Game Studio run-time engine[ACI version %s"
+		"[Game resolution %d x %d (%d-bit)"
+		"[Running %d x %d at %d-bit%s%s[GFX: %s; %s[Draw frame %d x %d["
+		"Sprite cache size: %d KB (limit %d KB; %d locked)",
+		EngineVersion.LongString.GetCStr(), game.GetGameRes().Width, game.GetGameRes().Height, game.GetColorDepth(),
+		mode.Width, mode.Height, mode.ColorDepth, (convert_16bit_bgr) ? " BGR" : "",
+		mode.Windowed ? " W" : "",
+		gfxDriver->GetDriverName(), filter->GetInfo().Name.GetCStr(),
+		render_frame.GetWidth(), render_frame.GetHeight(),
+		spriteset.GetCacheSize() / 1024, spriteset.GetMaxCacheSize() / 1024, spriteset.GetLockedSize() / 1024);
 	if (play.separate_music_lib)
 		runtimeInfo.Append("[AUDIO.VOX enabled");
 	if (play.want_speech >= 1)
@@ -185,3 +187,5 @@ void script_debug(int cmdd, int dataa) {
 		ccSetOption(SCOPT_DEBUGRUN, dataa);
 	else quit("!Debug: unknown command code");
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_dialog.cpp b/engines/ags/engine/ac/global_dialog.cpp
index ff9240615b..b2b95c497e 100644
--- a/engines/ags/engine/ac/global_dialog.cpp
+++ b/engines/ags/engine/ac/global_dialog.cpp
@@ -31,6 +31,8 @@
 #include "debug/out.h"
 #include "script/script.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern GameSetupStruct game;
@@ -49,7 +51,7 @@ void RunDialog(int tum) {
 			play.stop_dialog_at_end = DIALOG_NEWTOPIC + tum;
 		else
 			quitprintf("!RunDialog: two NewRoom/RunDialog/StopDialog requests within dialog; last was called in \"%s\", line %d",
-			           last_in_dialog_request_script_pos.Section.GetCStr(), last_in_dialog_request_script_pos.Line);
+				last_in_dialog_request_script_pos.Section.GetCStr(), last_in_dialog_request_script_pos.Line);
 		return;
 	}
 
@@ -106,3 +108,5 @@ int GetDialogOption(int dlg, int opt) {
 		return 1;
 	return 0;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_display.cpp b/engines/ags/engine/ac/global_display.cpp
index 1ac54d54ff..7aa5326bc2 100644
--- a/engines/ags/engine/ac/global_display.cpp
+++ b/engines/ags/engine/ac/global_display.cpp
@@ -41,6 +41,8 @@
 #include "game/roomstruct.h"
 #include "main/game_run.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern TopBarSettings topBar;
@@ -113,8 +115,8 @@ void DisplayMessageAtY(int msnum, int ypos) {
 	if (display_message_aschar > 0) {
 		display_message_aschar = 0;
 		quit("!DisplayMessage: data column specified a character for local\n"
-		     "message; use the message editor to select the character for room\n"
-		     "messages.\n");
+			"message; use the message editor to select the character for room\n"
+			"messages.\n");
 	}
 
 	int repeatloop = 1;
@@ -174,13 +176,13 @@ void DisplayAtY(int ypos, const char *texx) {
 
 		if (is_screen_dirty()) {
 			// erase any previous DisplaySpeech
-			play.disabled_user_interface ++;
+			play.disabled_user_interface++;
 			UpdateGameOnce();
-			play.disabled_user_interface --;
+			play.disabled_user_interface--;
 		}
 
 		_display_at(-1, ypos, ui_view.GetWidth() / 2 + ui_view.GetWidth() / 4,
-		            get_translation(texx), DISPLAYTEXT_MESSAGEBOX, 0, 0, 0, false);
+			get_translation(texx), DISPLAYTEXT_MESSAGEBOX, 0, 0, 0, false);
 	}
 }
 
@@ -201,3 +203,5 @@ void SetSkipSpeech(SkipSpeechStyle newval) {
 SkipSpeechStyle GetSkipSpeech() {
 	return internal_skip_speech_to_user(play.cant_skip_speech);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_drawingsurface.cpp b/engines/ags/engine/ac/global_drawingsurface.cpp
index f5556e7a07..36d19cb0e8 100644
--- a/engines/ags/engine/ac/global_drawingsurface.cpp
+++ b/engines/ags/engine/ac/global_drawingsurface.cpp
@@ -37,6 +37,8 @@
 #include "gfx/gfx_def.h"
 #include "gfx/gfx_util.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -78,8 +80,8 @@ void RawRestoreScreenTinted(int red, int green, int blue, int opacity) {
 		return;
 	}
 	if ((red < 0) || (green < 0) || (blue < 0) ||
-	        (red > 255) || (green > 255) || (blue > 255) ||
-	        (opacity < 1) || (opacity > 100))
+		(red > 255) || (green > 255) || (blue > 255) ||
+		(opacity < 1) || (opacity > 100))
 		quit("!RawRestoreScreenTinted: invalid parameter. R,G,B must be 0-255, opacity 1-100");
 
 	debug_script_log("RawRestoreTinted RGB(%d,%d,%d) %d%%", red, green, blue, opacity);
@@ -92,7 +94,7 @@ void RawRestoreScreenTinted(int red, int green, int blue, int opacity) {
 
 void RawDrawFrameTransparent(int frame, int translev) {
 	if ((frame < 0) || ((size_t)frame >= thisroom.BgFrameCount) ||
-	        (translev < 0) || (translev > 99))
+		(translev < 0) || (translev > 99))
 		quit("!RawDrawFrameTransparent: invalid parameter (transparency must be 0-99, frame a valid BG frame)");
 
 	PBitmap bg = thisroom.BgFrames[frame].Graphic;
@@ -109,7 +111,7 @@ void RawDrawFrameTransparent(int frame, int translev) {
 	} else {
 		// Draw it transparently
 		GfxUtil::DrawSpriteWithTransparency(RAW_SURFACE(), bg.get(), 0, 0,
-		                                    GfxDef::Trans100ToAlpha255(translev));
+			GfxDef::Trans100ToAlpha255(translev));
 	}
 	invalidate_screen();
 	mark_current_background_dirty();
@@ -129,7 +131,7 @@ void RawSetColor(int clr) {
 }
 void RawSetColorRGB(int red, int grn, int blu) {
 	if ((red < 0) || (red > 255) || (grn < 0) || (grn > 255) ||
-	        (blu < 0) || (blu > 255))
+		(blu < 0) || (blu > 255))
 		quit("!RawSetColorRGB: colour values must be 0-255");
 
 	play.raw_color = makecol_depth(thisroom.BgFrames[play.bg_frame].Graphic->GetColorDepth(), red, grn, blu);
@@ -243,8 +245,8 @@ void RawDrawImageResized(int xx, int yy, int gotSlot, int width, int height) {
 	// resize the sprite to the requested size
 	Bitmap *newPic = BitmapHelper::CreateBitmap(width, height, spriteset[gotSlot]->GetColorDepth());
 	newPic->StretchBlt(spriteset[gotSlot],
-	                   RectWH(0, 0, game.SpriteInfos[gotSlot].Width, game.SpriteInfos[gotSlot].Height),
-	                   RectWH(0, 0, width, height));
+		RectWH(0, 0, game.SpriteInfos[gotSlot].Width, game.SpriteInfos[gotSlot].Height),
+		RectWH(0, 0, width, height));
 
 	RAW_START();
 	if (newPic->GetColorDepth() != RAW_SURFACE()->GetColorDepth())
@@ -304,3 +306,5 @@ void RawDrawTriangle(int x1, int y1, int x2, int y2, int x3, int y3) {
 	invalidate_screen();
 	mark_current_background_dirty();
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_dynamicsprite.cpp b/engines/ags/engine/ac/global_dynamicsprite.cpp
index d5380a1993..b4019f1a35 100644
--- a/engines/ags/engine/ac/global_dynamicsprite.cpp
+++ b/engines/ags/engine/ac/global_dynamicsprite.cpp
@@ -30,6 +30,8 @@
 #include "gfx/graphicsdriver.h"
 #include "gfx/bitmap.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -55,3 +57,5 @@ int LoadImageFile(const char *filename) {
 
 	return gotSlot;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_file.cpp b/engines/ags/engine/ac/global_file.cpp
index 9b29b396d9..94b1c7ef46 100644
--- a/engines/ags/engine/ac/global_file.cpp
+++ b/engines/ags/engine/ac/global_file.cpp
@@ -32,6 +32,8 @@
 #include "util/path.h"
 #include "util/stream.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 int32_t FileOpenCMode(const char *fnmm, const char *cmode) {
@@ -57,7 +59,7 @@ int32_t FindFreeFileSlot() {
 	}
 
 	if (useindx >= num_open_script_files &&
-	        num_open_script_files >= MAX_OPEN_SCRIPT_FILES) {
+		num_open_script_files >= MAX_OPEN_SCRIPT_FILES) {
 		quit("!FileOpen: tried to open more than 10 files simultaneously - close some first");
 		return -1;
 	}
@@ -174,3 +176,5 @@ void FileWriteRawChar(int32_t handle, int chartoWrite) {
 
 	out->WriteInt8(chartoWrite);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_game.cpp b/engines/ags/engine/ac/global_game.cpp
index 306a63832a..8d2c9a36a5 100644
--- a/engines/ags/engine/ac/global_game.cpp
+++ b/engines/ags/engine/ac/global_game.cpp
@@ -69,6 +69,8 @@
 #include "util/string_utils.h"
 #include "media/audio/audio_system.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 #define ALLEGRO_KEYBOARD_HANDLER
@@ -187,8 +189,8 @@ int LoadSaveSlotScreenshot(int slnum, int width, int height) {
 	// resize the sprite to the requested size
 	Bitmap *newPic = BitmapHelper::CreateBitmap(width, height, spriteset[gotSlot]->GetColorDepth());
 	newPic->StretchBlt(spriteset[gotSlot],
-	                   RectWH(0, 0, game.SpriteInfos[gotSlot].Width, game.SpriteInfos[gotSlot].Height),
-	                   RectWH(0, 0, width, height));
+		RectWH(0, 0, game.SpriteInfos[gotSlot].Width, game.SpriteInfos[gotSlot].Height),
+		RectWH(0, 0, width, height));
 
 	update_polled_stuff_if_runtime();
 
@@ -319,7 +321,8 @@ int GetGameParameter(int parm, int data1, int data2, int data3) {
 	case GP_FRAMESPEED:
 	case GP_FRAMEIMAGE:
 	case GP_FRAMESOUND:
-	case GP_ISFRAMEFLIPPED: {
+	case GP_ISFRAMEFLIPPED:
+	{
 		if ((data1 < 1) || (data1 > game.numviews)) {
 			quitprintf("!GetGameParameter: invalid view specified (v: %d, l: %d, f: %d)", data1, data2, data3);
 		}
@@ -464,7 +467,7 @@ void StartCutscene(int skipwith) {
 
 	if (is_in_cutscene()) {
 		quitprintf("!StartCutscene: already in a cutscene; previous started in \"%s\", line %d",
-		           last_cutscene_script_pos.Section.GetCStr(), last_cutscene_script_pos.Line);
+			last_cutscene_script_pos.Section.GetCStr(), last_cutscene_script_pos.Line);
 	}
 
 	if ((skipwith < 1) || (skipwith > 6))
@@ -646,7 +649,7 @@ int IsKeyPressed(int keycode) {
 	case eAGSKeyCodeCloseBracket:
 		return ags_iskeypressed(__allegro_KEY_CLOSEBRACE);
 		break;
-	// NOTE: we're treating EQUALS like PLUS, even though it is only available shifted.
+		// NOTE: we're treating EQUALS like PLUS, even though it is only available shifted.
 	case eAGSKeyCodePlus:
 		return ags_iskeypressed(__allegro_KEY_EQUALS) || ags_iskeypressed(__allegro_KEY_PLUS_PAD);
 		break;
@@ -654,7 +657,7 @@ int IsKeyPressed(int keycode) {
 		return ags_iskeypressed(__allegro_KEY_MINUS) || ags_iskeypressed(__allegro_KEY_MINUS_PAD);
 		break;
 
-	// non-shifted versions of keys
+		// non-shifted versions of keys
 	case eAGSKeyCodeColon:
 		return ags_iskeypressed(__allegro_KEY_COLON) || ags_iskeypressed(__allegro_KEY_COLON2);
 		break;
@@ -846,8 +849,8 @@ int IsKeyPressed(int keycode) {
 		return ags_iskeypressed(__allegro_KEY_DEL) || ags_iskeypressed(__allegro_KEY_DEL_PAD);
 		break;
 
-	// These keys are not defined in the eAGSKey enum but are in the manual
-	// https://adventuregamestudio.github.io/ags-manual/ASCIIcodes.html
+		// These keys are not defined in the eAGSKey enum but are in the manual
+		// https://adventuregamestudio.github.io/ags-manual/ASCIIcodes.html
 
 	case 403:
 		return ags_iskeypressed(__allegro_KEY_LSHIFT);
@@ -865,9 +868,9 @@ int IsKeyPressed(int keycode) {
 		return ags_iskeypressed(__allegro_KEY_ALT);
 		break;
 
-	// (noted here for interest)
-	// The following are the AGS_EXT_KEY_SHIFT, derived from applying arithmetic to the original keycodes.
-	// These do not have a corresponding ags key enum, do not appear in the manual and may not be accessible because of OS contraints.
+		// (noted here for interest)
+		// The following are the AGS_EXT_KEY_SHIFT, derived from applying arithmetic to the original keycodes.
+		// These do not have a corresponding ags key enum, do not appear in the manual and may not be accessible because of OS contraints.
 
 	case 392:
 		return ags_iskeypressed(__allegro_KEY_PRTSCR);
@@ -918,10 +921,10 @@ int IsKeyPressed(int keycode) {
 		return ags_iskeypressed(__allegro_KEY_CAPSLOCK);
 		break;
 
-	// Allegro4 keys that were never supported:
-	// __allegro_KEY_COMMAND
-	// __allegro_KEY_TILDE
-	// __allegro_KEY_BACKQUOTE
+		// Allegro4 keys that were never supported:
+		// __allegro_KEY_COMMAND
+		// __allegro_KEY_TILDE
+		// __allegro_KEY_BACKQUOTE
 
 	default:
 		// Remaining Allegro4 keycodes are offset by AGS_EXT_KEY_SHIFT
@@ -996,9 +999,9 @@ void RoomProcessClick(int xx, int yy, int mood) {
 
 	if ((mood == MODE_WALK) && (game.options[OPT_NOWALKMODE] == 0)) {
 		int hsnum = get_hotspot_at(xx, yy);
-		if (hsnum < 1) ;
-		else if (thisroom.Hotspots[hsnum].WalkTo.X < 1) ;
-		else if (play.auto_use_walkto_points == 0) ;
+		if (hsnum < 1);
+		else if (thisroom.Hotspots[hsnum].WalkTo.X < 1);
+		else if (play.auto_use_walkto_points == 0);
 		else {
 			xx = thisroom.Hotspots[hsnum].WalkTo.X;
 			yy = thisroom.Hotspots[hsnum].WalkTo.Y;
@@ -1142,3 +1145,5 @@ int WaitMouseKey(int nloops) {
 void SkipWait() {
 	play.wait_counter = 0;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_gui.cpp b/engines/ags/engine/ac/global_gui.cpp
index d8a0cdc010..e5481f541d 100644
--- a/engines/ags/engine/ac/global_gui.cpp
+++ b/engines/ags/engine/ac/global_gui.cpp
@@ -36,6 +36,8 @@
 #include "script/runtimescriptvalue.h"
 #include "util/string_compat.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern GameSetupStruct game;
@@ -252,7 +254,7 @@ void SetTextWindowGUI(int guinum) {
 	if ((guinum < -1) | (guinum >= game.numgui))
 		quit("!SetTextWindowGUI: invalid GUI number");
 
-	if (guinum < 0) ;  // disable it
+	if (guinum < 0);  // disable it
 	else if (!guis[guinum].IsTextWindow())
 		quit("!SetTextWindowGUI: specified GUI is not a text window");
 
@@ -260,3 +262,5 @@ void SetTextWindowGUI(int guinum) {
 		play.speech_textwindow_gui = guinum;
 	game.options[OPT_TWCUSTOM] = guinum;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_hotspot.cpp b/engines/ags/engine/ac/global_hotspot.cpp
index a145d74bd8..747b169670 100644
--- a/engines/ags/engine/ac/global_hotspot.cpp
+++ b/engines/ags/engine/ac/global_hotspot.cpp
@@ -37,6 +37,8 @@
 #include "game/roomstruct.h"
 #include "script/script.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern RoomStruct thisroom;
@@ -109,8 +111,8 @@ void RunHotspotInteraction(int hotspothere, int mood) {
 		play.usedinv = cdata;
 	}
 
-	if ((game.options[OPT_WALKONLOOK] == 0) & (mood == MODE_LOOK)) ;
-	else if (play.auto_use_walkto_points == 0) ;
+	if ((game.options[OPT_WALKONLOOK] == 0) & (mood == MODE_LOOK));
+	else if (play.auto_use_walkto_points == 0);
 	else if ((mood != MODE_WALK) && (play.check_interaction_only == 0))
 		MoveCharacterToHotspot(game.playercharacter, hotspothere);
 
@@ -149,3 +151,5 @@ int GetHotspotProperty(int hss, const char *property) {
 void GetHotspotPropertyText(int item, const char *property, char *bufer) {
 	get_text_property(thisroom.Hotspots[item].Properties, croom->hsProps[item], property, bufer);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_inventoryitem.cpp b/engines/ags/engine/ac/global_inventoryitem.cpp
index 7de499ee5b..45f2b1170d 100644
--- a/engines/ags/engine/ac/global_inventoryitem.cpp
+++ b/engines/ags/engine/ac/global_inventoryitem.cpp
@@ -34,6 +34,8 @@
 #include "ac/event.h"
 #include "ac/gamestate.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern GameSetupStruct game;
@@ -148,3 +150,5 @@ int GetInvProperty(int item, const char *property) {
 void GetInvPropertyText(int item, const char *property, char *bufer) {
 	get_text_property(game.invProps[item], play.invProps[item], property, bufer);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_invwindow.cpp b/engines/ags/engine/ac/global_invwindow.cpp
index 4433a1b347..64553f430f 100644
--- a/engines/ags/engine/ac/global_invwindow.cpp
+++ b/engines/ags/engine/ac/global_invwindow.cpp
@@ -27,6 +27,8 @@
 #include "gui/guiinv.h"
 #include "script/executingscript.h"
 
+namespace AGS3 {
+
 extern ExecutingScript *curscript;
 extern GameState play;
 
@@ -46,3 +48,5 @@ void SetInvDimensions(int ww, int hh) {
 	}
 	guis_need_update = 1;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_label.cpp b/engines/ags/engine/ac/global_label.cpp
index 5561a7a63a..770a1f971d 100644
--- a/engines/ags/engine/ac/global_label.cpp
+++ b/engines/ags/engine/ac/global_label.cpp
@@ -27,6 +27,8 @@
 #include "ac/string.h"
 #include "gui/guimain.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern GameSetupStruct game;
@@ -64,3 +66,5 @@ void SetLabelFont(int guin, int objn, int fontnum) {
 	GUILabel *guil = (GUILabel *)guis[guin].GetControl(objn);
 	Label_SetFont(guil, fontnum);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_listbox.cpp b/engines/ags/engine/ac/global_listbox.cpp
index 99c3938dd2..935927cbe5 100644
--- a/engines/ags/engine/ac/global_listbox.cpp
+++ b/engines/ags/engine/ac/global_listbox.cpp
@@ -25,6 +25,8 @@
 #include "ac/listbox.h"
 #include "ac/string.h"
 
+namespace AGS3 {
+
 void ListBoxClear(int guin, int objn) {
 	GUIListBox *guisl = is_valid_listbox(guin, objn);
 	ListBox_Clear(guisl);
@@ -68,3 +70,5 @@ void ListBoxDirList(int guin, int objn, const char *filemask) {
 	GUIListBox *guisl = is_valid_listbox(guin, objn);
 	ListBox_FillDirList(guisl, filemask);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_mouse.cpp b/engines/ags/engine/ac/global_mouse.cpp
index af75346610..8b0e30bf53 100644
--- a/engines/ags/engine/ac/global_mouse.cpp
+++ b/engines/ags/engine/ac/global_mouse.cpp
@@ -23,6 +23,8 @@
 #include "ac/global_mouse.h"
 #include "ac/gamestate.h"
 
+namespace AGS3 {
+
 extern GameState play;
 
 void HideMouseCursor() {
@@ -32,3 +34,5 @@ void HideMouseCursor() {
 void ShowMouseCursor() {
 	play.mouse_cursor_hidden = 0;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_object.cpp b/engines/ags/engine/ac/global_object.cpp
index 53cae9bb3d..4feb25f4fa 100644
--- a/engines/ags/engine/ac/global_object.cpp
+++ b/engines/ags/engine/ac/global_object.cpp
@@ -45,6 +45,8 @@
 #include "gfx/bitmap.h"
 #include "gfx/gfx_def.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 #define OVERLAPPING_OBJECT 1000
@@ -60,7 +62,7 @@ extern int displayed_room;
 extern SpriteCache spriteset;
 extern int actSpsCount;
 extern Bitmap **actsps;
-extern IDriverDependantBitmap * *actspsbmp;
+extern IDriverDependantBitmap **actspsbmp;
 extern IGraphicsDriver *gfxDriver;
 
 // Used for deciding whether a char or obj was closer
@@ -91,7 +93,7 @@ int GetObjectIDAtRoom(int roomx, int roomy) {
 		Bitmap *theImage = GetObjectImage(aa, &isflipped);
 
 		if (is_pos_in_sprite(roomx, roomy, xxx, yyy - spHeight, theImage,
-		                     spWidth, spHeight, isflipped) == FALSE)
+			spWidth, spHeight, isflipped) == FALSE)
 			continue;
 
 		int usebasel = objs[aa].get_baseline();
@@ -106,9 +108,9 @@ int GetObjectIDAtRoom(int roomx, int roomy) {
 
 void SetObjectTint(int obj, int red, int green, int blue, int opacity, int luminance) {
 	if ((red < 0) || (green < 0) || (blue < 0) ||
-	        (red > 255) || (green > 255) || (blue > 255) ||
-	        (opacity < 0) || (opacity > 100) ||
-	        (luminance < 0) || (luminance > 100))
+		(red > 255) || (green > 255) || (blue > 255) ||
+		(opacity < 0) || (opacity > 100) ||
+		(luminance < 0) || (luminance > 100))
 		quit("!SetObjectTint: invalid parameter. R,G,B must be 0-255, opacity & luminance 0-100");
 
 	if (!is_valid_object(obj))
@@ -473,7 +475,7 @@ int AreThingsOverlapping(int thing1, int thing2) {
 		return 0;
 
 	if ((r1.x2 > r2.x1) && (r1.x1 < r2.x2) &&
-	        (r1.y2 > r2.y1) && (r1.y1 < r2.y2)) {
+		(r1.y2 > r2.y1) && (r1.y1 < r2.y2)) {
 		// determine how far apart they are
 		// take the smaller of the X distances as the overlapping amount
 		int xdist = abs(r1.x2 - r2.x1);
@@ -515,3 +517,5 @@ Bitmap *GetObjectImage(int obj, int *isFlipped) {
 	}
 	return spriteset[objs[obj].num];
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_overlay.cpp b/engines/ags/engine/ac/global_overlay.cpp
index 572a71cba5..ddc79f0554 100644
--- a/engines/ags/engine/ac/global_overlay.cpp
+++ b/engines/ags/engine/ac/global_overlay.cpp
@@ -35,6 +35,8 @@
 #include "ac/system.h"
 #include "gfx/bitmap.h"
 
+namespace AGS3 {
+
 using namespace Shared;
 using namespace Engine;
 
@@ -99,3 +101,5 @@ int IsOverlayValid(int ovrid) {
 
 	return 1;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_palette.cpp b/engines/ags/engine/ac/global_palette.cpp
index 25daf644a9..63a4f741e7 100644
--- a/engines/ags/engine/ac/global_palette.cpp
+++ b/engines/ags/engine/ac/global_palette.cpp
@@ -26,6 +26,8 @@
 #include "ac/gamestate.h"
 #include "ac/global_palette.h"
 
+namespace AGS3 {
+
 extern GameSetupStruct game;
 extern GameState play;
 extern color palette[256];
@@ -72,3 +74,5 @@ void UpdatePalette() {
 	if (!play.fast_forward)
 		setpal();
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_parser.cpp b/engines/ags/engine/ac/global_parser.cpp
index 54bcb0852d..6ae278cd18 100644
--- a/engines/ags/engine/ac/global_parser.cpp
+++ b/engines/ags/engine/ac/global_parser.cpp
@@ -26,6 +26,8 @@
 #include "ac/gamestate.h"
 #include "ac/string.h"
 
+namespace AGS3 {
+
 extern GameState play;
 
 int SaidUnknownWord(char *buffer) {
@@ -35,3 +37,5 @@ int SaidUnknownWord(char *buffer) {
 		return 0;
 	return 1;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_record.cpp b/engines/ags/engine/ac/global_record.cpp
index ef251f9ebf..9f2358045d 100644
--- a/engines/ags/engine/ac/global_record.cpp
+++ b/engines/ags/engine/ac/global_record.cpp
@@ -23,6 +23,10 @@
 #include "ac/global_record.h"
 #include "ac/common.h"
 
+namespace AGS3 {
+
 void scStartRecording(int keyToStop) {
 	quit("!StartRecording: not supported");
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_region.cpp b/engines/ags/engine/ac/global_region.cpp
index e02e28e582..e607e353c5 100644
--- a/engines/ags/engine/ac/global_region.cpp
+++ b/engines/ags/engine/ac/global_region.cpp
@@ -31,6 +31,7 @@
 #include "gfx/bitmap.h"
 #include "script/script.h"
 
+namespace AGS3 {
 
 using namespace AGS::Shared;
 
@@ -70,7 +71,7 @@ void SetAreaLightLevel(int area, int brightness) {
 	if (brightness > 100) brightness = 100;
 	thisroom.Regions[area].Light = brightness;
 	// disable RGB tint for this area
-	thisroom.Regions[area].Tint  = 0;
+	thisroom.Regions[area].Tint = 0;
 	debug_script_log("Region %d light level set to %d", area, brightness);
 }
 
@@ -79,7 +80,7 @@ void SetRegionTint(int area, int red, int green, int blue, int amount, int lumin
 		quit("!SetRegionTint: invalid region");
 
 	if ((red < 0) || (red > 255) || (green < 0) || (green > 255) ||
-	        (blue < 0) || (blue > 255)) {
+		(blue < 0) || (blue > 255)) {
 		quit("!SetRegionTint: RGB values must be 0-255");
 	}
 
@@ -100,9 +101,9 @@ void SetRegionTint(int area, int red, int green, int blue, int amount, int lumin
 	blue -= 100;*/
 
 	thisroom.Regions[area].Tint = (red & 0xFF) |
-	                              ((green & 0xFF) << 8) |
-	                              ((blue & 0XFF) << 16) |
-	                              ((amount & 0xFF) << 24);
+		((green & 0xFF) << 8) |
+		((blue & 0XFF) << 16) |
+		((amount & 0xFF) << 24);
 	thisroom.Regions[area].Light = (luminance * 25) / 10;
 }
 
@@ -165,3 +166,5 @@ void RunRegionInteraction(int regnum, int mood) {
 	evblockbasename = oldbasename;
 	evblocknum = oldblocknum;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_room.cpp b/engines/ags/engine/ac/global_room.cpp
index 1b55d8f42e..7fadb5a72b 100644
--- a/engines/ags/engine/ac/global_room.cpp
+++ b/engines/ags/engine/ac/global_room.cpp
@@ -39,6 +39,8 @@
 #include "script/script.h"
 #include "util/math.h"
 
+namespace AGS3 {
+
 using namespace Shared;
 
 extern GameState play;
@@ -55,9 +57,9 @@ extern RoomStruct thisroom;
 
 void SetAmbientTint(int red, int green, int blue, int opacity, int luminance) {
 	if ((red < 0) || (green < 0) || (blue < 0) ||
-	        (red > 255) || (green > 255) || (blue > 255) ||
-	        (opacity < 0) || (opacity > 100) ||
-	        (luminance < 0) || (luminance > 100))
+		(red > 255) || (green > 255) || (blue > 255) ||
+		(opacity < 0) || (opacity > 100) ||
+		(luminance < 0) || (luminance > 100))
 		quit("!SetTint: invalid parameter. R,G,B must be 0-255, opacity & luminance 0-100");
 
 	debug_script_log("Set ambient tint RGB(%d,%d,%d) %d%%", red, green, blue, opacity);
@@ -100,7 +102,7 @@ void NewRoom(int nrnum) {
 			play.stop_dialog_at_end = DIALOG_NEWROOM + nrnum;
 		else {
 			quitprintf("!NewRoom: two NewRoom/RunDialog/StopDialog requests within dialog; last was called in \"%s\", line %d",
-			           last_in_dialog_request_script_pos.Section.GetCStr(), last_in_dialog_request_script_pos.Line);
+				last_in_dialog_request_script_pos.Section.GetCStr(), last_in_dialog_request_script_pos.Line);
 		}
 		return;
 	}
@@ -220,3 +222,5 @@ void SetBackgroundFrame(int frnum) {
 int GetBackgroundFrame() {
 	return play.bg_frame;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_screen.cpp b/engines/ags/engine/ac/global_screen.cpp
index c8cb0f04d9..8ae85266af 100644
--- a/engines/ags/engine/ac/global_screen.cpp
+++ b/engines/ags/engine/ac/global_screen.cpp
@@ -35,6 +35,8 @@
 #include "gfx/graphicsdriver.h"
 #include "gfx/bitmap.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -164,7 +166,7 @@ void SetNextScreenTransition(int newtrans) {
 
 void SetFadeColor(int red, int green, int blue) {
 	if ((red < 0) || (red > 255) || (green < 0) || (green > 255) ||
-	        (blue < 0) || (blue > 255))
+		(blue < 0) || (blue > 255))
 		quit("!SetFadeColor: Red, Green and Blue must be 0-255");
 
 	play.fade_to_red = red;
@@ -180,3 +182,5 @@ void FadeIn(int sppd) {
 
 	my_fade_in(palette, sppd);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_slider.cpp b/engines/ags/engine/ac/global_slider.cpp
index 512af4c99d..b05ddacc0f 100644
--- a/engines/ags/engine/ac/global_slider.cpp
+++ b/engines/ags/engine/ac/global_slider.cpp
@@ -27,6 +27,8 @@
 #include "gui/guimain.h"
 #include "gui/guislider.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern GameSetupStruct game;
@@ -48,3 +50,5 @@ int GetSliderValue(int guin, int objn) {
 	GUISlider *guisl = (GUISlider *)guis[guin].GetControl(objn);
 	return Slider_GetValue(guisl);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_string.cpp b/engines/ags/engine/ac/global_string.cpp
index 7519320129..974b6cea23 100644
--- a/engines/ags/engine/ac/global_string.cpp
+++ b/engines/ags/engine/ac/global_string.cpp
@@ -28,6 +28,8 @@
 #include "ac/string.h"
 #include "util/string_compat.h"
 
+namespace AGS3 {
+
 extern int MAXSTRLEN;
 
 int StrGetCharAt(const char *strin, int posn) {
@@ -79,3 +81,5 @@ void _sc_strcpy(char *destt, const char *text) {
 	check_strlen(destt);
 	my_strncpy(destt, text, MAXSTRLEN - 1);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_textbox.cpp b/engines/ags/engine/ac/global_textbox.cpp
index 8cdbe69b2e..2f2bf556a0 100644
--- a/engines/ags/engine/ac/global_textbox.cpp
+++ b/engines/ags/engine/ac/global_textbox.cpp
@@ -28,6 +28,8 @@
 #include "gui/guimain.h"
 #include "gui/guitextbox.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern GameSetupStruct game;
@@ -63,3 +65,5 @@ void SetTextBoxText(int guin, int objn, const char *txbuf) {
 	GUITextBox *guisl = (GUITextBox *)guis[guin].GetControl(objn);
 	TextBox_SetText(guisl, txbuf);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_timer.cpp b/engines/ags/engine/ac/global_timer.cpp
index cc4373bcc5..04b325961e 100644
--- a/engines/ags/engine/ac/global_timer.cpp
+++ b/engines/ags/engine/ac/global_timer.cpp
@@ -25,6 +25,8 @@
 #include "ac/common.h"
 #include "ac/gamestate.h"
 
+namespace AGS3 {
+
 extern GameState play;
 
 
@@ -43,3 +45,5 @@ int IsTimerExpired(int tnum) {
 	}
 	return 0;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_translation.cpp b/engines/ags/engine/ac/global_translation.cpp
index d2a7b90d23..e27b75dee6 100644
--- a/engines/ags/engine/ac/global_translation.cpp
+++ b/engines/ags/engine/ac/global_translation.cpp
@@ -33,6 +33,8 @@
 #include "util/memory.h"
 #include "core/types.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared::Memory;
 
 extern GameState play;
@@ -89,3 +91,5 @@ int GetTranslationName(char *buffer) {
 
 	return IsTranslationAvailable();
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_video.cpp b/engines/ags/engine/ac/global_video.cpp
index 20582e0dcd..0aa8b375da 100644
--- a/engines/ags/engine/ac/global_video.cpp
+++ b/engines/ags/engine/ac/global_video.cpp
@@ -33,6 +33,7 @@
 #include "platform/base/agsplatformdriver.h"
 #include "util/string_compat.h"
 
+namespace AGS3 {
 
 void scrPlayVideo(const char *name, int skip, int flags) {
 	EndSkippingUntilCharStops();
@@ -83,6 +84,9 @@ void pause_sound_if_necessary_and_play_video(const char *name, int skip, int fla
 
 #else
 
-void pause_sound_if_necessary_and_play_video(const char *name, int skip, int flags) {}
+void pause_sound_if_necessary_and_play_video(const char *name, int skip, int flags) {
+}
 
 #endif
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_viewframe.cpp b/engines/ags/engine/ac/global_viewframe.cpp
index ad5f8da414..8a8f2942cf 100644
--- a/engines/ags/engine/ac/global_viewframe.cpp
+++ b/engines/ags/engine/ac/global_viewframe.cpp
@@ -27,6 +27,8 @@
 #include "debug/debug_log.h"
 #include "media/audio/audio_system.h"
 
+namespace AGS3 {
+
 extern GameSetupStruct game;
 extern ViewStruct *views;
 
@@ -52,3 +54,5 @@ void SetFrameSound(int vii, int loop, int frame, int sound) {
 		views[vii].loops[loop].frames[frame].sound = clip->id + (game.IsLegacyAudioSystem() ? 0x10000000 : 0);
 	}
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_viewport.cpp b/engines/ags/engine/ac/global_viewport.cpp
index cd64d8117c..456c582241 100644
--- a/engines/ags/engine/ac/global_viewport.cpp
+++ b/engines/ags/engine/ac/global_viewport.cpp
@@ -24,6 +24,8 @@
 #include "ac/draw.h"
 #include "debug/debug_log.h"
 
+namespace AGS3 {
+
 void SetViewport(int offsx, int offsy) {
 	offsx = data_to_game_coord(offsx);
 	offsy = data_to_game_coord(offsy);
@@ -38,3 +40,5 @@ int GetViewportX() {
 int GetViewportY() {
 	return game_to_data_coord(play.GetRoomCamera(0)->GetRect().Top);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_walkablearea.cpp b/engines/ags/engine/ac/global_walkablearea.cpp
index bd57d417f7..ca23e25a35 100644
--- a/engines/ags/engine/ac/global_walkablearea.cpp
+++ b/engines/ags/engine/ac/global_walkablearea.cpp
@@ -28,6 +28,8 @@
 #include "debug/debug_log.h"
 #include "game/roomstruct.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern RoomStruct thisroom;
@@ -94,5 +96,4 @@ int GetWalkableAreaAtRoom(int x, int y) {
 	return area >= 0 && area < (MAX_WALK_AREAS + 1) ? area : 0;
 }
 
-//=============================================================================
-
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/global_walkbehind.cpp b/engines/ags/engine/ac/global_walkbehind.cpp
index e48d80bd04..d49685c54b 100644
--- a/engines/ags/engine/ac/global_walkbehind.cpp
+++ b/engines/ags/engine/ac/global_walkbehind.cpp
@@ -28,6 +28,8 @@
 #include "ac/walkbehind.h"
 #include "debug/debug_log.h"
 
+namespace AGS3 {
+
 extern RoomStatus *croom;
 extern int walk_behind_baselines_changed;
 
@@ -42,3 +44,5 @@ void SetWalkBehindBase(int wa, int bl) {
 		debug_script_log("Walk-behind %d baseline changed to %d", wa, bl);
 	}
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/gui.cpp b/engines/ags/engine/ac/gui.cpp
index 060914d468..0d5d481f0f 100644
--- a/engines/ags/engine/ac/gui.cpp
+++ b/engines/ags/engine/ac/gui.cpp
@@ -55,6 +55,7 @@
 #include "script/runtimescriptvalue.h"
 #include "util/string_compat.h"
 
+namespace AGS3 {
 
 using namespace AGS::Shared;
 using namespace AGS::Engine;
@@ -334,8 +335,8 @@ void process_interface_click(int ifce, int btn, int mbut) {
 	if (btn < 0) {
 		// click on GUI background
 		QueueScriptFunction(kScInstGame, guis[ifce].OnClickHandler, 2,
-		                    RuntimeScriptValue().SetDynamicObject(&scrGui[ifce], &ccDynamicGUI),
-		                    RuntimeScriptValue().SetInt32(mbut));
+			RuntimeScriptValue().SetDynamicObject(&scrGui[ifce], &ccDynamicGUI),
+			RuntimeScriptValue().SetInt32(mbut));
 		return;
 	}
 
@@ -349,7 +350,7 @@ void process_interface_click(int ifce, int btn, int mbut) {
 		rtype = kGUIAction_RunScript;
 	else quit("unknown GUI object triggered process_interface");
 
-	if (rtype == kGUIAction_None) ;
+	if (rtype == kGUIAction_None);
 	else if (rtype == kGUIAction_SetMode)
 		set_cursor_mode(rdata);
 	else if (rtype == kGUIAction_RunScript) {
@@ -357,20 +358,20 @@ void process_interface_click(int ifce, int btn, int mbut) {
 		// if the object has a special handler script then run it;
 		// otherwise, run interface_click
 		if ((theObj->GetEventCount() > 0) &&
-		        (!theObj->EventHandlers[0].IsEmpty()) &&
-		        (!gameinst->GetSymbolAddress(theObj->EventHandlers[0]).IsNull())) {
+			(!theObj->EventHandlers[0].IsEmpty()) &&
+			(!gameinst->GetSymbolAddress(theObj->EventHandlers[0]).IsNull())) {
 			// control-specific event handler
 			if (strchr(theObj->GetEventArgs(0), ',') != nullptr)
 				QueueScriptFunction(kScInstGame, theObj->EventHandlers[0], 2,
-				                    RuntimeScriptValue().SetDynamicObject(theObj, &ccDynamicGUIObject),
-				                    RuntimeScriptValue().SetInt32(mbut));
+					RuntimeScriptValue().SetDynamicObject(theObj, &ccDynamicGUIObject),
+					RuntimeScriptValue().SetInt32(mbut));
 			else
 				QueueScriptFunction(kScInstGame, theObj->EventHandlers[0], 1,
-				                    RuntimeScriptValue().SetDynamicObject(theObj, &ccDynamicGUIObject));
+					RuntimeScriptValue().SetDynamicObject(theObj, &ccDynamicGUIObject));
 		} else
 			QueueScriptFunction(kScInstGame, "interface_click", 2,
-			                    RuntimeScriptValue().SetInt32(ifce),
-			                    RuntimeScriptValue().SetInt32(btn));
+				RuntimeScriptValue().SetInt32(ifce),
+				RuntimeScriptValue().SetInt32(btn));
 	}
 }
 
@@ -586,7 +587,7 @@ int gui_get_interactable(int x, int y) {
 int gui_on_mouse_move() {
 	int mouse_over_gui = -1;
 	// If all GUIs are off, skip the loop
-	if ((game.options[OPT_DISABLEOFF] == 3) && (all_buttons_disabled > 0)) ;
+	if ((game.options[OPT_DISABLEOFF] == 3) && (all_buttons_disabled > 0));
 	else {
 		// Scan for mouse-y-pos GUIs, and pop one up if appropriate
 		// Also work out the mouse-over GUI while we're at it
@@ -870,45 +871,45 @@ RuntimeScriptValue Sc_GUI_ProcessClick(const RuntimeScriptValue *params, int32_t
 }
 
 void RegisterGUIAPI() {
-	ccAddExternalObjectFunction("GUI::Centre^0",                Sc_GUI_Centre);
-	ccAddExternalObjectFunction("GUI::Click^1",                 Sc_GUI_Click);
-	ccAddExternalStaticFunction("GUI::GetAtScreenXY^2",         Sc_GetGUIAtLocation);
-	ccAddExternalStaticFunction("GUI::ProcessClick^3",          Sc_GUI_ProcessClick);
-	ccAddExternalObjectFunction("GUI::SetPosition^2",           Sc_GUI_SetPosition);
-	ccAddExternalObjectFunction("GUI::SetSize^2",               Sc_GUI_SetSize);
-	ccAddExternalObjectFunction("GUI::get_BackgroundGraphic",   Sc_GUI_GetBackgroundGraphic);
-	ccAddExternalObjectFunction("GUI::set_BackgroundGraphic",   Sc_GUI_SetBackgroundGraphic);
-	ccAddExternalObjectFunction("GUI::get_BackgroundColor",     Sc_GUI_GetBackgroundColor);
-	ccAddExternalObjectFunction("GUI::set_BackgroundColor",     Sc_GUI_SetBackgroundColor);
-	ccAddExternalObjectFunction("GUI::get_BorderColor",         Sc_GUI_GetBorderColor);
-	ccAddExternalObjectFunction("GUI::set_BorderColor",         Sc_GUI_SetBorderColor);
-	ccAddExternalObjectFunction("GUI::get_Clickable",           Sc_GUI_GetClickable);
-	ccAddExternalObjectFunction("GUI::set_Clickable",           Sc_GUI_SetClickable);
-	ccAddExternalObjectFunction("GUI::get_ControlCount",        Sc_GUI_GetControlCount);
-	ccAddExternalObjectFunction("GUI::geti_Controls",           Sc_GUI_GetiControls);
-	ccAddExternalObjectFunction("GUI::get_Height",              Sc_GUI_GetHeight);
-	ccAddExternalObjectFunction("GUI::set_Height",              Sc_GUI_SetHeight);
-	ccAddExternalObjectFunction("GUI::get_ID",                  Sc_GUI_GetID);
-	ccAddExternalObjectFunction("GUI::get_AsTextWindow",        Sc_GUI_AsTextWindow);
-	ccAddExternalObjectFunction("GUI::get_PopupStyle",          Sc_GUI_GetPopupStyle);
-	ccAddExternalObjectFunction("GUI::get_PopupYPos",           Sc_GUI_GetPopupYPos);
-	ccAddExternalObjectFunction("GUI::set_PopupYPos",           Sc_GUI_SetPopupYPos);
+	ccAddExternalObjectFunction("GUI::Centre^0", Sc_GUI_Centre);
+	ccAddExternalObjectFunction("GUI::Click^1", Sc_GUI_Click);
+	ccAddExternalStaticFunction("GUI::GetAtScreenXY^2", Sc_GetGUIAtLocation);
+	ccAddExternalStaticFunction("GUI::ProcessClick^3", Sc_GUI_ProcessClick);
+	ccAddExternalObjectFunction("GUI::SetPosition^2", Sc_GUI_SetPosition);
+	ccAddExternalObjectFunction("GUI::SetSize^2", Sc_GUI_SetSize);
+	ccAddExternalObjectFunction("GUI::get_BackgroundGraphic", Sc_GUI_GetBackgroundGraphic);
+	ccAddExternalObjectFunction("GUI::set_BackgroundGraphic", Sc_GUI_SetBackgroundGraphic);
+	ccAddExternalObjectFunction("GUI::get_BackgroundColor", Sc_GUI_GetBackgroundColor);
+	ccAddExternalObjectFunction("GUI::set_BackgroundColor", Sc_GUI_SetBackgroundColor);
+	ccAddExternalObjectFunction("GUI::get_BorderColor", Sc_GUI_GetBorderColor);
+	ccAddExternalObjectFunction("GUI::set_BorderColor", Sc_GUI_SetBorderColor);
+	ccAddExternalObjectFunction("GUI::get_Clickable", Sc_GUI_GetClickable);
+	ccAddExternalObjectFunction("GUI::set_Clickable", Sc_GUI_SetClickable);
+	ccAddExternalObjectFunction("GUI::get_ControlCount", Sc_GUI_GetControlCount);
+	ccAddExternalObjectFunction("GUI::geti_Controls", Sc_GUI_GetiControls);
+	ccAddExternalObjectFunction("GUI::get_Height", Sc_GUI_GetHeight);
+	ccAddExternalObjectFunction("GUI::set_Height", Sc_GUI_SetHeight);
+	ccAddExternalObjectFunction("GUI::get_ID", Sc_GUI_GetID);
+	ccAddExternalObjectFunction("GUI::get_AsTextWindow", Sc_GUI_AsTextWindow);
+	ccAddExternalObjectFunction("GUI::get_PopupStyle", Sc_GUI_GetPopupStyle);
+	ccAddExternalObjectFunction("GUI::get_PopupYPos", Sc_GUI_GetPopupYPos);
+	ccAddExternalObjectFunction("GUI::set_PopupYPos", Sc_GUI_SetPopupYPos);
 	ccAddExternalObjectFunction("TextWindowGUI::get_TextColor", Sc_GUI_GetTextColor);
 	ccAddExternalObjectFunction("TextWindowGUI::set_TextColor", Sc_GUI_SetTextColor);
 	ccAddExternalObjectFunction("TextWindowGUI::get_TextPadding", Sc_GUI_GetTextPadding);
 	ccAddExternalObjectFunction("TextWindowGUI::set_TextPadding", Sc_GUI_SetTextPadding);
-	ccAddExternalObjectFunction("GUI::get_Transparency",        Sc_GUI_GetTransparency);
-	ccAddExternalObjectFunction("GUI::set_Transparency",        Sc_GUI_SetTransparency);
-	ccAddExternalObjectFunction("GUI::get_Visible",             Sc_GUI_GetVisible);
-	ccAddExternalObjectFunction("GUI::set_Visible",             Sc_GUI_SetVisible);
-	ccAddExternalObjectFunction("GUI::get_Width",               Sc_GUI_GetWidth);
-	ccAddExternalObjectFunction("GUI::set_Width",               Sc_GUI_SetWidth);
-	ccAddExternalObjectFunction("GUI::get_X",                   Sc_GUI_GetX);
-	ccAddExternalObjectFunction("GUI::set_X",                   Sc_GUI_SetX);
-	ccAddExternalObjectFunction("GUI::get_Y",                   Sc_GUI_GetY);
-	ccAddExternalObjectFunction("GUI::set_Y",                   Sc_GUI_SetY);
-	ccAddExternalObjectFunction("GUI::get_ZOrder",              Sc_GUI_GetZOrder);
-	ccAddExternalObjectFunction("GUI::set_ZOrder",              Sc_GUI_SetZOrder);
+	ccAddExternalObjectFunction("GUI::get_Transparency", Sc_GUI_GetTransparency);
+	ccAddExternalObjectFunction("GUI::set_Transparency", Sc_GUI_SetTransparency);
+	ccAddExternalObjectFunction("GUI::get_Visible", Sc_GUI_GetVisible);
+	ccAddExternalObjectFunction("GUI::set_Visible", Sc_GUI_SetVisible);
+	ccAddExternalObjectFunction("GUI::get_Width", Sc_GUI_GetWidth);
+	ccAddExternalObjectFunction("GUI::set_Width", Sc_GUI_SetWidth);
+	ccAddExternalObjectFunction("GUI::get_X", Sc_GUI_GetX);
+	ccAddExternalObjectFunction("GUI::set_X", Sc_GUI_SetX);
+	ccAddExternalObjectFunction("GUI::get_Y", Sc_GUI_GetY);
+	ccAddExternalObjectFunction("GUI::set_Y", Sc_GUI_SetY);
+	ccAddExternalObjectFunction("GUI::get_ZOrder", Sc_GUI_GetZOrder);
+	ccAddExternalObjectFunction("GUI::set_ZOrder", Sc_GUI_SetZOrder);
 
 	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
 
@@ -938,3 +939,5 @@ void RegisterGUIAPI() {
 	ccAddExternalFunctionForPlugin("GUI::get_ZOrder", (void *)GUI_GetZOrder);
 	ccAddExternalFunctionForPlugin("GUI::set_ZOrder", (void *)GUI_SetZOrder);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/guicontrol.cpp b/engines/ags/engine/ac/guicontrol.cpp
index edb96d95cd..99cde3bd0e 100644
--- a/engines/ags/engine/ac/guicontrol.cpp
+++ b/engines/ags/engine/ac/guicontrol.cpp
@@ -35,6 +35,8 @@
 #include "ac/dynobj/cc_gui.h"
 #include "ac/dynobj/cc_guiobject.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern ScriptGUI *scrGui;
@@ -385,35 +387,35 @@ RuntimeScriptValue Sc_GUIControl_SetZOrder(void *self, const RuntimeScriptValue
 
 
 void RegisterGUIControlAPI() {
-	ccAddExternalObjectFunction("GUIControl::BringToFront^0",   Sc_GUIControl_BringToFront);
-	ccAddExternalStaticFunction("GUIControl::GetAtScreenXY^2",  Sc_GetGUIControlAtLocation);
-	ccAddExternalObjectFunction("GUIControl::SendToBack^0",     Sc_GUIControl_SendToBack);
-	ccAddExternalObjectFunction("GUIControl::SetPosition^2",    Sc_GUIControl_SetPosition);
-	ccAddExternalObjectFunction("GUIControl::SetSize^2",        Sc_GUIControl_SetSize);
-	ccAddExternalObjectFunction("GUIControl::get_AsButton",     Sc_GUIControl_GetAsButton);
-	ccAddExternalObjectFunction("GUIControl::get_AsInvWindow",  Sc_GUIControl_GetAsInvWindow);
-	ccAddExternalObjectFunction("GUIControl::get_AsLabel",      Sc_GUIControl_GetAsLabel);
-	ccAddExternalObjectFunction("GUIControl::get_AsListBox",    Sc_GUIControl_GetAsListBox);
-	ccAddExternalObjectFunction("GUIControl::get_AsSlider",     Sc_GUIControl_GetAsSlider);
-	ccAddExternalObjectFunction("GUIControl::get_AsTextBox",    Sc_GUIControl_GetAsTextBox);
-	ccAddExternalObjectFunction("GUIControl::get_Clickable",    Sc_GUIControl_GetClickable);
-	ccAddExternalObjectFunction("GUIControl::set_Clickable",    Sc_GUIControl_SetClickable);
-	ccAddExternalObjectFunction("GUIControl::get_Enabled",      Sc_GUIControl_GetEnabled);
-	ccAddExternalObjectFunction("GUIControl::set_Enabled",      Sc_GUIControl_SetEnabled);
-	ccAddExternalObjectFunction("GUIControl::get_Height",       Sc_GUIControl_GetHeight);
-	ccAddExternalObjectFunction("GUIControl::set_Height",       Sc_GUIControl_SetHeight);
-	ccAddExternalObjectFunction("GUIControl::get_ID",           Sc_GUIControl_GetID);
-	ccAddExternalObjectFunction("GUIControl::get_OwningGUI",    Sc_GUIControl_GetOwningGUI);
-	ccAddExternalObjectFunction("GUIControl::get_Visible",      Sc_GUIControl_GetVisible);
-	ccAddExternalObjectFunction("GUIControl::set_Visible",      Sc_GUIControl_SetVisible);
-	ccAddExternalObjectFunction("GUIControl::get_Width",        Sc_GUIControl_GetWidth);
-	ccAddExternalObjectFunction("GUIControl::set_Width",        Sc_GUIControl_SetWidth);
-	ccAddExternalObjectFunction("GUIControl::get_X",            Sc_GUIControl_GetX);
-	ccAddExternalObjectFunction("GUIControl::set_X",            Sc_GUIControl_SetX);
-	ccAddExternalObjectFunction("GUIControl::get_Y",            Sc_GUIControl_GetY);
-	ccAddExternalObjectFunction("GUIControl::set_Y",            Sc_GUIControl_SetY);
-	ccAddExternalObjectFunction("GUIControl::get_ZOrder",       Sc_GUIControl_GetZOrder);
-	ccAddExternalObjectFunction("GUIControl::set_ZOrder",       Sc_GUIControl_SetZOrder);
+	ccAddExternalObjectFunction("GUIControl::BringToFront^0", Sc_GUIControl_BringToFront);
+	ccAddExternalStaticFunction("GUIControl::GetAtScreenXY^2", Sc_GetGUIControlAtLocation);
+	ccAddExternalObjectFunction("GUIControl::SendToBack^0", Sc_GUIControl_SendToBack);
+	ccAddExternalObjectFunction("GUIControl::SetPosition^2", Sc_GUIControl_SetPosition);
+	ccAddExternalObjectFunction("GUIControl::SetSize^2", Sc_GUIControl_SetSize);
+	ccAddExternalObjectFunction("GUIControl::get_AsButton", Sc_GUIControl_GetAsButton);
+	ccAddExternalObjectFunction("GUIControl::get_AsInvWindow", Sc_GUIControl_GetAsInvWindow);
+	ccAddExternalObjectFunction("GUIControl::get_AsLabel", Sc_GUIControl_GetAsLabel);
+	ccAddExternalObjectFunction("GUIControl::get_AsListBox", Sc_GUIControl_GetAsListBox);
+	ccAddExternalObjectFunction("GUIControl::get_AsSlider", Sc_GUIControl_GetAsSlider);
+	ccAddExternalObjectFunction("GUIControl::get_AsTextBox", Sc_GUIControl_GetAsTextBox);
+	ccAddExternalObjectFunction("GUIControl::get_Clickable", Sc_GUIControl_GetClickable);
+	ccAddExternalObjectFunction("GUIControl::set_Clickable", Sc_GUIControl_SetClickable);
+	ccAddExternalObjectFunction("GUIControl::get_Enabled", Sc_GUIControl_GetEnabled);
+	ccAddExternalObjectFunction("GUIControl::set_Enabled", Sc_GUIControl_SetEnabled);
+	ccAddExternalObjectFunction("GUIControl::get_Height", Sc_GUIControl_GetHeight);
+	ccAddExternalObjectFunction("GUIControl::set_Height", Sc_GUIControl_SetHeight);
+	ccAddExternalObjectFunction("GUIControl::get_ID", Sc_GUIControl_GetID);
+	ccAddExternalObjectFunction("GUIControl::get_OwningGUI", Sc_GUIControl_GetOwningGUI);
+	ccAddExternalObjectFunction("GUIControl::get_Visible", Sc_GUIControl_GetVisible);
+	ccAddExternalObjectFunction("GUIControl::set_Visible", Sc_GUIControl_SetVisible);
+	ccAddExternalObjectFunction("GUIControl::get_Width", Sc_GUIControl_GetWidth);
+	ccAddExternalObjectFunction("GUIControl::set_Width", Sc_GUIControl_SetWidth);
+	ccAddExternalObjectFunction("GUIControl::get_X", Sc_GUIControl_GetX);
+	ccAddExternalObjectFunction("GUIControl::set_X", Sc_GUIControl_SetX);
+	ccAddExternalObjectFunction("GUIControl::get_Y", Sc_GUIControl_GetY);
+	ccAddExternalObjectFunction("GUIControl::set_Y", Sc_GUIControl_SetY);
+	ccAddExternalObjectFunction("GUIControl::get_ZOrder", Sc_GUIControl_GetZOrder);
+	ccAddExternalObjectFunction("GUIControl::set_ZOrder", Sc_GUIControl_SetZOrder);
 
 	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
 
@@ -445,3 +447,5 @@ void RegisterGUIControlAPI() {
 	ccAddExternalFunctionForPlugin("GUIControl::get_Y", (void *)GUIControl_GetY);
 	ccAddExternalFunctionForPlugin("GUIControl::set_Y", (void *)GUIControl_SetY);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/guiinv.cpp b/engines/ags/engine/ac/guiinv.cpp
index ef3608d34e..8110cc71ce 100644
--- a/engines/ags/engine/ac/guiinv.cpp
+++ b/engines/ags/engine/ac/guiinv.cpp
@@ -29,6 +29,7 @@
 #include "ac/spritecache.h"
 #include "gfx/bitmap.h"
 
+namespace AGS3 {
 
 extern GameSetupStruct game;
 extern int gui_disabled_style;
@@ -84,8 +85,8 @@ void GUIInvWindow::Draw(Bitmap *ds) {
 	}
 
 	if (!enabled &&
-	        gui_disabled_style == GUIDIS_GREYOUT &&
-	        play.inventory_greys_out == 1) {
+		gui_disabled_style == GUIDIS_GREYOUT &&
+		play.inventory_greys_out == 1) {
 		// darken the inventory when disabled
 		GUI::DrawDisabledEffect(ds, RectWH(X, Y, Width, Height));
 	}
@@ -93,3 +94,4 @@ void GUIInvWindow::Draw(Bitmap *ds) {
 
 } // namespace Shared
 } // namespace AGS
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/hotspot.cpp b/engines/ags/engine/ac/hotspot.cpp
index a57a57a458..f839323f7c 100644
--- a/engines/ags/engine/ac/hotspot.cpp
+++ b/engines/ags/engine/ac/hotspot.cpp
@@ -33,6 +33,8 @@
 #include "gfx/bitmap.h"
 #include "script/runtimescriptvalue.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern RoomStruct thisroom;
@@ -217,23 +219,23 @@ RuntimeScriptValue Sc_Hotspot_GetWalkToY(void *self, const RuntimeScriptValue *p
 
 
 void RegisterHotspotAPI() {
-	ccAddExternalStaticFunction("Hotspot::GetAtRoomXY^2",       Sc_GetHotspotAtRoom);
-	ccAddExternalStaticFunction("Hotspot::GetAtScreenXY^2",     Sc_GetHotspotAtScreen);
-	ccAddExternalStaticFunction("Hotspot::GetDrawingSurface",   Sc_Hotspot_GetDrawingSurface);
-	ccAddExternalObjectFunction("Hotspot::GetName^1",           Sc_Hotspot_GetName);
-	ccAddExternalObjectFunction("Hotspot::GetProperty^1",       Sc_Hotspot_GetProperty);
-	ccAddExternalObjectFunction("Hotspot::GetPropertyText^2",   Sc_Hotspot_GetPropertyText);
-	ccAddExternalObjectFunction("Hotspot::GetTextProperty^1",   Sc_Hotspot_GetTextProperty);
-	ccAddExternalObjectFunction("Hotspot::SetProperty^2",       Sc_Hotspot_SetProperty);
-	ccAddExternalObjectFunction("Hotspot::SetTextProperty^2",   Sc_Hotspot_SetTextProperty);
+	ccAddExternalStaticFunction("Hotspot::GetAtRoomXY^2", Sc_GetHotspotAtRoom);
+	ccAddExternalStaticFunction("Hotspot::GetAtScreenXY^2", Sc_GetHotspotAtScreen);
+	ccAddExternalStaticFunction("Hotspot::GetDrawingSurface", Sc_Hotspot_GetDrawingSurface);
+	ccAddExternalObjectFunction("Hotspot::GetName^1", Sc_Hotspot_GetName);
+	ccAddExternalObjectFunction("Hotspot::GetProperty^1", Sc_Hotspot_GetProperty);
+	ccAddExternalObjectFunction("Hotspot::GetPropertyText^2", Sc_Hotspot_GetPropertyText);
+	ccAddExternalObjectFunction("Hotspot::GetTextProperty^1", Sc_Hotspot_GetTextProperty);
+	ccAddExternalObjectFunction("Hotspot::SetProperty^2", Sc_Hotspot_SetProperty);
+	ccAddExternalObjectFunction("Hotspot::SetTextProperty^2", Sc_Hotspot_SetTextProperty);
 	ccAddExternalObjectFunction("Hotspot::IsInteractionAvailable^1", Sc_Hotspot_IsInteractionAvailable);
-	ccAddExternalObjectFunction("Hotspot::RunInteraction^1",    Sc_Hotspot_RunInteraction);
-	ccAddExternalObjectFunction("Hotspot::get_Enabled",         Sc_Hotspot_GetEnabled);
-	ccAddExternalObjectFunction("Hotspot::set_Enabled",         Sc_Hotspot_SetEnabled);
-	ccAddExternalObjectFunction("Hotspot::get_ID",              Sc_Hotspot_GetID);
-	ccAddExternalObjectFunction("Hotspot::get_Name",            Sc_Hotspot_GetName_New);
-	ccAddExternalObjectFunction("Hotspot::get_WalkToX",         Sc_Hotspot_GetWalkToX);
-	ccAddExternalObjectFunction("Hotspot::get_WalkToY",         Sc_Hotspot_GetWalkToY);
+	ccAddExternalObjectFunction("Hotspot::RunInteraction^1", Sc_Hotspot_RunInteraction);
+	ccAddExternalObjectFunction("Hotspot::get_Enabled", Sc_Hotspot_GetEnabled);
+	ccAddExternalObjectFunction("Hotspot::set_Enabled", Sc_Hotspot_SetEnabled);
+	ccAddExternalObjectFunction("Hotspot::get_ID", Sc_Hotspot_GetID);
+	ccAddExternalObjectFunction("Hotspot::get_Name", Sc_Hotspot_GetName_New);
+	ccAddExternalObjectFunction("Hotspot::get_WalkToX", Sc_Hotspot_GetWalkToX);
+	ccAddExternalObjectFunction("Hotspot::get_WalkToY", Sc_Hotspot_GetWalkToY);
 
 	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
 
@@ -251,3 +253,5 @@ void RegisterHotspotAPI() {
 	ccAddExternalFunctionForPlugin("Hotspot::get_WalkToX", (void *)Hotspot_GetWalkToX);
 	ccAddExternalFunctionForPlugin("Hotspot::get_WalkToY", (void *)Hotspot_GetWalkToY);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/interfacebutton.cpp b/engines/ags/engine/ac/interfacebutton.cpp
index d10d90c8d4..293870287d 100644
--- a/engines/ags/engine/ac/interfacebutton.cpp
+++ b/engines/ags/engine/ac/interfacebutton.cpp
@@ -22,6 +22,8 @@
 
 #include "ac/interfacebutton.h"
 
+namespace AGS3 {
+
 void InterfaceButton::set(int xx, int yy, int picc, int overpicc, int actionn) {
 	x = xx;
 	y = yy;
@@ -33,3 +35,5 @@ void InterfaceButton::set(int xx, int yy, int picc, int overpicc, int actionn) {
 	flags = IBFLG_ENABLED;
 	reserved_for_future = 0;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/interfaceelement.cpp b/engines/ags/engine/ac/interfaceelement.cpp
index 154ce79e57..5da22509f5 100644
--- a/engines/ags/engine/ac/interfaceelement.cpp
+++ b/engines/ags/engine/ac/interfaceelement.cpp
@@ -23,6 +23,8 @@
 #include <string.h>
 #include "ac/interfaceelement.h"
 
+namespace AGS3 {
+
 InterfaceElement::InterfaceElement() {
 	vtextxp = 0;
 	vtextyp = 1;
@@ -34,3 +36,5 @@ InterfaceElement::InterfaceElement() {
 	on = 1;
 	flags = 0;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/inventoryitem.cpp b/engines/ags/engine/ac/inventoryitem.cpp
index a32161f16b..e71a20ad60 100644
--- a/engines/ags/engine/ac/inventoryitem.cpp
+++ b/engines/ags/engine/ac/inventoryitem.cpp
@@ -33,6 +33,7 @@
 #include "script/runtimescriptvalue.h"
 #include "ac/dynobj/cc_inventory.h"
 
+namespace AGS3 {
 
 extern GameSetupStruct game;
 extern ScriptInvItem scrInv[MAX_INV];
@@ -213,23 +214,23 @@ RuntimeScriptValue Sc_InventoryItem_GetName_New(void *self, const RuntimeScriptV
 
 
 void RegisterInventoryItemAPI() {
-	ccAddExternalStaticFunction("InventoryItem::GetAtScreenXY^2",           Sc_GetInvAtLocation);
-	ccAddExternalObjectFunction("InventoryItem::IsInteractionAvailable^1",  Sc_InventoryItem_CheckInteractionAvailable);
-	ccAddExternalObjectFunction("InventoryItem::GetName^1",                 Sc_InventoryItem_GetName);
-	ccAddExternalObjectFunction("InventoryItem::GetProperty^1",             Sc_InventoryItem_GetProperty);
-	ccAddExternalObjectFunction("InventoryItem::GetPropertyText^2",         Sc_InventoryItem_GetPropertyText);
-	ccAddExternalObjectFunction("InventoryItem::GetTextProperty^1",         Sc_InventoryItem_GetTextProperty);
-	ccAddExternalObjectFunction("InventoryItem::SetProperty^2",             Sc_InventoryItem_SetProperty);
-	ccAddExternalObjectFunction("InventoryItem::SetTextProperty^2",         Sc_InventoryItem_SetTextProperty);
-	ccAddExternalObjectFunction("InventoryItem::RunInteraction^1",          Sc_InventoryItem_RunInteraction);
-	ccAddExternalObjectFunction("InventoryItem::SetName^1",                 Sc_InventoryItem_SetName);
-	ccAddExternalObjectFunction("InventoryItem::get_CursorGraphic",         Sc_InventoryItem_GetCursorGraphic);
-	ccAddExternalObjectFunction("InventoryItem::set_CursorGraphic",         Sc_InventoryItem_SetCursorGraphic);
-	ccAddExternalObjectFunction("InventoryItem::get_Graphic",               Sc_InventoryItem_GetGraphic);
-	ccAddExternalObjectFunction("InventoryItem::set_Graphic",               Sc_InventoryItem_SetGraphic);
-	ccAddExternalObjectFunction("InventoryItem::get_ID",                    Sc_InventoryItem_GetID);
-	ccAddExternalObjectFunction("InventoryItem::get_Name",                  Sc_InventoryItem_GetName_New);
-	ccAddExternalObjectFunction("InventoryItem::set_Name",                  Sc_InventoryItem_SetName);
+	ccAddExternalStaticFunction("InventoryItem::GetAtScreenXY^2", Sc_GetInvAtLocation);
+	ccAddExternalObjectFunction("InventoryItem::IsInteractionAvailable^1", Sc_InventoryItem_CheckInteractionAvailable);
+	ccAddExternalObjectFunction("InventoryItem::GetName^1", Sc_InventoryItem_GetName);
+	ccAddExternalObjectFunction("InventoryItem::GetProperty^1", Sc_InventoryItem_GetProperty);
+	ccAddExternalObjectFunction("InventoryItem::GetPropertyText^2", Sc_InventoryItem_GetPropertyText);
+	ccAddExternalObjectFunction("InventoryItem::GetTextProperty^1", Sc_InventoryItem_GetTextProperty);
+	ccAddExternalObjectFunction("InventoryItem::SetProperty^2", Sc_InventoryItem_SetProperty);
+	ccAddExternalObjectFunction("InventoryItem::SetTextProperty^2", Sc_InventoryItem_SetTextProperty);
+	ccAddExternalObjectFunction("InventoryItem::RunInteraction^1", Sc_InventoryItem_RunInteraction);
+	ccAddExternalObjectFunction("InventoryItem::SetName^1", Sc_InventoryItem_SetName);
+	ccAddExternalObjectFunction("InventoryItem::get_CursorGraphic", Sc_InventoryItem_GetCursorGraphic);
+	ccAddExternalObjectFunction("InventoryItem::set_CursorGraphic", Sc_InventoryItem_SetCursorGraphic);
+	ccAddExternalObjectFunction("InventoryItem::get_Graphic", Sc_InventoryItem_GetGraphic);
+	ccAddExternalObjectFunction("InventoryItem::set_Graphic", Sc_InventoryItem_SetGraphic);
+	ccAddExternalObjectFunction("InventoryItem::get_ID", Sc_InventoryItem_GetID);
+	ccAddExternalObjectFunction("InventoryItem::get_Name", Sc_InventoryItem_GetName_New);
+	ccAddExternalObjectFunction("InventoryItem::set_Name", Sc_InventoryItem_SetName);
 
 	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
 
@@ -249,3 +250,5 @@ void RegisterInventoryItemAPI() {
 	ccAddExternalFunctionForPlugin("InventoryItem::get_Name", (void *)InventoryItem_GetName_New);
 	ccAddExternalFunctionForPlugin("InventoryItem::set_Name", (void *)InventoryItem_SetName);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/invwindow.cpp b/engines/ags/engine/ac/invwindow.cpp
index ed8ba69464..1c9b860255 100644
--- a/engines/ags/engine/ac/invwindow.cpp
+++ b/engines/ags/engine/ac/invwindow.cpp
@@ -45,6 +45,8 @@
 #include "media/audio/audio_system.h"
 #include "ac/timer.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern GameSetupStruct game;
@@ -125,7 +127,7 @@ int InvWindow_GetRowCount(GUIInvWindow *guii) {
 
 void InvWindow_ScrollDown(GUIInvWindow *guii) {
 	if ((charextra[guii->GetCharacterId()].invorder_count) >
-	        (guii->TopItem + (guii->ColCount * guii->RowCount))) {
+		(guii->TopItem + (guii->ColCount * guii->RowCount))) {
 		guii->TopItem += guii->ColCount;
 		guis_need_update = 1;
 	}
@@ -308,8 +310,8 @@ void InventoryScreen::Draw(Bitmap *ds) {
 		if (i >= top_item + num_visible_items)
 			break;
 		Bitmap *spof = spriteset[dii[i].sprnum];
-		wputblock(ds, barxp + 1 + ((i - top_item) % 4)*widest + widest / 2 - spof->GetWidth() / 2,
-		          bartop + 1 + ((i - top_item) / 4)*highest + highest / 2 - spof->GetHeight() / 2, spof, 1);
+		wputblock(ds, barxp + 1 + ((i - top_item) % 4) * widest + widest / 2 - spof->GetWidth() / 2,
+			bartop + 1 + ((i - top_item) / 4) * highest + highest / 2 - spof->GetHeight() / 2, spof, 1);
 	}
 #define BUTTONWID Math::Max(1, game.SpriteInfos[btn_select_sprite].Width)
 	// Draw select, look and OK buttons
@@ -601,20 +603,20 @@ RuntimeScriptValue Sc_InvWindow_SetTopItem(void *self, const RuntimeScriptValue
 
 
 void RegisterInventoryWindowAPI() {
-	ccAddExternalObjectFunction("InvWindow::ScrollDown^0",          Sc_InvWindow_ScrollDown);
-	ccAddExternalObjectFunction("InvWindow::ScrollUp^0",            Sc_InvWindow_ScrollUp);
-	ccAddExternalObjectFunction("InvWindow::get_CharacterToUse",    Sc_InvWindow_GetCharacterToUse);
-	ccAddExternalObjectFunction("InvWindow::set_CharacterToUse",    Sc_InvWindow_SetCharacterToUse);
-	ccAddExternalObjectFunction("InvWindow::geti_ItemAtIndex",      Sc_InvWindow_GetItemAtIndex);
-	ccAddExternalObjectFunction("InvWindow::get_ItemCount",         Sc_InvWindow_GetItemCount);
-	ccAddExternalObjectFunction("InvWindow::get_ItemHeight",        Sc_InvWindow_GetItemHeight);
-	ccAddExternalObjectFunction("InvWindow::set_ItemHeight",        Sc_InvWindow_SetItemHeight);
-	ccAddExternalObjectFunction("InvWindow::get_ItemWidth",         Sc_InvWindow_GetItemWidth);
-	ccAddExternalObjectFunction("InvWindow::set_ItemWidth",         Sc_InvWindow_SetItemWidth);
-	ccAddExternalObjectFunction("InvWindow::get_ItemsPerRow",       Sc_InvWindow_GetItemsPerRow);
-	ccAddExternalObjectFunction("InvWindow::get_RowCount",          Sc_InvWindow_GetRowCount);
-	ccAddExternalObjectFunction("InvWindow::get_TopItem",           Sc_InvWindow_GetTopItem);
-	ccAddExternalObjectFunction("InvWindow::set_TopItem",           Sc_InvWindow_SetTopItem);
+	ccAddExternalObjectFunction("InvWindow::ScrollDown^0", Sc_InvWindow_ScrollDown);
+	ccAddExternalObjectFunction("InvWindow::ScrollUp^0", Sc_InvWindow_ScrollUp);
+	ccAddExternalObjectFunction("InvWindow::get_CharacterToUse", Sc_InvWindow_GetCharacterToUse);
+	ccAddExternalObjectFunction("InvWindow::set_CharacterToUse", Sc_InvWindow_SetCharacterToUse);
+	ccAddExternalObjectFunction("InvWindow::geti_ItemAtIndex", Sc_InvWindow_GetItemAtIndex);
+	ccAddExternalObjectFunction("InvWindow::get_ItemCount", Sc_InvWindow_GetItemCount);
+	ccAddExternalObjectFunction("InvWindow::get_ItemHeight", Sc_InvWindow_GetItemHeight);
+	ccAddExternalObjectFunction("InvWindow::set_ItemHeight", Sc_InvWindow_SetItemHeight);
+	ccAddExternalObjectFunction("InvWindow::get_ItemWidth", Sc_InvWindow_GetItemWidth);
+	ccAddExternalObjectFunction("InvWindow::set_ItemWidth", Sc_InvWindow_SetItemWidth);
+	ccAddExternalObjectFunction("InvWindow::get_ItemsPerRow", Sc_InvWindow_GetItemsPerRow);
+	ccAddExternalObjectFunction("InvWindow::get_RowCount", Sc_InvWindow_GetRowCount);
+	ccAddExternalObjectFunction("InvWindow::get_TopItem", Sc_InvWindow_GetTopItem);
+	ccAddExternalObjectFunction("InvWindow::set_TopItem", Sc_InvWindow_SetTopItem);
 
 	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
 
@@ -633,3 +635,5 @@ void RegisterInventoryWindowAPI() {
 	ccAddExternalFunctionForPlugin("InvWindow::get_TopItem", (void *)InvWindow_GetTopItem);
 	ccAddExternalFunctionForPlugin("InvWindow::set_TopItem", (void *)InvWindow_SetTopItem);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/keycode.cpp b/engines/ags/engine/ac/keycode.cpp
index e16de8b958..701790ee23 100644
--- a/engines/ags/engine/ac/keycode.cpp
+++ b/engines/ags/engine/ac/keycode.cpp
@@ -24,6 +24,8 @@
 
 #include <allegro.h>
 
+namespace AGS3 {
+
 int GetKeyForKeyPressCb(int keycode) {
 	// lower case 'a'..'z' do not exist as keycodes, only ascii. 'A'..'Z' do though!
 	return (keycode >= 'a' && keycode <= 'z') ? keycode - 32 : keycode;
@@ -33,7 +35,7 @@ int PlatformKeyFromAgsKey(int key) {
 	int platformKey = -1;
 
 	switch (key) {
-	// ctrl-[A-Z] keys are numbered 1-26 for A-Z
+		// ctrl-[A-Z] keys are numbered 1-26 for A-Z
 	case eAGSKeyCodeCtrlA:
 		platformKey = 1;
 		break;
@@ -55,8 +57,8 @@ int PlatformKeyFromAgsKey(int key) {
 	case eAGSKeyCodeCtrlG:
 		platformKey = 7;
 		break;
-	// case eAGSKeyCodeCtrlH: // overlap with backspace
-	// case eAGSKeyCodeCtrlI: // overlap with tab
+		// case eAGSKeyCodeCtrlH: // overlap with backspace
+		// case eAGSKeyCodeCtrlI: // overlap with tab
 	case eAGSKeyCodeCtrlJ:
 		platformKey = 10;
 		break;
@@ -66,7 +68,7 @@ int PlatformKeyFromAgsKey(int key) {
 	case eAGSKeyCodeCtrlL:
 		platformKey = 12;
 		break;
-	// case eAGSKeyCodeCtrlM: // overlap with return
+		// case eAGSKeyCodeCtrlM: // overlap with return
 	case eAGSKeyCodeCtrlN:
 		platformKey = 14;
 		break;
@@ -385,3 +387,5 @@ int PlatformKeyFromAgsKey(int key) {
 
 	return platformKey;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/label.cpp b/engines/ags/engine/ac/label.cpp
index 077a81b34a..8935c71abe 100644
--- a/engines/ags/engine/ac/label.cpp
+++ b/engines/ags/engine/ac/label.cpp
@@ -27,6 +27,8 @@
 #include "ac/global_translation.h"
 #include "ac/string.h"
 
+namespace AGS3 {
+
 extern GameSetupStruct game;
 
 // ** LABEL FUNCTIONS
@@ -144,14 +146,14 @@ RuntimeScriptValue Sc_Label_SetColor(void *self, const RuntimeScriptValue *param
 
 
 void RegisterLabelAPI() {
-	ccAddExternalObjectFunction("Label::GetText^1",     Sc_Label_GetText);
-	ccAddExternalObjectFunction("Label::SetText^1",     Sc_Label_SetText);
+	ccAddExternalObjectFunction("Label::GetText^1", Sc_Label_GetText);
+	ccAddExternalObjectFunction("Label::SetText^1", Sc_Label_SetText);
 	ccAddExternalObjectFunction("Label::get_TextAlignment", Sc_Label_GetTextAlignment);
 	ccAddExternalObjectFunction("Label::set_TextAlignment", Sc_Label_SetTextAlignment);
-	ccAddExternalObjectFunction("Label::get_Font",      Sc_Label_GetFont);
-	ccAddExternalObjectFunction("Label::set_Font",      Sc_Label_SetFont);
-	ccAddExternalObjectFunction("Label::get_Text",      Sc_Label_GetText_New);
-	ccAddExternalObjectFunction("Label::set_Text",      Sc_Label_SetText);
+	ccAddExternalObjectFunction("Label::get_Font", Sc_Label_GetFont);
+	ccAddExternalObjectFunction("Label::set_Font", Sc_Label_SetFont);
+	ccAddExternalObjectFunction("Label::get_Text", Sc_Label_GetText_New);
+	ccAddExternalObjectFunction("Label::set_Text", Sc_Label_SetText);
 	ccAddExternalObjectFunction("Label::get_TextColor", Sc_Label_GetColor);
 	ccAddExternalObjectFunction("Label::set_TextColor", Sc_Label_SetColor);
 
@@ -166,3 +168,5 @@ void RegisterLabelAPI() {
 	ccAddExternalFunctionForPlugin("Label::get_TextColor", (void *)Label_GetColor);
 	ccAddExternalFunctionForPlugin("Label::set_TextColor", (void *)Label_SetColor);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/listbox.cpp b/engines/ags/engine/ac/listbox.cpp
index 57635d104d..eec074c65f 100644
--- a/engines/ags/engine/ac/listbox.cpp
+++ b/engines/ags/engine/ac/listbox.cpp
@@ -32,6 +32,8 @@
 #include "gui/guimain.h"
 #include "debug/debug_log.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern GameState play;
@@ -569,46 +571,46 @@ RuntimeScriptValue Sc_ListBox_SetTopItem(void *self, const RuntimeScriptValue *p
 
 
 void RegisterListBoxAPI() {
-	ccAddExternalObjectFunction("ListBox::AddItem^1",           Sc_ListBox_AddItem);
-	ccAddExternalObjectFunction("ListBox::Clear^0",             Sc_ListBox_Clear);
-	ccAddExternalObjectFunction("ListBox::FillDirList^1",       Sc_ListBox_FillDirList);
-	ccAddExternalObjectFunction("ListBox::FillSaveGameList^0",  Sc_ListBox_FillSaveGameList);
+	ccAddExternalObjectFunction("ListBox::AddItem^1", Sc_ListBox_AddItem);
+	ccAddExternalObjectFunction("ListBox::Clear^0", Sc_ListBox_Clear);
+	ccAddExternalObjectFunction("ListBox::FillDirList^1", Sc_ListBox_FillDirList);
+	ccAddExternalObjectFunction("ListBox::FillSaveGameList^0", Sc_ListBox_FillSaveGameList);
 	ccAddExternalObjectFunction("ListBox::GetItemAtLocation^2", Sc_ListBox_GetItemAtLocation);
-	ccAddExternalObjectFunction("ListBox::GetItemText^2",       Sc_ListBox_GetItemText);
-	ccAddExternalObjectFunction("ListBox::InsertItemAt^2",      Sc_ListBox_InsertItemAt);
-	ccAddExternalObjectFunction("ListBox::RemoveItem^1",        Sc_ListBox_RemoveItem);
-	ccAddExternalObjectFunction("ListBox::ScrollDown^0",        Sc_ListBox_ScrollDown);
-	ccAddExternalObjectFunction("ListBox::ScrollUp^0",          Sc_ListBox_ScrollUp);
-	ccAddExternalObjectFunction("ListBox::SetItemText^2",       Sc_ListBox_SetItemText);
-	ccAddExternalObjectFunction("ListBox::get_Font",            Sc_ListBox_GetFont);
-	ccAddExternalObjectFunction("ListBox::set_Font",            Sc_ListBox_SetFont);
-	ccAddExternalObjectFunction("ListBox::get_ShowBorder",      Sc_ListBox_GetShowBorder);
-	ccAddExternalObjectFunction("ListBox::set_ShowBorder",      Sc_ListBox_SetShowBorder);
+	ccAddExternalObjectFunction("ListBox::GetItemText^2", Sc_ListBox_GetItemText);
+	ccAddExternalObjectFunction("ListBox::InsertItemAt^2", Sc_ListBox_InsertItemAt);
+	ccAddExternalObjectFunction("ListBox::RemoveItem^1", Sc_ListBox_RemoveItem);
+	ccAddExternalObjectFunction("ListBox::ScrollDown^0", Sc_ListBox_ScrollDown);
+	ccAddExternalObjectFunction("ListBox::ScrollUp^0", Sc_ListBox_ScrollUp);
+	ccAddExternalObjectFunction("ListBox::SetItemText^2", Sc_ListBox_SetItemText);
+	ccAddExternalObjectFunction("ListBox::get_Font", Sc_ListBox_GetFont);
+	ccAddExternalObjectFunction("ListBox::set_Font", Sc_ListBox_SetFont);
+	ccAddExternalObjectFunction("ListBox::get_ShowBorder", Sc_ListBox_GetShowBorder);
+	ccAddExternalObjectFunction("ListBox::set_ShowBorder", Sc_ListBox_SetShowBorder);
 	ccAddExternalObjectFunction("ListBox::get_ShowScrollArrows", Sc_ListBox_GetShowScrollArrows);
 	ccAddExternalObjectFunction("ListBox::set_ShowScrollArrows", Sc_ListBox_SetShowScrollArrows);
 	// old "inverted" properties
-	ccAddExternalObjectFunction("ListBox::get_HideBorder",      Sc_ListBox_GetHideBorder);
-	ccAddExternalObjectFunction("ListBox::set_HideBorder",      Sc_ListBox_SetHideBorder);
+	ccAddExternalObjectFunction("ListBox::get_HideBorder", Sc_ListBox_GetHideBorder);
+	ccAddExternalObjectFunction("ListBox::set_HideBorder", Sc_ListBox_SetHideBorder);
 	ccAddExternalObjectFunction("ListBox::get_HideScrollArrows", Sc_ListBox_GetHideScrollArrows);
 	ccAddExternalObjectFunction("ListBox::set_HideScrollArrows", Sc_ListBox_SetHideScrollArrows);
 	//
-	ccAddExternalObjectFunction("ListBox::get_ItemCount",       Sc_ListBox_GetItemCount);
-	ccAddExternalObjectFunction("ListBox::geti_Items",          Sc_ListBox_GetItems);
-	ccAddExternalObjectFunction("ListBox::seti_Items",          Sc_ListBox_SetItemText);
-	ccAddExternalObjectFunction("ListBox::get_RowCount",        Sc_ListBox_GetRowCount);
-	ccAddExternalObjectFunction("ListBox::geti_SaveGameSlots",  Sc_ListBox_GetSaveGameSlots);
+	ccAddExternalObjectFunction("ListBox::get_ItemCount", Sc_ListBox_GetItemCount);
+	ccAddExternalObjectFunction("ListBox::geti_Items", Sc_ListBox_GetItems);
+	ccAddExternalObjectFunction("ListBox::seti_Items", Sc_ListBox_SetItemText);
+	ccAddExternalObjectFunction("ListBox::get_RowCount", Sc_ListBox_GetRowCount);
+	ccAddExternalObjectFunction("ListBox::geti_SaveGameSlots", Sc_ListBox_GetSaveGameSlots);
 	ccAddExternalObjectFunction("ListBox::get_SelectedBackColor", Sc_ListBox_GetSelectedBackColor);
 	ccAddExternalObjectFunction("ListBox::set_SelectedBackColor", Sc_ListBox_SetSelectedBackColor);
-	ccAddExternalObjectFunction("ListBox::get_SelectedIndex",   Sc_ListBox_GetSelectedIndex);
-	ccAddExternalObjectFunction("ListBox::set_SelectedIndex",   Sc_ListBox_SetSelectedIndex);
+	ccAddExternalObjectFunction("ListBox::get_SelectedIndex", Sc_ListBox_GetSelectedIndex);
+	ccAddExternalObjectFunction("ListBox::set_SelectedIndex", Sc_ListBox_SetSelectedIndex);
 	ccAddExternalObjectFunction("ListBox::get_SelectedTextColor", Sc_ListBox_GetSelectedTextColor);
 	ccAddExternalObjectFunction("ListBox::set_SelectedTextColor", Sc_ListBox_SetSelectedTextColor);
-	ccAddExternalObjectFunction("ListBox::get_TextAlignment",   Sc_ListBox_GetTextAlignment);
-	ccAddExternalObjectFunction("ListBox::set_TextAlignment",   Sc_ListBox_SetTextAlignment);
-	ccAddExternalObjectFunction("ListBox::get_TextColor",       Sc_ListBox_GetTextColor);
-	ccAddExternalObjectFunction("ListBox::set_TextColor",       Sc_ListBox_SetTextColor);
-	ccAddExternalObjectFunction("ListBox::get_TopItem",         Sc_ListBox_GetTopItem);
-	ccAddExternalObjectFunction("ListBox::set_TopItem",         Sc_ListBox_SetTopItem);
+	ccAddExternalObjectFunction("ListBox::get_TextAlignment", Sc_ListBox_GetTextAlignment);
+	ccAddExternalObjectFunction("ListBox::set_TextAlignment", Sc_ListBox_SetTextAlignment);
+	ccAddExternalObjectFunction("ListBox::get_TextColor", Sc_ListBox_GetTextColor);
+	ccAddExternalObjectFunction("ListBox::set_TextColor", Sc_ListBox_SetTextColor);
+	ccAddExternalObjectFunction("ListBox::get_TopItem", Sc_ListBox_GetTopItem);
+	ccAddExternalObjectFunction("ListBox::set_TopItem", Sc_ListBox_SetTopItem);
 
 	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
 
@@ -639,3 +641,5 @@ void RegisterListBoxAPI() {
 	ccAddExternalFunctionForPlugin("ListBox::get_TopItem", (void *)ListBox_GetTopItem);
 	ccAddExternalFunctionForPlugin("ListBox::set_TopItem", (void *)ListBox_SetTopItem);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/math.cpp b/engines/ags/engine/ac/math.cpp
index 228558fc52..de2d521978 100644
--- a/engines/ags/engine/ac/math.cpp
+++ b/engines/ags/engine/ac/math.cpp
@@ -25,6 +25,8 @@
 #include "ac/common.h" // quit
 #include "util/math.h"
 
+namespace AGS3 {
+
 int FloatToInt(float value, int roundDirection) {
 	if (value >= 0.0) {
 		if (roundDirection == eRoundDown)
@@ -242,24 +244,24 @@ RuntimeScriptValue Sc_Math_GetPi(const RuntimeScriptValue *params, int32_t param
 
 
 void RegisterMathAPI() {
-	ccAddExternalStaticFunction("Maths::ArcCos^1",              Sc_Math_ArcCos);
-	ccAddExternalStaticFunction("Maths::ArcSin^1",              Sc_Math_ArcSin);
-	ccAddExternalStaticFunction("Maths::ArcTan^1",              Sc_Math_ArcTan);
-	ccAddExternalStaticFunction("Maths::ArcTan2^2",             Sc_Math_ArcTan2);
-	ccAddExternalStaticFunction("Maths::Cos^1",                 Sc_Math_Cos);
-	ccAddExternalStaticFunction("Maths::Cosh^1",                Sc_Math_Cosh);
-	ccAddExternalStaticFunction("Maths::DegreesToRadians^1",    Sc_Math_DegreesToRadians);
-	ccAddExternalStaticFunction("Maths::Exp^1",                 Sc_Math_Exp);
-	ccAddExternalStaticFunction("Maths::Log^1",                 Sc_Math_Log);
-	ccAddExternalStaticFunction("Maths::Log10^1",               Sc_Math_Log10);
-	ccAddExternalStaticFunction("Maths::RadiansToDegrees^1",    Sc_Math_RadiansToDegrees);
-	ccAddExternalStaticFunction("Maths::RaiseToPower^2",        Sc_Math_RaiseToPower);
-	ccAddExternalStaticFunction("Maths::Sin^1",                 Sc_Math_Sin);
-	ccAddExternalStaticFunction("Maths::Sinh^1",                Sc_Math_Sinh);
-	ccAddExternalStaticFunction("Maths::Sqrt^1",                Sc_Math_Sqrt);
-	ccAddExternalStaticFunction("Maths::Tan^1",                 Sc_Math_Tan);
-	ccAddExternalStaticFunction("Maths::Tanh^1",                Sc_Math_Tanh);
-	ccAddExternalStaticFunction("Maths::get_Pi",                Sc_Math_GetPi);
+	ccAddExternalStaticFunction("Maths::ArcCos^1", Sc_Math_ArcCos);
+	ccAddExternalStaticFunction("Maths::ArcSin^1", Sc_Math_ArcSin);
+	ccAddExternalStaticFunction("Maths::ArcTan^1", Sc_Math_ArcTan);
+	ccAddExternalStaticFunction("Maths::ArcTan2^2", Sc_Math_ArcTan2);
+	ccAddExternalStaticFunction("Maths::Cos^1", Sc_Math_Cos);
+	ccAddExternalStaticFunction("Maths::Cosh^1", Sc_Math_Cosh);
+	ccAddExternalStaticFunction("Maths::DegreesToRadians^1", Sc_Math_DegreesToRadians);
+	ccAddExternalStaticFunction("Maths::Exp^1", Sc_Math_Exp);
+	ccAddExternalStaticFunction("Maths::Log^1", Sc_Math_Log);
+	ccAddExternalStaticFunction("Maths::Log10^1", Sc_Math_Log10);
+	ccAddExternalStaticFunction("Maths::RadiansToDegrees^1", Sc_Math_RadiansToDegrees);
+	ccAddExternalStaticFunction("Maths::RaiseToPower^2", Sc_Math_RaiseToPower);
+	ccAddExternalStaticFunction("Maths::Sin^1", Sc_Math_Sin);
+	ccAddExternalStaticFunction("Maths::Sinh^1", Sc_Math_Sinh);
+	ccAddExternalStaticFunction("Maths::Sqrt^1", Sc_Math_Sqrt);
+	ccAddExternalStaticFunction("Maths::Tan^1", Sc_Math_Tan);
+	ccAddExternalStaticFunction("Maths::Tanh^1", Sc_Math_Tanh);
+	ccAddExternalStaticFunction("Maths::get_Pi", Sc_Math_GetPi);
 
 	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
 
@@ -282,3 +284,5 @@ void RegisterMathAPI() {
 	ccAddExternalFunctionForPlugin("Maths::Tanh^1", (void *)Math_Tanh);
 	ccAddExternalFunctionForPlugin("Maths::get_Pi", (void *)Math_GetPi);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/mouse.cpp b/engines/ags/engine/ac/mouse.cpp
index 9b6f65c89c..8fe2714039 100644
--- a/engines/ags/engine/ac/mouse.cpp
+++ b/engines/ags/engine/ac/mouse.cpp
@@ -42,6 +42,8 @@
 #include "gfx/graphicsdriver.h"
 #include "gfx/gfxfilter.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -89,7 +91,7 @@ void SetMouseBounds(int x1, int y1, int x2, int y2) {
 	} else {
 		if (x1 < 0 || x1 > xmax || x2 < 0 || x2 > xmax || x1 > x2 || y1 < 0 || y1 > ymax || y2 < 0 || y2 > ymax || y1 > y2)
 			debug_script_warn("SetMouseBounds: arguments are out of range and will be corrected: (%d,%d)-(%d,%d), range is (%d,%d)-(%d,%d)",
-			                  x1, y1, x2, y2, 0, 0, xmax, ymax);
+				x1, y1, x2, y2, 0, 0, xmax, ymax);
 		x1 = Math::Clamp(x1, 0, xmax);
 		x2 = Math::Clamp(x2, x1, xmax);
 		y1 = Math::Clamp(y1, 0, ymax);
@@ -115,7 +117,7 @@ void set_mouse_cursor(int newcurs) {
 
 	// if it's same cursor and there's animation in progress, then don't assign a new pic just yet
 	if (newcurs == cur_cursor && game.mcurs[newcurs].view >= 0 &&
-	        (mouse_frame > 0 || mouse_delay > 0)) {
+		(mouse_frame > 0 || mouse_delay > 0)) {
 		return;
 	}
 
@@ -133,17 +135,17 @@ void set_mouse_cursor(int newcurs) {
 
 	// If it's inventory cursor, draw hotspot crosshair sprite upon it
 	if ((newcurs == MODE_USE) && (game.mcurs[newcurs].pic > 0) &&
-	        ((game.hotdot > 0) || (game.invhotdotsprite > 0))) {
+		((game.hotdot > 0) || (game.invhotdotsprite > 0))) {
 		// If necessary, create a copy of the cursor and put the hotspot
 		// dot onto it
 		dotted_mouse_cursor = BitmapHelper::CreateBitmapCopy(mousecurs[0]);
 
 		if (game.invhotdotsprite > 0) {
 			draw_sprite_slot_support_alpha(dotted_mouse_cursor,
-			                               (game.SpriteInfos[game.mcurs[newcurs].pic].Flags & SPF_ALPHACHANNEL) != 0,
-			                               hotspotx - game.SpriteInfos[game.invhotdotsprite].Width / 2,
-			                               hotspoty - game.SpriteInfos[game.invhotdotsprite].Height / 2,
-			                               game.invhotdotsprite);
+				(game.SpriteInfos[game.mcurs[newcurs].pic].Flags & SPF_ALPHACHANNEL) != 0,
+				hotspotx - game.SpriteInfos[game.invhotdotsprite].Width / 2,
+				hotspoty - game.SpriteInfos[game.invhotdotsprite].Height / 2,
+				game.invhotdotsprite);
 		} else {
 			putpixel_compensate(dotted_mouse_cursor, hotspotx, hotspoty, MakeColor(game.hotdot));
 
@@ -315,8 +317,8 @@ int IsButtonDown(int which) {
 
 int IsModeEnabled(int which) {
 	return (which < 0) || (which >= game.numcursors) ? 0 :
-	       which == MODE_USE ? playerchar->activeinv > 0 :
-	       (game.mcurs[which].flags & MCF_DISABLED) == 0;
+		which == MODE_USE ? playerchar->activeinv > 0 :
+	(game.mcurs[which].flags & MCF_DISABLED) == 0;
 }
 
 void Mouse_EnableControl(bool on) {
@@ -326,7 +328,7 @@ void Mouse_EnableControl(bool on) {
 	// Whether mouse movement should be controlled by the engine - this is
 	// determined based on related config option.
 	bool should_control_mouse = usetup.mouse_ctrl_when == kMouseCtrl_Always ||
-	                            (usetup.mouse_ctrl_when == kMouseCtrl_Fullscreen && !is_windowed);
+		(usetup.mouse_ctrl_when == kMouseCtrl_Fullscreen && !is_windowed);
 	// Whether mouse movement control is supported by the engine - this is
 	// determined on per platform basis. Some builds may not have such
 	// capability, e.g. because of how backend library implements mouse utils.
@@ -582,31 +584,31 @@ RuntimeScriptValue Sc_Mouse_SetSpeed(const RuntimeScriptValue *params, int32_t p
 }
 
 void RegisterMouseAPI() {
-	ccAddExternalStaticFunction("Mouse::ChangeModeGraphic^2",       Sc_ChangeCursorGraphic);
-	ccAddExternalStaticFunction("Mouse::ChangeModeHotspot^3",       Sc_ChangeCursorHotspot);
-	ccAddExternalStaticFunction("Mouse::ChangeModeView^2",          Sc_Mouse_ChangeModeView);
-	ccAddExternalStaticFunction("Mouse::Click^1",                   Sc_Mouse_Click);
-	ccAddExternalStaticFunction("Mouse::DisableMode^1",             Sc_disable_cursor_mode);
-	ccAddExternalStaticFunction("Mouse::EnableMode^1",              Sc_enable_cursor_mode);
-	ccAddExternalStaticFunction("Mouse::GetModeGraphic^1",          Sc_Mouse_GetModeGraphic);
-	ccAddExternalStaticFunction("Mouse::IsButtonDown^1",            Sc_IsButtonDown);
-	ccAddExternalStaticFunction("Mouse::IsModeEnabled^1",           Sc_IsModeEnabled);
+	ccAddExternalStaticFunction("Mouse::ChangeModeGraphic^2", Sc_ChangeCursorGraphic);
+	ccAddExternalStaticFunction("Mouse::ChangeModeHotspot^3", Sc_ChangeCursorHotspot);
+	ccAddExternalStaticFunction("Mouse::ChangeModeView^2", Sc_Mouse_ChangeModeView);
+	ccAddExternalStaticFunction("Mouse::Click^1", Sc_Mouse_Click);
+	ccAddExternalStaticFunction("Mouse::DisableMode^1", Sc_disable_cursor_mode);
+	ccAddExternalStaticFunction("Mouse::EnableMode^1", Sc_enable_cursor_mode);
+	ccAddExternalStaticFunction("Mouse::GetModeGraphic^1", Sc_Mouse_GetModeGraphic);
+	ccAddExternalStaticFunction("Mouse::IsButtonDown^1", Sc_IsButtonDown);
+	ccAddExternalStaticFunction("Mouse::IsModeEnabled^1", Sc_IsModeEnabled);
 	ccAddExternalStaticFunction("Mouse::SaveCursorUntilItLeaves^0", Sc_SaveCursorForLocationChange);
-	ccAddExternalStaticFunction("Mouse::SelectNextMode^0",          Sc_SetNextCursor);
-	ccAddExternalStaticFunction("Mouse::SelectPreviousMode^0",      Sc_SetPreviousCursor);
-	ccAddExternalStaticFunction("Mouse::SetBounds^4",               Sc_SetMouseBounds);
-	ccAddExternalStaticFunction("Mouse::SetPosition^2",             Sc_SetMousePosition);
-	ccAddExternalStaticFunction("Mouse::Update^0",                  Sc_RefreshMouse);
-	ccAddExternalStaticFunction("Mouse::UseDefaultGraphic^0",       Sc_set_default_cursor);
-	ccAddExternalStaticFunction("Mouse::UseModeGraphic^1",          Sc_set_mouse_cursor);
-	ccAddExternalStaticFunction("Mouse::get_ControlEnabled",        Sc_Mouse_GetControlEnabled);
-	ccAddExternalStaticFunction("Mouse::set_ControlEnabled",        Sc_Mouse_SetControlEnabled);
-	ccAddExternalStaticFunction("Mouse::get_Mode",                  Sc_GetCursorMode);
-	ccAddExternalStaticFunction("Mouse::set_Mode",                  Sc_set_cursor_mode);
-	ccAddExternalStaticFunction("Mouse::get_Speed",                 Sc_Mouse_GetSpeed);
-	ccAddExternalStaticFunction("Mouse::set_Speed",                 Sc_Mouse_SetSpeed);
-	ccAddExternalStaticFunction("Mouse::get_Visible",               Sc_Mouse_GetVisible);
-	ccAddExternalStaticFunction("Mouse::set_Visible",               Sc_Mouse_SetVisible);
+	ccAddExternalStaticFunction("Mouse::SelectNextMode^0", Sc_SetNextCursor);
+	ccAddExternalStaticFunction("Mouse::SelectPreviousMode^0", Sc_SetPreviousCursor);
+	ccAddExternalStaticFunction("Mouse::SetBounds^4", Sc_SetMouseBounds);
+	ccAddExternalStaticFunction("Mouse::SetPosition^2", Sc_SetMousePosition);
+	ccAddExternalStaticFunction("Mouse::Update^0", Sc_RefreshMouse);
+	ccAddExternalStaticFunction("Mouse::UseDefaultGraphic^0", Sc_set_default_cursor);
+	ccAddExternalStaticFunction("Mouse::UseModeGraphic^1", Sc_set_mouse_cursor);
+	ccAddExternalStaticFunction("Mouse::get_ControlEnabled", Sc_Mouse_GetControlEnabled);
+	ccAddExternalStaticFunction("Mouse::set_ControlEnabled", Sc_Mouse_SetControlEnabled);
+	ccAddExternalStaticFunction("Mouse::get_Mode", Sc_GetCursorMode);
+	ccAddExternalStaticFunction("Mouse::set_Mode", Sc_set_cursor_mode);
+	ccAddExternalStaticFunction("Mouse::get_Speed", Sc_Mouse_GetSpeed);
+	ccAddExternalStaticFunction("Mouse::set_Speed", Sc_Mouse_SetSpeed);
+	ccAddExternalStaticFunction("Mouse::get_Visible", Sc_Mouse_GetVisible);
+	ccAddExternalStaticFunction("Mouse::set_Visible", Sc_Mouse_SetVisible);
 
 	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
 
@@ -631,3 +633,5 @@ void RegisterMouseAPI() {
 	ccAddExternalFunctionForPlugin("Mouse::get_Visible", (void *)Mouse_GetVisible);
 	ccAddExternalFunctionForPlugin("Mouse::set_Visible", (void *)Mouse_SetVisible);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/movelist.cpp b/engines/ags/engine/ac/movelist.cpp
index b2402618b3..0b46fbf8fd 100644
--- a/engines/ags/engine/ac/movelist.cpp
+++ b/engines/ags/engine/ac/movelist.cpp
@@ -24,6 +24,8 @@
 #include "ac/common.h"
 #include "util/stream.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -52,7 +54,7 @@ HSaveError MoveList::ReadFromFile(Stream *in, int32_t cmp_ver) {
 	// TODO: reimplement MoveList stages as vector to avoid these limits
 	if (numstage > MAXNEEDSTAGES) {
 		return new SavegameError(kSvgErr_IncompatibleEngine,
-		                         String::FromFormat("Incompatible number of movelist steps (count: %d, max : %d).", numstage, MAXNEEDSTAGES));
+			String::FromFormat("Incompatible number of movelist steps (count: %d, max : %d).", numstage, MAXNEEDSTAGES));
 	}
 
 	fromx = in->ReadInt32();
@@ -85,3 +87,5 @@ void MoveList::WriteToFile(Stream *out) {
 	out->WriteArrayOfInt32(xpermove, numstage);
 	out->WriteArrayOfInt32(ypermove, numstage);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/object.cpp b/engines/ags/engine/ac/object.cpp
index 399f4bbbc9..3fb358320a 100644
--- a/engines/ags/engine/ac/object.cpp
+++ b/engines/ags/engine/ac/object.cpp
@@ -46,6 +46,8 @@
 #include "ac/dynobj/cc_object.h"
 #include "ac/movelist.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 
@@ -870,76 +872,76 @@ RuntimeScriptValue Sc_Object_SetY(void *self, const RuntimeScriptValue *params,
 
 
 void RegisterObjectAPI() {
-	ccAddExternalObjectFunction("Object::Animate^5",                Sc_Object_Animate);
-	ccAddExternalObjectFunction("Object::Animate^6",                Sc_Object_AnimateFrom);
-	ccAddExternalObjectFunction("Object::IsCollidingWithObject^1",  Sc_Object_IsCollidingWithObject);
-	ccAddExternalObjectFunction("Object::GetName^1",                Sc_Object_GetName);
-	ccAddExternalObjectFunction("Object::GetProperty^1",            Sc_Object_GetProperty);
-	ccAddExternalObjectFunction("Object::GetPropertyText^2",        Sc_Object_GetPropertyText);
-	ccAddExternalObjectFunction("Object::GetTextProperty^1",        Sc_Object_GetTextProperty);
-	ccAddExternalObjectFunction("Object::SetProperty^2",            Sc_Object_SetProperty);
-	ccAddExternalObjectFunction("Object::SetTextProperty^2",        Sc_Object_SetTextProperty);
+	ccAddExternalObjectFunction("Object::Animate^5", Sc_Object_Animate);
+	ccAddExternalObjectFunction("Object::Animate^6", Sc_Object_AnimateFrom);
+	ccAddExternalObjectFunction("Object::IsCollidingWithObject^1", Sc_Object_IsCollidingWithObject);
+	ccAddExternalObjectFunction("Object::GetName^1", Sc_Object_GetName);
+	ccAddExternalObjectFunction("Object::GetProperty^1", Sc_Object_GetProperty);
+	ccAddExternalObjectFunction("Object::GetPropertyText^2", Sc_Object_GetPropertyText);
+	ccAddExternalObjectFunction("Object::GetTextProperty^1", Sc_Object_GetTextProperty);
+	ccAddExternalObjectFunction("Object::SetProperty^2", Sc_Object_SetProperty);
+	ccAddExternalObjectFunction("Object::SetTextProperty^2", Sc_Object_SetTextProperty);
 	ccAddExternalObjectFunction("Object::IsInteractionAvailable^1", Sc_Object_IsInteractionAvailable);
-	ccAddExternalObjectFunction("Object::MergeIntoBackground^0",    Sc_Object_MergeIntoBackground);
-	ccAddExternalObjectFunction("Object::Move^5",                   Sc_Object_Move);
-	ccAddExternalObjectFunction("Object::RemoveTint^0",             Sc_Object_RemoveTint);
-	ccAddExternalObjectFunction("Object::RunInteraction^1",         Sc_Object_RunInteraction);
-	ccAddExternalObjectFunction("Object::SetLightLevel^1",          Sc_Object_SetLightLevel);
-	ccAddExternalObjectFunction("Object::SetPosition^2",            Sc_Object_SetPosition);
-	ccAddExternalObjectFunction("Object::SetView^3",                Sc_Object_SetView);
-	ccAddExternalObjectFunction("Object::StopAnimating^0",          Sc_Object_StopAnimating);
-	ccAddExternalObjectFunction("Object::StopMoving^0",             Sc_Object_StopMoving);
-	ccAddExternalObjectFunction("Object::Tint^5",                   Sc_Object_Tint);
+	ccAddExternalObjectFunction("Object::MergeIntoBackground^0", Sc_Object_MergeIntoBackground);
+	ccAddExternalObjectFunction("Object::Move^5", Sc_Object_Move);
+	ccAddExternalObjectFunction("Object::RemoveTint^0", Sc_Object_RemoveTint);
+	ccAddExternalObjectFunction("Object::RunInteraction^1", Sc_Object_RunInteraction);
+	ccAddExternalObjectFunction("Object::SetLightLevel^1", Sc_Object_SetLightLevel);
+	ccAddExternalObjectFunction("Object::SetPosition^2", Sc_Object_SetPosition);
+	ccAddExternalObjectFunction("Object::SetView^3", Sc_Object_SetView);
+	ccAddExternalObjectFunction("Object::StopAnimating^0", Sc_Object_StopAnimating);
+	ccAddExternalObjectFunction("Object::StopMoving^0", Sc_Object_StopMoving);
+	ccAddExternalObjectFunction("Object::Tint^5", Sc_Object_Tint);
 
 	// static
-	ccAddExternalStaticFunction("Object::GetAtRoomXY^2",            Sc_GetObjectAtRoom);
-	ccAddExternalStaticFunction("Object::GetAtScreenXY^2",          Sc_GetObjectAtScreen);
-
-	ccAddExternalObjectFunction("Object::get_Animating",            Sc_Object_GetAnimating);
-	ccAddExternalObjectFunction("Object::get_Baseline",             Sc_Object_GetBaseline);
-	ccAddExternalObjectFunction("Object::set_Baseline",             Sc_Object_SetBaseline);
-	ccAddExternalObjectFunction("Object::get_BlockingHeight",       Sc_Object_GetBlockingHeight);
-	ccAddExternalObjectFunction("Object::set_BlockingHeight",       Sc_Object_SetBlockingHeight);
-	ccAddExternalObjectFunction("Object::get_BlockingWidth",        Sc_Object_GetBlockingWidth);
-	ccAddExternalObjectFunction("Object::set_BlockingWidth",        Sc_Object_SetBlockingWidth);
-	ccAddExternalObjectFunction("Object::get_Clickable",            Sc_Object_GetClickable);
-	ccAddExternalObjectFunction("Object::set_Clickable",            Sc_Object_SetClickable);
-	ccAddExternalObjectFunction("Object::get_Frame",                Sc_Object_GetFrame);
-	ccAddExternalObjectFunction("Object::get_Graphic",              Sc_Object_GetGraphic);
-	ccAddExternalObjectFunction("Object::set_Graphic",              Sc_Object_SetGraphic);
-	ccAddExternalObjectFunction("Object::get_ID",                   Sc_Object_GetID);
-	ccAddExternalObjectFunction("Object::get_IgnoreScaling",        Sc_Object_GetIgnoreScaling);
-	ccAddExternalObjectFunction("Object::set_IgnoreScaling",        Sc_Object_SetIgnoreScaling);
-	ccAddExternalObjectFunction("Object::get_IgnoreWalkbehinds",    Sc_Object_GetIgnoreWalkbehinds);
-	ccAddExternalObjectFunction("Object::set_IgnoreWalkbehinds",    Sc_Object_SetIgnoreWalkbehinds);
-	ccAddExternalObjectFunction("Object::get_Loop",                 Sc_Object_GetLoop);
-	ccAddExternalObjectFunction("Object::get_ManualScaling",        Sc_Object_GetIgnoreScaling);
-	ccAddExternalObjectFunction("Object::set_ManualScaling",        Sc_Object_SetManualScaling);
-	ccAddExternalObjectFunction("Object::get_Moving",               Sc_Object_GetMoving);
-	ccAddExternalObjectFunction("Object::get_Name",                 Sc_Object_GetName_New);
-	ccAddExternalObjectFunction("Object::get_Scaling",              Sc_Object_GetScaling);
-	ccAddExternalObjectFunction("Object::set_Scaling",              Sc_Object_SetScaling);
-	ccAddExternalObjectFunction("Object::get_Solid",                Sc_Object_GetSolid);
-	ccAddExternalObjectFunction("Object::set_Solid",                Sc_Object_SetSolid);
-	ccAddExternalObjectFunction("Object::get_Transparency",         Sc_Object_GetTransparency);
-	ccAddExternalObjectFunction("Object::set_Transparency",         Sc_Object_SetTransparency);
-	ccAddExternalObjectFunction("Object::get_View",                 Sc_Object_GetView);
-	ccAddExternalObjectFunction("Object::get_Visible",              Sc_Object_GetVisible);
-	ccAddExternalObjectFunction("Object::set_Visible",              Sc_Object_SetVisible);
-	ccAddExternalObjectFunction("Object::get_X",                    Sc_Object_GetX);
-	ccAddExternalObjectFunction("Object::set_X",                    Sc_Object_SetX);
-	ccAddExternalObjectFunction("Object::get_Y",                    Sc_Object_GetY);
-	ccAddExternalObjectFunction("Object::set_Y",                    Sc_Object_SetY);
-
-	ccAddExternalObjectFunction("Object::get_HasExplicitLight",     Sc_Object_HasExplicitLight);
-	ccAddExternalObjectFunction("Object::get_HasExplicitTint",      Sc_Object_HasExplicitTint);
-	ccAddExternalObjectFunction("Object::get_LightLevel",           Sc_Object_GetLightLevel);
-	ccAddExternalObjectFunction("Object::set_LightLevel",           Sc_Object_SetLightLevel);
-	ccAddExternalObjectFunction("Object::get_TintBlue",             Sc_Object_GetTintBlue);
-	ccAddExternalObjectFunction("Object::get_TintGreen",            Sc_Object_GetTintGreen);
-	ccAddExternalObjectFunction("Object::get_TintRed",              Sc_Object_GetTintRed);
-	ccAddExternalObjectFunction("Object::get_TintSaturation",       Sc_Object_GetTintSaturation);
-	ccAddExternalObjectFunction("Object::get_TintLuminance",        Sc_Object_GetTintLuminance);
+	ccAddExternalStaticFunction("Object::GetAtRoomXY^2", Sc_GetObjectAtRoom);
+	ccAddExternalStaticFunction("Object::GetAtScreenXY^2", Sc_GetObjectAtScreen);
+
+	ccAddExternalObjectFunction("Object::get_Animating", Sc_Object_GetAnimating);
+	ccAddExternalObjectFunction("Object::get_Baseline", Sc_Object_GetBaseline);
+	ccAddExternalObjectFunction("Object::set_Baseline", Sc_Object_SetBaseline);
+	ccAddExternalObjectFunction("Object::get_BlockingHeight", Sc_Object_GetBlockingHeight);
+	ccAddExternalObjectFunction("Object::set_BlockingHeight", Sc_Object_SetBlockingHeight);
+	ccAddExternalObjectFunction("Object::get_BlockingWidth", Sc_Object_GetBlockingWidth);
+	ccAddExternalObjectFunction("Object::set_BlockingWidth", Sc_Object_SetBlockingWidth);
+	ccAddExternalObjectFunction("Object::get_Clickable", Sc_Object_GetClickable);
+	ccAddExternalObjectFunction("Object::set_Clickable", Sc_Object_SetClickable);
+	ccAddExternalObjectFunction("Object::get_Frame", Sc_Object_GetFrame);
+	ccAddExternalObjectFunction("Object::get_Graphic", Sc_Object_GetGraphic);
+	ccAddExternalObjectFunction("Object::set_Graphic", Sc_Object_SetGraphic);
+	ccAddExternalObjectFunction("Object::get_ID", Sc_Object_GetID);
+	ccAddExternalObjectFunction("Object::get_IgnoreScaling", Sc_Object_GetIgnoreScaling);
+	ccAddExternalObjectFunction("Object::set_IgnoreScaling", Sc_Object_SetIgnoreScaling);
+	ccAddExternalObjectFunction("Object::get_IgnoreWalkbehinds", Sc_Object_GetIgnoreWalkbehinds);
+	ccAddExternalObjectFunction("Object::set_IgnoreWalkbehinds", Sc_Object_SetIgnoreWalkbehinds);
+	ccAddExternalObjectFunction("Object::get_Loop", Sc_Object_GetLoop);
+	ccAddExternalObjectFunction("Object::get_ManualScaling", Sc_Object_GetIgnoreScaling);
+	ccAddExternalObjectFunction("Object::set_ManualScaling", Sc_Object_SetManualScaling);
+	ccAddExternalObjectFunction("Object::get_Moving", Sc_Object_GetMoving);
+	ccAddExternalObjectFunction("Object::get_Name", Sc_Object_GetName_New);
+	ccAddExternalObjectFunction("Object::get_Scaling", Sc_Object_GetScaling);
+	ccAddExternalObjectFunction("Object::set_Scaling", Sc_Object_SetScaling);
+	ccAddExternalObjectFunction("Object::get_Solid", Sc_Object_GetSolid);
+	ccAddExternalObjectFunction("Object::set_Solid", Sc_Object_SetSolid);
+	ccAddExternalObjectFunction("Object::get_Transparency", Sc_Object_GetTransparency);
+	ccAddExternalObjectFunction("Object::set_Transparency", Sc_Object_SetTransparency);
+	ccAddExternalObjectFunction("Object::get_View", Sc_Object_GetView);
+	ccAddExternalObjectFunction("Object::get_Visible", Sc_Object_GetVisible);
+	ccAddExternalObjectFunction("Object::set_Visible", Sc_Object_SetVisible);
+	ccAddExternalObjectFunction("Object::get_X", Sc_Object_GetX);
+	ccAddExternalObjectFunction("Object::set_X", Sc_Object_SetX);
+	ccAddExternalObjectFunction("Object::get_Y", Sc_Object_GetY);
+	ccAddExternalObjectFunction("Object::set_Y", Sc_Object_SetY);
+
+	ccAddExternalObjectFunction("Object::get_HasExplicitLight", Sc_Object_HasExplicitLight);
+	ccAddExternalObjectFunction("Object::get_HasExplicitTint", Sc_Object_HasExplicitTint);
+	ccAddExternalObjectFunction("Object::get_LightLevel", Sc_Object_GetLightLevel);
+	ccAddExternalObjectFunction("Object::set_LightLevel", Sc_Object_SetLightLevel);
+	ccAddExternalObjectFunction("Object::get_TintBlue", Sc_Object_GetTintBlue);
+	ccAddExternalObjectFunction("Object::get_TintGreen", Sc_Object_GetTintGreen);
+	ccAddExternalObjectFunction("Object::get_TintRed", Sc_Object_GetTintRed);
+	ccAddExternalObjectFunction("Object::get_TintSaturation", Sc_Object_GetTintSaturation);
+	ccAddExternalObjectFunction("Object::get_TintLuminance", Sc_Object_GetTintLuminance);
 
 	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
 
@@ -992,3 +994,5 @@ void RegisterObjectAPI() {
 	ccAddExternalFunctionForPlugin("Object::get_Y", (void *)Object_GetY);
 	ccAddExternalFunctionForPlugin("Object::set_Y", (void *)Object_SetY);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/overlay.cpp b/engines/ags/engine/ac/overlay.cpp
index 8f6fe78dc7..f9b40cbec4 100644
--- a/engines/ags/engine/ac/overlay.cpp
+++ b/engines/ags/engine/ac/overlay.cpp
@@ -38,6 +38,8 @@
 #include "gfx/bitmap.h"
 #include "script/runtimescriptvalue.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -238,8 +240,8 @@ void get_overlay_position(const ScreenOverlay &over, int *x, int *y) {
 		const int charpic = views[game.chars[charid].view].loops[game.chars[charid].loop].frames[0].pic;
 		const int height = (charextra[charid].height < 1) ? game.SpriteInfos[charpic].Height : charextra[charid].height;
 		Point screenpt = view->RoomToScreen(
-		                     data_to_game_coord(game.chars[charid].x),
-		                     data_to_game_coord(game.chars[charid].get_effective_y()) - height).first;
+			data_to_game_coord(game.chars[charid].x),
+			data_to_game_coord(game.chars[charid].get_effective_y()) - height).first;
 		tdxp = screenpt.X - over.pic->GetWidth() / 2;
 		if (tdxp < 0) tdxp = 0;
 		tdyp = screenpt.Y - get_fixed_pixel_size(5);
@@ -298,7 +300,7 @@ RuntimeScriptValue Sc_Overlay_CreateGraphical(const RuntimeScriptValue *params,
 RuntimeScriptValue Sc_Overlay_CreateTextual(const RuntimeScriptValue *params, int32_t param_count) {
 	API_SCALL_SCRIPT_SPRINTF(Overlay_CreateTextual, 6);
 	ScriptOverlay *overlay = Overlay_CreateTextual(params[0].IValue, params[1].IValue, params[2].IValue,
-	                         params[3].IValue, params[4].IValue, scsf_buffer);
+		params[3].IValue, params[4].IValue, scsf_buffer);
 	return RuntimeScriptValue().SetDynamicObject(overlay, overlay);
 }
 
@@ -359,15 +361,15 @@ void ScPl_Overlay_SetText(ScriptOverlay *scover, int wii, int fontid, int clr, c
 
 
 void RegisterOverlayAPI() {
-	ccAddExternalStaticFunction("Overlay::CreateGraphical^4",   Sc_Overlay_CreateGraphical);
-	ccAddExternalStaticFunction("Overlay::CreateTextual^106",   Sc_Overlay_CreateTextual);
-	ccAddExternalObjectFunction("Overlay::SetText^104",         Sc_Overlay_SetText);
-	ccAddExternalObjectFunction("Overlay::Remove^0",            Sc_Overlay_Remove);
-	ccAddExternalObjectFunction("Overlay::get_Valid",           Sc_Overlay_GetValid);
-	ccAddExternalObjectFunction("Overlay::get_X",               Sc_Overlay_GetX);
-	ccAddExternalObjectFunction("Overlay::set_X",               Sc_Overlay_SetX);
-	ccAddExternalObjectFunction("Overlay::get_Y",               Sc_Overlay_GetY);
-	ccAddExternalObjectFunction("Overlay::set_Y",               Sc_Overlay_SetY);
+	ccAddExternalStaticFunction("Overlay::CreateGraphical^4", Sc_Overlay_CreateGraphical);
+	ccAddExternalStaticFunction("Overlay::CreateTextual^106", Sc_Overlay_CreateTextual);
+	ccAddExternalObjectFunction("Overlay::SetText^104", Sc_Overlay_SetText);
+	ccAddExternalObjectFunction("Overlay::Remove^0", Sc_Overlay_Remove);
+	ccAddExternalObjectFunction("Overlay::get_Valid", Sc_Overlay_GetValid);
+	ccAddExternalObjectFunction("Overlay::get_X", Sc_Overlay_GetX);
+	ccAddExternalObjectFunction("Overlay::set_X", Sc_Overlay_SetX);
+	ccAddExternalObjectFunction("Overlay::get_Y", Sc_Overlay_GetY);
+	ccAddExternalObjectFunction("Overlay::set_Y", Sc_Overlay_SetY);
 
 	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
 
@@ -381,3 +383,5 @@ void RegisterOverlayAPI() {
 	ccAddExternalFunctionForPlugin("Overlay::get_Y", (void *)Overlay_GetY);
 	ccAddExternalFunctionForPlugin("Overlay::set_Y", (void *)Overlay_SetY);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/parser.cpp b/engines/ags/engine/ac/parser.cpp
index c966d4d9fd..66fc367497 100644
--- a/engines/ags/engine/ac/parser.cpp
+++ b/engines/ags/engine/ac/parser.cpp
@@ -32,6 +32,8 @@
 #include "util/string.h"
 #include "util/string_compat.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern GameSetupStruct game;
@@ -207,8 +209,8 @@ int parse_sentence(const char *src_text, int *numwords, short *wordarray, short
 				}
 				if (word <= 0)
 					quitprintf("!Said: supplied word '%s' is not in dictionary or is an ignored word\nText: %s", thisword, src_text);
-				if (word == ANYWORD) { }
-				else if (word != compareto[comparing]) {
+				if (word == ANYWORD) {
+				} else if (word != compareto[comparing]) {
 					// words don't match - if a comma then a list of possibles,
 					// so allow retry
 					if (text[0] == ',')
@@ -329,10 +331,10 @@ RuntimeScriptValue Sc_Said(const RuntimeScriptValue *params, int32_t param_count
 
 
 void RegisterParserAPI() {
-	ccAddExternalStaticFunction("Parser::FindWordID^1",     Sc_Parser_FindWordID);
-	ccAddExternalStaticFunction("Parser::ParseText^1",      Sc_ParseText);
+	ccAddExternalStaticFunction("Parser::FindWordID^1", Sc_Parser_FindWordID);
+	ccAddExternalStaticFunction("Parser::ParseText^1", Sc_ParseText);
 	ccAddExternalStaticFunction("Parser::SaidUnknownWord^0", Sc_Parser_SaidUnknownWord);
-	ccAddExternalStaticFunction("Parser::Said^1",           Sc_Said);
+	ccAddExternalStaticFunction("Parser::Said^1", Sc_Said);
 
 	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
 
@@ -341,3 +343,5 @@ void RegisterParserAPI() {
 	ccAddExternalFunctionForPlugin("Parser::SaidUnknownWord^0", (void *)Parser_SaidUnknownWord);
 	ccAddExternalFunctionForPlugin("Parser::Said^1", (void *)Said);
 }
+
+} // namespace ASG3
diff --git a/engines/ags/engine/ac/properties.cpp b/engines/ags/engine/ac/properties.cpp
index e68c908cbd..84082a6e8e 100644
--- a/engines/ags/engine/ac/properties.cpp
+++ b/engines/ags/engine/ac/properties.cpp
@@ -28,6 +28,8 @@
 #include "script/runtimescriptvalue.h"
 #include "util/string_utils.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern GameSetupStruct game;
@@ -104,3 +106,5 @@ bool set_text_property(StringIMap &rt_prop, const char *property, const char *va
 	}
 	return false;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/region.cpp b/engines/ags/engine/ac/region.cpp
index 27a3d05ea5..9e12a5b705 100644
--- a/engines/ags/engine/ac/region.cpp
+++ b/engines/ags/engine/ac/region.cpp
@@ -32,6 +32,8 @@
 #include "game/roomstruct.h"
 #include "script/runtimescriptvalue.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern ScriptRegion scrRegion[MAX_ROOM_REGIONS];
@@ -223,23 +225,23 @@ RuntimeScriptValue Sc_Region_GetTintLuminance(void *self, const RuntimeScriptVal
 
 
 void RegisterRegionAPI() {
-	ccAddExternalStaticFunction("Region::GetAtRoomXY^2",        Sc_GetRegionAtRoom);
-	ccAddExternalStaticFunction("Region::GetAtScreenXY^2",      Sc_GetRegionAtScreen);
-	ccAddExternalStaticFunction("Region::GetDrawingSurface",    Sc_Region_GetDrawingSurface);
-	ccAddExternalObjectFunction("Region::Tint^4",               Sc_Region_TintNoLum);
-	ccAddExternalObjectFunction("Region::Tint^5",               Sc_Region_Tint);
-	ccAddExternalObjectFunction("Region::RunInteraction^1",     Sc_Region_RunInteraction);
-	ccAddExternalObjectFunction("Region::get_Enabled",          Sc_Region_GetEnabled);
-	ccAddExternalObjectFunction("Region::set_Enabled",          Sc_Region_SetEnabled);
-	ccAddExternalObjectFunction("Region::get_ID",               Sc_Region_GetID);
-	ccAddExternalObjectFunction("Region::get_LightLevel",       Sc_Region_GetLightLevel);
-	ccAddExternalObjectFunction("Region::set_LightLevel",       Sc_Region_SetLightLevel);
-	ccAddExternalObjectFunction("Region::get_TintEnabled",      Sc_Region_GetTintEnabled);
-	ccAddExternalObjectFunction("Region::get_TintBlue",         Sc_Region_GetTintBlue);
-	ccAddExternalObjectFunction("Region::get_TintGreen",        Sc_Region_GetTintGreen);
-	ccAddExternalObjectFunction("Region::get_TintRed",          Sc_Region_GetTintRed);
-	ccAddExternalObjectFunction("Region::get_TintSaturation",   Sc_Region_GetTintSaturation);
-	ccAddExternalObjectFunction("Region::get_TintLuminance",    Sc_Region_GetTintLuminance);
+	ccAddExternalStaticFunction("Region::GetAtRoomXY^2", Sc_GetRegionAtRoom);
+	ccAddExternalStaticFunction("Region::GetAtScreenXY^2", Sc_GetRegionAtScreen);
+	ccAddExternalStaticFunction("Region::GetDrawingSurface", Sc_Region_GetDrawingSurface);
+	ccAddExternalObjectFunction("Region::Tint^4", Sc_Region_TintNoLum);
+	ccAddExternalObjectFunction("Region::Tint^5", Sc_Region_Tint);
+	ccAddExternalObjectFunction("Region::RunInteraction^1", Sc_Region_RunInteraction);
+	ccAddExternalObjectFunction("Region::get_Enabled", Sc_Region_GetEnabled);
+	ccAddExternalObjectFunction("Region::set_Enabled", Sc_Region_SetEnabled);
+	ccAddExternalObjectFunction("Region::get_ID", Sc_Region_GetID);
+	ccAddExternalObjectFunction("Region::get_LightLevel", Sc_Region_GetLightLevel);
+	ccAddExternalObjectFunction("Region::set_LightLevel", Sc_Region_SetLightLevel);
+	ccAddExternalObjectFunction("Region::get_TintEnabled", Sc_Region_GetTintEnabled);
+	ccAddExternalObjectFunction("Region::get_TintBlue", Sc_Region_GetTintBlue);
+	ccAddExternalObjectFunction("Region::get_TintGreen", Sc_Region_GetTintGreen);
+	ccAddExternalObjectFunction("Region::get_TintRed", Sc_Region_GetTintRed);
+	ccAddExternalObjectFunction("Region::get_TintSaturation", Sc_Region_GetTintSaturation);
+	ccAddExternalObjectFunction("Region::get_TintLuminance", Sc_Region_GetTintLuminance);
 
 	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
 
@@ -258,3 +260,5 @@ void RegisterRegionAPI() {
 	ccAddExternalFunctionForPlugin("Region::get_TintRed", (void *)Region_GetTintRed);
 	ccAddExternalFunctionForPlugin("Region::get_TintSaturation", (void *)Region_GetTintSaturation);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/richgamemedia.cpp b/engines/ags/engine/ac/richgamemedia.cpp
index 3bf8e2c68c..0c15a3f702 100644
--- a/engines/ags/engine/ac/richgamemedia.cpp
+++ b/engines/ags/engine/ac/richgamemedia.cpp
@@ -23,6 +23,8 @@
 #include "ac/richgamemedia.h"
 #include "util/stream.h"
 
+namespace AGS3 {
+
 using AGS::Shared::Stream;
 
 void RICH_GAME_MEDIA_HEADER::ReadFromFile(Stream *in) {
@@ -52,3 +54,5 @@ void RICH_GAME_MEDIA_HEADER::WriteToFile(Stream *out) {
 	out->WriteArrayOfInt16((int16_t *)szLevelName, RM_MAXLENGTH);
 	out->WriteArrayOfInt16((int16_t *)szComments, RM_MAXLENGTH);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/room.cpp b/engines/ags/engine/ac/room.cpp
index d2055e6049..8b7b4276d0 100644
--- a/engines/ags/engine/ac/room.cpp
+++ b/engines/ags/engine/ac/room.cpp
@@ -77,6 +77,8 @@
 #include "util/math.h"
 #include "media/audio/audio_system.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -1222,3 +1224,5 @@ void RegisterRoomAPI() {
 	ccAddExternalFunctionForPlugin("Room::get_TopEdge", (void *)Room_GetTopEdge);
 	ccAddExternalFunctionForPlugin("Room::get_Width", (void *)Room_GetWidth);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/roomobject.cpp b/engines/ags/engine/ac/roomobject.cpp
index ac9a7b05e4..92947e3db7 100644
--- a/engines/ags/engine/ac/roomobject.cpp
+++ b/engines/ags/engine/ac/roomobject.cpp
@@ -30,6 +30,8 @@
 #include "main/update.h"
 #include "util/stream.h"
 
+namespace AGS3 {
+
 using AGS::Shared::Stream;
 
 extern ViewStruct *views;
@@ -121,8 +123,8 @@ void RoomObject::update_cycle_view_forwards() {
 			if (play.no_multiloop_repeat == 0) {
 				// multi-loop anims, go back to start of it
 				while ((loop > 0) &&
-				        (views[view].loops[loop - 1].RunNextLoop()))
-					loop --;
+					(views[view].loops[loop - 1].RunNextLoop()))
+					loop--;
 			}
 			if (cycling % ANIM_BACKWARDS == ANIM_ONCERESET)
 				cycling = 0;
@@ -136,9 +138,9 @@ void RoomObject::update_cycle_view_backwards() {
 	frame--;
 	if (frame < 0) {
 		if ((loop > 0) &&
-		        (views[view].loops[loop - 1].RunNextLoop())) {
+			(views[view].loops[loop - 1].RunNextLoop())) {
 			// If it's a Go-to-next-loop on the previous one, then go back
-			loop --;
+			loop--;
 			frame = views[view].loops[loop].numFrames - 1;
 		} else if (cycling % ANIM_BACKWARDS == ANIM_ONCE) {
 			// leave it on the first frame
@@ -163,3 +165,5 @@ void RoomObject::WriteToFile(Stream *out) const {
 	out->WriteArrayOfInt8((int8_t *)&cycling, 4);
 	out->WriteArrayOfInt16(&blocking_width, 2);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/roomstatus.cpp b/engines/ags/engine/ac/roomstatus.cpp
index 368875d0bf..3687e476b5 100644
--- a/engines/ags/engine/ac/roomstatus.cpp
+++ b/engines/ags/engine/ac/roomstatus.cpp
@@ -29,6 +29,8 @@
 #include "game/savegame_components.h"
 #include "util/alignedstream.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -47,12 +49,12 @@ RoomStatus::RoomStatus() {
 
 RoomStatus::~RoomStatus() {
 	if (tsdata)
-		delete [] tsdata;
+		delete[] tsdata;
 }
 
 void RoomStatus::FreeScriptData() {
 	if (tsdata)
-		delete [] tsdata;
+		delete[] tsdata;
 	tsdata = nullptr;
 	tsdatasize = 0;
 }
@@ -212,3 +214,5 @@ void resetRoomStatuses() {
 		}
 	}
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/route_finder.cpp b/engines/ags/engine/ac/route_finder.cpp
index 5de75a3e04..44fa3464fd 100644
--- a/engines/ags/engine/ac/route_finder.cpp
+++ b/engines/ags/engine/ac/route_finder.cpp
@@ -27,6 +27,8 @@
 
 #include "debug/out.h"
 
+namespace AGS3 {
+
 using AGS::Shared::Bitmap;
 
 class IRouteFinder {
@@ -138,3 +140,5 @@ int find_route(short srcx, short srcy, short xx, short yy, Bitmap *onscreen, int
 void calculate_move_stage(MoveList *mlsp, int aaa) {
 	route_finder_impl->calculate_move_stage(mlsp, aaa);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/route_finder_impl.cpp b/engines/ags/engine/ac/route_finder_impl.cpp
index 66970fb31f..a9d93a6bb5 100644
--- a/engines/ags/engine/ac/route_finder_impl.cpp
+++ b/engines/ags/engine/ac/route_finder_impl.cpp
@@ -39,6 +39,8 @@
 
 #include "route_finder_jps.inl"
 
+namespace AGS3 {
+
 extern MoveList *mls;
 
 using AGS::Shared::Bitmap;
@@ -265,3 +267,4 @@ int find_route(short srcx, short srcy, short xx, short yy, Bitmap *onscreen, int
 } // namespace RouteFinder
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/route_finder_impl_legacy.cpp b/engines/ags/engine/ac/route_finder_impl_legacy.cpp
index 4bbe4c35e6..be4c99a9d1 100644
--- a/engines/ags/engine/ac/route_finder_impl_legacy.cpp
+++ b/engines/ags/engine/ac/route_finder_impl_legacy.cpp
@@ -39,6 +39,8 @@
 #include "gfx/bitmap.h"
 #include "debug/out.h"
 
+namespace AGS3 {
+
 extern void update_polled_stuff_if_runtime();
 
 extern MoveList *mls;
@@ -85,11 +87,11 @@ static int lastcx, lastcy;
 static void line_callback(BITMAP *bmpp, int x, int y, int d) {
 	/*  if ((x>=320) | (y>=200) | (x<0) | (y<0)) line_failed=1;
 	  else */ if (getpixel(bmpp, x, y) < 1)
-		line_failed = 1;
-	else if (line_failed == 0) {
-		lastcx = x;
-		lastcy = y;
-	}
+		  line_failed = 1;
+	  else if (line_failed == 0) {
+		  lastcx = x;
+		  lastcy = y;
+	  }
 }
 
 
@@ -330,7 +332,7 @@ try_again:
 	}
 
 	if (((nextx < 0) | (nextx >= wallscreen->GetWidth()) | (nexty < 0) | (nexty >= wallscreen->GetHeight())) ||
-	        (wallscreen->GetPixel(nextx, nexty) == 0) || ((beenhere[srcy][srcx] & (1 << trydir)) != 0)) {
+		(wallscreen->GetPixel(nextx, nexty) == 0) || ((beenhere[srcy][srcx] & (1 << trydir)) != 0)) {
 
 		if (leftorright == 0) {
 			trydir++;
@@ -344,7 +346,7 @@ try_again:
 		goto try_again;
 	}
 	beenhere[srcy][srcx] |= (1 << trydir);
-//  srcx=nextx; srcy=nexty;
+	//  srcx=nextx; srcy=nexty;
 	beenhere[srcy][srcx] |= 0x80; // being processed
 
 	int retcod = try_this_square(nextx, nexty, tox, toy);
@@ -435,7 +437,7 @@ static int find_route_dijkstra(int fromx, int fromy, int destx, int desty) {
 		return 1;
 	}
 
-	int allocsize = int (wallscreen->GetWidth()) * int (wallscreen->GetHeight()) * sizeof(int);
+	int allocsize = int(wallscreen->GetWidth()) * int(wallscreen->GetHeight()) * sizeof(int);
 	int *parent = (int *)malloc(allocsize);
 	int min = 999999, cheapest[40], newcell[40], replace[40];
 	int *visited = (int *)malloc(MAX_TRAIL_LENGTH * sizeof(int));
@@ -511,8 +513,8 @@ static int find_route_dijkstra(int fromx, int fromy, int destx, int desty) {
 			newx = newcell[p] % wallscreen->GetWidth();
 			newy = newcell[p] / wallscreen->GetWidth();
 			beenhere[newy][newx] = beenhere[cheapest[p] / wallscreen->GetWidth()][cheapest[p] % wallscreen->GetWidth()] + 1;
-//      int wal = walk_area_granularity[->GetPixel(wallscreen, newx, newy)];
-//      beenhere[newy - newy%wal][newx - newx%wal] = beenhere[newy][newx];
+			//      int wal = walk_area_granularity[->GetPixel(wallscreen, newx, newy)];
+			//      beenhere[newy - newy%wal][newx - newx%wal] = beenhere[newy][newx];
 			parent[newcell[p]] = cheapest[p];
 
 			// edges of screen pose a problem, so if current and dest are within
@@ -525,7 +527,7 @@ static int find_route_dijkstra(int fromx, int fromy, int destx, int desty) {
 
 			// Found the desination, abort loop
 			if ((newx >= destxlow) && (newx <= destxhi) && (newy >= destylow)
-			        && (newy <= destyhi)) {
+				&& (newy <= destyhi)) {
 				foundAnswer = newcell[p];
 				break;
 			}
@@ -578,7 +580,7 @@ static int find_route_dijkstra(int fromx, int fromy, int destx, int desty) {
 		newx = on % wallscreen->GetWidth();
 		newy = on / wallscreen->GetWidth();
 		if ((newx >= destxlow) && (newx <= destxhi) && (newy >= destylow)
-		        && (newy <= destyhi))
+			&& (newy <= destyhi))
 			break;
 
 		pathbackx[pathbackstage] = on % wallscreen->GetWidth();
@@ -816,7 +818,7 @@ stage_again:
 		}
 
 		if ((nearestpos == 0) && (can_see_from(srcx, srcy, xx, yy) == 0) &&
-		        (srcx >= 0) && (srcy >= 0) && (srcx < wallscreen->GetWidth()) && (srcy < wallscreen->GetHeight()) && (pathbackstage > 0)) {
+			(srcx >= 0) && (srcy >= 0) && (srcx < wallscreen->GetWidth()) && (srcy < wallscreen->GetHeight()) && (pathbackstage > 0)) {
 			// If we couldn't see anything, we're stuck in a corner so advance
 			// to the next square anyway (but only if they're on the screen)
 			nearestindx = pathbackstage - 1;
@@ -906,8 +908,7 @@ void shutdown_pathfinder() {
 	beenhere_array_size = 0;
 }
 
-
-
 } // namespace RouteFinderLegacy
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/screen.cpp b/engines/ags/engine/ac/screen.cpp
index 299fb1d63f..ccdba13745 100644
--- a/engines/ags/engine/ac/screen.cpp
+++ b/engines/ags/engine/ac/screen.cpp
@@ -36,6 +36,8 @@
 #include "gfx/bitmap.h"
 #include "gfx/graphicsdriver.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -206,3 +208,5 @@ void RegisterScreenAPI() {
 	ccAddExternalStaticFunction("Screen::ScreenToRoomPoint", Sc_Screen_ScreenToRoomPoint);
 	ccAddExternalStaticFunction("Screen::RoomToScreenPoint", Sc_Screen_RoomToScreenPoint);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/screenoverlay.cpp b/engines/ags/engine/ac/screenoverlay.cpp
index 59926bbc87..ed1a886f52 100644
--- a/engines/ags/engine/ac/screenoverlay.cpp
+++ b/engines/ags/engine/ac/screenoverlay.cpp
@@ -23,6 +23,8 @@
 #include "screenoverlay.h"
 #include "util/stream.h"
 
+namespace AGS3 {
+
 using AGS::Shared::Stream;
 
 void ScreenOverlay::ReadFromFile(Stream *in, int32_t cmp_ver) {
@@ -62,3 +64,5 @@ void ScreenOverlay::WriteToFile(Stream *out) const {
 	out->WriteInt32(_offsetX);
 	out->WriteInt32(_offsetY);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/scriptcontainers.cpp b/engines/ags/engine/ac/scriptcontainers.cpp
index 6913fa606b..5b33fdd3a3 100644
--- a/engines/ags/engine/ac/scriptcontainers.cpp
+++ b/engines/ags/engine/ac/scriptcontainers.cpp
@@ -37,6 +37,8 @@
 #include "script/script_runtime.h"
 #include "util/bbop.h"
 
+namespace AGS3 {
+
 extern ScriptString myScriptStringImpl;
 
 //=============================================================================
@@ -316,3 +318,5 @@ void RegisterContainerAPI() {
 	ccAddExternalObjectFunction("Set::get_ItemCount", Sc_Set_GetItemCount);
 	ccAddExternalObjectFunction("Set::GetItemsAsArray", Sc_Set_GetItemAsArray);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/slider.cpp b/engines/ags/engine/ac/slider.cpp
index 2cd6b58e4c..66273367ba 100644
--- a/engines/ags/engine/ac/slider.cpp
+++ b/engines/ags/engine/ac/slider.cpp
@@ -23,6 +23,8 @@
 #include "ac/slider.h"
 #include "ac/common.h"
 
+namespace AGS3 {
+
 // *** SLIDER FUNCTIONS
 
 void Slider_SetMax(GUISlider *guisl, int valn) {
@@ -182,18 +184,18 @@ RuntimeScriptValue Sc_Slider_SetValue(void *self, const RuntimeScriptValue *para
 
 
 void RegisterSliderAPI() {
-	ccAddExternalObjectFunction("Slider::get_BackgroundGraphic",    Sc_Slider_GetBackgroundGraphic);
-	ccAddExternalObjectFunction("Slider::set_BackgroundGraphic",    Sc_Slider_SetBackgroundGraphic);
-	ccAddExternalObjectFunction("Slider::get_HandleGraphic",        Sc_Slider_GetHandleGraphic);
-	ccAddExternalObjectFunction("Slider::set_HandleGraphic",        Sc_Slider_SetHandleGraphic);
-	ccAddExternalObjectFunction("Slider::get_HandleOffset",         Sc_Slider_GetHandleOffset);
-	ccAddExternalObjectFunction("Slider::set_HandleOffset",         Sc_Slider_SetHandleOffset);
-	ccAddExternalObjectFunction("Slider::get_Max",                  Sc_Slider_GetMax);
-	ccAddExternalObjectFunction("Slider::set_Max",                  Sc_Slider_SetMax);
-	ccAddExternalObjectFunction("Slider::get_Min",                  Sc_Slider_GetMin);
-	ccAddExternalObjectFunction("Slider::set_Min",                  Sc_Slider_SetMin);
-	ccAddExternalObjectFunction("Slider::get_Value",                Sc_Slider_GetValue);
-	ccAddExternalObjectFunction("Slider::set_Value",                Sc_Slider_SetValue);
+	ccAddExternalObjectFunction("Slider::get_BackgroundGraphic", Sc_Slider_GetBackgroundGraphic);
+	ccAddExternalObjectFunction("Slider::set_BackgroundGraphic", Sc_Slider_SetBackgroundGraphic);
+	ccAddExternalObjectFunction("Slider::get_HandleGraphic", Sc_Slider_GetHandleGraphic);
+	ccAddExternalObjectFunction("Slider::set_HandleGraphic", Sc_Slider_SetHandleGraphic);
+	ccAddExternalObjectFunction("Slider::get_HandleOffset", Sc_Slider_GetHandleOffset);
+	ccAddExternalObjectFunction("Slider::set_HandleOffset", Sc_Slider_SetHandleOffset);
+	ccAddExternalObjectFunction("Slider::get_Max", Sc_Slider_GetMax);
+	ccAddExternalObjectFunction("Slider::set_Max", Sc_Slider_SetMax);
+	ccAddExternalObjectFunction("Slider::get_Min", Sc_Slider_GetMin);
+	ccAddExternalObjectFunction("Slider::set_Min", Sc_Slider_SetMin);
+	ccAddExternalObjectFunction("Slider::get_Value", Sc_Slider_GetValue);
+	ccAddExternalObjectFunction("Slider::set_Value", Sc_Slider_SetValue);
 
 	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
 
@@ -210,3 +212,5 @@ void RegisterSliderAPI() {
 	ccAddExternalFunctionForPlugin("Slider::get_Value", (void *)Slider_GetValue);
 	ccAddExternalFunctionForPlugin("Slider::set_Value", (void *)Slider_SetValue);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/speech.cpp b/engines/ags/engine/ac/speech.cpp
index 32c416a7c6..e91694c826 100644
--- a/engines/ags/engine/ac/speech.cpp
+++ b/engines/ags/engine/ac/speech.cpp
@@ -25,6 +25,8 @@
 #include "ac/speech.h"
 #include "debug/debug_log.h"
 
+namespace AGS3 {
+
 int user_to_internal_skip_speech(SkipSpeechStyle userval) {
 	switch (userval) {
 	case kSkipSpeechKeyMouseTime:
@@ -194,29 +196,31 @@ void RegisterSpeechAPI(ScriptAPIVersion base_api, ScriptAPIVersion compat_api) {
 	ccAddExternalStaticFunction("Speech::set_AnimationStopTimeMargin", Sc_Speech_SetAnimationStopTimeMargin);
 	ccAddExternalStaticFunction("Speech::get_CustomPortraitPlacement", Sc_Speech_GetCustomPortraitPlacement);
 	ccAddExternalStaticFunction("Speech::set_CustomPortraitPlacement", Sc_Speech_SetCustomPortraitPlacement);
-	ccAddExternalStaticFunction("Speech::get_DisplayPostTimeMs",      Sc_Speech_GetDisplayPostTimeMs);
-	ccAddExternalStaticFunction("Speech::set_DisplayPostTimeMs",      Sc_Speech_SetDisplayPostTimeMs);
+	ccAddExternalStaticFunction("Speech::get_DisplayPostTimeMs", Sc_Speech_GetDisplayPostTimeMs);
+	ccAddExternalStaticFunction("Speech::set_DisplayPostTimeMs", Sc_Speech_SetDisplayPostTimeMs);
 	ccAddExternalStaticFunction("Speech::get_GlobalSpeechAnimationDelay", Sc_Speech_GetGlobalSpeechAnimationDelay);
 	ccAddExternalStaticFunction("Speech::set_GlobalSpeechAnimationDelay", Sc_Speech_SetGlobalSpeechAnimationDelay);
-	ccAddExternalStaticFunction("Speech::get_PortraitXOffset",        Sc_Speech_GetPortraitXOffset);
-	ccAddExternalStaticFunction("Speech::set_PortraitXOffset",        Sc_Speech_SetPortraitXOffset);
-	ccAddExternalStaticFunction("Speech::get_PortraitY",              Sc_Speech_GetPortraitY);
-	ccAddExternalStaticFunction("Speech::set_PortraitY",              Sc_Speech_SetPortraitY);
-	ccAddExternalStaticFunction("Speech::get_SkipKey",                Sc_Speech_GetSkipKey);
-	ccAddExternalStaticFunction("Speech::set_SkipKey",                Sc_Speech_SetSkipKey);
-	ccAddExternalStaticFunction("Speech::get_SkipStyle",              Sc_Speech_GetSkipStyle);
-	ccAddExternalStaticFunction("Speech::set_SkipStyle",              Sc_SetSkipSpeech);
-	ccAddExternalStaticFunction("Speech::get_Style",                  Sc_Speech_GetStyle);
-	ccAddExternalStaticFunction("Speech::set_Style",                  Sc_SetSpeechStyle);
-	ccAddExternalStaticFunction("Speech::get_TextAlignment",          Sc_Speech_GetTextAlignment);
+	ccAddExternalStaticFunction("Speech::get_PortraitXOffset", Sc_Speech_GetPortraitXOffset);
+	ccAddExternalStaticFunction("Speech::set_PortraitXOffset", Sc_Speech_SetPortraitXOffset);
+	ccAddExternalStaticFunction("Speech::get_PortraitY", Sc_Speech_GetPortraitY);
+	ccAddExternalStaticFunction("Speech::set_PortraitY", Sc_Speech_SetPortraitY);
+	ccAddExternalStaticFunction("Speech::get_SkipKey", Sc_Speech_GetSkipKey);
+	ccAddExternalStaticFunction("Speech::set_SkipKey", Sc_Speech_SetSkipKey);
+	ccAddExternalStaticFunction("Speech::get_SkipStyle", Sc_Speech_GetSkipStyle);
+	ccAddExternalStaticFunction("Speech::set_SkipStyle", Sc_SetSkipSpeech);
+	ccAddExternalStaticFunction("Speech::get_Style", Sc_Speech_GetStyle);
+	ccAddExternalStaticFunction("Speech::set_Style", Sc_SetSpeechStyle);
+	ccAddExternalStaticFunction("Speech::get_TextAlignment", Sc_Speech_GetTextAlignment);
 	if (base_api < kScriptAPI_v350)
-		ccAddExternalStaticFunction("Speech::set_TextAlignment",      Sc_Speech_SetTextAlignment_Old);
+		ccAddExternalStaticFunction("Speech::set_TextAlignment", Sc_Speech_SetTextAlignment_Old);
 	else
-		ccAddExternalStaticFunction("Speech::set_TextAlignment",      Sc_Speech_SetTextAlignment);
+		ccAddExternalStaticFunction("Speech::set_TextAlignment", Sc_Speech_SetTextAlignment);
 	ccAddExternalStaticFunction("Speech::get_UseGlobalSpeechAnimationDelay", Sc_Speech_GetUseGlobalSpeechAnimationDelay);
 	ccAddExternalStaticFunction("Speech::set_UseGlobalSpeechAnimationDelay", Sc_Speech_SetUseGlobalSpeechAnimationDelay);
-	ccAddExternalStaticFunction("Speech::get_VoiceMode",              Sc_Speech_GetVoiceMode);
-	ccAddExternalStaticFunction("Speech::set_VoiceMode",              Sc_SetVoiceMode);
+	ccAddExternalStaticFunction("Speech::get_VoiceMode", Sc_Speech_GetVoiceMode);
+	ccAddExternalStaticFunction("Speech::set_VoiceMode", Sc_SetVoiceMode);
 
 	/* -- Don't register more unsafe plugin symbols until new plugin interface is designed --*/
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/sprite.cpp b/engines/ags/engine/ac/sprite.cpp
index 562b89719e..25457a4963 100644
--- a/engines/ags/engine/ac/sprite.cpp
+++ b/engines/ags/engine/ac/sprite.cpp
@@ -32,6 +32,8 @@
 #include "gfx/bitmap.h"
 #include "gfx/graphicsdriver.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -181,3 +183,5 @@ void initialize_sprite(int ee) {
 		our_eip = oldeip;
 	}
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/spritecache_engine.cpp b/engines/ags/engine/ac/spritecache_engine.cpp
index 5c6533d5dc..9f5ae3388e 100644
--- a/engines/ags/engine/ac/spritecache_engine.cpp
+++ b/engines/ags/engine/ac/spritecache_engine.cpp
@@ -37,6 +37,8 @@
 #include "ac/spritecache.h"
 #include "util/compress.h"
 
+namespace AGS3 {
+
 //=============================================================================
 // Engine-specific implementation split out of sprcache.cpp
 //=============================================================================
@@ -50,3 +52,5 @@ void SpriteCache::InitNullSpriteParams(sprkey_t index) {
 	_spriteData[index].Size = _spriteData[0].Size;
 	_spriteData[index].Flags = SPRCACHEFLAG_REMAPPED;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/statobj/agsstaticobject.cpp b/engines/ags/engine/ac/statobj/agsstaticobject.cpp
index 53233da9f8..54f975ee76 100644
--- a/engines/ags/engine/ac/statobj/agsstaticobject.cpp
+++ b/engines/ags/engine/ac/statobj/agsstaticobject.cpp
@@ -25,6 +25,8 @@
 #include "ac/game.h"
 #include "ac/gamestate.h"
 
+namespace AGS3 {
+
 AGSStaticObject GlobalStaticManager;
 StaticGame      GameStaticManager;
 
@@ -84,3 +86,5 @@ void StaticGame::WriteInt32(const char *address, intptr_t offset, int32_t val) {
 		*(int32_t *)(address + offset) = val;
 	}
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/statobj/staticarray.cpp b/engines/ags/engine/ac/statobj/staticarray.cpp
index 8b87c74932..a55758eac6 100644
--- a/engines/ags/engine/ac/statobj/staticarray.cpp
+++ b/engines/ags/engine/ac/statobj/staticarray.cpp
@@ -24,28 +24,30 @@
 #include "ac/statobj/staticarray.h"
 #include "ac/dynobj/cc_dynamicobject.h"
 
+namespace AGS3 {
+
 void StaticArray::Create(int elem_legacy_size, int elem_real_size, int elem_count) {
-	_staticMgr      = nullptr;
-	_dynamicMgr     = nullptr;
+	_staticMgr = nullptr;
+	_dynamicMgr = nullptr;
 	_elemLegacySize = elem_legacy_size;
-	_elemRealSize   = elem_real_size;
-	_elemCount      = elem_count;
+	_elemRealSize = elem_real_size;
+	_elemCount = elem_count;
 }
 
 void StaticArray::Create(ICCStaticObject *stcmgr, int elem_legacy_size, int elem_real_size, int elem_count) {
-	_staticMgr      = stcmgr;
-	_dynamicMgr     = nullptr;
+	_staticMgr = stcmgr;
+	_dynamicMgr = nullptr;
 	_elemLegacySize = elem_legacy_size;
-	_elemRealSize   = elem_real_size;
-	_elemCount      = elem_count;
+	_elemRealSize = elem_real_size;
+	_elemCount = elem_count;
 }
 
 void StaticArray::Create(ICCDynamicObject *dynmgr, int elem_legacy_size, int elem_real_size, int elem_count) {
-	_staticMgr      = nullptr;
-	_dynamicMgr     = dynmgr;
+	_staticMgr = nullptr;
+	_dynamicMgr = dynmgr;
 	_elemLegacySize = elem_legacy_size;
-	_elemRealSize   = elem_real_size;
-	_elemCount      = elem_count;
+	_elemRealSize = elem_real_size;
+	_elemCount = elem_count;
 }
 
 const char *StaticArray::GetElementPtr(const char *address, intptr_t legacy_offset) {
@@ -160,3 +162,5 @@ void StaticArray::WriteFloat(const char *address, intptr_t offset, float val) {
 		*(float *)(el_ptr + offset % _elemLegacySize) = val;
 	}
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/string.cpp b/engines/ags/engine/ac/string.cpp
index 11b27c34e4..3380f56c7d 100644
--- a/engines/ags/engine/ac/string.cpp
+++ b/engines/ags/engine/ac/string.cpp
@@ -34,6 +34,8 @@
 #include "script/runtimescriptvalue.h"
 #include "util/string_compat.h"
 
+namespace AGS3 {
+
 extern GameSetupStruct game;
 extern GameState play;
 extern int longestline;
@@ -254,14 +256,13 @@ size_t break_up_text_into_lines(const char *todis, SplitLines &lines, int wii, i
 			line_length = wgettextwidth_compensate(lines[rr], fonnt);
 			if (line_length > longestline)
 				longestline = line_length;
-		}
-	else
-		for (size_t rr = 0; rr < lines.Count(); rr++) {
-			line_length = wgettextwidth_compensate(lines[rr], fonnt);
-			if (line_length > longestline)
-				longestline = line_length;
-		}
-	return lines.Count();
+		} else
+			for (size_t rr = 0; rr < lines.Count(); rr++) {
+				line_length = wgettextwidth_compensate(lines[rr], fonnt);
+				if (line_length > longestline)
+					longestline = line_length;
+			}
+		return lines.Count();
 }
 
 int MAXSTRLEN = MAX_MAXSTRLEN;
@@ -412,26 +413,26 @@ const char *ScPl_String_Format(const char *texx, ...) {
 
 
 void RegisterStringAPI() {
-	ccAddExternalStaticFunction("String::IsNullOrEmpty^1",  Sc_String_IsNullOrEmpty);
-	ccAddExternalObjectFunction("String::Append^1",         Sc_String_Append);
-	ccAddExternalObjectFunction("String::AppendChar^1",     Sc_String_AppendChar);
-	ccAddExternalObjectFunction("String::CompareTo^2",      Sc_String_CompareTo);
-	ccAddExternalObjectFunction("String::Contains^1",       Sc_StrContains);
-	ccAddExternalObjectFunction("String::Copy^0",           Sc_String_Copy);
-	ccAddExternalObjectFunction("String::EndsWith^2",       Sc_String_EndsWith);
-	ccAddExternalStaticFunction("String::Format^101",       Sc_String_Format);
-	ccAddExternalObjectFunction("String::IndexOf^1",        Sc_StrContains);
-	ccAddExternalObjectFunction("String::LowerCase^0",      Sc_String_LowerCase);
-	ccAddExternalObjectFunction("String::Replace^3",        Sc_String_Replace);
-	ccAddExternalObjectFunction("String::ReplaceCharAt^2",  Sc_String_ReplaceCharAt);
-	ccAddExternalObjectFunction("String::StartsWith^2",     Sc_String_StartsWith);
-	ccAddExternalObjectFunction("String::Substring^2",      Sc_String_Substring);
-	ccAddExternalObjectFunction("String::Truncate^1",       Sc_String_Truncate);
-	ccAddExternalObjectFunction("String::UpperCase^0",      Sc_String_UpperCase);
-	ccAddExternalObjectFunction("String::get_AsFloat",      Sc_StringToFloat);
-	ccAddExternalObjectFunction("String::get_AsInt",        Sc_StringToInt);
-	ccAddExternalObjectFunction("String::geti_Chars",       Sc_String_GetChars);
-	ccAddExternalObjectFunction("String::get_Length",       Sc_strlen);
+	ccAddExternalStaticFunction("String::IsNullOrEmpty^1", Sc_String_IsNullOrEmpty);
+	ccAddExternalObjectFunction("String::Append^1", Sc_String_Append);
+	ccAddExternalObjectFunction("String::AppendChar^1", Sc_String_AppendChar);
+	ccAddExternalObjectFunction("String::CompareTo^2", Sc_String_CompareTo);
+	ccAddExternalObjectFunction("String::Contains^1", Sc_StrContains);
+	ccAddExternalObjectFunction("String::Copy^0", Sc_String_Copy);
+	ccAddExternalObjectFunction("String::EndsWith^2", Sc_String_EndsWith);
+	ccAddExternalStaticFunction("String::Format^101", Sc_String_Format);
+	ccAddExternalObjectFunction("String::IndexOf^1", Sc_StrContains);
+	ccAddExternalObjectFunction("String::LowerCase^0", Sc_String_LowerCase);
+	ccAddExternalObjectFunction("String::Replace^3", Sc_String_Replace);
+	ccAddExternalObjectFunction("String::ReplaceCharAt^2", Sc_String_ReplaceCharAt);
+	ccAddExternalObjectFunction("String::StartsWith^2", Sc_String_StartsWith);
+	ccAddExternalObjectFunction("String::Substring^2", Sc_String_Substring);
+	ccAddExternalObjectFunction("String::Truncate^1", Sc_String_Truncate);
+	ccAddExternalObjectFunction("String::UpperCase^0", Sc_String_UpperCase);
+	ccAddExternalObjectFunction("String::get_AsFloat", Sc_StringToFloat);
+	ccAddExternalObjectFunction("String::get_AsInt", Sc_StringToInt);
+	ccAddExternalObjectFunction("String::geti_Chars", Sc_String_GetChars);
+	ccAddExternalObjectFunction("String::get_Length", Sc_strlen);
 
 	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
 
@@ -456,3 +457,5 @@ void RegisterStringAPI() {
 	ccAddExternalFunctionForPlugin("String::geti_Chars", (void *)String_GetChars);
 	ccAddExternalFunctionForPlugin("String::get_Length", (void *)strlen);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/sys_events.cpp b/engines/ags/engine/ac/sys_events.cpp
index 37306e004a..fc20cdbd98 100644
--- a/engines/ags/engine/ac/sys_events.cpp
+++ b/engines/ags/engine/ac/sys_events.cpp
@@ -31,6 +31,8 @@
 #include "platform/base/agsplatformdriver.h"
 #include "ac/timer.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -133,106 +135,106 @@ int ags_getch() {
 		// the complete scan code list is not here.
 
 		switch (scancode) {
-		case __allegro_KEY_F1 :
-			gott = eAGSKeyCodeF1 ;
+		case __allegro_KEY_F1:
+			gott = eAGSKeyCodeF1;
 			break;
-		case __allegro_KEY_F2 :
-			gott = eAGSKeyCodeF2 ;
+		case __allegro_KEY_F2:
+			gott = eAGSKeyCodeF2;
 			break;
-		case __allegro_KEY_F3 :
-			gott = eAGSKeyCodeF3 ;
+		case __allegro_KEY_F3:
+			gott = eAGSKeyCodeF3;
 			break;
-		case __allegro_KEY_F4 :
-			gott = eAGSKeyCodeF4 ;
+		case __allegro_KEY_F4:
+			gott = eAGSKeyCodeF4;
 			break;
-		case __allegro_KEY_F5 :
-			gott = eAGSKeyCodeF5 ;
+		case __allegro_KEY_F5:
+			gott = eAGSKeyCodeF5;
 			break;
-		case __allegro_KEY_F6 :
-			gott = eAGSKeyCodeF6 ;
+		case __allegro_KEY_F6:
+			gott = eAGSKeyCodeF6;
 			break;
-		case __allegro_KEY_F7 :
-			gott = eAGSKeyCodeF7 ;
+		case __allegro_KEY_F7:
+			gott = eAGSKeyCodeF7;
 			break;
-		case __allegro_KEY_F8 :
-			gott = eAGSKeyCodeF8 ;
+		case __allegro_KEY_F8:
+			gott = eAGSKeyCodeF8;
 			break;
-		case __allegro_KEY_F9 :
-			gott = eAGSKeyCodeF9 ;
+		case __allegro_KEY_F9:
+			gott = eAGSKeyCodeF9;
 			break;
-		case __allegro_KEY_F10 :
-			gott = eAGSKeyCodeF10 ;
+		case __allegro_KEY_F10:
+			gott = eAGSKeyCodeF10;
 			break;
-		case __allegro_KEY_F11 :
-			gott = eAGSKeyCodeF11 ;
+		case __allegro_KEY_F11:
+			gott = eAGSKeyCodeF11;
 			break;
-		case __allegro_KEY_F12 :
-			gott = eAGSKeyCodeF12 ;
+		case __allegro_KEY_F12:
+			gott = eAGSKeyCodeF12;
 			break;
 
-		case __allegro_KEY_INSERT :
-			gott = eAGSKeyCodeInsert ;
+		case __allegro_KEY_INSERT:
+			gott = eAGSKeyCodeInsert;
 			break;
-		case __allegro_KEY_DEL :
-			gott = eAGSKeyCodeDelete ;
+		case __allegro_KEY_DEL:
+			gott = eAGSKeyCodeDelete;
 			break;
-		case __allegro_KEY_HOME :
-			gott = eAGSKeyCodeHome ;
+		case __allegro_KEY_HOME:
+			gott = eAGSKeyCodeHome;
 			break;
-		case __allegro_KEY_END :
-			gott = eAGSKeyCodeEnd ;
+		case __allegro_KEY_END:
+			gott = eAGSKeyCodeEnd;
 			break;
-		case __allegro_KEY_PGUP :
-			gott = eAGSKeyCodePageUp ;
+		case __allegro_KEY_PGUP:
+			gott = eAGSKeyCodePageUp;
 			break;
-		case __allegro_KEY_PGDN :
-			gott = eAGSKeyCodePageDown ;
+		case __allegro_KEY_PGDN:
+			gott = eAGSKeyCodePageDown;
 			break;
-		case __allegro_KEY_LEFT :
-			gott = eAGSKeyCodeLeftArrow ;
+		case __allegro_KEY_LEFT:
+			gott = eAGSKeyCodeLeftArrow;
 			break;
-		case __allegro_KEY_RIGHT :
-			gott = eAGSKeyCodeRightArrow ;
+		case __allegro_KEY_RIGHT:
+			gott = eAGSKeyCodeRightArrow;
 			break;
-		case __allegro_KEY_UP :
-			gott = eAGSKeyCodeUpArrow ;
+		case __allegro_KEY_UP:
+			gott = eAGSKeyCodeUpArrow;
 			break;
-		case __allegro_KEY_DOWN :
-			gott = eAGSKeyCodeDownArrow ;
+		case __allegro_KEY_DOWN:
+			gott = eAGSKeyCodeDownArrow;
 			break;
 
-		case __allegro_KEY_0_PAD :
-			gott = eAGSKeyCodeInsert ;
+		case __allegro_KEY_0_PAD:
+			gott = eAGSKeyCodeInsert;
 			break;
-		case __allegro_KEY_1_PAD :
-			gott = eAGSKeyCodeEnd ;
+		case __allegro_KEY_1_PAD:
+			gott = eAGSKeyCodeEnd;
 			break;
-		case __allegro_KEY_2_PAD :
-			gott = eAGSKeyCodeDownArrow ;
+		case __allegro_KEY_2_PAD:
+			gott = eAGSKeyCodeDownArrow;
 			break;
-		case __allegro_KEY_3_PAD :
-			gott = eAGSKeyCodePageDown ;
+		case __allegro_KEY_3_PAD:
+			gott = eAGSKeyCodePageDown;
 			break;
-		case __allegro_KEY_4_PAD :
-			gott = eAGSKeyCodeLeftArrow ;
+		case __allegro_KEY_4_PAD:
+			gott = eAGSKeyCodeLeftArrow;
 			break;
-		case __allegro_KEY_5_PAD :
-			gott = eAGSKeyCodeNumPad5 ;
+		case __allegro_KEY_5_PAD:
+			gott = eAGSKeyCodeNumPad5;
 			break;
-		case __allegro_KEY_6_PAD :
-			gott = eAGSKeyCodeRightArrow ;
+		case __allegro_KEY_6_PAD:
+			gott = eAGSKeyCodeRightArrow;
 			break;
-		case __allegro_KEY_7_PAD :
-			gott = eAGSKeyCodeHome ;
+		case __allegro_KEY_7_PAD:
+			gott = eAGSKeyCodeHome;
 			break;
-		case __allegro_KEY_8_PAD :
-			gott = eAGSKeyCodeUpArrow ;
+		case __allegro_KEY_8_PAD:
+			gott = eAGSKeyCodeUpArrow;
 			break;
-		case __allegro_KEY_9_PAD :
-			gott = eAGSKeyCodePageUp ;
+		case __allegro_KEY_9_PAD:
+			gott = eAGSKeyCodePageUp;
 			break;
-		case __allegro_KEY_DEL_PAD :
-			gott = eAGSKeyCodeDelete ;
+		case __allegro_KEY_DEL_PAD:
+			gott = eAGSKeyCodeDelete;
 			break;
 
 		default:
@@ -268,3 +270,5 @@ void ags_wait_until_keypress() {
 	}
 	ags_getch();
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/system.cpp b/engines/ags/engine/ac/system.cpp
index 667c75e6b6..33be22fd38 100644
--- a/engines/ags/engine/ac/system.cpp
+++ b/engines/ags/engine/ac/system.cpp
@@ -41,6 +41,8 @@
 #include "media/audio/audio_system.h"
 #include "util/string_compat.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -371,35 +373,35 @@ RuntimeScriptValue Sc_System_Log(const RuntimeScriptValue *params, int32_t param
 
 
 void RegisterSystemAPI() {
-	ccAddExternalStaticFunction("System::get_AudioChannelCount",    Sc_System_GetAudioChannelCount);
-	ccAddExternalStaticFunction("System::geti_AudioChannels",       Sc_System_GetAudioChannels);
-	ccAddExternalStaticFunction("System::get_CapsLock",             Sc_System_GetCapsLock);
-	ccAddExternalStaticFunction("System::get_ColorDepth",           Sc_System_GetColorDepth);
-	ccAddExternalStaticFunction("System::get_Gamma",                Sc_System_GetGamma);
-	ccAddExternalStaticFunction("System::set_Gamma",                Sc_System_SetGamma);
+	ccAddExternalStaticFunction("System::get_AudioChannelCount", Sc_System_GetAudioChannelCount);
+	ccAddExternalStaticFunction("System::geti_AudioChannels", Sc_System_GetAudioChannels);
+	ccAddExternalStaticFunction("System::get_CapsLock", Sc_System_GetCapsLock);
+	ccAddExternalStaticFunction("System::get_ColorDepth", Sc_System_GetColorDepth);
+	ccAddExternalStaticFunction("System::get_Gamma", Sc_System_GetGamma);
+	ccAddExternalStaticFunction("System::set_Gamma", Sc_System_SetGamma);
 	ccAddExternalStaticFunction("System::get_HardwareAcceleration", Sc_System_GetHardwareAcceleration);
-	ccAddExternalStaticFunction("System::get_HasInputFocus",        Sc_System_GetHasInputFocus);
-	ccAddExternalStaticFunction("System::get_NumLock",              Sc_System_GetNumLock);
-	ccAddExternalStaticFunction("System::set_NumLock",              Sc_System_SetNumLock);
-	ccAddExternalStaticFunction("System::get_OperatingSystem",      Sc_System_GetOS);
+	ccAddExternalStaticFunction("System::get_HasInputFocus", Sc_System_GetHasInputFocus);
+	ccAddExternalStaticFunction("System::get_NumLock", Sc_System_GetNumLock);
+	ccAddExternalStaticFunction("System::set_NumLock", Sc_System_SetNumLock);
+	ccAddExternalStaticFunction("System::get_OperatingSystem", Sc_System_GetOS);
 	ccAddExternalStaticFunction("System::get_RenderAtScreenResolution", Sc_System_GetRenderAtScreenResolution);
 	ccAddExternalStaticFunction("System::set_RenderAtScreenResolution", Sc_System_SetRenderAtScreenResolution);
-	ccAddExternalStaticFunction("System::get_RuntimeInfo",          Sc_System_GetRuntimeInfo);
-	ccAddExternalStaticFunction("System::get_ScreenHeight",         Sc_System_GetScreenHeight);
-	ccAddExternalStaticFunction("System::get_ScreenWidth",          Sc_System_GetScreenWidth);
-	ccAddExternalStaticFunction("System::get_ScrollLock",           Sc_System_GetScrollLock);
+	ccAddExternalStaticFunction("System::get_RuntimeInfo", Sc_System_GetRuntimeInfo);
+	ccAddExternalStaticFunction("System::get_ScreenHeight", Sc_System_GetScreenHeight);
+	ccAddExternalStaticFunction("System::get_ScreenWidth", Sc_System_GetScreenWidth);
+	ccAddExternalStaticFunction("System::get_ScrollLock", Sc_System_GetScrollLock);
 	ccAddExternalStaticFunction("System::get_SupportsGammaControl", Sc_System_GetSupportsGammaControl);
-	ccAddExternalStaticFunction("System::get_Version",              Sc_System_GetVersion);
-	ccAddExternalStaticFunction("SystemInfo::get_Version",          Sc_System_GetVersion);
-	ccAddExternalStaticFunction("System::get_ViewportHeight",       Sc_System_GetViewportHeight);
-	ccAddExternalStaticFunction("System::get_ViewportWidth",        Sc_System_GetViewportWidth);
-	ccAddExternalStaticFunction("System::get_Volume",               Sc_System_GetVolume);
-	ccAddExternalStaticFunction("System::set_Volume",               Sc_System_SetVolume);
-	ccAddExternalStaticFunction("System::get_VSync",                Sc_System_GetVsync);
-	ccAddExternalStaticFunction("System::set_VSync",                Sc_System_SetVsync);
-	ccAddExternalStaticFunction("System::get_Windowed",             Sc_System_GetWindowed);
-	ccAddExternalStaticFunction("System::set_Windowed",             Sc_System_SetWindowed);
-	ccAddExternalStaticFunction("System::Log^102",                  Sc_System_Log);
+	ccAddExternalStaticFunction("System::get_Version", Sc_System_GetVersion);
+	ccAddExternalStaticFunction("SystemInfo::get_Version", Sc_System_GetVersion);
+	ccAddExternalStaticFunction("System::get_ViewportHeight", Sc_System_GetViewportHeight);
+	ccAddExternalStaticFunction("System::get_ViewportWidth", Sc_System_GetViewportWidth);
+	ccAddExternalStaticFunction("System::get_Volume", Sc_System_GetVolume);
+	ccAddExternalStaticFunction("System::set_Volume", Sc_System_SetVolume);
+	ccAddExternalStaticFunction("System::get_VSync", Sc_System_GetVsync);
+	ccAddExternalStaticFunction("System::set_VSync", Sc_System_SetVsync);
+	ccAddExternalStaticFunction("System::get_Windowed", Sc_System_GetWindowed);
+	ccAddExternalStaticFunction("System::set_Windowed", Sc_System_SetWindowed);
+	ccAddExternalStaticFunction("System::Log^102", Sc_System_Log);
 
 	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
 
@@ -428,3 +430,5 @@ void RegisterSystemAPI() {
 	ccAddExternalFunctionForPlugin("System::set_VSync", (void *)System_SetVsync);
 	ccAddExternalFunctionForPlugin("System::get_Windowed", (void *)System_GetWindowed);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/textbox.cpp b/engines/ags/engine/ac/textbox.cpp
index 4d8bce4677..64f68cc217 100644
--- a/engines/ags/engine/ac/textbox.cpp
+++ b/engines/ags/engine/ac/textbox.cpp
@@ -26,6 +26,8 @@
 #include "ac/gamesetupstruct.h"
 #include "ac/string.h"
 
+namespace AGS3 {
+
 extern GameSetupStruct game;
 
 
@@ -141,16 +143,16 @@ RuntimeScriptValue Sc_TextBox_SetTextColor(void *self, const RuntimeScriptValue
 
 
 void RegisterTextBoxAPI() {
-	ccAddExternalObjectFunction("TextBox::GetText^1",       Sc_TextBox_GetText);
-	ccAddExternalObjectFunction("TextBox::SetText^1",       Sc_TextBox_SetText);
-	ccAddExternalObjectFunction("TextBox::get_Font",        Sc_TextBox_GetFont);
-	ccAddExternalObjectFunction("TextBox::set_Font",        Sc_TextBox_SetFont);
-	ccAddExternalObjectFunction("TextBox::get_ShowBorder",  Sc_TextBox_GetShowBorder);
-	ccAddExternalObjectFunction("TextBox::set_ShowBorder",  Sc_TextBox_SetShowBorder);
-	ccAddExternalObjectFunction("TextBox::get_Text",        Sc_TextBox_GetText_New);
-	ccAddExternalObjectFunction("TextBox::set_Text",        Sc_TextBox_SetText);
-	ccAddExternalObjectFunction("TextBox::get_TextColor",   Sc_TextBox_GetTextColor);
-	ccAddExternalObjectFunction("TextBox::set_TextColor",   Sc_TextBox_SetTextColor);
+	ccAddExternalObjectFunction("TextBox::GetText^1", Sc_TextBox_GetText);
+	ccAddExternalObjectFunction("TextBox::SetText^1", Sc_TextBox_SetText);
+	ccAddExternalObjectFunction("TextBox::get_Font", Sc_TextBox_GetFont);
+	ccAddExternalObjectFunction("TextBox::set_Font", Sc_TextBox_SetFont);
+	ccAddExternalObjectFunction("TextBox::get_ShowBorder", Sc_TextBox_GetShowBorder);
+	ccAddExternalObjectFunction("TextBox::set_ShowBorder", Sc_TextBox_SetShowBorder);
+	ccAddExternalObjectFunction("TextBox::get_Text", Sc_TextBox_GetText_New);
+	ccAddExternalObjectFunction("TextBox::set_Text", Sc_TextBox_SetText);
+	ccAddExternalObjectFunction("TextBox::get_TextColor", Sc_TextBox_GetTextColor);
+	ccAddExternalObjectFunction("TextBox::set_TextColor", Sc_TextBox_SetTextColor);
 
 	/* ----------------------- Registering unsafe exports for plugins -----------------------*/
 
@@ -163,3 +165,5 @@ void RegisterTextBoxAPI() {
 	ccAddExternalFunctionForPlugin("TextBox::get_TextColor", (void *)TextBox_GetTextColor);
 	ccAddExternalFunctionForPlugin("TextBox::set_TextColor", (void *)TextBox_SetTextColor);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/timer.cpp b/engines/ags/engine/ac/timer.cpp
index e94e7b3ed7..2e2f9b472b 100644
--- a/engines/ags/engine/ac/timer.cpp
+++ b/engines/ags/engine/ac/timer.cpp
@@ -31,6 +31,8 @@
 #include <thread>
 #include "platform/base/agsplatformdriver.h"
 
+namespace AGS3 {
+
 namespace {
 
 const auto MAXIMUM_FALL_BEHIND = 3;
@@ -120,3 +122,5 @@ void skipMissedTicks() {
 	last_tick_time = AGS_Clock::now();
 	next_frame_timestamp = AGS_Clock::now();
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/translation.cpp b/engines/ags/engine/ac/translation.cpp
index c7b3df4a28..4ca6ac1577 100644
--- a/engines/ags/engine/ac/translation.cpp
+++ b/engines/ags/engine/ac/translation.cpp
@@ -36,6 +36,8 @@
 #include "util/stream.h"
 #include "core/assetmanager.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern GameSetup usetup;
@@ -71,7 +73,7 @@ bool init_translation(const String &lang, const String &fallback_lang, bool quit
 	// in case it's inside a library file, record the offset
 	lang_offs_start = language_file->GetPosition();
 
-	char transsig[16] = {0};
+	char transsig[16] = { 0 };
 	language_file->Read(transsig, 15);
 	if (strcmp(transsig, "AGSTranslation") != 0) {
 		Debug::Printf(kDbgMsg_Error, "Translation signature mismatch: %s", transFileName);
@@ -136,7 +138,7 @@ bool parse_translation(Stream *language_file, String &parse_error) {
 			read_string_decrypt(language_file, wasgamename, sizeof(wasgamename));
 			if ((uidfrom != game.uniqueid) || (strcmp(wasgamename, game.gamename) != 0)) {
 				parse_error.Format("The translation file is not compatible with this game. The translation is designed for '%s'.",
-				                   wasgamename);
+					wasgamename);
 				return false;
 			}
 		} else if (blockType == 3) {
@@ -171,3 +173,5 @@ bool parse_translation(Stream *language_file, String &parse_error) {
 
 	return true;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/tree_map.cpp b/engines/ags/engine/ac/tree_map.cpp
index a25ab6dcc5..0f8680d14a 100644
--- a/engines/ags/engine/ac/tree_map.cpp
+++ b/engines/ags/engine/ac/tree_map.cpp
@@ -25,6 +25,8 @@
 #include "ac/common.h"
 #include "ac/tree_map.h"
 
+namespace AGS3 {
+
 TreeMap::TreeMap() {
 	left = nullptr;
 	right = nullptr;
@@ -53,7 +55,7 @@ char *TreeMap::findValue(const char *key) {
 
 void TreeMap::addText(const char *ntx, char *trans) {
 	if ((ntx == nullptr) || (ntx[0] == 0) ||
-	        ((text != nullptr) && (strcmp(ntx, text) == 0)))
+		((text != nullptr) && (strcmp(ntx, text) == 0)))
 		// don't add if it's an empty string or if it's already here
 		return;
 
@@ -101,3 +103,5 @@ void TreeMap::clear() {
 TreeMap::~TreeMap() {
 	clear();
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/viewframe.cpp b/engines/ags/engine/ac/viewframe.cpp
index 4d7f0543a2..6f749c52c2 100644
--- a/engines/ags/engine/ac/viewframe.cpp
+++ b/engines/ags/engine/ac/viewframe.cpp
@@ -31,6 +31,8 @@
 #include "ac/game_version.h"
 #include "media/audio/audio_system.h"
 
+} // namespace AGS3
+
 using AGS::Shared::Bitmap;
 using AGS::Shared::Graphics;
 
@@ -262,3 +264,5 @@ void RegisterViewFrameAPI() {
 	ccAddExternalFunctionForPlugin("ViewFrame::get_Speed", (void *)ViewFrame_GetSpeed);
 	ccAddExternalFunctionForPlugin("ViewFrame::get_View", (void *)ViewFrame_GetView);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/viewport_script.cpp b/engines/ags/engine/ac/viewport_script.cpp
index b6fb314f53..d4f405ab76 100644
--- a/engines/ags/engine/ac/viewport_script.cpp
+++ b/engines/ags/engine/ac/viewport_script.cpp
@@ -35,6 +35,8 @@
 #include "script/script_api.h"
 #include "script/script_runtime.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 //=============================================================================
@@ -553,3 +555,5 @@ void RegisterViewportAPI() {
 	ccAddExternalObjectFunction("Viewport::ScreenToRoomPoint", Sc_Viewport_ScreenToRoomPoint);
 	ccAddExternalObjectFunction("Viewport::RoomToScreenPoint", Sc_Viewport_RoomToScreenPoint);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/walkablearea.cpp b/engines/ags/engine/ac/walkablearea.cpp
index d129b3e138..93d6d5c07f 100644
--- a/engines/ags/engine/ac/walkablearea.cpp
+++ b/engines/ags/engine/ac/walkablearea.cpp
@@ -33,6 +33,8 @@
 #include "game/roomstruct.h"
 #include "gfx/bitmap.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern RoomStruct thisroom;
@@ -76,7 +78,7 @@ int get_area_scaling(int onarea, int xx, int yy) {
 	yy = room_to_mask_coord(yy);
 
 	if ((onarea >= 0) && (onarea <= MAX_WALK_AREAS) &&
-	        (thisroom.WalkAreas[onarea].ScalingNear != NOT_VECTOR_SCALED)) {
+		(thisroom.WalkAreas[onarea].ScalingNear != NOT_VECTOR_SCALED)) {
 		// We have vector scaling!
 		// In case the character is off the screen, limit the Y co-ordinate
 		// to within the area range (otherwise we get silly zoom levels
@@ -90,7 +92,7 @@ int get_area_scaling(int onarea, int xx, int yy) {
 		// Zoom level = ((max - min) * Percent) / 100
 		if (thisroom.WalkAreas[onarea].Bottom != thisroom.WalkAreas[onarea].Top) {
 			int percent = ((yy - thisroom.WalkAreas[onarea].Top) * 100)
-			              / (thisroom.WalkAreas[onarea].Bottom - thisroom.WalkAreas[onarea].Top);
+				/ (thisroom.WalkAreas[onarea].Bottom - thisroom.WalkAreas[onarea].Top);
 			zoom_level = ((thisroom.WalkAreas[onarea].ScalingNear - thisroom.WalkAreas[onarea].ScalingFar) * (percent)) / 100 + thisroom.WalkAreas[onarea].ScalingFar;
 		} else {
 			// Special case for 1px tall walkable area: take bottom line scaling
@@ -128,10 +130,10 @@ void remove_walkable_areas_from_temp(int fromx, int cwidth, int starty, int endy
 	if (starty < 0)
 		starty = 0;
 
-	for (; cwidth > 0; cwidth --) {
+	for (; cwidth > 0; cwidth--) {
 		for (yyy = starty; yyy <= endy; yyy++)
 			walkable_areas_temp->PutPixel(fromx, yyy, 0);
-		fromx ++;
+		fromx++;
 	}
 
 }
@@ -146,7 +148,7 @@ Bitmap *prepare_walkable_areas(int sourceChar) {
 	// copy the walkable areas to the temp bitmap
 	walkable_areas_temp->Blit(thisroom.WalkAreaMask.get(), 0, 0, 0, 0, thisroom.WalkAreaMask->GetWidth(), thisroom.WalkAreaMask->GetHeight());
 	// if the character who's moving doesn't Bitmap *, don't bother checking
-	if (sourceChar < 0) ;
+	if (sourceChar < 0);
 	else if (game.chars[sourceChar].flags & CHF_NOBLOCKING)
 		return walkable_areas_temp;
 
@@ -189,8 +191,8 @@ Bitmap *prepare_walkable_areas(int sourceChar) {
 		// if the character is currently standing on the object, ignore
 		// it so as to allow him to escape
 		if ((sourceChar >= 0) &&
-		        (is_point_in_rect(game.chars[sourceChar].x, game.chars[sourceChar].y,
-		                          x1, y1, x1 + width, y2)))
+			(is_point_in_rect(game.chars[sourceChar].x, game.chars[sourceChar].y,
+				x1, y1, x1 + width, y2)))
 			continue;
 
 		remove_walkable_areas_from_temp(x1, width, y1, y2);
@@ -239,3 +241,5 @@ int get_walkable_area_at_character(int charnum) {
 	CharacterInfo *chin = &game.chars[charnum];
 	return get_walkable_area_at_location(chin->x, chin->y);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/walkbehind.cpp b/engines/ags/engine/ac/walkbehind.cpp
index 7ad1b0e2ed..9074446185 100644
--- a/engines/ags/engine/ac/walkbehind.cpp
+++ b/engines/ags/engine/ac/walkbehind.cpp
@@ -27,6 +27,8 @@
 #include "gfx/graphicsdriver.h"
 #include "gfx/bitmap.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -54,9 +56,9 @@ void update_walk_behind_images() {
 
 		if (walkBehindRight[ee] > 0) {
 			wbbmp = BitmapHelper::CreateTransparentBitmap(
-			            (walkBehindRight[ee] - walkBehindLeft[ee]) + 1,
-			            (walkBehindBottom[ee] - walkBehindTop[ee]) + 1,
-			            thisroom.BgFrames[play.bg_frame].Graphic->GetColorDepth());
+				(walkBehindRight[ee] - walkBehindLeft[ee]) + 1,
+				(walkBehindBottom[ee] - walkBehindTop[ee]) + 1,
+				thisroom.BgFrames[play.bg_frame].Graphic->GetColorDepth());
 			int yy, startX = walkBehindLeft[ee], startY = walkBehindTop[ee];
 			for (rr = startX; rr <= walkBehindRight[ee]; rr++) {
 				for (yy = startY; yy <= walkBehindBottom[ee]; yy++) {
@@ -139,3 +141,5 @@ void recache_walk_behinds() {
 		update_walk_behind_images();
 	}
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/debugging/consoleoutputtarget.cpp b/engines/ags/engine/debugging/consoleoutputtarget.cpp
index 3e90694f39..6f638edd7b 100644
--- a/engines/ags/engine/debugging/consoleoutputtarget.cpp
+++ b/engines/ags/engine/debugging/consoleoutputtarget.cpp
@@ -24,6 +24,7 @@
 #include "consoleoutputtarget.h"
 #include "debug/debug_log.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
@@ -44,3 +45,4 @@ void ConsoleOutputTarget::PrintMessage(const DebugMessage &msg) {
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
diff --git a/engines/ags/engine/debugging/debug.cpp b/engines/ags/engine/debugging/debug.cpp
index 997add89ef..a974ff2995 100644
--- a/engines/ags/engine/debugging/debug.cpp
+++ b/engines/ags/engine/debugging/debug.cpp
@@ -48,6 +48,8 @@
 #include <winalleg.h>
 #endif
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -165,8 +167,8 @@ MessageType get_messagetype_from_string(const String &mt) {
 typedef std::pair<CommonDebugGroup, MessageType> DbgGroupOption;
 
 void apply_log_config(const ConfigTree &cfg, const String &log_id,
-                      bool def_enabled,
-                      std::initializer_list<DbgGroupOption> def_opts) {
+	bool def_enabled,
+	std::initializer_list<DbgGroupOption> def_opts) {
 	String value = INIreadstring(cfg, "log", log_id);
 	if (value.IsEmpty() && !def_enabled)
 		return;
@@ -231,32 +233,32 @@ void apply_debug_config(const ConfigTree &cfg) {
 	apply_log_config(cfg, OutputSystemID, /* defaults */ true, { DbgGroupOption(kDbgGroup_Main, kDbgMsg_Info) });
 	bool legacy_log_enabled = INIreadint(cfg, "misc", "log", 0) != 0;
 	apply_log_config(cfg, OutputFileID,
-	                 /* defaults */
-	legacy_log_enabled, {
-		DbgGroupOption(kDbgGroup_Main, kDbgMsg_All),
-		DbgGroupOption(kDbgGroup_Game, kDbgMsg_Info),
-		DbgGroupOption(kDbgGroup_Script, kDbgMsg_All),
-#ifdef DEBUG_SPRITECACHE
-		DbgGroupOption(kDbgGroup_SprCache, kDbgMsg_All),
-#else
-		DbgGroupOption(kDbgGroup_SprCache, kDbgMsg_Info),
-#endif
-#ifdef DEBUG_MANAGED_OBJECTS
-		DbgGroupOption(kDbgGroup_ManObj, kDbgMsg_All),
-#else
-		DbgGroupOption(kDbgGroup_ManObj, kDbgMsg_Info),
-#endif
-	});
+		/* defaults */
+		legacy_log_enabled, {
+			DbgGroupOption(kDbgGroup_Main, kDbgMsg_All),
+			DbgGroupOption(kDbgGroup_Game, kDbgMsg_Info),
+			DbgGroupOption(kDbgGroup_Script, kDbgMsg_All),
+	#ifdef DEBUG_SPRITECACHE
+			DbgGroupOption(kDbgGroup_SprCache, kDbgMsg_All),
+	#else
+			DbgGroupOption(kDbgGroup_SprCache, kDbgMsg_Info),
+	#endif
+	#ifdef DEBUG_MANAGED_OBJECTS
+			DbgGroupOption(kDbgGroup_ManObj, kDbgMsg_All),
+	#else
+			DbgGroupOption(kDbgGroup_ManObj, kDbgMsg_Info),
+	#endif
+		});
 
 	// Init game console if the game was compiled in Debug mode
 	if (game.options[OPT_DEBUGMODE] != 0) {
 		apply_log_config(cfg, OutputGameConsoleID,
-		                 /* defaults */
-		true, {
-			DbgGroupOption(kDbgGroup_Main, kDbgMsg_All),
-			DbgGroupOption(kDbgGroup_Game, kDbgMsg_All),
-			DbgGroupOption(kDbgGroup_Script, kDbgMsg_All)
-		});
+			/* defaults */
+			true, {
+				DbgGroupOption(kDbgGroup_Main, kDbgMsg_All),
+				DbgGroupOption(kDbgGroup_Game, kDbgMsg_All),
+				DbgGroupOption(kDbgGroup_Script, kDbgMsg_All)
+			});
 		debug_set_console(true);
 	}
 
@@ -430,7 +432,7 @@ int check_for_messages_from_editor() {
 			free(msg);
 			return 2;
 		} else if ((strncmp(msgPtr, "SETBREAK", 8) == 0) ||
-		           (strncmp(msgPtr, "DELBREAK", 8) == 0)) {
+			(strncmp(msgPtr, "DELBREAK", 8) == 0)) {
 			bool isDelete = (msgPtr[0] == 'D');
 			// Format:  SETBREAK $scriptname$lineNumber$
 			msgPtr += 10;
@@ -449,7 +451,7 @@ int check_for_messages_from_editor() {
 			if (isDelete) {
 				for (i = 0; i < numBreakpoints; i++) {
 					if ((breakpoints[i].lineNumber == lineNumber) &&
-					        (strcmp(breakpoints[i].scriptName, scriptNameBuf) == 0)) {
+						(strcmp(breakpoints[i].scriptName, scriptNameBuf) == 0)) {
 						numBreakpoints--;
 						breakpoints.erase(breakpoints.begin() + i);
 						break;
@@ -548,7 +550,7 @@ void scriptDebugHook(ccInstance *ccinst, int linenum) {
 
 	for (int i = 0; i < numBreakpoints; i++) {
 		if ((breakpoints[i].lineNumber == linenum) &&
-		        (strcmp(breakpoints[i].scriptName, scriptName) == 0)) {
+			(strcmp(breakpoints[i].scriptName, scriptName) == 0)) {
 			break_into_debugger();
 			break;
 		}
@@ -570,5 +572,6 @@ void check_debug_keys() {
 		}
 
 	}
-
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/debugging/filebasedagsdebugger.cpp b/engines/ags/engine/debugging/filebasedagsdebugger.cpp
index a95700ba4f..891fac1155 100644
--- a/engines/ags/engine/debugging/filebasedagsdebugger.cpp
+++ b/engines/ags/engine/debugging/filebasedagsdebugger.cpp
@@ -28,6 +28,8 @@
 #include "util/wgt2allg.h"              // exists()
 #include "platform/base/agsplatformdriver.h"
 
+namespace AGS3 {
+
 using AGS::Shared::Stream;
 using AGS::Shared::TextStreamWriter;
 
@@ -75,3 +77,5 @@ char *FileBasedAGSDebugger::GetNextMessage() {
 	msg[fileSize] = 0;
 	return msg;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/debugging/logfile.cpp b/engines/ags/engine/debugging/logfile.cpp
index ab1639991a..6e237e6f48 100644
--- a/engines/ags/engine/debugging/logfile.cpp
+++ b/engines/ags/engine/debugging/logfile.cpp
@@ -25,7 +25,7 @@
 #include "util/file.h"
 #include "util/stream.h"
 
-
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
@@ -40,7 +40,7 @@ void LogFile::PrintMessage(const DebugMessage &msg) {
 		if (_filePath.IsEmpty())
 			return;
 		_file.reset(File::OpenFile(_filePath, _openMode == kLogFile_Append ? Common::kFile_Create : Common::kFile_CreateAlways,
-		                           Common::kFile_Write));
+			Common::kFile_Write));
 		if (!_file) {
 			Debug::Printf("Unable to write log to '%s'.", _filePath.GetCStr());
 			_filePath = "";
@@ -69,8 +69,8 @@ bool LogFile::OpenFile(const String &file_path, OpenMode open_mode) {
 		return File::TestWriteFile(_filePath);
 	} else {
 		_file.reset(File::OpenFile(file_path,
-		                           open_mode == kLogFile_Append ? Common::kFile_Create : Common::kFile_CreateAlways,
-		                           Common::kFile_Write));
+			open_mode == kLogFile_Append ? Common::kFile_Create : Common::kFile_CreateAlways,
+			Common::kFile_Write));
 		return _file.get() != nullptr;
 	}
 }
@@ -82,3 +82,4 @@ void LogFile::CloseFile() {
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
diff --git a/engines/ags/engine/debugging/messagebuffer.cpp b/engines/ags/engine/debugging/messagebuffer.cpp
index 3413aa5b26..24fe07705d 100644
--- a/engines/ags/engine/debugging/messagebuffer.cpp
+++ b/engines/ags/engine/debugging/messagebuffer.cpp
@@ -23,6 +23,7 @@
 #include "debug/debugmanager.h"
 #include "debug/messagebuffer.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
@@ -51,7 +52,7 @@ void MessageBuffer::Send(const String &out_id) {
 	if (_msgLost > 0) {
 		DebugGroup gr = DbgMgr.GetGroup(kDbgGroup_Main);
 		DbgMgr.SendMessage(out_id, DebugMessage(String::FromFormat("WARNING: output %s lost exceeding buffer: %u debug messages\n", out_id.GetCStr(), (unsigned)_msgLost),
-		                                        gr.UID.ID, gr.OutputName, kDbgMsg_All));
+			gr.UID.ID, gr.OutputName, kDbgMsg_All));
 	}
 	for (std::vector<DebugMessage>::const_iterator it = _buffer.begin(); it != _buffer.end(); ++it) {
 		DbgMgr.SendMessage(out_id, *it);
@@ -65,3 +66,4 @@ void MessageBuffer::Flush(const String &out_id) {
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
diff --git a/engines/ags/engine/device/mousew32.cpp b/engines/ags/engine/device/mousew32.cpp
index d15a133573..7192299bae 100644
--- a/engines/ags/engine/device/mousew32.cpp
+++ b/engines/ags/engine/device/mousew32.cpp
@@ -60,6 +60,8 @@
 #include "ac/sys_events.h" // j for ags_iskeypressed
 #endif
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -76,7 +78,7 @@ int real_mouse_x = 0, real_mouse_y = 0;
 int boundx1 = 0, boundx2 = 99999, boundy1 = 0, boundy2 = 99999;
 int disable_mgetgraphpos = 0;
 char ignore_bounds = 0;
-extern char alpha_blend_cursor ;
+extern char alpha_blend_cursor;
 Bitmap *mousecurs[MAXCURSORS];
 extern color palette[256];
 extern volatile bool switched_away;
@@ -106,8 +108,8 @@ void mgraphconfine(int x1, int y1, int x2, int y2) {
 	Mouse::ControlRect = Rect(x1, y1, x2, y2);
 	set_mouse_range(Mouse::ControlRect.Left, Mouse::ControlRect.Top, Mouse::ControlRect.Right, Mouse::ControlRect.Bottom);
 	Debug::Printf("Mouse confined: (%d,%d)-(%d,%d) (%dx%d)",
-	              Mouse::ControlRect.Left, Mouse::ControlRect.Top, Mouse::ControlRect.Right, Mouse::ControlRect.Bottom,
-	              Mouse::ControlRect.GetWidth(), Mouse::ControlRect.GetHeight());
+		Mouse::ControlRect.Left, Mouse::ControlRect.Top, Mouse::ControlRect.Right, Mouse::ControlRect.Bottom,
+		Mouse::ControlRect.GetWidth(), Mouse::ControlRect.GetHeight());
 }
 
 void mgetgraphpos() {
@@ -116,7 +118,7 @@ void mgetgraphpos() {
 		// The cursor coordinates are provided from alternate source;
 		// in this case we completely ignore actual cursor movement.
 		if (!ignore_bounds &&
-		        (mousex < boundx1 || mousey < boundy1 || mousex > boundx2 || mousey > boundy2)) {
+			(mousex < boundx1 || mousey < boundy1 || mousex > boundx2 || mousey > boundy2)) {
 			mousex = Math::Clamp(mousex, boundx1, boundx2);
 			mousey = Math::Clamp(mousey, boundy1, boundy2);
 			msetgraphpos(mousex, mousey);
@@ -173,7 +175,7 @@ void mgetgraphpos() {
 	mousey = real_mouse_y;
 
 	if (!ignore_bounds &&
-	        (mousex < boundx1 || mousey < boundy1 || mousex > boundx2 || mousey > boundy2)) {
+		(mousex < boundx1 || mousey < boundy1 || mousex > boundx2 || mousey > boundy2)) {
 		mousex = Math::Clamp(mousex, boundx1, boundx2);
 		mousey = Math::Clamp(mousey, boundy1, boundy2);
 		msetgraphpos(mousex, mousey);
@@ -247,7 +249,7 @@ int mgetbutton() {
 	poll_mouse();
 	int butis = mouse_b;
 
-	if ((butis > 0) & (butwas > 0))
+	if ((butis > 0) &(butwas > 0))
 		return NONE;  // don't allow holding button down
 
 	if (butis & 1) {
@@ -356,3 +358,5 @@ void Mouse::SetSpeed(float speed) {
 float Mouse::GetSpeed() {
 	return SpeedVal;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/font/fonts_engine.cpp b/engines/ags/engine/font/fonts_engine.cpp
index 1f773351ca..2b77e3d496 100644
--- a/engines/ags/engine/font/fonts_engine.cpp
+++ b/engines/ags/engine/font/fonts_engine.cpp
@@ -29,6 +29,8 @@
 #include <alfont.h>
 #include "ac/gamesetupstruct.h"
 
+namespace AGS3 {
+
 extern int our_eip;
 extern GameSetupStruct game;
 
@@ -43,3 +45,5 @@ void set_our_eip(int eip) {
 int get_our_eip() {
 	return our_eip;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/game/game_init.cpp b/engines/ags/engine/game/game_init.cpp
index 8ba060cfa6..3df894addc 100644
--- a/engines/ags/engine/game/game_init.cpp
+++ b/engines/ags/engine/game/game_init.cpp
@@ -51,15 +51,17 @@
 #include "util/string_utils.h"
 #include "media/audio/audio_system.h"
 
+namespace AGS3 {
+
 using namespace Shared;
 using namespace Engine;
 
 extern GameSetupStruct game;
 extern int actSpsCount;
 extern Bitmap **actsps;
-extern IDriverDependantBitmap * *actspsbmp;
+extern IDriverDependantBitmap **actspsbmp;
 extern Bitmap **actspswb;
-extern IDriverDependantBitmap * *actspswbbmp;
+extern IDriverDependantBitmap **actspswbbmp;
 extern CachedActSpsData *actspswbcache;
 extern CharacterCache *charcache;
 
@@ -75,7 +77,7 @@ extern CCAudioChannel ccDynamicAudio;
 extern CCAudioClip ccDynamicAudioClip;
 extern ScriptString myScriptStringImpl;
 extern ScriptObject scrObj[MAX_ROOM_OBJECTS];
-extern ScriptGUI    *scrGui;
+extern ScriptGUI *scrGui;
 extern ScriptHotspot scrHotspot[MAX_ROOM_HOTSPOTS];
 extern ScriptRegion scrRegion[MAX_ROOM_REGIONS];
 extern ScriptInvItem scrInv[MAX_INV];
@@ -334,10 +336,10 @@ HGameInitError InitGameState(const LoadedGameEntities &ents, GameDataVersion dat
 	if (data_ver >= kGameVersion_341) {
 		// TODO: find a way to either automate this list of strings or make it more visible (shared & easier to find in engine code)
 		// TODO: stack-allocated strings, here and in other similar places
-		const String scapi_names[kScriptAPI_Current + 1] = {"v3.2.1", "v3.3.0", "v3.3.4", "v3.3.5", "v3.4.0", "v3.4.1", "v3.5.0", "v3.5.0.7"};
+		const String scapi_names[kScriptAPI_Current + 1] = { "v3.2.1", "v3.3.0", "v3.3.4", "v3.3.5", "v3.4.0", "v3.4.1", "v3.5.0", "v3.5.0.7" };
 		Debug::Printf(kDbgMsg_Info, "Requested script API: %s (%d), compat level: %s (%d)",
-		              base_api >= 0 && base_api <= kScriptAPI_Current ? scapi_names[base_api].GetCStr() : "unknown", base_api,
-		              compat_api >= 0 && compat_api <= kScriptAPI_Current ? scapi_names[compat_api].GetCStr() : "unknown", compat_api);
+			base_api >= 0 && base_api <= kScriptAPI_Current ? scapi_names[base_api].GetCStr() : "unknown", base_api,
+			compat_api >= 0 && compat_api <= kScriptAPI_Current ? scapi_names[compat_api].GetCStr() : "unknown", compat_api);
 	}
 	// If the game was compiled using unsupported version of the script API,
 	// we warn about potential incompatibilities but proceed further.
@@ -450,3 +452,4 @@ HGameInitError InitGameState(const LoadedGameEntities &ents, GameDataVersion dat
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
diff --git a/engines/ags/engine/game/savegame.cpp b/engines/ags/engine/game/savegame.cpp
index 693794a957..1b55a38210 100644
--- a/engines/ags/engine/game/savegame.cpp
+++ b/engines/ags/engine/game/savegame.cpp
@@ -62,6 +62,8 @@
 #include "util/string_utils.h"
 #include "media/audio/audio_system.h"
 
+namespace AGS3 {
+
 using namespace Shared;
 using namespace Engine;
 
@@ -82,7 +84,7 @@ namespace AGS {
 namespace Engine {
 
 const String SavegameSource::LegacySignature = "Adventure Game Studio saved game";
-const String SavegameSource::Signature       = "Adventure Game Studio saved game v2";
+const String SavegameSource::Signature = "Adventure Game Studio saved game v2";
 
 SavegameSource::SavegameSource()
 	: Version(kSvgVersion_Undefined) {
@@ -178,7 +180,7 @@ HSaveError ReadDescription(Stream *in, SavegameVersion &svg_ver, SavegameDescrip
 	svg_ver = (SavegameVersion)in->ReadInt32();
 	if (svg_ver < kSvgVersion_LowestSupported || svg_ver > kSvgVersion_Current)
 		return new SavegameError(kSvgErr_FormatVersionNotSupported,
-		                         String::FromFormat("Required: %d, supported: %d - %d.", svg_ver, kSvgVersion_LowestSupported, kSvgVersion_Current));
+			String::FromFormat("Required: %d, supported: %d - %d.", svg_ver, kSvgVersion_LowestSupported, kSvgVersion_Current));
 
 	// Enviroment information
 	if (elems & kSvgDesc_EnvInfo) {
@@ -223,9 +225,9 @@ HSaveError ReadDescription_v321(Stream *in, SavegameVersion &svg_ver, SavegameDe
 
 	// Check saved game format version
 	if (svg_ver < kSvgVersion_LowestSupported ||
-	        svg_ver > kSvgVersion_Current) {
+		svg_ver > kSvgVersion_Current) {
 		return new SavegameError(kSvgErr_FormatVersionNotSupported,
-		                         String::FromFormat("Required: %d, supported: %d - %d.", svg_ver, kSvgVersion_LowestSupported, kSvgVersion_Current));
+			String::FromFormat("Required: %d, supported: %d - %d.", svg_ver, kSvgVersion_LowestSupported, kSvgVersion_Current));
 	}
 
 	if (elems & kSvgDesc_UserImage)
@@ -236,10 +238,10 @@ HSaveError ReadDescription_v321(Stream *in, SavegameVersion &svg_ver, SavegameDe
 	String version_str = String::FromStream(in);
 	Version eng_version(version_str);
 	if (eng_version > EngineVersion ||
-	        eng_version < SavedgameLowestBackwardCompatVersion) {
+		eng_version < SavedgameLowestBackwardCompatVersion) {
 		// Engine version is either non-forward or non-backward compatible
 		return new SavegameError(kSvgErr_IncompatibleEngine,
-		                         String::FromFormat("Required: %s, supported: %s - %s.", eng_version.LongString.GetCStr(), SavedgameLowestBackwardCompatVersion.LongString.GetCStr(), EngineVersion.LongString.GetCStr()));
+			String::FromFormat("Required: %s, supported: %s - %s.", eng_version.LongString.GetCStr(), SavedgameLowestBackwardCompatVersion.LongString.GetCStr(), EngineVersion.LongString.GetCStr()));
 	}
 	if (elems & kSvgDesc_EnvInfo) {
 		desc.MainDataFilename.Read(in);
@@ -457,19 +459,19 @@ HSaveError DoAfterRestore(const PreservedParams &pp, const RestoredData &r_data)
 
 	if (create_global_script()) {
 		return new SavegameError(kSvgErr_GameObjectInitFailed,
-		                         String::FromFormat("Unable to recreate global script: %s", ccErrorString.GetCStr()));
+			String::FromFormat("Unable to recreate global script: %s", ccErrorString.GetCStr()));
 	}
 
 	// read the global data into the newly created script
 	if (r_data.GlobalScript.Data.get())
 		memcpy(gameinst->globaldata, r_data.GlobalScript.Data.get(),
-		       Math::Min((size_t)gameinst->globaldatasize, r_data.GlobalScript.Len));
+			Math::Min((size_t)gameinst->globaldatasize, r_data.GlobalScript.Len));
 
 	// restore the script module data
 	for (int i = 0; i < numScriptModules; ++i) {
 		if (r_data.ScriptModules[i].Data.get())
 			memcpy(moduleInst[i]->globaldata, r_data.ScriptModules[i].Data.get(),
-			       Math::Min((size_t)moduleInst[i]->globaldatasize, r_data.ScriptModules[i].Len));
+				Math::Min((size_t)moduleInst[i]->globaldatasize, r_data.ScriptModules[i].Len));
 	}
 
 	setup_player_character(game.playercharacter);
@@ -556,10 +558,10 @@ HSaveError DoAfterRestore(const PreservedParams &pp, const RestoredData &r_data)
 				continue;
 			if ((size_t)chan_info.ClipID >= game.audioClips.size()) {
 				return new SavegameError(kSvgErr_GameObjectInitFailed,
-				                         String::FromFormat("Invalid audio clip index: %d (clip count: %u).", chan_info.ClipID, game.audioClips.size()));
+					String::FromFormat("Invalid audio clip index: %d (clip count: %u).", chan_info.ClipID, game.audioClips.size()));
 			}
 			play_audio_clip_on_channel(i, &game.audioClips[chan_info.ClipID],
-			                           chan_info.Priority, chan_info.Repeat, chan_info.Pos);
+				chan_info.Priority, chan_info.Repeat, chan_info.Pos);
 
 			auto *ch = lock.GetChannel(i);
 			if (ch != nullptr) {
@@ -629,7 +631,7 @@ HSaveError DoAfterRestore(const PreservedParams &pp, const RestoredData &r_data)
 		AudioChannelsLock lock;
 
 		if ((crossFading > 0 && !lock.GetChannelIfPlaying(crossFading)) ||
-		        (crossFading <= 0 && !lock.GetChannelIfPlaying(SCHAN_MUSIC))) {
+			(crossFading <= 0 && !lock.GetChannelIfPlaying(SCHAN_MUSIC))) {
 			current_music_type = 0; // playback failed, reset flag
 		}
 	}
@@ -735,3 +737,4 @@ void SaveGameState(PStream out) {
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
diff --git a/engines/ags/engine/game/savegame_components.cpp b/engines/ags/engine/game/savegame_components.cpp
index b716e1db4d..c0bef7a568 100644
--- a/engines/ags/engine/game/savegame_components.cpp
+++ b/engines/ags/engine/game/savegame_components.cpp
@@ -60,6 +60,8 @@
 #include "util/filestream.h" // TODO: needed only because plugins expect file handle
 #include "media/audio/audio_system.h"
 
+namespace AGS3 {
+
 using namespace Shared;
 
 extern GameSetupStruct game;
@@ -1261,3 +1263,4 @@ HSaveError WriteAllCommon(PStream out) {
 } // namespace SavegameBlocks
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
diff --git a/engines/ags/engine/game/viewport.cpp b/engines/ags/engine/game/viewport.cpp
index 6bb62c5952..ddbed3d8be 100644
--- a/engines/ags/engine/game/viewport.cpp
+++ b/engines/ags/engine/game/viewport.cpp
@@ -26,6 +26,8 @@
 #include "game/roomstruct.h"
 #include "game/viewport.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern RoomStruct thisroom;
@@ -202,3 +204,5 @@ VpPoint Viewport::ScreenToRoom(int scrx, int scry, bool clip, bool convert_cam_t
 	}
 	return std::make_pair(p, _id);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/gfx/ali3dogl.cpp b/engines/ags/engine/gfx/ali3dogl.cpp
index 406449cc23..5b275a592b 100644
--- a/engines/ags/engine/gfx/ali3dogl.cpp
+++ b/engines/ags/engine/gfx/ali3dogl.cpp
@@ -35,6 +35,8 @@
 #include "util/math.h"
 #include "ac/timer.h"
 
+namespace AGS3 {
+
 #if AGS_PLATFORM_OS_ANDROID
 
 #define glOrtho glOrthof
@@ -1871,5 +1873,6 @@ OGLGfxFilter *OGLGraphicsFactory::CreateFilter(const String &id) {
 } // namespace OGL
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif // only on Windows, Android and iOS
diff --git a/engines/ags/engine/gfx/ali3dsw.cpp b/engines/ags/engine/gfx/ali3dsw.cpp
index 3ade745800..85b121ced9 100644
--- a/engines/ags/engine/gfx/ali3dsw.cpp
+++ b/engines/ags/engine/gfx/ali3dsw.cpp
@@ -37,6 +37,8 @@
 #include "platform/base/agsplatformdriver.h"
 #include "ac/timer.h"
 
+namespace AGS3 {
+
 #if AGS_DDRAW_GAMMA_CONTROL
 // NOTE: this struct and variables are defined internally in Allegro
 typedef struct DDRAW_SURFACE {
@@ -49,7 +51,7 @@ typedef struct DDRAW_SURFACE {
 } DDRAW_SURFACE;
 
 extern "C" extern LPDIRECTDRAW2 directdraw;
-extern "C" DDRAW_SURFACE *gfx_directx_primary_surface;
+extern "C" DDRAW_SURFACE * gfx_directx_primary_surface;
 #endif // AGS_DDRAW_GAMMA_CONTROL
 
 #ifndef AGS_NO_VIDEO_PLAYER
@@ -116,8 +118,8 @@ bool ALSoftwareGraphicsDriver::IsModeSupported(const DisplayMode &mode) {
 		// between loads of unsupported resolutions
 		for (int i = 0; i < _gfxModeList->num_modes; i++) {
 			if ((_gfxModeList->mode[i].width == mode.Width) &&
-			        (_gfxModeList->mode[i].height == mode.Height) &&
-			        (_gfxModeList->mode[i].bpp == mode.ColorDepth)) {
+				(_gfxModeList->mode[i].height == mode.Height) &&
+				(_gfxModeList->mode[i].bpp == mode.ColorDepth)) {
 				return true;
 			}
 		}
@@ -211,8 +213,8 @@ bool ALSoftwareGraphicsDriver::SetDisplayMode(const DisplayMode &mode, volatile
 		ddrawCaps.dwSize = sizeof(ddrawCaps);
 		IDirectDraw2_GetCaps(directdraw, &ddrawCaps, NULL);
 
-		if ((ddrawCaps.dwCaps2 & DDCAPS2_PRIMARYGAMMA) == 0) { }
-		else if (IDirectDrawSurface2_QueryInterface(gfx_directx_primary_surface->id, IID_IDirectDrawGammaControl, (void **)&dxGammaControl) == 0) {
+		if ((ddrawCaps.dwCaps2 & DDCAPS2_PRIMARYGAMMA) == 0) {
+		} else if (IDirectDrawSurface2_QueryInterface(gfx_directx_primary_surface->id, IID_IDirectDrawGammaControl, (void **)&dxGammaControl) == 0) {
 			dxGammaControl->GetGammaRamp(0, &defaultGammaRamp);
 		}
 	}
@@ -438,7 +440,7 @@ void ALSoftwareGraphicsDriver::RenderToBackBuffer() {
 			RenderSpriteBatch(batch, surface, transform.X, transform.Y);
 			if (!batch.IsVirtualScreen)
 				virtualScreen->StretchBlt(surface, RectWH(view_offx, view_offy, viewport.GetWidth(), viewport.GetHeight()),
-				                          batch.Opaque ? kBitmap_Copy : kBitmap_Transparency);
+					batch.Opaque ? kBitmap_Copy : kBitmap_Transparency);
 		} else {
 			RenderSpriteBatch(batch, virtualScreen, view_offx + transform.X, view_offy + transform.Y);
 		}
@@ -468,9 +470,10 @@ void ALSoftwareGraphicsDriver::RenderSpriteBatch(const ALSpriteBatch &batch, Com
 		int drawAtX = drawlist[i].x + surf_offx;
 		int drawAtY = drawlist[i].y + surf_offy;
 
-		if (bitmap->_transparency >= 255) {} // fully transparent, do nothing
-		else if ((bitmap->_opaque) && (bitmap->_bmp == surface) && (bitmap->_transparency == 0)) {}
-		else if (bitmap->_opaque) {
+		if (bitmap->_transparency >= 255) {
+		} // fully transparent, do nothing
+		else if ((bitmap->_opaque) && (bitmap->_bmp == surface) && (bitmap->_transparency == 0)) {
+		} else if (bitmap->_opaque) {
 			surface->Blit(bitmap->_bmp, 0, 0, drawAtX, drawAtY, bitmap->_bmp->GetWidth(), bitmap->_bmp->GetHeight());
 			// TODO: we need to also support non-masked translucent blend, but...
 			// Allegro 4 **does not have such function ready** :( (only masked blends, where it skips magenta pixels);
@@ -486,23 +489,23 @@ void ALSoftwareGraphicsDriver::RenderSpriteBatch(const ALSpriteBatch &batch, Com
 		} else {
 			// here _transparency is used as alpha (between 1 and 254), but 0 means opaque!
 			GfxUtil::DrawSpriteWithTransparency(surface, bitmap->_bmp, drawAtX, drawAtY,
-			                                    bitmap->_transparency ? bitmap->_transparency : 255);
+				bitmap->_transparency ? bitmap->_transparency : 255);
 		}
 	}
 	// NOTE: following is experimental tint code (currently unused)
 	/*  This alternate method gives the correct (D3D-style) result, but is just too slow!
-	    if ((_spareTintingScreen != NULL) &&
-	        ((_spareTintingScreen->GetWidth() != surface->GetWidth()) || (_spareTintingScreen->GetHeight() != surface->GetHeight())))
-	    {
-	      destroy_bitmap(_spareTintingScreen);
-	      _spareTintingScreen = NULL;
-	    }
-	    if (_spareTintingScreen == NULL)
-	    {
-	      _spareTintingScreen = BitmapHelper::CreateBitmap_(GetColorDepth(surface), surface->GetWidth(), surface->GetHeight());
-	    }
-	    tint_image(surface, _spareTintingScreen, _tint_red, _tint_green, _tint_blue, 100, 255);
-	    Blit(_spareTintingScreen, surface, 0, 0, 0, 0, _spareTintingScreen->GetWidth(), _spareTintingScreen->GetHeight());*/
+		if ((_spareTintingScreen != NULL) &&
+			((_spareTintingScreen->GetWidth() != surface->GetWidth()) || (_spareTintingScreen->GetHeight() != surface->GetHeight())))
+		{
+		  destroy_bitmap(_spareTintingScreen);
+		  _spareTintingScreen = NULL;
+		}
+		if (_spareTintingScreen == NULL)
+		{
+		  _spareTintingScreen = BitmapHelper::CreateBitmap_(GetColorDepth(surface), surface->GetWidth(), surface->GetHeight());
+		}
+		tint_image(surface, _spareTintingScreen, _tint_red, _tint_green, _tint_blue, 100, 255);
+		Blit(_spareTintingScreen, surface, 0, 0, 0, 0, _spareTintingScreen->GetWidth(), _spareTintingScreen->GetHeight());*/
 }
 
 void ALSoftwareGraphicsDriver::Render(int xoff, int yoff, GlobalFlipType flip) {
@@ -561,11 +564,11 @@ bool ALSoftwareGraphicsDriver::GetCopyOfScreenIntoBitmap(Bitmap *destination, bo
 }
 
 /**
-    fade.c - High Color Fading Routines
+	fade.c - High Color Fading Routines
 
-    Last Revision: 21 June, 2002
+	Last Revision: 21 June, 2002
 
-    Author: Matthew Leverton
+	Author: Matthew Leverton
 **/
 void ALSoftwareGraphicsDriver::highcolor_fade_in(Bitmap *vs, void(*draw_callback)(), int offx, int offy, int speed, int targetColourRed, int targetColourGreen, int targetColourBlue) {
 	Bitmap *bmp_orig = vs;
@@ -703,7 +706,7 @@ void ALSoftwareGraphicsDriver::BoxOutEffect(bool blackingOut, int speed, int del
 			boxhit += yspeed;
 			int vcentre = _srcRect.GetHeight() / 2;
 			bmp_orig->FillRect(Rect(_srcRect.GetWidth() / 2 - boxwid / 2, vcentre - boxhit / 2,
-			                        _srcRect.GetWidth() / 2 + boxwid / 2, vcentre + boxhit / 2), 0);
+				_srcRect.GetWidth() / 2 + boxwid / 2, vcentre + boxhit / 2), 0);
 			bmp_buff->Fill(0);
 			bmp_buff->Blit(bmp_orig);
 			if (_drawPostScreenCallback) {
@@ -808,3 +811,4 @@ AllegroGfxFilter *ALSWGraphicsFactory::CreateFilter(const String &id) {
 } // namespace ALSW
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
diff --git a/engines/ags/engine/gfx/blender.cpp b/engines/ags/engine/gfx/blender.cpp
index 8d802b5462..736768836e 100644
--- a/engines/ags/engine/gfx/blender.cpp
+++ b/engines/ags/engine/gfx/blender.cpp
@@ -24,6 +24,8 @@
 #include "gfx/blender.h"
 #include "util/wgt2allg.h"
 
+namespace AGS3 {
+
 extern "C" {
 	// Fallback routine for when we don't have anything better to do.
 	unsigned long _blender_black(unsigned long x, unsigned long y, unsigned long n);
@@ -186,25 +188,25 @@ FORCEINLINE unsigned long argb2argb_blend_core(unsigned long src_col, unsigned l
 		dst_alpha++;
 
 	// dst_g now contains the green hue from destination color
-	dst_g   = (dst_col & 0x00FF00) * dst_alpha / 256;
+	dst_g = (dst_col & 0x00FF00) * dst_alpha / 256;
 	// dst_col now contains the red & blue hues from destination color
 	dst_col = (dst_col & 0xFF00FF) * dst_alpha / 256;
 
 	// res_g now contains the green hue of the pre-final color
-	dst_g   = (((src_col & 0x00FF00) - (dst_g   & 0x00FF00)) * src_alpha / 256 + dst_g)   & 0x00FF00;
+	dst_g = (((src_col & 0x00FF00) - (dst_g & 0x00FF00)) * src_alpha / 256 + dst_g) & 0x00FF00;
 	// res_rb now contains the red & blue hues of the pre-final color
 	dst_col = (((src_col & 0xFF00FF) - (dst_col & 0xFF00FF)) * src_alpha / 256 + dst_col) & 0xFF00FF;
 
 	// dst_alpha now contains the final alpha
 	// we assume that final alpha will never be zero
-	dst_alpha  = 256 - (256 - src_alpha) * (256 - dst_alpha) / 256;
+	dst_alpha = 256 - (256 - src_alpha) * (256 - dst_alpha) / 256;
 	// src_alpha is now the final alpha factor made for being multiplied by,
 	// instead of divided by: this makes it possible to use it in faster
 	// calculation below
-	src_alpha  = /* 256 * 256 == */ 0x10000 / dst_alpha;
+	src_alpha = /* 256 * 256 == */ 0x10000 / dst_alpha;
 
 	// setting up final color hues
-	dst_g   = (dst_g   * src_alpha / 256) & 0x00FF00;
+	dst_g = (dst_g * src_alpha / 256) & 0x00FF00;
 	dst_col = (dst_col * src_alpha / 256) & 0xFF00FF;
 	return dst_col | dst_g | (--dst_alpha << 24);
 }
@@ -284,6 +286,8 @@ void set_opaque_alpha_blender() {
 
 void set_argb2any_blender() {
 	set_blender_mode_ex(_blender_black, _blender_black, _blender_black, _argb2argb_blender,
-	                    _blender_alpha15, skiptranspixels_blender_alpha16, _blender_alpha24,
-	                    0, 0, 0, 0xff); // TODO: do we need to support proper 15- and 24-bit here?
+		_blender_alpha15, skiptranspixels_blender_alpha16, _blender_alpha24,
+		0, 0, 0, 0xff); // TODO: do we need to support proper 15- and 24-bit here?
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/gfx/color_engine.cpp b/engines/ags/engine/gfx/color_engine.cpp
index 95f39dd88d..ae3ec5e192 100644
--- a/engines/ags/engine/gfx/color_engine.cpp
+++ b/engines/ags/engine/gfx/color_engine.cpp
@@ -31,6 +31,8 @@
 #include "util/wgt2allg.h"
 #include "gfx/bitmap.h"
 
+namespace AGS3 {
+
 void __my_setcolor(int *ctset, int newcol, int wantColDep) {
 	if (wantColDep == 8)
 		ctset[0] = newcol;
@@ -52,7 +54,7 @@ void __my_setcolor(int *ctset, int newcol, int wantColDep) {
 			ctset[0] = newcol;
 	} else {
 		ctset[0] = makecol_depth(wantColDep, col_lookups[newcol] >> 16,
-		                         (col_lookups[newcol] >> 8) & 0x000ff, col_lookups[newcol] & 0x000ff);
+			(col_lookups[newcol] >> 8) & 0x000ff, col_lookups[newcol] & 0x000ff);
 
 		// in case it's used on an alpha-channel sprite, make sure it's visible
 		if (wantColDep > 16)
@@ -63,3 +65,5 @@ void __my_setcolor(int *ctset, int newcol, int wantColDep) {
 	//if (wantColDep >= 24)
 //      ctset[0] |= 0x40000000;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/gfx/gfx_util.cpp b/engines/ags/engine/gfx/gfx_util.cpp
index 314c2c6d8a..dd309c0cef 100644
--- a/engines/ags/engine/gfx/gfx_util.cpp
+++ b/engines/ags/engine/gfx/gfx_util.cpp
@@ -24,6 +24,8 @@
 #include "gfx/gfx_util.h"
 #include "gfx/blender.h"
 
+namespace AGS3 {
+
 // CHECKME: is this hack still relevant?
 #if AGS_PLATFORM_OS_IOS || AGS_PLATFORM_OS_ANDROID
 extern int psp_gfx_renderer;
@@ -77,7 +79,7 @@ bool SetBlender(BlendMode blend_mode, bool dst_has_alpha, bool src_has_alpha, in
 	PfnBlenderCb blender;
 	if (dst_has_alpha)
 		blender = src_has_alpha ? set.AllAlpha :
-		          (blend_alpha == 0xFF ? set.OpaqueToAlphaNoTrans : set.OpaqueToAlpha);
+		(blend_alpha == 0xFF ? set.OpaqueToAlphaNoTrans : set.OpaqueToAlpha);
 	else
 		blender = src_has_alpha ? set.AlphaToOpaque : set.AllOpaque;
 
@@ -89,14 +91,14 @@ bool SetBlender(BlendMode blend_mode, bool dst_has_alpha, bool src_has_alpha, in
 }
 
 void DrawSpriteBlend(Bitmap *ds, const Point &ds_at, Bitmap *sprite,
-                     BlendMode blend_mode,  bool dst_has_alpha, bool src_has_alpha, int blend_alpha) {
+	BlendMode blend_mode, bool dst_has_alpha, bool src_has_alpha, int blend_alpha) {
 	if (blend_alpha <= 0)
 		return; // do not draw 100% transparent image
 
 	if (// support only 32-bit blending at the moment
-	    ds->GetColorDepth() == 32 && sprite->GetColorDepth() == 32 &&
-	    // set blenders if applicable and tell if succeeded
-	    SetBlender(blend_mode, dst_has_alpha, src_has_alpha, blend_alpha)) {
+		ds->GetColorDepth() == 32 && sprite->GetColorDepth() == 32 &&
+		// set blenders if applicable and tell if succeeded
+		SetBlender(blend_mode, dst_has_alpha, src_has_alpha, blend_alpha)) {
 		ds->TransBlendBlt(sprite, ds_at.X, ds_at.Y);
 	} else {
 		GfxUtil::DrawSpriteWithTransparency(ds, sprite, ds_at.X, ds_at.Y, blend_alpha);
@@ -110,14 +112,14 @@ void DrawSpriteWithTransparency(Bitmap *ds, Bitmap *sprite, int x, int y, int al
 	}
 
 	int surface_depth = ds->GetColorDepth();
-	int sprite_depth  = sprite->GetColorDepth();
+	int sprite_depth = sprite->GetColorDepth();
 
 	if (sprite_depth < surface_depth
-	        // CHECKME: what is the purpose of this hack and is this still relevant?
+		// CHECKME: what is the purpose of this hack and is this still relevant?
 #if AGS_PLATFORM_OS_IOS || AGS_PLATFORM_OS_ANDROID
-	        || (ds->GetBPP() < surface_depth && psp_gfx_renderer > 0) // Fix for corrupted speechbox outlines with the OGL driver
+		|| (ds->GetBPP() < surface_depth && psp_gfx_renderer > 0) // Fix for corrupted speechbox outlines with the OGL driver
 #endif
-	   ) {
+		) {
 		// If sprite is lower color depth than destination surface, e.g.
 		// 8-bit sprites drawn on 16/32-bit surfaces.
 		if (sprite_depth == 8 && surface_depth >= 24) {
@@ -138,7 +140,7 @@ void DrawSpriteWithTransparency(Bitmap *ds, Bitmap *sprite, int x, int y, int al
 			for (int scan_y = 0; scan_y < hctemp.GetHeight(); ++scan_y) {
 				// we know this must be 1 bpp source and 2 bpp pixel destination
 				const uint8_t *src_scanline = sprite->GetScanLine(scan_y);
-				uint16_t      *dst_scanline = (uint16_t *)hctemp.GetScanLineForWriting(scan_y);
+				uint16_t *dst_scanline = (uint16_t *)hctemp.GetScanLineForWriting(scan_y);
 				for (int scan_x = 0; scan_x < hctemp.GetWidth(); ++scan_x) {
 					if (src_scanline[scan_x] == 0) {
 						dst_scanline[scan_x] = mask_color;
@@ -167,3 +169,4 @@ void DrawSpriteWithTransparency(Bitmap *ds, Bitmap *sprite, int x, int y, int al
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
diff --git a/engines/ags/engine/gfx/gfxdriverbase.cpp b/engines/ags/engine/gfx/gfxdriverbase.cpp
index 1a10be6b83..7de8c33ed2 100644
--- a/engines/ags/engine/gfx/gfxdriverbase.cpp
+++ b/engines/ags/engine/gfx/gfxdriverbase.cpp
@@ -27,6 +27,8 @@
 #include "gfx/gfxdriverbase.h"
 #include "gfx/gfx_util.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 namespace AGS {
@@ -68,7 +70,7 @@ Rect GraphicsDriverBase::GetRenderDestination() const {
 }
 
 void GraphicsDriverBase::BeginSpriteBatch(const Rect &viewport, const SpriteTransform &transform,
-        const Point offset, GlobalFlipType flip, PBitmap surface) {
+	const Point offset, GlobalFlipType flip, PBitmap surface) {
 	_actSpriteBatch++;
 	_spriteBatchDesc.push_back(SpriteBatchDesc(viewport, transform, offset, flip, surface));
 	InitSpriteBatch(_actSpriteBatch, _spriteBatchDesc[_actSpriteBatch]);
@@ -283,14 +285,14 @@ __inline void get_pixel_if_not_transparent32(unsigned int *pixel, unsigned int *
 
 
 void VideoMemoryGraphicsDriver::BitmapToVideoMem(const Bitmap *bitmap, const bool has_alpha, const TextureTile *tile, const VideoMemDDB *target,
-        char *dst_ptr, const int dst_pitch, const bool usingLinearFiltering) {
+	char *dst_ptr, const int dst_pitch, const bool usingLinearFiltering) {
 	const int src_depth = bitmap->GetColorDepth();
 	bool lastPixelWasTransparent = false;
 	for (int y = 0; y < tile->height; y++) {
 		lastPixelWasTransparent = false;
 		const uint8_t *scanline_before = bitmap->GetScanLine(y + tile->y - 1);
-		const uint8_t *scanline_at     = bitmap->GetScanLine(y + tile->y);
-		const uint8_t *scanline_after  = bitmap->GetScanLine(y + tile->y + 1);
+		const uint8_t *scanline_at = bitmap->GetScanLine(y + tile->y);
+		const uint8_t *scanline_after = bitmap->GetScanLine(y + tile->y + 1);
 		unsigned int *memPtrLong = (unsigned int *)dst_ptr;
 
 		for (int x = 0; x < tile->width; x++) {
@@ -401,7 +403,7 @@ void VideoMemoryGraphicsDriver::BitmapToVideoMem(const Bitmap *bitmap, const boo
 }
 
 void VideoMemoryGraphicsDriver::BitmapToVideoMemOpaque(const Bitmap *bitmap, const bool has_alpha, const TextureTile *tile, const VideoMemDDB *target,
-        char *dst_ptr, const int dst_pitch) {
+	char *dst_ptr, const int dst_pitch) {
 	const int src_depth = bitmap->GetColorDepth();
 	for (int y = 0; y < tile->height; y++) {
 		const uint8_t *scanline_at = bitmap->GetScanLine(y + tile->y);
@@ -430,3 +432,4 @@ void VideoMemoryGraphicsDriver::BitmapToVideoMemOpaque(const Bitmap *bitmap, con
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
diff --git a/engines/ags/engine/gfx/gfxdriverfactory.cpp b/engines/ags/engine/gfx/gfxdriverfactory.cpp
index 4147c8d947..d2469785df 100644
--- a/engines/ags/engine/gfx/gfxdriverfactory.cpp
+++ b/engines/ags/engine/gfx/gfxdriverfactory.cpp
@@ -42,6 +42,7 @@
 
 #include "main/main_allegro.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
@@ -72,3 +73,4 @@ IGfxDriverFactory *GetGfxDriverFactory(const String id) {
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
diff --git a/engines/ags/engine/gfx/gfxfilter_aad3d.cpp b/engines/ags/engine/gfx/gfxfilter_aad3d.cpp
index c09ee706e8..bdbde84b75 100644
--- a/engines/ags/engine/gfx/gfxfilter_aad3d.cpp
+++ b/engines/ags/engine/gfx/gfxfilter_aad3d.cpp
@@ -28,6 +28,7 @@
 #include <d3d9.h>
 #endif
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 namespace D3D {
@@ -53,3 +54,4 @@ bool AAD3DGfxFilter::NeedToColourEdgeLines() {
 } // namespace D3D
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
diff --git a/engines/ags/engine/gfx/gfxfilter_aaogl.cpp b/engines/ags/engine/gfx/gfxfilter_aaogl.cpp
index cb34a0ae49..70d5e869a3 100644
--- a/engines/ags/engine/gfx/gfxfilter_aaogl.cpp
+++ b/engines/ags/engine/gfx/gfxfilter_aaogl.cpp
@@ -27,6 +27,7 @@
 #include "gfx/gfxfilter_aaogl.h"
 #include "ogl_headers.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 namespace OGL {
@@ -49,5 +50,6 @@ const GfxFilterInfo &AAOGLGfxFilter::GetInfo() const {
 } // namespace OGL
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif // only on Windows, Android and iOS
diff --git a/engines/ags/engine/gfx/gfxfilter_allegro.cpp b/engines/ags/engine/gfx/gfxfilter_allegro.cpp
index 94177683c2..8385ef783d 100644
--- a/engines/ags/engine/gfx/gfxfilter_allegro.cpp
+++ b/engines/ags/engine/gfx/gfxfilter_allegro.cpp
@@ -22,6 +22,7 @@
 
 #include "gfx/gfxfilter_allegro.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 namespace ALSW {
@@ -135,8 +136,8 @@ void AllegroGfxFilter::GetCopyOfScreenIntoBitmap(Bitmap *copyBitmap, bool copy_w
 			// so copy the screen to a buffer first.
 			realScreenSizedBuffer->Blit(realScreen, 0, 0);
 			copyBitmap->StretchBlt(realScreenSizedBuffer,
-			                       _dstRect,
-			                       RectWH(0, 0, copyBitmap->GetWidth(), copyBitmap->GetHeight()));
+				_dstRect,
+				RectWH(0, 0, copyBitmap->GetWidth(), copyBitmap->GetHeight()));
 		}
 	} else if (!lastBlitFrom)
 		copyBitmap->Fill(0);
@@ -144,8 +145,8 @@ void AllegroGfxFilter::GetCopyOfScreenIntoBitmap(Bitmap *copyBitmap, bool copy_w
 		copyBitmap->Blit(realScreen, lastBlitX, lastBlitY, 0, 0, copyBitmap->GetWidth(), copyBitmap->GetHeight());
 	else {
 		copyBitmap->StretchBlt(lastBlitFrom,
-		                       RectWH(0, 0, lastBlitFrom->GetWidth(), lastBlitFrom->GetHeight()),
-		                       RectWH(0, 0, copyBitmap->GetWidth(), copyBitmap->GetHeight()));
+			RectWH(0, 0, lastBlitFrom->GetWidth(), lastBlitFrom->GetHeight()),
+			RectWH(0, 0, copyBitmap->GetWidth(), copyBitmap->GetHeight()));
 	}
 }
 
@@ -157,3 +158,4 @@ Bitmap *AllegroGfxFilter::PreRenderPass(Bitmap *toRender) {
 } // namespace ALSW
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
diff --git a/engines/ags/engine/gfx/gfxfilter_d3d.cpp b/engines/ags/engine/gfx/gfxfilter_d3d.cpp
index 4ed4890b08..8156af57ee 100644
--- a/engines/ags/engine/gfx/gfxfilter_d3d.cpp
+++ b/engines/ags/engine/gfx/gfxfilter_d3d.cpp
@@ -26,6 +26,7 @@
 #include <d3d9.h>
 #endif
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 namespace D3D {
@@ -51,3 +52,4 @@ bool D3DGfxFilter::NeedToColourEdgeLines() {
 } // namespace D3D
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
diff --git a/engines/ags/engine/gfx/gfxfilter_hqx.cpp b/engines/ags/engine/gfx/gfxfilter_hqx.cpp
index 9bee9d28af..1974779a7c 100644
--- a/engines/ags/engine/gfx/gfxfilter_hqx.cpp
+++ b/engines/ags/engine/gfx/gfxfilter_hqx.cpp
@@ -24,6 +24,7 @@
 #include "gfx/gfxfilter_hqx.h"
 #include "gfx/hq2x3x.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 namespace ALSW {
@@ -79,7 +80,7 @@ Bitmap *HqxGfxFilter::ShutdownAndReturnRealScreen() {
 Bitmap *HqxGfxFilter::PreRenderPass(Bitmap *toRender) {
 	_hqxScalingBuffer->Acquire();
 	_pfnHqx(toRender->GetDataForWriting(), _hqxScalingBuffer->GetDataForWriting(),
-	        toRender->GetWidth(), toRender->GetHeight(), _hqxScalingBuffer->GetLineLength());
+		toRender->GetWidth(), toRender->GetHeight(), _hqxScalingBuffer->GetLineLength());
 	_hqxScalingBuffer->Release();
 	return _hqxScalingBuffer;
 }
@@ -87,3 +88,4 @@ Bitmap *HqxGfxFilter::PreRenderPass(Bitmap *toRender) {
 } // namespace ALSW
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
diff --git a/engines/ags/engine/gfx/gfxfilter_ogl.cpp b/engines/ags/engine/gfx/gfxfilter_ogl.cpp
index 7ca95acbb9..9d480c0de5 100644
--- a/engines/ags/engine/gfx/gfxfilter_ogl.cpp
+++ b/engines/ags/engine/gfx/gfxfilter_ogl.cpp
@@ -27,6 +27,7 @@
 #include "gfx/gfxfilter_ogl.h"
 #include "ogl_headers.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 namespace OGL {
@@ -49,5 +50,6 @@ const GfxFilterInfo &OGLGfxFilter::GetInfo() const {
 } // namespace OGL
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif // only on Windows, Android and iOS
diff --git a/engines/ags/engine/gfx/gfxfilter_scaling.cpp b/engines/ags/engine/gfx/gfxfilter_scaling.cpp
index 455015105b..7b013e1309 100644
--- a/engines/ags/engine/gfx/gfxfilter_scaling.cpp
+++ b/engines/ags/engine/gfx/gfxfilter_scaling.cpp
@@ -22,6 +22,7 @@
 
 #include "gfx/gfxfilter_scaling.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
@@ -47,3 +48,4 @@ Rect ScalingGfxFilter::GetDestination() const {
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
diff --git a/engines/ags/engine/gui/animatingguibutton.cpp b/engines/ags/engine/gui/animatingguibutton.cpp
index a5fcb1aa05..bac2621ab4 100644
--- a/engines/ags/engine/gui/animatingguibutton.cpp
+++ b/engines/ags/engine/gui/animatingguibutton.cpp
@@ -23,6 +23,8 @@
 #include "gui/animatingguibutton.h"
 #include "util/stream.h"
 
+namespace AGS3 {
+
 using AGS::Shared::Stream;
 
 void AnimatingGUIButton::ReadFromFile(Stream *in) {
@@ -48,3 +50,5 @@ void AnimatingGUIButton::WriteToFile(Stream *out) {
 	out->WriteInt16(repeat);
 	out->WriteInt16(wait);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/gui/cscidialog.cpp b/engines/ags/engine/gui/cscidialog.cpp
index 6c6cac7523..9dc7a079d3 100644
--- a/engines/ags/engine/gui/cscidialog.cpp
+++ b/engines/ags/engine/gui/cscidialog.cpp
@@ -43,6 +43,8 @@
 #include "platform/base/agsplatformdriver.h"
 #include "ac/timer.h"
 
+namespace AGS3 {
+
 using AGS::Shared::Bitmap;
 namespace BitmapHelper = AGS::Shared::BitmapHelper;
 
@@ -165,7 +167,7 @@ int CSCIWaitMessage(CSCIMessage *cscim) {
 			} else if (keywas == 27) {
 				cscim->id = finddefaultcontrol(CNF_CANCEL);
 				cscim->code = CM_COMMAND;
-			} else if ((keywas < 32) && (keywas != 8)) ;
+			} else if ((keywas < 32) && (keywas != 8));
 			else if ((keywas >= 372) & (keywas <= 381) & (finddefaultcontrol(CNT_LISTBOX) >= 0))
 				vobjs[finddefaultcontrol(CNT_LISTBOX)]->processmessage(CTB_KEYPRESS, keywas, 0);
 			else if (finddefaultcontrol(CNT_TEXTBOX) >= 0)
@@ -306,3 +308,5 @@ int finddefaultcontrol(int flagmask) {
 int GetBaseWidth() {
 	return play.GetUIViewport().GetWidth();
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/gui/gui_engine.cpp b/engines/ags/engine/gui/gui_engine.cpp
index e19c753eea..c5a7e1b650 100644
--- a/engines/ags/engine/gui/gui_engine.cpp
+++ b/engines/ags/engine/gui/gui_engine.cpp
@@ -44,6 +44,8 @@
 #include "gfx/bitmap.h"
 #include "gfx/blender.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 // For engine these are defined in ac.cpp
@@ -68,10 +70,10 @@ bool GUIMain::HasAlphaChannel() const {
 	}
 	// transparent background, enable alpha blending
 	return game.GetColorDepth() >= 24 &&
-	       // transparent background have alpha channel only since 3.2.0;
-	       // "classic" gui rendering mode historically had non-alpha transparent backgrounds
-	       // (3.2.0 broke the compatibility, now we restore it)
-	       loaded_game_file_version >= kGameVersion_320 && game.options[OPT_NEWGUIALPHA] != kGuiAlphaRender_Legacy;
+		// transparent background have alpha channel only since 3.2.0;
+		// "classic" gui rendering mode historically had non-alpha transparent backgrounds
+		// (3.2.0 broke the compatibility, now we restore it)
+		loaded_game_file_version >= kGameVersion_320 && game.options[OPT_NEWGUIALPHA] != kGuiAlphaRender_Legacy;
 }
 
 //=============================================================================
@@ -158,3 +160,4 @@ void GUIButton::PrepareTextToDraw() {
 
 } // namespace Shared
 } // namespace AGS
+} // namespace AGS3
diff --git a/engines/ags/engine/gui/guidialog.cpp b/engines/ags/engine/gui/guidialog.cpp
index cc9b7c977a..b793a689ca 100644
--- a/engines/ags/engine/gui/guidialog.cpp
+++ b/engines/ags/engine/gui/guidialog.cpp
@@ -34,6 +34,8 @@
 #include "gfx/graphicsdriver.h"
 #include "debug/debug_log.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -113,10 +115,10 @@ int loadgamedialog() {
 
 	int handl = CSCIDrawWindow(boxleft, boxtop, wnd_width, wnd_height);
 	int ctrlok =
-	    CSCICreateControl(CNT_PUSHBUTTON | CNF_DEFAULT, 135, 5, 60, 10, get_global_message(MSG_RESTORE));
+		CSCICreateControl(CNT_PUSHBUTTON | CNF_DEFAULT, 135, 5, 60, 10, get_global_message(MSG_RESTORE));
 	int ctrlcancel =
-	    CSCICreateControl(CNT_PUSHBUTTON | CNF_CANCEL, 135, 5 + buttonhit, 60, 10,
-	                      get_global_message(MSG_CANCEL));
+		CSCICreateControl(CNT_PUSHBUTTON | CNF_CANCEL, 135, 5 + buttonhit, 60, 10,
+			get_global_message(MSG_CANCEL));
 	int ctrllist = CSCICreateControl(CNT_LISTBOX, 10, 30, 120, 80, nullptr);
 	int ctrltex1 = CSCICreateControl(CNT_LABEL, 10, 5, 120, 0, get_global_message(MSG_SELECTLOAD));
 	CSCISendControlMessage(ctrllist, CLB_CLEAR, 0, 0);
@@ -168,8 +170,8 @@ int savegamedialog() {
 
 	int handl = CSCIDrawWindow(boxleft, boxtop, wnd_width, wnd_height);
 	int ctrlcancel =
-	    CSCICreateControl(CNT_PUSHBUTTON | CNF_CANCEL, 135, 5 + buttonhit, 60, 10,
-	                      get_global_message(MSG_CANCEL));
+		CSCICreateControl(CNT_PUSHBUTTON | CNF_CANCEL, 135, 5 + buttonhit, 60, 10,
+			get_global_message(MSG_CANCEL));
 	int ctrllist = CSCICreateControl(CNT_LISTBOX, 10, 40, 120, 80, nullptr);
 	int ctrltbox = 0;
 
@@ -210,17 +212,17 @@ int savegamedialog() {
 				if (toomanygames) {
 					int nwhand = CSCIDrawWindow(boxleft + 5, boxtop + 20, 190, 65);
 					int lbl1 =
-					    CSCICreateControl(CNT_LABEL, 15, 5, 160, 0, get_global_message(MSG_REPLACEWITH1));
+						CSCICreateControl(CNT_LABEL, 15, 5, 160, 0, get_global_message(MSG_REPLACEWITH1));
 					int lbl2 = CSCICreateControl(CNT_LABEL, 25, 14, 160, 0, bufTemp);
 					int lbl3 =
-					    CSCICreateControl(CNT_LABEL, 15, 25, 160, 0, get_global_message(MSG_REPLACEWITH2));
+						CSCICreateControl(CNT_LABEL, 15, 25, 160, 0, get_global_message(MSG_REPLACEWITH2));
 					int txt1 = CSCICreateControl(CNT_TEXTBOX, 15, 35, 160, 0, bufTemp);
 					int btnOk =
-					    CSCICreateControl(CNT_PUSHBUTTON | CNF_DEFAULT, 25, 50, 60, 10,
-					                      get_global_message(MSG_REPLACE));
+						CSCICreateControl(CNT_PUSHBUTTON | CNF_DEFAULT, 25, 50, 60, 10,
+							get_global_message(MSG_REPLACE));
 					int btnCancel =
-					    CSCICreateControl(CNT_PUSHBUTTON | CNF_CANCEL, 95, 50, 60, 10,
-					                      get_global_message(MSG_CANCEL));
+						CSCICreateControl(CNT_PUSHBUTTON | CNF_CANCEL, 95, 50, 60, 10,
+							get_global_message(MSG_CANCEL));
 
 					CSCIMessage cmes;
 					do {
@@ -413,7 +415,7 @@ int roomSelectorWindow(int currentRoom, int numRooms, int *roomNumbers, char **r
 	int handl = CSCIDrawWindow(boxleft, boxtop, wnd_width, wnd_height);
 	int ctrllist = CSCICreateControl(CNT_LISTBOX, 10, 40, 220, 100, nullptr);
 	int ctrlcancel =
-	    CSCICreateControl(CNT_PUSHBUTTON | CNF_CANCEL, 80, 145, 60, 10, "Cancel");
+		CSCICreateControl(CNT_PUSHBUTTON | CNF_CANCEL, 80, 145, 60, 10, "Cancel");
 
 	CSCISendControlMessage(ctrllist, CLB_CLEAR, 0, 0);    // clear the list box
 	for (int aa = 0; aa < numRooms; aa++) {
@@ -510,3 +512,5 @@ int quitdialog() {
 	strcpy(playbut, get_global_message(MSG_PLAYBUTTON));
 	return myscimessagebox(get_global_message(MSG_QUITDIALOG), quitbut, playbut);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/gui/mylabel.cpp b/engines/ags/engine/gui/mylabel.cpp
index ce173d589d..74bd80ab2a 100644
--- a/engines/ags/engine/gui/mylabel.cpp
+++ b/engines/ags/engine/gui/mylabel.cpp
@@ -29,6 +29,8 @@
 #include "gui/mylabel.h"
 #include "gui/guidialoginternaldefs.h"
 
+namespace AGS3 {
+
 using namespace Shared;
 
 extern GameSetup usetup;
@@ -64,3 +66,5 @@ int MyLabel::pressedon(int mousex, int mousey) {
 int MyLabel::processmessage(int mcode, int wParam, long lParam) {
 	return -1;                  // doesn't support messages
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/gui/mylistbox.cpp b/engines/ags/engine/gui/mylistbox.cpp
index 95a1f2d2ee..37d24a4dbe 100644
--- a/engines/ags/engine/gui/mylistbox.cpp
+++ b/engines/ags/engine/gui/mylistbox.cpp
@@ -30,6 +30,8 @@
 #include "gui/guidialoginternaldefs.h"
 #include "gui/mylistbox.h"
 
+namespace AGS3 {
+
 using AGS::Shared::Bitmap;
 
 extern GameSetup usetup;
@@ -112,7 +114,7 @@ int MyListBox::pressedon(int mousex, int mousey) {
 	if (mousex > x + wid - ARROWWIDTH) {
 		if ((mousey - y < hit / 2) & (topitem > 0))
 			topitem--;
-		else if ((mousey - y > hit / 2) & (topitem + numonscreen < items))
+		else if ((mousey - y > hit / 2) &(topitem + numonscreen < items))
 			topitem++;
 
 	} else {
@@ -122,7 +124,7 @@ int MyListBox::pressedon(int mousex, int mousey) {
 
 	}
 
-//    ags_domouse(DOMOUSE_DISABLE);
+	//    ags_domouse(DOMOUSE_DISABLE);
 	draw(get_gui_screen());
 	//  ags_domouse(DOMOUSE_ENABLE);
 	smcode = CM_SELCHANGE;
@@ -195,3 +197,5 @@ int MyListBox::processmessage(int mcode, int wParam, long lParam) {
 
 	return 0;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/gui/mypushbutton.cpp b/engines/ags/engine/gui/mypushbutton.cpp
index 8aa7ff69db..77e68a829b 100644
--- a/engines/ags/engine/gui/mypushbutton.cpp
+++ b/engines/ags/engine/gui/mypushbutton.cpp
@@ -33,6 +33,8 @@
 #include "platform/base/agsplatformdriver.h"
 #include "ac/timer.h"
 
+namespace AGS3 {
+
 using AGS::Shared::Bitmap;
 
 extern int windowbackgroundcolor, pushbuttondarkcolor;
@@ -109,3 +111,5 @@ int MyPushButton::pressedon(int mousex, int mousey) {
 int MyPushButton::processmessage(int mcode, int wParam, long lParam) {
 	return -1;                  // doesn't support messages
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/gui/mytextbox.cpp b/engines/ags/engine/gui/mytextbox.cpp
index fe545e917a..74e740bc84 100644
--- a/engines/ags/engine/gui/mytextbox.cpp
+++ b/engines/ags/engine/gui/mytextbox.cpp
@@ -27,6 +27,8 @@
 #include "gui/guidialoginternaldefs.h"
 #include "gfx/bitmap.h"
 
+namespace AGS3 {
+
 using AGS::Shared::Bitmap;
 
 extern GameSetup usetup;
@@ -90,3 +92,5 @@ int MyTextBox::processmessage(int mcode, int wParam, long lParam) {
 
 	return 0;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/gui/newcontrol.cpp b/engines/ags/engine/gui/newcontrol.cpp
index 80516ce6f5..cdc052d114 100644
--- a/engines/ags/engine/gui/newcontrol.cpp
+++ b/engines/ags/engine/gui/newcontrol.cpp
@@ -24,6 +24,8 @@
 #include "gui/guidialog.h"
 #include "gui/guidialoginternaldefs.h"
 
+namespace AGS3 {
+
 extern int topwindowhandle;
 
 NewControl::NewControl(int xx, int yy, int wi, int hi) {
@@ -51,7 +53,7 @@ int NewControl::mouseisinarea(int mousex, int mousey) {
 	if (topwindowhandle != wlevel)
 		return 0;
 
-	if ((mousex > x) & (mousex < x + wid) & (mousey > y) & (mousey < y + hit))
+	if ((mousex > x) &(mousex < x + wid) &(mousey > y) &(mousey < y + hit))
 		return 1;
 
 	return 0;
@@ -69,3 +71,5 @@ void NewControl::drawandmouse() {
 	draw(get_gui_screen());
 	//  ags_domouse(DOMOUSE_ENABLE);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/main/config.cpp b/engines/ags/engine/main/config.cpp
index 9a6c5e4936..58949bf10a 100644
--- a/engines/ags/engine/main/config.cpp
+++ b/engines/ags/engine/main/config.cpp
@@ -45,6 +45,7 @@
 #include "util/string_utils.h"
 #include "media/audio/audio_system.h"
 
+namespace AGS3 {
 
 using namespace AGS::Shared;
 using namespace AGS::Engine;
@@ -159,7 +160,7 @@ bool parse_legacy_frame_config(const String &scaling_option, String &filter_id,
 			filter_id = legacy_filters[i].CurrentName;
 			frame.ScaleDef = legacy_filters[i].Scaling == 0 ? kFrame_MaxRound : kFrame_IntScale;
 			frame.ScaleFactor = legacy_filters[i].Scaling >= 0 ? legacy_filters[i].Scaling :
-			                    scaling_option.Mid(legacy_filters[i].LegacyName.GetLength()).ToInt();
+				scaling_option.Mid(legacy_filters[i].LegacyName.GetLength()).ToInt();
 			return true;
 		}
 	}
@@ -197,17 +198,17 @@ int convert_fp_to_scaling(uint32_t scaling) {
 
 AlIDStr AlIDToChars(int al_id) {
 	if (al_id == 0)
-		return AlIDStr {{ 'N', 'O', 'N', 'E', '\0' }};
+		return AlIDStr{ { 'N', 'O', 'N', 'E', '\0' } };
 	else if (al_id == -1)
-		return AlIDStr {{ 'A', 'U', 'T', 'O', '\0' }};
+		return AlIDStr{ { 'A', 'U', 'T', 'O', '\0' } };
 	else
-		return AlIDStr {{
+		return AlIDStr{ {
 			static_cast<char>((al_id >> 24) & 0xFF),
 			static_cast<char>((al_id >> 16) & 0xFF),
 			static_cast<char>((al_id >> 8) & 0xFF),
 			static_cast<char>((al_id) & 0xFF),
 			'\0'
-		}};
+		} };
 }
 
 AlIDStr AlIDToChars(const String &s) {
@@ -364,8 +365,8 @@ void read_legacy_graphics_config(const ConfigTree &cfg) {
 			// AGS 3.2.1 and 3.3.0 aspect ratio preferences
 			if (!usetup.Screen.DisplayMode.Windowed) {
 				usetup.Screen.DisplayMode.ScreenSize.MatchDeviceRatio =
-				    (INIreadint(cfg, "misc", "sideborders") > 0 || INIreadint(cfg, "misc", "forceletterbox") > 0 ||
-				     INIreadint(cfg, "misc", "prefer_sideborders") > 0 || INIreadint(cfg, "misc", "prefer_letterbox") > 0);
+					(INIreadint(cfg, "misc", "sideborders") > 0 || INIreadint(cfg, "misc", "forceletterbox") > 0 ||
+						INIreadint(cfg, "misc", "prefer_sideborders") > 0 || INIreadint(cfg, "misc", "prefer_letterbox") > 0);
 			}
 		}
 
@@ -478,7 +479,7 @@ void apply_config(const ConfigTree &cfg) {
 		}
 
 		usetup.Screen.DisplayMode.ScreenSize.Size = Size(INIreadint(cfg, "graphics", "screen_width"),
-		        INIreadint(cfg, "graphics", "screen_height"));
+			INIreadint(cfg, "graphics", "screen_height"));
 		usetup.Screen.DisplayMode.ScreenSize.MatchDeviceRatio = INIreadint(cfg, "graphics", "match_device_ratio", 1) != 0;
 		// TODO: move to config overrides (replace values during config load)
 #if AGS_PLATFORM_OS_MACOS
@@ -609,3 +610,5 @@ void save_config_file() {
 	if (!cfg_file.IsEmpty())
 		IniUtil::Merge(cfg_file, cfg);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/main/engine.cpp b/engines/ags/engine/main/engine.cpp
index 89f3d3bf58..31cf7bca1a 100644
--- a/engines/ags/engine/main/engine.cpp
+++ b/engines/ags/engine/main/engine.cpp
@@ -79,6 +79,8 @@
 #include "util/misc.h"
 #include "util/path.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -1541,3 +1543,5 @@ const char *get_engine_version() {
 void engine_set_pre_init_callback(t_engine_pre_init_callback callback) {
 	engine_pre_init_callback = callback;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/main/engine_setup.cpp b/engines/ags/engine/main/engine_setup.cpp
index 22ae40663a..9168a24f7d 100644
--- a/engines/ags/engine/main/engine_setup.cpp
+++ b/engines/ags/engine/main/engine_setup.cpp
@@ -44,6 +44,8 @@
 #include "media/video/video.h"
 #include "platform/base/agsplatformdriver.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -131,7 +133,7 @@ void engine_init_resolution_settings(const Size game_size) {
 	usetup.textheight = getfontheight_outlined(0) + 1;
 
 	Debug::Printf(kDbgMsg_Info, "Game native resolution: %d x %d (%d bit)%s", game_size.Width, game_size.Height, game.color_depth * 8,
-	              game.IsLegacyLetterbox() ? " letterbox-by-design" : "");
+		game.IsLegacyLetterbox() ? " letterbox-by-design" : "");
 
 	convert_gui_to_game_resolution(loaded_game_file_version);
 	convert_objects_to_data_resolution(loaded_game_file_version);
@@ -268,12 +270,12 @@ void engine_post_gfxmode_mouse_setup(const DisplayMode &dm, const Size &init_des
 		Size cur_desktop;
 		if (get_desktop_resolution(&cur_desktop.Width, &cur_desktop.Height) == 0)
 			Mouse::SetSpeedUnit(Math::Max((float)cur_desktop.Width / (float)init_desktop.Width,
-			                              (float)cur_desktop.Height / (float)init_desktop.Height));
+			(float)cur_desktop.Height / (float)init_desktop.Height));
 	}
 
 	Mouse_EnableControl(usetup.mouse_ctrl_enabled);
 	Debug::Printf(kDbgMsg_Info, "Mouse control: %s, base: %f, speed: %f", Mouse::IsControlEnabled() ? "on" : "off",
-	              Mouse::GetSpeedUnit(), Mouse::GetSpeed());
+		Mouse::GetSpeedUnit(), Mouse::GetSpeed());
 
 	on_coordinates_scaling_changed();
 
@@ -340,3 +342,5 @@ void on_coordinates_scaling_changed() {
 	else
 		Mouse::SetMoveLimit(Rect(play.mboundx1, play.mboundy1, play.mboundx2, play.mboundy2));
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/main/game_file.cpp b/engines/ags/engine/main/game_file.cpp
index 857f80880a..a1590ca036 100644
--- a/engines/ags/engine/main/game_file.cpp
+++ b/engines/ags/engine/main/game_file.cpp
@@ -53,6 +53,8 @@
 #include "plugin/agsplugin.h"
 #include "script/script.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -88,9 +90,9 @@ String get_caps_list(const std::set<String> &caps) {
 HGameFileError game_file_first_open(MainGameSource &src) {
 	HGameFileError err = OpenMainGameFileFromDefaultAsset(src);
 	if (err ||
-	        err->Code() == kMGFErr_SignatureFailed ||
-	        err->Code() == kMGFErr_FormatVersionTooOld ||
-	        err->Code() == kMGFErr_FormatVersionNotSupported) {
+		err->Code() == kMGFErr_SignatureFailed ||
+		err->Code() == kMGFErr_FormatVersionTooOld ||
+		err->Code() == kMGFErr_FormatVersionNotSupported) {
 		// Log data description for debugging
 		Debug::Printf(kDbgMsg_Info, "Opened game data file: %s", src.Filename.GetCStr());
 		Debug::Printf(kDbgMsg_Info, "Game data version: %d", src.DataVersion);
@@ -117,7 +119,7 @@ void PreReadSaveFileInfo(Stream *in, GameDataVersion data_ver) {
 	AlignedStream align_s(in, Common::kAligned_Read);
 	game.ReadFromFile(&align_s);
 	// Discard game messages we do not need here
-	delete [] game.load_messages;
+	delete[] game.load_messages;
 	game.load_messages = nullptr;
 	game.read_savegame_info(in, data_ver);
 }
@@ -153,5 +155,7 @@ HError load_game_file() {
 
 void display_game_file_error(HError err) {
 	platform->DisplayAlert("Loading game failed with error:\n%s.\n\nThe game files may be incomplete, corrupt or from unsupported version of AGS.",
-	                       err->FullMessage().GetCStr());
+		err->FullMessage().GetCStr());
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/main/game_run.cpp b/engines/ags/engine/main/game_run.cpp
index 1532bf611f..63816c8cbe 100644
--- a/engines/ags/engine/main/game_run.cpp
+++ b/engines/ags/engine/main/game_run.cpp
@@ -66,6 +66,8 @@
 #include "ac/timer.h"
 #include "ac/keycode.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern AnimatingGUIButton animbuts[MAX_ANIMATING_BUTTONS];
@@ -128,7 +130,7 @@ static void ProperExit() {
 static void game_loop_check_problems_at_start() {
 	if ((in_enters_screen != 0) & (displayed_room == starting_room))
 		quit("!A text script run in the Player Enters Screen event caused the\n"
-		     "screen to be updated. If you need to use Wait(), do so in After Fadein");
+			"screen to be updated. If you need to use Wait(), do so in After Fadein");
 	if ((in_enters_screen != 0) && (done_es_error == 0)) {
 		debug_script_warn("Wait() was used in Player Enters Screen - use Enters Screen After Fadein instead");
 		done_es_error = 1;
@@ -251,7 +253,7 @@ static void check_mouse_controls() {
 		} else if (is_text_overlay > 0) {
 			if (play.cant_skip_speech & SKIP_MOUSECLICK)
 				remove_screen_overlay(OVER_TEXTMSG);
-		} else if (!IsInterfaceEnabled()) ; // blocking cutscene, ignore mouse
+		} else if (!IsInterfaceEnabled()); // blocking cutscene, ignore mouse
 		else if (pl_run_plugin_hooks(AGSE_MOUSECLICK, mbut + 1)) {
 			// plugin took the click
 			debug_script_log("Plugin handled mouse button %d", mbut + 1);
@@ -397,8 +399,8 @@ static void check_keyboard_controls() {
 		if (IsGamePaused() == 0) {
 			// check if it requires a specific keypress
 			if ((play.skip_speech_specific_key > 0) &&
-			        (kgn != play.skip_speech_specific_key)) { }
-			else
+				(kgn != play.skip_speech_specific_key)) {
+			} else
 				remove_screen_overlay(OVER_TEXTMSG);
 		}
 
@@ -425,22 +427,22 @@ static void check_keyboard_controls() {
 		int ff;
 		// MACPORT FIX 9/6/5: added last %s
 		sprintf(infobuf, "In room %d %s[Player at %d, %d (view %d, loop %d, frame %d)%s%s%s",
-		        displayed_room, (noWalkBehindsAtAll ? "(has no walk-behinds)" : ""), playerchar->x, playerchar->y,
-		        playerchar->view + 1, playerchar->loop, playerchar->frame,
-		        (IsGamePaused() == 0) ? "" : "[Game paused.",
-		        (play.ground_level_areas_disabled == 0) ? "" : "[Ground areas disabled.",
-		        (IsInterfaceEnabled() == 0) ? "[Game in Wait state" : "");
+			displayed_room, (noWalkBehindsAtAll ? "(has no walk-behinds)" : ""), playerchar->x, playerchar->y,
+			playerchar->view + 1, playerchar->loop, playerchar->frame,
+			(IsGamePaused() == 0) ? "" : "[Game paused.",
+			(play.ground_level_areas_disabled == 0) ? "" : "[Ground areas disabled.",
+			(IsInterfaceEnabled() == 0) ? "[Game in Wait state" : "");
 		for (ff = 0; ff < croom->numobj; ff++) {
 			if (ff >= 8) break; // buffer not big enough for more than 7
 			sprintf(&infobuf[strlen(infobuf)],
-			        "[Object %d: (%d,%d) size (%d x %d) on:%d moving:%s animating:%d slot:%d trnsp:%d clkble:%d",
-			        ff, objs[ff].x, objs[ff].y,
-			        (spriteset[objs[ff].num] != nullptr) ? game.SpriteInfos[objs[ff].num].Width : 0,
-			        (spriteset[objs[ff].num] != nullptr) ? game.SpriteInfos[objs[ff].num].Height : 0,
-			        objs[ff].on,
-			        (objs[ff].moving > 0) ? "yes" : "no", objs[ff].cycling,
-			        objs[ff].num, objs[ff].transparent,
-			        ((objs[ff].flags & OBJF_NOINTERACT) != 0) ? 0 : 1);
+				"[Object %d: (%d,%d) size (%d x %d) on:%d moving:%s animating:%d slot:%d trnsp:%d clkble:%d",
+				ff, objs[ff].x, objs[ff].y,
+				(spriteset[objs[ff].num] != nullptr) ? game.SpriteInfos[objs[ff].num].Width : 0,
+				(spriteset[objs[ff].num] != nullptr) ? game.SpriteInfos[objs[ff].num].Height : 0,
+				objs[ff].on,
+				(objs[ff].moving > 0) ? "yes" : "no", objs[ff].cycling,
+				objs[ff].num, objs[ff].transparent,
+				((objs[ff].flags & OBJF_NOINTERACT) != 0) ? 0 : 1);
 		}
 		Display(infobuf);
 		int chd = game.playercharacter;
@@ -454,12 +456,12 @@ static void check_keyboard_controls() {
 			}
 			chd = ff;
 			sprintf(&bigbuffer[strlen(bigbuffer)],
-			        "%s (view/loop/frm:%d,%d,%d  x/y/z:%d,%d,%d  idleview:%d,time:%d,left:%d walk:%d anim:%d follow:%d flags:%X wait:%d zoom:%d)[",
-			        game.chars[chd].scrname, game.chars[chd].view + 1, game.chars[chd].loop, game.chars[chd].frame,
-			        game.chars[chd].x, game.chars[chd].y, game.chars[chd].z,
-			        game.chars[chd].idleview, game.chars[chd].idletime, game.chars[chd].idleleft,
-			        game.chars[chd].walking, game.chars[chd].animating, game.chars[chd].following,
-			        game.chars[chd].flags, game.chars[chd].wait, charextra[chd].zoom);
+				"%s (view/loop/frm:%d,%d,%d  x/y/z:%d,%d,%d  idleview:%d,time:%d,left:%d walk:%d anim:%d follow:%d flags:%X wait:%d zoom:%d)[",
+				game.chars[chd].scrname, game.chars[chd].view + 1, game.chars[chd].loop, game.chars[chd].frame,
+				game.chars[chd].x, game.chars[chd].y, game.chars[chd].z,
+				game.chars[chd].idleview, game.chars[chd].idletime, game.chars[chd].idleleft,
+				game.chars[chd].walking, game.chars[chd].animating, game.chars[chd].following,
+				game.chars[chd].flags, game.chars[chd].wait, charextra[chd].zoom);
 		}
 		Display(bigbuffer);
 
@@ -496,7 +498,7 @@ static void check_keyboard_controls() {
 	// pressed, but exclude control characters (<32) and
 	// extended keys (eg. up/down arrow; 256+)
 	if ((((kgn >= 32) && (kgn <= 255) && (kgn != '[')) || (kgn == eAGSKeyCodeReturn) || (kgn == eAGSKeyCodeBackspace))
-	        && !all_buttons_disabled) {
+		&& !all_buttons_disabled) {
 		for (int guiIndex = 0; guiIndex < game.numgui; guiIndex++) {
 			auto &gui = guis[guiIndex];
 
@@ -552,13 +554,13 @@ static void check_controls() {
 
 static void check_room_edges(int numevents_was) {
 	if ((IsInterfaceEnabled()) && (IsGamePaused() == 0) &&
-	        (in_new_room == 0) && (new_room_was == 0)) {
+		(in_new_room == 0) && (new_room_was == 0)) {
 		// Only allow walking off edges if not in wait mode, and
 		// if not in Player Enters Screen (allow walking in from off-screen)
-		int edgesActivated[4] = {0, 0, 0, 0};
+		int edgesActivated[4] = { 0, 0, 0, 0 };
 		// Only do it if nothing else has happened (eg. mouseclick)
 		if ((numevents == numevents_was) &&
-		        ((play.ground_level_areas_disabled & GLED_INTERACTION) == 0)) {
+			((play.ground_level_areas_disabled & GLED_INTERACTION) == 0)) {
 
 			if (playerchar->x <= thisroom.Edges.Left)
 				edgesActivated[0] = 1;
@@ -602,7 +604,7 @@ static void game_loop_check_controls(bool checkControls) {
 }
 
 static void game_loop_do_update() {
-	if (debug_flags & DBG_NOUPDATE) ;
+	if (debug_flags & DBG_NOUPDATE);
 	else if (game_paused == 0) update_stuff();
 }
 
@@ -641,7 +643,7 @@ static void game_loop_do_render_and_check_mouse(IDriverDependantBitmap *extraBit
 			int offsety = cam->GetRect().Top;
 
 			if (((mwasatx != mousex) || (mwasaty != mousey) ||
-			        (offsetxWas != offsetx) || (offsetyWas != offsety))) {
+				(offsetxWas != offsetx) || (offsetyWas != offsety))) {
 				// mouse moves over hotspot
 				if (__GetLocationType(game_to_data_coord(mousex), game_to_data_coord(mousey), 1) == LOCTYPE_HOTSPOT) {
 					int onhs = getloctype_index;
@@ -675,7 +677,7 @@ static void game_loop_update_events() {
 
 static void game_loop_update_background_animation() {
 	if (play.bg_anim_delay > 0) play.bg_anim_delay--;
-	else if (play.bg_frame_locked) ;
+	else if (play.bg_frame_locked);
 	else {
 		play.bg_anim_delay = play.anim_background_speed;
 		play.bg_frame++;
@@ -815,8 +817,8 @@ static void UpdateMouseOverLocation() {
 	GetLocationName(game_to_data_coord(mousex), game_to_data_coord(mousey), tempo);
 
 	if ((play.get_loc_name_save_cursor >= 0) &&
-	        (play.get_loc_name_save_cursor != play.get_loc_name_last_time) &&
-	        (mouse_on_iface < 0) && (ifacepopped < 0)) {
+		(play.get_loc_name_save_cursor != play.get_loc_name_last_time) &&
+		(mouse_on_iface < 0) && (ifacepopped < 0)) {
 		// we have saved the cursor, but the mouse location has changed
 		// and it's time to restore it
 		play.get_loc_name_save_cursor = -1;
@@ -882,9 +884,9 @@ static int UpdateWaitMode() {
 	user_disabled_for = 0;
 
 	switch (was_disabled_for) {
-	// case FOR_ANIMATION:
-	//     run_animation((FullAnimation*)user_disabled_data2,user_disabled_data3);
-	//     break;
+		// case FOR_ANIMATION:
+		//     run_animation((FullAnimation*)user_disabled_data2,user_disabled_data3);
+		//     break;
 	case FOR_EXITLOOP:
 		return -1;
 	case FOR_SCRIPT:
@@ -921,7 +923,7 @@ static void SetupLoopParameters(int untilwhat, const void *udata) {
 	// Only change the mouse cursor if it hasn't been specifically changed first
 	// (or if it's speech, always change it)
 	if (((cur_cursor == cur_mode) || (untilwhat == UNTIL_NOOVERLAY)) &&
-	        (cur_mode != CURS_WAIT))
+		(cur_mode != CURS_WAIT))
 		set_mouse_cursor(CURS_WAIT);
 
 	restrict_until = untilwhat;
@@ -1011,3 +1013,5 @@ void update_polled_stuff_if_runtime() {
 	if (editor_debugging_initialized)
 		check_for_messages_from_editor();
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/main/game_start.cpp b/engines/ags/engine/main/game_start.cpp
index aad1e43195..244f007a35 100644
--- a/engines/ags/engine/main/game_start.cpp
+++ b/engines/ags/engine/main/game_start.cpp
@@ -44,6 +44,8 @@
 #include "media/audio/audio_system.h"
 #include "ac/timer.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -155,3 +157,5 @@ void initialize_start_and_play_game(int override_start_room, const char *loadSav
 		quit((char *)gfxException._message);
 	}
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/main/graphics_mode.cpp b/engines/ags/engine/main/graphics_mode.cpp
index 986b332414..2700ea1986 100644
--- a/engines/ags/engine/main/graphics_mode.cpp
+++ b/engines/ags/engine/main/graphics_mode.cpp
@@ -40,6 +40,8 @@
 #include "main/main_allegro.h"
 #include "platform/base/agsplatformdriver.h"
 
+namespace AGS3 {
+
 // Don't try to figure out the window size on the mac because the port resizes itself.
 #if AGS_PLATFORM_OS_MACOS || defined(ALLEGRO_SDL2) || AGS_PLATFORM_OS_IOS || AGS_PLATFORM_OS_ANDROID
 #define USE_SIMPLE_GFX_INIT
@@ -129,7 +131,7 @@ bool graphics_mode_set_filter_any(const GfxFilterSetup &setup) {
 		if (def_filter.CompareNoCase(setup.ID) == 0)
 			return false;
 		Debug::Printf(kDbgMsg_Error, "Failed to apply gfx filter: %s; will try to use factory default filter '%s' instead",
-		              setup.UserRequest.GetCStr(), def_filter.GetCStr());
+			setup.UserRequest.GetCStr(), def_filter.GetCStr());
 		if (!graphics_mode_set_filter(def_filter))
 			return false;
 	}
@@ -138,7 +140,7 @@ bool graphics_mode_set_filter_any(const GfxFilterSetup &setup) {
 }
 
 bool find_nearest_supported_mode(const IGfxModeList &modes, const Size &wanted_size, const int color_depth,
-                                 const Size *ratio_reference, const Size *upper_bound, DisplayMode &dm, int *mode_index) {
+	const Size *ratio_reference, const Size *upper_bound, DisplayMode &dm, int *mode_index) {
 	uint32_t wanted_ratio = 0;
 	if (ratio_reference && !ratio_reference->IsNull()) {
 		wanted_ratio = (ratio_reference->Height << kShift) / ratio_reference->Width;
@@ -181,8 +183,8 @@ bool find_nearest_supported_mode(const IGfxModeList &modes, const Size &wanted_s
 		bool same_diff_h_higher = (diff_h == nearest_height_diff && nearest_height < wanted_size.Height);
 
 		if (nearest_width == 0 ||
-		        ((diff_w < nearest_width_diff || same_diff_w_higher) && diff_h <= nearest_height_diff) ||
-		        ((diff_h < nearest_height_diff || same_diff_h_higher) && diff_w <= nearest_width_diff)) {
+			((diff_w < nearest_width_diff || same_diff_w_higher) && diff_h <= nearest_height_diff) ||
+			((diff_h < nearest_height_diff || same_diff_h_higher) && diff_w <= nearest_width_diff)) {
 			nearest_width = mode.Width;
 			nearest_width_diff = diff_w;
 			nearest_height = mode.Height;
@@ -212,7 +214,7 @@ Size set_game_frame_after_screen_size(const Size &game_size, const Size screen_s
 		int scale;
 		if (setup.ScaleDef == kFrame_MaxRound)
 			scale = Math::Min((screen_size.Width / game_size.Width) << kShift,
-			                  (screen_size.Height / game_size.Height) << kShift);
+			(screen_size.Height / game_size.Height) << kShift);
 		else
 			scale = convert_scaling_to_fp(setup.ScaleFactor);
 
@@ -267,7 +269,7 @@ bool try_init_compatible_mode(const DisplayMode &dm, const bool match_device_rat
 	const Size &screen_size = Size(dm.Width, dm.Height);
 	// Find nearest compatible mode and init that
 	Debug::Printf("Attempting to find nearest supported resolution for screen size %d x %d (%d-bit) %s",
-	              dm.Width, dm.Height, dm.ColorDepth, dm.Windowed ? "windowed" : "fullscreen");
+		dm.Width, dm.Height, dm.ColorDepth, dm.Windowed ? "windowed" : "fullscreen");
 	const Size device_size = get_max_display_size(dm.Windowed);
 	if (dm.Windowed)
 		Debug::Printf("Maximal allowed window size: %d x %d", device_size.Width, device_size.Height);
@@ -314,12 +316,12 @@ bool try_init_compatible_mode(const DisplayMode &dm, const bool match_device_rat
 
 // Try to find and initialize compatible display mode as close to given setup as possible
 bool try_init_mode_using_setup(const Size &game_size, const DisplayModeSetup &dm_setup,
-                               const int col_depth, const GameFrameSetup &frame_setup,
-                               const GfxFilterSetup &filter_setup) {
+	const int col_depth, const GameFrameSetup &frame_setup,
+	const GfxFilterSetup &filter_setup) {
 	// We determine the requested size of the screen using setup options
 	const Size screen_size = precalc_screen_size(game_size, dm_setup, frame_setup);
 	DisplayMode dm(GraphicResolution(screen_size.Width, screen_size.Height, col_depth),
-	               dm_setup.Windowed, dm_setup.RefreshRate, dm_setup.VSync);
+		dm_setup.Windowed, dm_setup.RefreshRate, dm_setup.VSync);
 	if (!try_init_compatible_mode(dm, dm_setup.ScreenSize.SizeDef == kScreenDef_Explicit ? false : dm_setup.ScreenSize.MatchDeviceRatio))
 		return false;
 
@@ -363,12 +365,12 @@ void log_out_driver_modes(const int color_depth) {
 // Create requested graphics driver and try to find and initialize compatible display mode as close to user setup as possible;
 // if the given setup fails, gets default setup for the opposite type of mode (fullscreen/windowed) and tries that instead.
 bool create_gfx_driver_and_init_mode_any(const String &gfx_driver_id, const Size &game_size, const DisplayModeSetup &dm_setup,
-        const ColorDepthOption &color_depth, const GameFrameSetup &frame_setup, const GfxFilterSetup &filter_setup) {
+	const ColorDepthOption &color_depth, const GameFrameSetup &frame_setup, const GfxFilterSetup &filter_setup) {
 	if (!graphics_mode_create_renderer(gfx_driver_id))
 		return false;
 
 	const int use_col_depth =
-	    color_depth.Forced ? color_depth.Bits : gfxDriver->GetDisplayDepthForNativeDepth(color_depth.Bits);
+		color_depth.Forced ? color_depth.Bits : gfxDriver->GetDisplayDepthForNativeDepth(color_depth.Bits);
 	// Log out supported driver modes
 	log_out_driver_modes(use_col_depth);
 
@@ -386,11 +388,11 @@ bool create_gfx_driver_and_init_mode_any(const String &gfx_driver_id, const Size
 }
 
 bool simple_create_gfx_driver_and_init_mode(const String &gfx_driver_id,
-        const Size &game_size,
-        const DisplayModeSetup &dm_setup,
-        const ColorDepthOption &color_depth,
-        const GameFrameSetup &frame_setup,
-        const GfxFilterSetup &filter_setup) {
+	const Size &game_size,
+	const DisplayModeSetup &dm_setup,
+	const ColorDepthOption &color_depth,
+	const GameFrameSetup &frame_setup,
+	const GfxFilterSetup &filter_setup) {
 	if (!graphics_mode_create_renderer(gfx_driver_id)) {
 		return false;
 	}
@@ -398,7 +400,7 @@ bool simple_create_gfx_driver_and_init_mode(const String &gfx_driver_id,
 	const int col_depth = gfxDriver->GetDisplayDepthForNativeDepth(color_depth.Bits);
 
 	DisplayMode dm(GraphicResolution(game_size.Width, game_size.Height, col_depth),
-	               dm_setup.Windowed, dm_setup.RefreshRate, dm_setup.VSync);
+		dm_setup.Windowed, dm_setup.RefreshRate, dm_setup.VSync);
 
 	if (!graphics_mode_set_dm(dm)) {
 		return false;
@@ -427,16 +429,16 @@ void display_gfx_mode_error(const Size &game_size, const ScreenSetup &setup, con
 	Size wanted_screen;
 	if (scsz.SizeDef == kScreenDef_Explicit)
 		main_error.Format("There was a problem initializing graphics mode %d x %d (%d-bit), or finding nearest compatible mode, with game size %d x %d and filter '%s'.",
-		                  scsz.Size.Width, scsz.Size.Height, color_depth, game_size.Width, game_size.Height, filter ? filter->GetInfo().Id.GetCStr() : "Undefined");
+			scsz.Size.Width, scsz.Size.Height, color_depth, game_size.Width, game_size.Height, filter ? filter->GetInfo().Id.GetCStr() : "Undefined");
 	else
 		main_error.Format("There was a problem finding and/or creating valid graphics mode for game size %d x %d (%d-bit) and requested filter '%s'.",
-		                  game_size.Width, game_size.Height, color_depth, setup.Filter.UserRequest.IsEmpty() ? "Undefined" : setup.Filter.UserRequest.GetCStr());
+			game_size.Width, game_size.Height, color_depth, setup.Filter.UserRequest.IsEmpty() ? "Undefined" : setup.Filter.UserRequest.GetCStr());
 
 	platform->DisplayAlert("%s\n"
-	                       "(Problem: '%s')\n"
-	                       "Try to correct the problem, or seek help from the AGS homepage."
-	                       "%s",
-	                       main_error.GetCStr(), get_allegro_error(), platform->GetGraphicsTroubleshootingText());
+		"(Problem: '%s')\n"
+		"Try to correct the problem, or seek help from the AGS homepage."
+		"%s",
+		main_error.GetCStr(), get_allegro_error(), platform->GetGraphicsTroubleshootingText());
 }
 
 bool graphics_mode_init_any(const Size game_size, const ScreenSetup &setup, const ColorDepthOption &color_depth) {
@@ -453,10 +455,10 @@ bool graphics_mode_init_any(const Size game_size, const ScreenSetup &setup, cons
 	GameFrameSetup gameframe = setup.DisplayMode.Windowed ? setup.WinGameFrame : setup.FsGameFrame;
 	const String scale_option = make_scaling_option(gameframe);
 	Debug::Printf(kDbgMsg_Info, "Graphic settings: driver: %s, windowed: %s, screen def: %s, screen size: %d x %d, match device ratio: %s, game scale: %s",
-	              setup.DriverID.GetCStr(),
-	              setup.DisplayMode.Windowed ? "yes" : "no", screen_sz_def_options[scsz.SizeDef],
-	              scsz.Size.Width, scsz.Size.Height,
-	              ignore_device_ratio ? "ignore" : (scsz.MatchDeviceRatio ? "yes" : "no"), scale_option.GetCStr());
+		setup.DriverID.GetCStr(),
+		setup.DisplayMode.Windowed ? "yes" : "no", screen_sz_def_options[scsz.SizeDef],
+		scsz.Size.Width, scsz.Size.Height,
+		ignore_device_ratio ? "ignore" : (scsz.MatchDeviceRatio ? "yes" : "no"), scale_option.GetCStr());
 
 	// Prepare the list of available gfx factories, having the one requested by user at first place
 	// TODO: make factory & driver IDs case-insensitive!
@@ -476,11 +478,11 @@ bool graphics_mode_init_any(const Size game_size, const ScreenSetup &setup, cons
 	for (StringV::const_iterator it = ids.begin(); it != ids.end(); ++it) {
 		result =
 #ifdef USE_SIMPLE_GFX_INIT
-		    simple_create_gfx_driver_and_init_mode
+			simple_create_gfx_driver_and_init_mode
 #else
-		    create_gfx_driver_and_init_mode_any
+			create_gfx_driver_and_init_mode_any
 #endif
-		    (*it, game_size, setup.DisplayMode, color_depth, gameframe, setup.Filter);
+			(*it, game_size, setup.DisplayMode, color_depth, gameframe, setup.Filter);
 
 		if (result)
 			break;
@@ -518,17 +520,17 @@ bool graphics_mode_create_renderer(const String &driver_id) {
 }
 
 bool graphics_mode_set_dm_any(const Size &game_size, const DisplayModeSetup &dm_setup,
-                              const ColorDepthOption &color_depth, const GameFrameSetup &frame_setup) {
+	const ColorDepthOption &color_depth, const GameFrameSetup &frame_setup) {
 	// We determine the requested size of the screen using setup options
 	const Size screen_size = precalc_screen_size(game_size, dm_setup, frame_setup);
 	DisplayMode dm(GraphicResolution(screen_size.Width, screen_size.Height, color_depth.Bits),
-	               dm_setup.Windowed, dm_setup.RefreshRate, dm_setup.VSync);
+		dm_setup.Windowed, dm_setup.RefreshRate, dm_setup.VSync);
 	return try_init_compatible_mode(dm, dm_setup.ScreenSize.MatchDeviceRatio);
 }
 
 bool graphics_mode_set_dm(const DisplayMode &dm) {
 	Debug::Printf("Attempt to switch gfx mode to %d x %d (%d-bit) %s",
-	              dm.Width, dm.Height, dm.ColorDepth, dm.Windowed ? "windowed" : "fullscreen");
+		dm.Width, dm.Height, dm.ColorDepth, dm.Windowed ? "windowed" : "fullscreen");
 
 	// Tell Allegro new default bitmap color depth (must be done before set_gfx_mode)
 	// TODO: this is also done inside ALSoftwareGraphicsDriver implementation; can remove one?
@@ -549,7 +551,7 @@ bool graphics_mode_set_dm(const DisplayMode &dm) {
 	else
 		SavedFullscreenSetting.Dm = rdm;
 	Debug::Printf("Succeeded. Using gfx mode %d x %d (%d-bit) %s",
-	              rdm.Width, rdm.Height, rdm.ColorDepth, rdm.Windowed ? "windowed" : "fullscreen");
+		rdm.Width, rdm.Height, rdm.ColorDepth, rdm.Windowed ? "windowed" : "fullscreen");
 	return true;
 }
 
@@ -565,14 +567,14 @@ bool graphics_mode_update_render_frame() {
 
 	if (!gfxDriver->SetRenderFrame(render_frame)) {
 		Debug::Printf(kDbgMsg_Error, "Failed to set render frame (%d, %d, %d, %d : %d x %d). Error: %s",
-		              render_frame.Left, render_frame.Top, render_frame.Right, render_frame.Bottom,
-		              render_frame.GetWidth(), render_frame.GetHeight(), get_allegro_error());
+			render_frame.Left, render_frame.Top, render_frame.Right, render_frame.Bottom,
+			render_frame.GetWidth(), render_frame.GetHeight(), get_allegro_error());
 		return false;
 	}
 
 	Rect dst_rect = gfxDriver->GetRenderDestination();
 	Debug::Printf("Render frame set, render dest (%d, %d, %d, %d : %d x %d)",
-	              dst_rect.Left, dst_rect.Top, dst_rect.Right, dst_rect.Bottom, dst_rect.GetWidth(), dst_rect.GetHeight());
+		dst_rect.Left, dst_rect.Top, dst_rect.Right, dst_rect.Bottom, dst_rect.GetWidth(), dst_rect.GetHeight());
 	// init game scaling transformation
 	GameScaling.Init(native_size, gfxDriver->GetRenderDestination());
 	return true;
@@ -615,9 +617,9 @@ bool graphics_mode_set_filter(const String &filter_id) {
 		Debug::Printf(kDbgMsg_Error, "Unable to set graphics filter '%s'. Error: %s", filter_id.GetCStr(), filter_error.GetCStr());
 		return false;
 	}
-	Rect filter_rect  = filter->GetDestination();
+	Rect filter_rect = filter->GetDestination();
 	Debug::Printf("Graphics filter set: '%s', filter dest (%d, %d, %d, %d : %d x %d)", filter->GetInfo().Id.GetCStr(),
-	              filter_rect.Left, filter_rect.Top, filter_rect.Right, filter_rect.Bottom, filter_rect.GetWidth(), filter_rect.GetHeight());
+		filter_rect.Left, filter_rect.Top, filter_rect.Right, filter_rect.Bottom, filter_rect.GetWidth(), filter_rect.GetHeight());
 	return true;
 }
 
@@ -630,3 +632,5 @@ void graphics_mode_shutdown() {
 	// Tell Allegro that we are no longer in graphics mode
 	set_gfx_mode(GFX_TEXT, 0, 0, 0, 0);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/main/main.cpp b/engines/ags/engine/main/main.cpp
index d41abba506..91f12195fc 100644
--- a/engines/ags/engine/main/main.cpp
+++ b/engines/ags/engine/main/main.cpp
@@ -63,6 +63,8 @@
 #define USE_CUSTOM_EXCEPTION_HANDLER
 #endif
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -164,12 +166,12 @@ void main_init(int argc, char *argv[]) {
 
 String get_engine_string() {
 	return String::FromFormat("Adventure Game Studio v%s Interpreter\n"
-	                          "Copyright (c) 1999-2011 Chris Jones and " ACI_COPYRIGHT_YEARS " others\n"
+		"Copyright (c) 1999-2011 Chris Jones and " ACI_COPYRIGHT_YEARS " others\n"
 #ifdef BUILD_STR
-	                          "ACI version %s (Build: %s)\n",
-	                          EngineVersion.ShortString.GetCStr(), EngineVersion.LongString.GetCStr(), EngineVersion.BuildInfo.GetCStr());
+		"ACI version %s (Build: %s)\n",
+		EngineVersion.ShortString.GetCStr(), EngineVersion.LongString.GetCStr(), EngineVersion.BuildInfo.GetCStr());
 #else
-	                          "ACI version %s\n", EngineVersion.ShortString.GetCStr(), EngineVersion.LongString.GetCStr());
+		"ACI version %s\n", EngineVersion.ShortString.GetCStr(), EngineVersion.LongString.GetCStr());
 #endif
 }
 
@@ -178,67 +180,67 @@ extern char return_to_room[150];
 
 void main_print_help() {
 	platform->WriteStdOut(
-	    "Usage: ags [OPTIONS] [GAMEFILE or DIRECTORY]\n\n"
-	    //--------------------------------------------------------------------------------|
-	    "Options:\n"
+		"Usage: ags [OPTIONS] [GAMEFILE or DIRECTORY]\n\n"
+		//--------------------------------------------------------------------------------|
+		"Options:\n"
 #if AGS_PLATFORM_OS_WINDOWS
-	    "  --console-attach             Write output to the parent process's console\n"
+		"  --console-attach             Write output to the parent process's console\n"
 #endif
-	    "  --fps                        Display fps counter\n"
-	    "  --fullscreen                 Force display mode to fullscreen\n"
-	    "  --gfxdriver <id>             Request graphics driver. Available options:\n"
+		"  --fps                        Display fps counter\n"
+		"  --fullscreen                 Force display mode to fullscreen\n"
+		"  --gfxdriver <id>             Request graphics driver. Available options:\n"
 #if AGS_PLATFORM_OS_WINDOWS
-	    "                                 d3d9, ogl, software\n"
+		"                                 d3d9, ogl, software\n"
 #else
-	    "                                 ogl, software\n"
+		"                                 ogl, software\n"
 #endif
-	    "  --gfxfilter FILTER [SCALING]\n"
-	    "                               Request graphics filter. Available options:\n"
-	    "                                 hqx, linear, none, stdscale\n"
-	    "                                 (support differs between graphic drivers);\n"
-	    "                                 scaling is specified by integer number\n"
-	    "  --help                       Print this help message and stop\n"
-	    "  --log-OUTPUT=GROUP[:LEVEL][,GROUP[:LEVEL]][,...]\n"
-	    "  --log-OUTPUT=+GROUPLIST[:LEVEL]\n"
-	    "                               Setup logging to the chosen OUTPUT with given\n"
-	    "                               log groups and verbosity levels. Groups may\n"
-	    "                               be also defined by a LIST of one-letter IDs,\n"
-	    "                               preceded by '+', e.g. +ABCD:LEVEL. Verbosity may\n"
-	    "                               be also defined by a numberic ID.\n"
-	    "                               OUTPUTs are\n"
-	    "                                 stdout, file, console\n"
-	    "                               (where \"console\" is internal engine's console)\n"
-	    "                               GROUPs are:\n"
-	    "                                 all, main (m), game (g), manobj (o),\n"
-	    "                                 script (s), sprcache (c)\n"
-	    "                               LEVELs are:\n"
-	    "                                 all, alert (1), fatal (2), error (3), warn (4),\n"
-	    "                                 info (5), debug (6)\n"
-	    "                               Examples:\n"
-	    "                                 --log-stdout=+mgs:debug\n"
-	    "                                 --log-file=all:warn\n"
-	    "  --log-file-path=PATH         Define custom path for the log file\n"
-	    //--------------------------------------------------------------------------------|
+		"  --gfxfilter FILTER [SCALING]\n"
+		"                               Request graphics filter. Available options:\n"
+		"                                 hqx, linear, none, stdscale\n"
+		"                                 (support differs between graphic drivers);\n"
+		"                                 scaling is specified by integer number\n"
+		"  --help                       Print this help message and stop\n"
+		"  --log-OUTPUT=GROUP[:LEVEL][,GROUP[:LEVEL]][,...]\n"
+		"  --log-OUTPUT=+GROUPLIST[:LEVEL]\n"
+		"                               Setup logging to the chosen OUTPUT with given\n"
+		"                               log groups and verbosity levels. Groups may\n"
+		"                               be also defined by a LIST of one-letter IDs,\n"
+		"                               preceded by '+', e.g. +ABCD:LEVEL. Verbosity may\n"
+		"                               be also defined by a numberic ID.\n"
+		"                               OUTPUTs are\n"
+		"                                 stdout, file, console\n"
+		"                               (where \"console\" is internal engine's console)\n"
+		"                               GROUPs are:\n"
+		"                                 all, main (m), game (g), manobj (o),\n"
+		"                                 script (s), sprcache (c)\n"
+		"                               LEVELs are:\n"
+		"                                 all, alert (1), fatal (2), error (3), warn (4),\n"
+		"                                 info (5), debug (6)\n"
+		"                               Examples:\n"
+		"                                 --log-stdout=+mgs:debug\n"
+		"                                 --log-file=all:warn\n"
+		"  --log-file-path=PATH         Define custom path for the log file\n"
+		//--------------------------------------------------------------------------------|
 #if AGS_PLATFORM_OS_WINDOWS
-	    "  --no-message-box             Disable reporting of alerts to message boxes\n"
-	    "  --setup                      Run setup application\n"
+		"  --no-message-box             Disable reporting of alerts to message boxes\n"
+		"  --setup                      Run setup application\n"
 #endif
-	    "  --tell                       Print various information concerning engine\n"
-	    "                                 and the game; for selected output use:\n"
-	    "  --tell-config                Print contents of merged game config\n"
-	    "  --tell-configpath            Print paths to available config files\n"
-	    "  --tell-data                  Print information on game data and its location\n"
-	    "  --tell-engine                Print engine name and version\n"
-	    "  --tell-graphicdriver         Print list of supported graphic drivers\n"
-	    "\n"
-	    "  --version                    Print engine's version and stop\n"
-	    "  --windowed                   Force display mode to windowed\n"
-	    "\n"
-	    "Gamefile options:\n"
-	    "  /dir/path/game/              Launch the game in specified directory\n"
-	    "  /dir/path/game/penguin.exe   Launch penguin.exe\n"
-	    "  [nothing]                    Launch the game in the current directory\n"
-	    //--------------------------------------------------------------------------------|
+		"  --tell                       Print various information concerning engine\n"
+		"                                 and the game; for selected output use:\n"
+		"  --tell-config                Print contents of merged game config\n"
+		"  --tell-configpath            Print paths to available config files\n"
+		"  --tell-data                  Print information on game data and its location\n"
+		"  --tell-engine                Print engine name and version\n"
+		"  --tell-graphicdriver         Print list of supported graphic drivers\n"
+		"\n"
+		"  --version                    Print engine's version and stop\n"
+		"  --windowed                   Force display mode to windowed\n"
+		"\n"
+		"Gamefile options:\n"
+		"  /dir/path/game/              Launch the game in specified directory\n"
+		"  /dir/path/game/penguin.exe   Launch penguin.exe\n"
+		"  [nothing]                    Launch the game in the current directory\n"
+		//--------------------------------------------------------------------------------|
 	);
 }
 
@@ -459,3 +461,5 @@ int ags_entry_point(int argc, char *argv[]) {
 	}
 #endif
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/main/quit.cpp b/engines/ags/engine/main/quit.cpp
index 5412b7d9a1..e76439281f 100644
--- a/engines/ags/engine/main/quit.cpp
+++ b/engines/ags/engine/main/quit.cpp
@@ -47,6 +47,8 @@
 #include "plugin/plugin_engine.h"
 #include "media/audio/audio_system.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -87,7 +89,7 @@ void quit_shutdown_scripts() {
 
 void quit_check_dynamic_sprites(QuitReason qreason) {
 	if ((qreason & kQuitKind_NormalExit) && (check_dynamic_sprites_at_exit) &&
-	        (game.options[OPT_DEBUGMODE] != 0)) {
+		(game.options[OPT_DEBUGMODE] != 0)) {
 		// game exiting normally -- make sure the dynamic sprites
 		// have been deleted
 		for (int i = 1; i < spriteset.GetSpriteSlotCount(); i++) {
@@ -146,8 +148,8 @@ QuitReason quit_check_for_error_state(const char *&qmsg, String &alertis) {
 		} else {
 			qreason = kQuit_GameError;
 			alertis.Format("An error has occurred. Please contact the game author for support, as this "
-			               "is likely to be a scripting error and not a bug in AGS.\n"
-			               "(ACI version %s)\n\n", EngineVersion.LongString.GetCStr());
+				"is likely to be a scripting error and not a bug in AGS.\n"
+				"(ACI version %s)\n\n", EngineVersion.LongString.GetCStr());
 		}
 
 		alertis.Append(get_cur_script(5));
@@ -160,14 +162,14 @@ QuitReason quit_check_for_error_state(const char *&qmsg, String &alertis) {
 	} else if (qmsg[0] == '%') {
 		qmsg++;
 		alertis.Format("A warning has been generated. This is not normally fatal, but you have selected "
-		               "to treat warnings as errors.\n"
-		               "(ACI version %s)\n\n%s\n", EngineVersion.LongString.GetCStr(), get_cur_script(5).GetCStr());
+			"to treat warnings as errors.\n"
+			"(ACI version %s)\n\n%s\n", EngineVersion.LongString.GetCStr(), get_cur_script(5).GetCStr());
 		return kQuit_GameWarning;
 	} else {
 		alertis.Format("An internal error has occurred. Please note down the following information.\n"
-		               "If the problem persists, post the details on the AGS Technical Forum.\n"
-		               "(ACI version %s)\n"
-		               "\nError: ", EngineVersion.LongString.GetCStr());
+			"If the problem persists, post the details on the AGS Technical Forum.\n"
+			"(ACI version %s)\n"
+			"\nError: ", EngineVersion.LongString.GetCStr());
 		return kQuit_FatalError;
 	}
 }
@@ -300,3 +302,5 @@ extern "C" {
 		quit(msg);
 	}
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/main/update.cpp b/engines/ags/engine/main/update.cpp
index 54a54daff2..f8810acccd 100644
--- a/engines/ags/engine/main/update.cpp
+++ b/engines/ags/engine/main/update.cpp
@@ -49,6 +49,8 @@
 #include "main/game_run.h"
 #include "ac/movelist.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -95,16 +97,18 @@ int do_movelist_move(short *mlnum, int *xx, int *yy) {
 		int adjAmnt = 3;
 		// 2.70: if the X permove is also <=1, don't do the skipping
 		if (((xpermove & 0xffff0000) == 0xffff0000) ||
-		        ((xpermove & 0xffff0000) == 0x00000000))
+			((xpermove & 0xffff0000) == 0x00000000))
 			adjAmnt = 2;
 
 		// 2.61 RC1: correct this to work with > -1 as well as < 1
-		if (ypermove == 0) { }
+		if (ypermove == 0) {
+		}
 		// Y per move is < 1, so finish the move
 		else if ((ypermove & 0xffff0000) == 0)
 			targety -= adjAmnt;
 		// Y per move is -1 exactly, don't snap to finish
-		else if (ypermove == 0xffff0000) { }
+		else if (ypermove == 0xffff0000) {
+		}
 		// Y per move is > -1, so finish the move
 		else if ((ypermove & 0xffff0000) == 0xffff0000)
 			targety += adjAmnt;
@@ -117,26 +121,28 @@ int do_movelist_move(short *mlnum, int *xx, int *yy) {
 
 		// if the Y permove is also <=1, don't skip as far
 		if (((ypermove & 0xffff0000) == 0xffff0000) ||
-		        ((ypermove & 0xffff0000) == 0x00000000))
+			((ypermove & 0xffff0000) == 0x00000000))
 			adjAmnt = 2;
 
-		if (xpermove == 0) { }
+		if (xpermove == 0) {
+		}
 		// Y per move is < 1, so finish the move
 		else if ((xpermove & 0xffff0000) == 0)
 			targetx -= adjAmnt;
 		// X per move is -1 exactly, don't snap to finish
-		else if (xpermove == 0xffff0000) { }
+		else if (xpermove == 0xffff0000) {
+		}
 		// X per move is > -1, so finish the move
 		else if ((xpermove & 0xffff0000) == 0xffff0000)
 			targetx += adjAmnt;
 
 		/*    int xpmm=(xpermove >> 16) & 0x0000ffff;
 		//    if ((xpmm==0) | (xpmm==0xffff)) cmls->doneflag|=1;
-		    if (xpmm==0) cmls->doneflag|=1;*/
+			if (xpmm==0) cmls->doneflag|=1;*/
 	} else yps = cmls->fromy + (int)(fixtof(ypermove) * (float)cmls->onpart);
 	// check if finished horizontal movement
 	if (((xpermove > 0) && (xps >= targetx)) ||
-	        ((xpermove < 0) && (xps <= targetx))) {
+		((xpermove < 0) && (xps <= targetx))) {
 		cmls->doneflag |= 1;
 		xps = targetx;
 		// if the Y is almost there too, finish it
@@ -147,7 +153,7 @@ int do_movelist_move(short *mlnum, int *xx, int *yy) {
 	} else if (xpermove == 0)
 		cmls->doneflag |= 1;
 	// check if finished vertical movement
-	if ((ypermove > 0) & (yps >= targety)) {
+	if ((ypermove > 0) &(yps >= targety)) {
 		cmls->doneflag |= 2;
 		yps = targety;
 	} else if ((ypermove < 0) & (yps <= targety)) {
@@ -205,8 +211,8 @@ void update_cycling_views() {
 void update_shadow_areas() {
 	// shadow areas
 	int onwalkarea = get_walkable_area_at_character(game.playercharacter);
-	if (onwalkarea < 0) ;
-	else if (playerchar->flags & CHF_FIXVIEW) ;
+	if (onwalkarea < 0);
+	else if (playerchar->flags & CHF_FIXVIEW);
 	else {
 		onwalkarea = thisroom.WalkAreas[onwalkarea].Light;
 		if (onwalkarea > 0) playerchar->view = onwalkarea - 1;
@@ -220,7 +226,7 @@ void update_character_move_and_anim(int &numSheep, int *followingAsSheep) {
 	for (int aa = 0; aa < game.numcharacters; aa++) {
 		if (game.chars[aa].on != 1) continue;
 
-		CharacterInfo *chi    = &game.chars[aa];
+		CharacterInfo *chi = &game.chars[aa];
 		CharacterExtras *chex = &charextra[aa];
 
 		chi->UpdateMoveAndAnim(aa, chex, numSheep, followingAsSheep);
@@ -270,7 +276,7 @@ void update_speech_and_messages() {
 		}
 
 		if (play.messagetime < 1 && play.speech_display_post_time_ms > 0 &&
-		        play.fast_forward == 0) {
+			play.fast_forward == 0) {
 			if (!play.speech_in_post_state) {
 				play.messagetime = ::lround(play.speech_display_post_time_ms * get_current_fps() / 1000.0f);
 			}
@@ -331,8 +337,8 @@ void update_sierra_speech() {
 				// the lip-sync has finished, so just stay idle
 			} else {
 				while ((curLipLinePhoneme < splipsync[curLipLine].numPhonemes) &&
-				        ((curLipLinePhoneme < 0) || (voice_pos_ms >= splipsync[curLipLine].endtimeoffs[curLipLinePhoneme]))) {
-					curLipLinePhoneme ++;
+					((curLipLinePhoneme < 0) || (voice_pos_ms >= splipsync[curLipLine].endtimeoffs[curLipLinePhoneme]))) {
+					curLipLinePhoneme++;
 					if (curLipLinePhoneme >= splipsync[curLipLine].numPhonemes)
 						facetalkframe = game.default_lipsync_frame;
 					else
@@ -347,18 +353,18 @@ void update_sierra_speech() {
 		} else if (facetalkwait > 0) facetalkwait--;
 		// don't animate if the speech has finished
 		else if ((play.messagetime < 1) && (facetalkframe == 0) &&
-		         // if play.close_mouth_speech_time = 0, this means animation should play till
-		         // the speech ends; but this should not work in voice mode, and also if the
-		         // speech is in the "post" state
-		         (play.speech_has_voice || play.speech_in_post_state || play.close_mouth_speech_time > 0))
+			// if play.close_mouth_speech_time = 0, this means animation should play till
+			// the speech ends; but this should not work in voice mode, and also if the
+			// speech is in the "post" state
+			(play.speech_has_voice || play.speech_in_post_state || play.close_mouth_speech_time > 0))
 			;
 		else {
 			// Close mouth at end of sentence: if speech has entered the "post" state,
 			// or if this is a text only mode and close_mouth_speech_time is set
 			if (play.speech_in_post_state ||
-			        (!play.speech_has_voice &&
-			         (play.messagetime < play.close_mouth_speech_time) &&
-			         (play.close_mouth_speech_time > 0))) {
+				(!play.speech_has_voice &&
+				(play.messagetime < play.close_mouth_speech_time) &&
+					(play.close_mouth_speech_time > 0))) {
 				facetalkframe = 0;
 				facetalkwait = play.messagetime;
 			} else if ((game.options[OPT_LIPSYNCTEXT]) && (facetalkrepeat > 0)) {
@@ -366,15 +372,15 @@ void update_sierra_speech() {
 				facetalkwait = update_lip_sync(facetalkview, facetalkloop, &facetalkframe);
 				// It is actually displayed for facetalkwait+1 loops
 				// (because when it's 1, it gets --'d then wait for next time)
-				facetalkwait --;
+				facetalkwait--;
 			} else {
 				// normal non-lip-sync
 				facetalkframe++;
 				if ((facetalkframe >= views[facetalkview].loops[facetalkloop].numFrames) ||
-				        (!play.speech_has_voice && (play.messagetime < 1) && (play.close_mouth_speech_time > 0))) {
+					(!play.speech_has_voice && (play.messagetime < 1) && (play.close_mouth_speech_time > 0))) {
 
 					if ((facetalkframe >= views[facetalkview].loops[facetalkloop].numFrames) &&
-					        (views[facetalkview].loops[facetalkloop].RunNextLoop())) {
+						(views[facetalkview].loops[facetalkloop].RunNextLoop())) {
 						facetalkloop++;
 					} else {
 						facetalkloop = 0;
@@ -468,3 +474,5 @@ void update_stuff() {
 
 	our_eip = 25;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/media/audio/ambientsound.cpp b/engines/ags/engine/media/audio/ambientsound.cpp
index ce89b44cc1..b7c77972e4 100644
--- a/engines/ags/engine/media/audio/ambientsound.cpp
+++ b/engines/ags/engine/media/audio/ambientsound.cpp
@@ -25,6 +25,8 @@
 #include "media/audio/soundclip.h"
 #include "util/stream.h"
 
+namespace AGS3 {
+
 using AGS::Shared::Stream;
 
 bool AmbientSound::IsPlaying() {
@@ -50,3 +52,5 @@ void AmbientSound::WriteToFile(Stream *out) {
 	out->WriteInt32(num);
 	out->WriteInt32(maxdist);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/media/audio/audio.cpp b/engines/ags/engine/media/audio/audio.cpp
index ffc2ba392d..cdd3339b5f 100644
--- a/engines/ags/engine/media/audio/audio.cpp
+++ b/engines/ags/engine/media/audio/audio.cpp
@@ -47,6 +47,8 @@
 #include "ac/timer.h"
 #include "main/game_run.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -200,14 +202,14 @@ static int find_free_audio_channel(ScriptAudioClip *clip, int priority, bool int
 			break;
 		}
 		if ((ch->priority < lowestPrioritySoFar) &&
-		        (ch->sourceClipType == clip->type)) {
+			(ch->sourceClipType == clip->type)) {
 			lowestPrioritySoFar = ch->priority;
 			lowestPriorityID = i;
 		}
 	}
 
 	if ((channelToUse < 0) && (lowestPriorityID >= 0) &&
-	        (lowestPrioritySoFar <= priority)) {
+		(lowestPrioritySoFar <= priority)) {
 		stop_or_fade_out_channel(lowestPriorityID, lowestPriorityID, clip);
 		channelToUse = lowestPriorityID;
 	} else if ((channelToUse >= 0) && (play.crossfading_in_channel < 1)) {
@@ -218,7 +220,7 @@ static int find_free_audio_channel(ScriptAudioClip *clip, int priority, bool int
 
 bool is_audiotype_allowed_to_play(AudioFileType type) {
 	return (type == eAudioFileMIDI && usetup.midicard != MIDI_NONE) ||
-	       (type != eAudioFileMIDI && usetup.digicard != DIGI_NONE);
+		(type != eAudioFileMIDI && usetup.digicard != DIGI_NONE);
 }
 
 SOUNDCLIP *load_sound_clip(ScriptAudioClip *audioClip, bool repeat) {
@@ -572,11 +574,11 @@ void update_directional_sound_vol() {
 		auto *ch = lock.GetChannelIfPlaying(chnum);
 		if ((ch != nullptr) && (ch->xSource >= 0)) {
 			ch->apply_directional_modifier(
-			    get_volume_adjusted_for_distance(ch->vol,
-			                                     ch->xSource,
-			                                     ch->ySource,
-			                                     ch->maximumPossibleDistanceAway) -
-			    ch->vol);
+				get_volume_adjusted_for_distance(ch->vol,
+					ch->xSource,
+					ch->ySource,
+					ch->maximumPossibleDistanceAway) -
+				ch->vol);
 		}
 	}
 }
@@ -892,7 +894,7 @@ void update_audio_system_on_game_loop() {
 			play.cur_music_number = -1;
 			play_next_queued();
 		} else if ((game.options[OPT_CROSSFADEMUSIC] > 0) &&
-		           (play.music_queue_size > 0) && (!crossFading)) {
+			(play.music_queue_size > 0) && (!crossFading)) {
 			// want to crossfade, and new tune in the queue
 			auto *ch = lock.GetChannel(SCHAN_MUSIC);
 			if (ch) {
@@ -932,10 +934,10 @@ void stopmusic() {
 			update_music_volume();
 		}
 	} else if ((game.options[OPT_CROSSFADEMUSIC] > 0)
-	           && (lock.GetChannelIfPlaying(SCHAN_MUSIC) != nullptr)
-	           && (current_music_type != 0)
-	           && (current_music_type != MUS_MIDI)
-	           && (current_music_type != MUS_MOD)) {
+		&& (lock.GetChannelIfPlaying(SCHAN_MUSIC) != nullptr)
+		&& (current_music_type != 0)
+		&& (current_music_type != MUS_MIDI)
+		&& (current_music_type != MUS_MOD)) {
 
 		crossFading = -1;
 		crossFadeStep = 0;
@@ -1013,9 +1015,9 @@ int prepare_for_new_music() {
 	int useChannel = SCHAN_MUSIC;
 
 	if ((game.options[OPT_CROSSFADEMUSIC] > 0)
-	        && (lock.GetChannelIfPlaying(SCHAN_MUSIC) != nullptr)
-	        && (current_music_type != MUS_MIDI)
-	        && (current_music_type != MUS_MOD)) {
+		&& (lock.GetChannelIfPlaying(SCHAN_MUSIC) != nullptr)
+		&& (current_music_type != MUS_MIDI)
+		&& (current_music_type != MUS_MOD)) {
 
 		if (crossFading > 0) {
 			// It's still crossfading to the previous track
@@ -1132,3 +1134,5 @@ static void play_new_music(int mnum, SOUNDCLIP *music) {
 void newmusic(int mnum) {
 	play_new_music(mnum, nullptr);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/media/audio/clip_mydumbmod.cpp b/engines/ags/engine/media/audio/clip_mydumbmod.cpp
index ddf8b2e439..29337fda62 100644
--- a/engines/ags/engine/media/audio/clip_mydumbmod.cpp
+++ b/engines/ags/engine/media/audio/clip_mydumbmod.cpp
@@ -27,6 +27,8 @@
 #include "media/audio/clip_mydumbmod.h"
 #include "media/audio/audiointernaldefs.h"
 
+namespace AGS3 {
+
 void al_duh_set_loop(AL_DUH_PLAYER *dp, int loop) {
 	DUH_SIGRENDERER *sr = al_duh_get_sigrenderer(dp);
 	DUMB_IT_SIGRENDERER *itsr = duh_get_it_sigrenderer(sr);
@@ -176,4 +178,6 @@ MYMOD::MYMOD() : SOUNDCLIP() {
 	duhPlayer = nullptr;
 }
 
+} // namespace AGS3
+
 #endif // DUMB_MOD_PLAYER
diff --git a/engines/ags/engine/media/audio/clip_myjgmod.cpp b/engines/ags/engine/media/audio/clip_myjgmod.cpp
index 2dbbc01c74..2225bb636b 100644
--- a/engines/ags/engine/media/audio/clip_myjgmod.cpp
+++ b/engines/ags/engine/media/audio/clip_myjgmod.cpp
@@ -27,6 +27,8 @@
 #include "media/audio/clip_myjgmod.h"
 #include "media/audio/audiointernaldefs.h"
 
+namespace AGS3 {
+
 int MYMOD::poll() {
 	if (done)
 		return done;
@@ -87,4 +89,6 @@ int MYMOD::play() {
 MYMOD::MYMOD() : SOUNDCLIP() {
 }
 
-#endif // #ifdef JGMOD_MOD_PLAYER
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/engine/media/audio/clip_mymidi.cpp b/engines/ags/engine/media/audio/clip_mymidi.cpp
index 06f5bf986f..389ed3b475 100644
--- a/engines/ags/engine/media/audio/clip_mymidi.cpp
+++ b/engines/ags/engine/media/audio/clip_mymidi.cpp
@@ -25,6 +25,8 @@
 #include "media/audio/clip_mymidi.h"
 #include "media/audio/audiointernaldefs.h"
 
+namespace AGS3 {
+
 void MYMIDI::poll() {
 	if (state_ != SoundClipPlaying) {
 		return;
@@ -122,3 +124,5 @@ MYMIDI::MYMIDI() : SOUNDCLIP() {
 	tune = nullptr;
 	lengthInSeconds = 0;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/media/audio/clip_mymp3.cpp b/engines/ags/engine/media/audio/clip_mymp3.cpp
index 792c563fb4..d90f2cfbfe 100644
--- a/engines/ags/engine/media/audio/clip_mymp3.cpp
+++ b/engines/ags/engine/media/audio/clip_mymp3.cpp
@@ -32,6 +32,7 @@
 
 #include "platform/base/agsplatformdriver.h"
 
+namespace AGS3 {
 
 void MYMP3::poll() {
 	if (state_ != SoundClipPlaying) {
@@ -181,4 +182,6 @@ MYMP3::MYMP3() : SOUNDCLIP() {
 	chunksize = 0;
 }
 
-#endif // !NO_MP3_PLAYER
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/engine/media/audio/clip_myogg.cpp b/engines/ags/engine/media/audio/clip_myogg.cpp
index 98a2d1485b..45634550cc 100644
--- a/engines/ags/engine/media/audio/clip_myogg.cpp
+++ b/engines/ags/engine/media/audio/clip_myogg.cpp
@@ -29,6 +29,8 @@
 
 #include "platform/base/agsplatformdriver.h"
 
+namespace AGS3 {
+
 extern "C" {
 	extern int alogg_is_end_of_oggstream(ALOGG_OGGSTREAM *ogg);
 	extern int alogg_is_end_of_ogg(ALOGG_OGG *ogg);
@@ -206,3 +208,5 @@ MYOGG::MYOGG() : SOUNDCLIP() {
 	last_but_one = 0;
 	last_ms_offs = 0;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/media/audio/clip_mystaticmp3.cpp b/engines/ags/engine/media/audio/clip_mystaticmp3.cpp
index 63b760bdaf..942a5fbe57 100644
--- a/engines/ags/engine/media/audio/clip_mystaticmp3.cpp
+++ b/engines/ags/engine/media/audio/clip_mystaticmp3.cpp
@@ -31,6 +31,8 @@
 
 #include "platform/base/agsplatformdriver.h"
 
+namespace AGS3 {
+
 extern int our_eip;
 
 // ALMP3 functions are not reentrant! This mutex should be locked before calling any
@@ -162,4 +164,6 @@ MYSTATICMP3::MYSTATICMP3() : SOUNDCLIP() {
 	mp3buffer = nullptr;
 }
 
-#endif // !NO_MP3_PLAYER
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/engine/media/audio/clip_mystaticogg.cpp b/engines/ags/engine/media/audio/clip_mystaticogg.cpp
index 1efb47f45a..8860ca7160 100644
--- a/engines/ags/engine/media/audio/clip_mystaticogg.cpp
+++ b/engines/ags/engine/media/audio/clip_mystaticogg.cpp
@@ -28,6 +28,8 @@
 
 #include "platform/base/agsplatformdriver.h"
 
+namespace AGS3 {
+
 extern "C" {
 	extern int alogg_is_end_of_oggstream(ALOGG_OGGSTREAM *ogg);
 	extern int alogg_is_end_of_ogg(ALOGG_OGG *ogg);
@@ -213,3 +215,5 @@ MYSTATICOGG::MYSTATICOGG() : SOUNDCLIP() {
 	last_ms_offs = 0;
 	last_but_one_but_one = 0;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/media/audio/clip_mywave.cpp b/engines/ags/engine/media/audio/clip_mywave.cpp
index 34ab83cc04..5efd2fbe32 100644
--- a/engines/ags/engine/media/audio/clip_mywave.cpp
+++ b/engines/ags/engine/media/audio/clip_mywave.cpp
@@ -29,6 +29,8 @@
 
 #include "platform/base/agsplatformdriver.h"
 
+namespace AGS3 {
+
 void MYWAVE::poll() {
 	if (state_ != SoundClipPlaying) {
 		return;
@@ -128,3 +130,5 @@ MYWAVE::MYWAVE() : SOUNDCLIP() {
 	wave = nullptr;
 	voice = -1;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/media/audio/queuedaudioitem.cpp b/engines/ags/engine/media/audio/queuedaudioitem.cpp
index 66be4bf249..a98f801af2 100644
--- a/engines/ags/engine/media/audio/queuedaudioitem.cpp
+++ b/engines/ags/engine/media/audio/queuedaudioitem.cpp
@@ -24,6 +24,8 @@
 #include "ac/common_defines.h"
 #include "util/stream.h"
 
+namespace AGS3 {
+
 using AGS::Shared::Stream;
 
 // [IKM] 2012-07-02: these functions are used during load/save game,
@@ -42,3 +44,5 @@ void QueuedAudioItem::WriteToFile(Stream *out) const {
 	out->WriteBool(repeat);
 	out->WriteInt32(0); // cachedClip
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/media/audio/sound.cpp b/engines/ags/engine/media/audio/sound.cpp
index 557c066c93..ac9f3e6d71 100644
--- a/engines/ags/engine/media/audio/sound.cpp
+++ b/engines/ags/engine/media/audio/sound.cpp
@@ -51,6 +51,8 @@
 #include "media/audio/soundcache.h"
 #include "util/mutex_lock.h"
 
+namespace AGS3 {
+
 #if defined JGMOD_MOD_PLAYER && defined DUMB_MOD_PLAYER
 #error JGMOD_MOD_PLAYER and DUMB_MOD_PLAYER macros cannot be defined at the same time.
 #endif
@@ -61,7 +63,7 @@
 
 extern "C"
 {
-// Load MIDI from PACKFILE stream
+	// Load MIDI from PACKFILE stream
 	MIDI *load_midi_pf(PACKFILE *pf);
 }
 
@@ -349,4 +351,6 @@ void remove_mod_player() {
 	dumb_exit();
 }
 
-#endif  // DUMB_MOD_PLAYER
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/engine/media/audio/soundcache.cpp b/engines/ags/engine/media/audio/soundcache.cpp
index fdeae5cbde..f8bbfa3095 100644
--- a/engines/ags/engine/media/audio/soundcache.cpp
+++ b/engines/ags/engine/media/audio/soundcache.cpp
@@ -31,6 +31,8 @@
 #include "util/string.h"
 #include "debug/out.h"
 
+namespace AGS3 {
+
 using namespace Shared;
 
 sound_cache_entry_t *sound_cache_entries = nullptr;
@@ -210,3 +212,5 @@ char *get_cached_sound(const AssetPath &asset_name, bool is_wave, size_t &size)
 	}
 
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/media/audio/soundclip.cpp b/engines/ags/engine/media/audio/soundclip.cpp
index 28298057d4..64a2238f31 100644
--- a/engines/ags/engine/media/audio/soundclip.cpp
+++ b/engines/ags/engine/media/audio/soundclip.cpp
@@ -26,6 +26,8 @@
 #include "media/audio/soundclip.h"
 #include "media/audio/audiointernaldefs.h"
 
+namespace AGS3 {
+
 int SOUNDCLIP::play_from(int position) {
 	int retVal = play();
 	if ((retVal != 0) && (position > 0)) {
@@ -90,3 +92,5 @@ SOUNDCLIP::SOUNDCLIP() {
 }
 
 SOUNDCLIP::~SOUNDCLIP() = default;
+
+} // namespace AGS3
diff --git a/engines/ags/engine/media/video/video.cpp b/engines/ags/engine/media/video/video.cpp
index b26b41321c..a34bdf43a9 100644
--- a/engines/ags/engine/media/video/video.cpp
+++ b/engines/ags/engine/media/video/video.cpp
@@ -50,6 +50,8 @@
 #include "util/stream.h"
 #include "media/audio/audio_system.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -223,7 +225,8 @@ void play_flc_file(int numb, int playflags) {
 	delete hicol_buf;
 	hicol_buf = nullptr;
 	//  SetVirtualScreen(screen); wputblock(0,0,backbuffer,0);
-	while (ags_mgetbutton() != NONE) { } // clear any queued mouse events.
+	while (ags_mgetbutton() != NONE) {
+	} // clear any queued mouse events.
 	invalidate_screen();
 }
 
@@ -232,7 +235,7 @@ void play_flc_file(int numb, int playflags) {
 // Theora player begin
 // TODO: find a way to take Bitmap here?
 Bitmap gl_TheoraBuffer;
-int theora_playing_callback(BITMAP *theoraBuffer) {
+int theora_playing_callback(BITMAP * theoraBuffer) {
 	if (theoraBuffer == nullptr) {
 		// No video, only sound
 		return check_if_user_input_should_cancel_video();
@@ -250,7 +253,7 @@ int theora_playing_callback(BITMAP *theoraBuffer) {
 		drawAtY = viewport.GetHeight() / 2 - fliTargetHeight / 2;
 		if (!gfxDriver->HasAcceleratedTransform()) {
 			fli_target->StretchBlt(&gl_TheoraBuffer, RectWH(0, 0, gl_TheoraBuffer.GetWidth(), gl_TheoraBuffer.GetHeight()),
-			                       RectWH(drawAtX, drawAtY, fliTargetWidth, fliTargetHeight));
+				RectWH(drawAtX, drawAtY, fliTargetWidth, fliTargetHeight));
 			gfxDriver->UpdateDDBFromBitmap(fli_ddb, fli_target, false);
 			drawAtX = 0;
 			drawAtY = 0;
@@ -290,7 +293,7 @@ void apeg_stream_skip(int bytes, void *ptr) {
 }
 //
 
-APEG_STREAM *get_theora_size(Stream *video_stream, int *width, int *height) {
+APEG_STREAM *get_theora_size(Stream * video_stream, int *width, int *height) {
 	APEG_STREAM *oggVid = apeg_open_stream_ex(video_stream);
 	if (oggVid != nullptr) {
 		apeg_get_video_size(oggVid, width, height);
@@ -393,8 +396,13 @@ void video_on_gfxmode_changed() {
 
 #else
 
-void play_theora_video(const char *name, int skip, int flags) {}
-void play_flc_file(int numb, int playflags) {}
-void video_on_gfxmode_changed() {}
+void play_theora_video(const char *name, int skip, int flags) {
+}
+void play_flc_file(int numb, int playflags) {
+}
+void video_on_gfxmode_changed() {
+}
 
 #endif
+
+} // namespace AGS3
diff --git a/engines/ags/engine/platform/android/acpland.cpp b/engines/ags/engine/platform/android/acpland.cpp
index 83d3136bda..7ce56c4d18 100644
--- a/engines/ags/engine/platform/android/acpland.cpp
+++ b/engines/ags/engine/platform/android/acpland.cpp
@@ -41,6 +41,8 @@
 #include <jni.h>
 #include <android/log.h>
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 #define ANDROID_CONFIG_FILENAME "android.cfg"
@@ -725,4 +727,6 @@ AGSPlatformDriver *AGSPlatformDriver::GetDriver() {
 	return instance;
 }
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/platform/base/agsplatformdriver.cpp b/engines/ags/engine/platform/base/agsplatformdriver.cpp
index 79db1193d7..ba78ed5a99 100644
--- a/engines/ags/engine/platform/base/agsplatformdriver.cpp
+++ b/engines/ags/engine/platform/base/agsplatformdriver.cpp
@@ -38,6 +38,8 @@
 #include "ac/timer.h"
 #include "media/audio/audio_system.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -55,25 +57,38 @@ AGSPlatformDriver *platform = nullptr;
 
 // ******** DEFAULT IMPLEMENTATIONS *******
 
-void AGSPlatformDriver::AboutToQuitGame() { }
-void AGSPlatformDriver::PostAllegroInit(bool windowed) { }
-void AGSPlatformDriver::AttachToParentConsole() { }
-void AGSPlatformDriver::DisplaySwitchOut() { }
-void AGSPlatformDriver::DisplaySwitchIn() { }
-void AGSPlatformDriver::PauseApplication() { }
-void AGSPlatformDriver::ResumeApplication() { }
-void AGSPlatformDriver::GetSystemDisplayModes(std::vector<DisplayMode> &dms) { }
+void AGSPlatformDriver::AboutToQuitGame() {
+}
+void AGSPlatformDriver::PostAllegroInit(bool windowed) {
+}
+void AGSPlatformDriver::AttachToParentConsole() {
+}
+void AGSPlatformDriver::DisplaySwitchOut() {
+}
+void AGSPlatformDriver::DisplaySwitchIn() {
+}
+void AGSPlatformDriver::PauseApplication() {
+}
+void AGSPlatformDriver::ResumeApplication() {
+}
+void AGSPlatformDriver::GetSystemDisplayModes(std::vector<DisplayMode> &dms) {
+}
 bool AGSPlatformDriver::EnterFullscreenMode(const DisplayMode &dm) {
 	return true;
 }
 bool AGSPlatformDriver::ExitFullscreenMode() {
 	return true;
 }
-void AGSPlatformDriver::AdjustWindowStyleForFullscreen() { }
-void AGSPlatformDriver::AdjustWindowStyleForWindowed() { }
-void AGSPlatformDriver::RegisterGameWithGameExplorer() { }
-void AGSPlatformDriver::UnRegisterGameWithGameExplorer() { }
-void AGSPlatformDriver::PlayVideo(const char *name, int skip, int flags) {}
+void AGSPlatformDriver::AdjustWindowStyleForFullscreen() {
+}
+void AGSPlatformDriver::AdjustWindowStyleForWindowed() {
+}
+void AGSPlatformDriver::RegisterGameWithGameExplorer() {
+}
+void AGSPlatformDriver::UnRegisterGameWithGameExplorer() {
+}
+void AGSPlatformDriver::PlayVideo(const char *name, int skip, int flags) {
+}
 
 const char *AGSPlatformDriver::GetAllegroFailUserHint() {
 	return "Make sure you have latest version of Allegro 4 libraries installed, and your system is running in graphical mode.";
@@ -149,7 +164,8 @@ int AGSPlatformDriver::ConvertKeycodeToScanCode(int keycode) {
 bool AGSPlatformDriver::LockMouseToWindow() {
 	return false;
 }
-void AGSPlatformDriver::UnlockMouse() { }
+void AGSPlatformDriver::UnlockMouse() {
+}
 
 //-----------------------------------------------
 // IOutputHandler implementation
@@ -209,7 +225,7 @@ int cd_player_control(int cmdd, int datt) {
 		cd_close();
 	else if (cmdd == 8)
 		return numcddrives;
-	else if (cmdd == 9) ;
+	else if (cmdd == 9);
 	else quit("!CDAudio: Unknown command code");
 
 	return 0;
@@ -240,3 +256,5 @@ void AGSPlatformDriver::Delay(int millis) {
 		now = AGS_Clock::now(); // update now
 	}
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/platform/ios/acplios.cpp b/engines/ags/engine/platform/ios/acplios.cpp
index 672a3b1a20..56e80d2753 100644
--- a/engines/ags/engine/platform/ios/acplios.cpp
+++ b/engines/ags/engine/platform/ios/acplios.cpp
@@ -36,6 +36,8 @@
 #include "plugin/agsplugin.h"
 #include "util/string_utils.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 #define IOS_CONFIG_FILENAME "ios.cfg"
@@ -624,4 +626,6 @@ AGSPlatformDriver *AGSPlatformDriver::GetDriver() {
 	return instance;
 }
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/platform/linux/acpllnx.cpp b/engines/ags/engine/platform/linux/acpllnx.cpp
index 9c0ce818da..092d67a2e3 100644
--- a/engines/ags/engine/platform/linux/acpllnx.cpp
+++ b/engines/ags/engine/platform/linux/acpllnx.cpp
@@ -39,6 +39,8 @@
 #include <pwd.h>
 #include <sys/stat.h>
 
+namespace AGS3 {
+
 using AGS::Shared::String;
 
 
@@ -201,4 +203,6 @@ void AGSLinux::GetSystemDisplayModes(std::vector<Engine::DisplayMode> &dms) {
 	destroy_gfx_mode_list(gmlist);
 }
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/platform/osx/acplmac.cpp b/engines/ags/engine/platform/osx/acplmac.cpp
index ef815cb945..449464d8bf 100644
--- a/engines/ags/engine/platform/osx/acplmac.cpp
+++ b/engines/ags/engine/platform/osx/acplmac.cpp
@@ -39,6 +39,8 @@
 #include "ac/common.h"
 #include "main/main.h"
 
+namespace AGS3 {
+
 void AGSMacInitPaths(char gamename[256], char appdata[PATH_MAX]);
 void AGSMacGetBundleDir(char gamepath[PATH_MAX]);
 //bool PlayMovie(char const *name, int skipType);
@@ -148,4 +150,6 @@ AGSPlatformDriver *AGSPlatformDriver::GetDriver() {
 	return instance;
 }
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/platform/windows/acplwin.cpp b/engines/ags/engine/platform/windows/acplwin.cpp
index a0097e2793..00965b04f7 100644
--- a/engines/ags/engine/platform/windows/acplwin.cpp
+++ b/engines/ags/engine/platform/windows/acplwin.cpp
@@ -48,6 +48,8 @@
 #include "util/string_compat.h"
 #include "media/audio/audio_system.h"
 
+namespace AGS3 {
+
 #ifndef AGS_NO_VIDEO_PLAYER
 extern void dxmedia_abort_video();
 extern void dxmedia_pause_video();
@@ -1045,4 +1047,6 @@ LPDIRECTINPUTDEVICE IAGSEngine::GetDirectInputMouse() {
 	return mouse_dinput_device;
 }
 
+} // namespace AGS3
+
 #endif
diff --git a/engines/ags/engine/platform/windows/debugging/namedpipesagsdebugger.cpp b/engines/ags/engine/platform/windows/debugging/namedpipesagsdebugger.cpp
index f2b22812bc..6985e435ae 100644
--- a/engines/ags/engine/platform/windows/debugging/namedpipesagsdebugger.cpp
+++ b/engines/ags/engine/platform/windows/debugging/namedpipesagsdebugger.cpp
@@ -28,6 +28,8 @@
 
 #include <stdio.h> // sprintf
 
+namespace AGS3 {
+
 void NamedPipesAGSDebugger::SendAcknowledgement() {
 	DWORD bytesWritten;
 	WriteFile(_hPipeSending, "MSGACK", 6, &bytesWritten, NULL);
@@ -50,7 +52,7 @@ bool NamedPipesAGSDebugger::Initialize() {
 	_hPipeReading = CreateFile(pipeNameBuffer, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
 
 	if ((_hPipeReading == INVALID_HANDLE_VALUE) ||
-	        (_hPipeSending == INVALID_HANDLE_VALUE))
+		(_hPipeSending == INVALID_HANDLE_VALUE))
 		return false;
 
 	return true;
@@ -91,7 +93,8 @@ char *NamedPipesAGSDebugger::GetNextMessage() {
 	} else {
 		return NULL;
 	}
-
 }
 
-#endif // AGS_PLATFORM_OS_WINDOWS
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp b/engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
index 2cfa9e0909..b7d06c1e35 100644
--- a/engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
+++ b/engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
@@ -45,6 +45,8 @@
 #include "platform/base/agsplatformdriver.h"
 #include "util/library.h"
 
+namespace AGS3 {
+
 #ifndef AGS_NO_VIDEO_PLAYER
 extern int dxmedia_play_video_3d(const char *filename, IDirect3DDevice9 *device, bool useAVISound, int canskip, int stretch);
 extern void dxmedia_shutdown_3d();
@@ -1866,5 +1868,6 @@ bool D3DGraphicsFactory::Init() {
 } // namespace D3D
 } // namespace Engine
 } // namespace AGS
+} // namsepace AGS3
 
-#endif // AGS_PLATFORM_OS_WINDOWS
+#endif
diff --git a/engines/ags/engine/platform/windows/media/video/acwavi.cpp b/engines/ags/engine/platform/windows/media/video/acwavi.cpp
index 071b942b5f..1e17d09aec 100644
--- a/engines/ags/engine/platform/windows/media/video/acwavi.cpp
+++ b/engines/ags/engine/platform/windows/media/video/acwavi.cpp
@@ -47,6 +47,8 @@
 #include "main/game_run.h"
 #include "platform/base/agsplatformdriver.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -435,4 +437,6 @@ int WINAPI WinMain(
 }
 #endif
 
-#endif // AGS_PLATFORM_OS_WINDOWS
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/engine/platform/windows/media/video/acwavi3d.cpp b/engines/ags/engine/platform/windows/media/video/acwavi3d.cpp
index c964e34127..a22f02848d 100644
--- a/engines/ags/engine/platform/windows/media/video/acwavi3d.cpp
+++ b/engines/ags/engine/platform/windows/media/video/acwavi3d.cpp
@@ -50,6 +50,8 @@ typedef float D3DVALUE, *LPD3DVALUE;
 //#include <atlbase.h>
 #include "media/audio/audio_system.h"
 
+namespace AGS3 {
+
 #define USES_CONVERSION int _convert = 0; _convert; UINT _acp = CP_ACP; _acp; LPCWSTR _lpw = NULL; _lpw; LPCSTR _lpa = NULL; _lpa
 
 inline LPWSTR WINAPI AtlA2WHelper(LPWSTR lpw, LPCSTR lpa, int nChars, UINT acp) {
@@ -920,4 +922,6 @@ BOOL CVMR9Graph::SetLayerZOrder(int nLayer, DWORD dwZOrder) {
 	return TRUE;
 }
 
-#endif // AGS_PLATFORM_OS_WINDOWS
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/engine/platform/windows/minidump.cpp b/engines/ags/engine/platform/windows/minidump.cpp
index 8f6314817a..6203f1eadc 100644
--- a/engines/ags/engine/platform/windows/minidump.cpp
+++ b/engines/ags/engine/platform/windows/minidump.cpp
@@ -29,6 +29,8 @@
 #include <crtdbg.h>
 #include "main/main.h"
 
+namespace AGS3 {
+
 CONTEXT cpustate;
 EXCEPTION_RECORD excinfo;
 int miniDumpResultCode = 0;
@@ -112,4 +114,6 @@ int CustomExceptionHandler(LPEXCEPTION_POINTERS exinfo) {
 	return EXCEPTION_EXECUTE_HANDLER;
 }
 
+} // namespace AGS3
+
 #endif  // AGS_PLATFORM_OS_WINDOWS && !AGS_PLATFORM_DEBUG
diff --git a/engines/ags/engine/platform/windows/setup/winsetup.cpp b/engines/ags/engine/platform/windows/setup/winsetup.cpp
index 87a4344067..0b33435e22 100644
--- a/engines/ags/engine/platform/windows/setup/winsetup.cpp
+++ b/engines/ags/engine/platform/windows/setup/winsetup.cpp
@@ -48,6 +48,8 @@
 #include "util/file.h"
 #include "util/string_utils.h"
 
+namespace AGS3 {
+
 #define AL_ID(a,b,c,d)     (((a)<<24) | ((b)<<16) | ((c)<<8) | (d))
 
 #define DIGI_DIRECTAMX(n)        AL_ID('A','X','A'+(n),' ')
@@ -1156,5 +1158,6 @@ SetupReturnValue WinSetup(const ConfigTree &cfg_in, ConfigTree &cfg_out,
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
-#endif // AGS_PLATFORM_OS_WINDOWS
+#endif
diff --git a/engines/ags/engine/platform/windows/win_ex_handling.cpp b/engines/ags/engine/platform/windows/win_ex_handling.cpp
index 7cf8f76889..3f2e35bfee 100644
--- a/engines/ags/engine/platform/windows/win_ex_handling.cpp
+++ b/engines/ags/engine/platform/windows/win_ex_handling.cpp
@@ -37,6 +37,8 @@
 #define USE_CUSTOM_EXCEPTION_HANDLER
 #endif
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 extern int our_eip;
@@ -96,4 +98,6 @@ void setup_malloc_handling() {
 	printfworkingspace = (char *)malloc(7000);
 }
 
+} // namespace AGS3
+
 #endif // AGS_PLATFORM_OS_WINDOWS
diff --git a/engines/ags/engine/plugin/agsplugin.cpp b/engines/ags/engine/plugin/agsplugin.cpp
index ee10afb532..83133ab32a 100644
--- a/engines/ags/engine/plugin/agsplugin.cpp
+++ b/engines/ags/engine/plugin/agsplugin.cpp
@@ -74,6 +74,8 @@
 #include "util/filestream.h"
 #include "media/audio/audio_system.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Shared::Memory;
 using namespace AGS::Engine;
@@ -124,7 +126,7 @@ struct EnginePlugin {
 	char        filename[PLUGIN_FILENAME_MAX + 1];
 	AGS::Engine::Library   library;
 	bool       available;
-	char       *savedata;
+	char *savedata;
 	int         savedatasize;
 	int         wantHook;
 	int         invalidatedRegion;
@@ -193,7 +195,7 @@ void IAGSEngine::RequestEventHook(int32 event) {
 		quit("!IAGSEngine::RequestEventHook: no callback AGS_EngineOnEvent function exported from plugin");
 
 	if ((event & AGSE_SCRIPTDEBUG) &&
-	        ((plugins[this->pluginId].wantHook & AGSE_SCRIPTDEBUG) == 0)) {
+		((plugins[this->pluginId].wantHook & AGSE_SCRIPTDEBUG) == 0)) {
 		pluginsWantingDebugHooks++;
 		ccSetDebugHook(scriptDebugHook);
 	}
@@ -211,7 +213,7 @@ void IAGSEngine::UnrequestEventHook(int32 event) {
 		quit("!IAGSEngine::UnrequestEventHook: invalid event requested");
 
 	if ((event & AGSE_SCRIPTDEBUG) &&
-	        (plugins[this->pluginId].wantHook & AGSE_SCRIPTDEBUG)) {
+		(plugins[this->pluginId].wantHook & AGSE_SCRIPTDEBUG)) {
 		pluginsWantingDebugHooks--;
 		if (pluginsWantingDebugHooks < 1)
 			ccSetDebugHook(nullptr);
@@ -564,7 +566,7 @@ void IAGSEngine::PlaySoundChannel(int32 channel, int32 soundType, int32 volume,
 	SOUNDCLIP *newcha = nullptr;
 
 	if (((soundType == PSND_MP3STREAM) || (soundType == PSND_OGGSTREAM))
-	        && (loop != 0))
+		&& (loop != 0))
 		quit("IAGSEngine::PlaySoundChannel: streamed samples cannot loop");
 
 	// TODO: find out how engine was supposed to decide on where to load the sound from
@@ -725,7 +727,7 @@ void IAGSEngine::QueueGameScriptFunction(const char *name, int32 globalScript, i
 		quit("IAGSEngine::QueueGameScriptFunction: invalid number of arguments");
 
 	curscript->run_another(name, globalScript ? kScInstGame : kScInstRoom, numArgs,
-	                       RuntimeScriptValue().SetPluginArgument(arg1), RuntimeScriptValue().SetPluginArgument(arg2));
+		RuntimeScriptValue().SetPluginArgument(arg1), RuntimeScriptValue().SetPluginArgument(arg2));
 }
 
 int IAGSEngine::RegisterManagedObject(const void *object, IAGSScriptManagedObject *callback) {
@@ -988,7 +990,7 @@ Engine::GameInitError pl_register_plugins(const std::vector<Common::PluginInfo>
 		// ".dll" extension appended; we need to take care of that
 		const String name_ext = ".dll";
 		if (name.GetLength() <= name_ext.GetLength() || name.GetLength() > PLUGIN_FILENAME_MAX + name_ext.GetLength() ||
-		        name.CompareRightNoCase(name_ext, name_ext.GetLength())) {
+			name.CompareRightNoCase(name_ext, name_ext.GetLength())) {
 			return kGameInitErr_PluginNameInvalid;
 		}
 		// remove ".dll" from plugin's name
@@ -1026,7 +1028,7 @@ Engine::GameInitError pl_register_plugins(const std::vector<Common::PluginInfo>
 			apl->initGfxHook = (void(*)(const char *, void *))apl->library.GetFunctionAddress("AGS_EngineInitGfx");
 		} else {
 			AGS::Shared::Debug::Printf(kDbgMsg_Info, "Plugin '%s' could not be loaded (expected '%s'), trying built-in plugins...",
-			                           apl->filename, expect_filename.GetCStr());
+				apl->filename, expect_filename.GetCStr());
 			if (pl_use_builtin_plugin(apl)) {
 				AGS::Shared::Debug::Printf(kDbgMsg_Info, "Build-in plugin '%s' found and being used.", apl->filename);
 			} else {
@@ -1065,3 +1067,5 @@ bool pl_any_want_hook(int event) {
 	}
 	return false;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/plugin/global_plugin.cpp b/engines/ags/engine/plugin/global_plugin.cpp
index 0be249c80a..52e66cd8f8 100644
--- a/engines/ags/engine/plugin/global_plugin.cpp
+++ b/engines/ags/engine/plugin/global_plugin.cpp
@@ -31,6 +31,8 @@
 #include "ac/mouse.h"
 #include "util/string_compat.h"
 
+namespace AGS3 {
+
 int pluginSimulatedClick = NONE;
 
 void PluginSimulateMouseClick(int pluginButtonID) {
@@ -65,114 +67,114 @@ bool RegisterPluginStubs(const char *name) {
 	// Stubs for plugin functions.
 
 	bool is_agsteam = (ags_stricmp(name, "agsteam") == 0) || (ags_stricmp(name, "agsteam-unified") == 0) ||
-	                  (ags_stricmp(name, "agsteam-disjoint") == 0);
+		(ags_stricmp(name, "agsteam-disjoint") == 0);
 	bool is_agsgalaxy = (ags_stricmp(name, "agsgalaxy") == 0) || (ags_stricmp(name, "agsgalaxy-unified") == 0) ||
-	                    (ags_stricmp(name, "agsgalaxy-disjoint") == 0);
+		(ags_stricmp(name, "agsgalaxy-disjoint") == 0);
 
 	if (ags_stricmp(name, "ags_shell") == 0) {
 		// ags_shell.dll
-		ccAddExternalStaticFunction("ShellExecute",                 Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("ShellExecute", Sc_PluginStub_Void);
 		return true;
 	} else if (ags_stricmp(name, "ags_snowrain") == 0) {
 		// ags_snowrain.dll
-		ccAddExternalStaticFunction("srSetSnowDriftRange",          Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("srSetSnowDriftSpeed",          Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("srSetSnowFallSpeed",           Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("srChangeSnowAmount",           Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("srSetSnowBaseline",            Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("srSetSnowTransparency",        Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("srSetSnowDefaultView",         Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("srSetSnowWindSpeed",           Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("srSetSnowAmount",              Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("srSetSnowView",                Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("srChangeRainAmount",           Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("srSetRainView",                Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("srSetRainDefaultView",         Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("srSetRainTransparency",        Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("srSetRainWindSpeed",           Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("srSetRainBaseline",            Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("srSetRainAmount",              Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("srSetRainFallSpeed",           Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("srSetWindSpeed",               Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("srSetBaseline",                Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("srSetSnowDriftRange", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("srSetSnowDriftSpeed", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("srSetSnowFallSpeed", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("srChangeSnowAmount", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("srSetSnowBaseline", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("srSetSnowTransparency", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("srSetSnowDefaultView", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("srSetSnowWindSpeed", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("srSetSnowAmount", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("srSetSnowView", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("srChangeRainAmount", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("srSetRainView", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("srSetRainDefaultView", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("srSetRainTransparency", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("srSetRainWindSpeed", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("srSetRainBaseline", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("srSetRainAmount", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("srSetRainFallSpeed", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("srSetWindSpeed", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("srSetBaseline", Sc_PluginStub_Void);
 		return true;
 	} else if (ags_stricmp(name, "agsjoy") == 0) {
 		// agsjoy.dll
-		ccAddExternalStaticFunction("JoystickCount",                Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("JoystickName",                 Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("JoystickRescan",               Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("Joystick::Open^1",             Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("Joystick::IsOpen^1",           Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("Joystick::Click^1",            Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("Joystick::Close^0",            Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("Joystick::Valid^0",            Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("Joystick::Unplugged^0",        Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("Joystick::GetName^0",          Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("Joystick::GetAxis^1",          Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("Joystick::IsButtonDown^1",     Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("Joystick::IsJoyBtnDown^1",     Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("Joystick::Update^0",           Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("Joystick::DisableEvents^0",    Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("Joystick::EnableEvents^1",     Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("JoystickCount", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("JoystickName", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("JoystickRescan", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("Joystick::Open^1", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("Joystick::IsOpen^1", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("Joystick::Click^1", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("Joystick::Close^0", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("Joystick::Valid^0", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("Joystick::Unplugged^0", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("Joystick::GetName^0", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("Joystick::GetAxis^1", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("Joystick::IsButtonDown^1", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("Joystick::IsJoyBtnDown^1", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("Joystick::Update^0", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("Joystick::DisableEvents^0", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("Joystick::EnableEvents^1", Sc_PluginStub_Void);
 		return true;
 	} else if (ags_stricmp(name, "agsblend") == 0) {
 		// agsblend.dll
-		ccAddExternalStaticFunction("DrawAlpha",                    Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("GetAlpha",                     Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("PutAlpha",                     Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("Blur",                         Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("HighPass",                     Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("DrawAdd",                      Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("DrawAlpha", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("GetAlpha", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("PutAlpha", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("Blur", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("HighPass", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("DrawAdd", Sc_PluginStub_Int0);
 		return true;
 	} else if (ags_stricmp(name, "agsflashlight") == 0) {
 		// agsflashlight.dll
-		ccAddExternalStaticFunction("SetFlashlightTint",            Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("GetFlashlightTintRed",         Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("GetFlashlightTintGreen",       Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("GetFlashlightTintBlue",        Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("GetFlashlightMinLightLevel",   Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("GetFlashlightMaxLightLevel",   Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("SetFlashlightDarkness",        Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("GetFlashlightDarkness",        Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("SetFlashlightDarknessSize",    Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("GetFlashlightDarknessSize",    Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("SetFlashlightBrightness",      Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("GetFlashlightBrightness",      Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("SetFlashlightBrightnessSize",  Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("GetFlashlightBrightnessSize",  Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("SetFlashlightPosition",        Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("GetFlashlightPositionX",       Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("GetFlashlightPositionY",       Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("SetFlashlightFollowMouse",     Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("GetFlashlightFollowMouse",     Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("SetFlashlightTint", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("GetFlashlightTintRed", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("GetFlashlightTintGreen", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("GetFlashlightTintBlue", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("GetFlashlightMinLightLevel", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("GetFlashlightMaxLightLevel", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("SetFlashlightDarkness", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("GetFlashlightDarkness", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("SetFlashlightDarknessSize", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("GetFlashlightDarknessSize", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("SetFlashlightBrightness", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("GetFlashlightBrightness", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("SetFlashlightBrightnessSize", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("GetFlashlightBrightnessSize", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("SetFlashlightPosition", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("GetFlashlightPositionX", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("GetFlashlightPositionY", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("SetFlashlightFollowMouse", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("GetFlashlightFollowMouse", Sc_PluginStub_Int0);
 		ccAddExternalStaticFunction("SetFlashlightFollowCharacter", Sc_PluginStub_Void);
 		ccAddExternalStaticFunction("GetFlashlightFollowCharacter", Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("GetFlashlightCharacterDX",     Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("GetFlashlightCharacterDY",     Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("GetFlashlightCharacterHorz",   Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("GetFlashlightCharacterVert",   Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("SetFlashlightMask",            Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("GetFlashlightMask",            Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("GetFlashlightCharacterDX", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("GetFlashlightCharacterDY", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("GetFlashlightCharacterHorz", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("GetFlashlightCharacterVert", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("SetFlashlightMask", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("GetFlashlightMask", Sc_PluginStub_Int0);
 		return true;
 	} else if (ags_stricmp(name, "agswadjetutil") == 0) {
 		// agswadjetutil.dll
-		ccAddExternalStaticFunction("IsOnPhone",                    Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("FakeKeypress",                 Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("IosSetAchievementValue",       Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("IosGetAchievementValue",       Sc_PluginStub_IntNeg1);
-		ccAddExternalStaticFunction("IosShowAchievements",          Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("IosResetAchievements",         Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("MobileGetAchievement",         Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("MobileSetAchievement",         Sc_PluginStub_Int0);
-		ccAddExternalStaticFunction("MobileShowAchievements",       Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("MobileResetAchievements",      Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("IsOnPhone", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("FakeKeypress", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("IosSetAchievementValue", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("IosGetAchievementValue", Sc_PluginStub_IntNeg1);
+		ccAddExternalStaticFunction("IosShowAchievements", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("IosResetAchievements", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("MobileGetAchievement", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("MobileSetAchievement", Sc_PluginStub_Int0);
+		ccAddExternalStaticFunction("MobileShowAchievements", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("MobileResetAchievements", Sc_PluginStub_Void);
 		return true;
 	} else if (ags_stricmp(name, "agsspritefont") == 0) {
-		ccAddExternalStaticFunction("SetSpriteFont",                Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("SetVariableSpriteFont",        Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("SetGlyph",                     Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("SetSpacing",                   Sc_PluginStub_Void);
-		ccAddExternalStaticFunction("SetLineHeightAdjust",          Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("SetSpriteFont", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("SetVariableSpriteFont", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("SetGlyph", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("SetSpacing", Sc_PluginStub_Void);
+		ccAddExternalStaticFunction("SetLineHeightAdjust", Sc_PluginStub_Void);
 		return true;
 	} else if (is_agsteam || is_agsgalaxy) {
 		// agsteam.dll or agsgalaxy.dll
@@ -245,3 +247,5 @@ bool RegisterPluginStubs(const char *name) {
 
 	return false;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/plugin/pluginobjectreader.cpp b/engines/ags/engine/plugin/pluginobjectreader.cpp
index 7cf0d2b8b0..c5d387dd12 100644
--- a/engines/ags/engine/plugin/pluginobjectreader.cpp
+++ b/engines/ags/engine/plugin/pluginobjectreader.cpp
@@ -23,5 +23,9 @@
 #include "plugin/pluginobjectreader.h"
 #include "ac/runtime_defines.h"
 
+namespace AGS3 {
+
 PluginObjectReader pluginReaders[MAX_PLUGIN_OBJECT_READERS];
 int numPluginReaders = 0;
+
+} // namespace AGS3
diff --git a/engines/ags/engine/script/cc_error_engine.cpp b/engines/ags/engine/script/cc_error_engine.cpp
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/engines/ags/engine/script/cc_instance.cpp b/engines/ags/engine/script/cc_instance.cpp
index 88038dc312..ef4b9dd643 100644
--- a/engines/ags/engine/script/cc_instance.cpp
+++ b/engines/ags/engine/script/cc_instance.cpp
@@ -46,6 +46,8 @@
 #include "util/memory.h"
 #include "util/string_utils.h" // linux strnicmp definition
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 using namespace AGS::Shared::Memory;
 
@@ -1819,3 +1821,5 @@ void ccInstance::PopFromFuncCallStack(FunctionCallStack &func_callstack, int32_t
 	func_callstack.Head += num_entries;
 	func_callstack.Count -= num_entries;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/script/executingscript.cpp b/engines/ags/engine/script/executingscript.cpp
index 41d8f87a17..3b977b517b 100644
--- a/engines/ags/engine/script/executingscript.cpp
+++ b/engines/ags/engine/script/executingscript.cpp
@@ -25,6 +25,8 @@
 #include "debug/debug_log.h"
 #include "debug/debugger.h"
 
+namespace AGS3 {
+
 QueuedScript::QueuedScript()
 	: Instance(kScInstGame)
 	, ParamCount(0) {
@@ -44,10 +46,10 @@ int ExecutingScript::queue_action(PostScriptAction act, int data, const char *an
 		case ePSARunAGSGame:
 		case ePSARestartGame:
 			quitprintf("!%s: Cannot run this command, since there was a %s command already queued to run in \"%s\", line %d",
-			           aname, postScriptActionNames[numPostScriptActions - 1],
-			           postScriptActionPositions[numPostScriptActions - 1].Section.GetCStr(), postScriptActionPositions[numPostScriptActions - 1].Line);
+				aname, postScriptActionNames[numPostScriptActions - 1],
+				postScriptActionPositions[numPostScriptActions - 1].Section.GetCStr(), postScriptActionPositions[numPostScriptActions - 1].Line);
 			break;
-		// MACPORT FIX 9/6/5: added default clause to remove warning
+			// MACPORT FIX 9/6/5: added default clause to remove warning
 		default:
 			break;
 		}
@@ -93,3 +95,5 @@ void ExecutingScript::init() {
 ExecutingScript::ExecutingScript() {
 	init();
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/script/exports.cpp b/engines/ags/engine/script/exports.cpp
index ce217931c2..3d067b9518 100644
--- a/engines/ags/engine/script/exports.cpp
+++ b/engines/ags/engine/script/exports.cpp
@@ -28,6 +28,8 @@
 
 #include "ac/gamestructdefines.h"
 
+namespace AGS3 {
+
 extern void RegisterAudioChannelAPI();
 extern void RegisterAudioClipAPI();
 extern void RegisterButtonAPI();
@@ -105,3 +107,5 @@ void setup_script_exports(ScriptAPIVersion base_api, ScriptAPIVersion compat_api
 
 	RegisterStaticObjects();
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/script/runtimescriptvalue.cpp b/engines/ags/engine/script/runtimescriptvalue.cpp
index ebcac94e8f..97f208099a 100644
--- a/engines/ags/engine/script/runtimescriptvalue.cpp
+++ b/engines/ags/engine/script/runtimescriptvalue.cpp
@@ -28,6 +28,8 @@
 
 #include <string.h> // for memcpy()
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 //
@@ -225,8 +227,8 @@ intptr_t RuntimeScriptValue::GetDirectPtr() const {
 	const RuntimeScriptValue *temp_val = this;
 	int ival = temp_val->IValue;
 	if (temp_val->Type == kScValGlobalVar || temp_val->Type == kScValStackPtr) {
-		temp_val  = temp_val->RValue;
-		ival     += temp_val->IValue;
+		temp_val = temp_val->RValue;
+		ival += temp_val->IValue;
 	}
 	if (temp_val->Type == kScValDynamicObject)
 		return (intptr_t)temp_val->DynMgr->GetFieldPtr(temp_val->Ptr, ival);
@@ -235,3 +237,5 @@ intptr_t RuntimeScriptValue::GetDirectPtr() const {
 	else
 		return (intptr_t)(temp_val->Ptr + ival);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/script/script.cpp b/engines/ags/engine/script/script.cpp
index ec59cc6a77..52ddbdcff3 100644
--- a/engines/ags/engine/script/script.cpp
+++ b/engines/ags/engine/script/script.cpp
@@ -52,6 +52,8 @@
 #include "util/string_compat.h"
 #include "media/audio/audio_system.h"
 
+namespace AGS3 {
+
 extern GameSetupStruct game;
 extern GameState play;
 extern int gameHasBeenRestored, displayed_room;
@@ -160,13 +162,13 @@ void run_function_on_non_blocking_thread(NonBlockingScriptFunction *funcToRun) {
 int run_interaction_event(Interaction *nint, int evnt, int chkAny, int isInv) {
 
 	if (evnt < 0 || (size_t)evnt >= nint->Events.size() ||
-	        (nint->Events[evnt].Response.get() == nullptr) || (nint->Events[evnt].Response->Cmds.size() == 0)) {
+		(nint->Events[evnt].Response.get() == nullptr) || (nint->Events[evnt].Response->Cmds.size() == 0)) {
 		// no response defined for this event
 		// If there is a response for "Any Click", then abort now so as to
 		// run that instead
-		if (chkAny < 0) ;
+		if (chkAny < 0);
 		else if ((size_t)chkAny < nint->Events.size() &&
-		         (nint->Events[chkAny].Response.get() != nullptr) && (nint->Events[chkAny].Response->Cmds.size() > 0))
+			(nint->Events[chkAny].Response.get() != nullptr) && (nint->Events[chkAny].Response->Cmds.size() > 0))
 			return 0;
 
 		// Otherwise, run unhandled_event
@@ -200,7 +202,7 @@ int run_interaction_script(InteractionScripts *nint, int evnt, int chkAny, int i
 		// no response defined for this event
 		// If there is a response for "Any Click", then abort now so as to
 		// run that instead
-		if (chkAny < 0) ;
+		if (chkAny < 0);
 		else if ((nint->ScriptFuncNames[chkAny] != nullptr) && (nint->ScriptFuncNames[chkAny][0u] != 0))
 			return 0;
 
@@ -438,7 +440,7 @@ int RunTextScript(ccInstance *sci, const char *tsname) {
 				RunScriptFunctionIfExists(moduleInst[kk], tsname, 0, nullptr);
 
 			if ((room_changes_was != play.room_changes) ||
-			        (restore_game_count_was != gameHasBeenRestored))
+				(restore_game_count_was != gameHasBeenRestored))
 				return 0;
 		}
 	}
@@ -672,7 +674,8 @@ int run_interaction_commandlist(InteractionCommandList *nicl, int *timesrun, int
 		switch (nicl->Cmds[i].Type) {
 		case 0:  // Do nothing
 			break;
-		case 1: { // Run script
+		case 1:
+		{ // Run script
 			TempEip tempip(4001);
 			RuntimeScriptValue rval_null;
 			update_polled_mp3();
@@ -713,7 +716,8 @@ int run_interaction_commandlist(InteractionCommandList *nicl, int *timesrun, int
 		case 8:  // Play Flic
 			play_flc_file(IPARAM1, IPARAM2);
 			break;
-		case 9: { // Run Dialog
+		case 9:
+		{ // Run Dialog
 			int room_was = play.room_changes;
 			RunDialog(IPARAM1);
 			// if they changed room within the dialog script,
@@ -903,11 +907,13 @@ void run_unhandled_event(int evnt) {
 		evtype = 4;
 	if ((evtype == 1) & ((evnt == 0) | (evnt == 5) | (evnt == 6)))
 		;  // character stands on hotspot, mouse moves over hotspot, any click
-	else if ((evtype == 2) & (evnt == 4)) ; // any click on object
-	else if ((evtype == 3) & (evnt == 4)) ; // any click on character
+	else if ((evtype == 2) & (evnt == 4)); // any click on object
+	else if ((evtype == 3) & (evnt == 4)); // any click on character
 	else if (evtype > 0) {
 		can_run_delayed_command();
 
 		QueueScriptFunction(kScInstGame, "unhandled_event", 2, RuntimeScriptValue().SetInt32(evtype), RuntimeScriptValue().SetInt32(evnt));
 	}
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/script/script_api.cpp b/engines/ags/engine/script/script_api.cpp
index 411da69bb3..da410e1389 100644
--- a/engines/ags/engine/script/script_api.cpp
+++ b/engines/ags/engine/script/script_api.cpp
@@ -28,6 +28,8 @@
 #include "script/script_api.h"
 #include "util/math.h"
 
+namespace AGS3 {
+
 namespace Math = AGS::Shared::Math;
 
 enum FormatParseResult {
@@ -71,7 +73,7 @@ inline const char *GetArgPtr(const RuntimeScriptValue *sc_args, va_list *varg_pt
 // snprintf but formatting values ourselves, or by using some library method
 // that supports customizing, such as getting arguments in a custom way.
 const char *ScriptSprintf(char *buffer, size_t buf_length, const char *format,
-                          const RuntimeScriptValue *sc_args, int32_t sc_argc, va_list *varg_ptr) {
+	const RuntimeScriptValue *sc_args, int32_t sc_argc, va_list *varg_ptr) {
 	if (!buffer || buf_length == 0) {
 		cc_error("Internal error in ScriptSprintf: buffer is null");
 		return "";
@@ -99,14 +101,14 @@ const char *ScriptSprintf(char *buffer, size_t buf_length, const char *format,
 	// number, such case is theoretically valid.
 	const size_t fmtbuf_size = 27;
 	char       fmtbuf[fmtbuf_size];
-	char       *fmt_bufptr;
-	char       *fmt_bufendptr = &fmtbuf[fmtbuf_size - 1];
+	char *fmt_bufptr;
+	char *fmt_bufendptr = &fmtbuf[fmtbuf_size - 1];
 
-	char       *out_ptr    = buffer;
+	char *out_ptr = buffer;
 	// save 1 character for null terminator
 	const char *out_endptr = buffer + buf_length - 1;
-	const char *fmt_ptr    = format;
-	int32_t    arg_idx     = 0;
+	const char *fmt_ptr = format;
+	int32_t    arg_idx = 0;
 
 	ptrdiff_t  avail_outbuf;
 	int        snprintf_res;
@@ -172,7 +174,7 @@ const char *ScriptSprintf(char *buffer, size_t buf_length, const char *format,
 				*(out_ptr++) = '%';
 				continue;
 			} else if (fmt_done >= kFormatParseArgFirst && fmt_done <= kFormatParseArgLast &&
-			           (varg_ptr || arg_idx < sc_argc)) {
+				(varg_ptr || arg_idx < sc_argc)) {
 				// Print the actual value
 				// NOTE: snprintf is called with avail_outbuf + 1 here, because we let it use our reserved
 				// character for null-terminator, in case we are at the end of the buffer
@@ -224,3 +226,5 @@ const char *ScriptSprintf(char *buffer, size_t buf_length, const char *format,
 	*out_ptr = 0;
 	return buffer;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/script/script_engine.cpp b/engines/ags/engine/script/script_engine.cpp
index 3d22a27aad..892b957ee0 100644
--- a/engines/ags/engine/script/script_engine.cpp
+++ b/engines/ags/engine/script/script_engine.cpp
@@ -37,11 +37,14 @@
 #include "util/file.h"
 #include "util/stream.h"
 
+namespace AGS3 {
+
 namespace AGS {
 namespace Shared {
 class RoomStruct;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS::Shared;
 
 extern void quit(const char *);
@@ -59,3 +62,5 @@ std::pair<String, String> cc_error_at_line(const char *error_msg) {
 String cc_error_without_line(const char *error_msg) {
 	return String::FromFormat("Runtime error: %s", error_msg);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/script/script_runtime.cpp b/engines/ags/engine/script/script_runtime.cpp
index 014c86c16c..d6eeeb827a 100644
--- a/engines/ags/engine/script/script_runtime.cpp
+++ b/engines/ags/engine/script/script_runtime.cpp
@@ -45,6 +45,8 @@
 #include "script/systemimports.h"
 #include "ac/statobj/staticobject.h"
 
+namespace AGS3 {
+
 extern ccInstance *current_instance; // in script/cc_instance
 
 bool ccAddExternalStaticFunction(const String &name, ScriptAPIFunction *pfn) {
@@ -83,10 +85,10 @@ void ccRemoveAllSymbols() {
 	simp.clear();
 }
 
-ccInstance *loadedInstances[MAX_LOADED_INSTANCES] = {nullptr,
-                                                     nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
-                                                     nullptr, nullptr, nullptr, nullptr, nullptr, nullptr
-                                                    };
+ccInstance *loadedInstances[MAX_LOADED_INSTANCES] = { nullptr,
+													 nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
+													 nullptr, nullptr, nullptr, nullptr, nullptr, nullptr
+};
 
 void nullfree(void *data) {
 	if (data != nullptr)
@@ -209,52 +211,62 @@ int call_function(intptr_t addr, const RuntimeScriptValue *object, int numparm,
 	//
 
 	switch (numparm) {
-	case 0: {
+	case 0:
+	{
 		int (*fparam)();
 		fparam = (int (*)())addr;
 		return fparam();
 	}
-	case 1: {
+	case 1:
+	{
 		int (*fparam)(intptr_t);
 		fparam = (int (*)(intptr_t))addr;
 		return fparam(parm_value[0]);
 	}
-	case 2: {
+	case 2:
+	{
 		int (*fparam)(intptr_t, intptr_t);
 		fparam = (int (*)(intptr_t, intptr_t))addr;
 		return fparam(parm_value[0], parm_value[1]);
 	}
-	case 3: {
+	case 3:
+	{
 		int (*fparam)(intptr_t, intptr_t, intptr_t);
 		fparam = (int (*)(intptr_t, intptr_t, intptr_t))addr;
 		return fparam(parm_value[0], parm_value[1], parm_value[2]);
 	}
-	case 4: {
+	case 4:
+	{
 		int (*fparam)(intptr_t, intptr_t, intptr_t, intptr_t);
 		fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t))addr;
 		return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3]);
 	}
-	case 5: {
+	case 5:
+	{
 		int (*fparam)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t);
 		fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr;
 		return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4]);
 	}
-	case 6: {
+	case 6:
+	{
 		int (*fparam)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t);
 		fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr;
 		return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4], parm_value[5]);
 	}
-	case 7: {
+	case 7:
+	{
 		int (*fparam)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t);
 		fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr;
 		return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4], parm_value[5], parm_value[6]);
 	}
-	case 8: {
+	case 8:
+	{
 		int (*fparam)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t);
 		fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr;
 		return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4], parm_value[5], parm_value[6], parm_value[7]);
 	}
-	case 9: {
+	case 9:
+	{
 		int (*fparam)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t);
 		fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr;
 		return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4], parm_value[5], parm_value[6], parm_value[7], parm_value[8]);
@@ -264,3 +276,5 @@ int call_function(intptr_t addr, const RuntimeScriptValue *object, int numparm,
 	cc_error("too many arguments in call to function");
 	return -1;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/script/systemimports.cpp b/engines/ags/engine/script/systemimports.cpp
index 67a06b7836..1912f111a8 100644
--- a/engines/ags/engine/script/systemimports.cpp
+++ b/engines/ags/engine/script/systemimports.cpp
@@ -24,6 +24,7 @@
 #include <string.h>
 #include "script/systemimports.h"
 
+namespace AGS3 {
 
 extern void quit(const char *);
 
@@ -53,9 +54,9 @@ int SystemImports::add(const String &name, const RuntimeScriptValue &value, ccIn
 	btree[name] = ixof;
 	if (ixof == imports.size())
 		imports.push_back(ScriptImport());
-	imports[ixof].Name          = name; // TODO: rather make a string copy here for safety reasons
-	imports[ixof].Value         = value;
-	imports[ixof].InstancePtr   = anotherscr;
+	imports[ixof].Name = name; // TODO: rather make a string copy here for safety reasons
+	imports[ixof].Value = value;
+	imports[ixof].InstancePtr = anotherscr;
 	return 0;
 }
 
@@ -129,3 +130,5 @@ void SystemImports::clear() {
 	btree.clear();
 	imports.clear();
 }
+
+} // namespace AGS3
diff --git a/engines/ags/shared/ac/audiocliptype.cpp b/engines/ags/shared/ac/audiocliptype.cpp
index f668c6b40b..d71acd72c2 100644
--- a/engines/ags/shared/ac/audiocliptype.cpp
+++ b/engines/ags/shared/ac/audiocliptype.cpp
@@ -23,6 +23,8 @@
 #include "ac/audiocliptype.h"
 #include "util/stream.h"
 
+namespace AGS3 {
+
 using AGS::Shared::Stream;
 
 void AudioClipType::ReadFromFile(Stream *in) {
@@ -50,3 +52,5 @@ void AudioClipType::WriteToSavegame(Common::Stream *out) const {
 	out->WriteInt32(volume_reduction_while_speech_playing);
 	out->WriteInt32(crossfadeSpeed);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/shared/ac/characterinfo.cpp b/engines/ags/shared/ac/characterinfo.cpp
index 6a3deb6a73..a6572e8d02 100644
--- a/engines/ags/shared/ac/characterinfo.cpp
+++ b/engines/ags/shared/ac/characterinfo.cpp
@@ -24,6 +24,8 @@
 #include "ac/characterinfo.h"
 #include "util/stream.h"
 
+namespace AGS3 {
+
 using AGS::Shared::Stream;
 
 
@@ -159,3 +161,5 @@ void ConvertOldCharacterToNew(OldCharacterInfo *oci, CharacterInfo *ci) {
 	ci->talkcolor = (oci->flags & OCHF_SPEECHCOL) >> OCHF_SPEECHCOLSHIFT;
 	ci->flags = ci->flags & (~OCHF_SPEECHCOL);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/shared/ac/common.cpp b/engines/ags/shared/ac/common.cpp
index 156703bf19..74a9b6cb9d 100644
--- a/engines/ags/shared/ac/common.cpp
+++ b/engines/ags/shared/ac/common.cpp
@@ -23,6 +23,8 @@
 #include "ac/common.h"
 #include "util/string.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 const char *game_file_sig = "Adventure Creator Game File v2";
@@ -34,3 +36,5 @@ void quitprintf(const char *fmt, ...) {
 	va_end(ap);
 	quit(text);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/shared/ac/dialogtopic.cpp b/engines/ags/shared/ac/dialogtopic.cpp
index f4ffdc0797..ac185000e3 100644
--- a/engines/ags/shared/ac/dialogtopic.cpp
+++ b/engines/ags/shared/ac/dialogtopic.cpp
@@ -23,6 +23,8 @@
 #include "ac/dialogtopic.h"
 #include "util/stream.h"
 
+namespace AGS3 {
+
 using AGS::Shared::Stream;
 
 void DialogTopic::ReadFromFile(Stream *in) {
@@ -45,3 +47,5 @@ void DialogTopic::ReadFromSavegame(Common::Stream *in) {
 void DialogTopic::WriteToSavegame(Common::Stream *out) const {
 	out->WriteArrayOfInt32(optionflags, MAXTOPICOPTIONS);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/shared/ac/dynobj/scriptaudioclip.cpp b/engines/ags/shared/ac/dynobj/scriptaudioclip.cpp
index a2b90d6f7b..4bee23fe7c 100644
--- a/engines/ags/shared/ac/dynobj/scriptaudioclip.cpp
+++ b/engines/ags/shared/ac/dynobj/scriptaudioclip.cpp
@@ -23,6 +23,8 @@
 #include "ac/dynobj/scriptaudioclip.h"
 #include "util/stream.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 void ScriptAudioClip::ReadFromFile(Stream *in) {
@@ -37,3 +39,5 @@ void ScriptAudioClip::ReadFromFile(Stream *in) {
 	defaultVolume = in->ReadInt16();
 	in->ReadInt32(); // reserved
 }
+
+} // namespace AGS3
diff --git a/engines/ags/shared/ac/gamesetupstruct.cpp b/engines/ags/shared/ac/gamesetupstruct.cpp
index e94ac5e416..970b8bc997 100644
--- a/engines/ags/shared/ac/gamesetupstruct.cpp
+++ b/engines/ags/shared/ac/gamesetupstruct.cpp
@@ -28,6 +28,8 @@
 #include "game/interactions.h"
 #include "util/alignedstream.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 GameSetupStruct::GameSetupStruct()
@@ -138,7 +140,7 @@ void GameSetupStruct::read_font_infos(Common::Stream *in, GameDataVersion data_v
 			if (data_ver >= kGameVersion_351) {
 				fonts[i].AutoOutlineThickness = in->ReadInt32();
 				fonts[i].AutoOutlineStyle =
-				    static_cast<enum FontInfo::AutoOutlineStyle>(in->ReadInt32());
+					static_cast<enum FontInfo::AutoOutlineStyle>(in->ReadInt32());
 			}
 		}
 	}
@@ -247,7 +249,7 @@ void GameSetupStruct::read_messages(Common::Stream *in, GameDataVersion data_ver
 		} else
 			read_string_decrypt(in, messages[ee], GLOBALMESLENGTH);
 	}
-	delete [] load_messages;
+	delete[] load_messages;
 	load_messages = nullptr;
 }
 
@@ -349,7 +351,7 @@ void GameSetupStruct::ReadAudioClips_Aligned(Common::Stream *in, size_t count) {
 }
 
 void GameSetupStruct::ReadFromSaveGame_v321(Stream *in, char *gswas, ccScript *compsc, CharacterInfo *chwas,
-        WordsDictionary *olddict, char **mesbk) {
+	WordsDictionary *olddict, char **mesbk) {
 	int bb;
 
 	ReadInvInfo_Aligned(in);
@@ -382,7 +384,7 @@ void ConvertOldGameStruct(OldGameSetupStruct *ogss, GameSetupStruct *gss) {
 	for (int i = 0; i < 20; i++)
 		gss->options[i] = ogss->options[i];
 	memcpy(&gss->paluses[0], &ogss->paluses[0], 256);
-	memcpy(&gss->defpal[0],  &ogss->defpal[0],  256 * sizeof(color));
+	memcpy(&gss->defpal[0], &ogss->defpal[0], 256 * sizeof(color));
 	gss->numviews = ogss->numviews;
 	gss->numcharacters = ogss->numcharacters;
 	gss->playercharacter = ogss->playercharacter;
@@ -443,3 +445,5 @@ void GameSetupStruct::WriteForSavegame(PStream out) {
 	out->WriteInt32(invhotdotsprite);
 	out->WriteInt32(default_lipsync_frame);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/shared/ac/gamesetupstructbase.cpp b/engines/ags/shared/ac/gamesetupstructbase.cpp
index cd1caef360..9781d3a4a5 100644
--- a/engines/ags/shared/ac/gamesetupstructbase.cpp
+++ b/engines/ags/shared/ac/gamesetupstructbase.cpp
@@ -27,6 +27,8 @@
 #include "script/cc_script.h"
 #include "util/stream.h"
 
+namespace AGS3 {
+
 using AGS::Shared::Stream;
 
 GameSetupStructBase::GameSetupStructBase()
@@ -251,3 +253,5 @@ Size ResolutionTypeToSize(GameResolutionType resolution, bool letterbox) {
 	}
 	return Size();
 }
+
+} // namespace AGS3
diff --git a/engines/ags/shared/ac/inventoryiteminfo.cpp b/engines/ags/shared/ac/inventoryiteminfo.cpp
index 0a34dbaa8f..3311180c2a 100644
--- a/engines/ags/shared/ac/inventoryiteminfo.cpp
+++ b/engines/ags/shared/ac/inventoryiteminfo.cpp
@@ -24,6 +24,8 @@
 #include "util/stream.h"
 #include "util/string_utils.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 void InventoryItemInfo::ReadFromFile(Stream *in) {
@@ -57,3 +59,5 @@ void InventoryItemInfo::WriteToSavegame(Stream *out) const {
 	out->WriteInt32(pic);
 	out->WriteInt32(cursorPic);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/shared/ac/mousecursor.cpp b/engines/ags/shared/ac/mousecursor.cpp
index 86548b2972..01f9323b92 100644
--- a/engines/ags/shared/ac/mousecursor.cpp
+++ b/engines/ags/shared/ac/mousecursor.cpp
@@ -23,6 +23,8 @@
 #include "ac/mousecursor.h"
 #include "util/stream.h"
 
+namespace AGS3 {
+
 using AGS::Shared::Stream;
 
 MouseCursor::MouseCursor() {
@@ -67,3 +69,5 @@ void MouseCursor::WriteToSavegame(Stream *out) const {
 	out->WriteInt32(view);
 	out->WriteInt32(flags);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/shared/ac/spritecache.cpp b/engines/ags/shared/ac/spritecache.cpp
index 178d9ebf65..592c6665d7 100644
--- a/engines/ags/shared/ac/spritecache.cpp
+++ b/engines/ags/shared/ac/spritecache.cpp
@@ -42,6 +42,8 @@
 #include "util/file.h"
 #include "util/stream.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 // [IKM] We have to forward-declare these because their implementations are in the Engine
@@ -219,7 +221,7 @@ sprkey_t SpriteCache::GetFreeIndex() {
 
 bool SpriteCache::SpriteData::DoesSpriteExist() const {
 	return (Image != nullptr) || // HAS loaded bitmap
-	       ((Flags & SPRCACHEFLAG_ISASSET) != 0); // OR found in the game resources
+		((Flags & SPRCACHEFLAG_ISASSET) != 0); // OR found in the game resources
 }
 
 bool SpriteCache::SpriteData::IsAssetSprite() const {
@@ -228,8 +230,8 @@ bool SpriteCache::SpriteData::IsAssetSprite() const {
 
 bool SpriteCache::SpriteData::IsExternalSprite() const {
 	return (Image != nullptr) &&  // HAS loaded bitmap
-	       ((Flags & SPRCACHEFLAG_ISASSET) == 0) && // AND NOT found in game resources
-	       ((Flags & SPRCACHEFLAG_REMAPPED) == 0); // AND was NOT remapped to another sprite
+		((Flags & SPRCACHEFLAG_ISASSET) == 0) && // AND NOT found in game resources
+		((Flags & SPRCACHEFLAG_REMAPPED) == 0); // AND was NOT remapped to another sprite
 }
 
 bool SpriteCache::SpriteData::IsLocked() const {
@@ -323,7 +325,7 @@ void SpriteCache::DisposeOldest() {
 			// There must be a bug somewhere causing this, but for now
 			// let's just reset the cache
 			Debug::Printf(kDbgGroup_SprCache, kDbgMsg_Error, "RUNTIME CACHE ERROR: CACHE INCONSISTENT: RESETTING\n\tAt size %d (of %d), start %d end %d  fwdlink=%d",
-			              _cacheSize, _maxCacheSize, oldstart, _listend, _liststart);
+				_cacheSize, _maxCacheSize, oldstart, _listend, _liststart);
 			DisposeAll();
 		}
 	}
@@ -338,7 +340,7 @@ void SpriteCache::DisposeAll() {
 	_listend = -1;
 	for (size_t i = 0; i < _spriteData.size(); ++i) {
 		if (!_spriteData[i].IsLocked() && // not locked
-		        _spriteData[i].IsAssetSprite()) { // sprite from game resource
+			_spriteData[i].IsAssetSprite()) { // sprite from game resource
 			delete _spriteData[i].Image;
 			_spriteData[i].Image = nullptr;
 		}
@@ -602,7 +604,7 @@ int SpriteCache::SaveToFile(const char *filename, bool compressOutput, SpriteFil
 
 		if (this->_compressed != compressOutput) {
 			// shouldn't be able to get here
-			delete [] memBuffer;
+			delete[] memBuffer;
 			delete output;
 			return -2;
 		}
@@ -635,7 +637,7 @@ int SpriteCache::SaveToFile(const char *filename, bool compressOutput, SpriteFil
 		output->WriteArray(memBuffer, sizeToCopy, 1);
 	}
 
-	delete [] memBuffer;
+	delete[] memBuffer;
 	delete output;
 
 	index.SpriteFileIDCheck = spriteFileIDCheck;
@@ -840,9 +842,9 @@ bool SpriteCache::LoadSpriteIndexFile(const char *filename, int expectedFileID,
 		}
 	}
 
-	delete [] rspritewidths;
-	delete [] rspriteheights;
-	delete [] spriteoffs;
+	delete[] rspritewidths;
+	delete[] rspriteheights;
+	delete[] spriteoffs;
 	delete fidx;
 	return true;
 }
@@ -862,3 +864,5 @@ int SpriteCache::AttachFile(const char *filename) {
 bool SpriteCache::IsFileCompressed() const {
 	return _compressed;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/shared/ac/view.cpp b/engines/ags/shared/ac/view.cpp
index e6299ebf54..d9ef44ff66 100644
--- a/engines/ags/shared/ac/view.cpp
+++ b/engines/ags/shared/ac/view.cpp
@@ -24,6 +24,8 @@
 #include "ac/view.h"
 #include "util/alignedstream.h"
 
+namespace AGS3 {
+
 using AGS::Shared::AlignedStream;
 using AGS::Shared::Stream;
 
@@ -177,7 +179,7 @@ void Convert272ViewsToNew(const std::vector<ViewStruct272> &oldv, ViewStruct *ne
 			newv[a].loops[b].Initialize(oldv[a].numframes[b]);
 
 			if ((oldv[a].numframes[b] > 0) &&
-			        (oldv[a].frames[b][oldv[a].numframes[b] - 1].pic == -1)) {
+				(oldv[a].frames[b][oldv[a].numframes[b] - 1].pic == -1)) {
 				newv[a].loops[b].flags = LOOPFLAG_RUNNEXTLOOP;
 				newv[a].loops[b].numFrames--;
 			} else
@@ -188,3 +190,5 @@ void Convert272ViewsToNew(const std::vector<ViewStruct272> &oldv, ViewStruct *ne
 		}
 	}
 }
+
+} // namespace AGS3
diff --git a/engines/ags/shared/ac/wordsdictionary.cpp b/engines/ags/shared/ac/wordsdictionary.cpp
index 2cddfd73b5..5f7d1381d5 100644
--- a/engines/ags/shared/ac/wordsdictionary.cpp
+++ b/engines/ags/shared/ac/wordsdictionary.cpp
@@ -26,6 +26,8 @@
 #include "util/stream.h"
 #include "util/string_compat.h"
 
+namespace AGS3 {
+
 using AGS::Shared::Stream;
 
 WordsDictionary::WordsDictionary()
@@ -52,9 +54,9 @@ void WordsDictionary::allocate_memory(int wordCount) {
 
 void WordsDictionary::free_memory() {
 	if (num_words > 0) {
-		delete [] word[0];
-		delete [] word;
-		delete [] wordnum;
+		delete[] word[0];
+		delete[] word;
+		delete[] wordnum;
 		word = nullptr;
 		wordnum = nullptr;
 		num_words = 0;
@@ -66,7 +68,7 @@ void WordsDictionary::sort() {
 	for (aa = 0; aa < num_words; aa++) {
 		for (bb = aa + 1; bb < num_words; bb++) {
 			if (((wordnum[aa] == wordnum[bb]) && (ags_stricmp(word[aa], word[bb]) > 0))
-			        || (wordnum[aa] > wordnum[bb])) {
+				|| (wordnum[aa] > wordnum[bb])) {
 				short temp = wordnum[aa];
 				char tempst[30];
 
@@ -172,3 +174,5 @@ void write_dictionary(WordsDictionary *dict, Stream *out) {
 		out->WriteInt16(dict->wordnum[ii]);//__putshort__lilendian(dict->wordnum[ii], writeto);
 	}
 }
+
+} // namespace AGS3
diff --git a/engines/ags/shared/core/asset.cpp b/engines/ags/shared/core/asset.cpp
index ce99ec5615..7c34675faf 100644
--- a/engines/ags/shared/core/asset.cpp
+++ b/engines/ags/shared/core/asset.cpp
@@ -22,6 +22,7 @@
 
 #include "core/asset.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Shared {
 
@@ -39,3 +40,4 @@ void AssetLibInfo::Unload() {
 
 } // namespace Shared
 } // namespace AGS
+} // namespace AGS3
diff --git a/engines/ags/shared/core/assetmanager.cpp b/engines/ags/shared/core/assetmanager.cpp
index 1fe72e4797..3017592cb1 100644
--- a/engines/ags/shared/core/assetmanager.cpp
+++ b/engines/ags/shared/core/assetmanager.cpp
@@ -26,7 +26,7 @@
 #include "util/path.h"
 #include "util/string_utils.h"
 
-
+namespace AGS3 {
 namespace AGS {
 namespace Shared {
 
@@ -145,8 +145,8 @@ AssetError AssetManager::ReadDataFileTOC(const String &data_file, AssetLibInfo &
 }
 
 /* static */ Stream *AssetManager::OpenAsset(const String &asset_name,
-        FileOpenMode open_mode,
-        FileWorkMode work_mode) {
+	FileOpenMode open_mode,
+	FileWorkMode work_mode) {
 	assert(_theAssetManager != NULL);
 	if (!_theAssetManager) {
 		return nullptr;
@@ -240,7 +240,7 @@ const AssetLibInfo &AssetManager::_GetLibraryTOC() const {
 
 bool AssetManager::_DoesAssetExist(const String &asset_name) {
 	return FindAssetByFileName(asset_name) != nullptr ||
-	       File::TestReadFile(asset_name);
+		File::TestReadFile(asset_name);
 }
 
 AssetError AssetManager::RegisterAssetLib(const String &data_file, const String &password) {
@@ -330,11 +330,11 @@ bool AssetManager::GetAssetByPriority(const String &asset_name, AssetLocation &l
 	if (_searchPriority == kAssetPriorityDir) {
 		// check for disk, otherwise use datafile
 		return GetAssetFromDir(asset_name, loc, open_mode, work_mode) ||
-		       GetAssetFromLib(asset_name, loc, open_mode, work_mode);
+			GetAssetFromLib(asset_name, loc, open_mode, work_mode);
 	} else if (_searchPriority == kAssetPriorityLib) {
 		// check datafile first, then scan directory
 		return GetAssetFromLib(asset_name, loc, open_mode, work_mode) ||
-		       GetAssetFromDir(asset_name, loc, open_mode, work_mode);
+			GetAssetFromDir(asset_name, loc, open_mode, work_mode);
 	}
 	return false;
 }
@@ -369,3 +369,4 @@ String GetAssetErrorText(AssetError err) {
 
 } // namespace Shared
 } // namespace AGS
+} // namespace AGS3
diff --git a/engines/ags/shared/debugging/debugmanager.cpp b/engines/ags/shared/debugging/debugmanager.cpp
index 180e06c97f..69800cc25f 100644
--- a/engines/ags/shared/debugging/debugmanager.cpp
+++ b/engines/ags/shared/debugging/debugmanager.cpp
@@ -24,6 +24,7 @@
 #include "debug/debugmanager.h"
 #include "util/string_types.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Shared {
 
@@ -88,7 +89,7 @@ void DebugOutput::ResolveGroupID(DebugGroupID id) {
 	}
 }
 
-bool DebugOutput::TestGroup(DebugGroupID id,  MessageType mt) const {
+bool DebugOutput::TestGroup(DebugGroupID id, MessageType mt) const {
 	DebugGroupID real_id = DbgMgr.GetGroup(id).UID;
 	if (real_id.ID == kDbgGroup_None || real_id.ID >= _groupFilter.size())
 		return false;
@@ -224,5 +225,6 @@ void Printf(DebugGroupID group, MessageType mt, const char *fmt, ...) {
 
 } // namespace Debug
 
-}   // namespace Shared
-}   // namespace AGS
+} // namespace Shared
+} // namespace AGS
+} // namespace AGS3
diff --git a/engines/ags/shared/font/fonts.cpp b/engines/ags/shared/font/fonts.cpp
index 77493dd202..6acbebd152 100644
--- a/engines/ags/shared/font/fonts.cpp
+++ b/engines/ags/shared/font/fonts.cpp
@@ -32,6 +32,8 @@
 #include "gui/guidefines.h" // MAXLINE
 #include "util/string_utils.h"
 
+namespace AGS3 {
+
 #define STD_BUFFER_SIZE 3000
 
 using namespace AGS::Shared;
@@ -40,8 +42,8 @@ namespace AGS {
 namespace Shared {
 
 struct Font {
-	IAGSFontRenderer   *Renderer;
-	IAGSFontRenderer2  *Renderer2;
+	IAGSFontRenderer *Renderer;
+	IAGSFontRenderer2 *Renderer2;
 	FontInfo            Info;
 
 	Font();
@@ -327,10 +329,10 @@ bool wloadfont_size(size_t fontNumber, const FontInfo &font_info) {
 	params.SizeMultiplier = font_info.SizeMultiplier;
 
 	if (ttfRenderer.LoadFromDiskEx(fontNumber, font_info.SizePt, &params)) {
-		fonts[fontNumber].Renderer  = &ttfRenderer;
+		fonts[fontNumber].Renderer = &ttfRenderer;
 		fonts[fontNumber].Renderer2 = &ttfRenderer;
 	} else if (wfnRenderer.LoadFromDiskEx(fontNumber, font_info.SizePt, &params)) {
-		fonts[fontNumber].Renderer  = &wfnRenderer;
+		fonts[fontNumber].Renderer = &wfnRenderer;
 		fonts[fontNumber].Renderer2 = &wfnRenderer;
 	}
 
@@ -371,3 +373,5 @@ void free_all_fonts() {
 	}
 	fonts.clear();
 }
+
+} // namespace AGS3
diff --git a/engines/ags/shared/font/ttffontrenderer.cpp b/engines/ags/shared/font/ttffontrenderer.cpp
index 73ec388d23..6dfc35161c 100644
--- a/engines/ags/shared/font/ttffontrenderer.cpp
+++ b/engines/ags/shared/font/ttffontrenderer.cpp
@@ -34,6 +34,8 @@
 #include "font/fonts.h"
 #endif
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 // project-specific implementation
@@ -119,7 +121,7 @@ bool TTFFontRenderer::LoadFromDiskEx(int fontNumber, int fontSize, const FontRen
 	// A simple workaround is to disable outline fonts for it and use
 	// automatic outline drawing.
 	if (get_font_outline(fontNumber) >= 0 &&
-	        strcmp(alfont_get_name(alfptr), "LucasFan-Font") == 0)
+		strcmp(alfont_get_name(alfptr), "LucasFan-Font") == 0)
 		set_font_outline(fontNumber, FONT_OUTLINE_AUTO);
 #endif
 	if (fontSize == 0)
@@ -138,3 +140,5 @@ void TTFFontRenderer::FreeMemory(int fontNumber) {
 	alfont_destroy_font(_fontData[fontNumber].AlFont);
 	_fontData.erase(fontNumber);
 }
+
+} // namespace AGS3
diff --git a/engines/ags/shared/font/wfnfont.cpp b/engines/ags/shared/font/wfnfont.cpp
index b891aff8cf..da07dead4f 100644
--- a/engines/ags/shared/font/wfnfont.cpp
+++ b/engines/ags/shared/font/wfnfont.cpp
@@ -26,11 +26,13 @@
 #include "util/memory.h"
 #include "util/stream.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
-static const char   *WFN_FILE_SIGNATURE  = "WGT Font File  ";
+static const char *WFN_FILE_SIGNATURE = "WGT Font File  ";
 static const size_t  WFN_FILE_SIG_LENGTH = 15;
-static const size_t  MinCharDataSize     = sizeof(uint16_t) * 2;
+static const size_t  MinCharDataSize = sizeof(uint16_t) * 2;
 
 WFNChar::WFNChar()
 	: Width(0)
@@ -99,7 +101,7 @@ WFNError WFNFont::ReadFromFile(Stream *in, const soff_t data_size) {
 		const uint16_t off = offset_table[i];
 		if (off < raw_data_offset || off + MinCharDataSize > table_addr) {
 			Debug::Printf("\tWFN: character %d -- bad item offset: %d (%d - %d, +%d)",
-			              i, off, raw_data_offset, table_addr, MinCharDataSize);
+				i, off, raw_data_offset, table_addr, MinCharDataSize);
 			err = kWFNErr_HasBadCharacters; // warn about potentially corrupt format
 			continue; // bad character offset
 		}
@@ -115,7 +117,7 @@ WFNError WFNFont::ReadFromFile(Stream *in, const soff_t data_size) {
 	size_t total_pixel_size = 0;
 	for (size_t i = 0; i < _items.size(); ++i) {
 		const uint8_t *p_data = raw_data + offs[i] - raw_data_offset;
-		init_ch.Width  = Memory::ReadInt16LE(p_data);
+		init_ch.Width = Memory::ReadInt16LE(p_data);
 		init_ch.Height = Memory::ReadInt16LE(p_data + sizeof(uint16_t));
 		total_pixel_size += init_ch.GetRequiredPixelSize();
 		_items[i] = init_ch;
@@ -133,12 +135,12 @@ WFNError WFNFont::ReadFromFile(Stream *in, const soff_t data_size) {
 			err = kWFNErr_HasBadCharacters;
 			continue; // just an empty character
 		}
-		const uint16_t raw_off  = offs[i] - raw_data_offset + MinCharDataSize; // offset in raw array
+		const uint16_t raw_off = offs[i] - raw_data_offset + MinCharDataSize; // offset in raw array
 		size_t src_size = pixel_data_size;
 		if (i + 1 != _items.size() && raw_off + src_size > offs[i + 1] - raw_data_offset) {
 			// character pixel data overlaps next character
 			Debug::Printf("\tWFN: item at off %d -- pixel data overlaps next known item (at %d, +%d)",
-			              offs[i], offs[i + 1], MinCharDataSize + src_size);
+				offs[i], offs[i + 1], MinCharDataSize + src_size);
 			err = kWFNErr_HasBadCharacters; // warn about potentially corrupt format
 			src_size = offs[i + 1] - offs[i] - MinCharDataSize;
 		}
@@ -146,7 +148,7 @@ WFNError WFNFont::ReadFromFile(Stream *in, const soff_t data_size) {
 		if (raw_off + src_size > total_char_data) {
 			// character pixel data overflow buffer
 			Debug::Printf("\tWFN: item at off %d -- pixel data exceeds available data (at %d, +%d)",
-			              offs[i], table_addr, MinCharDataSize + src_size);
+				offs[i], table_addr, MinCharDataSize + src_size);
 			err = kWFNErr_HasBadCharacters; // warn about potentially corrupt format
 			src_size = total_char_data - raw_off;
 		}
@@ -173,13 +175,15 @@ WFNError WFNFont::ReadFromFile(Stream *in, const soff_t data_size) {
 				// we know beforehand that such item must exist
 				std::vector<uint16_t>::const_iterator at = std::lower_bound(offs.begin(), offs.end(), off);
 				assert(at != offs.end() && *at == off && // should not normally fail
-				       at - offs.begin() >= 0 && static_cast<size_t>(at - offs.begin()) < _items.size());
+					at - offs.begin() >= 0 && static_cast<size_t>(at - offs.begin()) < _items.size());
 				_refs[i] = &_items[at - offs.begin()]; // set up reference to item
 			}
 		}
 	}
 
-	delete [] raw_data;
-	delete [] offset_table;
+	delete[] raw_data;
+	delete[] offset_table;
 	return err;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/shared/font/wfnfontrenderer.cpp b/engines/ags/shared/font/wfnfontrenderer.cpp
index 559e88a2e4..3366805408 100644
--- a/engines/ags/shared/font/wfnfontrenderer.cpp
+++ b/engines/ags/shared/font/wfnfontrenderer.cpp
@@ -28,6 +28,8 @@
 #include "gfx/bitmap.h"
 #include "util/stream.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
 static unsigned char GetCharCode(unsigned char wanted_code, const WFNFont *font) {
@@ -104,7 +106,7 @@ int RenderChar(Bitmap *ds, const int at_x, const int at_y, const WFNChar &wfn_ch
 			if (((actdata[h * bytewid + (w / 8)] & (0x80 >> (w % 8))) != 0)) {
 				if (scale > 1) {
 					ds->FillRect(Rect(x + w, y + h, x + w + (scale - 1),
-					                  y + h + (scale - 1)), text_color);
+						y + h + (scale - 1)), text_color);
 				} else {
 					ds->PutPixel(x + w, y + h, text_color);
 				}
@@ -162,3 +164,5 @@ void WFNFontRenderer::FreeMemory(int fontNumber) {
 bool WFNFontRenderer::SupportsExtendedCharacters(int fontNumber) {
 	return _fontData[fontNumber].Font->GetCharCount() > 128;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/shared/game/customproperties.cpp b/engines/ags/shared/game/customproperties.cpp
index 96440c7739..be148873fa 100644
--- a/engines/ags/shared/game/customproperties.cpp
+++ b/engines/ags/shared/game/customproperties.cpp
@@ -24,6 +24,7 @@
 #include "util/stream.h"
 #include "util/string_utils.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Shared {
 
@@ -44,7 +45,7 @@ namespace Properties {
 PropertyError ReadSchema(PropertySchema &schema, Stream *in) {
 	PropertyVersion version = (PropertyVersion)in->ReadInt32();
 	if (version < kPropertyVersion_Initial ||
-	        version > kPropertyVersion_Current) {
+		version > kPropertyVersion_Current) {
 		return kPropertyErr_UnsupportedFormat;
 	}
 
@@ -74,7 +75,7 @@ void WriteSchema(const PropertySchema &schema, Stream *out) {
 	out->WriteInt32(kPropertyVersion_Current);
 	out->WriteInt32(schema.size());
 	for (PropertySchema::const_iterator it = schema.begin();
-	        it != schema.end(); ++it) {
+		it != schema.end(); ++it) {
 		const PropertyDesc &prop = it->second;
 		StrUtil::WriteString(prop.Name, out);
 		out->WriteInt32(prop.Type);
@@ -86,19 +87,19 @@ void WriteSchema(const PropertySchema &schema, Stream *out) {
 PropertyError ReadValues(StringIMap &map, Stream *in) {
 	PropertyVersion version = (PropertyVersion)in->ReadInt32();
 	if (version < kPropertyVersion_Initial ||
-	        version > kPropertyVersion_Current) {
+		version > kPropertyVersion_Current) {
 		return kPropertyErr_UnsupportedFormat;
 	}
 
 	int count = in->ReadInt32();
 	if (version == kPropertyVersion_Initial) {
 		for (int i = 0; i < count; ++i) {
-			String name  = String::FromStream(in, LEGACY_MAX_CUSTOM_PROP_NAME_LENGTH);
+			String name = String::FromStream(in, LEGACY_MAX_CUSTOM_PROP_NAME_LENGTH);
 			map[name] = String::FromStream(in, LEGACY_MAX_CUSTOM_PROP_VALUE_LENGTH);
 		}
 	} else {
 		for (int i = 0; i < count; ++i) {
-			String name  = StrUtil::ReadString(in);
+			String name = StrUtil::ReadString(in);
 			map[name] = StrUtil::ReadString(in);
 		}
 	}
@@ -109,7 +110,7 @@ void WriteValues(const StringIMap &map, Stream *out) {
 	out->WriteInt32(kPropertyVersion_Current);
 	out->WriteInt32(map.size());
 	for (StringIMap::const_iterator it = map.begin();
-	        it != map.end(); ++it) {
+		it != map.end(); ++it) {
 		StrUtil::WriteString(it->first, out);
 		StrUtil::WriteString(it->second, out);
 	}
@@ -119,3 +120,4 @@ void WriteValues(const StringIMap &map, Stream *out) {
 
 } // namespace Shared
 } // namespace AGS
+} // namespace AGS3
diff --git a/engines/ags/shared/game/interactions.cpp b/engines/ags/shared/game/interactions.cpp
index 6c53f14a00..69cece5967 100644
--- a/engines/ags/shared/game/interactions.cpp
+++ b/engines/ags/shared/game/interactions.cpp
@@ -26,9 +26,11 @@
 #include "util/alignedstream.h"
 #include "util/math.h"
 
+namespace AGS3 {
+
 using namespace AGS::Shared;
 
-InteractionVariable globalvars[MAX_GLOBAL_VARIABLES] = {InteractionVariable("Global 1", 0, 0)};
+InteractionVariable globalvars[MAX_GLOBAL_VARIABLES] = { InteractionVariable("Global 1", 0, 0) };
 int numGlobalVars = 1;
 
 namespace AGS {
@@ -41,7 +43,7 @@ InteractionValue::InteractionValue() {
 }
 
 void InteractionValue::Read(Stream *in) {
-	Type  = (InterValType)in->ReadInt8();
+	Type = (InterValType)in->ReadInt8();
 	Value = in->ReadInt32();
 	Extra = in->ReadInt32();
 }
@@ -345,7 +347,7 @@ InteractionVariable::InteractionVariable(const String &name, char type, int val)
 
 void InteractionVariable::Read(Stream *in) {
 	Name.ReadCount(in, INTER_VAR_NAME_LENGTH);
-	Type  = in->ReadInt8();
+	Type = in->ReadInt8();
 	Value = in->ReadInt32();
 }
 
@@ -374,3 +376,4 @@ InteractionScripts *InteractionScripts::CreateFromStream(Stream *in) {
 
 } // namespace Shared
 } // namespace AGS
+} // namespace AGS3
diff --git a/engines/ags/shared/game/main_game_file.cpp b/engines/ags/shared/game/main_game_file.cpp
index f02e9c10f1..847f894f6d 100644
--- a/engines/ags/shared/game/main_game_file.cpp
+++ b/engines/ags/shared/game/main_game_file.cpp
@@ -39,6 +39,7 @@
 #include "util/string_utils.h"
 #include "font/fonts.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Shared {
 
@@ -111,7 +112,7 @@ bool IsMainGameLibrary(const String &filename) {
 		return false;
 	for (size_t i = 0; i < lib.AssetInfos.size(); ++i) {
 		if (lib.AssetInfos[i].FileName.CompareNoCase(MainGameSource::DefaultFilename_v3) == 0 ||
-		        lib.AssetInfos[i].FileName.CompareNoCase(MainGameSource::DefaultFilename_v2) == 0) {
+			lib.AssetInfos[i].FileName.CompareNoCase(MainGameSource::DefaultFilename_v2) == 0) {
 			return true;
 		}
 	}
@@ -132,7 +133,7 @@ HGameFileError OpenMainGameFileBase(PStream &in, MainGameSource &src) {
 		return new MainGameFileError(kMGFErr_FormatVersionTooOld, String::FromFormat("Required format version: %d, supported %d - %d", src.DataVersion, kGameVersion_250, kGameVersion_Current));
 	if (src.DataVersion > kGameVersion_Current)
 		return new MainGameFileError(kMGFErr_FormatVersionNotSupported,
-		                             String::FromFormat("Game was compiled with %s. Required format version: %d, supported %d - %d", src.CompiledWith.GetCStr(), src.DataVersion, kGameVersion_250, kGameVersion_Current));
+			String::FromFormat("Game was compiled with %s. Required format version: %d, supported %d - %d", src.CompiledWith.GetCStr(), src.DataVersion, kGameVersion_250, kGameVersion_Current));


Commit: 6c8789264de31c8a4350c32c1cab10a946828703
    https://github.com/scummvm/scummvm/commit/6c8789264de31c8a4350c32c1cab10a946828703
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added shared/util/ folder

Changed paths:
  A engines/ags/shared/util/stdio_compat.cpp
  A engines/ags/shared/util/string_compat.cpp
  A engines/ags/std/algorithm.h
  R engines/ags/shared/util/stdio_compat.c
  R engines/ags/shared/util/string_compat.c
    engines/ags/engine/ac/global_video.cpp
    engines/ags/engine/ac/keycode.cpp
    engines/ags/engine/gfx/ali3dsw.h
    engines/ags/engine/gfx/ogl_headers.h
    engines/ags/engine/platform/android/acpland.cpp
    engines/ags/engine/platform/ios/acplios.cpp
    engines/ags/engine/platform/linux/acpllnx.cpp
    engines/ags/engine/platform/windows/acplwin.cpp
    engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
    engines/ags/engine/platform/windows/gfx/ali3dd3d.h
    engines/ags/engine/platform/windows/media/video/acwavi.cpp
    engines/ags/engine/platform/windows/media/video/acwavi3d.cpp
    engines/ags/engine/platform/windows/win_ex_handling.cpp
    engines/ags/module.mk
    engines/ags/shared/ac/audiocliptype.cpp
    engines/ags/shared/ac/characterinfo.cpp
    engines/ags/shared/ac/characterinfo.h
    engines/ags/shared/ac/common.cpp
    engines/ags/shared/ac/common_defines.h
    engines/ags/shared/ac/dialogtopic.cpp
    engines/ags/shared/ac/dynobj/scriptaudioclip.cpp
    engines/ags/shared/ac/dynobj/scriptaudioclip.h
    engines/ags/shared/ac/gamesetupstruct.cpp
    engines/ags/shared/ac/gamesetupstruct.h
    engines/ags/shared/ac/gamesetupstructbase.cpp
    engines/ags/shared/ac/gamesetupstructbase.h
    engines/ags/shared/ac/gamestructdefines.h
    engines/ags/shared/ac/interfaceelement.h
    engines/ags/shared/ac/inventoryiteminfo.cpp
    engines/ags/shared/ac/mousecursor.cpp
    engines/ags/shared/ac/oldgamesetupstruct.h
    engines/ags/shared/ac/spritecache.cpp
    engines/ags/shared/ac/spritecache.h
    engines/ags/shared/ac/view.cpp
    engines/ags/shared/ac/view.h
    engines/ags/shared/ac/wordsdictionary.cpp
    engines/ags/shared/ac/wordsdictionary.h
    engines/ags/shared/api/stream_api.h
    engines/ags/shared/core/asset.cpp
    engines/ags/shared/core/asset.h
    engines/ags/shared/core/assetmanager.cpp
    engines/ags/shared/core/assetmanager.h
    engines/ags/shared/core/platform.h
    engines/ags/shared/core/types.h
    engines/ags/shared/debugging/assert.h
    engines/ags/shared/debugging/debugmanager.cpp
    engines/ags/shared/debugging/debugmanager.h
    engines/ags/shared/debugging/out.h
    engines/ags/shared/debugging/outputhandler.h
    engines/ags/shared/font/fonts.cpp
    engines/ags/shared/font/fonts.h
    engines/ags/shared/font/ttffontrenderer.cpp
    engines/ags/shared/font/ttffontrenderer.h
    engines/ags/shared/font/wfnfont.cpp
    engines/ags/shared/font/wfnfont.h
    engines/ags/shared/font/wfnfontrenderer.cpp
    engines/ags/shared/font/wfnfontrenderer.h
    engines/ags/shared/game/customproperties.cpp
    engines/ags/shared/game/customproperties.h
    engines/ags/shared/game/interactions.cpp
    engines/ags/shared/game/interactions.h
    engines/ags/shared/game/main_game_file.cpp
    engines/ags/shared/game/main_game_file.h
    engines/ags/shared/game/plugininfo.h
    engines/ags/shared/game/room_file.cpp
    engines/ags/shared/game/room_file.h
    engines/ags/shared/game/room_file_deprecated.cpp
    engines/ags/shared/game/roomstruct.cpp
    engines/ags/shared/game/roomstruct.h
    engines/ags/shared/gfx/allegrobitmap.cpp
    engines/ags/shared/gfx/allegrobitmap.h
    engines/ags/shared/gfx/bitmap.cpp
    engines/ags/shared/gfx/bitmap.h
    engines/ags/shared/gui/guibutton.cpp
    engines/ags/shared/gui/guibutton.h
    engines/ags/shared/gui/guiinv.cpp
    engines/ags/shared/gui/guiinv.h
    engines/ags/shared/gui/guilabel.cpp
    engines/ags/shared/gui/guilabel.h
    engines/ags/shared/gui/guilistbox.cpp
    engines/ags/shared/gui/guilistbox.h
    engines/ags/shared/gui/guimain.cpp
    engines/ags/shared/gui/guimain.h
    engines/ags/shared/gui/guiobject.cpp
    engines/ags/shared/gui/guiobject.h
    engines/ags/shared/gui/guislider.cpp
    engines/ags/shared/gui/guislider.h
    engines/ags/shared/gui/guitextbox.cpp
    engines/ags/shared/gui/guitextbox.h
    engines/ags/shared/script/cc_error.cpp
    engines/ags/shared/script/cc_error.h
    engines/ags/shared/script/cc_options.cpp
    engines/ags/shared/script/cc_script.cpp
    engines/ags/shared/script/cc_script.h
    engines/ags/shared/util/alignedstream.cpp
    engines/ags/shared/util/alignedstream.h
    engines/ags/shared/util/bbop.h
    engines/ags/shared/util/bufferedstream.cpp
    engines/ags/shared/util/bufferedstream.h
    engines/ags/shared/util/compress.cpp
    engines/ags/shared/util/compress.h
    engines/ags/shared/util/datastream.cpp
    engines/ags/shared/util/datastream.h
    engines/ags/shared/util/directory.cpp
    engines/ags/shared/util/directory.h
    engines/ags/shared/util/error.h
    engines/ags/shared/util/file.cpp
    engines/ags/shared/util/file.h
    engines/ags/shared/util/filestream.cpp
    engines/ags/shared/util/filestream.h
    engines/ags/shared/util/geometry.cpp
    engines/ags/shared/util/geometry.h
    engines/ags/shared/util/ini_util.cpp
    engines/ags/shared/util/ini_util.h
    engines/ags/shared/util/inifile.cpp
    engines/ags/shared/util/inifile.h
    engines/ags/shared/util/lzw.cpp
    engines/ags/shared/util/lzw.h
    engines/ags/shared/util/memory.h
    engines/ags/shared/util/misc.cpp
    engines/ags/shared/util/misc.h
    engines/ags/shared/util/multifilelib.h
    engines/ags/shared/util/mutifilelib.cpp
    engines/ags/shared/util/path.cpp
    engines/ags/shared/util/path.h
    engines/ags/shared/util/proxystream.cpp
    engines/ags/shared/util/proxystream.h
    engines/ags/shared/util/stdio_compat.h
    engines/ags/shared/util/stream.cpp
    engines/ags/shared/util/stream.h
    engines/ags/shared/util/string.cpp
    engines/ags/shared/util/string.h
    engines/ags/shared/util/string_compat.h
    engines/ags/shared/util/string_types.h
    engines/ags/shared/util/string_utils.cpp
    engines/ags/shared/util/string_utils.h
    engines/ags/shared/util/textreader.h
    engines/ags/shared/util/textstreamreader.cpp
    engines/ags/shared/util/textstreamreader.h
    engines/ags/shared/util/textstreamwriter.cpp
    engines/ags/shared/util/textstreamwriter.h
    engines/ags/shared/util/textwriter.h
    engines/ags/shared/util/version.cpp
    engines/ags/shared/util/version.h
    engines/ags/shared/util/wgt2allg.cpp
    engines/ags/shared/util/wgt2allg.h
    engines/ags/std/memory.h
    engines/ags/std/vector.h
    engines/ags/stubs/allegro.cpp
    engines/ags/stubs/allegro/error.cpp
    engines/ags/stubs/allegro/error.h
    engines/ags/stubs/allegro/fixed.h
    engines/ags/stubs/allegro/mouse.cpp


diff --git a/engines/ags/engine/ac/global_video.cpp b/engines/ags/engine/ac/global_video.cpp
index 0aa8b375da..718e91fbde 100644
--- a/engines/ags/engine/ac/global_video.cpp
+++ b/engines/ags/engine/ac/global_video.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include <allegro.h>
+#include "ags/stubs/allegro.h"
 #include "ac/gamesetup.h"
 #include "ac/gamestate.h"
 #include "ac/global_audio.h"
diff --git a/engines/ags/engine/ac/keycode.cpp b/engines/ags/engine/ac/keycode.cpp
index 701790ee23..6e05ca1853 100644
--- a/engines/ags/engine/ac/keycode.cpp
+++ b/engines/ags/engine/ac/keycode.cpp
@@ -22,7 +22,7 @@
 
 #include "ac/keycode.h"
 
-#include <allegro.h>
+#include "ags/stubs/allegro.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gfx/ali3dsw.h b/engines/ags/engine/gfx/ali3dsw.h
index 0788549a2d..e46b5f4cc2 100644
--- a/engines/ags/engine/gfx/ali3dsw.h
+++ b/engines/ags/engine/gfx/ali3dsw.h
@@ -34,7 +34,7 @@
 #include "core/platform.h"
 #define AGS_DDRAW_GAMMA_CONTROL (AGS_PLATFORM_OS_WINDOWS)
 
-#include <allegro.h>
+#include "ags/stubs/allegro.h"
 
 #if AGS_DDRAW_GAMMA_CONTROL
 #include <winalleg.h>
diff --git a/engines/ags/engine/gfx/ogl_headers.h b/engines/ags/engine/gfx/ogl_headers.h
index 9c41aa6f14..595b4647b5 100644
--- a/engines/ags/engine/gfx/ogl_headers.h
+++ b/engines/ags/engine/gfx/ogl_headers.h
@@ -29,7 +29,7 @@
 #include "core/platform.h"
 
 #if AGS_PLATFORM_OS_WINDOWS
-#include <allegro.h>
+#include "ags/stubs/allegro.h"
 #include <winalleg.h>
 #include <allegro/platform/aintwin.h>
 
@@ -37,7 +37,7 @@
 #include "glad/glad_wgl.h"
 
 #elif AGS_PLATFORM_OS_LINUX
-#include <allegro.h>
+#include "ags/stubs/allegro.h"
 #include <xalleg.h>
 #include <X11/Xatom.h>
 
diff --git a/engines/ags/engine/platform/android/acpland.cpp b/engines/ags/engine/platform/android/acpland.cpp
index 7ce56c4d18..3b191305b5 100644
--- a/engines/ags/engine/platform/android/acpland.cpp
+++ b/engines/ags/engine/platform/android/acpland.cpp
@@ -24,7 +24,7 @@
 
 #if AGS_PLATFORM_OS_ANDROID
 
-#include <allegro.h>
+#include "ags/stubs/allegro.h"
 #include "platform/base/agsplatformdriver.h"
 #include "ac/runtime_defines.h"
 #include "main/config.h"
diff --git a/engines/ags/engine/platform/ios/acplios.cpp b/engines/ags/engine/platform/ios/acplios.cpp
index 56e80d2753..a00f5aa2d4 100644
--- a/engines/ags/engine/platform/ios/acplios.cpp
+++ b/engines/ags/engine/platform/ios/acplios.cpp
@@ -29,7 +29,7 @@
 #include <sys/stat.h>
 #include <ctype.h>
 
-#include <allegro.h>
+#include "ags/stubs/allegro.h"
 #include "platform/base/agsplatformdriver.h"
 #include "ac/runtime_defines.h"
 #include "main/config.h"
diff --git a/engines/ags/engine/platform/linux/acpllnx.cpp b/engines/ags/engine/platform/linux/acpllnx.cpp
index 092d67a2e3..826d0a39d3 100644
--- a/engines/ags/engine/platform/linux/acpllnx.cpp
+++ b/engines/ags/engine/platform/linux/acpllnx.cpp
@@ -27,7 +27,7 @@
 // ********* LINUX PLACEHOLDER DRIVER *********
 
 #include <stdio.h>
-#include <allegro.h>
+#include "ags/stubs/allegro.h"
 #include <xalleg.h>
 #include "ac/runtime_defines.h"
 #include "gfx/gfxdefines.h"
diff --git a/engines/ags/engine/platform/windows/acplwin.cpp b/engines/ags/engine/platform/windows/acplwin.cpp
index 00965b04f7..d585c214bb 100644
--- a/engines/ags/engine/platform/windows/acplwin.cpp
+++ b/engines/ags/engine/platform/windows/acplwin.cpp
@@ -27,7 +27,7 @@
 // ********* WINDOWS *********
 
 #include <string.h>
-#include <allegro.h>
+#include "ags/stubs/allegro.h"
 #include <allegro/platform/aintwin.h>
 #include "ac/common.h"
 #include "ac/draw.h"
diff --git a/engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp b/engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
index b7d06c1e35..44cdc82d7d 100644
--- a/engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
+++ b/engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
@@ -32,7 +32,7 @@
 
 #include "platform/windows/gfx/ali3dd3d.h"
 
-#include <allegro.h>
+#include "ags/stubs/allegro.h"
 #include <allegro/platform/aintwin.h>
 #include "ac/timer.h"
 #include "debug/assert.h"
diff --git a/engines/ags/engine/platform/windows/gfx/ali3dd3d.h b/engines/ags/engine/platform/windows/gfx/ali3dd3d.h
index 2833ef7ae8..ed7fdc3924 100644
--- a/engines/ags/engine/platform/windows/gfx/ali3dd3d.h
+++ b/engines/ags/engine/platform/windows/gfx/ali3dd3d.h
@@ -36,7 +36,7 @@
 #endif
 
 #include <memory>
-#include <allegro.h>
+#include "ags/stubs/allegro.h"
 #include <winalleg.h>
 #include <d3d9.h>
 #include "gfx/bitmap.h"
diff --git a/engines/ags/engine/platform/windows/media/video/acwavi.cpp b/engines/ags/engine/platform/windows/media/video/acwavi.cpp
index 1e17d09aec..741ab58b48 100644
--- a/engines/ags/engine/platform/windows/media/video/acwavi.cpp
+++ b/engines/ags/engine/platform/windows/media/video/acwavi.cpp
@@ -33,7 +33,7 @@
 #if AGS_PLATFORM_OS_WINDOWS && ! defined (AGS_NO_VIDEO_PLAYER)
 
 //#define ALLEGRO_STATICLINK  // already defined in project settings
-#include <allegro.h>
+#include "ags/stubs/allegro.h"
 #include <winalleg.h>
 #include <windows.h>
 #include <stdlib.h>
diff --git a/engines/ags/engine/platform/windows/media/video/acwavi3d.cpp b/engines/ags/engine/platform/windows/media/video/acwavi3d.cpp
index a22f02848d..0d6cab1fe1 100644
--- a/engines/ags/engine/platform/windows/media/video/acwavi3d.cpp
+++ b/engines/ags/engine/platform/windows/media/video/acwavi3d.cpp
@@ -32,7 +32,7 @@
 #if AGS_PLATFORM_OS_WINDOWS && ! defined (AGS_NO_VIDEO_PLAYER)
 
 //#define ALLEGRO_STATICLINK  // already defined in project settings
-#include <allegro.h>
+#include "ags/stubs/allegro.h"
 #include <winalleg.h>
 #include <allegro/platform/aintwin.h>
 #include <d3d9.h>
diff --git a/engines/ags/engine/platform/windows/win_ex_handling.cpp b/engines/ags/engine/platform/windows/win_ex_handling.cpp
index 3f2e35bfee..c8aba200f5 100644
--- a/engines/ags/engine/platform/windows/win_ex_handling.cpp
+++ b/engines/ags/engine/platform/windows/win_ex_handling.cpp
@@ -24,7 +24,7 @@
 
 #if AGS_PLATFORM_OS_WINDOWS
 #include <new.h>
-#include <allegro.h>
+#include "ags/stubs/allegro.h"
 #include <winalleg.h>
 #include "ac/common.h"
 #include "ac/common_defines.h"
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 5256e3b69e..4d51bd9761 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -16,7 +16,30 @@ MODULE_OBJS = \
 	stubs/allegro/mouse.o \
 	stubs/allegro/sound.o \
 	stubs/allegro/system.o \
-	stubs/allegro/unicode.o
+	stubs/allegro/unicode.o \
+	shared/util/alignedstream.o \
+	shared/util/bufferedstream.o \
+	shared/util/compress.o \
+	shared/util/datastream.o \
+	shared/util/directory.o \
+	shared/util/file.o \
+	shared/util/filestream.o \
+	shared/util/geometry.o \
+	shared/util/inifile.o \
+	shared/util/ini_util.o \
+	shared/util/lzw.o \
+	shared/util/misc.o \
+	shared/util/mutifilelib.o \
+	shared/util/path.o \
+	shared/util/proxystream.o \
+	shared/util/stream.o \
+	shared/util/string.o \
+	shared/util/string_compat.o \
+	shared/util/string_utils.o \
+	shared/util/textstreamreader.o \
+	shared/util/textstreamwriter.o \
+	shared/util/version.o \
+	shared/util/wgt2allg.o
 
 
 # This module can be built as a plugin
diff --git a/engines/ags/shared/ac/audiocliptype.cpp b/engines/ags/shared/ac/audiocliptype.cpp
index d71acd72c2..a1de83d396 100644
--- a/engines/ags/shared/ac/audiocliptype.cpp
+++ b/engines/ags/shared/ac/audiocliptype.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ac/audiocliptype.h"
-#include "util/stream.h"
+#include "ags/shared/ac/audiocliptype.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/ac/characterinfo.cpp b/engines/ags/shared/ac/characterinfo.cpp
index a6572e8d02..dcc8eeca3e 100644
--- a/engines/ags/shared/ac/characterinfo.cpp
+++ b/engines/ags/shared/ac/characterinfo.cpp
@@ -20,9 +20,9 @@
  *
  */
 
-#include <string.h>
-#include "ac/characterinfo.h"
-#include "util/stream.h"
+//include <string.h>
+#include "ags/shared/ac/characterinfo.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/ac/characterinfo.h b/engines/ags/shared/ac/characterinfo.h
index 4a448299ff..287937994a 100644
--- a/engines/ags/shared/ac/characterinfo.h
+++ b/engines/ags/shared/ac/characterinfo.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_AC_CHARACTERINFO_H
 #define AGS_SHARED_AC_CHARACTERINFO_H
 
-#include "ac/common_defines.h" // constants
+#include "ags/shared/ac/common_defines.h" // constants
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/ac/common.cpp b/engines/ags/shared/ac/common.cpp
index 74a9b6cb9d..0990898673 100644
--- a/engines/ags/shared/ac/common.cpp
+++ b/engines/ags/shared/ac/common.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ac/common.h"
-#include "util/string.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/ac/common_defines.h b/engines/ags/shared/ac/common_defines.h
index 0311a452fe..282ad7ea89 100644
--- a/engines/ags/shared/ac/common_defines.h
+++ b/engines/ags/shared/ac/common_defines.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_AC_DEFINES_H
 #define AGS_SHARED_AC_DEFINES_H
 
-#include "core/platform.h"
+#include "ags/shared/core/platform.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/ac/dialogtopic.cpp b/engines/ags/shared/ac/dialogtopic.cpp
index ac185000e3..efcbb4f2c1 100644
--- a/engines/ags/shared/ac/dialogtopic.cpp
+++ b/engines/ags/shared/ac/dialogtopic.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ac/dialogtopic.h"
-#include "util/stream.h"
+#include "ags/shared/ac/dialogtopic.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/ac/dynobj/scriptaudioclip.cpp b/engines/ags/shared/ac/dynobj/scriptaudioclip.cpp
index 4bee23fe7c..e26d5ace8c 100644
--- a/engines/ags/shared/ac/dynobj/scriptaudioclip.cpp
+++ b/engines/ags/shared/ac/dynobj/scriptaudioclip.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ac/dynobj/scriptaudioclip.h"
-#include "util/stream.h"
+#include "ags/shared/ac/dynobj/scriptaudioclip.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/ac/dynobj/scriptaudioclip.h b/engines/ags/shared/ac/dynobj/scriptaudioclip.h
index 7167a38d4f..de4361bd04 100644
--- a/engines/ags/shared/ac/dynobj/scriptaudioclip.h
+++ b/engines/ags/shared/ac/dynobj/scriptaudioclip.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_AC_DYNOBJ_SCRIPTAUDIOCLIP_H
 #define AGS_SHARED_AC_DYNOBJ_SCRIPTAUDIOCLIP_H
 
-#include "util/string.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/ac/gamesetupstruct.cpp b/engines/ags/shared/ac/gamesetupstruct.cpp
index 970b8bc997..4c4139c82b 100644
--- a/engines/ags/shared/ac/gamesetupstruct.cpp
+++ b/engines/ags/shared/ac/gamesetupstruct.cpp
@@ -20,13 +20,13 @@
  *
  */
 
-#include "ac/audiocliptype.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/oldgamesetupstruct.h"
-#include "ac/wordsdictionary.h"
-#include "ac/dynobj/scriptaudioclip.h"
-#include "game/interactions.h"
-#include "util/alignedstream.h"
+#include "ags/shared/ac/audiocliptype.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/oldgamesetupstruct.h"
+#include "ags/shared/ac/wordsdictionary.h"
+#include "ags/shared/ac/dynobj/scriptaudioclip.h"
+#include "ags/shared/game/interactions.h"
+#include "ags/shared/util/alignedstream.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/ac/gamesetupstruct.h b/engines/ags/shared/ac/gamesetupstruct.h
index 951bcfbf47..76a8be3827 100644
--- a/engines/ags/shared/ac/gamesetupstruct.h
+++ b/engines/ags/shared/ac/gamesetupstruct.h
@@ -23,15 +23,15 @@
 #ifndef AGS_SHARED_AC_GAMESETUPSTRUCT_H
 #define AGS_SHARED_AC_GAMESETUPSTRUCT_H
 
-#include <vector>
-#include "ac/audiocliptype.h"
-#include "ac/characterinfo.h" // TODO: constants to separate header
-#include "ac/gamesetupstructbase.h"
-#include "ac/inventoryiteminfo.h"
-#include "ac/mousecursor.h"
-#include "ac/dynobj/scriptaudioclip.h"
-#include "game/customproperties.h"
-#include "game/main_game_file.h" // TODO: constants to separate header or split out reading functions
+//include <vector>
+#include "ags/shared/ac/audiocliptype.h"
+#include "ags/shared/ac/characterinfo.h" // TODO: constants to separate header
+#include "ags/shared/ac/gamesetupstructbase.h"
+#include "ags/shared/ac/inventoryiteminfo.h"
+#include "ags/shared/ac/mousecursor.h"
+#include "ags/shared/ac/dynobj/scriptaudioclip.h"
+#include "ags/shared/game/customproperties.h"
+#include "ags/shared/game/main_game_file.h" // TODO: constants to separate header or split out reading functions
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/ac/gamesetupstructbase.cpp b/engines/ags/shared/ac/gamesetupstructbase.cpp
index 9781d3a4a5..2b03a199b9 100644
--- a/engines/ags/shared/ac/gamesetupstructbase.cpp
+++ b/engines/ags/shared/ac/gamesetupstructbase.cpp
@@ -20,12 +20,12 @@
  *
  */
 
-#include "ac/characterinfo.h"
-#include "ac/gamesetupstructbase.h"
-#include "ac/game_version.h"
-#include "ac/wordsdictionary.h"
-#include "script/cc_script.h"
-#include "util/stream.h"
+#include "ags/shared/ac/characterinfo.h"
+#include "ags/shared/ac/gamesetupstructbase.h"
+#include "ags/shared/ac/game_version.h"
+#include "ags/shared/ac/wordsdictionary.h"
+#include "ags/shared/script/cc_script.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/ac/gamesetupstructbase.h b/engines/ags/shared/ac/gamesetupstructbase.h
index fc9ee3cbfd..045b751634 100644
--- a/engines/ags/shared/ac/gamesetupstructbase.h
+++ b/engines/ags/shared/ac/gamesetupstructbase.h
@@ -23,10 +23,10 @@
 #ifndef AGS_SHARED_AC_GAMESETUPSTRUCTBASE_H
 #define AGS_SHARED_AC_GAMESETUPSTRUCTBASE_H
 
-#include "ac/game_version.h"
-#include "ac/gamestructdefines.h"
-#include "util/string.h"
-#include "util/wgt2allg.h" // color (allegro RGB)
+#include "ags/shared/ac/game_version.h"
+#include "ags/shared/ac/gamestructdefines.h"
+#include "ags/shared/util/string.h"
+#include "ags/shared/util/wgt2allg.h" // color (allegro RGB)
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/ac/gamestructdefines.h b/engines/ags/shared/ac/gamestructdefines.h
index e865bc296b..367796aa43 100644
--- a/engines/ags/shared/ac/gamestructdefines.h
+++ b/engines/ags/shared/ac/gamestructdefines.h
@@ -23,8 +23,8 @@
 #ifndef AGS_SHARED_AC_GAMESTRUCTDEFINES_H
 #define AGS_SHARED_AC_GAMESTRUCTDEFINES_H
 
-#include "util/geometry.h"
-#include "core/types.h"
+#include "ags/shared/util/geometry.h"
+#include "ags/shared/core/types.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/ac/interfaceelement.h b/engines/ags/shared/ac/interfaceelement.h
index 1b897de03a..69f8fcaa02 100644
--- a/engines/ags/shared/ac/interfaceelement.h
+++ b/engines/ags/shared/ac/interfaceelement.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_AC_INTERFACEELEMENT_H
 #define AGS_SHARED_AC_INTERFACEELEMENT_H
 
-#include "ac/interfacebutton.h" // InterfaceButton
+#include "ags/shared/ac/interfacebutton.h" // InterfaceButton
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/ac/inventoryiteminfo.cpp b/engines/ags/shared/ac/inventoryiteminfo.cpp
index 3311180c2a..148e1362b0 100644
--- a/engines/ags/shared/ac/inventoryiteminfo.cpp
+++ b/engines/ags/shared/ac/inventoryiteminfo.cpp
@@ -20,9 +20,9 @@
  *
  */
 
-#include "ac/inventoryiteminfo.h"
-#include "util/stream.h"
-#include "util/string_utils.h"
+#include "ags/shared/ac/inventoryiteminfo.h"
+#include "ags/shared/util/stream.h"
+#include "ags/shared/util/string_utils.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/ac/mousecursor.cpp b/engines/ags/shared/ac/mousecursor.cpp
index 01f9323b92..8acbf41b41 100644
--- a/engines/ags/shared/ac/mousecursor.cpp
+++ b/engines/ags/shared/ac/mousecursor.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ac/mousecursor.h"
-#include "util/stream.h"
+#include "ags/shared/ac/mousecursor.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/ac/oldgamesetupstruct.h b/engines/ags/shared/ac/oldgamesetupstruct.h
index 1ceb6b25c9..cbe8023b20 100644
--- a/engines/ags/shared/ac/oldgamesetupstruct.h
+++ b/engines/ags/shared/ac/oldgamesetupstruct.h
@@ -23,15 +23,15 @@
 #ifndef AGS_SHARED_AC_OLDGAMESETUPSTRUCT_H
 #define AGS_SHARED_AC_OLDGAMESETUPSTRUCT_H
 
-#include "ac/characterinfo.h"       // OldCharacterInfo, CharacterInfo
+#include "ags/shared/ac/characterinfo.h"       // OldCharacterInfo, CharacterInfo
 #ifdef UNUSED_CODE
-#include "ac/eventblock.h"       // EventBlock
+#include "ags/shared/ac/eventblock.h"       // EventBlock
 #endif
-#include "ac/interfaceelement.h"    // InterfaceElement
-#include "ac/inventoryiteminfo.h"   // InventoryItemInfo
-#include "ac/mousecursor.h"      // MouseCursor
-#include "ac/wordsdictionary.h"  // WordsDictionary
-#include "script/cc_script.h"           // ccScript
+#include "ags/shared/ac/interfaceelement.h"    // InterfaceElement
+#include "ags/shared/ac/inventoryiteminfo.h"   // InventoryItemInfo
+#include "ags/shared/ac/mousecursor.h"      // MouseCursor
+#include "ags/shared/ac/wordsdictionary.h"  // WordsDictionary
+#include "ags/shared/script/cc_script.h"           // ccScript
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/ac/spritecache.cpp b/engines/ags/shared/ac/spritecache.cpp
index 592c6665d7..3d850d7fc3 100644
--- a/engines/ags/shared/ac/spritecache.cpp
+++ b/engines/ags/shared/ac/spritecache.cpp
@@ -32,15 +32,15 @@
 #pragma warning (disable: 4996 4312)  // disable deprecation warnings
 #endif
 
-#include "ac/common.h" // quit
-#include "ac/gamestructdefines.h"
-#include "ac/spritecache.h"
-#include "core/assetmanager.h"
-#include "debug/out.h"
-#include "gfx/bitmap.h"
-#include "util/compress.h"
-#include "util/file.h"
-#include "util/stream.h"
+#include "ags/shared/ac/common.h" // quit
+#include "ags/shared/ac/gamestructdefines.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/core/assetmanager.h"
+#include "ags/shared/debugging/out.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/util/compress.h"
+#include "ags/shared/util/file.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/ac/spritecache.h b/engines/ags/shared/ac/spritecache.h
index d7a2eb3593..a6ed86f3e5 100644
--- a/engines/ags/shared/ac/spritecache.h
+++ b/engines/ags/shared/ac/spritecache.h
@@ -45,10 +45,10 @@
 #ifndef AGS_SHARED_AC_SPRITECACHE_H
 #define AGS_SHARED_AC_SPRITECACHE_H
 
-#include <memory>
-#include <vector>
-#include "core/platform.h"
-#include "util/error.h"
+//include <memory>
+//include <vector>
+#include "ags/shared/core/platform.h"
+#include "ags/shared/util/error.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/ac/view.cpp b/engines/ags/shared/ac/view.cpp
index d9ef44ff66..614258fb1d 100644
--- a/engines/ags/shared/ac/view.cpp
+++ b/engines/ags/shared/ac/view.cpp
@@ -20,9 +20,9 @@
  *
  */
 
-#include <string.h>
-#include "ac/view.h"
-#include "util/alignedstream.h"
+//include <string.h>
+#include "ags/shared/ac/view.h"
+#include "ags/shared/util/alignedstream.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/ac/view.h b/engines/ags/shared/ac/view.h
index f8dc1fc0e5..41d27ebdd8 100644
--- a/engines/ags/shared/ac/view.h
+++ b/engines/ags/shared/ac/view.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_AC_VIEW_H
 #define AGS_SHARED_AC_VIEW_H
 
-#include <vector>
+//include <vector>
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/ac/wordsdictionary.cpp b/engines/ags/shared/ac/wordsdictionary.cpp
index 5f7d1381d5..9ea0a590ce 100644
--- a/engines/ags/shared/ac/wordsdictionary.cpp
+++ b/engines/ags/shared/ac/wordsdictionary.cpp
@@ -20,11 +20,11 @@
  *
  */
 
-#include <algorithm>
-#include <string.h>
-#include "ac/wordsdictionary.h"
-#include "util/stream.h"
-#include "util/string_compat.h"
+//include <algorithm>
+//include <string.h>
+#include "ags/shared/ac/wordsdictionary.h"
+#include "ags/shared/util/stream.h"
+#include "ags/shared/util/string_compat.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/ac/wordsdictionary.h b/engines/ags/shared/ac/wordsdictionary.h
index fba3277de8..db453aec60 100644
--- a/engines/ags/shared/ac/wordsdictionary.h
+++ b/engines/ags/shared/ac/wordsdictionary.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_AC_WORDSDICTIONARY_H
 #define AGS_SHARED_AC_WORDSDICTIONARY_H
 
-#include "core/types.h"
+#include "ags/shared/core/types.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/api/stream_api.h b/engines/ags/shared/api/stream_api.h
index 9bd209b434..682758f1d3 100644
--- a/engines/ags/shared/api/stream_api.h
+++ b/engines/ags/shared/api/stream_api.h
@@ -36,7 +36,7 @@
 // TODO: it would probably be better to not include core definition headers
 // in API class headers, but make separate core headers specifically for
 // plugins, and let plugin developers include them manually in plugin sources.
-#include "core/types.h"
+#include "ags/shared/core/types.h"
 
 namespace AGS3 {
 namespace AGS {
@@ -78,7 +78,7 @@ public:
 	virtual size_t      ReadArrayOfInt32(int32_t *buffer, size_t count) = 0;
 	virtual size_t      ReadArrayOfInt64(int64_t *buffer, size_t count) = 0;
 
-	virtual size_t      WriteInt8(int8_t val) = 0;;
+	virtual size_t      WriteInt8(int8_t val) = 0;
 	virtual size_t      WriteInt16(int16_t val) = 0;
 	virtual size_t      WriteInt32(int32_t val) = 0;
 	virtual size_t      WriteInt64(int64_t val) = 0;
diff --git a/engines/ags/shared/core/asset.cpp b/engines/ags/shared/core/asset.cpp
index 7c34675faf..7cb05ed89d 100644
--- a/engines/ags/shared/core/asset.cpp
+++ b/engines/ags/shared/core/asset.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "core/asset.h"
+#include "ags/shared/core/asset.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/core/asset.h b/engines/ags/shared/core/asset.h
index a531f8c94e..34647cc30a 100644
--- a/engines/ags/shared/core/asset.h
+++ b/engines/ags/shared/core/asset.h
@@ -29,8 +29,8 @@
 #ifndef AGS_SHARED_CORE_ASSET_H
 #define AGS_SHARED_CORE_ASSET_H
 
-#include <vector>
-#include "util/string.h"
+//include <vector>
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/core/assetmanager.cpp b/engines/ags/shared/core/assetmanager.cpp
index 3017592cb1..28b8d0a37c 100644
--- a/engines/ags/shared/core/assetmanager.cpp
+++ b/engines/ags/shared/core/assetmanager.cpp
@@ -20,11 +20,11 @@
  *
  */
 
-#include "core/assetmanager.h"
-#include "util/misc.h" // ci_fopen
-#include "util/multifilelib.h"
-#include "util/path.h"
-#include "util/string_utils.h"
+#include "ags/shared/core/assetmanager.h"
+#include "ags/shared/util/misc.h" // ci_fopen
+#include "ags/shared/util/multifilelib.h"
+#include "ags/shared/util/path.h"
+#include "ags/shared/util/string_utils.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/core/assetmanager.h b/engines/ags/shared/core/assetmanager.h
index bf942bdfa0..383c61b52d 100644
--- a/engines/ags/shared/core/assetmanager.h
+++ b/engines/ags/shared/core/assetmanager.h
@@ -44,7 +44,7 @@
 #ifndef AGS_SHARED_CORE_ASSETMANAGER_H
 #define AGS_SHARED_CORE_ASSETMANAGER_H
 
-#include "util/file.h" // TODO: extract filestream mode constants or introduce generic ones
+#include "ags/shared/util/file.h" // TODO: extract filestream mode constants or introduce generic ones
 
 namespace AGS3 {
 namespace AGS {
@@ -138,10 +138,10 @@ private:
 	AssetInfo *FindAssetByFileName(const String &asset_name);
 	String      MakeLibraryFileNameForAsset(const AssetInfo *asset);
 
-	bool        GetAssetFromLib(const String &asset_name, AssetLocation &loc, Common::FileOpenMode open_mode, Common::FileWorkMode work_mode);
-	bool        GetAssetFromDir(const String &asset_name, AssetLocation &loc, Common::FileOpenMode open_mode, Common::FileWorkMode work_mode);
-	bool        GetAssetByPriority(const String &asset_name, AssetLocation &loc, Common::FileOpenMode open_mode, Common::FileWorkMode work_mode);
-	Stream *OpenAssetAsStream(const String &asset_name, FileOpenMode open_mode, FileWorkMode work_mode);
+	bool        GetAssetFromLib(const String &asset_name, AssetLocation &loc, Shared::FileOpenMode open_mode, Shared::FileWorkMode work_mode);
+	bool        GetAssetFromDir(const String &asset_name, AssetLocation &loc, Shared::FileOpenMode open_mode, Shared::FileWorkMode work_mode);
+	bool        GetAssetByPriority(const String &asset_name, AssetLocation &loc, Shared::FileOpenMode open_mode, Shared::FileWorkMode work_mode);
+	Stream *OpenAssetAsStream(const String &asset_name, Shared::FileOpenMode open_mode, Shared::FileWorkMode work_mode);
 
 	static AssetManager *_theAssetManager;
 	AssetSearchPriority     _searchPriority;
diff --git a/engines/ags/shared/core/platform.h b/engines/ags/shared/core/platform.h
index 40d7cc1754..67ded4ac4b 100644
--- a/engines/ags/shared/core/platform.h
+++ b/engines/ags/shared/core/platform.h
@@ -27,8 +27,16 @@ namespace AGS3 {
 
 // platform definitions. Not intended for replacing types or checking for libraries.
 
+// ScummVM implementation is identifying as Linux for now
+#if 1
+#define AGS_PLATFORM_OS_WINDOWS (0)
+#define AGS_PLATFORM_OS_LINUX   (1)
+#define AGS_PLATFORM_OS_MACOS   (0)
+#define AGS_PLATFORM_OS_ANDROID (1)
+#define AGS_PLATFORM_OS_IOS     (0)
+#define AGS_PLATFORM_OS_PSP     (0)
 // check Android first because sometimes it can get confused with host OS
-#if defined(__ANDROID__) || defined(ANDROID)
+#elif defined(__ANDROID__) || defined(ANDROID)
 #define AGS_PLATFORM_OS_WINDOWS (0)
 #define AGS_PLATFORM_OS_LINUX   (0)
 #define AGS_PLATFORM_OS_MACOS   (0)
@@ -44,7 +52,7 @@ namespace AGS3 {
 #define AGS_PLATFORM_OS_IOS     (0)
 #define AGS_PLATFORM_OS_PSP     (0)
 #elif defined(__APPLE__)
-#include "TargetConditionals.h"
+#include "ags/shared/TargetConditionals.h"
 #ifndef TARGET_OS_SIMULATOR
 #define TARGET_OS_SIMULATOR (0)
 #endif
diff --git a/engines/ags/shared/core/types.h b/engines/ags/shared/core/types.h
index c7d0484462..9a9669f2cb 100644
--- a/engines/ags/shared/core/types.h
+++ b/engines/ags/shared/core/types.h
@@ -29,10 +29,11 @@
 #ifndef AGS_SHARED_CORE_TYPES_H
 #define AGS_SHARED_CORE_TYPES_H
 
-#include <stddef.h>
-#include <stdint.h>
-#include <stdlib.h> // for size_t
-#include <limits.h> // for _WORDSIZE
+#include "common/scummsys.h"
+//include <stddef.h>
+//include <stdint.h>
+//include <stdlib.h> // for size_t
+//include <limits.h> // for _WORDSIZE
 
 namespace AGS3 {
 
@@ -58,12 +59,33 @@ namespace AGS3 {
 #endif
 #endif
 
+typedef uint8 uint8_t;
+typedef uint16 uint16_t;
+typedef uint32 uint32_t;
+typedef int8 int8_t;
+typedef int16 int16_t;
+typedef int32 int32_t;
+typedef int64 int64_t;
+
 // Stream offset type
-typedef int64_t soff_t;
+typedef int64 soff_t;
 
 #define fixed_t int32_t // fixed point type
 #define color_t int32_t
 
+#undef INT32_MIN
+#undef INT32_MAX
+#undef INT_MIN
+#undef INT_MAX
+#undef UINT_MAX
+#undef SIZE_MAX
+#define INT32_MIN     (-2147483647 - 1)
+#define INT32_MAX       2147483647
+#define INT_MIN     (-2147483647 - 1)
+#define INT_MAX       2147483647
+#define UINT_MAX      0xffffffff
+#define SIZE_MAX      0xffffffff
+
 // TODO: use distinct fixed point class
 enum {
 	kShift = 16,
diff --git a/engines/ags/shared/debugging/assert.h b/engines/ags/shared/debugging/assert.h
index cb355fa6df..805ca9082e 100644
--- a/engines/ags/shared/debugging/assert.h
+++ b/engines/ags/shared/debugging/assert.h
@@ -29,6 +29,6 @@
 #ifndef AGS_SHARED_DEBUGGING_ASSERT_H
 #define AGS_SHARED_DEBUGGING_ASSERT_H
 
-#include <assert.h>
+//include <assert.h>
 
 #endif
diff --git a/engines/ags/shared/debugging/debugmanager.cpp b/engines/ags/shared/debugging/debugmanager.cpp
index 69800cc25f..d6106531cd 100644
--- a/engines/ags/shared/debugging/debugmanager.cpp
+++ b/engines/ags/shared/debugging/debugmanager.cpp
@@ -20,9 +20,9 @@
  *
  */
 
-#include <stdarg.h>
-#include "debug/debugmanager.h"
-#include "util/string_types.h"
+//include <stdarg.h>
+#include "ags/shared/debugging/debugmanager.h"
+#include "ags/shared/util/string_types.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/debugging/debugmanager.h b/engines/ags/shared/debugging/debugmanager.h
index 8390311257..97a7d89e6f 100644
--- a/engines/ags/shared/debugging/debugmanager.h
+++ b/engines/ags/shared/debugging/debugmanager.h
@@ -47,12 +47,12 @@
 #ifndef AGS_SHARED_DEBUGGING_DEBUGMANAGER_H
 #define AGS_SHARED_DEBUGGING_DEBUGMANAGER_H
 
-#include <memory>
-#include <unordered_map>
-#include "debug/out.h"
-#include "debug/outputhandler.h"
-#include "util/string.h"
-#include "util/string_types.h"
+//include <memory>
+//include <unordered_map>
+#include "ags/shared/debugging/out.h"
+#include "ags/shared/debugging/outputhandler.h"
+#include "ags/shared/util/string.h"
+#include "ags/shared/util/string_types.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/debugging/out.h b/engines/ags/shared/debugging/out.h
index c25eb655a0..b68cee3bec 100644
--- a/engines/ags/shared/debugging/out.h
+++ b/engines/ags/shared/debugging/out.h
@@ -77,7 +77,7 @@
 #ifndef AGS_SHARED_DEBUGGING_OUT_H
 #define AGS_SHARED_DEBUGGING_OUT_H
 
-#include "util/string.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/debugging/outputhandler.h b/engines/ags/shared/debugging/outputhandler.h
index 9d071b1755..635932b7fb 100644
--- a/engines/ags/shared/debugging/outputhandler.h
+++ b/engines/ags/shared/debugging/outputhandler.h
@@ -30,8 +30,8 @@
 #ifndef AGS_SHARED_DEBUGGING_OUTPUTHANDLER_H
 #define AGS_SHARED_DEBUGGING_OUTPUTHANDLER_H
 
-#include "debug/out.h"
-#include "util/string.h"
+#include "ags/shared/debugging/out.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/font/fonts.cpp b/engines/ags/shared/font/fonts.cpp
index 6acbebd152..5051c94db5 100644
--- a/engines/ags/shared/font/fonts.cpp
+++ b/engines/ags/shared/font/fonts.cpp
@@ -20,17 +20,17 @@
  *
  */
 
-#include <cstdio>
-#include <vector>
-#include <alfont.h>
-#include "ac/common.h" // set_our_eip
-#include "ac/gamestructdefines.h"
-#include "font/fonts.h"
-#include "font/ttffontrenderer.h"
-#include "font/wfnfontrenderer.h"
-#include "gfx/bitmap.h"
-#include "gui/guidefines.h" // MAXLINE
-#include "util/string_utils.h"
+//include <cstdio>
+//include <vector>
+//include <alfont.h>
+#include "ags/shared/ac/common.h" // set_our_eip
+#include "ags/shared/ac/gamestructdefines.h"
+#include "ags/shared/font/fonts.h"
+#include "ags/shared/font/ttffontrenderer.h"
+#include "ags/shared/font/wfnfontrenderer.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/gui/guidefines.h" // MAXLINE
+#include "ags/shared/util/string_utils.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/font/fonts.h b/engines/ags/shared/font/fonts.h
index 29a8b35e94..85d69d68c9 100644
--- a/engines/ags/shared/font/fonts.h
+++ b/engines/ags/shared/font/fonts.h
@@ -23,9 +23,9 @@
 #ifndef AGS_SHARED_FONT_FONTS_H
 #define AGS_SHARED_FONT_FONTS_H
 
-#include <vector>
-#include "core/types.h"
-#include "util/string.h"
+//include <vector>
+#include "ags/shared/core/types.h"
+#include "ags/shared/util/string.h"
 
 // TODO: we need to make some kind of TextManager class of this module
 
diff --git a/engines/ags/shared/font/ttffontrenderer.cpp b/engines/ags/shared/font/ttffontrenderer.cpp
index 6dfc35161c..dfbf669d21 100644
--- a/engines/ags/shared/font/ttffontrenderer.cpp
+++ b/engines/ags/shared/font/ttffontrenderer.cpp
@@ -20,18 +20,18 @@
  *
  */
 
-#include <alfont.h>
-#include "core/platform.h"
+//include <alfont.h>
+#include "ags/shared/core/platform.h"
 
 #define AGS_OUTLINE_FONT_FIX (!AGS_PLATFORM_OS_WINDOWS)
 
-#include "core/assetmanager.h"
-#include "font/ttffontrenderer.h"
-#include "util/stream.h"
+#include "ags/shared/core/assetmanager.h"
+#include "ags/shared/font/ttffontrenderer.h"
+#include "ags/shared/util/stream.h"
 
 #if AGS_OUTLINE_FONT_FIX // TODO: factor out the hack in LoadFromDiskEx
-#include "ac/gamestructdefines.h"
-#include "font/fonts.h"
+#include "ags/shared/ac/gamestructdefines.h"
+#include "ags/shared/font/fonts.h"
 #endif
 
 namespace AGS3 {
diff --git a/engines/ags/shared/font/ttffontrenderer.h b/engines/ags/shared/font/ttffontrenderer.h
index 84326fe49a..38e1fab00f 100644
--- a/engines/ags/shared/font/ttffontrenderer.h
+++ b/engines/ags/shared/font/ttffontrenderer.h
@@ -23,8 +23,8 @@
 #ifndef AGS_SHARED_FONT_TTFFONTRENDERER_H
 #define AGS_SHARED_FONT_TTFFONTRENDERER_H
 
-#include <map>
-#include "font/agsfontrenderer.h"
+//include <map>
+#include "ags/shared/font/agsfontrenderer.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/font/wfnfont.cpp b/engines/ags/shared/font/wfnfont.cpp
index da07dead4f..daea4e3285 100644
--- a/engines/ags/shared/font/wfnfont.cpp
+++ b/engines/ags/shared/font/wfnfont.cpp
@@ -20,11 +20,11 @@
  *
  */
 
-#include <algorithm>
-#include "font/wfnfont.h"
-#include "debug/out.h"
-#include "util/memory.h"
-#include "util/stream.h"
+//include <algorithm>
+#include "ags/shared/font/wfnfont.h"
+#include "ags/shared/debugging/out.h"
+#include "ags/shared/util/memory.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/font/wfnfont.h b/engines/ags/shared/font/wfnfont.h
index 6abe424268..c3212f684c 100644
--- a/engines/ags/shared/font/wfnfont.h
+++ b/engines/ags/shared/font/wfnfont.h
@@ -46,8 +46,8 @@
 #ifndef AGS_SHARED_FONT_WFNFONT_H
 #define AGS_SHARED_FONT_WFNFONT_H
 
-#include <vector>
-#include "core/types.h"
+//include <vector>
+#include "ags/shared/core/types.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/font/wfnfontrenderer.cpp b/engines/ags/shared/font/wfnfontrenderer.cpp
index 3366805408..301d4ee281 100644
--- a/engines/ags/shared/font/wfnfontrenderer.cpp
+++ b/engines/ags/shared/font/wfnfontrenderer.cpp
@@ -20,13 +20,13 @@
  *
  */
 
-#include "ac/common.h" // our_eip
-#include "core/assetmanager.h"
-#include "debug/out.h"
-#include "font/wfnfont.h"
-#include "font/wfnfontrenderer.h"
-#include "gfx/bitmap.h"
-#include "util/stream.h"
+#include "ags/shared/ac/common.h" // our_eip
+#include "ags/shared/core/assetmanager.h"
+#include "ags/shared/debugging/out.h"
+#include "ags/shared/font/wfnfont.h"
+#include "ags/shared/font/wfnfontrenderer.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/font/wfnfontrenderer.h b/engines/ags/shared/font/wfnfontrenderer.h
index ac816f647f..25fe6930d4 100644
--- a/engines/ags/shared/font/wfnfontrenderer.h
+++ b/engines/ags/shared/font/wfnfontrenderer.h
@@ -23,8 +23,8 @@
 #ifndef AGS_SHARED_FONT_WFNFONTRENDERER_H
 #define AGS_SHARED_FONT_WFNFONTRENDERER_H
 
-#include <map>
-#include "font/agsfontrenderer.h"
+//include <map>
+#include "ags/shared/font/agsfontrenderer.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/game/customproperties.cpp b/engines/ags/shared/game/customproperties.cpp
index be148873fa..c56eac64f5 100644
--- a/engines/ags/shared/game/customproperties.cpp
+++ b/engines/ags/shared/game/customproperties.cpp
@@ -20,9 +20,9 @@
  *
  */
 
-#include "game/customproperties.h"
-#include "util/stream.h"
-#include "util/string_utils.h"
+#include "ags/shared/game/customproperties.h"
+#include "ags/shared/util/stream.h"
+#include "ags/shared/util/string_utils.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/game/customproperties.h b/engines/ags/shared/game/customproperties.h
index 7908829e2d..fd7515041a 100644
--- a/engines/ags/shared/game/customproperties.h
+++ b/engines/ags/shared/game/customproperties.h
@@ -36,9 +36,9 @@
 #ifndef AGS_SHARED_GAME_CUSTOMPROPERTIES_H
 #define AGS_SHARED_GAME_CUSTOMPROPERTIES_H
 
-#include <unordered_map>
-#include "util/string.h"
-#include "util/string_types.h"
+//include <unordered_map>
+#include "ags/shared/util/string.h"
+#include "ags/shared/util/string_types.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/game/interactions.cpp b/engines/ags/shared/game/interactions.cpp
index 69cece5967..6996c69dae 100644
--- a/engines/ags/shared/game/interactions.cpp
+++ b/engines/ags/shared/game/interactions.cpp
@@ -20,11 +20,11 @@
  *
  */
 
-#include <string.h>
-#include "ac/common.h" // quit
-#include "game/interactions.h"
-#include "util/alignedstream.h"
-#include "util/math.h"
+//include <string.h>
+#include "ags/shared/ac/common.h" // quit
+#include "ags/shared/game/interactions.h"
+#include "ags/shared/util/alignedstream.h"
+#include "ags/shared/util/math.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/game/interactions.h b/engines/ags/shared/game/interactions.h
index c325ee6ebd..ad1278404c 100644
--- a/engines/ags/shared/game/interactions.h
+++ b/engines/ags/shared/game/interactions.h
@@ -49,8 +49,8 @@
 #ifndef AGS_SHARED_GAME_INTEREACTIONS_H
 #define AGS_SHARED_GAME_INTEREACTIONS_H
 
-#include <memory>
-#include "util/string_types.h"
+//include <memory>
+#include "ags/shared/util/string_types.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/game/main_game_file.cpp b/engines/ags/shared/game/main_game_file.cpp
index 847f894f6d..436c24ba41 100644
--- a/engines/ags/shared/game/main_game_file.cpp
+++ b/engines/ags/shared/game/main_game_file.cpp
@@ -20,24 +20,24 @@
  *
  */
 
-#include <cstdio>
-#include "ac/audiocliptype.h"
-#include "ac/dialogtopic.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/spritecache.h"
-#include "ac/view.h"
-#include "ac/wordsdictionary.h"
-#include "ac/dynobj/scriptaudioclip.h"
-#include "core/asset.h"
-#include "core/assetmanager.h"
-#include "game/main_game_file.h"
-#include "gui/guimain.h"
-#include "script/cc_error.h"
-#include "util/alignedstream.h"
-#include "util/path.h"
-#include "util/string_compat.h"
-#include "util/string_utils.h"
-#include "font/fonts.h"
+//include <cstdio>
+#include "ags/shared/ac/audiocliptype.h"
+#include "ags/shared/ac/dialogtopic.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/ac/view.h"
+#include "ags/shared/ac/wordsdictionary.h"
+#include "ags/shared/ac/dynobj/scriptaudioclip.h"
+#include "ags/shared/core/asset.h"
+#include "ags/shared/core/assetmanager.h"
+#include "ags/shared/game/main_game_file.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/script/cc_error.h"
+#include "ags/shared/util/alignedstream.h"
+#include "ags/shared/util/path.h"
+#include "ags/shared/util/string_compat.h"
+#include "ags/shared/util/string_utils.h"
+#include "ags/shared/font/fonts.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/game/main_game_file.h b/engines/ags/shared/game/main_game_file.h
index 8bb36b7ff0..93705bbade 100644
--- a/engines/ags/shared/game/main_game_file.h
+++ b/engines/ags/shared/game/main_game_file.h
@@ -31,16 +31,16 @@
 #ifndef AGS_SHARED_GAME_MAINGAMEFILE_H
 #define AGS_SHARED_GAME_MAINGAMEFILE_H
 
-#include <memory>
-#include <set>
-#include <vector>
-#include "ac/game_version.h"
-#include "game/plugininfo.h"
-#include "script/cc_script.h"
-#include "util/error.h"
-#include "util/stream.h"
-#include "util/string.h"
-#include "util/version.h"
+//include <memory>
+//include <set>
+//include <vector>
+#include "ags/shared/ac/game_version.h"
+#include "ags/shared/game/plugininfo.h"
+#include "ags/shared/script/cc_script.h"
+#include "ags/shared/util/error.h"
+#include "ags/shared/util/stream.h"
+#include "ags/shared/util/string.h"
+#include "ags/shared/util/version.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/game/plugininfo.h b/engines/ags/shared/game/plugininfo.h
index eac9f6e072..b10962dd5f 100644
--- a/engines/ags/shared/game/plugininfo.h
+++ b/engines/ags/shared/game/plugininfo.h
@@ -29,8 +29,8 @@
 #ifndef AGS_SHARED_GAME_PLUGININFO_H
 #define AGS_SHARED_GAME_PLUGININFO_H
 
-#include <memory>
-#include "util/string.h"
+//include <memory>
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/game/room_file.cpp b/engines/ags/shared/game/room_file.cpp
index 7793053e70..48796e19a6 100644
--- a/engines/ags/shared/game/room_file.cpp
+++ b/engines/ags/shared/game/room_file.cpp
@@ -20,20 +20,20 @@
  *
  */
 
-#include "ac/common.h" // update_polled_stuff
-#include "ac/common_defines.h"
-#include "ac/gamestructdefines.h"
-#include "ac/wordsdictionary.h" // TODO: extract string decryption
-#include "core/assetmanager.h"
-#include "debug/out.h"
-#include "game/customproperties.h"
-#include "game/room_file.h"
-#include "game/roomstruct.h"
-#include "gfx/bitmap.h"
-#include "script/cc_error.h"
-#include "script/cc_script.h"
-#include "util/compress.h"
-#include "util/string_utils.h"
+#include "ags/shared/ac/common.h" // update_polled_stuff
+#include "ags/shared/ac/common_defines.h"
+#include "ags/shared/ac/gamestructdefines.h"
+#include "ags/shared/ac/wordsdictionary.h" // TODO: extract string decryption
+#include "ags/shared/core/assetmanager.h"
+#include "ags/shared/debugging/out.h"
+#include "ags/shared/game/customproperties.h"
+#include "ags/shared/game/room_file.h"
+#include "ags/shared/game/roomstruct.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/script/cc_error.h"
+#include "ags/shared/script/cc_script.h"
+#include "ags/shared/util/compress.h"
+#include "ags/shared/util/string_utils.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/game/room_file.h b/engines/ags/shared/game/room_file.h
index 6276cb352a..e191e85470 100644
--- a/engines/ags/shared/game/room_file.h
+++ b/engines/ags/shared/game/room_file.h
@@ -31,12 +31,12 @@
 #ifndef AGS_SHARED_GAME_ROOMFILE_H
 #define AGS_SHARED_GAME_ROOMFILE_H
 
-#include <memory>
-#include <vector>
-#include "game/room_version.h"
-#include "util/error.h"
-#include "util/stream.h"
-#include "util/string.h"
+//include <memory>
+//include <vector>
+#include "ags/shared/game/room_version.h"
+#include "ags/shared/util/error.h"
+#include "ags/shared/util/stream.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/game/room_file_deprecated.cpp b/engines/ags/shared/game/room_file_deprecated.cpp
index 388d9783ce..a540e9dfc4 100644
--- a/engines/ags/shared/game/room_file_deprecated.cpp
+++ b/engines/ags/shared/game/room_file_deprecated.cpp
@@ -30,8 +30,8 @@
 
 #if defined (OBSOLETE)
 
-#include "ac/common.h"
-#include "util/stream.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/game/roomstruct.cpp b/engines/ags/shared/game/roomstruct.cpp
index 73d399ed0e..3d17591816 100644
--- a/engines/ags/shared/game/roomstruct.cpp
+++ b/engines/ags/shared/game/roomstruct.cpp
@@ -20,10 +20,10 @@
  *
  */
 
-#include "ac/common.h" // update_polled_stuff_if_runtime
-#include "game/room_file.h"
-#include "game/roomstruct.h"
-#include "gfx/bitmap.h"
+#include "ags/shared/ac/common.h" // update_polled_stuff_if_runtime
+#include "ags/shared/game/room_file.h"
+#include "ags/shared/game/roomstruct.h"
+#include "ags/shared/gfx/bitmap.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/game/roomstruct.h b/engines/ags/shared/game/roomstruct.h
index b9d48742e1..59f42ea829 100644
--- a/engines/ags/shared/game/roomstruct.h
+++ b/engines/ags/shared/game/roomstruct.h
@@ -48,11 +48,11 @@
 #ifndef AGS_SHARED_GAME_ROOMINFO_H
 #define AGS_SHARED_GAME_ROOMINFO_H
 
-#include <memory>
-#include "ac/common_defines.h"
-#include "game/interactions.h"
-#include "util/geometry.h"
-#include "util/wgt2allg.h" // color (allegro RGB)
+//include <memory>
+#include "ags/shared/ac/common_defines.h"
+#include "ags/shared/game/interactions.h"
+#include "ags/shared/util/geometry.h"
+#include "ags/shared/util/wgt2allg.h" // color (allegro RGB)
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/gfx/allegrobitmap.cpp b/engines/ags/shared/gfx/allegrobitmap.cpp
index 1112dfd327..42ed2dfa77 100644
--- a/engines/ags/shared/gfx/allegrobitmap.cpp
+++ b/engines/ags/shared/gfx/allegrobitmap.cpp
@@ -20,9 +20,9 @@
  *
  */
 
-#include <aastr.h>
-#include "gfx/allegrobitmap.h"
-#include "debug/assert.h"
+//include <aastr.h>
+#include "ags/shared/gfx/allegrobitmap.h"
+#include "ags/shared/debugging/assert.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/gfx/allegrobitmap.h b/engines/ags/shared/gfx/allegrobitmap.h
index 3a5092cc97..195bc85d43 100644
--- a/engines/ags/shared/gfx/allegrobitmap.h
+++ b/engines/ags/shared/gfx/allegrobitmap.h
@@ -32,9 +32,11 @@
 #ifndef AGS_SHARED_GFX_ALLEGROBITMAP_H
 #define AGS_SHARED_GFX_ALLEGROBITMAP_H
 
-#include <allegro.h>
-#include "core/types.h"
-#include "gfx/bitmap.h"
+#include "ags/stubs/allegro.h"
+#include "ags/shared/core/types.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/util/geometry.h"
+#include "graphics/screen.h"
 
 namespace AGS3 {
 namespace AGS {
@@ -74,15 +76,15 @@ public:
 
 	// Is this a "normal" bitmap created by application which data can be directly accessed for reading and writing
 	inline bool IsMemoryBitmap() const {
-		return is_memory_bitmap(_alBitmap) != 0;
+		return true;
 	}
 	// Is this a video bitmap
 	inline bool IsVideoBitmap() const {
-		return is_video_bitmap(_alBitmap) != 0;
+		return dynamic_cast<Graphics::Screen *>(_alBitmap) != nullptr;
 	}
 	// Is this a linear bitmap, the one that can be accessed linearly within each scanline
 	inline bool IsLinearBitmap() const {
-		return is_linear_bitmap(_alBitmap) != 0;
+		return true;
 	}
 
 	// Checks if bitmap cannot be used
@@ -103,7 +105,7 @@ public:
 		return Size(_alBitmap->w, _alBitmap->h);
 	}
 	inline int  GetColorDepth() const {
-		return bitmap_color_depth(_alBitmap);
+		return _alBitmap->format.bpp();
 	}
 	// BPP: bytes per pixel
 	inline int  GetBPP() const {
@@ -123,17 +125,17 @@ public:
 	// Gets a pointer to underlying graphic data
 	// FIXME: actually not a very good idea, since there's no 100% guarantee the scanline positions in memory are sequential
 	inline const unsigned char *GetData() const {
-		return _alBitmap->line[0];
+		return (unsigned char *)_alBitmap->getPixels();
 	}
 
 	// Get scanline for direct reading
 	inline const unsigned char *GetScanLine(int index) const {
-		return (index >= 0 && index < GetHeight()) ? _alBitmap->line[index] : nullptr;
+		return (index >= 0 && index < GetHeight()) ? (unsigned char *)_alBitmap->getBasePtr(0, index) : nullptr;
 	}
 
 	void    SetMaskColor(color_t color);
 	inline color_t GetMaskColor() const {
-		return bitmap_mask_color(_alBitmap);
+		return _alBitmap->getTransparentColor();
 	}
 
 	// FIXME: allegro manual states these should not be used externally;
@@ -210,10 +212,10 @@ public:
 	// TODO: think how to increase safety over this (some fixed memory buffer class with iterator?)
 	// Gets scanline for directly writing into it
 	inline unsigned char *GetScanLineForWriting(int index) {
-		return (index >= 0 && index < GetHeight()) ? _alBitmap->line[index] : nullptr;
+		return (index >= 0 && index < GetHeight()) ? (unsigned char *)_alBitmap->getBasePtr(0, index) : nullptr;
 	}
 	inline unsigned char *GetDataForWriting() {
-		return _alBitmap->line[0];
+		return (unsigned char *)_alBitmap->getPixels();
 	}
 	// Copies buffer contents into scanline
 	void    SetScanLine(int index, unsigned char *data, int data_size = -1);
diff --git a/engines/ags/shared/gfx/bitmap.cpp b/engines/ags/shared/gfx/bitmap.cpp
index 543fecba5d..9c6f311de6 100644
--- a/engines/ags/shared/gfx/bitmap.cpp
+++ b/engines/ags/shared/gfx/bitmap.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "gfx/bitmap.h"
-#include "util/memory.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/util/memory.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/gfx/bitmap.h b/engines/ags/shared/gfx/bitmap.h
index 91a4d15b07..3c22d7fbff 100644
--- a/engines/ags/shared/gfx/bitmap.h
+++ b/engines/ags/shared/gfx/bitmap.h
@@ -29,7 +29,7 @@
 #ifndef AGS_SHARED_GFX_BITMAP_H
 #define AGS_SHARED_GFX_BITMAP_H
 
-#include "util/geometry.h"
+#include "ags/shared/util/geometry.h"
 
 namespace AGS3 {
 namespace AGS {
@@ -51,11 +51,12 @@ enum BitmapFlip {
 
 } // namespace Shared
 } // namespace AGS
-
+} // namespace AGS3
 
 // Declare the actual bitmap class
-#include "gfx/allegrobitmap.h"
+#include "ags/shared/gfx/allegrobitmap.h"
 
+namespace AGS3 {
 namespace AGS {
 namespace Shared {
 
diff --git a/engines/ags/shared/gui/guibutton.cpp b/engines/ags/shared/gui/guibutton.cpp
index bcc61f7fa9..03a99749eb 100644
--- a/engines/ags/shared/gui/guibutton.cpp
+++ b/engines/ags/shared/gui/guibutton.cpp
@@ -20,11 +20,11 @@
  *
  */
 
-#include "ac/spritecache.h"
-#include "gui/guibutton.h"
-#include "gui/guimain.h" // TODO: extract helper functions
-#include "util/stream.h"
-#include "util/string_utils.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/gui/guibutton.h"
+#include "ags/shared/gui/guimain.h" // TODO: extract helper functions
+#include "ags/shared/util/stream.h"
+#include "ags/shared/util/string_utils.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/gui/guibutton.h b/engines/ags/shared/gui/guibutton.h
index f5ac628a03..87597ec57f 100644
--- a/engines/ags/shared/gui/guibutton.h
+++ b/engines/ags/shared/gui/guibutton.h
@@ -23,9 +23,9 @@
 #ifndef AGS_SHARED_GUI_GUIBUTTON_H
 #define AGS_SHARED_GUI_GUIBUTTON_H
 
-#include <vector>
-#include "gui/guiobject.h"
-#include "util/string.h"
+//include <vector>
+#include "ags/shared/gui/guiobject.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/gui/guiinv.cpp b/engines/ags/shared/gui/guiinv.cpp
index 7e71a39234..59c413cba3 100644
--- a/engines/ags/shared/gui/guiinv.cpp
+++ b/engines/ags/shared/gui/guiinv.cpp
@@ -20,11 +20,11 @@
  *
  */
 
-#include <math.h>
-#include "ac/game_version.h"
-#include "gui/guiinv.h"
-#include "gui/guimain.h"
-#include "util/stream.h"
+//include <math.h>
+#include "ags/shared/ac/game_version.h"
+#include "ags/shared/gui/guiinv.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/gui/guiinv.h b/engines/ags/shared/gui/guiinv.h
index 8c358dc0b8..9debe7dcec 100644
--- a/engines/ags/shared/gui/guiinv.h
+++ b/engines/ags/shared/gui/guiinv.h
@@ -23,8 +23,8 @@
 #ifndef AGS_SHARED_GUI_GUIINV_H
 #define AGS_SHARED_GUI_GUIINV_H
 
-#include <vector>
-#include "gui/guiobject.h"
+//include <vector>
+#include "ags/shared/gui/guiobject.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/gui/guilabel.cpp b/engines/ags/shared/gui/guilabel.cpp
index cf72d09d96..ea91eeef02 100644
--- a/engines/ags/shared/gui/guilabel.cpp
+++ b/engines/ags/shared/gui/guilabel.cpp
@@ -20,12 +20,12 @@
  *
  */
 
-#include "ac/game_version.h"
-#include "font/fonts.h"
-#include "gui/guilabel.h"
-#include "gui/guimain.h"
-#include "util/stream.h"
-#include "util/string_utils.h"
+#include "ags/shared/ac/game_version.h"
+#include "ags/shared/font/fonts.h"
+#include "ags/shared/gui/guilabel.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/util/stream.h"
+#include "ags/shared/util/string_utils.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/gui/guilabel.h b/engines/ags/shared/gui/guilabel.h
index ff11472571..6ad4a883b2 100644
--- a/engines/ags/shared/gui/guilabel.h
+++ b/engines/ags/shared/gui/guilabel.h
@@ -23,9 +23,9 @@
 #ifndef AGS_SHARED_GUI_GUILABEL_H
 #define AGS_SHARED_GUI_GUILABEL_H
 
-#include <vector>
-#include "gui/guiobject.h"
-#include "util/string.h"
+//include <vector>
+#include "ags/shared/gui/guiobject.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/gui/guilistbox.cpp b/engines/ags/shared/gui/guilistbox.cpp
index 4f574a10f8..b3ee25688b 100644
--- a/engines/ags/shared/gui/guilistbox.cpp
+++ b/engines/ags/shared/gui/guilistbox.cpp
@@ -20,11 +20,11 @@
  *
  */
 
-#include "font/fonts.h"
-#include "gui/guilistbox.h"
-#include "gui/guimain.h"
-#include "util/stream.h"
-#include "util/string_utils.h"
+#include "ags/shared/font/fonts.h"
+#include "ags/shared/gui/guilistbox.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/util/stream.h"
+#include "ags/shared/util/string_utils.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/gui/guilistbox.h b/engines/ags/shared/gui/guilistbox.h
index f3910c1074..61472388b8 100644
--- a/engines/ags/shared/gui/guilistbox.h
+++ b/engines/ags/shared/gui/guilistbox.h
@@ -23,9 +23,9 @@
 #ifndef AGS_SHARED_GUI_GUILISTBOX_H
 #define AGS_SHARED_GUI_GUILISTBOX_H
 
-#include <vector>
-#include "gui/guiobject.h"
-#include "util/string.h"
+//include <vector>
+#include "ags/shared/gui/guiobject.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/gui/guimain.cpp b/engines/ags/shared/gui/guimain.cpp
index 9463a712df..8b1f6e8b7f 100644
--- a/engines/ags/shared/gui/guimain.cpp
+++ b/engines/ags/shared/gui/guimain.cpp
@@ -20,20 +20,20 @@
  *
  */
 
-#include <algorithm>
-#include "ac/game_version.h"
-#include "ac/spritecache.h"
-#include "debug/out.h"
-#include "font/fonts.h"
-#include "gui/guibutton.h"
-#include "gui/guiinv.h"
-#include "gui/guilabel.h"
-#include "gui/guilistbox.h"
-#include "gui/guimain.h"
-#include "gui/guislider.h"
-#include "gui/guitextbox.h"
-#include "util/stream.h"
-#include "util/string_utils.h"
+//include <algorithm>
+#include "ags/shared/ac/game_version.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/debugging/out.h"
+#include "ags/shared/font/fonts.h"
+#include "ags/shared/gui/guibutton.h"
+#include "ags/shared/gui/guiinv.h"
+#include "ags/shared/gui/guilabel.h"
+#include "ags/shared/gui/guilistbox.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/gui/guislider.h"
+#include "ags/shared/gui/guitextbox.h"
+#include "ags/shared/util/stream.h"
+#include "ags/shared/util/string_utils.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/gui/guimain.h b/engines/ags/shared/gui/guimain.h
index 004f3b226a..4a930f3b4f 100644
--- a/engines/ags/shared/gui/guimain.h
+++ b/engines/ags/shared/gui/guimain.h
@@ -23,13 +23,13 @@
 #ifndef AGS_SHARED_GUI_GUIMAIN_H
 #define AGS_SHARED_GUI_GUIMAIN_H
 
-#include <vector>
-#include "ac/common_defines.h" // TODO: split out gui drawing helpers
-#include "gfx/gfx_def.h" // TODO: split out gui drawing helpers
-#include "gui/guidefines.h"
-#include "util/error.h"
-#include "util/geometry.h"
-#include "util/string.h"
+//include <vector>
+#include "ags/shared/ac/common_defines.h" // TODO: split out gui drawing helpers
+#include "ags/shared/gfx/gfx_def.h" // TODO: split out gui drawing helpers
+#include "ags/shared/gui/guidefines.h"
+#include "ags/shared/util/error.h"
+#include "ags/shared/util/geometry.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/gui/guiobject.cpp b/engines/ags/shared/gui/guiobject.cpp
index 69b44f47b3..81387b1c2a 100644
--- a/engines/ags/shared/gui/guiobject.cpp
+++ b/engines/ags/shared/gui/guiobject.cpp
@@ -20,10 +20,10 @@
  *
  */
 
-#include "ac/common.h" // quit
-#include "gui/guimain.h"
-#include "gui/guiobject.h"
-#include "util/stream.h"
+#include "ags/shared/ac/common.h" // quit
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/gui/guiobject.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/gui/guiobject.h b/engines/ags/shared/gui/guiobject.h
index 9dc698050d..bf37d9b792 100644
--- a/engines/ags/shared/gui/guiobject.h
+++ b/engines/ags/shared/gui/guiobject.h
@@ -23,10 +23,10 @@
 #ifndef AGS_SHARED_GUI_GUIOBJECT_H
 #define AGS_SHARED_GUI_GUIOBJECT_H
 
-#include "core/types.h"
-#include "gfx/bitmap.h"
-#include "gui/guidefines.h"
-#include "util/string.h"
+#include "ags/shared/core/types.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/gui/guidefines.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/gui/guislider.cpp b/engines/ags/shared/gui/guislider.cpp
index 557344bedd..e356d620e7 100644
--- a/engines/ags/shared/gui/guislider.cpp
+++ b/engines/ags/shared/gui/guislider.cpp
@@ -20,10 +20,10 @@
  *
  */
 
-#include "ac/spritecache.h"
-#include "gui/guimain.h"
-#include "gui/guislider.h"
-#include "util/stream.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/gui/guislider.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/gui/guislider.h b/engines/ags/shared/gui/guislider.h
index 338dc7124f..3eea0c3a39 100644
--- a/engines/ags/shared/gui/guislider.h
+++ b/engines/ags/shared/gui/guislider.h
@@ -23,8 +23,8 @@
 #ifndef AGS_SHARED_GUI_GUISLIDER_H
 #define AGS_SHARED_GUI_GUISLIDER_H
 
-#include <vector>
-#include "gui/guiobject.h"
+//include <vector>
+#include "ags/shared/gui/guiobject.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/gui/guitextbox.cpp b/engines/ags/shared/gui/guitextbox.cpp
index 8b9a20a940..b9b24df44b 100644
--- a/engines/ags/shared/gui/guitextbox.cpp
+++ b/engines/ags/shared/gui/guitextbox.cpp
@@ -20,11 +20,11 @@
  *
  */
 
-#include "font/fonts.h"
-#include "gui/guimain.h"
-#include "gui/guitextbox.h"
-#include "util/stream.h"
-#include "util/string_utils.h"
+#include "ags/shared/font/fonts.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/gui/guitextbox.h"
+#include "ags/shared/util/stream.h"
+#include "ags/shared/util/string_utils.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/gui/guitextbox.h b/engines/ags/shared/gui/guitextbox.h
index 9a69cd4c62..b1906cc861 100644
--- a/engines/ags/shared/gui/guitextbox.h
+++ b/engines/ags/shared/gui/guitextbox.h
@@ -23,9 +23,9 @@
 #ifndef AGS_SHARED_GUI_GUITEXTBOX_H
 #define AGS_SHARED_GUI_GUITEXTBOX_H
 
-#include <vector>
-#include "gui/guiobject.h"
-#include "util/string.h"
+//include <vector>
+#include "ags/shared/gui/guiobject.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/script/cc_error.cpp b/engines/ags/shared/script/cc_error.cpp
index b015289c50..8c0712b8cb 100644
--- a/engines/ags/shared/script/cc_error.cpp
+++ b/engines/ags/shared/script/cc_error.cpp
@@ -20,10 +20,10 @@
  *
  */
 
-#include <stdio.h>
-#include <utility>
-#include "script/script_common.h"  // current_line
-#include "util/string.h"
+//include <stdio.h>
+//include <utility>
+#include "ags/shared/script/script_common.h"  // current_line
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/script/cc_error.h b/engines/ags/shared/script/cc_error.h
index d211af6fbf..1417b137fc 100644
--- a/engines/ags/shared/script/cc_error.h
+++ b/engines/ags/shared/script/cc_error.h
@@ -29,7 +29,7 @@
 #ifndef AGS_SHARED_SCRIPT_ERROR_H
 #define AGS_SHARED_SCRIPT_ERROR_H
 
-#include "util/string.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/script/cc_options.cpp b/engines/ags/shared/script/cc_options.cpp
index 9c7821f1be..1262d6fa49 100644
--- a/engines/ags/shared/script/cc_options.cpp
+++ b/engines/ags/shared/script/cc_options.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "cc_options.h"
+#include "ags/shared/cc_options.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/script/cc_script.cpp b/engines/ags/shared/script/cc_script.cpp
index b7a79059cd..0c9079107c 100644
--- a/engines/ags/shared/script/cc_script.cpp
+++ b/engines/ags/shared/script/cc_script.cpp
@@ -20,13 +20,13 @@
  *
  */
 
-#include <stdlib.h>
-#include <string.h>
-#include "script/cc_error.h"
-#include "script/cc_script.h"
-#include "script/script_common.h"
-#include "util/stream.h"
-#include "util/string_compat.h"
+//include <stdlib.h>
+//include <string.h>
+#include "ags/shared/script/cc_error.h"
+#include "ags/shared/script/cc_script.h"
+#include "ags/shared/script/script_common.h"
+#include "ags/shared/util/stream.h"
+#include "ags/shared/util/string_compat.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/script/cc_script.h b/engines/ags/shared/script/cc_script.h
index e1390caa8c..53b3c4a750 100644
--- a/engines/ags/shared/script/cc_script.h
+++ b/engines/ags/shared/script/cc_script.h
@@ -29,8 +29,8 @@
 #ifndef AGS_SHARED_SCRIPT_CC_SCRIPT_H
 #define AGS_SHARED_SCRIPT_CC_SCRIPT_H
 
-#include <memory>
-#include "core/types.h"
+//include <memory>
+#include "ags/shared/core/types.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/util/alignedstream.cpp b/engines/ags/shared/util/alignedstream.cpp
index 9601283e69..8a8c24efa8 100644
--- a/engines/ags/shared/util/alignedstream.cpp
+++ b/engines/ags/shared/util/alignedstream.cpp
@@ -20,9 +20,9 @@
  *
  */
 
-#include "debug/assert.h"
-#include "util/alignedstream.h"
-#include "util/math.h"
+#include "ags/shared/debugging/assert.h"
+#include "ags/shared/util/alignedstream.h"
+#include "ags/shared/util/math.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/util/alignedstream.h b/engines/ags/shared/util/alignedstream.h
index 8d9d90a42a..494854aaba 100644
--- a/engines/ags/shared/util/alignedstream.h
+++ b/engines/ags/shared/util/alignedstream.h
@@ -45,7 +45,7 @@
 #ifndef AGS_SHARED_UTIL_ALIGNEDSTREAM_H
 #define AGS_SHARED_UTIL_ALIGNEDSTREAM_H
 
-#include "util/proxystream.h"
+#include "ags/shared/util/proxystream.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/util/bbop.h b/engines/ags/shared/util/bbop.h
index c8cb850ed8..48764722f8 100644
--- a/engines/ags/shared/util/bbop.h
+++ b/engines/ags/shared/util/bbop.h
@@ -29,8 +29,8 @@
 #ifndef AGS_SHARED_UTIL_BBOP_H
 #define AGS_SHARED_UTIL_BBOP_H
 
-#include "core/platform.h"
-#include "core/types.h"
+#include "ags/shared/core/platform.h"
+#include "ags/shared/core/types.h"
 
 #if AGS_PLATFORM_ENDIAN_BIG || defined (TEST_BIGENDIAN)
 #define BITBYTE_BIG_ENDIAN
diff --git a/engines/ags/shared/util/bufferedstream.cpp b/engines/ags/shared/util/bufferedstream.cpp
index 30d385f050..69e81b5cbc 100644
--- a/engines/ags/shared/util/bufferedstream.cpp
+++ b/engines/ags/shared/util/bufferedstream.cpp
@@ -20,12 +20,12 @@
  *
  */
 
-#include <algorithm>
-#include <cstring>
-#include <stdexcept>
-#include "util/bufferedstream.h"
-#include "util/stdio_compat.h"
-#include "util/string.h"
+#include "ags/std/algorithm.h"
+#include "ags/std/memory.h"
+#include "ags/shared/util/bufferedstream.h"
+#include "ags/shared/util/stdio_compat.h"
+#include "ags/shared/util/string.h"
+#include "common/textconsole.h"
 
 namespace AGS3 {
 namespace AGS {
@@ -34,14 +34,14 @@ namespace Shared {
 BufferedStream::BufferedStream(const String &file_name, FileOpenMode open_mode, FileWorkMode work_mode, DataEndianess stream_endianess)
 	: FileStream(file_name, open_mode, work_mode, stream_endianess), _buffer(BufferStreamSize), _bufferPosition(0), _position(0) {
 	if (FileStream::Seek(0, kSeekEnd) == false)
-		throw std::runtime_error("Error determining stream end.");
+		error("Error determining stream end.");
 
 	_end = FileStream::GetPosition();
 	if (_end == -1)
-		throw std::runtime_error("Error determining stream end.");
+		error("Error determining stream end.");
 
 	if (FileStream::Seek(0, kSeekBegin) == false)
-		throw std::runtime_error("Error determining stream end.");
+		error("Error determining stream end.");
 
 	_buffer.resize(0);
 
diff --git a/engines/ags/shared/util/bufferedstream.h b/engines/ags/shared/util/bufferedstream.h
index 1f4bb3a22f..ffc16c2de4 100644
--- a/engines/ags/shared/util/bufferedstream.h
+++ b/engines/ags/shared/util/bufferedstream.h
@@ -23,9 +23,9 @@
 #ifndef AGS_SHARED_UTIL_BUFFEREDSTREAM_H
 #define AGS_SHARED_UTIL_BUFFEREDSTREAM_H
 
-#include <vector>
-#include "util/filestream.h"
-#include "util/file.h" // TODO: extract filestream mode constants
+#include "ags/std/vector.h"
+#include "ags/shared/util/filestream.h"
+#include "ags/shared/util/file.h" // TODO: extract filestream mode constants
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/util/compress.cpp b/engines/ags/shared/util/compress.cpp
index d707ab8b55..0b8a455966 100644
--- a/engines/ags/shared/util/compress.cpp
+++ b/engines/ags/shared/util/compress.cpp
@@ -20,21 +20,14 @@
  *
  */
 
-#ifdef _MANAGED
-// ensure this doesn't get compiled to .NET IL
-#pragma unmanaged
-#endif
-
-#include <stdlib.h>
-#include <stdio.h>
-#include "ac/common.h"  // quit, update_polled_stuff
-#include "gfx/bitmap.h"
-#include "util/compress.h"
-#include "util/lzw.h"
-#include "util/misc.h"
-#include "util/stream.h"
+#include "ags/shared/ac/common.h"  // quit, update_polled_stuff
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/util/compress.h"
+#include "ags/shared/util/lzw.h"
+#include "ags/shared/util/misc.h"
+#include "ags/shared/util/stream.h"
 #if AGS_PLATFORM_ENDIAN_BIG
-#include "util/bbop.h"
+#include "ags/shared/util/bbop.h"
 #endif
 
 namespace AGS3 {
diff --git a/engines/ags/shared/util/compress.h b/engines/ags/shared/util/compress.h
index 0c4b8016a8..f8e8d7c833 100644
--- a/engines/ags/shared/util/compress.h
+++ b/engines/ags/shared/util/compress.h
@@ -23,7 +23,8 @@
 #ifndef AGS_SHARED_UTIL_COMPRESS_H
 #define AGS_SHARED_UTIL_COMPRESS_H
 
-#include "util/wgt2allg.h" // color (allegro RGB)
+#include "ags/shared/core/types.h"
+#include "ags/shared/util/wgt2allg.h" // color (allegro RGB)
 
 namespace AGS3 {
 
@@ -36,22 +37,22 @@ class Bitmap;
 
 using namespace AGS; // FIXME later
 
-void csavecompressed(Common::Stream *out, const unsigned char *tobesaved, const color pala[256]);
+void csavecompressed(Shared::Stream *out, const unsigned char *tobesaved, const color pala[256]);
 // RLE compression
-void cpackbitl(const uint8_t *line, int size, Common::Stream *out);
-void cpackbitl16(const uint16_t *line, int size, Common::Stream *out);
-void cpackbitl32(const uint32_t *line, int size, Common::Stream *out);
+void cpackbitl(const uint8_t *line, int size, Shared::Stream *out);
+void cpackbitl16(const uint16_t *line, int size, Shared::Stream *out);
+void cpackbitl32(const uint32_t *line, int size, Shared::Stream *out);
 // RLE decompression
-int  cunpackbitl(uint8_t *line, int size, Common::Stream *in);
-int  cunpackbitl16(uint16_t *line, int size, Common::Stream *in);
-int  cunpackbitl32(uint32_t *line, int size, Common::Stream *in);
+int  cunpackbitl(uint8_t *line, int size, Shared::Stream *in);
+int  cunpackbitl16(uint16_t *line, int size, Shared::Stream *in);
+int  cunpackbitl32(uint32_t *line, int size, Shared::Stream *in);
 
 //=============================================================================
 
-void save_lzw(Common::Stream *out, const Common::Bitmap *bmpp, const color *pall);
-void load_lzw(Common::Stream *in, Common::Bitmap **bmm, int dst_bpp, color *pall);
-void savecompressed_allegro(Common::Stream *out, const Common::Bitmap *bmpp, const color *pall);
-void loadcompressed_allegro(Common::Stream *in, Common::Bitmap **bimpp, color *pall);
+void save_lzw(Shared::Stream *out, const Shared::Bitmap *bmpp, const color *pall);
+void load_lzw(Shared::Stream *in, Shared::Bitmap **bmm, int dst_bpp, color *pall);
+void savecompressed_allegro(Shared::Stream *out, const Shared::Bitmap *bmpp, const color *pall);
+void loadcompressed_allegro(Shared::Stream *in, Shared::Bitmap **bimpp, color *pall);
 
 } // namespace AGS3
 
diff --git a/engines/ags/shared/util/datastream.cpp b/engines/ags/shared/util/datastream.cpp
index 1eb27225ae..9ec8f39fff 100644
--- a/engines/ags/shared/util/datastream.cpp
+++ b/engines/ags/shared/util/datastream.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "util/datastream.h"
+#include "ags/shared/util/datastream.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/util/datastream.h b/engines/ags/shared/util/datastream.h
index 16322fd4aa..4e45ba1c7b 100644
--- a/engines/ags/shared/util/datastream.h
+++ b/engines/ags/shared/util/datastream.h
@@ -31,8 +31,8 @@
 #ifndef AGS_SHARED_UTIL_DATASTREAM_H
 #define AGS_SHARED_UTIL_DATASTREAM_H
 
-#include "util/bbop.h"
-#include "util/stream.h"
+#include "ags/shared/util/bbop.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/util/directory.cpp b/engines/ags/shared/util/directory.cpp
index e8c790cb60..5bbecdb074 100644
--- a/engines/ags/shared/util/directory.cpp
+++ b/engines/ags/shared/util/directory.cpp
@@ -20,17 +20,12 @@
  *
  */
 
-#include "core/platform.h"
-#include <errno.h>
-#if AGS_PLATFORM_OS_WINDOWS
-#include <direct.h>
-#else
-#include <sys/stat.h>
-#include <unistd.h>
-#endif
-#include "util/directory.h"
-#include "util/path.h"
-#include "stdio_compat.h"
+#include "ags/shared/core/platform.h"
+#include "ags/shared/util/directory.h"
+#include "ags/shared/util/path.h"
+#include "ags/shared/util/stdio_compat.h"
+#include "common/config-manager.h"
+#include "common/fs.h"
 
 namespace AGS3 {
 namespace AGS {
@@ -39,11 +34,7 @@ namespace Shared {
 namespace Directory {
 
 bool CreateDirectory(const String &path) {
-	return mkdir(path
-#if ! AGS_PLATFORM_OS_WINDOWS
-		, 0755
-#endif
-	) == 0 || errno == EEXIST;
+	return Common::FSNode(path.GetNullableCStr()).createDirectory();
 }
 
 bool CreateAllDirectories(const String &parent, const String &path) {
@@ -68,16 +59,22 @@ bool CreateAllDirectories(const String &parent, const String &path) {
 }
 
 String SetCurrentDirectory(const String &path) {
-	chdir(path);
-	return GetCurrentDirectory();
+	warning("TODO: SetCurrentDirectory: %s", path.GetNullableCStr());
+//	chdir(path);
+//	return GetCurrentDirectory();
+	return path;
 }
 
 String GetCurrentDirectory() {
+#ifdef TODO
 	char buf[512];
 	getcwd(buf, 512);
 	String str(buf);
 	Path::FixupPath(str);
 	return str;
+#else
+	return ConfMan.get("path");
+#endif
 }
 
 } // namespace Directory
diff --git a/engines/ags/shared/util/directory.h b/engines/ags/shared/util/directory.h
index 07f5cac469..754e6837bb 100644
--- a/engines/ags/shared/util/directory.h
+++ b/engines/ags/shared/util/directory.h
@@ -29,8 +29,8 @@
 #ifndef AGS_SHARED_UTIL_DIRECTORY_H
 #define AGS_SHARED_UTIL_DIRECTORY_H
 
-#include "core/platform.h"
-#include "util/string.h"
+#include "ags/shared/core/platform.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/util/error.h b/engines/ags/shared/util/error.h
index f404b44ae3..4a983dfea4 100644
--- a/engines/ags/shared/util/error.h
+++ b/engines/ags/shared/util/error.h
@@ -30,8 +30,8 @@
 #ifndef AGS_SHARED_UTIL_ERROR_H
 #define AGS_SHARED_UTIL_ERROR_H
 
-#include <memory>
-#include "util/string.h"
+#include "ags/std/memory.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/util/file.cpp b/engines/ags/shared/util/file.cpp
index f02286c8cb..e94d56e9e0 100644
--- a/engines/ags/shared/util/file.cpp
+++ b/engines/ags/shared/util/file.cpp
@@ -20,14 +20,14 @@
  *
  */
 
-#include "util/file.h"
-
-#include <stdexcept>
-#include "core/platform.h"
-#include "util/stdio_compat.h"
-#include <errno.h>
-#include "util/filestream.h"
-#include "util/bufferedstream.h"
+#include "ags/shared/core/platform.h"
+#include "ags/shared/util/stdio_compat.h"
+#include "ags/shared/util/filestream.h"
+#include "ags/shared/util/bufferedstream.h"
+#include "ags/shared/util/file.h"
+#include "common/file.h"
+#include "common/savefile.h"
+#include "common/system.h"
 
 namespace AGS3 {
 namespace AGS {
@@ -38,46 +38,24 @@ soff_t File::GetFileSize(const String &filename) {
 }
 
 bool File::TestReadFile(const String &filename) {
-	FILE *test_file = fopen(filename, "rb");
-	if (test_file) {
-		fclose(test_file);
-		return true;
-	}
-	return false;
+	return Common::File::exists(filename.GetNullableCStr());
 }
 
 bool File::TestWriteFile(const String &filename) {
-	FILE *test_file = fopen(filename, "r+");
-	if (test_file) {
-		fclose(test_file);
-		return true;
-	}
 	return TestCreateFile(filename);
 }
 
 bool File::TestCreateFile(const String &filename) {
-	FILE *test_file = fopen(filename, "wb");
-	if (test_file) {
-		fclose(test_file);
-		::remove(filename);
-		return true;
-	}
-	return false;
+	Common::DumpFile df;
+
+	bool result = df.open(filename.GetNullableCStr());
+	df.close();
+
+	return result;
 }
 
 bool File::DeleteFile(const String &filename) {
-	if (::remove(filename) != 0) {
-		int err;
-#if AGS_PLATFORM_OS_WINDOWS
-		_get_errno(&err);
-#else
-		err = errno;
-#endif
-		if (err == EACCES) {
-			return false;
-		}
-	}
-	return true;
+	return g_system->getSavefileManager()->removeSavefile(filename.GetNullableCStr());
 }
 
 bool File::GetFileModesFromCMode(const String &cmode, FileOpenMode &open_mode, FileWorkMode &work_mode) {
@@ -137,7 +115,7 @@ String File::GetCMode(FileOpenMode open_mode, FileWorkMode work_mode) {
 
 Stream *File::OpenFile(const String &filename, FileOpenMode open_mode, FileWorkMode work_mode) {
 	FileStream *fs = nullptr;
-	try {
+//	try {
 		if (work_mode == kFile_Read) // NOTE: BufferedStream does not work correctly in the write mode
 			fs = new BufferedStream(filename, open_mode, work_mode);
 		else
@@ -146,9 +124,10 @@ Stream *File::OpenFile(const String &filename, FileOpenMode open_mode, FileWorkM
 			delete fs;
 			fs = nullptr;
 		}
-	} catch (std::runtime_error) {
-		fs = nullptr;
-	}
+//	} catch (std::runtime_error) {
+//		fs = nullptr;
+//	}
+
 	return fs;
 }
 
diff --git a/engines/ags/shared/util/file.h b/engines/ags/shared/util/file.h
index 73f21201cd..e858b75f78 100644
--- a/engines/ags/shared/util/file.h
+++ b/engines/ags/shared/util/file.h
@@ -29,8 +29,8 @@
 #ifndef AGS_SHARED_UTIL_FILE_H
 #define AGS_SHARED_UTIL_FILE_H
 
-#include "core/platform.h"
-#include "util/string.h"
+#include "ags/shared/core/platform.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/util/filestream.cpp b/engines/ags/shared/util/filestream.cpp
index db89789493..5134f2e046 100644
--- a/engines/ags/shared/util/filestream.cpp
+++ b/engines/ags/shared/util/filestream.cpp
@@ -20,11 +20,10 @@
  *
  */
 
-#include "util/filestream.h"
-
-#include <stdexcept>
-#include "util/stdio_compat.h"
-#include "util/string.h"
+#include "ags/shared/util/filestream.h"
+#include "ags/shared/util/stdio_compat.h"
+#include "ags/shared/util/string.h"
+#include "common/file.h"
 
 namespace AGS3 {
 namespace AGS {
@@ -44,20 +43,21 @@ FileStream::~FileStream() {
 }
 
 bool FileStream::HasErrors() const {
-	return IsValid() && ferror(_file) != 0;
+	return IsValid() && _file->err();
 }
 
 void FileStream::Close() {
 	if (_file) {
-		fclose(_file);
+		delete _file;
 	}
 	_file = nullptr;
 }
 
 bool FileStream::Flush() {
-	if (_file) {
-		return fflush(_file) == 0;
-	}
+	Common::WriteStream *ws = dynamic_cast<Common::WriteStream *>(_file);
+	if (ws)
+		ws->flush();
+
 	return false;
 }
 
@@ -66,7 +66,8 @@ bool FileStream::IsValid() const {
 }
 
 bool FileStream::EOS() const {
-	return !IsValid() || feof(_file) != 0;
+	Common::ReadStream *rs = dynamic_cast<Common::ReadStream *>(_file);
+	return !rs || rs->eos();
 }
 
 soff_t FileStream::GetLength() const {
@@ -101,30 +102,43 @@ bool FileStream::CanSeek() const {
 }
 
 size_t FileStream::Read(void *buffer, size_t size) {
-	if (_file && buffer) {
-		return fread(buffer, sizeof(uint8_t), size, _file);
+	Common::ReadStream *rs = dynamic_cast<Common::ReadStream *>(_file);
+
+	if (rs && buffer) {
+		return rs->read(buffer, size);
 	}
+
 	return 0;
 }
 
 int32_t FileStream::ReadByte() {
-	if (_file) {
-		return fgetc(_file);
+	Common::ReadStream *rs = dynamic_cast<Common::ReadStream *>(_file);
+
+	if (rs) {
+		return rs->eos() ? -1 : (int32_t)rs->readByte();
 	}
+
 	return -1;
 }
 
 size_t FileStream::Write(const void *buffer, size_t size) {
-	if (_file && buffer) {
-		return fwrite(buffer, sizeof(uint8_t), size, _file);
+	Common::WriteStream *ws = dynamic_cast<Common::WriteStream *>(_file);
+
+	if (ws && buffer) {
+		return ws->write(buffer, size);
 	}
+
 	return 0;
 }
 
 int32_t FileStream::WriteByte(uint8_t val) {
-	if (_file) {
-		return fputc(val, _file);
+	Common::WriteStream *ws = dynamic_cast<Common::WriteStream *>(_file);
+
+	if (ws) {
+		ws->writeByte(val);
+		return 1;
 	}
+
 	return -1;
 }
 
@@ -153,12 +167,27 @@ bool FileStream::Seek(soff_t offset, StreamSeek origin) {
 }
 
 void FileStream::Open(const String &file_name, FileOpenMode open_mode, FileWorkMode work_mode) {
-	String mode = File::GetCMode(open_mode, work_mode);
-	if (mode.IsEmpty())
-		throw std::runtime_error("Error determining open mode");
-	_file = fopen(file_name, mode);
+	if (open_mode == kFile_Open) {
+		Common::File *f = new Common::File();
+		if (!f->open(file_name.GetNullableCStr())) {
+			delete f;
+			_file = nullptr;
+		} else {
+			_file = f;
+		}
+
+	} else {
+		Common::DumpFile *f = new Common::DumpFile();
+		if (!f->open(file_name.GetNullableCStr())) {
+			delete f;
+			_file = nullptr;
+		} else {
+			_file = f;
+		}
+	}
+
 	if (_file == nullptr)
-		throw std::runtime_error("Error opening file.");
+		error("Error opening file.");
 }
 
 } // namespace Shared
diff --git a/engines/ags/shared/util/filestream.h b/engines/ags/shared/util/filestream.h
index 77aae7dac1..69d56f6f9a 100644
--- a/engines/ags/shared/util/filestream.h
+++ b/engines/ags/shared/util/filestream.h
@@ -23,10 +23,11 @@
 #ifndef AGS_SHARED_UTIL_FILESTREAM_H
 #define AGS_SHARED_UTIL_FILESTREAM_H
 
-#include <stdio.h>
+//include <stdio.h>
 
-#include "util/datastream.h"
-#include "util/file.h" // TODO: extract filestream mode constants
+#include "ags/shared/util/datastream.h"
+#include "ags/shared/util/file.h" // TODO: extract filestream mode constants
+#include "common/stream.h"
 
 namespace AGS3 {
 namespace AGS {
@@ -69,7 +70,7 @@ public:
 private:
 	void            Open(const String &file_name, FileOpenMode open_mode, FileWorkMode work_mode);
 
-	FILE *_file;
+	Common::Stream *_file;
 	const FileOpenMode  _openMode;
 	const FileWorkMode  _workMode;
 };
diff --git a/engines/ags/shared/util/geometry.cpp b/engines/ags/shared/util/geometry.cpp
index 770344f3af..5da09aabd1 100644
--- a/engines/ags/shared/util/geometry.cpp
+++ b/engines/ags/shared/util/geometry.cpp
@@ -20,9 +20,10 @@
  *
  */
 
-#include "util/geometry.h"
-#include <algorithm>
-#include <cmath>
+#include "ags/shared/util/geometry.h"
+#include "ags/std/algorithm.h"
+#include "ags/std/algorithm.h"
+//include <cmath>
 
 namespace AGS3 {
 
@@ -52,7 +53,7 @@ float DistanceBetween(const Rect &r1, const Rect &r2) {
 	);
 	int inner_width = std::max(0, rect_outer.GetWidth() - r1.GetWidth() - r2.GetWidth());
 	int inner_height = std::max(0, rect_outer.GetHeight() - r1.GetHeight() - r2.GetHeight());
-	return std::sqrt(inner_width ^ 2 + inner_height ^ 2);
+	return std::sqrt((inner_width ^ 2) + (inner_height ^ 2));
 }
 
 Size ProportionalStretch(int dest_w, int dest_h, int item_w, int item_h) {
diff --git a/engines/ags/shared/util/geometry.h b/engines/ags/shared/util/geometry.h
index 570868df7c..d24e33ada2 100644
--- a/engines/ags/shared/util/geometry.h
+++ b/engines/ags/shared/util/geometry.h
@@ -29,7 +29,7 @@
 #ifndef AGS_SHARED_UTIL_GEOMETRY_H
 #define AGS_SHARED_UTIL_GEOMETRY_H
 
-#include "util/math.h"
+#include "ags/shared/util/math.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/util/ini_util.cpp b/engines/ags/shared/util/ini_util.cpp
index 7c7bb0b1f8..e4849740d2 100644
--- a/engines/ags/shared/util/ini_util.cpp
+++ b/engines/ags/shared/util/ini_util.cpp
@@ -20,12 +20,12 @@
  *
  */
 
-#include <memory>
-#include "util/file.h"
-#include "util/ini_util.h"
-#include "util/inifile.h"
-#include "util/stream.h"
-#include "util/textstreamwriter.h"
+#include "ags/std/memory.h"
+#include "ags/shared/util/file.h"
+#include "ags/shared/util/ini_util.h"
+#include "ags/shared/util/inifile.h"
+#include "ags/shared/util/stream.h"
+#include "ags/shared/util/textstreamwriter.h"
 
 namespace AGS3 {
 namespace AGS {
@@ -71,8 +71,8 @@ void IniUtil::Write(const String &file, const ConfigTree &tree) {
 	TextStreamWriter writer(fs.get());
 
 	for (ConfigNode it_sec = tree.begin(); it_sec != tree.end(); ++it_sec) {
-		const String &sec_key = it_sec->first;
-		const StringOrderMap &sec_tree = it_sec->second;
+		const String &sec_key = it_sec->_key;
+		const StringOrderMap &sec_tree = it_sec->_value;
 
 		if (!sec_tree.size())
 			continue; // skip empty sections
@@ -83,8 +83,8 @@ void IniUtil::Write(const String &file, const ConfigTree &tree) {
 		}
 		// write all items
 		for (StrStrOIter keyval = sec_tree.begin(); keyval != sec_tree.end(); ++keyval) {
-			const String &item_key = keyval->first;
-			const String &item_value = keyval->second;
+			const String &item_key = keyval->_key;
+			const String &item_value = keyval->_value;
 
 			writer.WriteFormat("%s = %s", item_key.GetCStr(), item_value.GetCStr());
 			writer.WriteLineBreak();
@@ -96,8 +96,8 @@ void IniUtil::Write(const String &file, const ConfigTree &tree) {
 
 void IniUtil::WriteToString(String &s, const ConfigTree &tree) {
 	for (ConfigNode it_sec = tree.begin(); it_sec != tree.end(); ++it_sec) {
-		const String &sec_key = it_sec->first;
-		const StringOrderMap &sec_tree = it_sec->second;
+		const String &sec_key = it_sec->_key;
+		const StringOrderMap &sec_tree = it_sec->_value;
 		if (!sec_tree.size())
 			continue; // skip empty sections
 		// write section name
@@ -105,7 +105,7 @@ void IniUtil::WriteToString(String &s, const ConfigTree &tree) {
 			s.Append(String::FromFormat("[%s]\n", sec_key.GetCStr()));
 		// write all items
 		for (StrStrOIter keyval = sec_tree.begin(); keyval != sec_tree.end(); ++keyval)
-			s.Append(String::FromFormat("%s = %s\n", keyval->first.GetCStr(), keyval->second.GetCStr()));
+			s.Append(String::FromFormat("%s = %s\n", keyval->_key.GetCStr(), keyval->_value.GetCStr()));
 	}
 }
 
@@ -118,7 +118,7 @@ bool IniUtil::Merge(const String &file, const ConfigTree &tree) {
 	// they will be appended to the end of file.
 	std::map<String, bool> sections_found;
 	for (ConfigNode it = tree.begin(); it != tree.end(); ++it)
-		sections_found[it->first] = false;
+		sections_found[it->_key] = false;
 
 	// Merge existing sections
 	for (SectionIterator sec = ini.Begin(); sec != ini.End(); ++sec) {
@@ -131,10 +131,10 @@ bool IniUtil::Merge(const String &file, const ConfigTree &tree) {
 
 		// Remember the items we find in this section, if some items are not found,
 		// they will be appended to the end of section.
-		const StringOrderMap &subtree = tree_node->second;
+		const StringOrderMap &subtree = tree_node->_value;
 		std::map<String, bool> items_found;
 		for (StrStrOIter keyval = subtree.begin(); keyval != subtree.end(); ++keyval)
-			items_found[keyval->first] = false;
+			items_found[keyval->_key] = false;
 
 		// Replace matching items
 		for (ItemIterator item = sec->Begin(); item != sec->End(); ++item) {
@@ -144,7 +144,7 @@ bool IniUtil::Merge(const String &file, const ConfigTree &tree) {
 				continue; // this item is not interesting for us
 
 			String old_value = item->GetValue();
-			String new_value = keyval->second;
+			String new_value = keyval->_value;
 			if (old_value != new_value)
 				item->SetValue(new_value);
 			items_found[key] = true;
@@ -153,10 +153,10 @@ bool IniUtil::Merge(const String &file, const ConfigTree &tree) {
 		// Append new items
 		if (!sections_found[secname]) {
 			for (std::map<String, bool>::const_iterator item_f = items_found.begin(); item_f != items_found.end(); ++item_f) {
-				if (item_f->second)
+				if (item_f->_value)
 					continue; // item was already found
-				StrStrOIter keyval = subtree.find(item_f->first);
-				ini.InsertItem(sec, sec->End(), keyval->first, keyval->second);
+				StrStrOIter keyval = subtree.find(item_f->_key);
+				ini.InsertItem(sec, sec->End(), keyval->_key, keyval->_value);
 			}
 			sections_found[secname] = true; // mark section as known
 		}
@@ -164,12 +164,12 @@ bool IniUtil::Merge(const String &file, const ConfigTree &tree) {
 
 	// Add new sections
 	for (std::map<String, bool>::const_iterator sec_f = sections_found.begin(); sec_f != sections_found.end(); ++sec_f) {
-		if (sec_f->second)
+		if (sec_f->_value)
 			continue;
-		SectionIterator sec = ini.InsertSection(ini.End(), sec_f->first);
-		const StringOrderMap &subtree = tree.find(sec_f->first)->second;
+		SectionIterator sec = ini.InsertSection(ini.End(), sec_f->_key);
+		const StringOrderMap &subtree = tree.find(sec_f->_key)->_value;
 		for (StrStrOIter keyval = subtree.begin(); keyval != subtree.end(); ++keyval)
-			ini.InsertItem(sec, sec->End(), keyval->first, keyval->second);
+			ini.InsertItem(sec, sec->End(), keyval->_key, keyval->_value);
 	}
 
 	// Write the resulting set of lines
diff --git a/engines/ags/shared/util/ini_util.h b/engines/ags/shared/util/ini_util.h
index 6a127f3652..c3fd2276db 100644
--- a/engines/ags/shared/util/ini_util.h
+++ b/engines/ags/shared/util/ini_util.h
@@ -30,20 +30,22 @@
 #ifndef AGS_SHARED_UTIL_INIUTIL_H
 #define AGS_SHARED_UTIL_INIUTIL_H
 
-#include <map>
-#include "util/string.h"
+#include "ags/std/map.h"
+#include "ags/shared/util/string.h"
+#include "ags/shared/util/string_types.h"
 
 namespace AGS3 {
 namespace AGS {
 namespace Shared {
 
-typedef std::map<String, String>         StringOrderMap;
+typedef std::map<String, String> StringOrderMap;
 typedef StringOrderMap::const_iterator   StrStrOIter;
 
 typedef std::map<String, StringOrderMap> ConfigTree;
 typedef ConfigTree::const_iterator       ConfigNode;
 
 namespace IniUtil {
+
 // Parse the contents of given file as INI format and insert values
 // into the tree. The pre-existing tree items, if any, are NOT erased.
 // Returns FALSE if the file could not be opened.
@@ -67,7 +69,8 @@ void WriteToString(String &s, const ConfigTree &tree);
 // or same stream opened for both reading and writing.
 // Returns FALSE if the file could not be opened for writing.
 bool Merge(const String &file, const ConfigTree &tree);
-};
+
+} // namespace IniUtil
 
 } // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/util/inifile.cpp b/engines/ags/shared/util/inifile.cpp
index 200fbe21fe..4c75cd8cd0 100644
--- a/engines/ags/shared/util/inifile.cpp
+++ b/engines/ags/shared/util/inifile.cpp
@@ -20,11 +20,11 @@
  *
  */
 
-#include <cctype>
-#include <string.h>
-#include "util/inifile.h"
-#include "util/textstreamreader.h"
-#include "util/textstreamwriter.h"
+//include <cctype>
+//include <string.h>
+#include "ags/shared/util/inifile.h"
+#include "ags/shared/util/textstreamreader.h"
+#include "ags/shared/util/textstreamwriter.h"
 
 namespace AGS3 {
 
@@ -155,7 +155,7 @@ void IniFile::RemoveSection(SectionIterator sec) {
 
 // Moves string pointer forward to the first non-space character
 const char *SkipSpace(const char *line, const char *endl) {
-	for (; line != endl && isspace(*line); ++line);
+	for (; line != endl && Common::isSpace(*line); ++line);
 	return line;
 }
 
diff --git a/engines/ags/shared/util/inifile.h b/engines/ags/shared/util/inifile.h
index eaa490c368..0008f7b13d 100644
--- a/engines/ags/shared/util/inifile.h
+++ b/engines/ags/shared/util/inifile.h
@@ -33,8 +33,9 @@
 #ifndef AGS_SHARED_UTIL_INIFILE_H
 #define AGS_SHARED_UTIL_INIFILE_H
 
-#include <list>
-#include "util/string.h"
+#include "ags/shared/util/string.h"
+#include "ags/std/utility.h"
+#include "ags/std/list.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/util/lzw.cpp b/engines/ags/shared/util/lzw.cpp
index 8c78f628e4..b93ec36cb4 100644
--- a/engines/ags/shared/util/lzw.cpp
+++ b/engines/ags/shared/util/lzw.cpp
@@ -26,9 +26,9 @@
 //
 //=============================================================================
 
-#include <stdlib.h>
-#include "ac/common.h" // quit
-#include "util/stream.h"
+//include <stdlib.h>
+#include "ags/shared/ac/common.h" // quit
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 
@@ -220,12 +220,12 @@ void myputc(int ccc, Stream *out) {
 
 void lzwexpand(Stream *lzw_in, Stream *out) {
 	int bits, ch, i, j, len, mask;
-	char *lzbuffer;
+	char *lzBuffer;
 	//  printf(" UnShrinking: %s ",filena);
 	putbytes = 0;
 
-	lzbuffer = (char *)malloc(N);
-	if (lzbuffer == nullptr) {
+	lzBuffer = (char *)malloc(N);
+	if (lzBuffer == nullptr) {
 		quit("compress.cpp: unable to decompress: insufficient memory");
 	}
 	i = N - F;
@@ -243,13 +243,13 @@ void lzwexpand(Stream *lzw_in, Stream *out) {
 				j = (i - j - 1) & (N - 1);
 
 				while (len--) {
-					myputc(lzbuffer[i] = lzbuffer[j], out);
+					myputc(lzBuffer[i] = lzBuffer[j], out);
 					j = (j + 1) & (N - 1);
 					i = (i + 1) & (N - 1);
 				}
 			} else {
 				ch = lzw_in->ReadByte();
-				myputc(lzbuffer[i] = ch, out);
+				myputc(lzBuffer[i] = ch, out);
 				i = (i + 1) & (N - 1);
 			}
 
@@ -264,7 +264,7 @@ void lzwexpand(Stream *lzw_in, Stream *out) {
 			break;
 	}
 
-	free(lzbuffer);
+	free(lzBuffer);
 	expand_to_mem = 0;
 }
 
diff --git a/engines/ags/shared/util/lzw.h b/engines/ags/shared/util/lzw.h
index 25171da1d3..bbb0404647 100644
--- a/engines/ags/shared/util/lzw.h
+++ b/engines/ags/shared/util/lzw.h
@@ -33,8 +33,8 @@ class Stream;
 
 using namespace AGS; // FIXME later
 
-void lzwcompress(Common::Stream *lzw_in, Common::Stream *out);
-unsigned char *lzwexpand_to_mem(Common::Stream *in);
+void lzwcompress(Shared::Stream *lzw_in, Shared::Stream *out);
+unsigned char *lzwexpand_to_mem(Shared::Stream *in);
 
 extern long outbytes, maxsize, putbytes;
 
diff --git a/engines/ags/shared/util/memory.h b/engines/ags/shared/util/memory.h
index 3b6a0f3c4e..29c6b791b5 100644
--- a/engines/ags/shared/util/memory.h
+++ b/engines/ags/shared/util/memory.h
@@ -29,9 +29,9 @@
 #ifndef AGS_SHARED_UTIL_MEMORY_H
 #define AGS_SHARED_UTIL_MEMORY_H
 
-#include <string.h>
-#include "util/bbop.h"
-#include "util/math.h"
+//include <string.h>
+#include "ags/shared/util/bbop.h"
+#include "ags/shared/util/math.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/util/misc.cpp b/engines/ags/shared/util/misc.cpp
index 71c6596c35..1bdad6992d 100644
--- a/engines/ags/shared/util/misc.cpp
+++ b/engines/ags/shared/util/misc.cpp
@@ -49,19 +49,19 @@
   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
 
-#include "core/platform.h"
+#include "ags/shared/core/platform.h"
 
-#include <stdio.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <string.h>
+//include <stdio.h>
+//include <sys/types.h>
+//include <sys/stat.h>
+//include <string.h>
 #if !AGS_PLATFORM_OS_WINDOWS
-#include <dirent.h>
+//include <dirent.h>
 #endif
 
-#include "allegro.h"
-#include "util/file.h"
-#include "util/stream.h"
+#include "ags/stubs/allegro.h"
+#include "ags/shared/util/file.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/util/misc.h b/engines/ags/shared/util/misc.h
index 1cd6e6efc3..c84500c929 100644
--- a/engines/ags/shared/util/misc.h
+++ b/engines/ags/shared/util/misc.h
@@ -52,7 +52,7 @@
 #ifndef AGS_SHARED_UTIL_MISC_H
 #define AGS_SHARED_UTIL_MISC_H
 
-#include "util/file.h" // TODO: extract filestream mode constants
+#include "ags/shared/util/file.h" // TODO: extract filestream mode constants
 
 namespace AGS3 {
 
@@ -70,9 +70,9 @@ using namespace AGS; // FIXME later
 // names in different character case.
 // They are used as a system-independent way to open a file when its name
 // case can be ignored.
-Common::Stream *ci_fopen(const char *file_name,
-	Common::FileOpenMode open_mode = Common::kFile_Open,
-	Common::FileWorkMode work_mode = Common::kFile_Read);
+Shared::Stream *ci_fopen(const char *file_name,
+	Shared::FileOpenMode open_mode = Shared::kFile_Open,
+	Shared::FileWorkMode work_mode = Shared::kFile_Read);
 // TODO: return String object
 char *ci_find_file(const char *dir_name, const char *file_name);
 
diff --git a/engines/ags/shared/util/multifilelib.h b/engines/ags/shared/util/multifilelib.h
index 49dad28c69..e79c4cbe24 100644
--- a/engines/ags/shared/util/multifilelib.h
+++ b/engines/ags/shared/util/multifilelib.h
@@ -34,8 +34,8 @@
 #ifndef AGS_SHARED_UTIL_MULTIFILELIB_H
 #define AGS_SHARED_UTIL_MULTIFILELIB_H
 
-#include "core/asset.h"
-#include "util/stream.h"
+#include "ags/shared/core/asset.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 namespace AGS {
@@ -45,6 +45,7 @@ namespace Shared {
 // MultiFileLib utilities: (de)serialization of asset library in MFL format
 //
 namespace MFLUtil {
+
 enum MFLError {
 	kMFLNoError = 0,
 	kMFLErrNoLibSig = -1, // library signature does not match
@@ -71,7 +72,8 @@ MFLError ReadHeader(AssetLibInfo &lib, Stream *in);
 
 void     WriteHeader(const AssetLibInfo &lib, MFLVersion lib_version, int lib_index, Stream *out);
 void     WriteEnder(soff_t lib_offset, MFLVersion lib_index, Stream *out);
-};
+
+} // namespace MFLUtil
 
 } // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/util/mutifilelib.cpp b/engines/ags/shared/util/mutifilelib.cpp
index 9d578e01bb..5d1eac5c5b 100644
--- a/engines/ags/shared/util/mutifilelib.cpp
+++ b/engines/ags/shared/util/mutifilelib.cpp
@@ -20,16 +20,17 @@
  *
  */
 
-#include "util/bbop.h"
-#include "util/multifilelib.h"
-#include "util/stream.h"
-#include "util/string_utils.h"
+#include "ags/shared/util/bbop.h"
+#include "ags/shared/util/multifilelib.h"
+#include "ags/shared/util/stream.h"
+#include "ags/shared/util/string_utils.h"
 
 namespace AGS3 {
 namespace AGS {
 namespace Shared {
 
 namespace MFLUtil {
+
 const String HeadSig = "CLIB\x1a";
 const String TailSig = "CLIB\x1\x2\x3\x4SIGE";
 
@@ -60,7 +61,8 @@ void     ReadEncArray(void *data, size_t size, size_t count, Stream *in, int &ra
 int8_t   ReadEncInt8(Stream *in, int &rand_val);
 int32_t  ReadEncInt32(Stream *in, int &rand_val);
 void     ReadEncString(char *buffer, size_t max_len, Stream *in, int &rand_val);
-};
+
+} // namespace  MFLUtil
 
 
 MFLUtil::MFLError MFLUtil::TestIsMFL(Stream *in, bool test_is_main) {
@@ -127,7 +129,7 @@ MFLUtil::MFLError MFLUtil::ReadSigsAndVersion(Stream *in, MFLVersion *p_lib_vers
 		soff_t abs_offset_32 = in->ReadInt32();
 
 		// test for header signature again, with 64-bit and 32-bit offsets if necessary
-		if (abs_offset > 0 && abs_offset < (tail_abs_offset - HeadSig.GetLength())) {
+		if (abs_offset > 0 && abs_offset < (soff_t)(tail_abs_offset - HeadSig.GetLength())) {
 			in->Seek(abs_offset, kSeekBegin);
 			sig.ReadCount(in, HeadSig.GetLength());
 		}
@@ -135,7 +137,7 @@ MFLUtil::MFLError MFLUtil::ReadSigsAndVersion(Stream *in, MFLVersion *p_lib_vers
 		// try again with 32-bit offset
 		if (HeadSig.Compare(sig) != 0) {
 			abs_offset = abs_offset_32;
-			if (abs_offset > 0 && abs_offset < (tail_abs_offset - HeadSig.GetLength())) {
+			if (abs_offset > 0 && abs_offset < (soff_t)(tail_abs_offset - HeadSig.GetLength())) {
 				in->Seek(abs_offset, kSeekBegin);
 				sig.ReadCount(in, HeadSig.GetLength());
 			}
diff --git a/engines/ags/shared/util/path.cpp b/engines/ags/shared/util/path.cpp
index ad47317fe7..763808bf2b 100644
--- a/engines/ags/shared/util/path.cpp
+++ b/engines/ags/shared/util/path.cpp
@@ -20,13 +20,14 @@
  *
  */
 
-#include "core/platform.h"
+#include "ags/shared/core/platform.h"
 #if AGS_PLATFORM_OS_WINDOWS
-#include <windows.h>
+//include <windows.h>
 #endif
-#include "allegro/file.h"
-#include "util/path.h"
-#include "util/stdio_compat.h"
+
+#include "ags/stubs/allegro/file.h"
+#include "ags/shared/util/path.h"
+#include "ags/shared/util/stdio_compat.h"
 
 namespace AGS3 {
 
@@ -80,7 +81,7 @@ String GetDirectoryPath(const String &path) {
 	String dir = path;
 	FixupPath(dir);
 	size_t slash_at = dir.FindCharReverse('/');
-	if (slash_at != -1) {
+	if (slash_at != String::npos) {
 		dir.ClipMid(slash_at + 1);
 		return dir;
 	}
diff --git a/engines/ags/shared/util/path.h b/engines/ags/shared/util/path.h
index 0901c6d57b..a78782e4ed 100644
--- a/engines/ags/shared/util/path.h
+++ b/engines/ags/shared/util/path.h
@@ -29,7 +29,7 @@
 #ifndef AGS_SHARED_UTIL_PATH_H
 #define AGS_SHARED_UTIL_PATH_H
 
-#include "util/string.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/util/proxystream.cpp b/engines/ags/shared/util/proxystream.cpp
index c8c810a7ab..c763c6fb2e 100644
--- a/engines/ags/shared/util/proxystream.cpp
+++ b/engines/ags/shared/util/proxystream.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "util/proxystream.h"
+#include "ags/shared/util/proxystream.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/util/proxystream.h b/engines/ags/shared/util/proxystream.h
index ef40dd10c4..915d3a0993 100644
--- a/engines/ags/shared/util/proxystream.h
+++ b/engines/ags/shared/util/proxystream.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_UTIL_PROXYSTREAM_H
 #define AGS_SHARED_UTIL_PROXYSTREAM_H
 
-#include "util/stream.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/util/stdio_compat.c b/engines/ags/shared/util/stdio_compat.c
deleted file mode 100644
index d3c7e25e3b..0000000000
--- a/engines/ags/shared/util/stdio_compat.c
+++ /dev/null
@@ -1,95 +0,0 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-
-#include "util/stdio_compat.h"
-
-#include "core/platform.h"
-#include <stdio.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-
-#if AGS_PLATFORM_OS_WINDOWS
-#include <windows.h>
-#include <shlwapi.h>
-#endif
-
-int	 ags_fseek(FILE * stream, file_off_t offset, int whence)
-{
-#if defined(HAVE_FSEEKO) // Contemporary POSIX libc
-    return fseeko(stream, offset, whence);
-#elif AGS_PLATFORM_OS_WINDOWS // MSVC
-    return _fseeki64(stream, offset, whence); 
-#else // No distinct interface with off_t
-    return fseek(stream, offset, whence);
-#endif
-}
-
-file_off_t ags_ftell(FILE * stream) 
-{
-    #if defined(HAVE_FSEEKO) // Contemporary POSIX libc
-        return ftello(stream);
-    #elif AGS_PLATFORM_OS_WINDOWS // MSVC
-        return _ftelli64(stream); 
-    #else // No distinct interface with off_t
-        return ftell(stream);
-    #endif
-}
-
-int  ags_file_exists(const char *path) 
-{
-#if AGS_PLATFORM_OS_WINDOWS
-    return PathFileExistsA(path) && ! PathIsDirectoryA(path);
-#else
-    struct stat path_stat;
-    if (stat(path, &path_stat) != 0) {
-        return 0;
-    }
-    return S_ISREG(path_stat.st_mode);
-#endif
-}
-
-int ags_directory_exists(const char *path)
-{
-#if AGS_PLATFORM_OS_WINDOWS
-    return PathFileExistsA(path) && PathIsDirectoryA(path);
-#else
-    struct stat path_stat;
-    if (stat(path, &path_stat) != 0) {
-        return 0;
-    }
-    return S_ISDIR(path_stat.st_mode);
-#endif
-}
-
-int ags_path_exists(const char *path)
-{
-    #if AGS_PLATFORM_OS_WINDOWS
-        return PathFileExistsA(path);
-    #else
-        struct stat path_stat;
-        if (stat(path, &path_stat) != 0) {
-            return 0;
-        }
-        return S_ISREG(path_stat.st_mode) || S_ISDIR(path_stat.st_mode);
-    #endif
-}
-
-file_off_t ags_file_size(const char *path)
-{
-    struct stat path_stat;
-    if (stat(path, &path_stat) != 0) {
-        return -1;
-    }
-    return path_stat.st_size;
-}
diff --git a/engines/ags/shared/util/stdio_compat.cpp b/engines/ags/shared/util/stdio_compat.cpp
new file mode 100644
index 0000000000..8a0048364d
--- /dev/null
+++ b/engines/ags/shared/util/stdio_compat.cpp
@@ -0,0 +1,67 @@
+/* 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 "ags/shared/util/stdio_compat.h"
+#include "ags/shared/core/platform.h"
+#include "common/file.h"
+#include "common/fs.h"
+#include "common/textconsole.h"
+
+namespace AGS3 {
+
+int	 ags_fseek(Common::Stream *stream, file_off_t offset, int whence) {
+	Common::SeekableReadStream *rs = dynamic_cast<Common::SeekableReadStream *>(stream);
+	Common::SeekableWriteStream *ws = dynamic_cast<Common::SeekableWriteStream *>(stream);
+
+	if (rs)
+		return rs->seek(offset, whence);
+	else if (ws)
+		return ws->seek(offset, whence);
+	else
+		error("Seek on null stream");
+}
+
+file_off_t ags_ftell(FILE *stream) {
+	return stream->pos();
+}
+
+int  ags_file_exists(const char *path) {
+	Common::FSNode fs(path);
+	return fs.exists() && !fs.isDirectory()  ? 0 : -1;
+}
+
+int ags_directory_exists(const char *path) {
+	Common::FSNode fs(path);
+	return fs.exists() && fs.isDirectory() ? 0 : -1;
+}
+
+int ags_path_exists(const char *path) {
+	return Common::FSNode(path).exists() ? 0 : -1;
+}
+
+file_off_t ags_file_size(const char *path) {
+	Common::File f;
+
+	return f.open(path) ? f.size() : (file_off_t )-1;
+}
+
+} // namespace AGS3
diff --git a/engines/ags/shared/util/stdio_compat.h b/engines/ags/shared/util/stdio_compat.h
index 289d23b6e3..c930546b03 100644
--- a/engines/ags/shared/util/stdio_compat.h
+++ b/engines/ags/shared/util/stdio_compat.h
@@ -20,27 +20,26 @@
  *
  */
 
-#ifndef AGS_SHARED_UTIL_STDIOCOMPAT_H
-#define AGS_SHARED_UTIL_STDIOCOMPAT_H
+#ifndef AGS_SHARED_UTIL_STDIO_COMPAT_H
+#define AGS_SHARED_UTIL_STDIO_COMPAT_H
 
-#include <stdio.h>
-#include <stdint.h>
+#include "common/stream.h"
 
 namespace AGS3 {
 
-typedef int64_t file_off_t;
+typedef int64 file_off_t;
 
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-	int  ags_fseek(FILE *stream, file_off_t offset, int whence);
-	file_off_t   ags_ftell(FILE *stream);
+int  ags_fseek(Common::Stream *stream, file_off_t offset, int whence);
+file_off_t ags_ftell(Common::Stream *stream);
 
-	int ags_file_exists(const char *path);
-	int ags_directory_exists(const char *path);
-	int ags_path_exists(const char *path);
-	file_off_t ags_file_size(const char *path);
+int ags_file_exists(const char *path);
+int ags_directory_exists(const char *path);
+int ags_path_exists(const char *path);
+file_off_t ags_file_size(const char *path);
 
 #ifdef __cplusplus
 }
diff --git a/engines/ags/shared/util/stream.cpp b/engines/ags/shared/util/stream.cpp
index 29a46cafb0..8eed38dd39 100644
--- a/engines/ags/shared/util/stream.cpp
+++ b/engines/ags/shared/util/stream.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "util/stream.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/util/stream.h b/engines/ags/shared/util/stream.h
index 90cb0011e5..9940e96695 100644
--- a/engines/ags/shared/util/stream.h
+++ b/engines/ags/shared/util/stream.h
@@ -35,7 +35,7 @@
 #ifndef AGS_SHARED_UTIL_STREAM_H
 #define AGS_SHARED_UTIL_STREAM_H
 
-#include "api/stream_api.h"
+#include "ags/shared/api/stream_api.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/util/string.cpp b/engines/ags/shared/util/string.cpp
index cff8342c58..49c5fad5ac 100644
--- a/engines/ags/shared/util/string.cpp
+++ b/engines/ags/shared/util/string.cpp
@@ -20,13 +20,11 @@
  *
  */
 
-#include <stdio.h>
-#include <string.h>
-#include <ctype.h>
-#include "util/math.h"
-#include "util/stream.h"
-#include "util/string.h"
-#include "util/string_compat.h"
+#include "ags/shared/util/math.h"
+#include "ags/shared/util/stream.h"
+#include "ags/shared/util/string.h"
+#include "ags/shared/util/string_compat.h"
+#include "ags/std/algorithm.h"
 
 namespace AGS3 {
 namespace AGS {
@@ -52,6 +50,10 @@ String::String(const char *cstr)
 	*this = cstr;
 }
 
+String::String(const Common::String &s) : _cstr(nullptr), _len(0), _buf(nullptr) {
+	*this = s.c_str();
+}
+
 String::String(const char *cstr, size_t length)
 	: _cstr(nullptr)
 	, _len(0)
@@ -144,36 +146,36 @@ int String::CompareNoCase(const char *cstr) const {
 
 int String::CompareLeft(const char *cstr, size_t count) const {
 	cstr = cstr ? cstr : "";
-	return strncmp(GetCStr(), cstr, count != -1 ? count : strlen(cstr));
+	return strncmp(GetCStr(), cstr, count != npos ? count : strlen(cstr));
 }
 
 int String::CompareLeftNoCase(const char *cstr, size_t count) const {
 	cstr = cstr ? cstr : "";
-	return ags_strnicmp(GetCStr(), cstr, count != -1 ? count : strlen(cstr));
+	return ags_strnicmp(GetCStr(), cstr, count != npos ? count : strlen(cstr));
 }
 
 int String::CompareMid(const char *cstr, size_t from, size_t count) const {
 	cstr = cstr ? cstr : "";
 	from = Math::Min(from, GetLength());
-	return strncmp(GetCStr() + from, cstr, count != -1 ? count : strlen(cstr));
+	return strncmp(GetCStr() + from, cstr, count != npos ? count : strlen(cstr));
 }
 
 int String::CompareMidNoCase(const char *cstr, size_t from, size_t count) const {
 	cstr = cstr ? cstr : "";
 	from = Math::Min(from, GetLength());
-	return ags_strnicmp(GetCStr() + from, cstr, count != -1 ? count : strlen(cstr));
+	return ags_strnicmp(GetCStr() + from, cstr, count != npos ? count : strlen(cstr));
 }
 
 int String::CompareRight(const char *cstr, size_t count) const {
 	cstr = cstr ? cstr : "";
-	count = count != -1 ? count : strlen(cstr);
+	count = count != npos ? count : strlen(cstr);
 	size_t off = Math::Min(GetLength(), count);
 	return strncmp(GetCStr() + GetLength() - off, cstr, count);
 }
 
 int String::CompareRightNoCase(const char *cstr, size_t count) const {
 	cstr = cstr ? cstr : "";
-	count = count != -1 ? count : strlen(cstr);
+	count = count != npos ? count : strlen(cstr);
 	size_t off = Math::Min(GetLength(), count);
 	return ags_strnicmp(GetCStr() + GetLength() - off, cstr, count);
 }
@@ -181,14 +183,14 @@ int String::CompareRightNoCase(const char *cstr, size_t count) const {
 size_t String::FindChar(char c, size_t from) const {
 	if (c && from < _len) {
 		const char *found_cstr = strchr(_cstr + from, c);
-		return found_cstr ? found_cstr - _cstr : -1;
+		return found_cstr ? found_cstr - _cstr : npos;
 	}
-	return -1;
+	return npos;
 }
 
 size_t String::FindCharReverse(char c, size_t from) const {
 	if (!_cstr || !c) {
-		return -1;
+		return npos;
 	}
 
 	from = Math::Min(from, _len - 1);
@@ -199,15 +201,15 @@ size_t String::FindCharReverse(char c, size_t from) const {
 		}
 		seek_ptr--;
 	}
-	return -1;
+	return npos;
 }
 
 size_t String::FindString(const char *cstr, size_t from) const {
 	if (cstr && from < _len) {
 		const char *found_cstr = strstr(_cstr + from, cstr);
-		return found_cstr ? found_cstr - _cstr : -1;
+		return found_cstr ? found_cstr - _cstr : npos;
 	}
-	return -1;
+	return npos;
 }
 
 bool String::FindSection(char separator, size_t first, size_t last, bool exclude_first_sep, bool exclude_last_sep,
@@ -222,10 +224,10 @@ bool String::FindSection(char separator, size_t first, size_t last, bool exclude
 	size_t this_field = 0;
 	size_t slice_from = 0;
 	size_t slice_to = _len;
-	size_t slice_at = -1;
+	size_t slice_at = npos;
 	do {
 		slice_at = FindChar(separator, slice_at + 1);
-		if (slice_at == -1)
+		if (slice_at == npos)
 			slice_at = _len;
 		// found where previous field ends
 		if (this_field == last) {
@@ -322,7 +324,7 @@ String String::Right(size_t count) const {
 String String::LeftSection(char separator, bool exclude_separator) const {
 	if (_cstr && separator) {
 		size_t slice_at = FindChar(separator);
-		if (slice_at != -1) {
+		if (slice_at != npos) {
 			slice_at = exclude_separator ? slice_at : slice_at + 1;
 			return Left(slice_at);
 		}
@@ -333,7 +335,7 @@ String String::LeftSection(char separator, bool exclude_separator) const {
 String String::RightSection(char separator, bool exclude_separator) const {
 	if (_cstr && separator) {
 		size_t slice_at = FindCharReverse(separator);
-		if (slice_at != -1) {
+		if (slice_at != npos) {
 			size_t count = exclude_separator ? _len - slice_at - 1 : _len - slice_at;
 			return Right(count);
 		}
@@ -454,7 +456,7 @@ void String::ClipRight(size_t count) {
 void String::ClipLeftSection(char separator, bool include_separator) {
 	if (_cstr && separator) {
 		size_t slice_at = FindChar(separator);
-		if (slice_at != -1) {
+		if (slice_at != npos) {
 			ClipLeft(include_separator ? slice_at + 1 : slice_at);
 		} else
 			Empty();
@@ -464,7 +466,7 @@ void String::ClipLeftSection(char separator, bool include_separator) {
 void String::ClipRightSection(char separator, bool include_separator) {
 	if (_cstr && separator) {
 		size_t slice_at = FindCharReverse(separator);
-		if (slice_at != -1) {
+		if (slice_at != npos) {
 			ClipRight(include_separator ? _len - slice_at : _len - slice_at - 1);
 		} else
 			Empty();
@@ -645,7 +647,7 @@ void String::TrimLeft(char c) {
 		if (c && t != c) {
 			break;
 		}
-		if (!c && !isspace(t)) {
+		if (!c && !Common::isSpace(t)) {
 			break;
 		}
 		trim_ptr++;
@@ -672,7 +674,7 @@ void String::TrimRight(char c) {
 		if (c && t != c) {
 			break;
 		}
-		if (!c && !isspace(t)) {
+		if (!c && !Common::isSpace(t)) {
 			break;
 		}
 		trim_ptr--;
@@ -722,7 +724,7 @@ void String::TruncateToRight(size_t count) {
 void String::TruncateToLeftSection(char separator, bool exclude_separator) {
 	if (_cstr && separator) {
 		size_t slice_at = FindChar(separator);
-		if (slice_at != -1) {
+		if (slice_at != npos) {
 			TruncateToLeft(exclude_separator ? slice_at : slice_at + 1);
 		}
 	}
@@ -731,7 +733,7 @@ void String::TruncateToLeftSection(char separator, bool exclude_separator) {
 void String::TruncateToRightSection(char separator, bool exclude_separator) {
 	if (_cstr && separator) {
 		size_t slice_at = FindCharReverse(separator);
-		if (slice_at != -1) {
+		if (slice_at != npos) {
 			TruncateToRight(exclude_separator ? _len - slice_at - 1 : _len - slice_at);
 		}
 	}
@@ -816,7 +818,7 @@ void String::Align(size_t offset) {
 }
 
 void String::BecomeUnique() {
-	if (_cstr && (_bufHead && _bufHead->RefCount > 1 || !_bufHead)) {
+	if (_cstr && (!_bufHead || (_bufHead && _bufHead->RefCount > 1))) {
 		Copy(_len);
 	}
 }
diff --git a/engines/ags/shared/util/string.h b/engines/ags/shared/util/string.h
index c2ecec93fb..33cfd0ac3c 100644
--- a/engines/ags/shared/util/string.h
+++ b/engines/ags/shared/util/string.h
@@ -46,11 +46,12 @@
 #ifndef AGS_SHARED_UTIL_STRING_H
 #define AGS_SHARED_UTIL_STRING_H
 
-#include <stdarg.h>
-#include <vector>
-#include "core/platform.h"
-#include "core/types.h"
-#include "debug/assert.h"
+//include <stdarg.h>
+#include "ags/std/vector.h"
+#include "ags/shared/core/platform.h"
+#include "ags/shared/core/types.h"
+#include "ags/shared/debugging/assert.h"
+#include "common/str.h"
 
 namespace AGS3 {
 namespace AGS {
@@ -60,6 +61,8 @@ class Stream;
 
 class String {
 public:
+	static const uint32 npos = (uint32)-1;
+
 	// Standard constructor: intialize empty string
 	String();
 	// Copy constructor
@@ -70,6 +73,8 @@ public:
 	String(const char *cstr, size_t length);
 	// Initialize by filling N chars with certain value
 	String(char c, size_t count);
+	// Initialize with a ScummVM string
+	String(const Common::String &s);
 	~String();
 
 	// Get underlying C-string for reading; this method guarantees valid C-string
@@ -132,19 +137,19 @@ public:
 	int     Compare(const char *cstr) const;
 	int     CompareNoCase(const char *cstr) const;
 	// Compares the leftmost part of this string with given C-string
-	int     CompareLeft(const char *cstr, size_t count = -1) const;
-	int     CompareLeftNoCase(const char *cstr, size_t count = -1) const;
+	int     CompareLeft(const char *cstr, size_t count = npos) const;
+	int     CompareLeftNoCase(const char *cstr, size_t count = npos) const;
 	// Compares any part of this string with given C-string
-	int     CompareMid(const char *cstr, size_t from, size_t count = -1) const;
-	int     CompareMidNoCase(const char *cstr, size_t from, size_t count = -1) const;
+	int     CompareMid(const char *cstr, size_t from, size_t count = npos) const;
+	int     CompareMidNoCase(const char *cstr, size_t from, size_t count = npos) const;
 	// Compares the rightmost part of this string with given C-string
-	int     CompareRight(const char *cstr, size_t count = -1) const;
-	int     CompareRightNoCase(const char *cstr, size_t count = -1) const;
+	int     CompareRight(const char *cstr, size_t count = npos) const;
+	int     CompareRightNoCase(const char *cstr, size_t count = npos) const;
 
 	// These functions search for character or substring inside this string
-	// and return the index of the (first) character, or -1 if nothing found.
+	// and return the index of the (first) character, or npos if nothing found.
 	size_t  FindChar(char c, size_t from = 0) const;
-	size_t  FindCharReverse(char c, size_t from = -1) const;
+	size_t  FindCharReverse(char c, size_t from = npos) const;
 	size_t  FindString(const char *cstr, size_t from = 0) const;
 
 	// Section methods treat string as a sequence of 'fields', separated by
@@ -198,7 +203,7 @@ public:
 	// Extract N leftmost characters as a new string
 	String  Left(size_t count) const;
 	// Extract up to N characters starting from given index
-	String  Mid(size_t from, size_t count = -1) const;
+	String  Mid(size_t from, size_t count = npos) const;
 	// Extract N rightmost characters
 	String  Right(size_t count) const;
 
@@ -237,7 +242,7 @@ public:
 	// Cuts off leftmost N characters
 	void    ClipLeft(size_t count);
 	// Cuts out N characters starting from given index
-	void    ClipMid(size_t from, size_t count = -1);
+	void    ClipMid(size_t from, size_t count = npos);
 	// Cuts off rightmost N characters
 	void    ClipRight(size_t count);
 	// Cuts off leftmost part, separated by the given char; if no separator was
@@ -280,7 +285,7 @@ public:
 	// Overwrite the Nth character of the string; does not change string's length
 	void    SetAt(size_t index, char c);
 	// Makes a new string by copying up to N chars from C-string
-	void    SetString(const char *cstr, size_t length = -1);
+	void    SetString(const char *cstr, size_t length = npos);
 	// For all Trim functions, if given character value is 0, all whitespace
 	// characters (space, tabs, CRLF) are removed.
 	// Remove heading and trailing characters from the string
@@ -293,7 +298,7 @@ public:
 	// Truncate the string to the leftmost N characters
 	void    TruncateToLeft(size_t count);
 	// Truncate the string to the middle N characters
-	void    TruncateToMid(size_t from, size_t count = -1);
+	void    TruncateToMid(size_t from, size_t count = npos);
 	// Truncate the string to the rightmost N characters
 	void    TruncateToRight(size_t count);
 	// Truncate the string to the leftmost part, separated by the given char;
@@ -334,6 +339,9 @@ public:
 	inline bool operator <(const char *cstr) const {
 		return Compare(cstr) < 0;
 	}
+	Common::String operator()() const {
+		return Common::String(GetCStr());
+	}
 
 private:
 	// Creates new empty string with buffer enough to fit given length
diff --git a/engines/ags/shared/util/string_compat.c b/engines/ags/shared/util/string_compat.c
deleted file mode 100644
index 0f925e3ce9..0000000000
--- a/engines/ags/shared/util/string_compat.c
+++ /dev/null
@@ -1,58 +0,0 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-#include "util/string_compat.h"
-#include <ctype.h>
-#include <string.h>
-#include "core/platform.h"
-
-char *ags_strlwr(char *s)
-{
-    char *p = s;
-    for (; *p; p++)
-        *p = tolower(*p);
-    return s;
-}
-
-char *ags_strupr(char *s)
-{
-    char *p = s;
-    for (; *p; p++)
-        *p = toupper(*p);
-    return s;
-}
-
-int ags_stricmp(const char *s1, const char *s2)
-{
-#if AGS_PLATFORM_OS_WINDOWS
-    return stricmp(s1, s2);
-#else
-    return strcasecmp(s1, s2);
-#endif
-}
-
-int ags_strnicmp(const char *s1, const char *s2, size_t n)
-{
-#if AGS_PLATFORM_OS_WINDOWS
-    return strnicmp(s1, s2, n);
-#else
-    return strncasecmp(s1, s2, n);
-#endif
-}
-
-char *ags_strdup(const char *s)
-{
-    char *result = (char *)malloc(strlen(s) + 1);
-    strcpy(result, s);
-    return result;
-}
diff --git a/engines/ags/shared/util/string_compat.cpp b/engines/ags/shared/util/string_compat.cpp
new file mode 100644
index 0000000000..ec45962c39
--- /dev/null
+++ b/engines/ags/shared/util/string_compat.cpp
@@ -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.
+ *
+ */
+
+#include "ags/shared/util/string_compat.h"
+#include "ags/shared/core/platform.h"
+#include "common/str.h"
+
+namespace AGS3 {
+
+char *ags_strlwr(char *s) {
+	char *p = s;
+	for (; *p; p++)
+		*p = tolower(*p);
+	return s;
+}
+
+char *ags_strupr(char *s) {
+	char *p = s;
+	for (; *p; p++)
+		*p = toupper(*p);
+	return s;
+}
+
+int ags_stricmp(const char *s1, const char *s2) {
+	return scumm_stricmp(s1, s2);
+}
+
+int ags_strnicmp(const char *s1, const char *s2, size_t n) {
+	return scumm_strnicmp(s1, s2, n);
+}
+
+char *ags_strdup(const char *s) {
+	char *result = (char *)malloc(strlen(s) + 1);
+	strcpy(result, s);
+	return result;
+}
+
+} // namespace AGS3
diff --git a/engines/ags/shared/util/string_compat.h b/engines/ags/shared/util/string_compat.h
index 3931eae1f5..3a8f30dc6e 100644
--- a/engines/ags/shared/util/string_compat.h
+++ b/engines/ags/shared/util/string_compat.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_UTIL_STRINGCOMPAT_H
 #define AGS_SHARED_UTIL_STRINGCOMPAT_H
 
-#include "core/types.h"
+#include "ags/shared/core/types.h"
 
 namespace AGS3 {
 
@@ -31,11 +31,11 @@ namespace AGS3 {
 extern "C" {
 #endif
 
-	char *ags_strlwr(char *s);
-	char *ags_strupr(char *s);
-	int ags_stricmp(const char *, const char *);
-	int ags_strnicmp(const char *, const char *, size_t);
-	char *ags_strdup(const char *s);
+char *ags_strlwr(char *s);
+char *ags_strupr(char *s);
+int ags_stricmp(const char *, const char *);
+int ags_strnicmp(const char *, const char *, size_t);
+char *ags_strdup(const char *s);
 
 #ifdef __cplusplus
 }
diff --git a/engines/ags/shared/util/string_types.h b/engines/ags/shared/util/string_types.h
index 60fe83f991..13b4c4c5f9 100644
--- a/engines/ags/shared/util/string_types.h
+++ b/engines/ags/shared/util/string_types.h
@@ -23,12 +23,10 @@
 #ifndef AGS_SHARED_UTIL_STRINGTYPES_H
 #define AGS_SHARED_UTIL_STRINGTYPES_H
 
-#include <cctype>
-#include <functional>
-#include <unordered_map>
-
-#include <vector>
-#include "util/string.h"
+#include "ags/std/map.h"
+#include "ags/std/vector.h"
+#include "ags/shared/util/string.h"
+#include "common/hash-str.h"
 
 namespace AGS3 {
 namespace FNV {
@@ -51,29 +49,59 @@ inline size_t Hash_LowerCase(const char *data, const size_t len) {
 }
 
 } // namespace FNV
-
+} // namespace AGS3
 
 // A std::hash specialization for AGS String
-namespace std {
-#ifdef AGS_NEEDS_TR1
-namespace tr1 {
-#endif
-// std::hash for String object
+namespace AGS3 {
+
+struct CaseSensitiveString_EqualTo {
+	bool operator()(const AGS3::AGS::Shared::String &x, const AGS3::AGS::Shared::String &y) const {
+		return x.Compare(y) == 0;
+	}
+};
+
+struct CaseSensitiveString_Hash {
+	uint operator()(const AGS3::AGS::Shared::String &x) const {
+		return Common::hashit(x.GetNullableCStr());
+	}
+};
+
+struct IgnoreCase_EqualTo {
+	bool operator()(const AGS3::AGS::Shared::String &x, const AGS3::AGS::Shared::String &y) const {
+		return x.CompareNoCase(y) == 0;
+	}
+};
+
+struct IgnoreCase_Hash {
+	uint operator()(const AGS3::AGS::Shared::String &x) const {
+		return Common::hashit_lower(x.GetNullableCStr());
+	}
+};
+
+} // namespace AGS3
+
+namespace Common {
+
+// Specalization of the Hash functor for String objects.
+// We do case sensitve hashing here, because that is what
+// the default EqualTo is compatible with. If one wants to use
+// case insensitve hashing, then only because one wants to use
+// IgnoreCase_EqualTo, and then one has to specify a custom
+// hash anyway.
 template<>
-struct hash<AGS::Shared::String> : public unary_function<AGS::Shared::String, size_t> {
-	size_t operator()(const AGS::Shared::String &key) const {
-		return FNV::Hash(key.GetCStr(), key.GetLength());
+struct Hash<AGS3::AGS::Shared::String> {
+	uint operator()(const AGS3::AGS::Shared::String &s) const {
+		return Common::hashit(s.GetNullableCStr());
 	}
 };
-#ifdef AGS_NEEDS_TR1
-}
-#endif
-}
 
+} // namespace Common
 
+namespace AGS3 {
 namespace AGS {
 namespace Shared {
 
+#if 0
 //
 // Various comparison functors
 //
@@ -98,10 +126,11 @@ struct HashStrNoCase : public std::unary_function<String, size_t> {
 		return FNV::Hash_LowerCase(key.GetCStr(), key.GetLength());
 	}
 };
+#endif
 
 typedef std::vector<String> StringV;
 typedef std::unordered_map<String, String> StringMap;
-typedef std::unordered_map<String, String, HashStrNoCase, StrEqNoCase> StringIMap;
+typedef std::unordered_map<String, String, IgnoreCase_Hash, IgnoreCase_EqualTo> StringIMap;
 
 } // namespace Shared
 } // namespace AGS
diff --git a/engines/ags/shared/util/string_utils.cpp b/engines/ags/shared/util/string_utils.cpp
index fe0dbdec08..16eeaccf47 100644
--- a/engines/ags/shared/util/string_utils.cpp
+++ b/engines/ags/shared/util/string_utils.cpp
@@ -20,12 +20,13 @@
  *
  */
 
-#include <errno.h>
-#include <string.h>
-#include "core/platform.h"
-#include "util/math.h"
-#include "util/string_utils.h"
-#include "util/stream.h"
+//include <errno.h>
+//include <string.h>
+#include "ags/shared/core/platform.h"
+#include "ags/shared/util/math.h"
+#include "ags/shared/util/string_utils.h"
+#include "ags/shared/util/stream.h"
+#include "ags/stubs/allegro/error.h"
 
 namespace AGS3 {
 
@@ -58,11 +59,11 @@ StrUtil::ConversionError StrUtil::StringToInt(const String &s, int &val, int def
 	if (!s.GetCStr())
 		return StrUtil::kFailed;
 	char *stop_ptr;
-	errno = 0;
+	errnum = 0;
 	long lval = strtol(s.GetCStr(), &stop_ptr, 0);
 	if (stop_ptr != s.GetCStr() + s.GetLength())
 		return StrUtil::kFailed;
-	if (lval > INT_MAX || lval < INT_MIN || errno == ERANGE)
+	if (lval > INT_MAX || lval < INT_MIN || errnum == ERANGE)
 		return StrUtil::kOutOfRange;
 	val = (int)lval;
 	return StrUtil::kNoError;
diff --git a/engines/ags/shared/util/string_utils.h b/engines/ags/shared/util/string_utils.h
index fc4ebd8f6b..43d6234e77 100644
--- a/engines/ags/shared/util/string_utils.h
+++ b/engines/ags/shared/util/string_utils.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_UTIL_STRING_UTILS_H
 #define AGS_SHARED_UTIL_STRING_UTILS_H
 
-#include "util/string.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 
@@ -39,7 +39,7 @@ using namespace AGS; // FIXME later
 
 // Converts char* to string and frees original malloc-ed array;
 // This is used when we get a malloc'd char array from some utility function.
-Common::String cbuf_to_string_and_free(char *char_buf);
+Shared::String cbuf_to_string_and_free(char *char_buf);
 
 namespace AGS {
 namespace Shared {
diff --git a/engines/ags/shared/util/textreader.h b/engines/ags/shared/util/textreader.h
index 78a507c5a9..c226805659 100644
--- a/engines/ags/shared/util/textreader.h
+++ b/engines/ags/shared/util/textreader.h
@@ -29,7 +29,7 @@
 #ifndef AGS_SHARED_UTIL_TEXTREADER_H
 #define AGS_SHARED_UTIL_TEXTREADER_H
 
-#include "util/string.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/util/textstreamreader.cpp b/engines/ags/shared/util/textstreamreader.cpp
index a19169470d..f066c01366 100644
--- a/engines/ags/shared/util/textstreamreader.cpp
+++ b/engines/ags/shared/util/textstreamreader.cpp
@@ -20,9 +20,9 @@
  *
  */
 
-#include "util/math.h"
-#include "util/stream.h"
-#include "util/textstreamreader.h"
+#include "ags/shared/util/math.h"
+#include "ags/shared/util/stream.h"
+#include "ags/shared/util/textstreamreader.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/util/textstreamreader.h b/engines/ags/shared/util/textstreamreader.h
index 9c527dcc23..79d2e55048 100644
--- a/engines/ags/shared/util/textstreamreader.h
+++ b/engines/ags/shared/util/textstreamreader.h
@@ -29,7 +29,7 @@
 #ifndef AGS_SHARED_UTIL_TEXTSTREAMREADER_H
 #define AGS_SHARED_UTIL_TEXTSTREAMREADER_H
 
-#include "util/textreader.h"
+#include "ags/shared/util/textreader.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/util/textstreamwriter.cpp b/engines/ags/shared/util/textstreamwriter.cpp
index 1d72acc24c..fe2ffad380 100644
--- a/engines/ags/shared/util/textstreamwriter.cpp
+++ b/engines/ags/shared/util/textstreamwriter.cpp
@@ -20,11 +20,11 @@
  *
  */
 
-#include <stdarg.h>
-#include <stdio.h> // sprintf
-#include "core/platform.h"
-#include "util/textstreamwriter.h"
-#include "util/stream.h"
+//include <stdarg.h>
+//include <stdio.h> // sprintf
+#include "ags/shared/core/platform.h"
+#include "ags/shared/util/textstreamwriter.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/util/textstreamwriter.h b/engines/ags/shared/util/textstreamwriter.h
index ef15320996..932759b029 100644
--- a/engines/ags/shared/util/textstreamwriter.h
+++ b/engines/ags/shared/util/textstreamwriter.h
@@ -29,7 +29,7 @@
 #ifndef AGS_SHARED_UTIL_TEXTSTREAMWRITER_H
 #define AGS_SHARED_UTIL_TEXTSTREAMWRITER_H
 
-#include "util/textwriter.h"
+#include "ags/shared/util/textwriter.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/util/textwriter.h b/engines/ags/shared/util/textwriter.h
index 42c735c371..87123e5801 100644
--- a/engines/ags/shared/util/textwriter.h
+++ b/engines/ags/shared/util/textwriter.h
@@ -29,7 +29,7 @@
 #ifndef AGS_SHARED_UTIL_TEXTWRITER_H
 #define AGS_SHARED_UTIL_TEXTWRITER_H
 
-#include "util/string.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/util/version.cpp b/engines/ags/shared/util/version.cpp
index f3f7ae9ebc..40ef6bd313 100644
--- a/engines/ags/shared/util/version.cpp
+++ b/engines/ags/shared/util/version.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include <ctype.h>
-#include "util/version.h"
+//include <ctype.h>
+#include "ags/shared/util/version.h"
 
 namespace AGS3 {
 namespace AGS {
@@ -107,7 +107,7 @@ void Version::SetFromString(const String &version_string) {
 		const char *seek_ptr = revision_section.GetCStr();
 		const char *end_ptr = revision_section.GetCStr() + revision_section.GetLength();
 		while (seek_ptr != end_ptr) {
-			if (!isdigit(*seek_ptr)) {
+			if (!Common::isDigit(*seek_ptr)) {
 				break;
 			}
 			revision_length++;
diff --git a/engines/ags/shared/util/version.h b/engines/ags/shared/util/version.h
index 95dad1377a..829540a97c 100644
--- a/engines/ags/shared/util/version.h
+++ b/engines/ags/shared/util/version.h
@@ -29,13 +29,13 @@
 #ifndef AGS_SHARED_UTIL_VERSION_H
 #define AGS_SHARED_UTIL_VERSION_H
 
-#include "util/string.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 namespace AGS {
 namespace Shared {
 
-using Common::String;
+using Shared::String;
 
 struct Version {
 	int32_t Major;
diff --git a/engines/ags/shared/util/wgt2allg.cpp b/engines/ags/shared/util/wgt2allg.cpp
index 8975fd02f7..ea5067d79a 100644
--- a/engines/ags/shared/util/wgt2allg.cpp
+++ b/engines/ags/shared/util/wgt2allg.cpp
@@ -20,196 +20,188 @@
  *
  */
 
-#include "core/assetmanager.h"
-#include "gfx/bitmap.h"
-#include "util/stream.h"
-#include "util/wgt2allg.h"
+#include "ags/shared/core/assetmanager.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/gfx/allegrobitmap.h"
+#include "ags/shared/util/stream.h"
+#include "ags/shared/util/wgt2allg.h"
+#include "ags/stubs/allegro.h"
 
 namespace AGS3 {
 
 using namespace AGS::Shared;
 
-#ifdef __cplusplus
-extern "C"
-{
-#endif
+void wsetrgb(int coll, int r, int g, int b, color *pall) {
+	pall[coll].r = r;
+	pall[coll].g = g;
+	pall[coll].b = b;
+}
 
-	void wsetrgb(int coll, int r, int g, int b, color *pall) {
-		pall[coll].r = r;
-		pall[coll].g = g;
-		pall[coll].b = b;
-	}
+void wcolrotate(unsigned char start, unsigned char finish, int dir, color *pall) {
+	int jj;
+	if (dir == 0) {
+		// rotate left
+		color tempp = pall[start];
 
-	void wcolrotate(unsigned char start, unsigned char finish, int dir, color *pall) {
-		int jj;
-		if (dir == 0) {
-			// rotate left
-			color tempp = pall[start];
+		for (jj = start; jj < finish; jj++)
+			pall[jj] = pall[jj + 1];
 
-			for (jj = start; jj < finish; jj++)
-				pall[jj] = pall[jj + 1];
+		pall[finish] = tempp;
+	} else {
+		// rotate right
+		color tempp = pall[finish];
 
-			pall[finish] = tempp;
-		} else {
-			// rotate right
-			color tempp = pall[finish];
+		for (jj = finish - 1; jj >= start; jj--)
+			pall[jj + 1] = pall[jj];
 
-			for (jj = finish - 1; jj >= start; jj--)
-				pall[jj + 1] = pall[jj];
-
-			pall[start] = tempp;
-		}
+		pall[start] = tempp;
 	}
+}
+
+Bitmap *wnewblock(Shared::Bitmap *src, int x1, int y1, int x2, int y2) {
+	Bitmap *tempbitm;
+	int twid = (x2 - x1) + 1, thit = (y2 - y1) + 1;
 
-	Bitmap *wnewblock(Common::Bitmap *src, int x1, int y1, int x2, int y2) {
-		Bitmap *tempbitm;
-		int twid = (x2 - x1) + 1, thit = (y2 - y1) + 1;
+	if (twid < 1)
+		twid = 1;
 
-		if (twid < 1)
-			twid = 1;
+	if (thit < 1)
+		thit = 1;
 
-		if (thit < 1)
-			thit = 1;
+	tempbitm = BitmapHelper::CreateBitmap(twid, thit);
 
-		tempbitm = BitmapHelper::CreateBitmap(twid, thit);
+	if (tempbitm == nullptr)
+		return nullptr;
 
-		if (tempbitm == nullptr)
-			return nullptr;
+	tempbitm->Blit(src, x1, y1, 0, 0, tempbitm->GetWidth(), tempbitm->GetHeight());
+	return tempbitm;
+}
 
-		tempbitm->Blit(src, x1, y1, 0, 0, tempbitm->GetWidth(), tempbitm->GetHeight());
-		return tempbitm;
+int wloadsprites(color *pall, char *filnam, Bitmap **sarray, int strt, int eend) {
+	int vers;
+	char buff[20];
+	int numspri = 0, vv, hh, wdd, htt;
+
+	Stream *in = Shared::AssetManager::OpenAsset(filnam);
+	if (in == nullptr)
+		return -1;
+
+	vers = in->ReadInt16();
+	in->ReadArray(&buff[0], 13, 1);
+	for (vv = 0; vv < 256; vv++)        // there's a filler byte
+		in->ReadArray(&pall[vv], 3, 1);
+
+	if (vers > 4)
+		return -1;
+
+	if (vers == 4)
+		numspri = in->ReadInt16();
+	else {
+		numspri = in->ReadInt16();
+		if ((numspri < 2) || (numspri > 200))
+			numspri = 200;
 	}
 
-	int wloadsprites(color *pall, char *filnam, Bitmap **sarray, int strt, int eend) {
-		int vers;
-		char buff[20];
-		int numspri = 0, vv, hh, wdd, htt;
+	for (vv = strt; vv <= eend; vv++)
+		sarray[vv] = nullptr;
 
-		Stream *in = Common::AssetManager::OpenAsset(filnam);
-		if (in == nullptr)
-			return -1;
+	for (vv = 0; vv <= numspri; vv++) {
+		int coldep = in->ReadInt16();
 
-		vers = in->ReadInt16();
-		in->ReadArray(&buff[0], 13, 1);
-		for (vv = 0; vv < 256; vv++)        // there's a filler byte
-			in->ReadArray(&pall[vv], 3, 1);
-
-		if (vers > 4)
-			return -1;
+		if (coldep == 0) {
+			sarray[vv] = nullptr;
+			if (in->EOS())
+				break;
 
-		if (vers == 4)
-			numspri = in->ReadInt16();
-		else {
-			numspri = in->ReadInt16();
-			if ((numspri < 2) || (numspri > 200))
-				numspri = 200;
+			continue;
 		}
 
-		for (vv = strt; vv <= eend; vv++)
-			sarray[vv] = nullptr;
+		if (in->EOS())
+			break;
 
-		for (vv = 0; vv <= numspri; vv++) {
-			int coldep = in->ReadInt16();
+		if (vv > eend)
+			break;
 
-			if (coldep == 0) {
-				sarray[vv] = nullptr;
-				if (in->EOS())
-					break;
+		wdd = in->ReadInt16();
+		htt = in->ReadInt16();
+		if (vv < strt) {
+			in->Seek(wdd * htt);
+			continue;
+		}
+		sarray[vv] = BitmapHelper::CreateBitmap(wdd, htt, coldep * 8);
 
-				continue;
-			}
+		if (sarray[vv] == nullptr) {
+			delete in;
+			return -1;
+		}
 
-			if (in->EOS())
-				break;
+		for (hh = 0; hh < htt; hh++)
+			in->ReadArray(&sarray[vv]->GetScanLineForWriting(hh)[0], wdd * coldep, 1);
+	}
+	delete in;
+	return 0;
+}
 
-			if (vv > eend)
-				break;
+void wputblock(Shared::Bitmap *ds, int xx, int yy, Bitmap *bll, int xray) {
+	if (xray)
+		ds->Blit(bll, xx, yy, Shared::kBitmap_Transparency);
+	else
+		ds->Blit(bll, 0, 0, xx, yy, bll->GetWidth(), bll->GetHeight());
+}
 
-			wdd = in->ReadInt16();
-			htt = in->ReadInt16();
-			if (vv < strt) {
-				in->Seek(wdd * htt);
-				continue;
-			}
-			sarray[vv] = BitmapHelper::CreateBitmap(wdd, htt, coldep * 8);
-
-			if (sarray[vv] == nullptr) {
-				delete in;
-				return -1;
-			}
-
-			for (hh = 0; hh < htt; hh++)
-				in->ReadArray(&sarray[vv]->GetScanLineForWriting(hh)[0], wdd * coldep, 1);
-		}
-		delete in;
-		return 0;
-	}
+Bitmap wputblock_wrapper; // [IKM] argh! :[
+void wputblock_raw(Shared::Bitmap *ds, int xx, int yy, BITMAP *bll, int xray) {
+	wputblock_wrapper.WrapAllegroBitmap(bll, true);
+	if (xray)
+		ds->Blit(&wputblock_wrapper, xx, yy, Shared::kBitmap_Transparency);
+	else
+		ds->Blit(&wputblock_wrapper, 0, 0, xx, yy, wputblock_wrapper.GetWidth(), wputblock_wrapper.GetHeight());
+}
 
-	void wputblock(Common::Bitmap *ds, int xx, int yy, Bitmap *bll, int xray) {
-		if (xray)
-			ds->Blit(bll, xx, yy, Common::kBitmap_Transparency);
-		else
-			ds->Blit(bll, 0, 0, xx, yy, bll->GetWidth(), bll->GetHeight());
-	}
+const int col_lookups[32] = {
+	0x000000, 0x0000A0, 0x00A000, 0x00A0A0, 0xA00000,   // 4
+	0xA000A0, 0xA05000, 0xA0A0A0, 0x505050, 0x5050FF, 0x50FF50, 0x50FFFF,       // 11
+	0xFF5050, 0xFF50FF, 0xFFFF50, 0xFFFFFF, 0x000000, 0x101010, 0x202020,       // 18
+	0x303030, 0x404040, 0x505050, 0x606060, 0x707070, 0x808080, 0x909090,       // 25
+	0xA0A0A0, 0xB0B0B0, 0xC0C0C0, 0xD0D0D0, 0xE0E0E0, 0xF0F0F0
+};
 
-	Bitmap wputblock_wrapper; // [IKM] argh! :[
-	void wputblock_raw(Common::Bitmap *ds, int xx, int yy, BITMAP *bll, int xray) {
-		wputblock_wrapper.WrapAllegroBitmap(bll, true);
-		if (xray)
-			ds->Blit(&wputblock_wrapper, xx, yy, Common::kBitmap_Transparency);
-		else
-			ds->Blit(&wputblock_wrapper, 0, 0, xx, yy, wputblock_wrapper.GetWidth(), wputblock_wrapper.GetHeight());
-	}
+int __wremap_keep_transparent = 1;
 
-	const int col_lookups[32] = {
-		0x000000, 0x0000A0, 0x00A000, 0x00A0A0, 0xA00000,   // 4
-		0xA000A0, 0xA05000, 0xA0A0A0, 0x505050, 0x5050FF, 0x50FF50, 0x50FFFF,       // 11
-		0xFF5050, 0xFF50FF, 0xFFFF50, 0xFFFFFF, 0x000000, 0x101010, 0x202020,       // 18
-		0x303030, 0x404040, 0x505050, 0x606060, 0x707070, 0x808080, 0x909090,       // 25
-		0xA0A0A0, 0xB0B0B0, 0xC0C0C0, 0xD0D0D0, 0xE0E0E0, 0xF0F0F0
-	};
-
-	int __wremap_keep_transparent = 1;
-
-	void wremap(color *pal1, Bitmap *picc, color *pal2) {
-		int jj;
-		unsigned char color_mapped_table[256];
-
-		for (jj = 0; jj < 256; jj++) {
-			if ((pal1[jj].r == 0) && (pal1[jj].g == 0) && (pal1[jj].b == 0)) {
-				color_mapped_table[jj] = 0;
-			} else {
-				color_mapped_table[jj] = bestfit_color(pal2, pal1[jj].r, pal1[jj].g, pal1[jj].b);
-			}
-		}
+void wremap(color *pal1, Bitmap *picc, color *pal2) {
+	int jj;
+	unsigned char color_mapped_table[256];
 
-		if (__wremap_keep_transparent > 0) {
-			// keep transparency
-			color_mapped_table[0] = 0;
-			// any other pixels which are being mapped to 0, map to 16 instead
-			for (jj = 1; jj < 256; jj++) {
-				if (color_mapped_table[jj] == 0)
-					color_mapped_table[jj] = 16;
-			}
+	for (jj = 0; jj < 256; jj++) {
+		if ((pal1[jj].r == 0) && (pal1[jj].g == 0) && (pal1[jj].b == 0)) {
+			color_mapped_table[jj] = 0;
+		} else {
+			color_mapped_table[jj] = bestfit_color(pal2, pal1[jj].r, pal1[jj].g, pal1[jj].b);
 		}
+	}
 
-		int pic_size = picc->GetWidth() * picc->GetHeight();
-		for (jj = 0; jj < pic_size; jj++) {
-			int xxl = jj % (picc->GetWidth()), yyl = jj / (picc->GetWidth());
-			int rr = picc->GetPixel(xxl, yyl);
-			picc->PutPixel(xxl, yyl, color_mapped_table[rr]);
+	if (__wremap_keep_transparent > 0) {
+		// keep transparency
+		color_mapped_table[0] = 0;
+		// any other pixels which are being mapped to 0, map to 16 instead
+		for (jj = 1; jj < 256; jj++) {
+			if (color_mapped_table[jj] == 0)
+				color_mapped_table[jj] = 16;
 		}
 	}
 
-	void wremapall(color *pal1, Bitmap *picc, color *pal2) {
-		__wremap_keep_transparent--;
-		wremap(pal1, picc, pal2);
-		__wremap_keep_transparent++;
+	int pic_size = picc->GetWidth() * picc->GetHeight();
+	for (jj = 0; jj < pic_size; jj++) {
+		int xxl = jj % (picc->GetWidth()), yyl = jj / (picc->GetWidth());
+		int rr = picc->GetPixel(xxl, yyl);
+		picc->PutPixel(xxl, yyl, color_mapped_table[rr]);
 	}
+}
 
-
-#ifdef __cplusplus
+void wremapall(color *pal1, Bitmap *picc, color *pal2) {
+	__wremap_keep_transparent--;
+	wremap(pal1, picc, pal2);
+	__wremap_keep_transparent++;
 }
-#endif
 
 } // namespace AGS3
diff --git a/engines/ags/shared/util/wgt2allg.h b/engines/ags/shared/util/wgt2allg.h
index b9624c53bb..090f51ca49 100644
--- a/engines/ags/shared/util/wgt2allg.h
+++ b/engines/ags/shared/util/wgt2allg.h
@@ -28,14 +28,13 @@
 //
 //=============================================================================
 
-#include "core/platform.h"
+#ifndef AGS_SHARED_UTIL_WGT2ALLG_H
+#define AGS_SHARED_UTIL_WGT2ALLG_H
 
 #define _WGT45_
 
-#ifndef AGS_SHARED_UTIL_WGT4_H
-#define AGS_SHARED_UTIL_WGT4_H
-
-#include "allegro.h"
+#include "ags/shared/core/platform.h"
+#include "ags/stubs/allegro.h"
 
 namespace AGS3 {
 
@@ -47,12 +46,11 @@ class Bitmap;
 
 using namespace AGS; // FIXME later
 
-
 #if defined WGT2ALLEGRO_NOFUNCTIONS
 #error WGT2ALLEGRO_NOFUNCTIONS macro is obsolete and should not be defined anymore.
 #endif
 
-#define color RGB
+//define color RGB
 
 //=============================================================================
 
@@ -67,20 +65,20 @@ extern "C"
 	extern void wsetrgb(int coll, int r, int g, int b, color *pall);
 	extern void wcolrotate(unsigned char start, unsigned char finish, int dir, color *pall);
 
-	extern Common::Bitmap *wnewblock(Common::Bitmap *src, int x1, int y1, int x2, int y2);
+	extern Shared::Bitmap *wnewblock(Shared::Bitmap *src, int x1, int y1, int x2, int y2);
 
-	extern int wloadsprites(color *pall, char *filnam, Common::Bitmap **sarray, int strt, int eend);
+	extern int wloadsprites(color *pall, char *filnam, Shared::Bitmap **sarray, int strt, int eend);
 
-	extern void wputblock(Common::Bitmap *ds, int xx, int yy, Common::Bitmap *bll, int xray);
+	extern void wputblock(Shared::Bitmap *ds, int xx, int yy, Shared::Bitmap *bll, int xray);
 	// CHECKME: temporary solution for plugin system
-	extern void wputblock_raw(Common::Bitmap *ds, int xx, int yy, BITMAP *bll, int xray);
+	extern void wputblock_raw(Shared::Bitmap *ds, int xx, int yy, BITMAP *bll, int xray);
 	extern const int col_lookups[32];
 
 	//extern void wsetcolor(int nval);
 
 	extern int __wremap_keep_transparent;
-	extern void wremap(color *pal1, Common::Bitmap *picc, color *pal2);
-	extern void wremapall(color *pal1, Common::Bitmap *picc, color *pal2);
+	extern void wremap(color *pal1, Shared::Bitmap *picc, color *pal2);
+	extern void wremapall(color *pal1, Shared::Bitmap *picc, color *pal2);
 
 #ifdef __cplusplus
 }
diff --git a/engines/ags/std/algorithm.h b/engines/ags/std/algorithm.h
new file mode 100644
index 0000000000..504e883a42
--- /dev/null
+++ b/engines/ags/std/algorithm.h
@@ -0,0 +1,42 @@
+/* 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 AGS_STD_ALGORITHM_H
+#define AGS_STD_ALGORITHM_H
+
+#include "common/algorithm.h"
+#include "common/util.h"
+
+namespace AGS3 {
+namespace std {
+
+template<typename T> inline T abs(T x) { return ABS(x); }
+template<typename T> inline T min(T a, T b) { return MIN(a, b); }
+template<typename T> inline T max(T a, T b) { return MAX(a, b); }
+template<typename T> inline T clip(T v, T amin, T amax) { return CLIP(v, amin, amax); }
+template<typename T> inline T sqrt(T x) { return ::sqrt(x); }
+template<typename T> inline void swap(T a, T b) { SWAP(a, b); }
+
+} // namespace std
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/std/memory.h b/engines/ags/std/memory.h
index c33d945d76..99c85916a0 100644
--- a/engines/ags/std/memory.h
+++ b/engines/ags/std/memory.h
@@ -38,6 +38,11 @@ using weak_ptr = Common::WeakPtr<T>;
 template<typename T, class DL = Common::DefaultDeleter<T> >
 using unique_ptr = Common::ScopedPtr<T, DL>;
 
+template<class T>
+T *memcpy(T *dest, const T *src, size_t n) {
+	return (T *)::memcpy(dest, src, n);
+}
+
 } // namespace std
 } // namespace AGS3
 
diff --git a/engines/ags/std/vector.h b/engines/ags/std/vector.h
index 87814229c6..84a1915d49 100644
--- a/engines/ags/std/vector.h
+++ b/engines/ags/std/vector.h
@@ -125,7 +125,7 @@ public:
 	 * Rotates the array so that the item pointed to by the iterator becomes
 	 * the first item, and the predeceding item becomes the last one
 	 */
-	void rotate(Common::Array<T>::iterator &it) {
+	void rotate(typename Common::Array<T>::iterator it) {
 		if (it != Common::Array<T>::end()) {
 			size_t count = it - Common::Array<T>::begin();
 			for (size_t ctr = 0; ctr < count; ++ctr) {
diff --git a/engines/ags/stubs/allegro.cpp b/engines/ags/stubs/allegro.cpp
index 44f7099b30..93a597c56f 100644
--- a/engines/ags/stubs/allegro.cpp
+++ b/engines/ags/stubs/allegro.cpp
@@ -25,6 +25,7 @@
 namespace AGS3 {
 
 int install_allegro() {
+	errnum = 0;
 	return 0;
 }
 
diff --git a/engines/ags/stubs/allegro/error.cpp b/engines/ags/stubs/allegro/error.cpp
index b25496e834..25105d9461 100644
--- a/engines/ags/stubs/allegro/error.cpp
+++ b/engines/ags/stubs/allegro/error.cpp
@@ -20,9 +20,11 @@
  *
  */
 
+#include "ags/stubs/allegro/error.h"
+
 namespace AGS3 {
 
-static int allegro_error;
-extern int *allegro_errno = &allegro_error;
+int errnum;
+int *allegro_errno = &errnum;
 
 } // namespace AGS3
diff --git a/engines/ags/stubs/allegro/error.h b/engines/ags/stubs/allegro/error.h
index 46d3e03fde..7a5aeb627a 100644
--- a/engines/ags/stubs/allegro/error.h
+++ b/engines/ags/stubs/allegro/error.h
@@ -27,8 +27,6 @@
 
 namespace AGS3 {
 
-
-
 // Error codes
 #define EPERM           1
 #define ENOENT          2
@@ -75,6 +73,7 @@ namespace AGS3 {
 #define STRUNCATE       80
 #endif
 
+extern int errnum;
 extern int *allegro_errno;
 
 } // namespace AGS3
diff --git a/engines/ags/stubs/allegro/fixed.h b/engines/ags/stubs/allegro/fixed.h
index 45acd42c99..fa1e456b12 100644
--- a/engines/ags/stubs/allegro/fixed.h
+++ b/engines/ags/stubs/allegro/fixed.h
@@ -27,7 +27,7 @@
 
 namespace AGS3 {
 
-typedef uint32 fixed;
+typedef long fixed;
 
 extern fixed fixtorad_r;
 extern fixed radtofix_r;
diff --git a/engines/ags/stubs/allegro/mouse.cpp b/engines/ags/stubs/allegro/mouse.cpp
index c8bad8476f..daa0bad28f 100644
--- a/engines/ags/stubs/allegro/mouse.cpp
+++ b/engines/ags/stubs/allegro/mouse.cpp
@@ -27,7 +27,9 @@ namespace AGS3 {
 
 MOUSE_DRIVER mousedrv_none;
 MOUSE_DRIVER *mouse_driver;
-_DRIVER_INFO _mouse_driver_list[];
+_DRIVER_INFO _mouse_driver_list[] = {
+	{ 0, nullptr, 0 }
+};
 
 BITMAP *mouse_sprite;
 int mouse_x_focus;


Commit: b177fe144589986c8789ce59572419ae197b2431
    https://github.com/scummvm/scummvm/commit/b177fe144589986c8789ce59572419ae197b2431
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added shared/script/

Changed paths:
    engines/ags/module.mk
    engines/ags/shared/script/cc_error.cpp
    engines/ags/shared/script/cc_error.h
    engines/ags/shared/script/cc_options.cpp
    engines/ags/shared/script/cc_script.cpp
    engines/ags/shared/script/cc_script.h


diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 4d51bd9761..ae53b8b55d 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -17,6 +17,9 @@ MODULE_OBJS = \
 	stubs/allegro/sound.o \
 	stubs/allegro/system.o \
 	stubs/allegro/unicode.o \
+	shared/script/cc_error.o \
+	shared/script/cc_options.o \
+	shared/script/cc_script.o \
 	shared/util/alignedstream.o \
 	shared/util/bufferedstream.o \
 	shared/util/compress.o \
diff --git a/engines/ags/shared/script/cc_error.cpp b/engines/ags/shared/script/cc_error.cpp
index 8c0712b8cb..9e5736bb81 100644
--- a/engines/ags/shared/script/cc_error.cpp
+++ b/engines/ags/shared/script/cc_error.cpp
@@ -20,10 +20,9 @@
  *
  */
 
-//include <stdio.h>
-//include <utility>
 #include "ags/shared/script/script_common.h"  // current_line
 #include "ags/shared/util/string.h"
+#include "ags/std/utility.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/script/cc_error.h b/engines/ags/shared/script/cc_error.h
index 1417b137fc..35089ada23 100644
--- a/engines/ags/shared/script/cc_error.h
+++ b/engines/ags/shared/script/cc_error.h
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#ifndef AGS_SHARED_SCRIPT_ERROR_H
-#define AGS_SHARED_SCRIPT_ERROR_H
+#ifndef AGS_SHARED_SCRIPT_CC_ERROR_H
+#define AGS_SHARED_SCRIPT_CC_ERROR_H
 
 #include "ags/shared/util/string.h"
 
diff --git a/engines/ags/shared/script/cc_options.cpp b/engines/ags/shared/script/cc_options.cpp
index 1262d6fa49..d0b8c1b1e8 100644
--- a/engines/ags/shared/script/cc_options.cpp
+++ b/engines/ags/shared/script/cc_options.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/shared/cc_options.h"
+#include "ags/shared/script/cc_options.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/script/cc_script.cpp b/engines/ags/shared/script/cc_script.cpp
index 0c9079107c..3e638d3d15 100644
--- a/engines/ags/shared/script/cc_script.cpp
+++ b/engines/ags/shared/script/cc_script.cpp
@@ -62,7 +62,7 @@ void fwritestring(const char *strptr, Stream *out) {
 	}
 }
 
-ccScript *ccScript::CreateFromStream(Stream *in) {
+ccScript *ccScript::CreateFromStream(Shared::Stream *in) {
 	ccScript *scri = new ccScript();
 	if (!scri->Read(in)) {
 		delete scri;
@@ -177,7 +177,7 @@ ccScript::~ccScript() {
 	Free();
 }
 
-void ccScript::Write(Stream *out) {
+void ccScript::Write(Shared::Stream *out) {
 	int n;
 	out->Write(scfilesig, 4);
 	out->WriteInt32(SCOM_VERSION);
@@ -211,7 +211,7 @@ void ccScript::Write(Stream *out) {
 	out->WriteInt32(ENDFILESIG);
 }
 
-bool ccScript::Read(Stream *in) {
+bool ccScript::Read(Shared::Stream *in) {
 	instances = 0;
 	int n;
 	char gotsig[5];
@@ -296,7 +296,7 @@ bool ccScript::Read(Stream *in) {
 		sectionOffsets = nullptr;
 	}
 
-	if (in->ReadInt32() != ENDFILESIG) {
+	if (in->ReadInt32() != (int32)ENDFILESIG) {
 		cc_error("internal error rebuilding script");
 		return false;
 	}
diff --git a/engines/ags/shared/script/cc_script.h b/engines/ags/shared/script/cc_script.h
index 53b3c4a750..a0852f5851 100644
--- a/engines/ags/shared/script/cc_script.h
+++ b/engines/ags/shared/script/cc_script.h
@@ -29,8 +29,8 @@
 #ifndef AGS_SHARED_SCRIPT_CC_SCRIPT_H
 #define AGS_SHARED_SCRIPT_CC_SCRIPT_H
 
-//include <memory>
 #include "ags/shared/core/types.h"
+#include "ags/std/memory.h"
 
 namespace AGS3 {
 
@@ -68,16 +68,16 @@ public:
 	int numSections;
 	int capacitySections;
 
-	static ccScript *CreateFromStream(Common::Stream *in);
+	static ccScript *CreateFromStream(Shared::Stream *in);
 
 	ccScript();
 	ccScript(const ccScript &src);
 	virtual ~ccScript(); // there are few derived classes, so dtor should be virtual
 
 	// write the script to disk (after compiling)
-	void        Write(Common::Stream *out);
+	void        Write(Shared::Stream *out);
 	// read back a script written with Write
-	bool        Read(Common::Stream *in);
+	bool        Read(Shared::Stream *in);
 	const char *GetSectionName(int32_t offset);
 
 protected:


Commit: d43369f309e594266f4f30f2b0872e3c4f2ba4df
    https://github.com/scummvm/scummvm/commit/d43369f309e594266f4f30f2b0872e3c4f2ba4df
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Adding shared/gui/ folder

Changed paths:
    engines/ags/module.mk
    engines/ags/shared/ac/common_defines.h
    engines/ags/shared/ac/spritecache.h
    engines/ags/shared/debugging/out.h
    engines/ags/shared/font/fonts.h
    engines/ags/shared/gui/guibutton.cpp
    engines/ags/shared/gui/guibutton.h
    engines/ags/shared/gui/guiinv.h
    engines/ags/shared/gui/guilabel.cpp
    engines/ags/shared/gui/guilabel.h
    engines/ags/shared/gui/guilistbox.cpp
    engines/ags/shared/gui/guilistbox.h
    engines/ags/shared/gui/guimain.cpp
    engines/ags/shared/gui/guimain.h
    engines/ags/shared/gui/guiobject.h
    engines/ags/shared/gui/guislider.cpp
    engines/ags/std/algorithm.h


diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index ae53b8b55d..6a5a42c6c7 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -17,6 +17,14 @@ MODULE_OBJS = \
 	stubs/allegro/sound.o \
 	stubs/allegro/system.o \
 	stubs/allegro/unicode.o \
+	shared/gui/guibutton.o \
+	shared/gui/guiinv.o \
+	shared/gui/guilabel.o \
+	shared/gui/guilistbox.o \
+	shared/gui/guimain.o \
+	shared/gui/guiobject.o \
+	shared/gui/guislider.o \
+	shared/gui/guitextbox.o \
 	shared/script/cc_error.o \
 	shared/script/cc_options.o \
 	shared/script/cc_script.o \
diff --git a/engines/ags/shared/ac/common_defines.h b/engines/ags/shared/ac/common_defines.h
index 282ad7ea89..c606d6e627 100644
--- a/engines/ags/shared/ac/common_defines.h
+++ b/engines/ags/shared/ac/common_defines.h
@@ -106,10 +106,6 @@ namespace AGS3 {
 #define LEGACY_MAX_SPRITES      30000
 #define MAX_CURSOR          20
 
-#ifndef int32
-#define int32 int
-#endif
-
 #if AGS_PLATFORM_OS_WINDOWS
 #define AGS_INLINE inline
 #else
diff --git a/engines/ags/shared/ac/spritecache.h b/engines/ags/shared/ac/spritecache.h
index a6ed86f3e5..5a0ebf0dff 100644
--- a/engines/ags/shared/ac/spritecache.h
+++ b/engines/ags/shared/ac/spritecache.h
@@ -117,8 +117,8 @@ public:
 	static const size_t   MAX_SPRITE_SLOTS = INT32_MAX;
 
 	// Standart sprite file and sprite index names
-	static const Common::String DefaultSpriteFileName;
-	static const Common::String DefaultSpriteIndexName;
+	static const Shared::String DefaultSpriteFileName;
+	static const Shared::String DefaultSpriteIndexName;
 
 	SpriteCache(std::vector<SpriteInfo> &sprInfos);
 	~SpriteCache();
@@ -153,12 +153,12 @@ public:
 	// Deletes all data and resets cache to the clear state
 	void        Reset();
 	// Assigns new sprite for the given index; this sprite won't be auto disposed
-	void        SetSprite(sprkey_t index, Common::Bitmap *);
+	void        SetSprite(sprkey_t index, Shared::Bitmap *);
 	// Assigns new sprite for the given index, remapping it to sprite 0;
 	// optionally marks it as an asset placeholder
 	void        SetEmptySprite(sprkey_t index, bool as_asset);
 	// Assigns new bitmap for the *registered* sprite without changing its properties
-	void        SubstituteBitmap(sprkey_t index, Common::Bitmap *);
+	void        SubstituteBitmap(sprkey_t index, Shared::Bitmap *);
 	// Sets max cache size in bytes
 	void        SetMaxCacheSize(size_t size);
 
@@ -177,7 +177,7 @@ public:
 	int         SaveSpriteIndex(const char *filename, const SpriteFileIndex &index);
 
 	// Loads (if it's not in cache yet) and returns bitmap by the sprite index
-	Common::Bitmap *operator[](sprkey_t index);
+	Shared::Bitmap *operator[](sprkey_t index);
 
 private:
 	void        Init();
@@ -199,7 +199,7 @@ private:
 		uint32_t        Flags;
 		// TODO: investigate if we may safely use unique_ptr here
 		// (some of these bitmaps may be assigned from outside of the cache)
-		Common::Bitmap *Image; // actual bitmap
+		Shared::Bitmap *Image; // actual bitmap
 
 		// Tells if there actually is a registered sprite in this slot
 		bool DoesSpriteExist() const;
@@ -220,7 +220,7 @@ private:
 	std::vector<SpriteData> _spriteData;
 	bool _compressed;        // are sprites compressed
 
-	std::unique_ptr<Common::Stream> _stream; // the sprite stream
+	std::unique_ptr<Shared::Stream> _stream; // the sprite stream
 	sprkey_t _lastLoad; // last loaded sprite index
 
 	size_t _maxCacheSize;  // cache size limit
@@ -240,9 +240,9 @@ private:
 	// Rebuilds sprite index from the main sprite file
 	HAGSError   RebuildSpriteIndex(AGS::Shared::Stream *in, sprkey_t topmost, SpriteFileVersion vers);
 	// Writes compressed sprite to the stream
-	void        CompressSprite(Common::Bitmap *sprite, Common::Stream *out);
+	void        CompressSprite(Shared::Bitmap *sprite, Shared::Stream *out);
 	// Uncompresses sprite from stream into the given bitmap
-	void        UnCompressSprite(Common::Bitmap *sprite, Common::Stream *in);
+	void        UnCompressSprite(Shared::Bitmap *sprite, Shared::Stream *in);
 
 	// Initialize the empty sprite slot
 	void        InitNullSpriteParams(sprkey_t index);
diff --git a/engines/ags/shared/debugging/out.h b/engines/ags/shared/debugging/out.h
index b68cee3bec..74fc343bc8 100644
--- a/engines/ags/shared/debugging/out.h
+++ b/engines/ags/shared/debugging/out.h
@@ -132,19 +132,19 @@ struct DebugGroupID {
 	uint32_t    ID;
 	String      SID;
 
-	DebugGroupID() : ID(kDbgGroup_None) {
+	DebugGroupID() : ID((uint32_t)kDbgGroup_None) {
 	}
 	DebugGroupID(uint32_t id, const String &sid = "") : ID(id), SID(sid) {
 	}
-	DebugGroupID(const String &sid) : ID(kDbgGroup_None), SID(sid) {
+	DebugGroupID(const String &sid) : ID((uint32_t)kDbgGroup_None), SID(sid) {
 	}
 	// Tells if any of the id components is valid
 	bool IsValid() const {
-		return ID != kDbgGroup_None || !SID.IsEmpty();
+		return ID != (uint32_t)kDbgGroup_None || !SID.IsEmpty();
 	}
 	// Tells if both id components are properly set
 	bool IsComplete() const {
-		return ID != kDbgGroup_None && !SID.IsEmpty();
+		return ID != (uint32_t)kDbgGroup_None && !SID.IsEmpty();
 	}
 };
 
diff --git a/engines/ags/shared/font/fonts.h b/engines/ags/shared/font/fonts.h
index 85d69d68c9..c3e9265588 100644
--- a/engines/ags/shared/font/fonts.h
+++ b/engines/ags/shared/font/fonts.h
@@ -31,9 +31,9 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Bitmap;
-namespace Sharedhared
+} // namespace Shared
 } // namespace AGS
 
 using namespace AGS;
@@ -79,12 +79,12 @@ void set_font_outline(size_t font_number, int outline_type);
 // Outputs a single line of text on the defined position on bitmap, using defined font, color and parameters
 int getfontlinespacing(size_t fontNumber);
 // Print text on a surface using a given font
-void wouttextxy(Common::Bitmap *ds, int xxx, int yyy, size_t fontNumber, color_t text_color, const char *texx);
+void wouttextxy(Shared::Bitmap *ds, int xxx, int yyy, size_t fontNumber, color_t text_color, const char *texx);
 // Assigns FontInfo to the font
 void set_fontinfo(size_t fontNumber, const FontInfo &finfo);
 // Loads a font from disk
 bool wloadfont_size(size_t fontNumber, const FontInfo &font_info);
-void wgtprintf(Common::Bitmap *ds, int xxx, int yyy, size_t fontNumber, color_t text_color, char *fmt, ...);
+void wgtprintf(Shared::Bitmap *ds, int xxx, int yyy, size_t fontNumber, color_t text_color, char *fmt, ...);
 // Free particular font's data
 void wfreefont(size_t fontNumber);
 // Free all fonts data
@@ -100,10 +100,10 @@ public:
 	inline size_t Count() const {
 		return _count;
 	}
-	inline const Common::String &operator[](size_t i) const {
+	inline const Shared::String &operator[](size_t i) const {
 		return _pool[i];
 	}
-	inline Common::String &operator[](size_t i) {
+	inline Shared::String &operator[](size_t i) {
 		return _pool[i];
 	}
 	inline void Clear() {
@@ -122,7 +122,7 @@ public:
 	std::vector<char> LineBuf;
 
 private:
-	std::vector<Common::String> _pool;
+	std::vector<Shared::String> _pool;
 	size_t _count; // actual number of lines in use
 };
 
@@ -131,9 +131,9 @@ private:
 size_t split_lines(const char *texx, SplitLines &lines, int width, int fontNumber, size_t max_lines = -1);
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 extern SplitLines Lines;
-namespace Sharedhared
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 
diff --git a/engines/ags/shared/gui/guibutton.cpp b/engines/ags/shared/gui/guibutton.cpp
index 03a99749eb..eee618201a 100644
--- a/engines/ags/shared/gui/guibutton.cpp
+++ b/engines/ags/shared/gui/guibutton.cpp
@@ -279,7 +279,7 @@ void GUIButton::DrawImageButton(Bitmap *ds, bool draw_disabled) {
 		}
 
 		if (place == kButtonPlace_InvItemStretch) {
-			ds->StretchBlt(spriteset[gui_inv_pic], RectWH(X + 3, Y + 3, Width - 6, Height - 6), Common::kBitmap_Transparency);
+			ds->StretchBlt(spriteset[gui_inv_pic], RectWH(X + 3, Y + 3, Width - 6, Height - 6), Shared::kBitmap_Transparency);
 		} else if (place == kButtonPlace_InvItemCenter) {
 			draw_gui_sprite(ds, gui_inv_pic,
 				X + Width / 2 - get_adjusted_spritewidth(gui_inv_pic) / 2,
diff --git a/engines/ags/shared/gui/guibutton.h b/engines/ags/shared/gui/guibutton.h
index 87597ec57f..955df3c5c6 100644
--- a/engines/ags/shared/gui/guibutton.h
+++ b/engines/ags/shared/gui/guibutton.h
@@ -79,8 +79,8 @@ public:
 	// Serialization
 	void ReadFromFile(Stream *in, GuiVersion gui_version) override;
 	void WriteToFile(Stream *out) const override;
-	void ReadFromSavegame(Common::Stream *in, GuiSvgVersion svg_ver) override;
-	void WriteToSavegame(Common::Stream *out) const override;
+	void ReadFromSavegame(Stream *in, GuiSvgVersion svg_ver) override;
+	void WriteToSavegame(Stream *out) const override;
 
 	// TODO: these members are currently public; hide them later
 public:
diff --git a/engines/ags/shared/gui/guiinv.h b/engines/ags/shared/gui/guiinv.h
index 9debe7dcec..ba16d7a596 100644
--- a/engines/ags/shared/gui/guiinv.h
+++ b/engines/ags/shared/gui/guiinv.h
@@ -50,8 +50,8 @@ public:
 	// Serialization
 	void ReadFromFile(Stream *in, GuiVersion gui_version) override;
 	void WriteToFile(Stream *out) const override;
-	void ReadFromSavegame(Common::Stream *in, GuiSvgVersion svg_ver) override;
-	void WriteToSavegame(Common::Stream *out) const override;
+	void ReadFromSavegame(Stream *in, GuiSvgVersion svg_ver) override;
+	void WriteToSavegame(Stream *out) const override;
 
 	// TODO: these members are currently public; hide them later
 public:
diff --git a/engines/ags/shared/gui/guilabel.cpp b/engines/ags/shared/gui/guilabel.cpp
index ea91eeef02..96b26c1bfe 100644
--- a/engines/ags/shared/gui/guilabel.cpp
+++ b/engines/ags/shared/gui/guilabel.cpp
@@ -49,7 +49,7 @@ String GUILabel::GetText() const {
 	return Text;
 }
 
-void GUILabel::Draw(Common::Bitmap *ds) {
+void GUILabel::Draw(Shared::Bitmap *ds) {
 	check_font(&Font);
 
 	// TODO: need to find a way to cache text prior to drawing;
diff --git a/engines/ags/shared/gui/guilabel.h b/engines/ags/shared/gui/guilabel.h
index 6ad4a883b2..836b473a4b 100644
--- a/engines/ags/shared/gui/guilabel.h
+++ b/engines/ags/shared/gui/guilabel.h
@@ -47,8 +47,8 @@ public:
 	// Serialization
 	void ReadFromFile(Stream *in, GuiVersion gui_version) override;
 	void WriteToFile(Stream *out) const override;
-	void ReadFromSavegame(Common::Stream *in, GuiSvgVersion svg_ver) override;
-	void WriteToSavegame(Common::Stream *out) const override;
+	void ReadFromSavegame(Stream *in, GuiSvgVersion svg_ver) override;
+	void WriteToSavegame(Stream *out) const override;
 
 	// TODO: these members are currently public; hide them later
 public:
diff --git a/engines/ags/shared/gui/guilistbox.cpp b/engines/ags/shared/gui/guilistbox.cpp
index b3ee25688b..f908df0dac 100644
--- a/engines/ags/shared/gui/guilistbox.cpp
+++ b/engines/ags/shared/gui/guilistbox.cpp
@@ -97,7 +97,7 @@ void GUIListBox::Clear() {
 	guis_need_update = 1;
 }
 
-void GUIListBox::Draw(Common::Bitmap *ds) {
+void GUIListBox::Draw(Shared::Bitmap *ds) {
 	const int width = Width - 1;
 	const int height = Height - 1;
 	const int pixel_size = get_fixed_pixel_size(1);
diff --git a/engines/ags/shared/gui/guilistbox.h b/engines/ags/shared/gui/guilistbox.h
index 61472388b8..090184ba04 100644
--- a/engines/ags/shared/gui/guilistbox.h
+++ b/engines/ags/shared/gui/guilistbox.h
@@ -61,8 +61,8 @@ public:
 	// Serialization
 	void ReadFromFile(Stream *in, GuiVersion gui_version) override;
 	void WriteToFile(Stream *out) const override;
-	void ReadFromSavegame(Common::Stream *in, GuiSvgVersion svg_ver) override;
-	void WriteToSavegame(Common::Stream *out) const override;
+	void ReadFromSavegame(Stream *in, GuiSvgVersion svg_ver) override;
+	void WriteToSavegame(Stream *out) const override;
 
 	// TODO: these members are currently public; hide them later
 public:
diff --git a/engines/ags/shared/gui/guimain.cpp b/engines/ags/shared/gui/guimain.cpp
index 8b1f6e8b7f..1fb82b5175 100644
--- a/engines/ags/shared/gui/guimain.cpp
+++ b/engines/ags/shared/gui/guimain.cpp
@@ -20,7 +20,6 @@
  *
  */
 
-//include <algorithm>
 #include "ags/shared/ac/game_version.h"
 #include "ags/shared/ac/spritecache.h"
 #include "ags/shared/debugging/out.h"
@@ -34,6 +33,7 @@
 #include "ags/shared/gui/guitextbox.h"
 #include "ags/shared/util/stream.h"
 #include "ags/shared/util/string_utils.h"
+#include "ags/std/algorithm.h"
 
 namespace AGS3 {
 
@@ -561,7 +561,7 @@ void GUIMain::WriteToFile(Stream *out) const {
 	}
 }
 
-void GUIMain::ReadFromSavegame(Common::Stream *in, GuiSvgVersion svg_version) {
+void GUIMain::ReadFromSavegame(Stream *in, GuiSvgVersion svg_version) {
 	// Properties
 	_flags = in->ReadInt32();
 	X = in->ReadInt32();
@@ -593,7 +593,7 @@ void GUIMain::ReadFromSavegame(Common::Stream *in, GuiSvgVersion svg_version) {
 	MouseWasAt.Y = in->ReadInt32();
 }
 
-void GUIMain::WriteToSavegame(Common::Stream *out) const {
+void GUIMain::WriteToSavegame(Stream *out) const {
 	// Properties
 	out->WriteInt32(_flags);
 	out->WriteInt32(X);
@@ -643,10 +643,10 @@ void DrawTextAlignedHor(Bitmap *ds, const char *text, int font, color_t text_col
 	wouttext_outline(ds, x, y, font, text_color, text);
 }
 
-HError ResortGUI(std::vector<GUIMain> &guis, bool bwcompat_ctrl_zorder = false) {
+HError ResortGUI(std::vector<GUIMain> &theGuis, bool bwcompat_ctrl_zorder = false) {
 	// set up the reverse-lookup array
-	for (size_t gui_index = 0; gui_index < guis.size(); ++gui_index) {
-		GUIMain &gui = guis[gui_index];
+	for (size_t gui_index = 0; gui_index < theGuis.size(); ++gui_index) {
+		GUIMain &gui = theGuis[gui_index];
 		HError err = gui.RebuildArray();
 		if (!err)
 			return err;
@@ -663,7 +663,7 @@ HError ResortGUI(std::vector<GUIMain> &guis, bool bwcompat_ctrl_zorder = false)
 	return HError::None();
 }
 
-HError ReadGUI(std::vector<GUIMain> &guis, Stream *in, bool is_savegame) {
+HError ReadGUI(std::vector<GUIMain> &theGuis, Stream *in, bool is_savegame) {
 	if (in->ReadInt32() != (int)GUIMAGIC)
 		return new Error("ReadGUI: unknown format or file is corrupt");
 
@@ -678,11 +678,11 @@ HError ReadGUI(std::vector<GUIMain> &guis, Stream *in, bool is_savegame) {
 			GameGuiVersion, kGuiVersion_Initial, kGuiVersion_Current));
 	else
 		gui_count = in->ReadInt32();
-	guis.resize(gui_count);
+	theGuis.resize(gui_count);
 
 	// import the main GUI elements
 	for (size_t i = 0; i < gui_count; ++i) {
-		GUIMain &gui = guis[i];
+		GUIMain &gui = theGuis[i];
 		gui.InitDefaults();
 		gui.ReadFromFile(in, GameGuiVersion);
 
@@ -764,16 +764,16 @@ HError ReadGUI(std::vector<GUIMain> &guis, Stream *in, bool is_savegame) {
 			guilist[i].ReadFromFile(in, GameGuiVersion);
 		}
 	}
-	return ResortGUI(guis, GameGuiVersion < kGuiVersion_272e);
+	return ResortGUI(theGuis, GameGuiVersion < kGuiVersion_272e);
 }
 
-void WriteGUI(const std::vector<GUIMain> &guis, Stream *out) {
+void WriteGUI(const std::vector<GUIMain> &theGuis, Stream *out) {
 	out->WriteInt32(GUIMAGIC);
 	out->WriteInt32(kGuiVersion_Current);
-	out->WriteInt32(guis.size());
+	out->WriteInt32(theGuis.size());
 
-	for (size_t i = 0; i < guis.size(); ++i) {
-		guis[i].WriteToFile(out);
+	for (size_t i = 0; i < theGuis.size(); ++i) {
+		theGuis[i].WriteToFile(out);
 	}
 	out->WriteInt32(numguibuts);
 	for (int i = 0; i < numguibuts; ++i) {
diff --git a/engines/ags/shared/gui/guimain.h b/engines/ags/shared/gui/guimain.h
index 4a930f3b4f..4c42a25e59 100644
--- a/engines/ags/shared/gui/guimain.h
+++ b/engines/ags/shared/gui/guimain.h
@@ -23,13 +23,14 @@
 #ifndef AGS_SHARED_GUI_GUIMAIN_H
 #define AGS_SHARED_GUI_GUIMAIN_H
 
-//include <vector>
 #include "ags/shared/ac/common_defines.h" // TODO: split out gui drawing helpers
 #include "ags/shared/gfx/gfx_def.h" // TODO: split out gui drawing helpers
 #include "ags/shared/gui/guidefines.h"
 #include "ags/shared/util/error.h"
 #include "ags/shared/util/geometry.h"
 #include "ags/shared/util/string.h"
+#include "ags/std/utility.h"
+#include "ags/std/vector.h"
 
 namespace AGS3 {
 
@@ -217,7 +218,7 @@ void ApplyLegacyVisibility(GUIMain &gui, LegacyGUIVisState vis);
 } // namespace Shared
 } // namespace AGS
 
-extern std::vector<Common::GUIMain> guis;
+extern std::vector<Shared::GUIMain> guis;
 extern int all_buttons_disabled, gui_inv_pic;
 extern int gui_disabled_style;
 
@@ -228,8 +229,8 @@ extern int get_adjusted_spriteheight(int spr);
 extern bool is_sprite_alpha(int spr);
 
 // This function has distinct implementations in Engine and Editor
-extern void draw_gui_sprite(Common::Bitmap *ds, int spr, int x, int y, bool use_alpha = true,
-	Common::BlendMode blend_mode = Common::kBlendMode_Alpha);
+extern void draw_gui_sprite(Shared::Bitmap *ds, int spr, int x, int y, bool use_alpha = true,
+	Shared::BlendMode blend_mode = Shared::kBlendMode_Alpha);
 
 extern AGS_INLINE int game_to_data_coord(int coord);
 extern AGS_INLINE int data_to_game_coord(int coord);
@@ -237,8 +238,8 @@ extern AGS_INLINE void data_to_game_coords(int *x, int *y);
 extern AGS_INLINE int get_fixed_pixel_size(int pixels);
 
 // Those function have distinct implementations in Engine and Editor
-extern void wouttext_outline(Common::Bitmap *ds, int xxp, int yyp, int usingfont, color_t text_color, const char *texx);
-extern int wgettextwidth_compensate(Common::Bitmap *ds, const char *tex, int font);
+extern void wouttext_outline(Shared::Bitmap *ds, int xxp, int yyp, int usingfont, color_t text_color, const char *texx);
+extern int wgettextwidth_compensate(Shared::Bitmap *ds, const char *tex, int font);
 extern void check_font(int *fontnum);
 
 extern void set_our_eip(int eip);
diff --git a/engines/ags/shared/gui/guiobject.h b/engines/ags/shared/gui/guiobject.h
index bf37d9b792..c0ba3c4630 100644
--- a/engines/ags/shared/gui/guiobject.h
+++ b/engines/ags/shared/gui/guiobject.h
@@ -95,10 +95,10 @@ public:
 	}
 
 	// Serialization
-	virtual void    ReadFromFile(Common::Stream *in, GuiVersion gui_version);
-	virtual void    WriteToFile(Common::Stream *out) const;
-	virtual void    ReadFromSavegame(Common::Stream *in, GuiSvgVersion svg_ver);
-	virtual void    WriteToSavegame(Common::Stream *out) const;
+	virtual void    ReadFromFile(Stream *in, GuiVersion gui_version);
+	virtual void    WriteToFile(Stream *out) const;
+	virtual void    ReadFromSavegame(Stream *in, GuiSvgVersion svg_ver);
+	virtual void    WriteToSavegame(Stream *out) const;
 
 	// TODO: these members are currently public; hide them later
 public:
diff --git a/engines/ags/shared/gui/guislider.cpp b/engines/ags/shared/gui/guislider.cpp
index e356d620e7..fff16de2aa 100644
--- a/engines/ags/shared/gui/guislider.cpp
+++ b/engines/ags/shared/gui/guislider.cpp
@@ -51,15 +51,15 @@ bool GUISlider::IsHorizontal() const {
 	return Width > Height;
 }
 
-bool GUISlider::IsOverControl(int X, int Y, int leeway) const {
+bool GUISlider::IsOverControl(int x, int y, int leeway) const {
 	// check the overall boundary
-	if (GUIObject::IsOverControl(X, Y, leeway))
+	if (GUIObject::IsOverControl(x, y, leeway))
 		return true;
 	// now check the handle too
-	return _cachedHandle.IsInside(Point(X, Y));
+	return _cachedHandle.IsInside(Point(x, y));
 }
 
-void GUISlider::Draw(Common::Bitmap *ds) {
+void GUISlider::Draw(Bitmap *ds) {
 	Rect bar;
 	Rect handle;
 	int  thickness;
diff --git a/engines/ags/std/algorithm.h b/engines/ags/std/algorithm.h
index 504e883a42..8b5f070125 100644
--- a/engines/ags/std/algorithm.h
+++ b/engines/ags/std/algorithm.h
@@ -36,6 +36,11 @@ template<typename T> inline T clip(T v, T amin, T amax) { return CLIP(v, amin, a
 template<typename T> inline T sqrt(T x) { return ::sqrt(x); }
 template<typename T> inline void swap(T a, T b) { SWAP(a, b); }
 
+template<typename T, class StrictWeakOrdering>
+void sort(T first, T last, StrictWeakOrdering comp) {
+	Common::sort<T, StrictWeakOrdering>(first, last, comp);
+}
+
 } // namespace std
 } // namespace AGS3
 


Commit: b12ea53326be363e1c74e29e0746e36275ee5c88
    https://github.com/scummvm/scummvm/commit/b12ea53326be363e1c74e29e0746e36275ee5c88
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added shared/gfx/ and support code

Changed paths:
  A engines/ags/lib/aastr-0.1.1/aarot.cpp
  A engines/ags/lib/aastr-0.1.1/aastr.cpp
  A engines/ags/lib/aastr-0.1.1/aastr.h
  A engines/ags/lib/aastr-0.1.1/aautil.cpp
  A engines/ags/lib/aastr-0.1.1/aautil.h
  A engines/ags/shared/gfx/image.cpp
  A engines/ags/shared/gfx/image.h
    engines/ags/module.mk
    engines/ags/shared/core/types.h
    engines/ags/shared/gfx/allegrobitmap.cpp
    engines/ags/shared/gfx/allegrobitmap.h
    engines/ags/shared/gfx/bitmap.cpp
    engines/ags/shared/util/wgt2allg.h
    engines/ags/stubs/allegro/color.cpp
    engines/ags/stubs/allegro/color.h
    engines/ags/stubs/allegro/gfx.cpp
    engines/ags/stubs/allegro/gfx.h


diff --git a/engines/ags/lib/aastr-0.1.1/aarot.cpp b/engines/ags/lib/aastr-0.1.1/aarot.cpp
new file mode 100644
index 0000000000..e2bd4f325b
--- /dev/null
+++ b/engines/ags/lib/aastr-0.1.1/aarot.cpp
@@ -0,0 +1,559 @@
+/* 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.
+ *
+ */
+
+/*
+ * aarot.c --- anti-aliased rotation for Allegro
+ *
+ * This file is gift-ware.  This file is given to you freely
+ * as a gift.  You may use, modify, redistribute, and generally hack
+ * it about in any way you like, and you do not have to give anyone
+ * anything in return.
+ *
+ * I do not accept any responsibility for any effects, adverse or
+ * otherwise, that this code may have on just about anything that
+ * you can think of.  Use it at your own risk.
+ *
+ * Copyright (C) 1998, 1999  Michael Bukin
+ */
+
+#include "ags/lib/aastr-0.1.1/aastr.h"
+#include "ags/lib/aastr-0.1.1/aautil.h"
+
+namespace AGS3 {
+
+/*
+ * Engine of anti-aliased rotation.
+ */
+static void
+_aa_rotate_bitmap(BITMAP *_src, BITMAP *_dst, int _x, int _y, fixed _angle,
+	fixed _scalex, fixed _scaley, int _masked) {
+	int sw, sh, dw, dh;
+	fixed fx0, fy0, fux, fuy, fvx, fvy;
+	fixed fdw, fdh, fsinangle, fcosangle;
+	struct {
+		int dx, dy;
+		int sx, sy;
+	} point[4], *lpoint1, *lpoint2, *rpoint1, *rpoint2;
+	int ledge[4], redge[4], lindex, rindex;
+	int xbeg, xend, ybeg, yend;
+	int sx, sy, dx, dy, dsx, dsy;
+	int ldx, lsx, lsy, *lsc;
+	int rdx, rsx, rsy, *rsc;
+	int ldxinc, ldxdd, ldxi1, ldxi2;
+	int rdxinc, rdxdd, rdxi1, rdxi2;
+	int lscinc, lscdd, lsci1, lsci2;
+	int rscinc, rscdd, rsci1, rsci2;
+	int sxinc, sxdd, sxi1, sxi2;
+	int syinc, sydd, syi1, syi2;
+	unsigned long num;
+	void (*add) (BITMAP * _src, int _sx1, int _sx2, int _sy1, int _sy2, unsigned long _num);
+	void (*put) (unsigned long _addr, int _x);
+
+	if (_dst->clip) {
+		xbeg = _dst->cl;
+		xend = _dst->cr;
+		ybeg = _dst->ct;
+		yend = _dst->cb;
+	} else {
+		xbeg = 0;
+		xend = _dst->w;
+		ybeg = 0;
+		yend = _dst->h;
+	}
+
+	if ((xbeg >= xend) || (ybeg >= yend))
+		return;
+
+	/* Convert angle to [0, 256) range.  */
+	_angle %= itofix(256);
+	if (_angle < 0)
+		_angle += itofix(256);
+
+	/* Width and height of source and destination.  */
+	sw = _src->w;
+	sh = _src->h;
+	fdw = fixmul(ABS(_scalex), itofix(sw));
+	fdh = fixmul(ABS(_scaley), itofix(sh));
+	dw = fixtoi(fdw);
+	dh = fixtoi(fdh);
+	if ((dw <= 0) || (dh <= 0))
+		return;
+
+	fdw /= 2;
+	fdh /= 2;
+
+	/* Center of destination.  */
+	fx0 = itofix(_x);
+	fy0 = itofix(_y);
+
+	fsinangle = fixsin(_angle);
+	fcosangle = fixcos(_angle);
+
+	/* Map source (half) edges onto destination.  */
+	fux = fixmul(fdw, fcosangle);
+	fuy = fixmul(fdw, fsinangle);
+	fvx = -fixmul(fdh, fsinangle);
+	fvy = fixmul(fdh, fcosangle);
+
+	/* Coordinates of corners in destination.  */
+	point[0].dx = fixtoi(fx0 - fux - fvx);
+	point[1].dx = fixtoi(fx0 + fux - fvx);
+	point[2].dx = fixtoi(fx0 - fux + fvx);
+	point[3].dx = fixtoi(fx0 + fux + fvx);
+	point[0].dy = fixtoi(fy0 - fuy - fvy);
+	point[1].dy = fixtoi(fy0 + fuy - fvy);
+	point[2].dy = fixtoi(fy0 - fuy + fvy);
+	point[3].dy = fixtoi(fy0 + fuy + fvy);
+
+	sw <<= aa_BITS;
+	dsx = sw / dw;
+	if (dsx < aa_SIZE)
+		dsx = aa_SIZE;
+	sw -= dsx;
+
+	sh <<= aa_BITS;
+	dsy = sh / dh;
+	if (dsy < aa_SIZE)
+		dsy = aa_SIZE;
+	sh -= dsy;
+
+	num = dsx * dsy;
+
+	/* Avoid overflow.  */
+	if (num > aa_MAX_NUM) {
+		if (dsx > aa_MAX_SIZE)
+			dsx = aa_MAX_SIZE;
+		if (dsy > aa_MAX_SIZE)
+			dsy = aa_MAX_SIZE;
+		num = dsx * dsy;
+	}
+
+	/* Coordinates of corners in source.  */
+	if (_scalex < 0) {
+		point[0].sx = sw;
+		point[1].sx = 0;
+		point[2].sx = sw;
+		point[3].sx = 0;
+	} else {
+		point[0].sx = 0;
+		point[1].sx = sw;
+		point[2].sx = 0;
+		point[3].sx = sw;
+	}
+	if (_scaley < 0) {
+		point[0].sy = sh;
+		point[1].sy = sh;
+		point[2].sy = 0;
+		point[3].sy = 0;
+	} else {
+		point[0].sy = 0;
+		point[1].sy = 0;
+		point[2].sy = sh;
+		point[3].sy = sh;
+	}
+
+	/* Sort left and right edges.  */
+	if ((_angle < itofix(32)) || (_angle >= itofix(128 + 64 + 32))) {
+		if (point[0].dy < point[1].dy) {
+			ledge[0] = 0;
+			ledge[1] = 2;
+			ledge[2] = 3;
+			redge[0] = 0;
+			redge[1] = 1;
+			redge[2] = 3;
+		} else if (point[0].dy > point[1].dy) {
+			ledge[0] = 1;
+			ledge[1] = 0;
+			ledge[2] = 2;
+			redge[0] = 1;
+			redge[1] = 3;
+			redge[2] = 2;
+		} else {
+			ledge[0] = 0;
+			ledge[1] = 2;
+			ledge[2] = 3;
+			redge[0] = 1;
+			redge[1] = 3;
+			redge[2] = 2;
+		}
+	} else if (_angle < itofix(64 + 32)) {
+		if (point[0].dy < point[2].dy) {
+			ledge[0] = 0;
+			ledge[1] = 2;
+			ledge[2] = 3;
+			redge[0] = 0;
+			redge[1] = 1;
+			redge[2] = 3;
+		} else if (point[0].dy > point[2].dy) {
+			ledge[0] = 2;
+			ledge[1] = 3;
+			ledge[2] = 1;
+			redge[0] = 2;
+			redge[1] = 0;
+			redge[2] = 1;
+		} else {
+			ledge[0] = 2;
+			ledge[1] = 3;
+			ledge[2] = 1;
+			redge[0] = 0;
+			redge[1] = 1;
+			redge[2] = 3;
+		}
+	} else if (_angle < itofix(128 + 32)) {
+		if (point[2].dy < point[3].dy) {
+			ledge[0] = 2;
+			ledge[1] = 3;
+			ledge[2] = 1;
+			redge[0] = 2;
+			redge[1] = 0;
+			redge[2] = 1;
+		} else if (point[2].dy > point[3].dy) {
+			ledge[0] = 3;
+			ledge[1] = 1;
+			ledge[2] = 0;
+			redge[0] = 3;
+			redge[1] = 2;
+			redge[2] = 0;
+		} else {
+			ledge[0] = 3;
+			ledge[1] = 1;
+			ledge[2] = 0;
+			redge[0] = 2;
+			redge[1] = 0;
+			redge[2] = 1;
+		}
+	} else {
+		if (point[1].dy < point[3].dy) {
+			ledge[0] = 1;
+			ledge[1] = 0;
+			ledge[2] = 2;
+			redge[0] = 1;
+			redge[1] = 3;
+			redge[2] = 2;
+		} else if (point[1].dy > point[3].dy) {
+			ledge[0] = 3;
+			ledge[1] = 1;
+			ledge[2] = 0;
+			redge[0] = 3;
+			redge[1] = 2;
+			redge[2] = 0;
+		} else {
+			ledge[0] = 1;
+			ledge[1] = 0;
+			ledge[2] = 2;
+			redge[0] = 3;
+			redge[1] = 2;
+			redge[2] = 0;
+		}
+	}
+
+	/* Remove wrong edges on bottom.  */
+	if (point[ledge[0]].dy == point[ledge[1]].dy) {
+		ledge[0] = ledge[1];
+		ledge[1] = ledge[2];
+	}
+	if (point[ledge[1]].dy >= point[ledge[2]].dy)
+		ledge[2] = -1;
+	ledge[3] = -1;
+
+	if (point[redge[0]].dy == point[redge[1]].dy) {
+		redge[0] = redge[1];
+		redge[1] = redge[2];
+	}
+	if (point[redge[1]].dy >= point[redge[2]].dy)
+		redge[2] = -1;
+	redge[3] = -1;
+
+	/* Completely clipped by y?  */
+	if ((point[ledge[0]].dy >= yend)
+		|| ((ledge[2] == -1) && (point[ledge[1]].dy < ybeg))
+		|| (point[ledge[2]].dy < ybeg))
+		return;
+
+	/* Color manipulation routines.  */
+	if (is_screen_bitmap(_src))
+		return;
+	else {
+		switch (bitmap_color_depth(_src)) {
+		case 8:
+			add = ((_masked != 0) ? _aa_masked_add_rgb8 : _aa_add_rgb8);
+			break;
+#ifdef ALLEGRO_COLOR16
+		case 15:
+			add = ((_masked != 0) ? _aa_masked_add_rgb15 : _aa_add_rgb15);
+			break;
+		case 16:
+			add = ((_masked != 0) ? _aa_masked_add_rgb16 : _aa_add_rgb16);
+			break;
+#endif
+#ifdef ALLEGRO_COLOR24
+		case 24:
+			add = ((_masked != 0) ? _aa_masked_add_rgb24 : _aa_add_rgb24);
+			_aa_prepare_for_24bpp();
+			break;
+#endif
+#ifdef ALLEGRO_COLOR32
+		case 32:
+			add = ((_masked != 0) ? _aa_masked_add_rgb32 : _aa_add_rgb32);
+			break;
+#endif
+		default:
+			return;
+		}
+	}
+
+	if (is_planar_bitmap(_dst))
+		return;
+	else {
+		switch (bitmap_color_depth(_dst)) {
+		case 8:
+			put = ((_masked != 0) ? _aa_masked_put_rgb8 : _aa_put_rgb8);
+			break;
+#ifdef ALLEGRO_COLOR16
+		case 15:
+			put = ((_masked != 0) ? _aa_masked_put_rgb15 : _aa_put_rgb15);
+			break;
+		case 16:
+			put = ((_masked != 0) ? _aa_masked_put_rgb16 : _aa_put_rgb16);
+			break;
+#endif
+#ifdef ALLEGRO_COLOR24
+		case 24:
+			put = ((_masked != 0) ? _aa_masked_put_rgb24 : _aa_put_rgb24);
+			_aa_prepare_for_24bpp();
+			break;
+#endif
+#ifdef ALLEGRO_COLOR32
+		case 32:
+			put = ((_masked != 0) ? _aa_masked_put_rgb32 : _aa_put_rgb32);
+			break;
+#endif
+		default:
+			return;
+		}
+	}
+
+	lindex = 1;
+	rindex = 1;
+	lpoint1 = &point[ledge[0]];
+	lpoint2 = &point[ledge[1]];
+	rpoint1 = &point[redge[0]];
+	rpoint2 = &point[redge[1]];
+
+	dy = lpoint1->dy;
+	if (ledge[2] == -1) {
+		if (point[ledge[1]].dy < yend)
+			yend = point[ledge[1]].dy + 1;
+	} else if (point[ledge[2]].dy < yend)
+		yend = point[ledge[2]].dy + 1;
+
+	ldx = lpoint1->dx;
+	aa_PREPARE(ldxinc, ldxdd, ldxi1, ldxi2,
+		lpoint2->dx - lpoint1->dx, lpoint2->dy - lpoint1->dy);
+
+	lsx = lpoint1->sx;
+	lsy = lpoint1->sy;
+	if (lpoint1->sx != lpoint2->sx) {
+		lsc = &lsx;
+		aa_PREPARE(lscinc, lscdd, lsci1, lsci2,
+			lpoint2->sx - lpoint1->sx, lpoint2->dy - lpoint1->dy);
+	} else {
+		lsc = &lsy;
+		aa_PREPARE(lscinc, lscdd, lsci1, lsci2,
+			lpoint2->sy - lpoint1->sy, lpoint2->dy - lpoint1->dy);
+	}
+
+	rdx = rpoint1->dx;
+	aa_PREPARE(rdxinc, rdxdd, rdxi1, rdxi2,
+		rpoint2->dx - rpoint1->dx, rpoint2->dy - rpoint1->dy);
+
+	rsx = rpoint1->sx;
+	rsy = rpoint1->sy;
+	if (rpoint1->sx != rpoint2->sx) {
+		rsc = &rsx;
+		aa_PREPARE(rscinc, rscdd, rsci1, rsci2,
+			rpoint2->sx - rpoint1->sx, rpoint2->dy - rpoint1->dy);
+	} else {
+		rsc = &rsy;
+		aa_PREPARE(rscinc, rscdd, rsci1, rsci2,
+			rpoint2->sy - rpoint1->sy, rpoint2->dy - rpoint1->dy);
+	}
+
+	/* Skip region clipped on top.  */
+	while (dy < ybeg) {
+		dy++;
+
+		if (dy > lpoint2->dy) {
+			if (ledge[++lindex] == -1)
+				return;
+			lpoint1 = lpoint2;
+			lpoint2 = &point[ledge[lindex]];
+
+			if (lpoint1->sx != lpoint2->sx) {
+				lsc = &lsx;
+				aa_PREPARE(lscinc, lscdd, lsci1, lsci2,
+					lpoint2->sx - lpoint1->sx, lpoint2->dy - lpoint1->dy);
+			} else {
+				lsc = &lsy;
+				aa_PREPARE(lscinc, lscdd, lsci1, lsci2,
+					lpoint2->sy - lpoint1->sy, lpoint2->dy - lpoint1->dy);
+			}
+			aa_PREPARE(ldxinc, ldxdd, ldxi1, ldxi2,
+				lpoint2->dx - lpoint1->dx, lpoint2->dy - lpoint1->dy);
+		}
+		aa_ADVANCE(*lsc, lscinc, lscdd, lsci1, lsci2);
+		aa_ADVANCE(ldx, ldxinc, ldxdd, ldxi1, ldxi2);
+
+		if (dy > rpoint2->dy) {
+			if (redge[++rindex] == -1)
+				return;
+			rpoint1 = rpoint2;
+			rpoint2 = &point[redge[rindex]];
+
+			if (rpoint1->sx != rpoint2->sx) {
+				rsc = &rsx;
+				aa_PREPARE(rscinc, rscdd, rsci1, rsci2,
+					rpoint2->sx - rpoint1->sx, rpoint2->dy - rpoint1->dy);
+			} else {
+				rsc = &rsy;
+				aa_PREPARE(rscinc, rscdd, rsci1, rsci2,
+					rpoint2->sy - rpoint1->sy, rpoint2->dy - rpoint1->dy);
+			}
+			aa_PREPARE(rdxinc, rdxdd, rdxi1, rdxi2,
+				rpoint2->dx - rpoint1->dx, rpoint2->dy - rpoint1->dy);
+		}
+		aa_ADVANCE(*rsc, rscinc, rscdd, rsci1, rsci2);
+		aa_ADVANCE(rdx, rdxinc, rdxdd, rdxi1, rdxi2);
+	}
+
+	bmp_select(_dst);
+
+	/* Stretch lines.  */
+	while (dy < yend) {
+		unsigned long daddr = bmp_write_line(_dst, dy);
+
+		if ((ldx < xend) && (rdx >= xbeg)) {
+			int curxend;
+
+			aa_PREPARE(sxinc, sxdd, sxi1, sxi2,
+				rsx - lsx, rdx - ldx);
+			aa_PREPARE(syinc, sydd, syi1, syi2,
+				rsy - lsy, rdx - ldx);
+
+			for (sx = lsx, sy = lsy, dx = ldx; dx < xbeg; dx++) {
+				aa_ADVANCE(sx, sxinc, sxdd, sxi1, sxi2);
+				aa_ADVANCE(sy, syinc, sydd, syi1, syi2);
+			}
+
+			curxend = (rdx < xend) ? (rdx + 1) : xend;
+			for (; dx < curxend; dx++) {
+				(*add) (_src, sx, sx + dsx, sy, sy + dsy, num);
+				(*put) (daddr, dx);
+
+				aa_ADVANCE(sx, sxinc, sxdd, sxi1, sxi2);
+				aa_ADVANCE(sy, syinc, sydd, syi1, syi2);
+			}
+		}
+
+		dy++;
+
+		if (dy > lpoint2->dy) {
+			if (ledge[++lindex] == -1)
+				return;
+			lpoint1 = lpoint2;
+			lpoint2 = &point[ledge[lindex]];
+
+			if (lpoint1->sx != lpoint2->sx) {
+				lsc = &lsx;
+				aa_PREPARE(lscinc, lscdd, lsci1, lsci2,
+					lpoint2->sx - lpoint1->sx, lpoint2->dy - lpoint1->dy);
+			} else {
+				lsc = &lsy;
+				aa_PREPARE(lscinc, lscdd, lsci1, lsci2,
+					lpoint2->sy - lpoint1->sy, lpoint2->dy - lpoint1->dy);
+			}
+			aa_PREPARE(ldxinc, ldxdd, ldxi1, ldxi2,
+				lpoint2->dx - lpoint1->dx, lpoint2->dy - lpoint1->dy);
+		}
+		aa_ADVANCE(*lsc, lscinc, lscdd, lsci1, lsci2);
+		aa_ADVANCE(ldx, ldxinc, ldxdd, ldxi1, ldxi2);
+
+		if (dy > rpoint2->dy) {
+			if (redge[++rindex] == -1)
+				return;
+			rpoint1 = rpoint2;
+			rpoint2 = &point[redge[rindex]];
+
+			if (rpoint1->sx != rpoint2->sx) {
+				rsc = &rsx;
+				aa_PREPARE(rscinc, rscdd, rsci1, rsci2,
+					rpoint2->sx - rpoint1->sx, rpoint2->dy - rpoint1->dy);
+			} else {
+				rsc = &rsy;
+				aa_PREPARE(rscinc, rscdd, rsci1, rsci2,
+					rpoint2->sy - rpoint1->sy, rpoint2->dy - rpoint1->dy);
+			}
+			aa_PREPARE(rdxinc, rdxdd, rdxi1, rdxi2,
+				rpoint2->dx - rpoint1->dx, rpoint2->dy - rpoint1->dy);
+		}
+		aa_ADVANCE(*rsc, rscinc, rscdd, rsci1, rsci2);
+		aa_ADVANCE(rdx, rdxinc, rdxdd, rdxi1, rdxi2);
+	}
+
+	bmp_unwrite_line(_dst);
+}
+
+/*
+ * Anti-aliased bitmap rotation with scaling.
+ */
+void
+aa_rotate_scaled_bitmap(BITMAP *_src, BITMAP *_dst, int _x, int _y, fixed _angle,
+	fixed _scalex, fixed _scaley) {
+	_aa_rotate_bitmap(_src, _dst, _x, _y, _angle, _scalex, _scaley, 0);
+}
+
+/*
+ * Anti-aliased bitmap rotation with scaling (masked).
+ */
+void
+aa_rotate_scaled_sprite(BITMAP *_dst, BITMAP *_src, int _x, int _y, fixed _angle,
+	fixed _scalex, fixed _scaley) {
+	_aa_rotate_bitmap(_src, _dst, _x, _y, _angle, _scalex, _scaley, 1);
+}
+
+/*
+ * Anti-aliased bitmap rotation.
+ */
+void
+aa_rotate_bitmap(BITMAP *_src, BITMAP *_dst, int _x, int _y, fixed _angle) {
+	_aa_rotate_bitmap(_src, _dst, _x, _y, _angle, itofix(1), itofix(1), 0);
+}
+
+/*
+ * Anti-aliased bitmap rotation (masked).
+ */
+void
+aa_rotate_sprite(BITMAP *_dst, BITMAP *_src, int _x, int _y, fixed _angle) {
+	_aa_rotate_bitmap(_src, _dst, _x, _y, _angle, itofix(1), itofix(1), 1);
+}
+
+} // namespace AGS3
diff --git a/engines/ags/lib/aastr-0.1.1/aastr.cpp b/engines/ags/lib/aastr-0.1.1/aastr.cpp
new file mode 100644
index 0000000000..e62bbf7020
--- /dev/null
+++ b/engines/ags/lib/aastr-0.1.1/aastr.cpp
@@ -0,0 +1,224 @@
+/* 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.
+ *
+ */
+
+/*
+ * aastr.c --- anti-aliased stretching for Allegro
+ *
+ * This file is gift-ware.  This file is given to you freely
+ * as a gift.  You may use, modify, redistribute, and generally hack
+ * it about in any way you like, and you do not have to give anyone
+ * anything in return.
+ *
+ * I do not accept any responsibility for any effects, adverse or
+ * otherwise, that this code may have on just about anything that
+ * you can think of.  Use it at your own risk.
+ *
+ * Copyright (C) 1998, 1999  Michael Bukin
+ */
+
+#include "ags/lib/aastr-0.1.1/aastr.h"
+#include "ags/lib/aastr-0.1.1/aautil.h"
+
+namespace AGS3 {
+
+/*
+ * Engine of anti-aliased stretching.
+ */
+static void
+_aa_stretch_blit(BITMAP *_src, BITMAP *_dst,
+	int _sx, int _sy, int _sw, int _sh,
+	int _dx, int _dy, int _dw, int _dh, int _masked) {
+	int sx, sy, dx, dy, ydx, ysx;
+	int xinc, yinc, dsx, dsy;
+	int xi1, xi2, xdd, yxdd;
+	int yi1, yi2, ydd;
+	int dxbeg, dxend, dybeg, dyend;
+	unsigned long num;
+	void (*add) (BITMAP * _src, int _sx1, int _sx2, int _sy1, int _sy2, unsigned long _num);
+	void (*put) (unsigned long _addr, int _x);
+
+	if ((_dw <= 0) || (_dh <= 0) || (_sw <= 0) || (_sh <= 0))
+		return;
+
+	if (_dst->clip) {
+		dybeg = ((_dy > _dst->ct) ? _dy : _dst->ct);
+		dyend = (((_dy + _dh) < _dst->cb) ? (_dy + _dh) : _dst->cb);
+		if (dybeg >= dyend)
+			return;
+
+		dxbeg = ((_dx > _dst->cl) ? _dx : _dst->cl);
+		dxend = (((_dx + _dw) < _dst->cr) ? (_dx + _dw) : _dst->cr);
+		if (dxbeg >= dxend)
+			return;
+	} else {
+		dxbeg = _dx;
+		dybeg = _dy;
+		dxend = _dx + _dw;
+		dyend = _dy + _dh;
+	}
+
+	_sx <<= aa_BITS;
+	_sw <<= aa_BITS;
+	dsx = _sw / _dw;
+
+	if (dsx < aa_SIZE) {
+		/* Exploding by x.  */
+		_dw--;
+		_sw -= aa_SIZE;
+		dsx = aa_SIZE;
+	}
+
+	_sy <<= aa_BITS;
+	_sh <<= aa_BITS;
+	dsy = _sh / _dh;
+
+	if (dsy < aa_SIZE) {
+		/* Exploding by y.  */
+		_dh--;
+		_sh -= aa_SIZE;
+		dsy = aa_SIZE;
+	}
+
+	num = dsx * dsy;
+
+	if (num > aa_MAX_NUM) {
+		if (dsx > aa_MAX_SIZE)
+			dsx = aa_MAX_SIZE;
+		if (dsy > aa_MAX_SIZE)
+			dsy = aa_MAX_SIZE;
+		num = dsx * dsy;
+	}
+
+	/* Walk in x direction up to dxbeg and save Bresenham state there.
+	 * Later, it will be used to restart at any line.  */
+	aa_PREPARE(xinc, yxdd, xi1, xi2, _sw, _dw);
+	for (ydx = _dx, ysx = _sx; ydx < dxbeg; ydx++) {
+		aa_ADVANCE(ysx, xinc, yxdd, xi1, xi2);
+	}
+
+	/* Color manipulation routines.  */
+	if (is_screen_bitmap(_src))
+		return;
+	else {
+		switch (bitmap_color_depth(_src)) {
+		case 8:
+			add = ((_masked != 0) ? _aa_masked_add_rgb8 : _aa_add_rgb8);
+			break;
+#ifdef ALLEGRO_COLOR16
+		case 15:
+			add = ((_masked != 0) ? _aa_masked_add_rgb15 : _aa_add_rgb15);
+			break;
+		case 16:
+			add = ((_masked != 0) ? _aa_masked_add_rgb16 : _aa_add_rgb16);
+			break;
+#endif
+#ifdef ALLEGRO_COLOR24
+		case 24:
+			add = ((_masked != 0) ? _aa_masked_add_rgb24 : _aa_add_rgb24);
+			_aa_prepare_for_24bpp();
+			break;
+#endif
+#ifdef ALLEGRO_COLOR32
+		case 32:
+			add = ((_masked != 0) ? _aa_masked_add_rgb32 : _aa_add_rgb32);
+			break;
+#endif
+		default:
+			return;
+		}
+	}
+
+	if (is_planar_bitmap(_dst))
+		return;
+	else {
+		switch (bitmap_color_depth(_dst)) {
+		case 8:
+			put = ((_masked != 0) ? _aa_masked_put_rgb8 : _aa_put_rgb8);
+			break;
+#ifdef ALLEGRO_COLOR16
+		case 15:
+			put = ((_masked != 0) ? _aa_masked_put_rgb15 : _aa_put_rgb15);
+			break;
+		case 16:
+			put = ((_masked != 0) ? _aa_masked_put_rgb16 : _aa_put_rgb16);
+			break;
+#endif
+#ifdef ALLEGRO_COLOR24
+		case 24:
+			put = ((_masked != 0) ? _aa_masked_put_rgb24 : _aa_put_rgb24);
+			_aa_prepare_for_24bpp();
+			break;
+#endif
+#ifdef ALLEGRO_COLOR32
+		case 32:
+			put = ((_masked != 0) ? _aa_masked_put_rgb32 : _aa_put_rgb32);
+			break;
+#endif
+		default:
+			return;
+		}
+	}
+
+	/* Walk in y until we reach first non-clipped line.  */
+	aa_PREPARE(yinc, ydd, yi1, yi2, _sh, _dh);
+	for (dy = _dy, sy = _sy; dy < dybeg; dy++) {
+		aa_ADVANCE(sy, yinc, ydd, yi1, yi2);
+	}
+
+	bmp_select(_dst);
+
+	/* Stretch all non-clipped lines.  */
+	for (; dy < dyend; dy++) {
+		unsigned long daddr = bmp_write_line(_dst, dy);
+
+		for (dx = ydx, sx = ysx, xdd = yxdd; dx < dxend; dx++) {
+			(*add) (_src, sx, sx + dsx, sy, sy + dsy, num);
+			(*put) (daddr, dx);
+
+			aa_ADVANCE(sx, xinc, xdd, xi1, xi2);
+		}
+
+		aa_ADVANCE(sy, yinc, ydd, yi1, yi2);
+	}
+
+	bmp_unwrite_line(_dst);
+}
+
+/*
+ * Anti-aliased bitmap stretching with blit.
+ */
+void
+aa_stretch_blit(BITMAP *_src, BITMAP *_dst,
+	int _sx, int _sy, int _sw, int _sh,
+	int _dx, int _dy, int _dw, int _dh) {
+	_aa_stretch_blit(_src, _dst, _sx, _sy, _sw, _sh, _dx, _dy, _dw, _dh, 0);
+}
+
+/*
+ * Anti-aliased bitmap stretching with blit (masked).
+ */
+void
+aa_stretch_sprite(BITMAP *_dst, BITMAP *_src, int _dx, int _dy, int _dw, int _dh) {
+	_aa_stretch_blit(_src, _dst, 0, 0, _src->w, _src->h, _dx, _dy, _dw, _dh, 1);
+}
+
+} // namespace AGS3
diff --git a/engines/ags/lib/aastr-0.1.1/aastr.h b/engines/ags/lib/aastr-0.1.1/aastr.h
new file mode 100644
index 0000000000..3a85ca1a73
--- /dev/null
+++ b/engines/ags/lib/aastr-0.1.1/aastr.h
@@ -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.
+ *
+ */
+
+/*
+ * aastr.h --- anti-aliased stretching and rotation for Allegro
+ *
+ * This file is gift-ware.  This file is given to you freely
+ * as a gift.  You may use, modify, redistribute, and generally hack
+ * it about in any way you like, and you do not have to give anyone
+ * anything in return.
+ *
+ * I do not accept any responsibility for any effects, adverse or
+ * otherwise, that this code may have on just about anything that
+ * you can think of.  Use it at your own risk.
+ *
+ * Copyright (C) 1998, 1999  Michael Bukin
+ */
+
+#ifndef AGS_LIB_AASTR_AASTR_H
+#define AGS_LIB_AASTR_AASTR_H
+
+#include "ags/stubs/allegro.h"
+
+namespace AGS3 {
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Stretching.  */
+void aa_stretch_blit(BITMAP *src, BITMAP *dst,
+	int sx, int sy, int sw, int sh,
+	int dx, int dy, int dw, int dh);
+void aa_stretch_sprite(BITMAP *dst, BITMAP *src,
+	int dx, int dy, int dw, int dh);
+
+/* Rotation.  */
+void aa_rotate_scaled_bitmap(BITMAP *src, BITMAP *dst,
+	int x, int y, fixed angle,
+	fixed scalex, fixed scaley);
+void aa_rotate_scaled_sprite(BITMAP *dst, BITMAP *src,
+	int x, int y, fixed angle,
+	fixed scalex, fixed scaley);
+void aa_rotate_bitmap(BITMAP *src, BITMAP *dst,
+	int x, int y, fixed angle);
+void aa_rotate_sprite(BITMAP *dst, BITMAP *src,
+	int x, int y, fixed angle);
+
+#ifdef __cplusplus
+}
+#endif
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/lib/aastr-0.1.1/aautil.cpp b/engines/ags/lib/aastr-0.1.1/aautil.cpp
new file mode 100644
index 0000000000..25b789c36f
--- /dev/null
+++ b/engines/ags/lib/aastr-0.1.1/aautil.cpp
@@ -0,0 +1,1836 @@
+/* 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.
+ *
+ */
+
+/*
+ * aautil.c --- helpers for anti-aliasing routines for Allegro
+ *
+ * This file is gift-ware.  This file is given to you freely
+ * as a gift.  You may use, modify, redistribute, and generally hack
+ * it about in any way you like, and you do not have to give anyone
+ * anything in return.
+ *
+ * I do not accept any responsibility for any effects, adverse or
+ * otherwise, that this code may have on just about anything that
+ * you can think of.  Use it at your own risk.
+ *
+ * Copyright (C) 1998, 1999  Michael Bukin
+ */
+
+#include "ags/lib/aastr-0.1.1/aautil.h"
+
+namespace AGS3 {
+
+/* Multiply b by a (0 <= a <= aa_SIZE). */
+#define MUL(a, b) ((b) * (a))
+
+static struct
+{
+  int transparent;
+  unsigned int r;
+  unsigned int g;
+  unsigned int b;
+  int roffset24;
+  int goffset24;
+  int boffset24;
+} _aa;
+
+/*
+ * Prepare offsets for direct access to 24bpp bitmap.
+ */
+void
+_aa_prepare_for_24bpp (void)
+{
+  _aa.roffset24 = _rgb_r_shift_24 / 8;
+  _aa.goffset24 = _rgb_g_shift_24 / 8;
+  _aa.boffset24 = _rgb_b_shift_24 / 8;
+}
+
+/*
+ * Add r, g, b values of pixels.
+ */
+void
+_aa_add_rgb8 (BITMAP *_src, int _sx1, int _sx2, int _sy1, int _sy2, unsigned long _num)
+{
+  unsigned char *sline;
+  int sx, sx1i, sx1f, sx2i, sx2f;
+  int sy, sy1i, sy1f, sy2i, sy2f;
+  unsigned int r1, g1, b1;
+  unsigned int r2, g2, b2;
+  unsigned int scolor;
+
+  sy1i = _sy1 >> aa_BITS;
+  sy = sy1i;
+
+  /* First line.  */
+  sx1i = _sx1 >> aa_BITS;
+  sx = sx1i;
+  sline = _src->line[sy] + sx;
+
+  sx1f = aa_SIZE - (_sx1 & aa_MASK);
+  scolor = *sline;
+  r1 = MUL (getr8 (scolor), sx1f);
+  g1 = MUL (getg8 (scolor), sx1f);
+  b1 = MUL (getb8 (scolor), sx1f);
+
+  sx2i = _sx2 >> aa_BITS;
+  for (sline++, sx++; sx < sx2i; sline++, sx++)
+    {
+      scolor = *sline;
+      r1 += getr8 (scolor) << aa_BITS;
+      g1 += getg8 (scolor) << aa_BITS;
+      b1 += getb8 (scolor) << aa_BITS;
+    }
+
+  sx2f = _sx2 & aa_MASK;
+  if (sx2f != 0)
+    {
+      scolor = *sline;
+      r1 += MUL (getr8 (scolor), sx2f);
+      g1 += MUL (getg8 (scolor), sx2f);
+      b1 += MUL (getb8 (scolor), sx2f);
+    }
+
+  sy1f = aa_SIZE - (_sy1 & aa_MASK);
+  r1 = MUL (r1, sy1f);
+  g1 = MUL (g1, sy1f);
+  b1 = MUL (b1, sy1f);
+
+  /* Middle lines.  */
+  sy2i = _sy2 >> aa_BITS;
+  if (++sy < sy2i)
+    {
+      r2 = g2 = b2 = 0;
+      do
+	{
+	  sx = sx1i;
+	  sline = _src->line[sy] + sx;
+
+	  scolor = *sline;
+	  r2 += MUL (getr8 (scolor), sx1f);
+	  g2 += MUL (getg8 (scolor), sx1f);
+	  b2 += MUL (getb8 (scolor), sx1f);
+
+	  for (sline++, sx++; sx < sx2i; sline++, sx++)
+	    {
+	      scolor = *sline;
+	      r2 += getr8 (scolor) << aa_BITS;
+	      g2 += getg8 (scolor) << aa_BITS;
+	      b2 += getb8 (scolor) << aa_BITS;
+	    }
+
+	  if (sx2f != 0)
+	    {
+	      scolor = *sline;
+	      r2 += MUL (getr8 (scolor), sx2f);
+	      g2 += MUL (getg8 (scolor), sx2f);
+	      b2 += MUL (getb8 (scolor), sx2f);
+	    }
+	}
+      while (++sy < sy2i);
+
+      r1 += r2 << aa_BITS;
+      g1 += g2 << aa_BITS;
+      b1 += b2 << aa_BITS;
+    }
+
+  /* Last line.  */
+  sy2f = _sy2 & aa_MASK;
+  if (sy2f != 0)
+    {
+      sx = sx1i;
+      sline = _src->line[sy] + sx;
+
+      scolor = *sline;
+      r2 = MUL (getr8 (scolor), sx1f);
+      g2 = MUL (getg8 (scolor), sx1f);
+      b2 = MUL (getb8 (scolor), sx1f);
+
+      for (sline++, sx++; sx < sx2i; sline++, sx++)
+	{
+	  scolor = *sline;
+	  r2 += getr8 (scolor) << aa_BITS;
+	  g2 += getg8 (scolor) << aa_BITS;
+	  b2 += getb8 (scolor) << aa_BITS;
+	}
+
+      if (sx2f != 0)
+	{
+	  scolor = *sline;
+	  r2 += MUL (getr8 (scolor), sx2f);
+	  g2 += MUL (getg8 (scolor), sx2f);
+	  b2 += MUL (getb8 (scolor), sx2f);
+	}
+
+      r1 += MUL (r2, sy2f);
+      g1 += MUL (g2, sy2f);
+      b1 += MUL (b2, sy2f);
+    }
+
+  if (_num == (aa_SIZE * aa_SIZE))
+    {
+      _aa.r = r1 >> (2 * aa_BITS);
+      _aa.g = g1 >> (2 * aa_BITS);
+      _aa.b = b1 >> (2 * aa_BITS);
+    }
+  else
+    {
+      _aa.r = r1 / _num;
+      _aa.g = g1 / _num;
+      _aa.b = b1 / _num;
+    }
+}
+#ifdef ALLEGRO_COLOR16
+void
+_aa_add_rgb15 (BITMAP *_src, int _sx1, int _sx2, int _sy1, int _sy2, unsigned long _num)
+{
+  unsigned short *sline;
+  int sx, sx1i, sx1f, sx2i, sx2f;
+  int sy, sy1i, sy1f, sy2i, sy2f;
+  unsigned int r1, g1, b1;
+  unsigned int r2, g2, b2;
+  unsigned int scolor;
+
+  sy1i = _sy1 >> aa_BITS;
+  sy = sy1i;
+
+  /* First line.  */
+  sx1i = _sx1 >> aa_BITS;
+  sx = sx1i;
+  sline = (unsigned short*) (_src->line[sy]) + sx;
+
+  sx1f = aa_SIZE - (_sx1 & aa_MASK);
+  scolor = *sline;
+  r1 = MUL (getr15 (scolor), sx1f);
+  g1 = MUL (getg15 (scolor), sx1f);
+  b1 = MUL (getb15 (scolor), sx1f);
+
+  sx2i = _sx2 >> aa_BITS;
+  for (sline++, sx++; sx < sx2i; sline++, sx++)
+    {
+      scolor = *sline;
+      r1 += getr15 (scolor) << aa_BITS;
+      g1 += getg15 (scolor) << aa_BITS;
+      b1 += getb15 (scolor) << aa_BITS;
+    }
+
+  sx2f = _sx2 & aa_MASK;
+  if (sx2f != 0)
+    {
+      scolor = *sline;
+      r1 += MUL (getr15 (scolor), sx2f);
+      g1 += MUL (getg15 (scolor), sx2f);
+      b1 += MUL (getb15 (scolor), sx2f);
+    }
+
+  sy1f = aa_SIZE - (_sy1 & aa_MASK);
+  r1 = MUL (r1, sy1f);
+  g1 = MUL (g1, sy1f);
+  b1 = MUL (b1, sy1f);
+
+  /* Middle lines.  */
+  sy2i = _sy2 >> aa_BITS;
+  if (++sy < sy2i)
+    {
+      r2 = g2 = b2 = 0;
+      do
+	{
+	  sx = sx1i;
+	  sline = (unsigned short*) (_src->line[sy]) + sx;
+
+	  scolor = *sline;
+	  r2 += MUL (getr15 (scolor), sx1f);
+	  g2 += MUL (getg15 (scolor), sx1f);
+	  b2 += MUL (getb15 (scolor), sx1f);
+
+	  for (sline++, sx++; sx < sx2i; sline++, sx++)
+	    {
+	      scolor = *sline;
+	      r2 += getr15 (scolor) << aa_BITS;
+	      g2 += getg15 (scolor) << aa_BITS;
+	      b2 += getb15 (scolor) << aa_BITS;
+	    }
+
+	  if (sx2f != 0)
+	    {
+	      scolor = *sline;
+	      r2 += MUL (getr15 (scolor), sx2f);
+	      g2 += MUL (getg15 (scolor), sx2f);
+	      b2 += MUL (getb15 (scolor), sx2f);
+	    }
+	}
+      while (++sy < sy2i);
+
+      r1 += r2 << aa_BITS;
+      g1 += g2 << aa_BITS;
+      b1 += b2 << aa_BITS;
+    }
+
+  /* Last line.  */
+  sy2f = _sy2 & aa_MASK;
+  if (sy2f != 0)
+    {
+      sx = sx1i;
+      sline = (unsigned short*) (_src->line[sy]) + sx;
+
+      scolor = *sline;
+      r2 = MUL (getr15 (scolor), sx1f);
+      g2 = MUL (getg15 (scolor), sx1f);
+      b2 = MUL (getb15 (scolor), sx1f);
+
+      for (sline++, sx++; sx < sx2i; sline++, sx++)
+	{
+	  scolor = *sline;
+	  r2 += getr15 (scolor) << aa_BITS;
+	  g2 += getg15 (scolor) << aa_BITS;
+	  b2 += getb15 (scolor) << aa_BITS;
+	}
+
+      if (sx2f != 0)
+	{
+	  scolor = *sline;
+	  r2 += MUL (getr15 (scolor), sx2f);
+	  g2 += MUL (getg15 (scolor), sx2f);
+	  b2 += MUL (getb15 (scolor), sx2f);
+	}
+
+      r1 += MUL (r2, sy2f);
+      g1 += MUL (g2, sy2f);
+      b1 += MUL (b2, sy2f);
+    }
+
+  if (_num == (aa_SIZE * aa_SIZE))
+    {
+      _aa.r = r1 >> (2 * aa_BITS);
+      _aa.g = g1 >> (2 * aa_BITS);
+      _aa.b = b1 >> (2 * aa_BITS);
+    }
+  else
+    {
+      _aa.r = r1 / _num;
+      _aa.g = g1 / _num;
+      _aa.b = b1 / _num;
+    }
+}
+void
+_aa_add_rgb16 (BITMAP *_src, int _sx1, int _sx2, int _sy1, int _sy2, unsigned long _num)
+{
+  unsigned short *sline;
+  int sx, sx1i, sx1f, sx2i, sx2f;
+  int sy, sy1i, sy1f, sy2i, sy2f;
+  unsigned int r1, g1, b1;
+  unsigned int r2, g2, b2;
+  unsigned int scolor;
+
+  sy1i = _sy1 >> aa_BITS;
+  sy = sy1i;
+
+  /* First line.  */
+  sx1i = _sx1 >> aa_BITS;
+  sx = sx1i;
+  sline = (unsigned short*) (_src->line[sy]) + sx;
+
+  sx1f = aa_SIZE - (_sx1 & aa_MASK);
+  scolor = *sline;
+  r1 = MUL (getr16 (scolor), sx1f);
+  g1 = MUL (getg16 (scolor), sx1f);
+  b1 = MUL (getb16 (scolor), sx1f);
+
+  sx2i = _sx2 >> aa_BITS;
+  for (sline++, sx++; sx < sx2i; sline++, sx++)
+    {
+      scolor = *sline;
+      r1 += getr16 (scolor) << aa_BITS;
+      g1 += getg16 (scolor) << aa_BITS;
+      b1 += getb16 (scolor) << aa_BITS;
+    }
+
+  sx2f = _sx2 & aa_MASK;
+  if (sx2f != 0)
+    {
+      scolor = *sline;
+      r1 += MUL (getr16 (scolor), sx2f);
+      g1 += MUL (getg16 (scolor), sx2f);
+      b1 += MUL (getb16 (scolor), sx2f);
+    }
+
+  sy1f = aa_SIZE - (_sy1 & aa_MASK);
+  r1 = MUL (r1, sy1f);
+  g1 = MUL (g1, sy1f);
+  b1 = MUL (b1, sy1f);
+
+  /* Middle lines.  */
+  sy2i = _sy2 >> aa_BITS;
+  if (++sy < sy2i)
+    {
+      r2 = g2 = b2 = 0;
+      do
+	{
+	  sx = sx1i;
+	  sline = (unsigned short*) (_src->line[sy]) + sx;
+
+	  scolor = *sline;
+	  r2 += MUL (getr16 (scolor), sx1f);
+	  g2 += MUL (getg16 (scolor), sx1f);
+	  b2 += MUL (getb16 (scolor), sx1f);
+
+	  for (sline++, sx++; sx < sx2i; sline++, sx++)
+	    {
+	      scolor = *sline;
+	      r2 += getr16 (scolor) << aa_BITS;
+	      g2 += getg16 (scolor) << aa_BITS;
+	      b2 += getb16 (scolor) << aa_BITS;
+	    }
+
+	  if (sx2f != 0)
+	    {
+	      scolor = *sline;
+	      r2 += MUL (getr16 (scolor), sx2f);
+	      g2 += MUL (getg16 (scolor), sx2f);
+	      b2 += MUL (getb16 (scolor), sx2f);
+	    }
+	}
+      while (++sy < sy2i);
+
+      r1 += r2 << aa_BITS;
+      g1 += g2 << aa_BITS;
+      b1 += b2 << aa_BITS;
+    }
+
+  /* Last line.  */
+  sy2f = _sy2 & aa_MASK;
+  if (sy2f != 0)
+    {
+      sx = sx1i;
+      sline = (unsigned short*) (_src->line[sy]) + sx;
+
+      scolor = *sline;
+      r2 = MUL (getr16 (scolor), sx1f);
+      g2 = MUL (getg16 (scolor), sx1f);
+      b2 = MUL (getb16 (scolor), sx1f);
+
+      for (sline++, sx++; sx < sx2i; sline++, sx++)
+	{
+	  scolor = *sline;
+	  r2 += getr16 (scolor) << aa_BITS;
+	  g2 += getg16 (scolor) << aa_BITS;
+	  b2 += getb16 (scolor) << aa_BITS;
+	}
+
+      if (sx2f != 0)
+	{
+	  scolor = *sline;
+	  r2 += MUL (getr16 (scolor), sx2f);
+	  g2 += MUL (getg16 (scolor), sx2f);
+	  b2 += MUL (getb16 (scolor), sx2f);
+	}
+
+      r1 += MUL (r2, sy2f);
+      g1 += MUL (g2, sy2f);
+      b1 += MUL (b2, sy2f);
+    }
+
+  if (_num == (aa_SIZE * aa_SIZE))
+    {
+      _aa.r = r1 >> (2 * aa_BITS);
+      _aa.g = g1 >> (2 * aa_BITS);
+      _aa.b = b1 >> (2 * aa_BITS);
+    }
+  else
+    {
+      _aa.r = r1 / _num;
+      _aa.g = g1 / _num;
+      _aa.b = b1 / _num;
+    }
+}
+#endif
+#ifdef ALLEGRO_COLOR24
+void
+_aa_add_rgb24 (BITMAP *_src, int _sx1, int _sx2, int _sy1, int _sy2, unsigned long _num)
+{
+  unsigned char *sline;
+  int sx, sx1i, sx1f, sx2i, sx2f;
+  int sy, sy1i, sy1f, sy2i, sy2f;
+  unsigned int r1, g1, b1;
+  unsigned int r2, g2, b2;
+
+  sy1i = _sy1 >> aa_BITS;
+  sy = sy1i;
+
+  /* First line.  */
+  sx1i = _sx1 >> aa_BITS;
+  sx = sx1i;
+  sline = _src->line[sy] + sx * 3;
+
+  sx1f = aa_SIZE - (_sx1 & aa_MASK);
+  r1 = MUL (sline[_aa.roffset24], sx1f);
+  g1 = MUL (sline[_aa.goffset24], sx1f);
+  b1 = MUL (sline[_aa.boffset24], sx1f);
+
+  sx2i = _sx2 >> aa_BITS;
+  for (sline += 3, sx++; sx < sx2i; sline += 3, sx++)
+    {
+      r1 += sline[_aa.roffset24] << aa_BITS;
+      g1 += sline[_aa.goffset24] << aa_BITS;
+      b1 += sline[_aa.boffset24] << aa_BITS;
+    }
+
+  sx2f = _sx2 & aa_MASK;
+  if (sx2f != 0)
+    {
+      r1 += MUL (sline[_aa.roffset24], sx2f);
+      g1 += MUL (sline[_aa.goffset24], sx2f);
+      b1 += MUL (sline[_aa.boffset24], sx2f);
+    }
+
+  sy1f = aa_SIZE - (_sy1 & aa_MASK);
+  r1 = MUL (r1, sy1f);
+  g1 = MUL (g1, sy1f);
+  b1 = MUL (b1, sy1f);
+
+  /* Middle lines.  */
+  sy2i = _sy2 >> aa_BITS;
+  if (++sy < sy2i)
+    {
+      r2 = g2 = b2 = 0;
+      do
+	{
+	  sx = sx1i;
+	  sline = _src->line[sy] + sx * 3;
+
+	  r2 += MUL (sline[_aa.roffset24], sx1f);
+	  g2 += MUL (sline[_aa.goffset24], sx1f);
+	  b2 += MUL (sline[_aa.boffset24], sx1f);
+
+	  for (sline += 3, sx++; sx < sx2i; sline += 3, sx++)
+	    {
+	      r2 += sline[_aa.roffset24] << aa_BITS;
+	      g2 += sline[_aa.goffset24] << aa_BITS;
+	      b2 += sline[_aa.boffset24] << aa_BITS;
+	    }
+
+	  if (sx2f != 0)
+	    {
+	      r2 += MUL (sline[_aa.roffset24], sx2f);
+	      g2 += MUL (sline[_aa.goffset24], sx2f);
+	      b2 += MUL (sline[_aa.boffset24], sx2f);
+	    }
+	}
+      while (++sy < sy2i);
+
+      r1 += r2 << aa_BITS;
+      g1 += g2 << aa_BITS;
+      b1 += b2 << aa_BITS;
+    }
+
+  /* Last line.  */
+  sy2f = _sy2 & aa_MASK;
+  if (sy2f != 0)
+    {
+      sx = sx1i;
+      sline = _src->line[sy] + sx * 3;
+
+      r2 = MUL (sline[_aa.roffset24], sx1f);
+      g2 = MUL (sline[_aa.goffset24], sx1f);
+      b2 = MUL (sline[_aa.boffset24], sx1f);
+
+      for (sline += 3, sx++; sx < sx2i; sline += 3, sx++)
+	{
+	  r2 += sline[_aa.roffset24] << aa_BITS;
+	  g2 += sline[_aa.goffset24] << aa_BITS;
+	  b2 += sline[_aa.boffset24] << aa_BITS;
+	}
+
+      if (sx2f != 0)
+	{
+	  r2 += MUL (sline[_aa.roffset24], sx2f);
+	  g2 += MUL (sline[_aa.goffset24], sx2f);
+	  b2 += MUL (sline[_aa.boffset24], sx2f);
+	}
+
+      r1 += MUL (r2, sy2f);
+      g1 += MUL (g2, sy2f);
+      b1 += MUL (b2, sy2f);
+    }
+
+  if (_num == (aa_SIZE * aa_SIZE))
+    {
+      _aa.r = r1 >> (2 * aa_BITS);
+      _aa.g = g1 >> (2 * aa_BITS);
+      _aa.b = b1 >> (2 * aa_BITS);
+    }
+  else
+    {
+      _aa.r = r1 / _num;
+      _aa.g = g1 / _num;
+      _aa.b = b1 / _num;
+    }
+}
+#endif
+#ifdef ALLEGRO_COLOR32
+void
+_aa_add_rgb32 (BITMAP *_src, int _sx1, int _sx2, int _sy1, int _sy2, unsigned long _num)
+{
+  unsigned int *sline;
+  int sx, sx1i, sx1f, sx2i, sx2f;
+  int sy, sy1i, sy1f, sy2i, sy2f;
+  unsigned int r1, g1, b1;
+  unsigned int r2, g2, b2;
+  unsigned int scolor;
+
+  sy1i = _sy1 >> aa_BITS;
+  sy = sy1i;
+
+  /* First line.  */
+  sx1i = _sx1 >> aa_BITS;
+  sx = sx1i;
+  sline = (unsigned int*) (_src->line[sy]) + sx;
+
+  sx1f = aa_SIZE - (_sx1 & aa_MASK);
+  scolor = *sline;
+  r1 = MUL (getr32 (scolor), sx1f);
+  g1 = MUL (getg32 (scolor), sx1f);
+  b1 = MUL (getb32 (scolor), sx1f);
+
+  sx2i = _sx2 >> aa_BITS;
+  for (sline++, sx++; sx < sx2i; sline++, sx++)
+    {
+      scolor = *sline;
+      r1 += getr32 (scolor) << aa_BITS;
+      g1 += getg32 (scolor) << aa_BITS;
+      b1 += getb32 (scolor) << aa_BITS;
+    }
+
+  sx2f = _sx2 & aa_MASK;
+  if (sx2f != 0)
+    {
+      scolor = *sline;
+      r1 += MUL (getr32 (scolor), sx2f);
+      g1 += MUL (getg32 (scolor), sx2f);
+      b1 += MUL (getb32 (scolor), sx2f);
+    }
+
+  sy1f = aa_SIZE - (_sy1 & aa_MASK);
+  r1 = MUL (r1, sy1f);
+  g1 = MUL (g1, sy1f);
+  b1 = MUL (b1, sy1f);
+
+  /* Middle lines.  */
+  sy2i = _sy2 >> aa_BITS;
+  if (++sy < sy2i)
+    {
+      r2 = g2 = b2 = 0;
+      do
+	{
+	  sx = sx1i;
+	  sline = (unsigned int*) (_src->line[sy]) + sx;
+
+	  scolor = *sline;
+	  r2 += MUL (getr32 (scolor), sx1f);
+	  g2 += MUL (getg32 (scolor), sx1f);
+	  b2 += MUL (getb32 (scolor), sx1f);
+
+	  for (sline++, sx++; sx < sx2i; sline++, sx++)
+	    {
+	      scolor = *sline;
+	      r2 += getr32 (scolor) << aa_BITS;
+	      g2 += getg32 (scolor) << aa_BITS;
+	      b2 += getb32 (scolor) << aa_BITS;
+	    }
+
+	  if (sx2f != 0)
+	    {
+	      scolor = *sline;
+	      r2 += MUL (getr32 (scolor), sx2f);
+	      g2 += MUL (getg32 (scolor), sx2f);
+	      b2 += MUL (getb32 (scolor), sx2f);
+	    }
+	}
+      while (++sy < sy2i);
+
+      r1 += r2 << aa_BITS;
+      g1 += g2 << aa_BITS;
+      b1 += b2 << aa_BITS;
+    }
+
+  /* Last line.  */
+  sy2f = _sy2 & aa_MASK;
+  if (sy2f != 0)
+    {
+      sx = sx1i;
+      sline = (unsigned int*) (_src->line[sy]) + sx;
+
+      scolor = *sline;
+      r2 = MUL (getr32 (scolor), sx1f);
+      g2 = MUL (getg32 (scolor), sx1f);
+      b2 = MUL (getb32 (scolor), sx1f);
+
+      for (sline++, sx++; sx < sx2i; sline++, sx++)
+	{
+	  scolor = *sline;
+	  r2 += getr32 (scolor) << aa_BITS;
+	  g2 += getg32 (scolor) << aa_BITS;
+	  b2 += getb32 (scolor) << aa_BITS;
+	}
+
+      if (sx2f != 0)
+	{
+	  scolor = *sline;
+	  r2 += MUL (getr32 (scolor), sx2f);
+	  g2 += MUL (getg32 (scolor), sx2f);
+	  b2 += MUL (getb32 (scolor), sx2f);
+	}
+
+      r1 += MUL (r2, sy2f);
+      g1 += MUL (g2, sy2f);
+      b1 += MUL (b2, sy2f);
+    }
+
+  if (_num == (aa_SIZE * aa_SIZE))
+    {
+      _aa.r = r1 >> (2 * aa_BITS);
+      _aa.g = g1 >> (2 * aa_BITS);
+      _aa.b = b1 >> (2 * aa_BITS);
+    }
+  else
+    {
+      _aa.r = r1 / _num;
+      _aa.g = g1 / _num;
+      _aa.b = b1 / _num;
+    }
+}
+#endif
+
+/*
+ * Putting pixel to destination bitmap.
+ */
+void
+_aa_put_rgb8 (unsigned long _addr, int _x)
+{
+  bmp_write8 (_addr + _x, makecol8 (_aa.r, _aa.g, _aa.b));
+}
+#ifdef ALLEGRO_COLOR16
+void
+_aa_put_rgb15 (unsigned long _addr, int _x)
+{
+  bmp_write15 (_addr + sizeof (short) * _x, makecol15 (_aa.r, _aa.g, _aa.b));
+}
+void
+_aa_put_rgb16 (unsigned long _addr, int _x)
+{
+  bmp_write16 (_addr + sizeof (short) * _x, makecol16 (_aa.r, _aa.g, _aa.b));
+}
+#endif
+#ifdef ALLEGRO_COLOR24
+void
+_aa_put_rgb24 (unsigned long _addr, int _x)
+{
+  bmp_write24 (_addr + 3 * _x, makecol24 (_aa.r, _aa.g, _aa.g));
+}
+#endif
+#ifdef ALLEGRO_COLOR32
+void
+_aa_put_rgb32 (unsigned long _addr, int _x)
+{
+  bmp_write32 (_addr + sizeof (int) * _x, makecol32 (_aa.r, _aa.g, _aa.b));
+}
+#endif
+
+/*
+ * Add masked r, g, b values of pixels.
+ */
+void
+_aa_masked_add_rgb8 (BITMAP *_src, int _sx1, int _sx2, int _sy1, int _sy2, unsigned long _num)
+{
+  unsigned char *sline;
+  int sx, sx1i, sx1f, sx2i, sx2f;
+  int sy, sy1i, sy1f, sy2i, sy2f;
+  unsigned long r1, g1, b1, t1;
+  unsigned long r2, g2, b2, t2;
+  unsigned long scolor;
+
+  sy1i = _sy1 >> aa_BITS;
+  sy = sy1i;
+
+  /* First line.  */
+  sx1i = _sx1 >> aa_BITS;
+  sx = sx1i;
+  sline = _src->line[sy] + sx;
+
+  sx1f = aa_SIZE - (_sx1 & aa_MASK);
+  scolor = *sline;
+  if (scolor != MASK_COLOR_8)
+    {
+      r1 = MUL (getr8 (scolor), sx1f);
+      g1 = MUL (getg8 (scolor), sx1f);
+      b1 = MUL (getb8 (scolor), sx1f);
+      t1 = 0;
+    }
+  else
+    {
+      r1 = g1 = b1 = 0;
+      t1 = sx1f;
+    }
+
+  sx2i = _sx2 >> aa_BITS;
+  for (sline++, sx++; sx < sx2i; sline++, sx++)
+    {
+      scolor = *sline;
+      if (scolor != MASK_COLOR_8)
+	{
+	  r1 += getr8 (scolor) << aa_BITS;
+	  g1 += getg8 (scolor) << aa_BITS;
+	  b1 += getb8 (scolor) << aa_BITS;
+	}
+      else
+	t1 += aa_SIZE;
+    }
+
+  sx2f = _sx2 & aa_MASK;
+  if (sx2f != 0)
+    {
+      scolor = *sline;
+      if (scolor != MASK_COLOR_8)
+	{
+	  r1 += MUL (getr8 (scolor), sx2f);
+	  g1 += MUL (getg8 (scolor), sx2f);
+	  b1 += MUL (getb8 (scolor), sx2f);
+	}
+      else
+	t1 += sx2f;
+    }
+
+  sy1f = aa_SIZE - (_sy1 & aa_MASK);
+  r1 = MUL (r1, sy1f);
+  g1 = MUL (g1, sy1f);
+  b1 = MUL (b1, sy1f);
+  t1 = MUL (t1, sy1f);
+
+  /* Middle lines.  */
+  sy2i = _sy2 >> aa_BITS;
+  if (++sy < sy2i)
+    {
+      r2 = g2 = b2 = t2 = 0;
+      do
+	{
+	  sx = sx1i;
+	  sline = _src->line[sy] + sx;
+
+	  scolor = *sline;
+	  if (scolor != MASK_COLOR_8)
+	    {
+	      r2 += MUL (getr8 (scolor), sx1f);
+	      g2 += MUL (getg8 (scolor), sx1f);
+	      b2 += MUL (getb8 (scolor), sx1f);
+	    }
+	  else
+	    t2 += sx1f;
+
+	  for (sline++, sx++; sx < sx2i; sline++, sx++)
+	    {
+	      scolor = *sline;
+	      if (scolor != MASK_COLOR_8)
+		{
+		  r2 += getr8 (scolor) << aa_BITS;
+		  g2 += getg8 (scolor) << aa_BITS;
+		  b2 += getb8 (scolor) << aa_BITS;
+		}
+	      else
+		t2 += aa_SIZE;
+	    }
+
+	  if (sx2f != 0)
+	    {
+	      scolor = *sline;
+	      if (scolor != MASK_COLOR_8)
+		{
+		  r2 += MUL (getr8 (scolor), sx2f);
+		  g2 += MUL (getg8 (scolor), sx2f);
+		  b2 += MUL (getb8 (scolor), sx2f);
+		}
+	      else
+		t2 += sx2f;
+	    }
+	}
+      while (++sy < sy2i);
+
+      r1 += r2 << aa_BITS;
+      g1 += g2 << aa_BITS;
+      b1 += b2 << aa_BITS;
+      t1 += t2 << aa_BITS;
+    }
+
+  /* Last line.  */
+  sy2f = _sy2 & aa_MASK;
+  if (sy2f != 0)
+    {
+      sx = sx1i;
+      sline = _src->line[sy] + sx;
+
+      scolor = *sline;
+      if (scolor != MASK_COLOR_8)
+	{
+	  r2 = MUL (getr8 (scolor), sx1f);
+	  g2 = MUL (getg8 (scolor), sx1f);
+	  b2 = MUL (getb8 (scolor), sx1f);
+	  t2 = 0;
+	}
+      else
+	{
+	  r2 = g2 = b2 = 0;
+	  t2 = sx1f;
+	}
+
+      for (sline++, sx++; sx < sx2i; sline++, sx++)
+	{
+	  scolor = *sline;
+	  if (scolor != MASK_COLOR_8)
+	    {
+	      r2 += getr8 (scolor) << aa_BITS;
+	      g2 += getg8 (scolor) << aa_BITS;
+	      b2 += getb8 (scolor) << aa_BITS;
+	    }
+	  else
+	    t2 += aa_SIZE;
+	}
+
+      if (sx2f != 0)
+	{
+	  scolor = *sline;
+	  if (scolor != MASK_COLOR_8)
+	    {
+	      r2 += MUL (getr8 (scolor), sx2f);
+	      g2 += MUL (getg8 (scolor), sx2f);
+	      b2 += MUL (getb8 (scolor), sx2f);
+	    }
+	  else
+	    t2 += sx2f;
+	}
+
+      r1 += MUL (r2, sy2f);
+      g1 += MUL (g2, sy2f);
+      b1 += MUL (b2, sy2f);
+      t1 += MUL (t2, sy2f);
+    }
+
+  if (_num >= (2 * t1))
+    {
+      if (_num == (aa_SIZE * aa_SIZE))
+	{
+	  _aa.r = r1 >> (2 * aa_BITS);
+	  _aa.g = g1 >> (2 * aa_BITS);
+	  _aa.b = b1 >> (2 * aa_BITS);
+	}
+      else
+	{
+	  _aa.r = r1 / _num;
+	  _aa.g = g1 / _num;
+	  _aa.b = b1 / _num;
+	}
+      _aa.transparent = 0;
+    }
+  else
+    _aa.transparent = 1;
+}
+#ifdef ALLEGRO_COLOR16
+void
+_aa_masked_add_rgb15 (BITMAP *_src, int _sx1, int _sx2, int _sy1, int _sy2, unsigned long _num)
+{
+  unsigned short *sline;
+  int sx, sx1i, sx1f, sx2i, sx2f;
+  int sy, sy1i, sy1f, sy2i, sy2f;
+  unsigned int r1, g1, b1, t1;
+  unsigned int r2, g2, b2, t2;
+  unsigned int scolor;
+
+  sy1i = _sy1 >> aa_BITS;
+  sy = sy1i;
+
+  /* First line.  */
+  sx1i = _sx1 >> aa_BITS;
+  sx = sx1i;
+  sline = (unsigned short*) (_src->line[sy]) + sx;
+
+  sx1f = aa_SIZE - (_sx1 & aa_MASK);
+  scolor = *sline;
+  if (scolor != MASK_COLOR_15)
+    {
+      r1 = MUL (getr15 (scolor), sx1f);
+      g1 = MUL (getg15 (scolor), sx1f);
+      b1 = MUL (getb15 (scolor), sx1f);
+      t1 = 0;
+    }
+  else
+    {
+      r1 = g1 = b1 = 0;
+      t1 = sx1f;
+    }
+
+  sx2i = _sx2 >> aa_BITS;
+  for (sline++, sx++; sx < sx2i; sline++, sx++)
+    {
+      scolor = *sline;
+      if (scolor != MASK_COLOR_15)
+	{
+	  r1 += getr15 (scolor) << aa_BITS;
+	  g1 += getg15 (scolor) << aa_BITS;
+	  b1 += getb15 (scolor) << aa_BITS;
+	}
+      else
+	t1 += aa_SIZE;
+    }
+
+  sx2f = _sx2 & aa_MASK;
+  if (sx2f != 0)
+    {
+      scolor = *sline;
+      if (scolor != MASK_COLOR_15)
+	{
+	  r1 += MUL (getr15 (scolor), sx2f);
+	  g1 += MUL (getg15 (scolor), sx2f);
+	  b1 += MUL (getb15 (scolor), sx2f);
+	}
+      else
+	t1 += sx2f;
+    }
+
+  sy1f = aa_SIZE - (_sy1 & aa_MASK);
+  r1 = MUL (r1, sy1f);
+  g1 = MUL (g1, sy1f);
+  b1 = MUL (b1, sy1f);
+  t1 = MUL (t1, sy1f);
+
+  /* Middle lines.  */
+  sy2i = _sy2 >> aa_BITS;
+  if (++sy < sy2i)
+    {
+      r2 = g2 = b2 = t2 = 0;
+      do
+	{
+	  sx = sx1i;
+	  sline = (unsigned short*) (_src->line[sy]) + sx;
+
+	  scolor = *sline;
+	  if (scolor != MASK_COLOR_15)
+	    {
+	      r2 += MUL (getr15 (scolor), sx1f);
+	      g2 += MUL (getg15 (scolor), sx1f);
+	      b2 += MUL (getb15 (scolor), sx1f);
+	    }
+	  else
+	    t2 += sx1f;
+
+	  for (sline++, sx++; sx < sx2i; sline++, sx++)
+	    {
+	      scolor = *sline;
+	      if (scolor != MASK_COLOR_15)
+		{
+		  r2 += getr15 (scolor) << aa_BITS;
+		  g2 += getg15 (scolor) << aa_BITS;
+		  b2 += getb15 (scolor) << aa_BITS;
+		}
+	      else
+		t2 += aa_SIZE;
+	    }
+
+	  if (sx2f != 0)
+	    {
+	      scolor = *sline;
+	      if (scolor != MASK_COLOR_15)
+		{
+		  r2 += MUL (getr15 (scolor), sx2f);
+		  g2 += MUL (getg15 (scolor), sx2f);
+		  b2 += MUL (getb15 (scolor), sx2f);
+		}
+	      else
+		t2 += sx2f;
+	    }
+	}
+      while (++sy < sy2i);
+
+      r1 += r2 << aa_BITS;
+      g1 += g2 << aa_BITS;
+      b1 += b2 << aa_BITS;
+      t1 += t2 << aa_BITS;
+    }
+
+  /* Last line.  */
+  sy2f = _sy2 & aa_MASK;
+  if (sy2f != 0)
+    {
+      sx = sx1i;
+      sline = (unsigned short*) (_src->line[sy]) + sx;
+
+      scolor = *sline;
+      if (scolor != MASK_COLOR_15)
+	{
+	  r2 = MUL (getr15 (scolor), sx1f);
+	  g2 = MUL (getg15 (scolor), sx1f);
+	  b2 = MUL (getb15 (scolor), sx1f);
+	  t2 = 0;
+	}
+      else
+	{
+	  r2 = g2 = b2 = 0;
+	  t2 = sx1f;
+	}
+
+      for (sline++, sx++; sx < sx2i; sline++, sx++)
+	{
+	  scolor = *sline;
+	  if (scolor != MASK_COLOR_15)
+	    {
+	      r2 += getr15 (scolor) << aa_BITS;
+	      g2 += getg15 (scolor) << aa_BITS;
+	      b2 += getb15 (scolor) << aa_BITS;
+	    }
+	  else
+	    t2 += aa_SIZE;
+	}
+
+      if (sx2f != 0)
+	{
+	  scolor = *sline;
+	  if (scolor != MASK_COLOR_15)
+	    {
+	      r2 += MUL (getr15 (scolor), sx2f);
+	      g2 += MUL (getg15 (scolor), sx2f);
+	      b2 += MUL (getb15 (scolor), sx2f);
+	    }
+	  else
+	    t2 += sx2f;
+	}
+
+      r1 += MUL (r2, sy2f);
+      g1 += MUL (g2, sy2f);
+      b1 += MUL (b2, sy2f);
+      t1 += MUL (t2, sy2f);
+    }
+
+  if (_num >= (2 * t1))
+    {
+      if (_num == (aa_SIZE * aa_SIZE))
+	{
+	  _aa.r = r1 >> (2 * aa_BITS);
+	  _aa.g = g1 >> (2 * aa_BITS);
+	  _aa.b = b1 >> (2 * aa_BITS);
+	}
+      else
+	{
+	  _aa.r = r1 / _num;
+	  _aa.g = g1 / _num;
+	  _aa.b = b1 / _num;
+	}
+      _aa.transparent = 0;
+    }
+  else
+    _aa.transparent = 1;
+}
+void
+_aa_masked_add_rgb16 (BITMAP *_src, int _sx1, int _sx2, int _sy1, int _sy2, unsigned long _num)
+{
+  unsigned short *sline;
+  int sx, sx1i, sx1f, sx2i, sx2f;
+  int sy, sy1i, sy1f, sy2i, sy2f;
+  unsigned int r1, g1, b1, t1;
+  unsigned int r2, g2, b2, t2;
+  unsigned int scolor;
+
+  sy1i = _sy1 >> aa_BITS;
+  sy = sy1i;
+
+  /* First line.  */
+  sx1i = _sx1 >> aa_BITS;
+  sx = sx1i;
+  sline = (unsigned short*) (_src->line[sy]) + sx;
+
+  sx1f = aa_SIZE - (_sx1 & aa_MASK);
+  scolor = *sline;
+  if (scolor != MASK_COLOR_16)
+    {
+      r1 = MUL (getr16 (scolor), sx1f);
+      g1 = MUL (getg16 (scolor), sx1f);
+      b1 = MUL (getb16 (scolor), sx1f);
+      t1 = 0;
+    }
+  else
+    {
+      r1 = g1 = b1 = 0;
+      t1 = sx1f;
+    }
+
+  sx2i = _sx2 >> aa_BITS;
+  for (sline++, sx++; sx < sx2i; sline++, sx++)
+    {
+      scolor = *sline;
+      if (scolor != MASK_COLOR_16)
+	{
+	  r1 += getr16 (scolor) << aa_BITS;
+	  g1 += getg16 (scolor) << aa_BITS;
+	  b1 += getb16 (scolor) << aa_BITS;
+	}
+      else
+	t1 += aa_SIZE;
+    }
+
+  sx2f = _sx2 & aa_MASK;
+  if (sx2f != 0)
+    {
+      scolor = *sline;
+      if (scolor != MASK_COLOR_16)
+	{
+	  r1 += MUL (getr16 (scolor), sx2f);
+	  g1 += MUL (getg16 (scolor), sx2f);
+	  b1 += MUL (getb16 (scolor), sx2f);
+	}
+      else
+	t1 += sx2f;
+    }
+
+  sy1f = aa_SIZE - (_sy1 & aa_MASK);
+  r1 = MUL (r1, sy1f);
+  g1 = MUL (g1, sy1f);
+  b1 = MUL (b1, sy1f);
+  t1 = MUL (t1, sy1f);
+
+  /* Middle lines.  */
+  sy2i = _sy2 >> aa_BITS;
+  if (++sy < sy2i)
+    {
+      r2 = g2 = b2 = t2 = 0;
+      do
+	{
+	  sx = sx1i;
+	  sline = (unsigned short*) (_src->line[sy]) + sx;
+
+	  scolor = *sline;
+	  if (scolor != MASK_COLOR_16)
+	    {
+	      r2 += MUL (getr16 (scolor), sx1f);
+	      g2 += MUL (getg16 (scolor), sx1f);
+	      b2 += MUL (getb16 (scolor), sx1f);
+	    }
+	  else
+	    t2 += sx1f;
+
+	  for (sline++, sx++; sx < sx2i; sline++, sx++)
+	    {
+	      scolor = *sline;
+	      if (scolor != MASK_COLOR_16)
+		{
+		  r2 += getr16 (scolor) << aa_BITS;
+		  g2 += getg16 (scolor) << aa_BITS;
+		  b2 += getb16 (scolor) << aa_BITS;
+		}
+	      else
+		t2 += aa_SIZE;
+	    }
+
+	  if (sx2f != 0)
+	    {
+	      scolor = *sline;
+	      if (scolor != MASK_COLOR_16)
+		{
+		  r2 += MUL (getr16 (scolor), sx2f);
+		  g2 += MUL (getg16 (scolor), sx2f);
+		  b2 += MUL (getb16 (scolor), sx2f);
+		}
+	      else
+		t2 += sx2f;
+	    }
+	}
+      while (++sy < sy2i);
+
+      r1 += r2 << aa_BITS;
+      g1 += g2 << aa_BITS;
+      b1 += b2 << aa_BITS;
+      t1 += t2 << aa_BITS;
+    }
+
+  /* Last line.  */
+  sy2f = _sy2 & aa_MASK;
+  if (sy2f != 0)
+    {
+      sx = sx1i;
+      sline = (unsigned short*) (_src->line[sy]) + sx;
+
+      scolor = *sline;
+      if (scolor != MASK_COLOR_16)
+	{
+	  r2 = MUL (getr16 (scolor), sx1f);
+	  g2 = MUL (getg16 (scolor), sx1f);
+	  b2 = MUL (getb16 (scolor), sx1f);
+	  t2 = 0;
+	}
+      else
+	{
+	  r2 = g2 = b2 = 0;
+	  t2 = sx1f;
+	}
+
+      for (sline++, sx++; sx < sx2i; sline++, sx++)
+	{
+	  scolor = *sline;
+	  if (scolor != MASK_COLOR_16)
+	    {
+	      r2 += getr16 (scolor) << aa_BITS;
+	      g2 += getg16 (scolor) << aa_BITS;
+	      b2 += getb16 (scolor) << aa_BITS;
+	    }
+	  else
+	    t2 += aa_SIZE;
+	}
+
+      if (sx2f != 0)
+	{
+	  scolor = *sline;
+	  if (scolor != MASK_COLOR_16)
+	    {
+	      r2 += MUL (getr16 (scolor), sx2f);
+	      g2 += MUL (getg16 (scolor), sx2f);
+	      b2 += MUL (getb16 (scolor), sx2f);
+	    }
+	  else
+	    t2 += sx2f;
+	}
+
+      r1 += MUL (r2, sy2f);
+      g1 += MUL (g2, sy2f);
+      b1 += MUL (b2, sy2f);
+      t1 += MUL (t2, sy2f);
+    }
+
+  if (_num >= (2 * t1))
+    {
+      if (_num == (aa_SIZE * aa_SIZE))
+	{
+	  _aa.r = r1 >> (2 * aa_BITS);
+	  _aa.g = g1 >> (2 * aa_BITS);
+	  _aa.b = b1 >> (2 * aa_BITS);
+	}
+      else
+	{
+	  _aa.r = r1 / _num;
+	  _aa.g = g1 / _num;
+	  _aa.b = b1 / _num;
+	}
+      _aa.transparent = 0;
+    }
+  else
+    _aa.transparent = 1;
+}
+#endif
+#ifdef ALLEGRO_COLOR24
+void
+_aa_masked_add_rgb24 (BITMAP *_src, int _sx1, int _sx2, int _sy1, int _sy2, unsigned long _num)
+{
+  unsigned char *sline;
+  int sx, sx1i, sx1f, sx2i, sx2f;
+  int sy, sy1i, sy1f, sy2i, sy2f;
+  unsigned int r1, g1, b1, t1;
+  unsigned int r2, g2, b2, t2;
+  unsigned int scolor;
+
+  sy1i = _sy1 >> aa_BITS;
+  sy = sy1i;
+
+  /* First line.  */
+  sx1i = _sx1 >> aa_BITS;
+  sx = sx1i;
+  sline = _src->line[sy] + sx * 3;
+
+  sx1f = aa_SIZE - (_sx1 & aa_MASK);
+#ifdef USE_24BIT_AS_CHARS
+  scolor = ((unsigned int) (sline[0])
+	    | ((unsigned int) (sline[1]) << 8)
+	    | ((unsigned int) (sline[2]) << 16));
+#else
+  scolor = ((unsigned int) (((unsigned short*) sline)[0])
+	    | ((unsigned int) (sline[2]) << 16));
+#endif
+  if (scolor != MASK_COLOR_24)
+    {
+      r1 = MUL (getr24 (scolor), sx1f);
+      g1 = MUL (getg24 (scolor), sx1f);
+      b1 = MUL (getb24 (scolor), sx1f);
+      t1 = 0;
+    }
+  else
+    {
+      r1 = g1 = b1 = 0;
+      t1 = sx1f;
+    }
+
+  sx2i = _sx2 >> aa_BITS;
+  for (sline += 3, sx++; sx < sx2i; sline += 3, sx++)
+    {
+#ifdef USE_24BIT_AS_CHARS
+      scolor = ((unsigned int) (sline[0])
+		| ((unsigned int) (sline[1]) << 8)
+		| ((unsigned int) (sline[2]) << 16));
+#else
+      scolor = ((unsigned int) (((unsigned short*) sline)[0])
+		| ((unsigned int) (sline[2]) << 16));
+#endif
+      if (scolor != MASK_COLOR_24)
+	{
+	  r1 += getr24 (scolor) << aa_BITS;
+	  g1 += getg24 (scolor) << aa_BITS;
+	  b1 += getb24 (scolor) << aa_BITS;
+	}
+      else
+	t1 += aa_SIZE;
+    }
+
+  sx2f = _sx2 & aa_MASK;
+  if (sx2f != 0)
+    {
+#ifdef USE_24BIT_AS_CHARS
+      scolor = ((unsigned int) (sline[0])
+		| ((unsigned int) (sline[1]) << 8)
+		| ((unsigned int) (sline[2]) << 16));
+#else
+      scolor = ((unsigned int) (((unsigned short*) sline)[0])
+		| ((unsigned int) (sline[2]) << 16));
+#endif
+      if (scolor != MASK_COLOR_24)
+	{
+	  r1 += MUL (getr24 (scolor), sx2f);
+	  g1 += MUL (getg24 (scolor), sx2f);
+	  b1 += MUL (getb24 (scolor), sx2f);
+	}
+      else
+	t1 += sx2f;
+    }
+
+  sy1f = aa_SIZE - (_sy1 & aa_MASK);
+  r1 = MUL (r1, sy1f);
+  g1 = MUL (g1, sy1f);
+  b1 = MUL (b1, sy1f);
+  t1 = MUL (t1, sy1f);
+
+  /* Middle lines.  */
+  sy2i = _sy2 >> aa_BITS;
+  if (++sy < sy2i)
+    {
+      r2 = g2 = b2 = t2 = 0;
+      do
+	{
+	  sx = sx1i;
+	  sline = _src->line[sy] + sx * 3;
+
+#ifdef USE_24BIT_AS_CHARS
+	  scolor = ((unsigned int) (sline[0])
+		    | ((unsigned int) (sline[1]) << 8)
+		    | ((unsigned int) (sline[2]) << 16));
+#else
+	  scolor = ((unsigned int) (((unsigned short*) sline)[0])
+		    | ((unsigned int) (sline[2]) << 16));
+#endif
+	  if (scolor != MASK_COLOR_24)
+	    {
+	      r2 += MUL (getr24 (scolor), sx1f);
+	      g2 += MUL (getg24 (scolor), sx1f);
+	      b2 += MUL (getb24 (scolor), sx1f);
+	    }
+	  else
+	    t2 += sx1f;
+
+	  for (sline += 3, sx++; sx < sx2i; sline += 3, sx++)
+	    {
+#ifdef USE_24BIT_AS_CHARS
+	      scolor = ((unsigned int) (sline[0])
+			| ((unsigned int) (sline[1]) << 8)
+			| ((unsigned int) (sline[2]) << 16));
+#else
+	      scolor = ((unsigned int) (((unsigned short*) sline)[0])
+			| ((unsigned int) (sline[2]) << 16));
+#endif
+	      if (scolor != MASK_COLOR_24)
+		{
+		  r2 += getr24 (scolor) << aa_BITS;
+		  g2 += getg24 (scolor) << aa_BITS;
+		  b2 += getb24 (scolor) << aa_BITS;
+		}
+	      else
+		t2 += aa_SIZE;
+	    }
+
+	  if (sx2f != 0)
+	    {
+#ifdef USE_24BIT_AS_CHARS
+	      scolor = ((unsigned int) (sline[0])
+			| ((unsigned int) (sline[1]) << 8)
+			| ((unsigned int) (sline[2]) << 16));
+#else
+	      scolor = ((unsigned int) (((unsigned short*) sline)[0])
+			| ((unsigned int) (sline[2]) << 16));
+#endif
+	      if (scolor != MASK_COLOR_24)
+		{
+		  r2 += MUL (getr24 (scolor), sx2f);
+		  g2 += MUL (getg24 (scolor), sx2f);
+		  b2 += MUL (getb24 (scolor), sx2f);
+		}
+	      else
+		t2 += sx2f;
+	    }
+	}
+      while (++sy < sy2i);
+
+      r1 += r2 << aa_BITS;
+      g1 += g2 << aa_BITS;
+      b1 += b2 << aa_BITS;
+      t1 += t2 << aa_BITS;
+    }
+
+  /* Last line.  */
+  sy2f = _sy2 & aa_MASK;
+  if (sy2f != 0)
+    {
+      sx = sx1i;
+      sline = _src->line[sy] + sx * 3;
+
+#ifdef USE_24BIT_AS_CHARS
+      scolor = ((unsigned int) (sline[0])
+		| ((unsigned int) (sline[1]) << 8)
+		| ((unsigned int) (sline[2]) << 16));
+#else
+      scolor = ((unsigned int) (((unsigned short*) sline)[0])
+		| ((unsigned int) (sline[2]) << 16));
+#endif
+      if (scolor != MASK_COLOR_24)
+	{
+	  r2 = MUL (getr24 (scolor), sx1f);
+	  g2 = MUL (getg24 (scolor), sx1f);
+	  b2 = MUL (getb24 (scolor), sx1f);
+	  t2 = 0;
+	}
+      else
+	{
+	  r2 = g2 = b2 = 0;
+	  t2 = sx1f;
+	}
+
+      for (sline += 3, sx++; sx < sx2i; sline += 3, sx++)
+	{
+#ifdef USE_24BIT_AS_CHARS
+	  scolor = ((unsigned int) (sline[0])
+		    | ((unsigned int) (sline[1]) << 8)
+		    | ((unsigned int) (sline[2]) << 16));
+#else
+	  scolor = ((unsigned int) (((unsigned short*) sline)[0])
+		    | ((unsigned int) (sline[2]) << 16));
+#endif
+	  if (scolor != MASK_COLOR_24)
+	    {
+	      r2 += getr24 (scolor) << aa_BITS;
+	      g2 += getg24 (scolor) << aa_BITS;
+	      b2 += getb24 (scolor) << aa_BITS;
+	    }
+	  else
+	    t2 += aa_SIZE;
+	}
+
+      if (sx2f != 0)
+	{
+#ifdef USE_24BIT_AS_CHARS
+	  scolor = ((unsigned int) (sline[0])
+		    | ((unsigned int) (sline[1]) << 8)
+		    | ((unsigned int) (sline[2]) << 16));
+#else
+	  scolor = ((unsigned int) (((unsigned short*) sline)[0])
+		    | ((unsigned int) (sline[2]) << 16));
+#endif
+	  if (scolor != MASK_COLOR_24)
+	    {
+	      r2 += MUL (getr24 (scolor), sx2f);
+	      g2 += MUL (getg24 (scolor), sx2f);
+	      b2 += MUL (getb24 (scolor), sx2f);
+	    }
+	  else
+	    t2 += sx2f;
+	}
+
+      r1 += MUL (r2, sy2f);
+      g1 += MUL (g2, sy2f);
+      b1 += MUL (b2, sy2f);
+      t1 += MUL (t2, sy2f);
+    }
+
+  if (_num >= (2 * t1))
+    {
+      if (_num == (aa_SIZE * aa_SIZE))
+	{
+	  _aa.r = r1 >> (2 * aa_BITS);
+	  _aa.g = g1 >> (2 * aa_BITS);
+	  _aa.b = b1 >> (2 * aa_BITS);
+	}
+      else
+	{
+	  _aa.r = r1 / _num;
+	  _aa.g = g1 / _num;
+	  _aa.b = b1 / _num;
+	}
+      _aa.transparent = 0;
+    }
+  else
+    _aa.transparent = 1;
+}
+#endif
+#ifdef ALLEGRO_COLOR32
+void
+_aa_masked_add_rgb32 (BITMAP *_src, int _sx1, int _sx2, int _sy1, int _sy2, unsigned long _num)
+{
+  unsigned int *sline;
+  int sx, sx1i, sx1f, sx2i, sx2f;
+  int sy, sy1i, sy1f, sy2i, sy2f;
+  unsigned int r1, g1, b1, t1;
+  unsigned int r2, g2, b2, t2;
+  unsigned int scolor;
+
+  sy1i = _sy1 >> aa_BITS;
+  sy = sy1i;
+
+  /* First line.  */
+  sx1i = _sx1 >> aa_BITS;
+  sx = sx1i;
+  sline = (unsigned int*) (_src->line[sy]) + sx;
+
+  sx1f = aa_SIZE - (_sx1 & aa_MASK);
+  scolor = *sline;
+  if (scolor != MASK_COLOR_32)
+    {
+      r1 = MUL (getr32 (scolor), sx1f);
+      g1 = MUL (getg32 (scolor), sx1f);
+      b1 = MUL (getb32 (scolor), sx1f);
+      t1 = 0;
+    }
+  else
+    {
+      r1 = g1 = b1 = 0;
+      t1 = sx1f;
+    }
+
+  sx2i = _sx2 >> aa_BITS;
+  for (sline++, sx++; sx < sx2i; sline++, sx++)
+    {
+      scolor = *sline;
+      if (scolor != MASK_COLOR_32)
+	{
+	  r1 += getr32 (scolor) << aa_BITS;
+	  g1 += getg32 (scolor) << aa_BITS;
+	  b1 += getb32 (scolor) << aa_BITS;
+	}
+      else
+	t1 += aa_SIZE;
+    }
+
+  sx2f = _sx2 & aa_MASK;
+  if (sx2f != 0)
+    {
+      scolor = *sline;
+      if (scolor != MASK_COLOR_32)
+	{
+	  r1 += MUL (getr32 (scolor), sx2f);
+	  g1 += MUL (getg32 (scolor), sx2f);
+	  b1 += MUL (getb32 (scolor), sx2f);
+	}
+      else
+	t1 += sx2f;
+    }
+
+  sy1f = aa_SIZE - (_sy1 & aa_MASK);
+  r1 = MUL (r1, sy1f);
+  g1 = MUL (g1, sy1f);
+  b1 = MUL (b1, sy1f);
+  t1 = MUL (t1, sy1f);
+
+  /* Middle lines.  */
+  sy2i = _sy2 >> aa_BITS;
+  if (++sy < sy2i)
+    {
+      r2 = g2 = b2 = t2 = 0;
+      do
+	{
+	  sx = sx1i;
+	  sline = (unsigned int*) (_src->line[sy]) + sx;
+
+	  scolor = *sline;
+	  if (scolor != MASK_COLOR_32)
+	    {
+	      r2 += MUL (getr32 (scolor), sx1f);
+	      g2 += MUL (getg32 (scolor), sx1f);
+	      b2 += MUL (getb32 (scolor), sx1f);
+	    }
+	  else
+	    t2 += sx1f;
+
+	  for (sline++, sx++; sx < sx2i; sline++, sx++)
+	    {
+	      scolor = *sline;
+	      if (scolor != MASK_COLOR_32)
+		{
+		  r2 += getr32 (scolor) << aa_BITS;
+		  g2 += getg32 (scolor) << aa_BITS;
+		  b2 += getb32 (scolor) << aa_BITS;
+		}
+	      else
+		t2 += aa_SIZE;
+	    }
+
+	  if (sx2f != 0)
+	    {
+	      scolor = *sline;
+	      if (scolor != MASK_COLOR_32)
+		{
+		  r2 += MUL (getr32 (scolor), sx2f);
+		  g2 += MUL (getg32 (scolor), sx2f);
+		  b2 += MUL (getb32 (scolor), sx2f);
+		}
+	      else
+		t2 += sx2f;
+	    }
+	}
+      while (++sy < sy2i);
+
+      r1 += r2 << aa_BITS;
+      g1 += g2 << aa_BITS;
+      b1 += b2 << aa_BITS;
+      t1 += t2 << aa_BITS;
+    }
+
+  /* Last line.  */
+  sy2f = _sy2 & aa_MASK;
+  if (sy2f != 0)
+    {
+      sx = sx1i;
+      sline = (unsigned int*) (_src->line[sy]) + sx;
+
+      scolor = *sline;
+      if (scolor != MASK_COLOR_32)
+	{
+	  r2 = MUL (getr32 (scolor), sx1f);
+	  g2 = MUL (getg32 (scolor), sx1f);
+	  b2 = MUL (getb32 (scolor), sx1f);
+	  t2 = 0;
+	}
+      else
+	{
+	  r2 = g2 = b2 = 0;
+	  t2 = sx1f;
+	}
+
+      for (sline++, sx++; sx < sx2i; sline++, sx++)
+	{
+	  scolor = *sline;
+	  if (scolor != MASK_COLOR_32)
+	    {
+	      r2 += getr32 (scolor) << aa_BITS;
+	      g2 += getg32 (scolor) << aa_BITS;
+	      b2 += getb32 (scolor) << aa_BITS;
+	    }
+	  else
+	    t2 += aa_SIZE;
+	}
+
+      if (sx2f != 0)
+	{
+	  scolor = *sline;
+	  if (scolor != MASK_COLOR_32)
+	    {
+	      r2 += MUL (getr32 (scolor), sx2f);
+	      g2 += MUL (getg32 (scolor), sx2f);
+	      b2 += MUL (getb32 (scolor), sx2f);
+	    }
+	  else
+	    t2 += sx2f;
+	}
+
+      r1 += MUL (r2, sy2f);
+      g1 += MUL (g2, sy2f);
+      b1 += MUL (b2, sy2f);
+      t1 += MUL (t2, sy2f);
+    }
+
+  if (_num >= (2 * t1))
+    {
+      if (_num == (aa_SIZE * aa_SIZE))
+	{
+	  _aa.r = r1 >> (2 * aa_BITS);
+	  _aa.g = g1 >> (2 * aa_BITS);
+	  _aa.b = b1 >> (2 * aa_BITS);
+	}
+      else
+	{
+	  _aa.r = r1 / _num;
+	  _aa.g = g1 / _num;
+	  _aa.b = b1 / _num;
+	}
+      _aa.transparent = 0;
+    }
+  else
+    _aa.transparent = 1;
+}
+#endif
+
+/*
+ * Putting pixel to destination bitmap.
+ */
+void
+_aa_masked_put_rgb8 (unsigned long _addr, int _x)
+{
+  if (!_aa.transparent)
+    bmp_write8 (_addr + _x, makecol8 (_aa.r, _aa.g, _aa.b));
+}
+#ifdef ALLEGRO_COLOR16
+void
+_aa_masked_put_rgb15 (unsigned long _addr, int _x)
+{
+  if (!_aa.transparent)
+    bmp_write15 (_addr + sizeof (short) * _x, makecol15 (_aa.r, _aa.g, _aa.b));
+}
+void
+_aa_masked_put_rgb16 (unsigned long _addr, int _x)
+{
+  if (!_aa.transparent)
+    bmp_write16 (_addr + sizeof (short) * _x, makecol16 (_aa.r, _aa.g, _aa.b));
+}
+#endif
+#ifdef ALLEGRO_COLOR24
+void
+_aa_masked_put_rgb24 (unsigned long _addr, int _x)
+{
+  if (!_aa.transparent)
+    bmp_write24 (_addr + 3 * _x, makecol24 (_aa.r, _aa.g, _aa.b));
+}
+#endif
+#ifdef ALLEGRO_COLOR32
+void
+_aa_masked_put_rgb32 (unsigned long _addr, int _x)
+{
+  if (!_aa.transparent)
+    bmp_write32 (_addr + sizeof (int) * _x, makecol32 (_aa.r, _aa.g, _aa.b));
+}
+
+#endif
+
+} // namespace AGS3
diff --git a/engines/ags/lib/aastr-0.1.1/aautil.h b/engines/ags/lib/aastr-0.1.1/aautil.h
new file mode 100644
index 0000000000..81b1f97fec
--- /dev/null
+++ b/engines/ags/lib/aastr-0.1.1/aautil.h
@@ -0,0 +1,166 @@
+/* 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.
+ *
+ */
+
+/*
+ * aautil.h --- helpers for anti-aliasing routines for Allegro
+ *
+ * This file is gift-ware.  This file is given to you freely
+ * as a gift.  You may use, modify, redistribute, and generally hack
+ * it about in any way you like, and you do not have to give anyone
+ * anything in return.
+ *
+ * I do not accept any responsibility for any effects, adverse or
+ * otherwise, that this code may have on just about anything that
+ * you can think of.  Use it at your own risk.
+ *
+ * Copyright (C) 1998, 1999  Michael Bukin
+ */
+
+#ifndef AGS_LIB_AASTR_AAUTIL_H
+#define AGS_LIB_AASTR_AAUTIL_H
+
+#include "ags/stubs/allegro.h"
+
+namespace AGS3 {
+
+/*
+ * Change aa_BITS, and never aa_SIZE or aa_MASK.
+ * 8 or 4 are probably the fastest for i386+.
+ * Recompile the package after changing aa_BITS.
+ */
+#ifdef aa_BITS
+#undef aa_BITS
+#endif
+#define aa_BITS		8
+
+#if ((aa_BITS < 0) || (aa_BITS > 12))
+#error aa_BITS must be (0 <= aa_BITS <= 12)
+#endif
+
+#define aa_SIZE		(1UL << aa_BITS)
+#define aa_MASK		(aa_SIZE - 1)
+
+#define aa_MAX_SIZE	(1UL << 12)
+#define aa_MAX_NUM	(aa_MAX_SIZE * aa_MAX_SIZE)
+
+
+ /* Prepare Bresenham line parameters.  */
+#define aa_PREPARE(inc,dd,i1,i2,_yw,_xw)			\
+{								\
+  int xw = (_xw);						\
+  int yw = (_yw);						\
+								\
+  if ((xw == 0) || ((yw < xw) && (yw > -xw))) {			\
+    (inc) = 0;							\
+  }								\
+  else {							\
+    (inc) = yw / xw;						\
+    yw %= xw;							\
+  }								\
+  if (yw < 0) {							\
+    (inc) -= 1;							\
+    yw += xw;							\
+  }								\
+  (i2) = ((dd) = ((i1) = 2 * yw) - xw) - xw;			\
+}
+
+/* Advance to the next point.  */
+#define aa_ADVANCE(y,inc,dd,i1,i2)				\
+{								\
+  if ((dd) >= 0)						\
+    (y) += (inc) + 1, (dd) += (i2);				\
+  else								\
+    (y) += (inc), (dd) += (i1);					\
+}
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+	/* Prepare offsets for direct access to 24bpp bitmap.  */
+	void _aa_prepare_for_24bpp(void);
+
+	/* Add r,g,b values from source bitmap.  */
+	void _aa_add_rgb8(BITMAP *_src, int _sx1, int _sx2, int _sy1, int _sy2, unsigned long _num);
+#ifdef ALLEGRO_COLOR16
+	void _aa_add_rgb15(BITMAP *_src, int _sx1, int _sx2, int _sy1, int _sy2, unsigned long _num);
+	void _aa_add_rgb16(BITMAP *_src, int _sx1, int _sx2, int _sy1, int _sy2, unsigned long _num);
+#endif
+#ifdef ALLEGRO_COLOR24
+	void _aa_add_rgb24(BITMAP *_src, int _sx1, int _sx2, int _sy1, int _sy2, unsigned long _num);
+#endif
+#ifdef ALLEGRO_COLOR32
+	void _aa_add_rgb32(BITMAP *_src, int _sx1, int _sx2, int _sy1, int _sy2, unsigned long _num);
+#endif
+
+	/* Put pixel to destination bitmap.  */
+	void _aa_put_rgb8(unsigned long _addr, int _x);
+#ifdef ALLEGRO_COLOR16
+	void _aa_put_rgb15(unsigned long _addr, int _x);
+	void _aa_put_rgb16(unsigned long _addr, int _x);
+#endif
+#ifdef ALLEGRO_COLOR24
+	void _aa_put_rgb24(unsigned long _addr, int _x);
+#endif
+#ifdef ALLEGRO_COLOR32
+	void _aa_put_rgb32(unsigned long _addr, int _x);
+#endif
+
+	/* Add r,g,b and transparency values from source bitmap.  */
+	void _aa_masked_add_rgb8(BITMAP *_src, int _sx1, int _sx2, int _sy1, int _sy2,
+		unsigned long _num);
+#ifdef ALLEGRO_COLOR16
+	void _aa_masked_add_rgb15(BITMAP *_src, int _sx1, int _sx2, int _sy1, int _sy2,
+		unsigned long _num);
+	void _aa_masked_add_rgb16(BITMAP *_src, int _sx1, int _sx2, int _sy1, int _sy2,
+		unsigned long _num);
+#endif
+#ifdef ALLEGRO_COLOR24
+	void _aa_masked_add_rgb24(BITMAP *_src, int _sx1, int _sx2, int _sy1, int _sy2,
+		unsigned long _num);
+#endif
+#ifdef ALLEGRO_COLOR32
+	void _aa_masked_add_rgb32(BITMAP *_src, int _sx1, int _sx2, int _sy1, int _sy2,
+		unsigned long _num);
+#endif
+
+	/* Put masked pixel to destination bitmap.  */
+	void _aa_masked_put_rgb8(unsigned long _addr, int _x);
+#ifdef ALLEGRO_COLOR16
+	void _aa_masked_put_rgb15(unsigned long _addr, int _x);
+	void _aa_masked_put_rgb16(unsigned long _addr, int _x);
+#endif
+#ifdef ALLEGRO_COLOR24
+	void _aa_masked_put_rgb24(unsigned long _addr, int _x);
+#endif
+#ifdef ALLEGRO_COLOR32
+	void _aa_masked_put_rgb32(unsigned long _addr, int _x);
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 6a5a42c6c7..148852c3cd 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -3,6 +3,9 @@ MODULE := engines/ags
 MODULE_OBJS = \
 	ags.o \
 	metaengine.o \
+	lib/aastr-0.1.1/aarot.o \
+	lib/aastr-0.1.1/aastr.o \
+	lib/aastr-0.1.1/aautil.o \
 	stubs/allegro.o \
 	stubs/allegro/color.o \
 	stubs/allegro/config.o \
@@ -17,6 +20,9 @@ MODULE_OBJS = \
 	stubs/allegro/sound.o \
 	stubs/allegro/system.o \
 	stubs/allegro/unicode.o \
+	shared/gfx/allegrobitmap.o \
+	shared/gfx/bitmap.o \
+	shared/gfx/image.o \
 	shared/gui/guibutton.o \
 	shared/gui/guiinv.o \
 	shared/gui/guilabel.o \
diff --git a/engines/ags/shared/core/types.h b/engines/ags/shared/core/types.h
index 9a9669f2cb..7370da5934 100644
--- a/engines/ags/shared/core/types.h
+++ b/engines/ags/shared/core/types.h
@@ -71,7 +71,7 @@ typedef int64 int64_t;
 typedef int64 soff_t;
 
 #define fixed_t int32_t // fixed point type
-#define color_t int32_t
+#define color_t int
 
 #undef INT32_MIN
 #undef INT32_MAX
diff --git a/engines/ags/shared/gfx/allegrobitmap.cpp b/engines/ags/shared/gfx/allegrobitmap.cpp
index 42ed2dfa77..cb471b43e7 100644
--- a/engines/ags/shared/gfx/allegrobitmap.cpp
+++ b/engines/ags/shared/gfx/allegrobitmap.cpp
@@ -20,13 +20,14 @@
  *
  */
 
-//include <aastr.h>
 #include "ags/shared/gfx/allegrobitmap.h"
+#include "ags/shared/gfx/image.h"
 #include "ags/shared/debugging/assert.h"
+#include "ags/lib/aastr-0.1.1/aastr.h"
 
 namespace AGS3 {
 
-extern void __my_setcolor(int *ctset, int newcol, int wantColDep);
+extern void __my_setcolor(color_t *ctset, color_t newcol, int wantColDep);
 
 namespace AGS {
 namespace Shared {
diff --git a/engines/ags/shared/gfx/allegrobitmap.h b/engines/ags/shared/gfx/allegrobitmap.h
index 195bc85d43..f59f346dae 100644
--- a/engines/ags/shared/gfx/allegrobitmap.h
+++ b/engines/ags/shared/gfx/allegrobitmap.h
@@ -125,12 +125,12 @@ public:
 	// Gets a pointer to underlying graphic data
 	// FIXME: actually not a very good idea, since there's no 100% guarantee the scanline positions in memory are sequential
 	inline const unsigned char *GetData() const {
-		return (unsigned char *)_alBitmap->getPixels();
+		return _alBitmap->getPixels();
 	}
 
 	// Get scanline for direct reading
 	inline const unsigned char *GetScanLine(int index) const {
-		return (index >= 0 && index < GetHeight()) ? (unsigned char *)_alBitmap->getBasePtr(0, index) : nullptr;
+		return (index >= 0 && index < GetHeight()) ? _alBitmap->getBasePtr(0, index) : nullptr;
 	}
 
 	void    SetMaskColor(color_t color);
@@ -212,10 +212,10 @@ public:
 	// TODO: think how to increase safety over this (some fixed memory buffer class with iterator?)
 	// Gets scanline for directly writing into it
 	inline unsigned char *GetScanLineForWriting(int index) {
-		return (index >= 0 && index < GetHeight()) ? (unsigned char *)_alBitmap->getBasePtr(0, index) : nullptr;
+		return (index >= 0 && index < GetHeight()) ? _alBitmap->getBasePtr(0, index) : nullptr;
 	}
 	inline unsigned char *GetDataForWriting() {
-		return (unsigned char *)_alBitmap->getPixels();
+		return _alBitmap->getPixels();
 	}
 	// Copies buffer contents into scanline
 	void    SetScanLine(int index, unsigned char *data, int data_size = -1);
diff --git a/engines/ags/shared/gfx/bitmap.cpp b/engines/ags/shared/gfx/bitmap.cpp
index 9c6f311de6..01ee210b60 100644
--- a/engines/ags/shared/gfx/bitmap.cpp
+++ b/engines/ags/shared/gfx/bitmap.cpp
@@ -117,7 +117,7 @@ struct PixelTransCpy24 {
 struct PixelTransCpy32 {
 	static const size_t BPP = 4;
 	inline void operator()(uint8_t *dst, const uint8_t *src, color_t mask_color, bool use_alpha) const {
-		if (*(const uint32_t *)src == mask_color)
+		if (*(const uint32_t *)src == (uint32_t)mask_color)
 			*(uint32_t *)dst = mask_color;
 		else if (use_alpha)
 			dst[3] = src[3]; // copy alpha channel
@@ -128,7 +128,7 @@ struct PixelTransCpy32 {
 
 struct PixelTransSkip32 {
 	inline bool operator()(uint8_t *data, color_t mask_color, bool use_alpha) const {
-		return *(uint32_t *)data == mask_color || (use_alpha && data[3] == 0);
+		return *(uint32_t *)data == (uint32_t)mask_color || (use_alpha && data[3] == 0);
 	}
 };
 
diff --git a/engines/ags/shared/gfx/image.cpp b/engines/ags/shared/gfx/image.cpp
new file mode 100644
index 0000000000..b77e08286c
--- /dev/null
+++ b/engines/ags/shared/gfx/image.cpp
@@ -0,0 +1,77 @@
+/* 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 "ags/shared/gfx/image.h"
+#include "ags/stubs/allegro.h"
+#include "common/str.h"
+#include "common/textconsole.h"
+
+namespace AGS3 {
+
+BITMAP *load_bmp_pf(PACKFILE *f, color *pal) {
+	error("TODO: load_bmp_pf");
+}
+
+BITMAP *load_pcx_pf(PACKFILE *f, color *pal) {
+	error("TODO: load_pcx_pf");
+}
+
+BITMAP *load_tga_pf(PACKFILE *f, color *pal) {
+	error("TODO: load_tga_pf");
+}
+
+BITMAP *load_bmp(const char *filename, color *pal) {
+	error("TODO: load_bmp");
+}
+
+BITMAP *load_lbm(const char *filename, color *pal) {
+	error("TODO: load_lbm");
+}
+
+BITMAP *load_pcx(const char *filename, color *pal) {
+	error("TODO: load_pcx");
+}
+
+BITMAP *load_tga(const char *filename, color *pal) {
+	error("TODO: load_tga");
+}
+
+BITMAP *load_bitmap(const char *filename, color *pal) {
+	Common::String fname(filename);
+
+	if (fname.hasSuffixIgnoreCase(".bmp"))
+		return load_bmp(filename, pal);
+	else if (fname.hasSuffixIgnoreCase(".lbm"))
+		return load_lbm(filename, pal);
+	else if (fname.hasSuffixIgnoreCase(".pcx"))
+		return load_pcx(filename, pal);
+	else if (fname.hasSuffixIgnoreCase(".tga"))
+		return load_tga(filename, pal);
+	else
+		error("Unknown image file - %s", filename);
+}
+
+int save_bitmap(const char *filename, BITMAP *bmp, const RGB *pal) {
+	error("TODO: save_bitmap");
+}
+
+} // namespace AGS
diff --git a/engines/ags/shared/gfx/image.h b/engines/ags/shared/gfx/image.h
new file mode 100644
index 0000000000..a37358fa25
--- /dev/null
+++ b/engines/ags/shared/gfx/image.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 AGS_SHARED_GFX_IMAGE_H
+#define AGS_SHARED_GFX_IMAGE_H
+
+#include "ags/stubs/allegro.h"
+
+namespace AGS3 {
+
+BITMAP *load_bitmap(const char *filename, color *pal);
+BITMAP *load_bmp(const char *filename, color *pal);
+BITMAP *load_bmp_pf(PACKFILE *f, color *pal);
+BITMAP *load_lbm(const char *filename, color *pal);
+BITMAP *load_pcx(const char *filename, color *pal);
+BITMAP *load_pcx_pf(PACKFILE *f, color *pal);
+BITMAP *load_tga(const char *filename, color *pal);
+BITMAP *load_tga_pf(PACKFILE *f, color *pal);
+
+int save_bitmap(const char *filename, BITMAP *bmp, const RGB *pal);
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/shared/util/wgt2allg.h b/engines/ags/shared/util/wgt2allg.h
index 090f51ca49..0302f118b0 100644
--- a/engines/ags/shared/util/wgt2allg.h
+++ b/engines/ags/shared/util/wgt2allg.h
@@ -55,7 +55,7 @@ using namespace AGS; // FIXME later
 //=============================================================================
 
 // [IKM] 2012-09-13: this function is now defined in engine and editor separately
-extern void __my_setcolor(int *ctset, int newcol, int wantColDep);
+extern void __my_setcolor(color_t *ctset, color_t newcol, int wantColDep);
 
 #ifdef __cplusplus
 extern "C"
diff --git a/engines/ags/stubs/allegro/color.cpp b/engines/ags/stubs/allegro/color.cpp
index a69500e387..f096998d42 100644
--- a/engines/ags/stubs/allegro/color.cpp
+++ b/engines/ags/stubs/allegro/color.cpp
@@ -41,22 +41,28 @@ int _rgb_g_shift_32 = 0;
 int _rgb_b_shift_32 = 0;
 int _rgb_a_shift_32 = 0;
 
+PALETTE _current_palette;
+
 int bestfit_color(const PALETTE pal, int r, int g, int b) {
 	error("TODO: bestfit_color");
 }
 
 void set_color(int idx, const RGB *p) {
+	_current_palette[idx] = *p;
 	g_system->getPaletteManager()->setPalette((const byte *)p, idx, 1);
 }
 
 void set_palette(const PALETTE p) {
-
+	for (int idx = 0; idx < PALETTE_COUNT; ++idx)
+		_current_palette[idx] = p[idx];
+	g_system->getPaletteManager()->setPalette((const byte *)p, 0, PALETTE_COUNT);
 }
 
 void set_palette_range(const PALETTE p, int from, int to, int retracesync) {
 	byte palette[256 * 3];
 	byte *destP = palette;
 	for (int i = 0; i < 256; ++i, destP += 3) {
+		_current_palette[i] = *p;
 		destP[0] = p->r;
 		destP[1] = p->g;
 		destP[2] = p->b;
@@ -65,4 +71,56 @@ void set_palette_range(const PALETTE p, int from, int to, int retracesync) {
 	g_system->getPaletteManager()->setPalette(&palette[from], from, to - from + 1);
 }
 
+
+int makecol15(int r, int g, int b) {
+	return (((r >> 3) << _rgb_r_shift_15) |
+		((g >> 3) << _rgb_g_shift_15) |
+		((b >> 3) << _rgb_b_shift_15));
+}
+
+int makecol16(int r, int g, int b) {
+	return (((r >> 3) << _rgb_r_shift_16) |
+		((g >> 2) << _rgb_g_shift_16) |
+		((b >> 3) << _rgb_b_shift_16));
+}
+
+int makecol24(int r, int g, int b) {
+	return ((r << _rgb_r_shift_24) |
+		(g << _rgb_g_shift_24) |
+		(b << _rgb_b_shift_24));
+}
+
+int makecol32(int r, int g, int b) {
+	return ((r << _rgb_r_shift_32) |
+		(g << _rgb_g_shift_32) |
+		(b << _rgb_b_shift_32));
+}
+
+int makeacol32(int r, int g, int b, int a) {
+	return ((r << _rgb_r_shift_32) |
+		(g << _rgb_g_shift_32) |
+		(b << _rgb_b_shift_32) |
+		(a << _rgb_a_shift_32));
+}
+
+int getr8(int c) {
+	return (int)_current_palette[c].r;
+}
+
+int getg8(int c) {
+	return (int)_current_palette[c].g;
+}
+
+int getb8(int c) {
+	return (int)_current_palette[c].b;
+}
+
+int makecol(byte r, byte g, byte b) {
+	return (b) | (g << 8) | (r << 16);
+}
+
+int makecol8(byte r, byte g, byte b) {
+	return (b) | (g << 8) | (r << 16);
+}
+
 } // namespace AGS3
diff --git a/engines/ags/stubs/allegro/color.h b/engines/ags/stubs/allegro/color.h
index e465562850..de8ab5b14b 100644
--- a/engines/ags/stubs/allegro/color.h
+++ b/engines/ags/stubs/allegro/color.h
@@ -28,6 +28,13 @@
 
 namespace AGS3 {
 
+#define PALETTE_COUNT 256
+#define MASK_COLOR_8       0
+#define MASK_COLOR_15      0x7C1F
+#define MASK_COLOR_16      0xF81F
+#define MASK_COLOR_24      0xFF00FF
+#define MASK_COLOR_32      0xFF00FF
+
 #include "common/pack-start.h"  // START STRUCT PACKING
 
 struct color {
@@ -35,7 +42,9 @@ struct color {
 } PACKED_STRUCT;
 
 typedef color RGB;
-typedef color PALETTE[256];
+typedef color PALETTE[PALETTE_COUNT];
+
+AL_VAR(PALETTE, _current_palette);
 
 #include "common/pack-end.h"    // END STRUCT PACKING
 
@@ -61,6 +70,18 @@ AL_FUNC(void, set_color, (int idx, AL_CONST RGB *p));
 AL_FUNC(void, set_palette, (AL_CONST PALETTE p));
 AL_FUNC(void, set_palette_range, (AL_CONST PALETTE p, int from, int to, int retracesync));
 
+
+extern int makecol15(int r, int g, int b);
+extern int makecol16(int r, int g, int b);
+extern int makecol24(int r, int g, int b);
+extern int makecol32(int r, int g, int b);
+extern int makeacol32(int r, int g, int b, int a);
+extern int getr8(int c);
+extern int getg8(int c);
+extern int getb8(int c);
+extern int makecol(byte r, byte g, byte b);
+extern int makecol8(byte r, byte g, byte b);
+
 } // namespace AGS3
 
 #endif
diff --git a/engines/ags/stubs/allegro/gfx.cpp b/engines/ags/stubs/allegro/gfx.cpp
index 799e42a07d..0aec33c9f9 100644
--- a/engines/ags/stubs/allegro/gfx.cpp
+++ b/engines/ags/stubs/allegro/gfx.cpp
@@ -22,11 +22,54 @@
 
 #include "ags/stubs/allegro/gfx.h"
 #include "common/textconsole.h"
+#include "graphics/screen.h"
 
 namespace AGS3 {
 
 int color_conversion;
 
+/*-------------------------------------------------------------------*/
+
+BITMAP::BITMAP(Graphics::ManagedSurface *owner) : _owner(owner),
+		w(owner->w), h(owner->h), format(owner->format),
+		clip(false), ct(0), cb(0), cl(0), cr(0) {
+	line.resize(h);
+	for (uint y = 0; y < h; ++y)
+		line[y] = (byte *)_owner->getBasePtr(0, y);
+}
+
+/*-------------------------------------------------------------------*/
+
+/**
+ * Derived surface class
+ */
+class Surface : public Graphics::ManagedSurface, public BITMAP {
+public:
+	Surface() : Graphics::ManagedSurface(), BITMAP(this) {}
+	Surface(const Graphics::ManagedSurface &surf) : Graphics::ManagedSurface(surf), BITMAP(this) {}
+	Surface(int width, int height) : Graphics::ManagedSurface(width, height), BITMAP(this) {}
+	Surface(int width, int height, const Graphics::PixelFormat &pixelFormat) :
+		Graphics::ManagedSurface(width, height, pixelFormat), BITMAP(this) {}
+	Surface(Graphics::ManagedSurface &surf, const Common::Rect &bounds) :
+		Graphics::ManagedSurface(surf, bounds), BITMAP(this) {}
+	~Surface() override {}
+};
+
+/**
+ * Dervied screen surface
+ */
+class Screen : public Graphics::Screen, public BITMAP {
+public:
+	Screen() : Graphics::Screen(), BITMAP(this) {}
+	Screen(int width, int height) : Graphics::Screen(width, height), BITMAP(this) {}
+	Screen(int width, int height, const Graphics::PixelFormat &pixelFormat) :
+		Graphics::Screen(width, height, pixelFormat), BITMAP(this) {}
+	~Screen() override {}
+};
+
+
+/*-------------------------------------------------------------------*/
+
 void set_color_conversion(int mode) {
 	color_conversion = mode;
 }
@@ -39,5 +82,308 @@ int set_gfx_mode(int card, int w, int h, int v_w, int v_h) {
 	error("TODO: set_gfx_mode");
 }
 
+BITMAP *create_bitmap(int width, int height) {
+	return new Surface(width, height);
+}
+
+BITMAP *create_bitmap_ex(int color_depth, int width, int height) {
+	Graphics::PixelFormat format;
+
+	switch (color_depth) {
+	case 16:
+		format = Graphics::PixelFormat(2, 5, 6, 5, 0, 11, 5, 0, 0);
+	case 32:
+		format = Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0);
+	default:
+		error("Invalid color depth");
+	}
+
+	return new Surface(width, height, format);
+}
+
+BITMAP *create_sub_bitmap(BITMAP *parent, int x, int y, int width, int height) {
+	Graphics::ManagedSurface &surf = **parent;
+	return new Surface(surf, Common::Rect(x, y, x + width, y + height));
+}
+
+BITMAP *create_video_bitmap(int width, int height) {
+	return new Screen(width, height);
+}
+
+BITMAP *create_system_bitmap(int width, int height) {
+	return create_bitmap(width, height);
+}
+
+void destroy_bitmap(BITMAP *bitmap) {
+	delete bitmap;
+}
+
+void set_clip_rect(BITMAP *bitmap, int x1, int y1, int x2, int y2) {
+	warning("TODO: set_clip_rect");
+}
+
+void add_clip_rect(BITMAP *bitmap, int x1, int y1, int x2, int y2) {
+	warning("TODO: add_clip_rect");
+}
+
+void get_clip_rect(BITMAP *bitmap, int *x1, int *y1, int *x2, int *y2) {
+	warning("TODO: get_clip_rect");
+	*x1 = *y1 = *x2 = *y2 = 0;
+}
+
+void acquire_bitmap(BITMAP *bitmap) {
+	// No implementation needed
+}
+
+void release_bitmap(BITMAP *bitmap) {
+	// No implementation needed
+}
+
+void clear_to_color(BITMAP *bitmap, int color) {
+	Graphics::ManagedSurface &surf = **bitmap;
+
+   surf.clear(color);
+}
+
+int bitmap_color_depth(BITMAP *bmp) {
+	Graphics::ManagedSurface &surf = **bmp;
+
+	return surf.format.bpp();
+}
+
+int bitmap_mask_color(BITMAP *bmp) {
+	Graphics::ManagedSurface &surf = **bmp;
+	return surf.getTransparentColor();
+}
+
+void blit(const BITMAP *src, BITMAP *dest, int src_x, int src_y, int dst_x, int dst_y, int width, int height) {
+	Graphics::ManagedSurface &srcS = **src;
+	Graphics::ManagedSurface &destS = **dest;
+
+	destS.blitFrom(srcS, Common::Rect(src_x, src_y, src_x + width, src_y + height), Common::Point(dst_x, dst_y));
+}
+
+void stretch_blit(const BITMAP *src, BITMAP *dest, int source_x, int source_y, int source_width, int source_height,
+		int dest_x, int dest_y, int dest_width, int dest_height) {
+	Graphics::ManagedSurface &srcS = **src;
+	Graphics::ManagedSurface &destS = **dest;
+
+	destS.transBlitFrom(srcS, Common::Rect(source_x, source_y, source_x + source_width, source_y + source_height),
+		Common::Rect(dest_x, dest_y, dest_x + dest_width, dest_y + dest_height));
+}
+
+void masked_blit(const BITMAP *src, BITMAP *dest, int src_x, int src_y, int dst_x, int dst_y, int width, int height) {
+	Graphics::ManagedSurface &srcS = **src;
+	Graphics::ManagedSurface &destS = **dest;
+
+	destS.blitFrom(srcS, Common::Rect(src_x, src_y, src_x + width, src_y + height), Common::Point(dst_x, dst_y));
+}
+
+void masked_stretch_blit(const BITMAP *src, BITMAP *dest, int source_x, int source_y, int source_width, int source_height,
+	int dest_x, int dest_y, int dest_width, int dest_height) {
+	Graphics::ManagedSurface &srcS = **src;
+	Graphics::ManagedSurface &destS = **dest;
+
+	destS.transBlitFrom(srcS, Common::Rect(source_x, source_y, source_x + source_width, source_y + source_height),
+		Common::Rect(dest_x, dest_y, dest_x + dest_width, dest_y + dest_height));
+}
+
+void draw_sprite(BITMAP *bmp, const BITMAP *sprite, int x, int y) {
+	Graphics::ManagedSurface &bmpS = **bmp;
+	Graphics::ManagedSurface &spriteS = **sprite;
+
+	bmpS.blitFrom(spriteS, Common::Point(x, y));
+}
+
+void stretch_sprite(BITMAP *bmp, BITMAP *sprite, int x, int y, int w, int h) {
+	Graphics::ManagedSurface &bmpS = **bmp;
+	Graphics::ManagedSurface &spriteS = **sprite;
+
+	bmpS.transBlitFrom(spriteS, Common::Rect(0, 0, sprite->w, sprite->h),
+		Common::Rect(x, y, x + w, y + h));
+}
+
+void draw_trans_sprite(BITMAP *bmp, const BITMAP *sprite, int x, int y) {
+	error("TODO: draw_trans_sprite");
+}
+
+void draw_lit_sprite(BITMAP *bmp, const BITMAP *sprite, int x, int y, int color) {
+	error("TODO: draw_lit_sprite");
+}
+
+void draw_sprite_h_flip(BITMAP *bmp, const BITMAP *sprite, int x, int y) {
+	error("TODO: draw_sprite_h_flip");
+}
+
+void draw_sprite_v_flip(BITMAP *bmp, const BITMAP *sprite, int x, int y) {
+	error("TODO: draw_sprite_v_flip");
+}
+
+void draw_sprite_vh_flip(BITMAP *bmp, const BITMAP *sprite, int x, int y) {
+	error("TODO: draw_sprite_vh_flip");
+}
+
+void rotate_sprite(BITMAP *bmp, const BITMAP *sprite, int x, int y, fixed angle) {
+	error("TODO: rotate_sprite");
+}
+
+void pivot_sprite(BITMAP *bmp, const BITMAP *sprite, int x, int y, int cx, int cy, fixed angle) {
+	error("TODO: pivot_sprite");
+}
+
+
+bool is_screen_bitmap(BITMAP *bmp) {
+	return dynamic_cast<Graphics::Screen *>(bmp) != nullptr;
+}
+
+bool is_video_bitmap(BITMAP *bmp) {
+	return dynamic_cast<Graphics::Screen *>(bmp) != nullptr;
+}
+
+bool is_planar_bitmap(BITMAP *bmp) {
+	return false;
+}
+
+void bmp_select(BITMAP *bmp) {
+	// No implementation needed
+}
+
+long bmp_write_line(BITMAP *bmp, int line) {
+	return (long)bmp->line[line];
+}
+
+void bmp_unwrite_line(BITMAP *bmp) {
+	// No implementation needed
+}
+
+void bmp_write8(unsigned long addr, int color) {
+	*((byte *)addr) = color;
+}
+
+void memory_putpixel(BITMAP *bmp, int x, int y, int color) {
+	putpixel(bmp, x, y, color);
+}
+
+void putpixel(BITMAP *bmp, int x, int y, int color) {
+	Graphics::ManagedSurface &surf = **bmp;
+	void *p = surf.getBasePtr(x, y);
+
+	switch (surf.format.bytesPerPixel) {
+	case 1:
+		*((uint8 *)p) = color;
+		break;
+	case 2:
+		*((uint16 *)p) = color;
+		break;
+	case 4:
+		*((uint32 *)p) = color;
+		break;
+	default:
+		break;
+	}
+}
+
+void _putpixel(BITMAP *bmp, int x, int y, int color) {
+	Graphics::ManagedSurface &surf = **bmp;
+	void *p = surf.getBasePtr(x, y);
+	*((uint8 *)p) = color;
+}
+
+void _putpixel15(BITMAP *bmp, int x, int y, int color) {
+	error("Unsupported bpp");
+}
+
+void _putpixel16(BITMAP *bmp, int x, int y, int color) {
+	Graphics::ManagedSurface &surf = **bmp;
+	void *p = surf.getBasePtr(x, y);
+	*((uint16 *)p) = color;
+}
+
+void _putpixel24(BITMAP *bmp, int x, int y, int color) {
+	error("Unsupported bpp");
+}
+
+void _putpixel32(BITMAP *bmp, int x, int y, int color) {
+	Graphics::ManagedSurface &surf = **bmp;
+	void *p = surf.getBasePtr(x, y);
+	*((uint32 *)p) = color;
+}
+
+int getpixel(BITMAP *bmp, int x, int y) {
+	Graphics::ManagedSurface &surf = **bmp;
+	void *p = surf.getBasePtr(x, y);
+
+	switch (surf.format.bytesPerPixel) {
+	case 1:
+		return *((uint8 *)p);
+		break;
+	case 2:
+		return *((uint16 *)p);
+		break;
+	case 4:
+		return *((uint32 *)p);
+		break;
+	default:
+		break;
+	}
+
+	error("Unsupported bpp");
+}
+
+int _getpixel(BITMAP *bmp, int x, int y) {
+	Graphics::ManagedSurface &surf = **bmp;
+	void *p = surf.getBasePtr(x, y);
+	return *((uint8 *)p);
+}
+
+int _getpixel15(BITMAP *bmp, int x, int y) {
+	error("Unsupported bpp");
+}
+
+int _getpixel16(BITMAP *bmp, int x, int y) {
+	Graphics::ManagedSurface &surf = **bmp;
+	void *p = surf.getBasePtr(x, y);
+	return *((uint16 *)p);
+}
+
+int _getpixel24(BITMAP *bmp, int x, int y) {
+	error("Unsupported bpp");
+}
+
+int _getpixel32(BITMAP *bmp, int x, int y) {
+	Graphics::ManagedSurface &surf = **bmp;
+	void *p = surf.getBasePtr(x, y);
+	return *((uint32 *)p);
+}
+
+void line(BITMAP *bmp, int x1, int y1, int x2, int y2, int color) {
+	Graphics::ManagedSurface &surf = **bmp;
+	surf.drawLine(x1, y1, x2, y2, color);
+}
+
+void rect(BITMAP *bmp, int x1, int y1, int x2, int y2, int color) {
+	Graphics::ManagedSurface &surf = **bmp;
+	surf.frameRect(Common::Rect(x1, y1, x2, y2), color);
+}
+
+void rectfill(BITMAP *bmp, int x1, int y1, int x2, int y2, int color) {
+	Graphics::ManagedSurface &surf = **bmp;
+	surf.fillRect(Common::Rect(x1, y1, x2, y2), color);
+}
+
+void triangle(BITMAP *bmp, int x1, int y1, int x2, int y2, int x3, int y3, int color) {
+	Graphics::ManagedSurface &surf = **bmp;
+	surf.drawLine(x1, y1, x2, y2, color);
+	surf.drawLine(x2, y2, x3, y3, color);
+	surf.drawLine(x3, y3, x1, y1, color);
+}
+
+void floodfill(BITMAP *bmp, int x, int y, int color) {
+	error("TODO: floodfill");
+}
+
+void circlefill(BITMAP *bmp, int x, int y, int radius, int color) {
+	error("TODO: circlefill");
+}
 
 } // namespace AGS3
diff --git a/engines/ags/stubs/allegro/gfx.h b/engines/ags/stubs/allegro/gfx.h
index a6e71afccb..b6f8c3be3d 100644
--- a/engines/ags/stubs/allegro/gfx.h
+++ b/engines/ags/stubs/allegro/gfx.h
@@ -25,6 +25,8 @@
 
 #include "graphics/managed_surface.h"
 #include "ags/stubs/allegro/base.h"
+#include "ags/stubs/allegro/fixed.h"
+#include "common/array.h"
 
 namespace AGS3 {
 
@@ -164,12 +166,100 @@ namespace AGS3 {
                                              COLORCONV_32A_TO_16 |       \
                                              COLORCONV_32A_TO_24))
 
-class BITMAP : public Graphics::ManagedSurface {
+class BITMAP {
+private:
+	Graphics::ManagedSurface *_owner;
+public:
+	uint16 &w, &h;
+	Graphics::PixelFormat &format;
+	bool clip;
+	int ct, cb, cl, cr;
+	Common::Array<byte *> line;
+public:
+	BITMAP(Graphics::ManagedSurface *owner);
+	virtual ~BITMAP() {}
+
+	Graphics::ManagedSurface &operator*() const {
+		return *_owner;
+	}
+
+	unsigned char *getPixels() const {
+		return (unsigned char *)_owner->getPixels();
+	}
+
+	unsigned char *getBasePtr(uint16 x, uint16 y) const {
+		return (unsigned char *)_owner->getBasePtr(x, y);
+	}
+
+	uint getTransparentColor() const {
+		return _owner->getTransparentColor();
+	}
 };
 
 AL_FUNC(void, set_color_conversion, (int mode));
 AL_FUNC(int, get_color_conversion, ());
 AL_FUNC(int, set_gfx_mode, (int card, int w, int h, int v_w, int v_h));
+AL_FUNC(BITMAP *, create_bitmap, (int width, int height));
+AL_FUNC(BITMAP *, create_bitmap_ex, (int color_depth, int width, int height));
+AL_FUNC(BITMAP *, create_sub_bitmap, (BITMAP *parent, int x, int y, int width, int height));
+AL_FUNC(BITMAP *, create_video_bitmap, (int width, int height));
+AL_FUNC(BITMAP *, create_system_bitmap, (int width, int height));
+
+AL_FUNC(void, destroy_bitmap, (BITMAP *bitmap));
+AL_FUNC(void, set_clip_rect, (BITMAP *bitmap, int x1, int y1, int x2, int y2));
+AL_FUNC(void, add_clip_rect, (BITMAP *bitmap, int x1, int y1, int x2, int y2));
+AL_FUNC(void, get_clip_rect, (BITMAP *bitmap, int *x1, int *y1, int *x2, int *y2));
+AL_FUNC(void, clear_bitmap, (BITMAP *bitmap));
+
+AL_FUNC(void, acquire_bitmap, (BITMAP *bitmap));
+AL_FUNC(void, release_bitmap, (BITMAP *bitmap));
+AL_FUNC(void, draw_sprite, (BITMAP *bmp, const BITMAP *sprite, int x, int y));
+AL_FUNC(void, stretch_sprite, (BITMAP *bmp, const BITMAP *sprite, int x, int y, int w, int h));
+
+
+extern void clear_to_color(BITMAP *bitmap, int color);
+extern int bitmap_color_depth(BITMAP *bmp);
+extern int bitmap_mask_color(BITMAP *bmp);
+extern void blit(const BITMAP *src, BITMAP *dest, int src_x, int src_y, int dst_x, int dst_y, int width, int height);
+extern void masked_blit(const BITMAP *src, BITMAP *dest, int src_x, int src_y, int dst_x, int dst_y, int width, int height);
+extern void stretch_blit(const BITMAP *src, BITMAP *dest, int source_x, int source_y, int source_width, int source_height,
+	int dest_x, int dest_y, int dest_width, int dest_height);
+extern void masked_stretch_blit(const BITMAP *src, BITMAP *dest, int source_x, int source_y, int source_width, int source_height,
+	int dest_x, int dest_y, int dest_width, int dest_height);
+extern void draw_trans_sprite(BITMAP *bmp, const BITMAP *sprite, int x, int y);
+extern void draw_lit_sprite(BITMAP *bmp, const BITMAP *sprite, int x, int y, int color);
+extern void draw_sprite_h_flip(BITMAP *bmp, const BITMAP *sprite, int x, int y);
+extern void draw_sprite_v_flip(BITMAP *bmp, const BITMAP *sprite, int x, int y);
+extern void draw_sprite_vh_flip(BITMAP *bmp, const BITMAP *sprite, int x, int y);
+extern void rotate_sprite(BITMAP *bmp, const BITMAP *sprite, int x, int y, fixed angle);
+extern void pivot_sprite(BITMAP *bmp, const BITMAP *sprite, int x, int y, int cx, int cy, fixed angle);
+
+extern bool is_screen_bitmap(BITMAP *bmp);
+extern bool is_video_bitmap(BITMAP *bmp);
+extern bool is_planar_bitmap(BITMAP *bmp);
+extern void bmp_select(BITMAP *bmp);
+extern long bmp_write_line(BITMAP *bmp, int line);
+extern void bmp_unwrite_line(BITMAP *bmp);
+extern void bmp_write8(unsigned long addr, int color);
+extern void memory_putpixel(BITMAP *bmp, int x, int y, int color);
+extern void putpixel(BITMAP *bmp, int x, int y, int color);
+extern void _putpixel(BITMAP *bmp, int x, int y, int color);
+extern void _putpixel15(BITMAP *bmp, int x, int y, int color);
+extern void _putpixel16(BITMAP *bmp, int x, int y, int color);
+extern void _putpixel24(BITMAP *bmp, int x, int y, int color);
+extern void _putpixel32(BITMAP *bmp, int x, int y, int color);
+extern int getpixel(BITMAP *bmp, int x, int y);
+extern int _getpixel(BITMAP *bmp, int x, int y);
+extern int _getpixel15(BITMAP *bmp, int x, int y);
+extern int _getpixel16(BITMAP *bmp, int x, int y);
+extern int _getpixel24(BITMAP *bmp, int x, int y);
+extern int _getpixel32(BITMAP *bmp, int x, int y);
+extern void line(BITMAP *bmp, int x1, int y_1, int x2, int y2, int color);
+extern void rect(BITMAP *bmp, int x1, int y_1, int x2, int y2, int color);
+extern void rectfill(BITMAP *bmp, int x1, int y_1, int x2, int y2, int color);
+extern void triangle(BITMAP *bmp, int x1, int y_1, int x2, int y2, int x3, int y3, int color);
+extern void floodfill(BITMAP *bmp, int x, int y, int color);
+extern void circlefill(BITMAP *bmp, int x, int y, int radius, int color);
 
 } // namespace AGS3
 


Commit: fdcfe8362fe422f8b91357a7d69640d188594169
    https://github.com/scummvm/scummvm/commit/fdcfe8362fe422f8b91357a7d69640d188594169
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Move allegro from stubs/ to lib/

Changed paths:
  A engines/ags/lib/allegro.cpp
  A engines/ags/lib/allegro.h
  A engines/ags/lib/allegro/alconfig.h
  A engines/ags/lib/allegro/base.h
  A engines/ags/lib/allegro/color.cpp
  A engines/ags/lib/allegro/color.h
  A engines/ags/lib/allegro/config.cpp
  A engines/ags/lib/allegro/config.h
  A engines/ags/lib/allegro/digi.cpp
  A engines/ags/lib/allegro/digi.h
  A engines/ags/lib/allegro/error.cpp
  A engines/ags/lib/allegro/error.h
  A engines/ags/lib/allegro/file.cpp
  A engines/ags/lib/allegro/file.h
  A engines/ags/lib/allegro/fixed.cpp
  A engines/ags/lib/allegro/fixed.h
  A engines/ags/lib/allegro/gfx.cpp
  A engines/ags/lib/allegro/gfx.h
  A engines/ags/lib/allegro/keyboard.cpp
  A engines/ags/lib/allegro/keyboard.h
  A engines/ags/lib/allegro/midi.cpp
  A engines/ags/lib/allegro/midi.h
  A engines/ags/lib/allegro/mouse.cpp
  A engines/ags/lib/allegro/mouse.h
  A engines/ags/lib/allegro/sound.cpp
  A engines/ags/lib/allegro/sound.h
  A engines/ags/lib/allegro/system.cpp
  A engines/ags/lib/allegro/system.h
  A engines/ags/lib/allegro/unicode.cpp
  A engines/ags/lib/allegro/unicode.h
  R engines/ags/stubs/allegro.cpp
  R engines/ags/stubs/allegro.h
  R engines/ags/stubs/allegro/alconfig.h
  R engines/ags/stubs/allegro/base.h
  R engines/ags/stubs/allegro/color.cpp
  R engines/ags/stubs/allegro/color.h
  R engines/ags/stubs/allegro/config.cpp
  R engines/ags/stubs/allegro/config.h
  R engines/ags/stubs/allegro/digi.cpp
  R engines/ags/stubs/allegro/digi.h
  R engines/ags/stubs/allegro/error.cpp
  R engines/ags/stubs/allegro/error.h
  R engines/ags/stubs/allegro/file.cpp
  R engines/ags/stubs/allegro/file.h
  R engines/ags/stubs/allegro/fixed.cpp
  R engines/ags/stubs/allegro/fixed.h
  R engines/ags/stubs/allegro/gfx.cpp
  R engines/ags/stubs/allegro/gfx.h
  R engines/ags/stubs/allegro/keyboard.cpp
  R engines/ags/stubs/allegro/keyboard.h
  R engines/ags/stubs/allegro/midi.cpp
  R engines/ags/stubs/allegro/midi.h
  R engines/ags/stubs/allegro/mouse.cpp
  R engines/ags/stubs/allegro/mouse.h
  R engines/ags/stubs/allegro/sound.cpp
  R engines/ags/stubs/allegro/sound.h
  R engines/ags/stubs/allegro/system.cpp
  R engines/ags/stubs/allegro/system.h
  R engines/ags/stubs/allegro/unicode.cpp
  R engines/ags/stubs/allegro/unicode.h
    engines/ags/engine/ac/global_video.cpp
    engines/ags/engine/ac/keycode.cpp
    engines/ags/engine/gfx/ali3dsw.h
    engines/ags/engine/gfx/ogl_headers.h
    engines/ags/engine/platform/android/acpland.cpp
    engines/ags/engine/platform/ios/acplios.cpp
    engines/ags/engine/platform/linux/acpllnx.cpp
    engines/ags/engine/platform/windows/acplwin.cpp
    engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
    engines/ags/engine/platform/windows/gfx/ali3dd3d.h
    engines/ags/engine/platform/windows/media/video/acwavi.cpp
    engines/ags/engine/platform/windows/media/video/acwavi3d.cpp
    engines/ags/engine/platform/windows/win_ex_handling.cpp
    engines/ags/lib/aastr-0.1.1/aastr.h
    engines/ags/lib/aastr-0.1.1/aautil.h
    engines/ags/module.mk
    engines/ags/shared/gfx/allegrobitmap.h
    engines/ags/shared/gfx/image.cpp
    engines/ags/shared/gfx/image.h
    engines/ags/shared/util/misc.cpp
    engines/ags/shared/util/path.cpp
    engines/ags/shared/util/string_utils.cpp
    engines/ags/shared/util/wgt2allg.cpp
    engines/ags/shared/util/wgt2allg.h


diff --git a/engines/ags/engine/ac/global_video.cpp b/engines/ags/engine/ac/global_video.cpp
index 718e91fbde..1629b1cf8f 100644
--- a/engines/ags/engine/ac/global_video.cpp
+++ b/engines/ags/engine/ac/global_video.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/stubs/allegro.h"
+#include "ags/lib/allegro.h"
 #include "ac/gamesetup.h"
 #include "ac/gamestate.h"
 #include "ac/global_audio.h"
diff --git a/engines/ags/engine/ac/keycode.cpp b/engines/ags/engine/ac/keycode.cpp
index 6e05ca1853..e938b14ef6 100644
--- a/engines/ags/engine/ac/keycode.cpp
+++ b/engines/ags/engine/ac/keycode.cpp
@@ -22,7 +22,7 @@
 
 #include "ac/keycode.h"
 
-#include "ags/stubs/allegro.h"
+#include "ags/lib/allegro.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gfx/ali3dsw.h b/engines/ags/engine/gfx/ali3dsw.h
index e46b5f4cc2..54bfc93d90 100644
--- a/engines/ags/engine/gfx/ali3dsw.h
+++ b/engines/ags/engine/gfx/ali3dsw.h
@@ -34,7 +34,7 @@
 #include "core/platform.h"
 #define AGS_DDRAW_GAMMA_CONTROL (AGS_PLATFORM_OS_WINDOWS)
 
-#include "ags/stubs/allegro.h"
+#include "ags/lib/allegro.h"
 
 #if AGS_DDRAW_GAMMA_CONTROL
 #include <winalleg.h>
diff --git a/engines/ags/engine/gfx/ogl_headers.h b/engines/ags/engine/gfx/ogl_headers.h
index 595b4647b5..b4f3c2f222 100644
--- a/engines/ags/engine/gfx/ogl_headers.h
+++ b/engines/ags/engine/gfx/ogl_headers.h
@@ -29,7 +29,7 @@
 #include "core/platform.h"
 
 #if AGS_PLATFORM_OS_WINDOWS
-#include "ags/stubs/allegro.h"
+#include "ags/lib/allegro.h"
 #include <winalleg.h>
 #include <allegro/platform/aintwin.h>
 
@@ -37,7 +37,7 @@
 #include "glad/glad_wgl.h"
 
 #elif AGS_PLATFORM_OS_LINUX
-#include "ags/stubs/allegro.h"
+#include "ags/lib/allegro.h"
 #include <xalleg.h>
 #include <X11/Xatom.h>
 
diff --git a/engines/ags/engine/platform/android/acpland.cpp b/engines/ags/engine/platform/android/acpland.cpp
index 3b191305b5..a3f24a8c1f 100644
--- a/engines/ags/engine/platform/android/acpland.cpp
+++ b/engines/ags/engine/platform/android/acpland.cpp
@@ -24,7 +24,7 @@
 
 #if AGS_PLATFORM_OS_ANDROID
 
-#include "ags/stubs/allegro.h"
+#include "ags/lib/allegro.h"
 #include "platform/base/agsplatformdriver.h"
 #include "ac/runtime_defines.h"
 #include "main/config.h"
diff --git a/engines/ags/engine/platform/ios/acplios.cpp b/engines/ags/engine/platform/ios/acplios.cpp
index a00f5aa2d4..8134a608ea 100644
--- a/engines/ags/engine/platform/ios/acplios.cpp
+++ b/engines/ags/engine/platform/ios/acplios.cpp
@@ -29,7 +29,7 @@
 #include <sys/stat.h>
 #include <ctype.h>
 
-#include "ags/stubs/allegro.h"
+#include "ags/lib/allegro.h"
 #include "platform/base/agsplatformdriver.h"
 #include "ac/runtime_defines.h"
 #include "main/config.h"
diff --git a/engines/ags/engine/platform/linux/acpllnx.cpp b/engines/ags/engine/platform/linux/acpllnx.cpp
index 826d0a39d3..3adccfd820 100644
--- a/engines/ags/engine/platform/linux/acpllnx.cpp
+++ b/engines/ags/engine/platform/linux/acpllnx.cpp
@@ -27,7 +27,7 @@
 // ********* LINUX PLACEHOLDER DRIVER *********
 
 #include <stdio.h>
-#include "ags/stubs/allegro.h"
+#include "ags/lib/allegro.h"
 #include <xalleg.h>
 #include "ac/runtime_defines.h"
 #include "gfx/gfxdefines.h"
diff --git a/engines/ags/engine/platform/windows/acplwin.cpp b/engines/ags/engine/platform/windows/acplwin.cpp
index d585c214bb..ccf9dc00c5 100644
--- a/engines/ags/engine/platform/windows/acplwin.cpp
+++ b/engines/ags/engine/platform/windows/acplwin.cpp
@@ -27,7 +27,7 @@
 // ********* WINDOWS *********
 
 #include <string.h>
-#include "ags/stubs/allegro.h"
+#include "ags/lib/allegro.h"
 #include <allegro/platform/aintwin.h>
 #include "ac/common.h"
 #include "ac/draw.h"
diff --git a/engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp b/engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
index 44cdc82d7d..93c926e8c0 100644
--- a/engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
+++ b/engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
@@ -32,7 +32,7 @@
 
 #include "platform/windows/gfx/ali3dd3d.h"
 
-#include "ags/stubs/allegro.h"
+#include "ags/lib/allegro.h"
 #include <allegro/platform/aintwin.h>
 #include "ac/timer.h"
 #include "debug/assert.h"
diff --git a/engines/ags/engine/platform/windows/gfx/ali3dd3d.h b/engines/ags/engine/platform/windows/gfx/ali3dd3d.h
index ed7fdc3924..1d5abbebe4 100644
--- a/engines/ags/engine/platform/windows/gfx/ali3dd3d.h
+++ b/engines/ags/engine/platform/windows/gfx/ali3dd3d.h
@@ -36,7 +36,7 @@
 #endif
 
 #include <memory>
-#include "ags/stubs/allegro.h"
+#include "ags/lib/allegro.h"
 #include <winalleg.h>
 #include <d3d9.h>
 #include "gfx/bitmap.h"
diff --git a/engines/ags/engine/platform/windows/media/video/acwavi.cpp b/engines/ags/engine/platform/windows/media/video/acwavi.cpp
index 741ab58b48..fe9a62160d 100644
--- a/engines/ags/engine/platform/windows/media/video/acwavi.cpp
+++ b/engines/ags/engine/platform/windows/media/video/acwavi.cpp
@@ -33,7 +33,7 @@
 #if AGS_PLATFORM_OS_WINDOWS && ! defined (AGS_NO_VIDEO_PLAYER)
 
 //#define ALLEGRO_STATICLINK  // already defined in project settings
-#include "ags/stubs/allegro.h"
+#include "ags/lib/allegro.h"
 #include <winalleg.h>
 #include <windows.h>
 #include <stdlib.h>
diff --git a/engines/ags/engine/platform/windows/media/video/acwavi3d.cpp b/engines/ags/engine/platform/windows/media/video/acwavi3d.cpp
index 0d6cab1fe1..e49ef7c05c 100644
--- a/engines/ags/engine/platform/windows/media/video/acwavi3d.cpp
+++ b/engines/ags/engine/platform/windows/media/video/acwavi3d.cpp
@@ -32,7 +32,7 @@
 #if AGS_PLATFORM_OS_WINDOWS && ! defined (AGS_NO_VIDEO_PLAYER)
 
 //#define ALLEGRO_STATICLINK  // already defined in project settings
-#include "ags/stubs/allegro.h"
+#include "ags/lib/allegro.h"
 #include <winalleg.h>
 #include <allegro/platform/aintwin.h>
 #include <d3d9.h>
diff --git a/engines/ags/engine/platform/windows/win_ex_handling.cpp b/engines/ags/engine/platform/windows/win_ex_handling.cpp
index c8aba200f5..c59d7e3456 100644
--- a/engines/ags/engine/platform/windows/win_ex_handling.cpp
+++ b/engines/ags/engine/platform/windows/win_ex_handling.cpp
@@ -24,7 +24,7 @@
 
 #if AGS_PLATFORM_OS_WINDOWS
 #include <new.h>
-#include "ags/stubs/allegro.h"
+#include "ags/lib/allegro.h"
 #include <winalleg.h>
 #include "ac/common.h"
 #include "ac/common_defines.h"
diff --git a/engines/ags/lib/aastr-0.1.1/aastr.h b/engines/ags/lib/aastr-0.1.1/aastr.h
index 3a85ca1a73..05a082e40c 100644
--- a/engines/ags/lib/aastr-0.1.1/aastr.h
+++ b/engines/ags/lib/aastr-0.1.1/aastr.h
@@ -38,7 +38,7 @@
 #ifndef AGS_LIB_AASTR_AASTR_H
 #define AGS_LIB_AASTR_AASTR_H
 
-#include "ags/stubs/allegro.h"
+#include "ags/lib/allegro.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/lib/aastr-0.1.1/aautil.h b/engines/ags/lib/aastr-0.1.1/aautil.h
index 81b1f97fec..8616f8c286 100644
--- a/engines/ags/lib/aastr-0.1.1/aautil.h
+++ b/engines/ags/lib/aastr-0.1.1/aautil.h
@@ -38,7 +38,7 @@
 #ifndef AGS_LIB_AASTR_AAUTIL_H
 #define AGS_LIB_AASTR_AAUTIL_H
 
-#include "ags/stubs/allegro.h"
+#include "ags/lib/allegro.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/stubs/allegro.cpp b/engines/ags/lib/allegro.cpp
similarity index 97%
rename from engines/ags/stubs/allegro.cpp
rename to engines/ags/lib/allegro.cpp
index 93a597c56f..90365ef825 100644
--- a/engines/ags/stubs/allegro.cpp
+++ b/engines/ags/lib/allegro.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/stubs/allegro.h"
+#include "ags/lib/allegro.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/stubs/allegro.h b/engines/ags/lib/allegro.h
similarity index 66%
rename from engines/ags/stubs/allegro.h
rename to engines/ags/lib/allegro.h
index 6d3aed6b22..09d26765d7 100644
--- a/engines/ags/stubs/allegro.h
+++ b/engines/ags/lib/allegro.h
@@ -23,21 +23,21 @@
 #ifndef AGS_STUBS_ALLEGRO_H
 #define AGS_STUBS_ALLEGRO_H
 
-#include "ags/stubs/allegro/alconfig.h"
-#include "ags/stubs/allegro/base.h"
-#include "ags/stubs/allegro/color.h"
-#include "ags/stubs/allegro/config.h"
-#include "ags/stubs/allegro/digi.h"
-#include "ags/stubs/allegro/error.h"
-#include "ags/stubs/allegro/file.h"
-#include "ags/stubs/allegro/fixed.h"
-#include "ags/stubs/allegro/gfx.h"
-#include "ags/stubs/allegro/keyboard.h"
-#include "ags/stubs/allegro/midi.h"
-#include "ags/stubs/allegro/mouse.h"
-#include "ags/stubs/allegro/sound.h"
-#include "ags/stubs/allegro/system.h"
-#include "ags/stubs/allegro/unicode.h"
+#include "ags/lib/allegro/alconfig.h"
+#include "ags/lib/allegro/base.h"
+#include "ags/lib/allegro/color.h"
+#include "ags/lib/allegro/config.h"
+#include "ags/lib/allegro/digi.h"
+#include "ags/lib/allegro/error.h"
+#include "ags/lib/allegro/file.h"
+#include "ags/lib/allegro/fixed.h"
+#include "ags/lib/allegro/gfx.h"
+#include "ags/lib/allegro/keyboard.h"
+#include "ags/lib/allegro/midi.h"
+#include "ags/lib/allegro/mouse.h"
+#include "ags/lib/allegro/sound.h"
+#include "ags/lib/allegro/system.h"
+#include "ags/lib/allegro/unicode.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/stubs/allegro/alconfig.h b/engines/ags/lib/allegro/alconfig.h
similarity index 100%
rename from engines/ags/stubs/allegro/alconfig.h
rename to engines/ags/lib/allegro/alconfig.h
diff --git a/engines/ags/stubs/allegro/base.h b/engines/ags/lib/allegro/base.h
similarity index 100%
rename from engines/ags/stubs/allegro/base.h
rename to engines/ags/lib/allegro/base.h
diff --git a/engines/ags/stubs/allegro/color.cpp b/engines/ags/lib/allegro/color.cpp
similarity index 98%
rename from engines/ags/stubs/allegro/color.cpp
rename to engines/ags/lib/allegro/color.cpp
index f096998d42..45a994e7f7 100644
--- a/engines/ags/stubs/allegro/color.cpp
+++ b/engines/ags/lib/allegro/color.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/stubs/allegro/color.h"
+#include "ags/lib/allegro/color.h"
 #include "common/textconsole.h"
 #include "common/system.h"
 #include "graphics/palette.h"
diff --git a/engines/ags/stubs/allegro/color.h b/engines/ags/lib/allegro/color.h
similarity index 98%
rename from engines/ags/stubs/allegro/color.h
rename to engines/ags/lib/allegro/color.h
index de8ab5b14b..d08762f8de 100644
--- a/engines/ags/stubs/allegro/color.h
+++ b/engines/ags/lib/allegro/color.h
@@ -24,7 +24,7 @@
 #define AGS_STUBS_ALLEGRO_COLOR_H
 
 #include "common/scummsys.h"
-#include "ags/stubs/allegro/alconfig.h"
+#include "ags/lib/allegro/alconfig.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/stubs/allegro/config.cpp b/engines/ags/lib/allegro/config.cpp
similarity index 96%
rename from engines/ags/stubs/allegro/config.cpp
rename to engines/ags/lib/allegro/config.cpp
index 537f86e439..390f17332e 100644
--- a/engines/ags/stubs/allegro/config.cpp
+++ b/engines/ags/lib/allegro/config.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/stubs/allegro/config.h"
+#include "ags/lib/allegro/config.h"
 #include "common/textconsole.h"
 
 namespace AGS3 {
diff --git a/engines/ags/stubs/allegro/config.h b/engines/ags/lib/allegro/config.h
similarity index 100%
rename from engines/ags/stubs/allegro/config.h
rename to engines/ags/lib/allegro/config.h
diff --git a/engines/ags/stubs/allegro/digi.cpp b/engines/ags/lib/allegro/digi.cpp
similarity index 96%
rename from engines/ags/stubs/allegro/digi.cpp
rename to engines/ags/lib/allegro/digi.cpp
index 07ba5ecfda..c3dbacf4ba 100644
--- a/engines/ags/stubs/allegro/digi.cpp
+++ b/engines/ags/lib/allegro/digi.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/stubs/allegro/digi.h"
+#include "ags/lib/allegro/digi.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/stubs/allegro/digi.h b/engines/ags/lib/allegro/digi.h
similarity index 98%
rename from engines/ags/stubs/allegro/digi.h
rename to engines/ags/lib/allegro/digi.h
index 0dc8d44ade..7eeaa72382 100644
--- a/engines/ags/stubs/allegro/digi.h
+++ b/engines/ags/lib/allegro/digi.h
@@ -24,8 +24,8 @@
 #define AGS_STUBS_ALLEGRO_DIGI_H
 
 #include "common/scummsys.h"
-#include "ags/stubs/allegro/base.h"
-#include "ags/stubs/allegro/alconfig.h"
+#include "ags/lib/allegro/base.h"
+#include "ags/lib/allegro/alconfig.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/stubs/allegro/error.cpp b/engines/ags/lib/allegro/error.cpp
similarity index 96%
rename from engines/ags/stubs/allegro/error.cpp
rename to engines/ags/lib/allegro/error.cpp
index 25105d9461..4c78014fb3 100644
--- a/engines/ags/stubs/allegro/error.cpp
+++ b/engines/ags/lib/allegro/error.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/stubs/allegro/error.h"
+#include "ags/lib/allegro/error.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/stubs/allegro/error.h b/engines/ags/lib/allegro/error.h
similarity index 100%
rename from engines/ags/stubs/allegro/error.h
rename to engines/ags/lib/allegro/error.h
diff --git a/engines/ags/stubs/allegro/file.cpp b/engines/ags/lib/allegro/file.cpp
similarity index 97%
rename from engines/ags/stubs/allegro/file.cpp
rename to engines/ags/lib/allegro/file.cpp
index ad121f296b..8ac3f05793 100644
--- a/engines/ags/stubs/allegro/file.cpp
+++ b/engines/ags/lib/allegro/file.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/stubs/allegro/file.h"
+#include "ags/lib/allegro/file.h"
 #include "common/str.h"
 
 namespace AGS3 {
diff --git a/engines/ags/stubs/allegro/file.h b/engines/ags/lib/allegro/file.h
similarity index 100%
rename from engines/ags/stubs/allegro/file.h
rename to engines/ags/lib/allegro/file.h
diff --git a/engines/ags/stubs/allegro/fixed.cpp b/engines/ags/lib/allegro/fixed.cpp
similarity index 97%
rename from engines/ags/stubs/allegro/fixed.cpp
rename to engines/ags/lib/allegro/fixed.cpp
index 09d0343a7d..be16f6ae40 100644
--- a/engines/ags/stubs/allegro/fixed.cpp
+++ b/engines/ags/lib/allegro/fixed.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ags/stubs/allegro/fixed.h"
-#include "ags/stubs/allegro/error.h"
+#include "ags/lib/allegro/fixed.h"
+#include "ags/lib/allegro/error.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/stubs/allegro/fixed.h b/engines/ags/lib/allegro/fixed.h
similarity index 100%
rename from engines/ags/stubs/allegro/fixed.h
rename to engines/ags/lib/allegro/fixed.h
diff --git a/engines/ags/stubs/allegro/gfx.cpp b/engines/ags/lib/allegro/gfx.cpp
similarity index 99%
rename from engines/ags/stubs/allegro/gfx.cpp
rename to engines/ags/lib/allegro/gfx.cpp
index 0aec33c9f9..e5ccd68ec8 100644
--- a/engines/ags/stubs/allegro/gfx.cpp
+++ b/engines/ags/lib/allegro/gfx.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/stubs/allegro/gfx.h"
+#include "ags/lib/allegro/gfx.h"
 #include "common/textconsole.h"
 #include "graphics/screen.h"
 
diff --git a/engines/ags/stubs/allegro/gfx.h b/engines/ags/lib/allegro/gfx.h
similarity index 99%
rename from engines/ags/stubs/allegro/gfx.h
rename to engines/ags/lib/allegro/gfx.h
index b6f8c3be3d..cf2402acb2 100644
--- a/engines/ags/stubs/allegro/gfx.h
+++ b/engines/ags/lib/allegro/gfx.h
@@ -24,8 +24,8 @@
 #define AGS_STUBS_ALLEGRO_GRAPHICS_H
 
 #include "graphics/managed_surface.h"
-#include "ags/stubs/allegro/base.h"
-#include "ags/stubs/allegro/fixed.h"
+#include "ags/lib/allegro/base.h"
+#include "ags/lib/allegro/fixed.h"
 #include "common/array.h"
 
 namespace AGS3 {
diff --git a/engines/ags/stubs/allegro/keyboard.cpp b/engines/ags/lib/allegro/keyboard.cpp
similarity index 96%
rename from engines/ags/stubs/allegro/keyboard.cpp
rename to engines/ags/lib/allegro/keyboard.cpp
index ba014a85f5..9e0a0f638a 100644
--- a/engines/ags/stubs/allegro/keyboard.cpp
+++ b/engines/ags/lib/allegro/keyboard.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/stubs/allegro/keyboard.h"
+#include "ags/lib/allegro/keyboard.h"
 #include "common/algorithm.h"
 #include "common/textconsole.h"
 
diff --git a/engines/ags/stubs/allegro/keyboard.h b/engines/ags/lib/allegro/keyboard.h
similarity index 100%
rename from engines/ags/stubs/allegro/keyboard.h
rename to engines/ags/lib/allegro/keyboard.h
diff --git a/engines/ags/stubs/allegro/midi.cpp b/engines/ags/lib/allegro/midi.cpp
similarity index 97%
rename from engines/ags/stubs/allegro/midi.cpp
rename to engines/ags/lib/allegro/midi.cpp
index d0bab80254..7b058574ba 100644
--- a/engines/ags/stubs/allegro/midi.cpp
+++ b/engines/ags/lib/allegro/midi.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/stubs/allegro/midi.h"
+#include "ags/lib/allegro/midi.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/stubs/allegro/midi.h b/engines/ags/lib/allegro/midi.h
similarity index 98%
rename from engines/ags/stubs/allegro/midi.h
rename to engines/ags/lib/allegro/midi.h
index e1f5f2071d..66a89f0aba 100644
--- a/engines/ags/stubs/allegro/midi.h
+++ b/engines/ags/lib/allegro/midi.h
@@ -24,8 +24,8 @@
 #define AGS_STUBS_ALLEGRO_MIDI_H
 
 #include "common/scummsys.h"
-#include "ags/stubs/allegro/base.h"
-#include "ags/stubs/allegro/alconfig.h"
+#include "ags/lib/allegro/base.h"
+#include "ags/lib/allegro/alconfig.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/stubs/allegro/mouse.cpp b/engines/ags/lib/allegro/mouse.cpp
similarity index 98%
rename from engines/ags/stubs/allegro/mouse.cpp
rename to engines/ags/lib/allegro/mouse.cpp
index daa0bad28f..9c719db02f 100644
--- a/engines/ags/stubs/allegro/mouse.cpp
+++ b/engines/ags/lib/allegro/mouse.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/stubs/allegro/mouse.h"
+#include "ags/lib/allegro/mouse.h"
 #include "common/textconsole.h"
 
 namespace AGS3 {
diff --git a/engines/ags/stubs/allegro/mouse.h b/engines/ags/lib/allegro/mouse.h
similarity index 97%
rename from engines/ags/stubs/allegro/mouse.h
rename to engines/ags/lib/allegro/mouse.h
index 33538fac92..3ad8998f77 100644
--- a/engines/ags/stubs/allegro/mouse.h
+++ b/engines/ags/lib/allegro/mouse.h
@@ -24,9 +24,9 @@
 #define AGS_STUBS_ALLEGRO_MOUSE_H
 
 #include "common/events.h"
-#include "ags/stubs/allegro/base.h"
-#include "ags/stubs/allegro/alconfig.h"
-#include "ags/stubs/allegro/gfx.h"
+#include "ags/lib/allegro/base.h"
+#include "ags/lib/allegro/alconfig.h"
+#include "ags/lib/allegro/gfx.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/stubs/allegro/sound.cpp b/engines/ags/lib/allegro/sound.cpp
similarity index 98%
rename from engines/ags/stubs/allegro/sound.cpp
rename to engines/ags/lib/allegro/sound.cpp
index 5eda1fe992..a4acc0565f 100644
--- a/engines/ags/stubs/allegro/sound.cpp
+++ b/engines/ags/lib/allegro/sound.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/stubs/allegro/sound.h"
+#include "ags/lib/allegro/sound.h"
 #include "common/textconsole.h"
 
 namespace AGS3 {
diff --git a/engines/ags/stubs/allegro/sound.h b/engines/ags/lib/allegro/sound.h
similarity index 96%
rename from engines/ags/stubs/allegro/sound.h
rename to engines/ags/lib/allegro/sound.h
index fa9f64097e..d487041039 100644
--- a/engines/ags/stubs/allegro/sound.h
+++ b/engines/ags/lib/allegro/sound.h
@@ -24,8 +24,8 @@
 #define AGS_STUBS_ALLEGRO_SOUND_H
 
 #include "common/scummsys.h"
-#include "ags/stubs/allegro/base.h"
-#include "ags/stubs/allegro/alconfig.h"
+#include "ags/lib/allegro/base.h"
+#include "ags/lib/allegro/alconfig.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/stubs/allegro/system.cpp b/engines/ags/lib/allegro/system.cpp
similarity index 97%
rename from engines/ags/stubs/allegro/system.cpp
rename to engines/ags/lib/allegro/system.cpp
index 4767537379..67a6d806a4 100644
--- a/engines/ags/stubs/allegro/system.cpp
+++ b/engines/ags/lib/allegro/system.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/stubs/allegro/system.h"
+#include "ags/lib/allegro/system.h"
 #include "common/system.h"
 
 namespace AGS3 {
diff --git a/engines/ags/stubs/allegro/system.h b/engines/ags/lib/allegro/system.h
similarity index 97%
rename from engines/ags/stubs/allegro/system.h
rename to engines/ags/lib/allegro/system.h
index 0f67246006..f461d00195 100644
--- a/engines/ags/stubs/allegro/system.h
+++ b/engines/ags/lib/allegro/system.h
@@ -23,9 +23,9 @@
 #ifndef AGS_STUBS_ALLEGRO_SYSTEM_H
 #define AGS_STUBS_ALLEGRO_SYSTEM_H
 
-#include "ags/stubs/allegro/base.h"
-#include "ags/stubs/allegro/color.h"
-#include "ags/stubs/allegro/gfx.h"
+#include "ags/lib/allegro/base.h"
+#include "ags/lib/allegro/color.h"
+#include "ags/lib/allegro/gfx.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/stubs/allegro/unicode.cpp b/engines/ags/lib/allegro/unicode.cpp
similarity index 96%
rename from engines/ags/stubs/allegro/unicode.cpp
rename to engines/ags/lib/allegro/unicode.cpp
index 36372960e2..073fda45ec 100644
--- a/engines/ags/stubs/allegro/unicode.cpp
+++ b/engines/ags/lib/allegro/unicode.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/stubs/allegro/unicode.h"
+#include "ags/lib/allegro/unicode.h"
 #include "common/textconsole.h"
 
 namespace AGS3 {
diff --git a/engines/ags/stubs/allegro/unicode.h b/engines/ags/lib/allegro/unicode.h
similarity index 97%
rename from engines/ags/stubs/allegro/unicode.h
rename to engines/ags/lib/allegro/unicode.h
index 24e84d913a..48667d7f8a 100644
--- a/engines/ags/stubs/allegro/unicode.h
+++ b/engines/ags/lib/allegro/unicode.h
@@ -23,7 +23,7 @@
 #ifndef AGS_STUBS_ALLEGRO_UNICODE_H
 #define AGS_STUBS_ALLEGRO_UNICODE_H
 
-#include "ags/stubs/allegro/base.h"
+#include "ags/lib/allegro/base.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 148852c3cd..f87f6cbd10 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -6,20 +6,20 @@ MODULE_OBJS = \
 	lib/aastr-0.1.1/aarot.o \
 	lib/aastr-0.1.1/aastr.o \
 	lib/aastr-0.1.1/aautil.o \
-	stubs/allegro.o \
-	stubs/allegro/color.o \
-	stubs/allegro/config.o \
-	stubs/allegro/digi.o \
-	stubs/allegro/error.o \
-	stubs/allegro/file.o \
-	stubs/allegro/fixed.o \
-	stubs/allegro/gfx.o \
-	stubs/allegro/keyboard.o \
-	stubs/allegro/midi.o \
-	stubs/allegro/mouse.o \
-	stubs/allegro/sound.o \
-	stubs/allegro/system.o \
-	stubs/allegro/unicode.o \
+	lib/allegro.o \
+	lib/allegro/color.o \
+	lib/allegro/config.o \
+	lib/allegro/digi.o \
+	lib/allegro/error.o \
+	lib/allegro/file.o \
+	lib/allegro/fixed.o \
+	lib/allegro/gfx.o \
+	lib/allegro/keyboard.o \
+	lib/allegro/midi.o \
+	lib/allegro/mouse.o \
+	lib/allegro/sound.o \
+	lib/allegro/system.o \
+	lib/allegro/unicode.o \
 	shared/gfx/allegrobitmap.o \
 	shared/gfx/bitmap.o \
 	shared/gfx/image.o \
diff --git a/engines/ags/shared/gfx/allegrobitmap.h b/engines/ags/shared/gfx/allegrobitmap.h
index f59f346dae..37ba3fcd97 100644
--- a/engines/ags/shared/gfx/allegrobitmap.h
+++ b/engines/ags/shared/gfx/allegrobitmap.h
@@ -32,7 +32,7 @@
 #ifndef AGS_SHARED_GFX_ALLEGROBITMAP_H
 #define AGS_SHARED_GFX_ALLEGROBITMAP_H
 
-#include "ags/stubs/allegro.h"
+#include "ags/lib/allegro.h"
 #include "ags/shared/core/types.h"
 #include "ags/shared/gfx/bitmap.h"
 #include "ags/shared/util/geometry.h"
diff --git a/engines/ags/shared/gfx/image.cpp b/engines/ags/shared/gfx/image.cpp
index b77e08286c..8de490b338 100644
--- a/engines/ags/shared/gfx/image.cpp
+++ b/engines/ags/shared/gfx/image.cpp
@@ -21,7 +21,7 @@
  */
 
 #include "ags/shared/gfx/image.h"
-#include "ags/stubs/allegro.h"
+#include "ags/lib/allegro.h"
 #include "common/str.h"
 #include "common/textconsole.h"
 
diff --git a/engines/ags/shared/gfx/image.h b/engines/ags/shared/gfx/image.h
index a37358fa25..592009ec01 100644
--- a/engines/ags/shared/gfx/image.h
+++ b/engines/ags/shared/gfx/image.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_GFX_IMAGE_H
 #define AGS_SHARED_GFX_IMAGE_H
 
-#include "ags/stubs/allegro.h"
+#include "ags/lib/allegro.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/util/misc.cpp b/engines/ags/shared/util/misc.cpp
index 1bdad6992d..f499d29794 100644
--- a/engines/ags/shared/util/misc.cpp
+++ b/engines/ags/shared/util/misc.cpp
@@ -59,7 +59,7 @@
 //include <dirent.h>
 #endif
 
-#include "ags/stubs/allegro.h"
+#include "ags/lib/allegro.h"
 #include "ags/shared/util/file.h"
 #include "ags/shared/util/stream.h"
 
diff --git a/engines/ags/shared/util/path.cpp b/engines/ags/shared/util/path.cpp
index 763808bf2b..495ddb23db 100644
--- a/engines/ags/shared/util/path.cpp
+++ b/engines/ags/shared/util/path.cpp
@@ -25,7 +25,7 @@
 //include <windows.h>
 #endif
 
-#include "ags/stubs/allegro/file.h"
+#include "ags/lib/allegro/file.h"
 #include "ags/shared/util/path.h"
 #include "ags/shared/util/stdio_compat.h"
 
diff --git a/engines/ags/shared/util/string_utils.cpp b/engines/ags/shared/util/string_utils.cpp
index 16eeaccf47..9d33819956 100644
--- a/engines/ags/shared/util/string_utils.cpp
+++ b/engines/ags/shared/util/string_utils.cpp
@@ -26,7 +26,7 @@
 #include "ags/shared/util/math.h"
 #include "ags/shared/util/string_utils.h"
 #include "ags/shared/util/stream.h"
-#include "ags/stubs/allegro/error.h"
+#include "ags/lib/allegro/error.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/util/wgt2allg.cpp b/engines/ags/shared/util/wgt2allg.cpp
index ea5067d79a..80793adb9c 100644
--- a/engines/ags/shared/util/wgt2allg.cpp
+++ b/engines/ags/shared/util/wgt2allg.cpp
@@ -25,7 +25,7 @@
 #include "ags/shared/gfx/allegrobitmap.h"
 #include "ags/shared/util/stream.h"
 #include "ags/shared/util/wgt2allg.h"
-#include "ags/stubs/allegro.h"
+#include "ags/lib/allegro.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/util/wgt2allg.h b/engines/ags/shared/util/wgt2allg.h
index 0302f118b0..6126da9591 100644
--- a/engines/ags/shared/util/wgt2allg.h
+++ b/engines/ags/shared/util/wgt2allg.h
@@ -34,7 +34,7 @@
 #define _WGT45_
 
 #include "ags/shared/core/platform.h"
-#include "ags/stubs/allegro.h"
+#include "ags/lib/allegro.h"
 
 namespace AGS3 {
 


Commit: f4544dff7ad8bc2efdc4b3ef4c1e57b8699a9fae
    https://github.com/scummvm/scummvm/commit/f4544dff7ad8bc2efdc4b3ef4c1e57b8699a9fae
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added shared/ac/ folder

Changed paths:
    engines/ags/module.mk
    engines/ags/shared/ac/audiocliptype.cpp
    engines/ags/shared/ac/audiocliptype.h
    engines/ags/shared/ac/characterinfo.h
    engines/ags/shared/ac/dialogtopic.cpp
    engines/ags/shared/ac/dialogtopic.h
    engines/ags/shared/ac/dynobj/scriptaudioclip.h
    engines/ags/shared/ac/gamesetupstruct.cpp
    engines/ags/shared/ac/gamesetupstruct.h
    engines/ags/shared/ac/gamesetupstructbase.h
    engines/ags/shared/ac/inventoryiteminfo.h
    engines/ags/shared/ac/mousecursor.h
    engines/ags/shared/ac/spritecache.cpp
    engines/ags/shared/ac/spritecache.h
    engines/ags/shared/ac/view.cpp
    engines/ags/shared/ac/view.h
    engines/ags/shared/ac/wordsdictionary.cpp
    engines/ags/shared/ac/wordsdictionary.h
    engines/ags/shared/core/asset.h
    engines/ags/shared/debugging/debugmanager.h
    engines/ags/shared/font/fonts.cpp
    engines/ags/shared/font/fonts.h
    engines/ags/shared/font/wfnfont.cpp
    engines/ags/shared/font/wfnfont.h
    engines/ags/shared/game/customproperties.cpp
    engines/ags/shared/game/customproperties.h
    engines/ags/shared/game/interactions.cpp
    engines/ags/shared/game/interactions.h
    engines/ags/shared/game/main_game_file.h
    engines/ags/shared/game/plugininfo.h
    engines/ags/shared/game/room_file.cpp
    engines/ags/shared/game/room_file.h
    engines/ags/shared/game/roomstruct.h
    engines/ags/shared/gui/guibutton.h
    engines/ags/shared/gui/guiinv.h
    engines/ags/shared/gui/guilabel.h
    engines/ags/shared/gui/guilistbox.h
    engines/ags/shared/gui/guislider.h
    engines/ags/shared/gui/guitextbox.h


diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index f87f6cbd10..f039ffe63f 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -20,6 +20,18 @@ MODULE_OBJS = \
 	lib/allegro/sound.o \
 	lib/allegro/system.o \
 	lib/allegro/unicode.o \
+	shared/ac/dynobj/scriptaudioclip.o \
+	shared/ac/audiocliptype.o \
+	shared/ac/characterinfo.o \
+	shared/ac/common.o \
+	shared/ac/dialogtopic.o \
+	shared/ac/gamesetupstruct.o \
+	shared/ac/gamesetupstructbase.o \
+	shared/ac/inventoryiteminfo.o \
+	shared/ac/mousecursor.o \
+	shared/ac/spritecache.o \
+	shared/ac/view.o \
+	shared/ac/wordsdictionary.o \
 	shared/gfx/allegrobitmap.o \
 	shared/gfx/bitmap.o \
 	shared/gfx/image.o \
diff --git a/engines/ags/shared/ac/audiocliptype.cpp b/engines/ags/shared/ac/audiocliptype.cpp
index a1de83d396..4417559e33 100644
--- a/engines/ags/shared/ac/audiocliptype.cpp
+++ b/engines/ags/shared/ac/audiocliptype.cpp
@@ -43,12 +43,12 @@ void AudioClipType::WriteToFile(Stream *out) {
 	out->WriteInt32(reservedForFuture);
 }
 
-void AudioClipType::ReadFromSavegame(Common::Stream *in) {
+void AudioClipType::ReadFromSavegame(Stream *in) {
 	volume_reduction_while_speech_playing = in->ReadInt32();
 	crossfadeSpeed = in->ReadInt32();
 }
 
-void AudioClipType::WriteToSavegame(Common::Stream *out) const {
+void AudioClipType::WriteToSavegame(Stream *out) const {
 	out->WriteInt32(volume_reduction_while_speech_playing);
 	out->WriteInt32(crossfadeSpeed);
 }
diff --git a/engines/ags/shared/ac/audiocliptype.h b/engines/ags/shared/ac/audiocliptype.h
index 9871c5e294..80ff9a1681 100644
--- a/engines/ags/shared/ac/audiocliptype.h
+++ b/engines/ags/shared/ac/audiocliptype.h
@@ -42,10 +42,10 @@ struct AudioClipType {
 	int crossfadeSpeed;
 	int reservedForFuture;
 
-	void ReadFromFile(Common::Stream *in);
-	void WriteToFile(Common::Stream *out);
-	void ReadFromSavegame(Common::Stream *in);
-	void WriteToSavegame(Common::Stream *out) const;
+	void ReadFromFile(Shared::Stream *in);
+	void WriteToFile(Shared::Stream *out);
+	void ReadFromSavegame(Shared::Stream *in);
+	void WriteToSavegame(Shared::Stream *out) const;
 };
 
 } // namespace AGS3
diff --git a/engines/ags/shared/ac/characterinfo.h b/engines/ags/shared/ac/characterinfo.h
index 287937994a..b8175c0062 100644
--- a/engines/ags/shared/ac/characterinfo.h
+++ b/engines/ags/shared/ac/characterinfo.h
@@ -128,8 +128,8 @@ struct CharacterInfo {
 	void update_character_idle(CharacterExtras *chex, int &doing_nothing);
 	void update_character_follower(int &char_index, int &numSheep, int *followingAsSheep, int &doing_nothing);
 
-	void ReadFromFile(Common::Stream *in);
-	void WriteToFile(Common::Stream *out);
+	void ReadFromFile(Shared::Stream *in);
+	void WriteToFile(Shared::Stream *out);
 };
 
 
diff --git a/engines/ags/shared/ac/dialogtopic.cpp b/engines/ags/shared/ac/dialogtopic.cpp
index efcbb4f2c1..546877bd0c 100644
--- a/engines/ags/shared/ac/dialogtopic.cpp
+++ b/engines/ags/shared/ac/dialogtopic.cpp
@@ -40,11 +40,11 @@ void DialogTopic::ReadFromFile(Stream *in) {
 	topicFlags = in->ReadInt32();
 }
 
-void DialogTopic::ReadFromSavegame(Common::Stream *in) {
+void DialogTopic::ReadFromSavegame(Stream *in) {
 	in->ReadArrayOfInt32(optionflags, MAXTOPICOPTIONS);
 }
 
-void DialogTopic::WriteToSavegame(Common::Stream *out) const {
+void DialogTopic::WriteToSavegame(Stream *out) const {
 	out->WriteArrayOfInt32(optionflags, MAXTOPICOPTIONS);
 }
 
diff --git a/engines/ags/shared/ac/dialogtopic.h b/engines/ags/shared/ac/dialogtopic.h
index e23d534f0f..8fb0031e10 100644
--- a/engines/ags/shared/ac/dialogtopic.h
+++ b/engines/ags/shared/ac/dialogtopic.h
@@ -70,10 +70,10 @@ struct DialogTopic {
 	int           numoptions;
 	int           topicFlags;
 
-	void ReadFromFile(Common::Stream *in);
+	void ReadFromFile(Shared::Stream *in);
 
-	void ReadFromSavegame(Common::Stream *in);
-	void WriteToSavegame(Common::Stream *out) const;
+	void ReadFromSavegame(Shared::Stream *in);
+	void WriteToSavegame(Shared::Stream *out) const;
 };
 
 } // namespace AGS3
diff --git a/engines/ags/shared/ac/dynobj/scriptaudioclip.h b/engines/ags/shared/ac/dynobj/scriptaudioclip.h
index de4361bd04..dfde8e752e 100644
--- a/engines/ags/shared/ac/dynobj/scriptaudioclip.h
+++ b/engines/ags/shared/ac/dynobj/scriptaudioclip.h
@@ -51,8 +51,8 @@ enum AudioFileType {
 #define SCRIPTAUDIOCLIP_FILENAMELENGTH      15
 struct ScriptAudioClip {
 	int id = 0;
-	Common::String scriptName;
-	Common::String fileName;
+	Shared::String scriptName;
+	Shared::String fileName;
 	char bundlingType = AUCL_BUNDLE_EXE;
 	char type = 0;
 	char fileType = eAudioFileOGG;
@@ -60,7 +60,7 @@ struct ScriptAudioClip {
 	short defaultPriority = 50;
 	short defaultVolume = 100;
 
-	void ReadFromFile(Common::Stream *in);
+	void ReadFromFile(Shared::Stream *in);
 };
 
 } // namespace AGS3
diff --git a/engines/ags/shared/ac/gamesetupstruct.cpp b/engines/ags/shared/ac/gamesetupstruct.cpp
index 4c4139c82b..73cb35d8de 100644
--- a/engines/ags/shared/ac/gamesetupstruct.cpp
+++ b/engines/ags/shared/ac/gamesetupstruct.cpp
@@ -107,7 +107,7 @@ ScriptAudioClip *GetAudioClipForOldStyleNumber(GameSetupStruct &game, bool is_mu
 //-----------------------------------------------------------------------------
 // Reading Part 1
 
-void GameSetupStruct::read_savegame_info(Common::Stream *in, GameDataVersion data_ver) {
+void GameSetupStruct::read_savegame_info(Shared::Stream *in, GameDataVersion data_ver) {
 	if (data_ver > kGameVersion_272) { // only 3.x
 		in->Read(&guid[0], MAX_GUID_LENGTH);
 		in->Read(&saveGameFileExtension[0], MAX_SG_EXT_LENGTH);
@@ -115,7 +115,7 @@ void GameSetupStruct::read_savegame_info(Common::Stream *in, GameDataVersion dat
 	}
 }
 
-void GameSetupStruct::read_font_infos(Common::Stream *in, GameDataVersion data_ver) {
+void GameSetupStruct::read_font_infos(Shared::Stream *in, GameDataVersion data_ver) {
 	fonts.resize(numfonts);
 	if (data_ver < kGameVersion_350) {
 		for (int i = 0; i < numfonts; ++i)
@@ -147,7 +147,7 @@ void GameSetupStruct::read_font_infos(Common::Stream *in, GameDataVersion data_v
 }
 
 void GameSetupStruct::ReadInvInfo_Aligned(Stream *in) {
-	AlignedStream align_s(in, Common::kAligned_Read);
+	AlignedStream align_s(in, Shared::kAligned_Read);
 	for (int iteratorCount = 0; iteratorCount < numinvitems; ++iteratorCount) {
 		invinfo[iteratorCount].ReadFromFile(&align_s);
 		align_s.Reset();
@@ -155,14 +155,14 @@ void GameSetupStruct::ReadInvInfo_Aligned(Stream *in) {
 }
 
 void GameSetupStruct::WriteInvInfo_Aligned(Stream *out) {
-	AlignedStream align_s(out, Common::kAligned_Write);
+	AlignedStream align_s(out, Shared::kAligned_Write);
 	for (int iteratorCount = 0; iteratorCount < numinvitems; ++iteratorCount) {
 		invinfo[iteratorCount].WriteToFile(&align_s);
 		align_s.Reset();
 	}
 }
 
-HGameFileError GameSetupStruct::read_cursors(Common::Stream *in, GameDataVersion data_ver) {
+HGameFileError GameSetupStruct::read_cursors(Shared::Stream *in, GameDataVersion data_ver) {
 	if (numcursors > MAX_CURSOR)
 		return new MainGameFileError(kMGFErr_TooManyCursors, String::FromFormat("Count: %d, max: %d", numcursors, MAX_CURSOR));
 
@@ -170,7 +170,7 @@ HGameFileError GameSetupStruct::read_cursors(Common::Stream *in, GameDataVersion
 	return HGameFileError::None();
 }
 
-void GameSetupStruct::read_interaction_scripts(Common::Stream *in, GameDataVersion data_ver) {
+void GameSetupStruct::read_interaction_scripts(Shared::Stream *in, GameDataVersion data_ver) {
 	numGlobalVars = 0;
 
 	if (data_ver > kGameVersion_272) { // 3.x
@@ -194,7 +194,7 @@ void GameSetupStruct::read_interaction_scripts(Common::Stream *in, GameDataVersi
 	}
 }
 
-void GameSetupStruct::read_words_dictionary(Common::Stream *in) {
+void GameSetupStruct::read_words_dictionary(Shared::Stream *in) {
 	if (load_dictionary) {
 		dict = new WordsDictionary();
 		read_dictionary(dict, in);
@@ -202,7 +202,7 @@ void GameSetupStruct::read_words_dictionary(Common::Stream *in) {
 }
 
 void GameSetupStruct::ReadMouseCursors_Aligned(Stream *in) {
-	AlignedStream align_s(in, Common::kAligned_Read);
+	AlignedStream align_s(in, Shared::kAligned_Read);
 	for (int iteratorCount = 0; iteratorCount < numcursors; ++iteratorCount) {
 		mcurs[iteratorCount].ReadFromFile(&align_s);
 		align_s.Reset();
@@ -210,7 +210,7 @@ void GameSetupStruct::ReadMouseCursors_Aligned(Stream *in) {
 }
 
 void GameSetupStruct::WriteMouseCursors_Aligned(Stream *out) {
-	AlignedStream align_s(out, Common::kAligned_Write);
+	AlignedStream align_s(out, Shared::kAligned_Write);
 	for (int iteratorCount = 0; iteratorCount < numcursors; ++iteratorCount) {
 		mcurs[iteratorCount].WriteToFile(&align_s);
 		align_s.Reset();
@@ -220,18 +220,18 @@ void GameSetupStruct::WriteMouseCursors_Aligned(Stream *out) {
 //-----------------------------------------------------------------------------
 // Reading Part 2
 
-void GameSetupStruct::read_characters(Common::Stream *in, GameDataVersion data_ver) {
+void GameSetupStruct::read_characters(Shared::Stream *in, GameDataVersion data_ver) {
 	chars = new CharacterInfo[numcharacters + 5]; // TODO: why +5, is this really needed?
 
 	ReadCharacters_Aligned(in);
 }
 
-void GameSetupStruct::read_lipsync(Common::Stream *in, GameDataVersion data_ver) {
+void GameSetupStruct::read_lipsync(Shared::Stream *in, GameDataVersion data_ver) {
 	if (data_ver >= kGameVersion_254) // lip syncing was introduced in 2.54
 		in->ReadArray(&lipSyncFrameLetters[0][0], MAXLIPSYNCFRAMES, 50);
 }
 
-void GameSetupStruct::read_messages(Common::Stream *in, GameDataVersion data_ver) {
+void GameSetupStruct::read_messages(Shared::Stream *in, GameDataVersion data_ver) {
 	for (int ee = 0; ee < MAXGLOBALMES; ee++) {
 		if (!load_messages[ee]) continue;
 		messages[ee] = new char[GLOBALMESLENGTH];
@@ -254,7 +254,7 @@ void GameSetupStruct::read_messages(Common::Stream *in, GameDataVersion data_ver
 }
 
 void GameSetupStruct::ReadCharacters_Aligned(Stream *in) {
-	AlignedStream align_s(in, Common::kAligned_Read);
+	AlignedStream align_s(in, Shared::kAligned_Read);
 	for (int iteratorCount = 0; iteratorCount < numcharacters; ++iteratorCount) {
 		chars[iteratorCount].ReadFromFile(&align_s);
 		align_s.Reset();
@@ -262,7 +262,7 @@ void GameSetupStruct::ReadCharacters_Aligned(Stream *in) {
 }
 
 void GameSetupStruct::WriteCharacters_Aligned(Stream *out) {
-	AlignedStream align_s(out, Common::kAligned_Write);
+	AlignedStream align_s(out, Shared::kAligned_Write);
 	for (int iteratorCount = 0; iteratorCount < numcharacters; ++iteratorCount) {
 		chars[iteratorCount].WriteToFile(&align_s);
 		align_s.Reset();
@@ -272,7 +272,7 @@ void GameSetupStruct::WriteCharacters_Aligned(Stream *out) {
 //-----------------------------------------------------------------------------
 // Reading Part 3
 
-HGameFileError GameSetupStruct::read_customprops(Common::Stream *in, GameDataVersion data_ver) {
+HGameFileError GameSetupStruct::read_customprops(Shared::Stream *in, GameDataVersion data_ver) {
 	dialogScriptNames.resize(numdialog);
 	viewNames.resize(numviews);
 	if (data_ver >= kGameVersion_260) { // >= 2.60
@@ -304,7 +304,7 @@ HGameFileError GameSetupStruct::read_customprops(Common::Stream *in, GameDataVer
 	return HGameFileError::None();
 }
 
-HGameFileError GameSetupStruct::read_audio(Common::Stream *in, GameDataVersion data_ver) {
+HGameFileError GameSetupStruct::read_audio(Shared::Stream *in, GameDataVersion data_ver) {
 	if (data_ver >= kGameVersion_320) {
 		size_t audiotype_count = in->ReadInt32();
 		audioClipTypes.resize(audiotype_count);
@@ -342,8 +342,8 @@ void GameSetupStruct::read_room_names(Stream *in, GameDataVersion data_ver) {
 	}
 }
 
-void GameSetupStruct::ReadAudioClips_Aligned(Common::Stream *in, size_t count) {
-	AlignedStream align_s(in, Common::kAligned_Read);
+void GameSetupStruct::ReadAudioClips_Aligned(Shared::Stream *in, size_t count) {
+	AlignedStream align_s(in, Shared::kAligned_Read);
 	for (size_t i = 0; i < count; ++i) {
 		audioClips[i].ReadFromFile(&align_s);
 		align_s.Reset();
diff --git a/engines/ags/shared/ac/gamesetupstruct.h b/engines/ags/shared/ac/gamesetupstruct.h
index 76a8be3827..af10c29ccf 100644
--- a/engines/ags/shared/ac/gamesetupstruct.h
+++ b/engines/ags/shared/ac/gamesetupstruct.h
@@ -23,7 +23,8 @@
 #ifndef AGS_SHARED_AC_GAMESETUPSTRUCT_H
 #define AGS_SHARED_AC_GAMESETUPSTRUCT_H
 
-//include <vector>
+#include "ags/std/vector.h"
+#include "ags/std/memory.h"
 #include "ags/shared/ac/audiocliptype.h"
 #include "ags/shared/ac/characterinfo.h" // TODO: constants to separate header
 #include "ags/shared/ac/gamesetupstructbase.h"
@@ -36,10 +37,10 @@
 namespace AGS3 {
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 struct AssetLibInfo;
 struct Interaction;
-namespace SharedonScripts;
+struct InteractionScripts;
 typedef std::shared_ptr<Interaction> PInteraction;
 typedef std::shared_ptr<InteractionScripts> PInteractionScripts;
 } // namespace Shared
@@ -128,39 +129,39 @@ struct GameSetupStruct : public GameSetupStructBase {
 	// Do not call these directly
 	//------------------------------
 	// Part 1
-	void read_savegame_info(Common::Stream *in, GameDataVersion data_ver);
-	void read_font_infos(Common::Stream *in, GameDataVersion data_ver);
-	HGameFileError read_cursors(Common::Stream *in, GameDataVersion data_ver);
-	void read_interaction_scripts(Common::Stream *in, GameDataVersion data_ver);
-	void read_words_dictionary(Common::Stream *in);
-
-	void ReadInvInfo_Aligned(Common::Stream *in);
-	void WriteInvInfo_Aligned(Common::Stream *out);
-	void ReadMouseCursors_Aligned(Common::Stream *in);
-	void WriteMouseCursors_Aligned(Common::Stream *out);
+	void read_savegame_info(Shared::Stream *in, GameDataVersion data_ver);
+	void read_font_infos(Shared::Stream *in, GameDataVersion data_ver);
+	HGameFileError read_cursors(Shared::Stream *in, GameDataVersion data_ver);
+	void read_interaction_scripts(Shared::Stream *in, GameDataVersion data_ver);
+	void read_words_dictionary(Shared::Stream *in);
+
+	void ReadInvInfo_Aligned(Shared::Stream *in);
+	void WriteInvInfo_Aligned(Shared::Stream *out);
+	void ReadMouseCursors_Aligned(Shared::Stream *in);
+	void WriteMouseCursors_Aligned(Shared::Stream *out);
 	//------------------------------
 	// Part 2
-	void read_characters(Common::Stream *in, GameDataVersion data_ver);
-	void read_lipsync(Common::Stream *in, GameDataVersion data_ver);
-	void read_messages(Common::Stream *in, GameDataVersion data_ver);
+	void read_characters(Shared::Stream *in, GameDataVersion data_ver);
+	void read_lipsync(Shared::Stream *in, GameDataVersion data_ver);
+	void read_messages(Shared::Stream *in, GameDataVersion data_ver);
 
-	void ReadCharacters_Aligned(Common::Stream *in);
-	void WriteCharacters_Aligned(Common::Stream *out);
+	void ReadCharacters_Aligned(Shared::Stream *in);
+	void WriteCharacters_Aligned(Shared::Stream *out);
 	//------------------------------
 	// Part 3
-	HGameFileError read_customprops(Common::Stream *in, GameDataVersion data_ver);
-	HGameFileError read_audio(Common::Stream *in, GameDataVersion data_ver);
-	void read_room_names(Common::Stream *in, GameDataVersion data_ver);
+	HGameFileError read_customprops(Shared::Stream *in, GameDataVersion data_ver);
+	HGameFileError read_audio(Shared::Stream *in, GameDataVersion data_ver);
+	void read_room_names(Shared::Stream *in, GameDataVersion data_ver);
 
-	void ReadAudioClips_Aligned(Common::Stream *in, size_t count);
+	void ReadAudioClips_Aligned(Shared::Stream *in, size_t count);
 	//--------------------------------------------------------------------
 
 	// Functions for reading and writing appropriate data from/to save game
-	void ReadFromSaveGame_v321(Common::Stream *in, char *gswas, ccScript *compsc, CharacterInfo *chwas,
+	void ReadFromSaveGame_v321(Shared::Stream *in, char *gswas, ccScript *compsc, CharacterInfo *chwas,
 		WordsDictionary *olddict, char **mesbk);
 
-	void ReadFromSavegame(Common::PStream in);
-	void WriteForSavegame(Common::PStream out);
+	void ReadFromSavegame(Shared::PStream in);
+	void WriteForSavegame(Shared::PStream out);
 };
 
 //=============================================================================
diff --git a/engines/ags/shared/ac/gamesetupstructbase.h b/engines/ags/shared/ac/gamesetupstructbase.h
index 045b751634..41656ed5ee 100644
--- a/engines/ags/shared/ac/gamesetupstructbase.h
+++ b/engines/ags/shared/ac/gamesetupstructbase.h
@@ -70,13 +70,13 @@ struct GameSetupStructBase {
 	int               default_lipsync_frame; // used for unknown chars
 	int               invhotdotsprite;
 	int               reserved[NUM_INTS_RESERVED];
-	char             *messages[MAXGLOBALMES];
-	WordsDictionary  *dict;
-	char             *globalscript;
-	CharacterInfo    *chars;
-	ccScript         *compiled_script;
+	char *messages[MAXGLOBALMES];
+	WordsDictionary *dict;
+	char *globalscript;
+	CharacterInfo *chars;
+	ccScript *compiled_script;
 
-	int             *load_messages;
+	int *load_messages;
 	bool             load_dictionary;
 	bool             load_compiled_script;
 	// [IKM] 2013-03-30
@@ -91,8 +91,8 @@ struct GameSetupStructBase {
 	void SetDefaultResolution(Size game_res);
 	void SetGameResolution(GameResolutionType type);
 	void SetGameResolution(Size game_res);
-	void ReadFromFile(Common::Stream *in);
-	void WriteToFile(Common::Stream *out);
+	void ReadFromFile(Shared::Stream *in);
+	void WriteToFile(Shared::Stream *out);
 
 
 	//
@@ -187,7 +187,7 @@ struct GameSetupStructBase {
 	inline bool IsLegacyHiRes() const {
 		if (_resolutionType == kGameResolution_Custom)
 			return (_gameResolution.Width * _gameResolution.Height) > (320 * 240);
-		return ::IsLegacyHiRes(_resolutionType);
+		return AGS3::IsLegacyHiRes(_resolutionType);
 	}
 	// Tells if data has coordinates in default game resolution
 	inline bool IsDataInNativeCoordinates() const {
@@ -247,6 +247,6 @@ private:
 	int _screenUpscaleMult;
 };
 
-// namespace AGS3
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/shared/ac/inventoryiteminfo.h b/engines/ags/shared/ac/inventoryiteminfo.h
index e3f1ab5779..ee4786613b 100644
--- a/engines/ags/shared/ac/inventoryiteminfo.h
+++ b/engines/ags/shared/ac/inventoryiteminfo.h
@@ -41,10 +41,10 @@ struct InventoryItemInfo {
 	int  reserved[5];
 	char flags;
 
-	void ReadFromFile(Common::Stream *in);
-	void WriteToFile(Common::Stream *out);
-	void ReadFromSavegame(Common::Stream *in);
-	void WriteToSavegame(Common::Stream *out) const;
+	void ReadFromFile(Shared::Stream *in);
+	void WriteToFile(Shared::Stream *out);
+	void ReadFromSavegame(Shared::Stream *in);
+	void WriteToSavegame(Shared::Stream *out) const;
 };
 
 } // namespace AGS3
diff --git a/engines/ags/shared/ac/mousecursor.h b/engines/ags/shared/ac/mousecursor.h
index 7ae0ef406d..9e42fa0ea0 100644
--- a/engines/ags/shared/ac/mousecursor.h
+++ b/engines/ags/shared/ac/mousecursor.h
@@ -26,10 +26,10 @@
 namespace AGS3 {
 
 namespace AGS {
-namespace Common {
+namespace Shared {
 class Stream;
 } // namespace Shared
-namespace SharedGS
+} // namespace AGS
 
 using namespace AGS; // FIXME later
 
@@ -46,10 +46,10 @@ struct MouseCursor {
 	char  flags;
 	MouseCursor();
 
-	void ReadFromFile(Common::Stream *in);
-	void WriteToFile(Common::Stream *out);
-	void ReadFromSavegame(Common::Stream *in);
-	void WriteToSavegame(Common::Stream *out) const;
+	void ReadFromFile(Shared::Stream *in);
+	void WriteToFile(Shared::Stream *out);
+	void ReadFromSavegame(Shared::Stream *in);
+	void WriteToSavegame(Shared::Stream *out) const;
 };
 
 } // namespace AGS3
diff --git a/engines/ags/shared/ac/spritecache.cpp b/engines/ags/shared/ac/spritecache.cpp
index 3d850d7fc3..496ba10b51 100644
--- a/engines/ags/shared/ac/spritecache.cpp
+++ b/engines/ags/shared/ac/spritecache.cpp
@@ -41,6 +41,7 @@
 #include "ags/shared/util/compress.h"
 #include "ags/shared/util/file.h"
 #include "ags/shared/util/stream.h"
+#include "common/system.h"
 
 namespace AGS3 {
 
@@ -172,7 +173,7 @@ void SpriteCache::SetEmptySprite(sprkey_t index, bool as_asset) {
 	RemapSpriteToSprite0(index);
 }
 
-void SpriteCache::SubstituteBitmap(sprkey_t index, Common::Bitmap *sprite) {
+void SpriteCache::SubstituteBitmap(sprkey_t index, Shared::Bitmap *sprite) {
 	if (!DoesSpriteExist(index)) {
 		Debug::Printf(kDbgGroup_SprCache, kDbgMsg_Error, "SubstituteBitmap: attempt to set for non-existing sprite %d", index);
 		return;
@@ -510,19 +511,19 @@ void SpriteCache::UnCompressSprite(Bitmap *sprite, Stream *in) {
 }
 
 int SpriteCache::SaveToFile(const char *filename, bool compressOutput, SpriteFileIndex &index) {
-	Stream *output = Common::File::CreateFile(filename);
+	Stream *output = Shared::File::CreateFile(filename);
 	if (output == nullptr)
 		return -1;
 
 	if (compressOutput) {
 		// re-open the file so that it can be seeked
 		delete output;
-		output = File::OpenFile(filename, Common::kFile_Open, Common::kFile_ReadWrite); // CHECKME why mode was "r+" here?
+		output = File::OpenFile(filename, Shared::kFile_Open, Shared::kFile_ReadWrite); // CHECKME why mode was "r+" here?
 		if (output == nullptr)
 			return -1;
 	}
 
-	int spriteFileIDCheck = (int)time(nullptr);
+	int spriteFileIDCheck = g_system->getMillis();
 
 	// sprite file version
 	output->WriteInt16(kSprfVersion_Current);
@@ -678,7 +679,7 @@ HError SpriteCache::InitFile(const char *filename, const char *sprindex_filename
 	soff_t spr_initial_offs = 0;
 	int spriteFileID = 0;
 
-	_stream.reset(Common::AssetManager::OpenAsset(filename));
+	_stream.reset(Shared::AssetManager::OpenAsset(filename));
 	if (_stream == nullptr)
 		return new Error(String::FromFormat("Failed to open spriteset file '%s'.", filename));
 
@@ -780,7 +781,7 @@ HError SpriteCache::RebuildSpriteIndex(AGS::Shared::Stream *in, sprkey_t topmost
 }
 
 bool SpriteCache::LoadSpriteIndexFile(const char *filename, int expectedFileID, soff_t spr_initial_offs, sprkey_t topmost) {
-	Stream *fidx = Common::AssetManager::OpenAsset(filename);
+	Stream *fidx = Shared::AssetManager::OpenAsset(filename);
 	if (fidx == nullptr) {
 		return false;
 	}
@@ -855,7 +856,7 @@ void SpriteCache::DetachFile() {
 }
 
 int SpriteCache::AttachFile(const char *filename) {
-	_stream.reset(Common::AssetManager::OpenAsset((char *)filename));
+	_stream.reset(Shared::AssetManager::OpenAsset((char *)filename));
 	if (_stream == nullptr)
 		return -1;
 	return 0;
diff --git a/engines/ags/shared/ac/spritecache.h b/engines/ags/shared/ac/spritecache.h
index 5a0ebf0dff..4ee33e4f61 100644
--- a/engines/ags/shared/ac/spritecache.h
+++ b/engines/ags/shared/ac/spritecache.h
@@ -45,8 +45,8 @@
 #ifndef AGS_SHARED_AC_SPRITECACHE_H
 #define AGS_SHARED_AC_SPRITECACHE_H
 
-//include <memory>
-//include <vector>
+#include "ags/std/memory.h"
+#include "ags/std/vector.h"
 #include "ags/shared/core/platform.h"
 #include "ags/shared/util/error.h"
 
diff --git a/engines/ags/shared/ac/view.cpp b/engines/ags/shared/ac/view.cpp
index 614258fb1d..886e4c4859 100644
--- a/engines/ags/shared/ac/view.cpp
+++ b/engines/ags/shared/ac/view.cpp
@@ -93,7 +93,7 @@ void ViewLoopNew::WriteToFile_v321(Stream *out) {
 }
 
 void ViewLoopNew::WriteFrames_Aligned(Stream *out) {
-	AlignedStream align_s(out, Common::kAligned_Write);
+	AlignedStream align_s(out, Shared::kAligned_Write);
 	for (int i = 0; i < numFrames; ++i) {
 		frames[i].WriteToFile(&align_s);
 		align_s.Reset();
@@ -111,7 +111,7 @@ void ViewLoopNew::ReadFromFile_v321(Stream *in) {
 }
 
 void ViewLoopNew::ReadFrames_Aligned(Stream *in) {
-	AlignedStream align_s(in, Common::kAligned_Read);
+	AlignedStream align_s(in, Shared::kAligned_Read);
 	for (int i = 0; i < numFrames; ++i) {
 		frames[i].ReadFromFile(&align_s);
 		align_s.Reset();
diff --git a/engines/ags/shared/ac/view.h b/engines/ags/shared/ac/view.h
index 41d27ebdd8..b30b406e58 100644
--- a/engines/ags/shared/ac/view.h
+++ b/engines/ags/shared/ac/view.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_AC_VIEW_H
 #define AGS_SHARED_AC_VIEW_H
 
-//include <vector>
+#include "ags/std/vector.h"
 
 namespace AGS3 {
 
@@ -46,8 +46,8 @@ struct ViewFrame {
 	int   reserved_for_future[2];
 	ViewFrame();
 
-	void ReadFromFile(Common::Stream *in);
-	void WriteToFile(Common::Stream *out);
+	void ReadFromFile(Shared::Stream *in);
+	void WriteToFile(Shared::Stream *out);
 };
 
 #define LOOPFLAG_RUNNEXTLOOP 1
@@ -61,10 +61,10 @@ struct ViewLoopNew {
 	void Initialize(int frameCount);
 	void Dispose();
 	bool RunNextLoop();
-	void WriteToFile_v321(Common::Stream *out);
-	void ReadFromFile_v321(Common::Stream *in);
-	void WriteFrames_Aligned(Common::Stream *out);
-	void ReadFrames_Aligned(Common::Stream *in);
+	void WriteToFile_v321(Shared::Stream *out);
+	void ReadFromFile_v321(Shared::Stream *in);
+	void WriteFrames_Aligned(Shared::Stream *out);
+	void ReadFrames_Aligned(Shared::Stream *in);
 };
 
 struct ViewStruct {
@@ -74,8 +74,8 @@ struct ViewStruct {
 	ViewStruct();
 	void Initialize(int loopCount);
 	void Dispose();
-	void WriteToFile(Common::Stream *out);
-	void ReadFromFile(Common::Stream *in);
+	void WriteToFile(Shared::Stream *out);
+	void ReadFromFile(Shared::Stream *in);
 };
 
 struct ViewStruct272 {
@@ -85,7 +85,7 @@ struct ViewStruct272 {
 	ViewFrame frames[16][20];
 
 	ViewStruct272();
-	void ReadFromFile(Common::Stream *in);
+	void ReadFromFile(Shared::Stream *in);
 };
 
 void Convert272ViewsToNew(const std::vector<ViewStruct272> &oldv, ViewStruct *newv);
diff --git a/engines/ags/shared/ac/wordsdictionary.cpp b/engines/ags/shared/ac/wordsdictionary.cpp
index 9ea0a590ce..6ec5cfe571 100644
--- a/engines/ags/shared/ac/wordsdictionary.cpp
+++ b/engines/ags/shared/ac/wordsdictionary.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-//include <algorithm>
+#include "ags/std/algorithm.h"
 //include <string.h>
 #include "ags/shared/ac/wordsdictionary.h"
 #include "ags/shared/util/stream.h"
diff --git a/engines/ags/shared/ac/wordsdictionary.h b/engines/ags/shared/ac/wordsdictionary.h
index db453aec60..24ac7efce4 100644
--- a/engines/ags/shared/ac/wordsdictionary.h
+++ b/engines/ags/shared/ac/wordsdictionary.h
@@ -55,8 +55,8 @@ struct WordsDictionary {
 extern const char *passwencstring;
 
 extern void decrypt_text(char *toenc);
-extern void read_string_decrypt(Common::Stream *in, char *buf, size_t buf_sz);
-extern void read_dictionary(WordsDictionary *dict, Common::Stream *in);
+extern void read_string_decrypt(Shared::Stream *in, char *buf, size_t buf_sz);
+extern void read_dictionary(WordsDictionary *dict, Shared::Stream *in);
 
 #if defined (OBSOLETE)
 // TODO: not a part of wordsdictionary, move to obsoletes
@@ -64,8 +64,8 @@ extern void freadmissout(short *pptr, Common::Stream *in);
 #endif
 
 extern void encrypt_text(char *toenc);
-extern void write_string_encrypt(Common::Stream *out, const char *s);
-extern void write_dictionary(WordsDictionary *dict, Common::Stream *out);
+extern void write_string_encrypt(Shared::Stream *out, const char *s);
+extern void write_dictionary(WordsDictionary *dict, Shared::Stream *out);
 
 } // namespace AGS3
 
diff --git a/engines/ags/shared/core/asset.h b/engines/ags/shared/core/asset.h
index 34647cc30a..bcbed3a231 100644
--- a/engines/ags/shared/core/asset.h
+++ b/engines/ags/shared/core/asset.h
@@ -29,7 +29,7 @@
 #ifndef AGS_SHARED_CORE_ASSET_H
 #define AGS_SHARED_CORE_ASSET_H
 
-//include <vector>
+#include "ags/std/vector.h"
 #include "ags/shared/util/string.h"
 
 namespace AGS3 {
diff --git a/engines/ags/shared/debugging/debugmanager.h b/engines/ags/shared/debugging/debugmanager.h
index 97a7d89e6f..cb8c125707 100644
--- a/engines/ags/shared/debugging/debugmanager.h
+++ b/engines/ags/shared/debugging/debugmanager.h
@@ -47,8 +47,8 @@
 #ifndef AGS_SHARED_DEBUGGING_DEBUGMANAGER_H
 #define AGS_SHARED_DEBUGGING_DEBUGMANAGER_H
 
-//include <memory>
-//include <unordered_map>
+#include "ags/std/memory.h"
+#include "ags/std/map.h"
 #include "ags/shared/debugging/out.h"
 #include "ags/shared/debugging/outputhandler.h"
 #include "ags/shared/util/string.h"
diff --git a/engines/ags/shared/font/fonts.cpp b/engines/ags/shared/font/fonts.cpp
index 5051c94db5..0bc9c8505c 100644
--- a/engines/ags/shared/font/fonts.cpp
+++ b/engines/ags/shared/font/fonts.cpp
@@ -21,7 +21,7 @@
  */
 
 //include <cstdio>
-//include <vector>
+#include "ags/std/vector.h"
 //include <alfont.h>
 #include "ags/shared/ac/common.h" // set_our_eip
 #include "ags/shared/ac/gamestructdefines.h"
diff --git a/engines/ags/shared/font/fonts.h b/engines/ags/shared/font/fonts.h
index c3e9265588..56dcb7d3c0 100644
--- a/engines/ags/shared/font/fonts.h
+++ b/engines/ags/shared/font/fonts.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_FONT_FONTS_H
 #define AGS_SHARED_FONT_FONTS_H
 
-//include <vector>
+#include "ags/std/vector.h"
 #include "ags/shared/core/types.h"
 #include "ags/shared/util/string.h"
 
diff --git a/engines/ags/shared/font/wfnfont.cpp b/engines/ags/shared/font/wfnfont.cpp
index daea4e3285..ce76cda9e3 100644
--- a/engines/ags/shared/font/wfnfont.cpp
+++ b/engines/ags/shared/font/wfnfont.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-//include <algorithm>
+#include "ags/std/algorithm.h"
 #include "ags/shared/font/wfnfont.h"
 #include "ags/shared/debugging/out.h"
 #include "ags/shared/util/memory.h"
diff --git a/engines/ags/shared/font/wfnfont.h b/engines/ags/shared/font/wfnfont.h
index c3212f684c..583d304598 100644
--- a/engines/ags/shared/font/wfnfont.h
+++ b/engines/ags/shared/font/wfnfont.h
@@ -46,7 +46,7 @@
 #ifndef AGS_SHARED_FONT_WFNFONT_H
 #define AGS_SHARED_FONT_WFNFONT_H
 
-//include <vector>
+#include "ags/std/vector.h"
 #include "ags/shared/core/types.h"
 
 namespace AGS3 {
diff --git a/engines/ags/shared/game/customproperties.cpp b/engines/ags/shared/game/customproperties.cpp
index c56eac64f5..aeeffe5c8c 100644
--- a/engines/ags/shared/game/customproperties.cpp
+++ b/engines/ags/shared/game/customproperties.cpp
@@ -76,7 +76,7 @@ void WriteSchema(const PropertySchema &schema, Stream *out) {
 	out->WriteInt32(schema.size());
 	for (PropertySchema::const_iterator it = schema.begin();
 		it != schema.end(); ++it) {
-		const PropertyDesc &prop = it->second;
+		const PropertyDesc &prop = it->_value;
 		StrUtil::WriteString(prop.Name, out);
 		out->WriteInt32(prop.Type);
 		StrUtil::WriteString(prop.Description, out);
@@ -111,8 +111,8 @@ void WriteValues(const StringIMap &map, Stream *out) {
 	out->WriteInt32(map.size());
 	for (StringIMap::const_iterator it = map.begin();
 		it != map.end(); ++it) {
-		StrUtil::WriteString(it->first, out);
-		StrUtil::WriteString(it->second, out);
+		StrUtil::WriteString(it->_key, out);
+		StrUtil::WriteString(it->_value, out);
 	}
 }
 
diff --git a/engines/ags/shared/game/customproperties.h b/engines/ags/shared/game/customproperties.h
index fd7515041a..7b956e9d79 100644
--- a/engines/ags/shared/game/customproperties.h
+++ b/engines/ags/shared/game/customproperties.h
@@ -36,7 +36,7 @@
 #ifndef AGS_SHARED_GAME_CUSTOMPROPERTIES_H
 #define AGS_SHARED_GAME_CUSTOMPROPERTIES_H
 
-//include <unordered_map>
+#include "ags/std/map.h"
 #include "ags/shared/util/string.h"
 #include "ags/shared/util/string_types.h"
 
@@ -87,7 +87,7 @@ struct PropertyDesc {
 
 // NOTE: AGS has case-insensitive property IDs
 // Schema - a map of property descriptions
-typedef std::unordered_map<String, PropertyDesc, HashStrNoCase, StrEqNoCase> PropertySchema;
+typedef std::unordered_map<String, PropertyDesc, IgnoreCase_Hash, IgnoreCase_EqualTo> PropertySchema;
 
 
 namespace Properties {
diff --git a/engines/ags/shared/game/interactions.cpp b/engines/ags/shared/game/interactions.cpp
index 6996c69dae..46021eb150 100644
--- a/engines/ags/shared/game/interactions.cpp
+++ b/engines/ags/shared/game/interactions.cpp
@@ -80,7 +80,7 @@ void InteractionCommand::Reset() {
 }
 
 void InteractionCommand::ReadValues_Aligned(Stream *in) {
-	AlignedStream align_s(in, Common::kAligned_Read);
+	AlignedStream align_s(in, Shared::kAligned_Read);
 	for (int i = 0; i < MAX_ACTION_ARGS; ++i) {
 		Data[i].Read(&align_s);
 		align_s.Reset();
@@ -96,7 +96,7 @@ void InteractionCommand::Read_v321(Stream *in, bool &has_children) {
 }
 
 void InteractionCommand::WriteValues_Aligned(Stream *out) const {
-	AlignedStream align_s(out, Common::kAligned_Write);
+	AlignedStream align_s(out, Shared::kAligned_Write);
 	for (int i = 0; i < MAX_ACTION_ARGS; ++i) {
 		Data[i].Write(&align_s);
 		align_s.Reset();
@@ -139,7 +139,7 @@ void InteractionCommandList::Reset() {
 }
 
 void InteractionCommandList::Read_Aligned(Stream *in, std::vector<bool> &cmd_children) {
-	AlignedStream align_s(in, Common::kAligned_Read);
+	AlignedStream align_s(in, Shared::kAligned_Read);
 	for (size_t i = 0; i < Cmds.size(); ++i) {
 		bool has_children;
 		Cmds[i].Read_v321(&align_s, has_children);
@@ -167,7 +167,7 @@ void InteractionCommandList::Read_v321(Stream *in) {
 }
 
 void InteractionCommandList::Write_Aligned(Stream *out) const {
-	AlignedStream align_s(out, Common::kAligned_Write);
+	AlignedStream align_s(out, Shared::kAligned_Write);
 	for (InterCmdVector::const_iterator it = Cmds.begin(); it != Cmds.end(); ++it) {
 		it->Write_v321(&align_s);
 		align_s.Reset();
@@ -351,7 +351,7 @@ void InteractionVariable::Read(Stream *in) {
 	Value = in->ReadInt32();
 }
 
-void InteractionVariable::Write(Common::Stream *out) const {
+void InteractionVariable::Write(Shared::Stream *out) const {
 	out->Write(Name, INTER_VAR_NAME_LENGTH);
 	out->WriteInt8(Type);
 	out->WriteInt32(Value);
diff --git a/engines/ags/shared/game/interactions.h b/engines/ags/shared/game/interactions.h
index ad1278404c..ead5ec7a48 100644
--- a/engines/ags/shared/game/interactions.h
+++ b/engines/ags/shared/game/interactions.h
@@ -49,8 +49,8 @@
 #ifndef AGS_SHARED_GAME_INTEREACTIONS_H
 #define AGS_SHARED_GAME_INTEREACTIONS_H
 
-//include <memory>
 #include "ags/shared/util/string_types.h"
+#include "ags/std/memory.h"
 
 namespace AGS3 {
 
@@ -130,8 +130,8 @@ struct InteractionCommandList {
 	void Write_v321(Stream *out) const;
 
 protected:
-	void Read_Aligned(Common::Stream *in, std::vector<bool> &cmd_children);
-	void Write_Aligned(Common::Stream *out) const;
+	void Read_Aligned(Stream *in, std::vector<bool> &cmd_children);
+	void Write_Aligned(Stream *out) const;
 };
 
 
diff --git a/engines/ags/shared/game/main_game_file.h b/engines/ags/shared/game/main_game_file.h
index 93705bbade..3fb86a794c 100644
--- a/engines/ags/shared/game/main_game_file.h
+++ b/engines/ags/shared/game/main_game_file.h
@@ -31,9 +31,9 @@
 #ifndef AGS_SHARED_GAME_MAINGAMEFILE_H
 #define AGS_SHARED_GAME_MAINGAMEFILE_H
 
-//include <memory>
-//include <set>
-//include <vector>
+#include "ags/std/memory.h"
+#include "ags/std/set.h"
+#include "ags/std/vector.h"
 #include "ags/shared/ac/game_version.h"
 #include "ags/shared/game/plugininfo.h"
 #include "ags/shared/script/cc_script.h"
diff --git a/engines/ags/shared/game/plugininfo.h b/engines/ags/shared/game/plugininfo.h
index b10962dd5f..025ccd8ce6 100644
--- a/engines/ags/shared/game/plugininfo.h
+++ b/engines/ags/shared/game/plugininfo.h
@@ -29,7 +29,7 @@
 #ifndef AGS_SHARED_GAME_PLUGININFO_H
 #define AGS_SHARED_GAME_PLUGININFO_H
 
-//include <memory>
+#include "ags/std/memory.h"
 #include "ags/shared/util/string.h"
 
 namespace AGS3 {
diff --git a/engines/ags/shared/game/room_file.cpp b/engines/ags/shared/game/room_file.cpp
index 48796e19a6..6ddbf93670 100644
--- a/engines/ags/shared/game/room_file.cpp
+++ b/engines/ags/shared/game/room_file.cpp
@@ -411,7 +411,7 @@ HRoomFileError ReadCompSc3Block(RoomStruct *room, Stream *in, RoomFileVersion da
 // Room object names
 HRoomFileError ReadObjNamesBlock(RoomStruct *room, Stream *in, RoomFileVersion data_ver) {
 	int name_count = in->ReadByte();
-	if (name_count != room->ObjectCount)
+	if (name_count != (int)room->ObjectCount)
 		return new RoomFileError(kRoomFileErr_InconsistentData,
 			String::FromFormat("In the object names block, expected name count: %d, got %d", room->ObjectCount, name_count));
 
@@ -525,7 +525,7 @@ HRoomFileError ReadRoomBlock(RoomStruct *room, Stream *in, RoomFileBlock block,
 	} else if (cur_pos < block_end) {
 		Debug::Printf(kDbgMsg_Warn, "WARNING: room data blocks nonsequential, block type %d expected to end at %u, finished reading at %u",
 			block, block_end, cur_pos);
-		in->Seek(block_end, Common::kSeekBegin);
+		in->Seek(block_end, Shared::kSeekBegin);
 	}
 	return HRoomFileError::None();
 }
@@ -718,10 +718,10 @@ void WriteBlock(const RoomStruct *room, RoomFileBlock block, PfnWriteBlock write
 	soff_t end_at = out->GetPosition();
 	soff_t block_size = (end_at - sz_at) - sizeof(int64_t);
 	// ...return back and write block's size in the placeholder
-	out->Seek(sz_at, Common::kSeekBegin);
+	out->Seek(sz_at, Shared::kSeekBegin);
 	out->WriteInt64(block_size);
 	// ...and get back to the end of the file
-	out->Seek(0, Common::kSeekEnd);
+	out->Seek(0, Shared::kSeekEnd);
 }
 
 void WriteInteractionScripts(const InteractionScripts *interactions, Stream *out) {
@@ -742,9 +742,9 @@ void WriteMainBlock(const RoomStruct *room, Stream *out) {
 		out->WriteInt16(room->Hotspots[i].WalkTo.Y);
 	}
 	for (size_t i = 0; i < room->HotspotCount; ++i)
-		Common::StrUtil::WriteString(room->Hotspots[i].Name, out);
+		Shared::StrUtil::WriteString(room->Hotspots[i].Name, out);
 	for (size_t i = 0; i < room->HotspotCount; ++i)
-		Common::StrUtil::WriteString(room->Hotspots[i].ScriptName, out);
+		Shared::StrUtil::WriteString(room->Hotspots[i].ScriptName, out);
 
 	out->WriteInt32(0); // legacy poly-point areas
 
@@ -828,13 +828,13 @@ void WriteCompSc3Block(const RoomStruct *room, Stream *out) {
 void WriteObjNamesBlock(const RoomStruct *room, Stream *out) {
 	out->WriteByte((int8_t)room->ObjectCount);
 	for (size_t i = 0; i < room->ObjectCount; ++i)
-		Common::StrUtil::WriteString(room->Objects[i].Name, out);
+		Shared::StrUtil::WriteString(room->Objects[i].Name, out);
 }
 
 void WriteObjScNamesBlock(const RoomStruct *room, Stream *out) {
 	out->WriteByte((int8_t)room->ObjectCount);
 	for (size_t i = 0; i < room->ObjectCount; ++i)
-		Common::StrUtil::WriteString(room->Objects[i].ScriptName, out);
+		Shared::StrUtil::WriteString(room->Objects[i].ScriptName, out);
 }
 
 void WriteAnimBgBlock(const RoomStruct *room, Stream *out) {
diff --git a/engines/ags/shared/game/room_file.h b/engines/ags/shared/game/room_file.h
index e191e85470..1de92c364b 100644
--- a/engines/ags/shared/game/room_file.h
+++ b/engines/ags/shared/game/room_file.h
@@ -31,8 +31,8 @@
 #ifndef AGS_SHARED_GAME_ROOMFILE_H
 #define AGS_SHARED_GAME_ROOMFILE_H
 
-//include <memory>
-//include <vector>
+#include "ags/std/memory.h"
+#include "ags/std/vector.h"
 #include "ags/shared/game/room_version.h"
 #include "ags/shared/util/error.h"
 #include "ags/shared/util/stream.h"
diff --git a/engines/ags/shared/game/roomstruct.h b/engines/ags/shared/game/roomstruct.h
index 59f42ea829..40bd7dd461 100644
--- a/engines/ags/shared/game/roomstruct.h
+++ b/engines/ags/shared/game/roomstruct.h
@@ -48,11 +48,11 @@
 #ifndef AGS_SHARED_GAME_ROOMINFO_H
 #define AGS_SHARED_GAME_ROOMINFO_H
 
-//include <memory>
 #include "ags/shared/ac/common_defines.h"
 #include "ags/shared/game/interactions.h"
 #include "ags/shared/util/geometry.h"
 #include "ags/shared/util/wgt2allg.h" // color (allegro RGB)
+#include "ags/std/memory.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/gui/guibutton.h b/engines/ags/shared/gui/guibutton.h
index 955df3c5c6..ab03e4fd23 100644
--- a/engines/ags/shared/gui/guibutton.h
+++ b/engines/ags/shared/gui/guibutton.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_GUI_GUIBUTTON_H
 #define AGS_SHARED_GUI_GUIBUTTON_H
 
-//include <vector>
+#include "ags/std/vector.h"
 #include "ags/shared/gui/guiobject.h"
 #include "ags/shared/util/string.h"
 
diff --git a/engines/ags/shared/gui/guiinv.h b/engines/ags/shared/gui/guiinv.h
index ba16d7a596..7ab166063e 100644
--- a/engines/ags/shared/gui/guiinv.h
+++ b/engines/ags/shared/gui/guiinv.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_GUI_GUIINV_H
 #define AGS_SHARED_GUI_GUIINV_H
 
-//include <vector>
+#include "ags/std/vector.h"
 #include "ags/shared/gui/guiobject.h"
 
 namespace AGS3 {
diff --git a/engines/ags/shared/gui/guilabel.h b/engines/ags/shared/gui/guilabel.h
index 836b473a4b..82d7b7538d 100644
--- a/engines/ags/shared/gui/guilabel.h
+++ b/engines/ags/shared/gui/guilabel.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_GUI_GUILABEL_H
 #define AGS_SHARED_GUI_GUILABEL_H
 
-//include <vector>
+#include "ags/std/vector.h"
 #include "ags/shared/gui/guiobject.h"
 #include "ags/shared/util/string.h"
 
diff --git a/engines/ags/shared/gui/guilistbox.h b/engines/ags/shared/gui/guilistbox.h
index 090184ba04..52193b6af4 100644
--- a/engines/ags/shared/gui/guilistbox.h
+++ b/engines/ags/shared/gui/guilistbox.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_GUI_GUILISTBOX_H
 #define AGS_SHARED_GUI_GUILISTBOX_H
 
-//include <vector>
+#include "ags/std/vector.h"
 #include "ags/shared/gui/guiobject.h"
 #include "ags/shared/util/string.h"
 
diff --git a/engines/ags/shared/gui/guislider.h b/engines/ags/shared/gui/guislider.h
index 3eea0c3a39..5cbb4fc00d 100644
--- a/engines/ags/shared/gui/guislider.h
+++ b/engines/ags/shared/gui/guislider.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_GUI_GUISLIDER_H
 #define AGS_SHARED_GUI_GUISLIDER_H
 
-//include <vector>
+#include "ags/std/vector.h"
 #include "ags/shared/gui/guiobject.h"
 
 namespace AGS3 {
diff --git a/engines/ags/shared/gui/guitextbox.h b/engines/ags/shared/gui/guitextbox.h
index b1906cc861..53b830590a 100644
--- a/engines/ags/shared/gui/guitextbox.h
+++ b/engines/ags/shared/gui/guitextbox.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_GUI_GUITEXTBOX_H
 #define AGS_SHARED_GUI_GUITEXTBOX_H
 
-//include <vector>
+#include "ags/std/vector.h"
 #include "ags/shared/gui/guiobject.h"
 #include "ags/shared/util/string.h"
 


Commit: 6b8f864134e80a4f8c47630d2258d679c9a5e2f1
    https://github.com/scummvm/scummvm/commit/6b8f864134e80a4f8c47630d2258d679c9a5e2f1
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added shared/core/ folder

Changed paths:
    engines/ags/module.mk
    engines/ags/shared/core/assetmanager.cpp


diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index f039ffe63f..6bc49486b9 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -32,6 +32,8 @@ MODULE_OBJS = \
 	shared/ac/spritecache.o \
 	shared/ac/view.o \
 	shared/ac/wordsdictionary.o \
+	shared/core/asset.o \
+	shared/core/assetmanager.o \
 	shared/gfx/allegrobitmap.o \
 	shared/gfx/bitmap.o \
 	shared/gfx/image.o \
diff --git a/engines/ags/shared/core/assetmanager.cpp b/engines/ags/shared/core/assetmanager.cpp
index 28b8d0a37c..e3f62a8f16 100644
--- a/engines/ags/shared/core/assetmanager.cpp
+++ b/engines/ags/shared/core/assetmanager.cpp
@@ -67,7 +67,7 @@ AssetManager::~AssetManager() {
 }
 
 /* static */ bool AssetManager::IsDataFile(const String &data_file) {
-	Stream *in = ci_fopen(data_file, Common::kFile_Open, Common::kFile_Read);
+	Stream *in = ci_fopen(data_file, Shared::kFile_Open, Shared::kFile_Read);
 	if (in) {
 		MFLUtil::MFLError err = MFLUtil::TestIsMFL(in, true);
 		delete in;
@@ -77,7 +77,7 @@ AssetManager::~AssetManager() {
 }
 
 AssetError AssetManager::ReadDataFileTOC(const String &data_file, AssetLibInfo &lib) {
-	Stream *in = ci_fopen(data_file, Common::kFile_Open, Common::kFile_Read);
+	Stream *in = ci_fopen(data_file, Shared::kFile_Open, Shared::kFile_Read);
 	if (in) {
 		MFLUtil::MFLError err = MFLUtil::ReadHeader(lib, in);
 		delete in;
@@ -248,7 +248,7 @@ AssetError AssetManager::RegisterAssetLib(const String &data_file, const String
 	_basePath = ".";
 
 	// open data library
-	Stream *in = ci_fopen(data_file, Common::kFile_Open, Common::kFile_Read);
+	Stream *in = ci_fopen(data_file, Shared::kFile_Open, Shared::kFile_Read);
 	if (!in)
 		return kAssetErrNoLibFile; // can't be opened, return error code
 
@@ -300,7 +300,7 @@ String AssetManager::MakeLibraryFileNameForAsset(const AssetInfo *asset) {
 }
 
 bool AssetManager::GetAssetFromLib(const String &asset_name, AssetLocation &loc, FileOpenMode open_mode, FileWorkMode work_mode) {
-	if (open_mode != Common::kFile_Open || work_mode != Common::kFile_Read)
+	if (open_mode != Shared::kFile_Open || work_mode != Shared::kFile_Read)
 		return false; // creating/writing is allowed only for common files on disk
 
 	AssetInfo *asset = FindAssetByFileName(asset_name);


Commit: 216657c3ab7ad27754f951833eab6703c01b86e8
    https://github.com/scummvm/scummvm/commit/216657c3ab7ad27754f951833eab6703c01b86e8
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added shared/debugging/ folder

Changed paths:
    engines/ags/module.mk
    engines/ags/shared/debugging/debugmanager.cpp
    engines/ags/shared/debugging/debugmanager.h
    engines/ags/shared/debugging/outputhandler.h


diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 6bc49486b9..edb48894ef 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -34,6 +34,7 @@ MODULE_OBJS = \
 	shared/ac/wordsdictionary.o \
 	shared/core/asset.o \
 	shared/core/assetmanager.o \
+	shared/debugging/debugmanager.o \
 	shared/gfx/allegrobitmap.o \
 	shared/gfx/bitmap.o \
 	shared/gfx/image.o \
diff --git a/engines/ags/shared/debugging/debugmanager.cpp b/engines/ags/shared/debugging/debugmanager.cpp
index d6106531cd..f1889e2ab8 100644
--- a/engines/ags/shared/debugging/debugmanager.cpp
+++ b/engines/ags/shared/debugging/debugmanager.cpp
@@ -64,7 +64,7 @@ void DebugOutput::SetAllGroupFilters(MessageType verbosity) {
 	for (auto &group : _groupFilter)
 		group = verbosity;
 	for (auto &group : _unresolvedGroups)
-		group.second = verbosity;
+		group._value = verbosity;
 }
 
 void DebugOutput::ClearGroupFilters() {
@@ -83,7 +83,7 @@ void DebugOutput::ResolveGroupID(DebugGroupID id) {
 			_groupFilter.resize(id.ID + 1, _defaultVerbosity);
 		GroupNameToMTMap::const_iterator it = _unresolvedGroups.find(real_id.SID);
 		if (it != _unresolvedGroups.end()) {
-			_groupFilter[real_id.ID] = it->second;
+			_groupFilter[real_id.ID] = it->_value;
 			_unresolvedGroups.erase(it);
 		}
 	}
@@ -112,14 +112,14 @@ DebugGroup DebugManager::GetGroup(DebugGroupID id) {
 		return id.ID < _groups.size() ? _groups[id.ID] : DebugGroup();
 	} else if (!id.SID.IsEmpty()) {
 		GroupByStringMap::const_iterator it = _groupByStrLookup.find(id.SID);
-		return it != _groupByStrLookup.end() ? _groups[it->second.ID] : DebugGroup();
+		return it != _groupByStrLookup.end() ? _groups[it->_value.ID] : DebugGroup();
 	}
 	return DebugGroup();
 }
 
 PDebugOutput DebugManager::GetOutput(const String &id) {
 	OutMap::const_iterator it = _outputs.find(id);
-	return it != _outputs.end() ? it->second.Target : PDebugOutput();
+	return it != _outputs.end() ? it->_value.Target : PDebugOutput();
 }
 
 DebugGroup DebugManager::RegisterGroup(const String &id, const String &out_name) {
@@ -132,7 +132,7 @@ DebugGroup DebugManager::RegisterGroup(const String &id, const String &out_name)
 
 	// Resolve group reference on every output target
 	for (OutMap::const_iterator it = _outputs.begin(); it != _outputs.end(); ++it) {
-		it->second.Target->ResolveGroupID(group.UID);
+		it->_value.Target->ResolveGroupID(group.UID);
 	}
 	return group;
 }
@@ -172,14 +172,14 @@ void DebugManager::Print(DebugGroupID group_id, MessageType mt, const String &te
 	DebugMessage msg(text, group.UID.ID, group.OutputName, mt);
 
 	for (OutMap::iterator it = _outputs.begin(); it != _outputs.end(); ++it) {
-		SendMessage(it->second, msg);
+		SendMessage(it->_value, msg);
 	}
 }
 
 void DebugManager::SendMessage(const String &out_id, const DebugMessage &msg) {
 	OutMap::iterator it = _outputs.find(out_id);
 	if (it != _outputs.end())
-		SendMessage(it->second, msg);
+		SendMessage(it->_value, msg);
 }
 
 void DebugManager::SendMessage(OutputSlot &out, const DebugMessage &msg) {
diff --git a/engines/ags/shared/debugging/debugmanager.h b/engines/ags/shared/debugging/debugmanager.h
index cb8c125707..eefa9aac01 100644
--- a/engines/ags/shared/debugging/debugmanager.h
+++ b/engines/ags/shared/debugging/debugmanager.h
@@ -100,7 +100,7 @@ private:
 	// Set of permitted groups' numeric IDs
 	std::vector<MessageType> _groupFilter;
 	// Set of unresolved groups, which numeric IDs are not yet known
-	typedef std::unordered_map<String, MessageType, HashStrNoCase, StrEqNoCase> GroupNameToMTMap;
+	typedef std::unordered_map<String, MessageType, IgnoreCase_Hash, IgnoreCase_EqualTo> GroupNameToMTMap;
 	GroupNameToMTMap _unresolvedGroups;
 };
 
@@ -149,8 +149,8 @@ private:
 	};
 
 	typedef std::vector<DebugGroup> GroupVector;
-	typedef std::unordered_map<String, DebugGroupID, HashStrNoCase, StrEqNoCase> GroupByStringMap;
-	typedef std::unordered_map<String, OutputSlot, HashStrNoCase, StrEqNoCase> OutMap;
+	typedef std::unordered_map<String, DebugGroupID, IgnoreCase_Hash, IgnoreCase_EqualTo> GroupByStringMap;
+	typedef std::unordered_map<String, OutputSlot, IgnoreCase_Hash, IgnoreCase_EqualTo> OutMap;
 
 	void RegisterGroup(const DebugGroup &id);
 	void SendMessage(OutputSlot &out, const DebugMessage &msg);
diff --git a/engines/ags/shared/debugging/outputhandler.h b/engines/ags/shared/debugging/outputhandler.h
index 635932b7fb..8e51ab19b3 100644
--- a/engines/ags/shared/debugging/outputhandler.h
+++ b/engines/ags/shared/debugging/outputhandler.h
@@ -35,15 +35,15 @@
 
 namespace AGS3 {
 namespace AGS {
-namespace Common {
+namespace Shared {
 
 struct DebugMessage {
 	String       Text;
-namespace SharedoupID;
+	uint32_t     GroupID;
 	String       GroupName;
 	MessageType  MT;
 
-	DebugMessage() : GroupID(kDbgGroup_None), MT(kDbgMsg_None) {
+	DebugMessage() : GroupID((uint32_t)kDbgGroup_None), MT(kDbgMsg_None) {
 	}
 	DebugMessage(const String &text, uint32_t group_id, const String &group_name, MessageType mt)
 		: Text(text)
@@ -62,7 +62,7 @@ public:
 	virtual void PrintMessage(const DebugMessage &msg) = 0;
 };
 
-} // namespace Common
+} // namespace Shared
 } // namespace AGS
 } // namespace AGS3
 


Commit: 197b2ef34df8df44536e8284eedb6911f6aac1b1
    https://github.com/scummvm/scummvm/commit/197b2ef34df8df44536e8284eedb6911f6aac1b1
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Adding shared/game/ folder

Changed paths:
    engines/ags/module.mk
    engines/ags/shared/game/main_game_file.cpp


diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index edb48894ef..4c650f9b43 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -35,6 +35,11 @@ MODULE_OBJS = \
 	shared/core/asset.o \
 	shared/core/assetmanager.o \
 	shared/debugging/debugmanager.o \
+	shared/game/customproperties.o \
+	shared/game/interactions.o \
+	shared/game/room_file.o \
+	shared/game/room_file_deprecated.o \
+	shared/game/roomstruct.o \
 	shared/gfx/allegrobitmap.o \
 	shared/gfx/bitmap.o \
 	shared/gfx/image.o \
diff --git a/engines/ags/shared/game/main_game_file.cpp b/engines/ags/shared/game/main_game_file.cpp
index 436c24ba41..276aceb53c 100644
--- a/engines/ags/shared/game/main_game_file.cpp
+++ b/engines/ags/shared/game/main_game_file.cpp
@@ -20,7 +20,6 @@
  *
  */
 
-//include <cstdio>
 #include "ags/shared/ac/audiocliptype.h"
 #include "ags/shared/ac/dialogtopic.h"
 #include "ags/shared/ac/gamesetupstruct.h"
@@ -34,10 +33,12 @@
 #include "ags/shared/gui/guimain.h"
 #include "ags/shared/script/cc_error.h"
 #include "ags/shared/util/alignedstream.h"
+#include "ags/shared/util/directory.h"
 #include "ags/shared/util/path.h"
 #include "ags/shared/util/string_compat.h"
 #include "ags/shared/util/string_utils.h"
 #include "ags/shared/font/fonts.h"
+#include "common/fs.h"
 
 namespace AGS3 {
 namespace AGS {
@@ -204,7 +205,7 @@ HGameFileError ReadScriptModules(std::vector<PScript> &sc_mods, Stream *in, Game
 }
 
 void ReadViewStruct272_Aligned(std::vector<ViewStruct272> &oldv, Stream *in, size_t count) {
-	AlignedStream align_s(in, Common::kAligned_Read);
+	AlignedStream align_s(in, Shared::kAligned_Read);
 	oldv.resize(count);
 	for (size_t i = 0; i < count; ++i) {
 		oldv[i].ReadFromFile(&align_s);
@@ -434,7 +435,7 @@ void UpgradeFonts(GameSetupStruct &game, GameDataVersion data_ver) {
 		}
 	}
 	if (data_ver < kGameVersion_351) {
-		for (size_t font = 0; font < game.numfonts; font++) {
+		for (size_t font = 0; font < (size_t)game.numfonts; font++) {
 			FontInfo &finfo = game.fonts[font];
 			// Thickness that corresponds to 1 game pixel
 			finfo.AutoOutlineThickness =
@@ -498,15 +499,16 @@ void UpgradeAudio(GameSetupStruct &game, GameDataVersion data_ver) {
 		}
 	}
 	// Append contents of the game directory
-	// TODO: use explicit path instead of cwd? keep this consistent with AssetManager!
 	{
-		al_ffblk ff;
-		if (al_findfirst("*.*", &ff, FA_ALL & ~(FA_DIREC)) == 0) {
-			do {
-				if (ags_strnicmp(ff.name, "music", 5) == 0 || ags_strnicmp(ff.name, "sound", 5) == 0)
-					assets.push_back(ff.name);
-			} while (al_findnext(&ff) == 0);
-			al_findclose(&ff);
+		Common::FSNode folder(Directory::GetCurrentDirectory().GetNullableCStr());
+		Common::FSList files;
+		folder.getChildren(files, Common::FSNode::kListFilesOnly);
+
+		for (uint idx = 0; idx < files.size(); ++idx) {
+			Common::String name = files[idx].getName();
+			if (name.hasPrefixIgnoreCase("music") || name.hasPrefixIgnoreCase("sound")) {
+				assets.push_back(name);
+			}
 		}
 	}
 	BuildAudioClipArray(assets, audioclips);
@@ -627,7 +629,8 @@ HGameFileError ReadSpriteFlags(LoadedGameEntities &ents, Stream *in, GameDataVer
 	else
 		sprcount = in->ReadInt32();
 	if (sprcount > (uint32_t)SpriteCache::MAX_SPRITE_INDEX + 1)
-		return new MainGameFileError(kMGFErr_TooManySprites, String::FromFormat("Count: %u, max: %u", sprcount, (uint32_t)SpriteCache::MAX_SPRITE_INDEX + 1));
+		return new MainGameFileError(kMGFErr_TooManySprites, String::FromFormat("Count: %u, max: %u",
+			sprcount, (uint32_t)SpriteCache::MAX_SPRITE_INDEX + 1));
 
 	ents.SpriteCount = sprcount;
 	ents.SpriteFlags.reset(new char[sprcount]);
@@ -639,7 +642,7 @@ HGameFileError ReadGameData(LoadedGameEntities &ents, Stream *in, GameDataVersio
 	GameSetupStruct &game = ents.Game;
 
 	{
-		AlignedStream align_s(in, Common::kAligned_Read);
+		AlignedStream align_s(in, Shared::kAligned_Read);
 		game.GameSetupStructBase::ReadFromFile(&align_s);
 	}
 


Commit: 9a78e04039685c1a9c6911d6178ef73bcd8c2978
    https://github.com/scummvm/scummvm/commit/9a78e04039685c1a9c6911d6178ef73bcd8c2978
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Beginnings of engine/ inclusion

Changed paths:
  A engines/ags/std/initializer_list.h
  A engines/ags/std/xtr1common.h
    engines/ags/engine/ac/asset_helper.h
    engines/ags/engine/ac/audiochannel.cpp
    engines/ags/engine/ac/audiochannel.h
    engines/ags/engine/ac/audioclip.cpp
    engines/ags/engine/ac/audioclip.h
    engines/ags/engine/ac/button.cpp
    engines/ags/engine/ac/button.h
    engines/ags/engine/ac/cdaudio.cpp
    engines/ags/engine/ac/character.cpp
    engines/ags/engine/ac/character.h
    engines/ags/engine/ac/charactercache.h
    engines/ags/engine/ac/characterextras.cpp
    engines/ags/engine/ac/characterextras.h
    engines/ags/engine/ac/characterinfo_engine.cpp
    engines/ags/engine/ac/datetime.cpp
    engines/ags/engine/ac/datetime.h
    engines/ags/engine/ac/dialog.cpp
    engines/ags/engine/ac/dialog.h
    engines/ags/engine/ac/dialogoptionsrendering.cpp
    engines/ags/engine/ac/dialogoptionsrendering.h
    engines/ags/engine/ac/display.cpp
    engines/ags/engine/ac/display.h
    engines/ags/engine/ac/draw.cpp
    engines/ags/engine/ac/draw.h
    engines/ags/engine/ac/draw_software.cpp
    engines/ags/engine/ac/draw_software.h
    engines/ags/engine/ac/drawingsurface.cpp
    engines/ags/engine/ac/drawingsurface.h
    engines/ags/engine/ac/dynamicsprite.cpp
    engines/ags/engine/ac/dynamicsprite.h
    engines/ags/engine/ac/dynobj/all_dynamicclasses.h
    engines/ags/engine/ac/dynobj/all_scriptclasses.h
    engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp
    engines/ags/engine/ac/dynobj/cc_agsdynamicobject.h
    engines/ags/engine/ac/dynobj/cc_audiochannel.cpp
    engines/ags/engine/ac/dynobj/cc_audiochannel.h
    engines/ags/engine/ac/dynobj/cc_audioclip.cpp
    engines/ags/engine/ac/dynobj/cc_audioclip.h
    engines/ags/engine/ac/dynobj/cc_character.cpp
    engines/ags/engine/ac/dynobj/cc_character.h
    engines/ags/engine/ac/dynobj/cc_dialog.cpp
    engines/ags/engine/ac/dynobj/cc_dialog.h
    engines/ags/engine/ac/dynobj/cc_dynamicarray.cpp
    engines/ags/engine/ac/dynobj/cc_dynamicarray.h
    engines/ags/engine/ac/dynobj/cc_dynamicobject.cpp
    engines/ags/engine/ac/dynobj/cc_dynamicobject.h
    engines/ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h
    engines/ags/engine/ac/dynobj/cc_gui.cpp
    engines/ags/engine/ac/dynobj/cc_gui.h
    engines/ags/engine/ac/dynobj/cc_guiobject.cpp
    engines/ags/engine/ac/dynobj/cc_guiobject.h
    engines/ags/engine/ac/dynobj/cc_hotspot.cpp
    engines/ags/engine/ac/dynobj/cc_hotspot.h
    engines/ags/engine/ac/dynobj/cc_inventory.cpp
    engines/ags/engine/ac/dynobj/cc_inventory.h
    engines/ags/engine/ac/dynobj/cc_object.cpp
    engines/ags/engine/ac/dynobj/cc_object.h
    engines/ags/engine/ac/dynobj/cc_region.cpp
    engines/ags/engine/ac/dynobj/cc_region.h
    engines/ags/engine/ac/dynobj/cc_serializer.cpp
    engines/ags/engine/ac/dynobj/cc_serializer.h
    engines/ags/engine/ac/dynobj/managedobjectpool.cpp
    engines/ags/engine/ac/dynobj/managedobjectpool.h
    engines/ags/engine/ac/dynobj/scriptcamera.cpp
    engines/ags/engine/ac/dynobj/scriptcamera.h
    engines/ags/engine/ac/dynobj/scriptdatetime.cpp
    engines/ags/engine/ac/dynobj/scriptdatetime.h
    engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.cpp
    engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.h
    engines/ags/engine/ac/dynobj/scriptdict.cpp
    engines/ags/engine/ac/dynobj/scriptdict.h
    engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp
    engines/ags/engine/ac/dynobj/scriptdrawingsurface.h
    engines/ags/engine/ac/dynobj/scriptdynamicsprite.cpp
    engines/ags/engine/ac/dynobj/scriptdynamicsprite.h
    engines/ags/engine/ac/dynobj/scriptfile.cpp
    engines/ags/engine/ac/dynobj/scriptfile.h
    engines/ags/engine/ac/dynobj/scriptobject.h
    engines/ags/engine/ac/dynobj/scriptoverlay.cpp
    engines/ags/engine/ac/dynobj/scriptoverlay.h
    engines/ags/engine/ac/dynobj/scriptset.cpp
    engines/ags/engine/ac/dynobj/scriptset.h
    engines/ags/engine/ac/dynobj/scriptstring.cpp
    engines/ags/engine/ac/dynobj/scriptstring.h
    engines/ags/engine/ac/dynobj/scriptuserobject.cpp
    engines/ags/engine/ac/dynobj/scriptuserobject.h
    engines/ags/engine/ac/dynobj/scriptviewframe.cpp
    engines/ags/engine/ac/dynobj/scriptviewframe.h
    engines/ags/engine/ac/dynobj/scriptviewport.cpp
    engines/ags/engine/ac/dynobj/scriptviewport.h
    engines/ags/engine/ac/event.cpp
    engines/ags/engine/ac/event.h
    engines/ags/engine/ac/file.cpp
    engines/ags/engine/ac/file.h
    engines/ags/engine/ac/game.cpp
    engines/ags/engine/ac/game.h
    engines/ags/engine/ac/gamesetup.cpp
    engines/ags/engine/ac/gamesetup.h
    engines/ags/engine/ac/gamestate.cpp
    engines/ags/engine/ac/gamestate.h
    engines/ags/engine/ac/global_api.cpp
    engines/ags/engine/ac/global_audio.cpp
    engines/ags/engine/ac/global_button.cpp
    engines/ags/engine/ac/global_character.cpp
    engines/ags/engine/ac/global_character.h
    engines/ags/engine/ac/global_datetime.cpp
    engines/ags/engine/ac/global_debug.cpp
    engines/ags/engine/ac/global_debug.h
    engines/ags/engine/ac/global_dialog.cpp
    engines/ags/engine/ac/global_display.cpp
    engines/ags/engine/ac/global_display.h
    engines/ags/engine/ac/global_drawingsurface.cpp
    engines/ags/engine/ac/global_drawingsurface.h
    engines/ags/engine/ac/global_dynamicsprite.cpp
    engines/ags/engine/ac/global_file.cpp
    engines/ags/engine/ac/global_file.h
    engines/ags/engine/ac/global_game.cpp
    engines/ags/engine/ac/global_game.h
    engines/ags/engine/ac/global_gui.cpp
    engines/ags/engine/ac/global_hotspot.cpp
    engines/ags/engine/ac/global_inventoryitem.cpp
    engines/ags/engine/ac/global_invwindow.cpp
    engines/ags/engine/ac/global_label.cpp
    engines/ags/engine/ac/global_listbox.cpp
    engines/ags/engine/ac/global_mouse.cpp
    engines/ags/engine/ac/global_object.cpp
    engines/ags/engine/ac/global_object.h
    engines/ags/engine/ac/global_overlay.cpp
    engines/ags/engine/ac/global_palette.cpp
    engines/ags/engine/ac/global_parser.cpp
    engines/ags/engine/ac/global_record.cpp
    engines/ags/engine/ac/global_region.cpp
    engines/ags/engine/ac/global_room.cpp
    engines/ags/engine/ac/global_screen.cpp
    engines/ags/engine/ac/global_slider.cpp
    engines/ags/engine/ac/global_string.cpp
    engines/ags/engine/ac/global_textbox.cpp
    engines/ags/engine/ac/global_timer.cpp
    engines/ags/engine/ac/global_translation.cpp
    engines/ags/engine/ac/global_video.cpp
    engines/ags/engine/ac/global_viewframe.cpp
    engines/ags/engine/ac/global_viewport.cpp
    engines/ags/engine/ac/global_walkablearea.cpp
    engines/ags/engine/ac/global_walkbehind.cpp
    engines/ags/engine/ac/gui.cpp
    engines/ags/engine/ac/gui.h
    engines/ags/engine/ac/guicontrol.cpp
    engines/ags/engine/ac/guicontrol.h
    engines/ags/engine/ac/guiinv.cpp
    engines/ags/engine/ac/hotspot.cpp
    engines/ags/engine/ac/hotspot.h
    engines/ags/engine/ac/interfacebutton.cpp
    engines/ags/engine/ac/interfaceelement.cpp
    engines/ags/engine/ac/inventoryitem.cpp
    engines/ags/engine/ac/inventoryitem.h
    engines/ags/engine/ac/invwindow.cpp
    engines/ags/engine/ac/invwindow.h
    engines/ags/engine/ac/keycode.cpp
    engines/ags/engine/ac/keycode.h
    engines/ags/engine/ac/label.cpp
    engines/ags/engine/ac/label.h
    engines/ags/engine/ac/listbox.cpp
    engines/ags/engine/ac/listbox.h
    engines/ags/engine/ac/math.cpp
    engines/ags/engine/ac/math.h
    engines/ags/engine/ac/mouse.cpp
    engines/ags/engine/ac/mouse.h
    engines/ags/engine/ac/movelist.cpp
    engines/ags/engine/ac/movelist.h
    engines/ags/engine/ac/object.cpp
    engines/ags/engine/ac/object.h
    engines/ags/engine/ac/objectcache.h
    engines/ags/engine/ac/overlay.cpp
    engines/ags/engine/ac/overlay.h
    engines/ags/engine/ac/parser.cpp
    engines/ags/engine/ac/path_helper.h
    engines/ags/engine/ac/properties.cpp
    engines/ags/engine/ac/properties.h
    engines/ags/engine/ac/region.cpp
    engines/ags/engine/ac/region.h
    engines/ags/engine/ac/richgamemedia.cpp
    engines/ags/engine/ac/richgamemedia.h
    engines/ags/engine/ac/room.cpp
    engines/ags/engine/ac/room.h
    engines/ags/engine/ac/roomobject.cpp
    engines/ags/engine/ac/roomobject.h
    engines/ags/engine/ac/roomstatus.cpp
    engines/ags/engine/ac/roomstatus.h
    engines/ags/engine/ac/route_finder.cpp
    engines/ags/engine/ac/route_finder.h
    engines/ags/engine/ac/route_finder_impl.cpp
    engines/ags/engine/ac/route_finder_impl.h
    engines/ags/engine/ac/route_finder_impl_legacy.cpp
    engines/ags/engine/ac/route_finder_jps.inl
    engines/ags/engine/ac/runtime_defines.h
    engines/ags/engine/ac/screen.cpp
    engines/ags/engine/ac/screenoverlay.cpp
    engines/ags/engine/ac/screenoverlay.h
    engines/ags/engine/ac/scriptcontainers.cpp
    engines/ags/engine/ac/slider.cpp
    engines/ags/engine/ac/slider.h
    engines/ags/engine/ac/speech.cpp
    engines/ags/engine/ac/sprite.cpp
    engines/ags/engine/ac/sprite.h
    engines/ags/engine/ac/spritecache_engine.cpp
    engines/ags/engine/ac/spritelistentry.h
    engines/ags/engine/ac/statobj/agsstaticobject.cpp
    engines/ags/engine/ac/statobj/agsstaticobject.h
    engines/ags/engine/ac/statobj/staticarray.cpp
    engines/ags/engine/ac/statobj/staticarray.h
    engines/ags/engine/ac/statobj/staticobject.h
    engines/ags/engine/ac/string.cpp
    engines/ags/engine/ac/string.h
    engines/ags/engine/ac/sys_events.cpp
    engines/ags/engine/ac/system.cpp
    engines/ags/engine/ac/system.h
    engines/ags/engine/ac/textbox.cpp
    engines/ags/engine/ac/textbox.h
    engines/ags/engine/ac/timer.cpp
    engines/ags/engine/ac/timer.h
    engines/ags/engine/ac/translation.cpp
    engines/ags/engine/ac/translation.h
    engines/ags/engine/ac/tree_map.cpp
    engines/ags/engine/ac/viewframe.cpp
    engines/ags/engine/ac/viewframe.h
    engines/ags/engine/ac/viewport_script.cpp
    engines/ags/engine/ac/walkablearea.cpp
    engines/ags/engine/ac/walkablearea.h
    engines/ags/engine/ac/walkbehind.cpp
    engines/ags/engine/debugging/consoleoutputtarget.cpp
    engines/ags/engine/debugging/consoleoutputtarget.h
    engines/ags/engine/debugging/debug.cpp
    engines/ags/engine/debugging/debug_log.h
    engines/ags/engine/debugging/debugger.h
    engines/ags/engine/debugging/dummyagsdebugger.h
    engines/ags/engine/debugging/filebasedagsdebugger.cpp
    engines/ags/engine/debugging/filebasedagsdebugger.h
    engines/ags/engine/debugging/logfile.cpp
    engines/ags/engine/debugging/logfile.h
    engines/ags/engine/debugging/messagebuffer.cpp
    engines/ags/engine/debugging/messagebuffer.h
    engines/ags/engine/device/mousew32.cpp
    engines/ags/engine/device/mousew32.h
    engines/ags/engine/font/fonts_engine.cpp
    engines/ags/engine/game/game_init.cpp
    engines/ags/engine/game/game_init.h
    engines/ags/engine/game/savegame.cpp
    engines/ags/engine/game/savegame.h
    engines/ags/engine/game/savegame_components.cpp
    engines/ags/engine/game/savegame_components.h
    engines/ags/engine/game/savegame_internal.h
    engines/ags/engine/game/viewport.cpp
    engines/ags/engine/game/viewport.h
    engines/ags/engine/gfx/ali3dogl.cpp
    engines/ags/engine/gfx/ali3dogl.h
    engines/ags/engine/gfx/ali3dsw.cpp
    engines/ags/engine/gfx/ali3dsw.h
    engines/ags/engine/gfx/blender.cpp
    engines/ags/engine/gfx/color_engine.cpp
    engines/ags/engine/gfx/gfx_util.cpp
    engines/ags/engine/gfx/gfx_util.h
    engines/ags/engine/gfx/gfxdefines.h
    engines/ags/engine/gfx/gfxdriverbase.cpp
    engines/ags/engine/gfx/gfxdriverbase.h
    engines/ags/engine/gfx/gfxdriverfactory.cpp
    engines/ags/engine/gfx/gfxdriverfactory.h
    engines/ags/engine/gfx/gfxdriverfactorybase.h
    engines/ags/engine/gfx/gfxfilter.h
    engines/ags/engine/gfx/gfxfilter_aad3d.cpp
    engines/ags/engine/gfx/gfxfilter_aad3d.h
    engines/ags/engine/gfx/gfxfilter_aaogl.cpp
    engines/ags/engine/gfx/gfxfilter_aaogl.h
    engines/ags/engine/gfx/gfxfilter_allegro.cpp
    engines/ags/engine/gfx/gfxfilter_allegro.h
    engines/ags/engine/gfx/gfxfilter_d3d.cpp
    engines/ags/engine/gfx/gfxfilter_d3d.h
    engines/ags/engine/gfx/gfxfilter_hqx.cpp
    engines/ags/engine/gfx/gfxfilter_hqx.h
    engines/ags/engine/gfx/gfxfilter_ogl.cpp
    engines/ags/engine/gfx/gfxfilter_ogl.h
    engines/ags/engine/gfx/gfxfilter_scaling.cpp
    engines/ags/engine/gfx/gfxfilter_scaling.h
    engines/ags/engine/gfx/gfxmodelist.h
    engines/ags/engine/gfx/graphicsdriver.h
    engines/ags/engine/gfx/hq2x3x.h
    engines/ags/engine/gfx/ogl_headers.h
    engines/ags/engine/gui/animatingguibutton.cpp
    engines/ags/engine/gui/animatingguibutton.h
    engines/ags/engine/gui/cscidialog.cpp
    engines/ags/engine/gui/cscidialog.h
    engines/ags/engine/gui/gui_engine.cpp
    engines/ags/engine/gui/guidialog.cpp
    engines/ags/engine/gui/guidialogdefines.h
    engines/ags/engine/gui/guidialoginternaldefs.h
    engines/ags/engine/gui/mycontrols.h
    engines/ags/engine/gui/mylabel.cpp
    engines/ags/engine/gui/mylabel.h
    engines/ags/engine/gui/mylistbox.cpp
    engines/ags/engine/gui/mylistbox.h
    engines/ags/engine/gui/mypushbutton.cpp
    engines/ags/engine/gui/mypushbutton.h
    engines/ags/engine/gui/mytextbox.cpp
    engines/ags/engine/gui/mytextbox.h
    engines/ags/engine/gui/newcontrol.cpp
    engines/ags/engine/gui/newcontrol.h
    engines/ags/engine/main/config.cpp
    engines/ags/engine/main/config.h
    engines/ags/engine/main/engine.cpp
    engines/ags/engine/main/engine.h
    engines/ags/engine/main/engine_setup.cpp
    engines/ags/engine/main/engine_setup.h
    engines/ags/engine/main/game_file.cpp
    engines/ags/engine/main/game_file.h
    engines/ags/engine/main/game_run.cpp
    engines/ags/engine/main/game_start.cpp
    engines/ags/engine/main/graphics_mode.cpp
    engines/ags/engine/main/graphics_mode.h
    engines/ags/engine/main/main.cpp
    engines/ags/engine/main/main.h
    engines/ags/engine/main/mainheader.h
    engines/ags/engine/main/quit.cpp
    engines/ags/engine/main/update.cpp
    engines/ags/engine/media/audio/ambientsound.cpp
    engines/ags/engine/media/audio/ambientsound.h
    engines/ags/engine/media/audio/audio.cpp
    engines/ags/engine/media/audio/audio.h
    engines/ags/engine/media/audio/audio_system.h
    engines/ags/engine/media/audio/clip_mydumbmod.cpp
    engines/ags/engine/media/audio/clip_mydumbmod.h
    engines/ags/engine/media/audio/clip_myjgmod.cpp
    engines/ags/engine/media/audio/clip_myjgmod.h
    engines/ags/engine/media/audio/clip_mymidi.cpp
    engines/ags/engine/media/audio/clip_mymidi.h
    engines/ags/engine/media/audio/clip_mymp3.cpp
    engines/ags/engine/media/audio/clip_mymp3.h
    engines/ags/engine/media/audio/clip_myogg.cpp
    engines/ags/engine/media/audio/clip_myogg.h
    engines/ags/engine/media/audio/clip_mystaticmp3.cpp
    engines/ags/engine/media/audio/clip_mystaticmp3.h
    engines/ags/engine/media/audio/clip_mystaticogg.cpp
    engines/ags/engine/media/audio/clip_mystaticogg.h
    engines/ags/engine/media/audio/clip_mywave.cpp
    engines/ags/engine/media/audio/clip_mywave.h
    engines/ags/engine/media/audio/queuedaudioitem.cpp
    engines/ags/engine/media/audio/queuedaudioitem.h
    engines/ags/engine/media/audio/sound.cpp
    engines/ags/engine/media/audio/sound.h
    engines/ags/engine/media/audio/soundcache.cpp
    engines/ags/engine/media/audio/soundcache.h
    engines/ags/engine/media/audio/soundclip.cpp
    engines/ags/engine/media/audio/soundclip.h
    engines/ags/engine/media/video/VMR9Graph.h
    engines/ags/engine/media/video/video.cpp
    engines/ags/engine/platform/android/acpland.cpp
    engines/ags/engine/platform/base/agsplatformdriver.cpp
    engines/ags/engine/platform/base/agsplatformdriver.h
    engines/ags/engine/platform/ios/acplios.cpp
    engines/ags/engine/platform/linux/acpllnx.cpp
    engines/ags/engine/platform/osx/acplmac.cpp
    engines/ags/engine/platform/osx/alplmac.mm
    engines/ags/engine/platform/util/libc.c
    engines/ags/engine/platform/util/pe.c
    engines/ags/engine/platform/windows/acplwin.cpp
    engines/ags/engine/platform/windows/debugging/namedpipesagsdebugger.cpp
    engines/ags/engine/platform/windows/debugging/namedpipesagsdebugger.h
    engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
    engines/ags/engine/platform/windows/gfx/ali3dd3d.h
    engines/ags/engine/platform/windows/media/video/acwavi.cpp
    engines/ags/engine/platform/windows/media/video/acwavi3d.cpp
    engines/ags/engine/platform/windows/minidump.cpp
    engines/ags/engine/platform/windows/setup/winsetup.cpp
    engines/ags/engine/platform/windows/setup/winsetup.h
    engines/ags/engine/platform/windows/win_ex_handling.cpp
    engines/ags/engine/platform/windows/win_ex_handling.h
    engines/ags/engine/plugin/agsplugin.cpp
    engines/ags/engine/plugin/global_plugin.cpp
    engines/ags/engine/plugin/plugin_engine.h
    engines/ags/engine/plugin/pluginobjectreader.cpp
    engines/ags/engine/resource/version.rc
    engines/ags/engine/script/cc_instance.cpp
    engines/ags/engine/script/cc_instance.h
    engines/ags/engine/script/executingscript.cpp
    engines/ags/engine/script/executingscript.h
    engines/ags/engine/script/exports.cpp
    engines/ags/engine/script/nonblockingscriptfunction.h
    engines/ags/engine/script/runtimescriptvalue.cpp
    engines/ags/engine/script/runtimescriptvalue.h
    engines/ags/engine/script/script.cpp
    engines/ags/engine/script/script.h
    engines/ags/engine/script/script_api.cpp
    engines/ags/engine/script/script_api.h
    engines/ags/engine/script/script_engine.cpp
    engines/ags/engine/script/script_runtime.cpp
    engines/ags/engine/script/script_runtime.h
    engines/ags/engine/script/systemimports.cpp
    engines/ags/engine/script/systemimports.h
    engines/ags/engine/util/library.h
    engines/ags/engine/util/library_posix.h
    engines/ags/engine/util/library_psp.h
    engines/ags/engine/util/library_windows.h
    engines/ags/engine/util/mutex.h
    engines/ags/engine/util/mutex_lock.h
    engines/ags/engine/util/mutex_psp.h
    engines/ags/engine/util/mutex_pthread.h
    engines/ags/engine/util/mutex_std.h
    engines/ags/engine/util/mutex_wii.h
    engines/ags/engine/util/scaling.h
    engines/ags/engine/util/thread.h
    engines/ags/engine/util/thread_psp.h
    engines/ags/engine/util/thread_pthread.h
    engines/ags/engine/util/thread_std.h
    engines/ags/engine/util/thread_wii.h
    engines/ags/lib/allegro.h
    engines/ags/lib/allegro/alconfig.h
    engines/ags/lib/allegro/base.h
    engines/ags/lib/allegro/color.h
    engines/ags/lib/allegro/config.h
    engines/ags/lib/allegro/digi.h
    engines/ags/lib/allegro/error.h
    engines/ags/lib/allegro/file.h
    engines/ags/lib/allegro/fixed.h
    engines/ags/lib/allegro/gfx.h
    engines/ags/lib/allegro/keyboard.h
    engines/ags/lib/allegro/midi.h
    engines/ags/lib/allegro/mouse.h
    engines/ags/lib/allegro/sound.h
    engines/ags/lib/allegro/system.h
    engines/ags/lib/allegro/unicode.h
    engines/ags/module.mk
    engines/ags/shared/ac/gamesetupstruct.h
    engines/ags/shared/font/agsfontrenderer.h
    engines/ags/shared/game/room_file.cpp
    engines/ags/shared/util/path.h
    engines/ags/shared/util/string.h


diff --git a/engines/ags/engine/ac/asset_helper.h b/engines/ags/engine/ac/asset_helper.h
index f617444960..84604052ed 100644
--- a/engines/ags/engine/ac/asset_helper.h
+++ b/engines/ags/engine/ac/asset_helper.h
@@ -29,9 +29,9 @@
 #ifndef AGS_ENGINE_AC_ASSETHELPER_H
 #define AGS_ENGINE_AC_ASSETHELPER_H
 
-#include <memory>
-#include <utility>
-#include "util/string.h"
+#include "ags/std/memory.h"
+#include "ags/std/utility.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/audiochannel.cpp b/engines/ags/engine/ac/audiochannel.cpp
index 5d41da4340..9773f5f2b0 100644
--- a/engines/ags/engine/ac/audiochannel.cpp
+++ b/engines/ags/engine/ac/audiochannel.cpp
@@ -20,14 +20,14 @@
  *
  */
 
-#include "ac/audiochannel.h"
-#include "ac/gamestate.h"
-#include "ac/global_audio.h"
-#include "ac/dynobj/cc_audioclip.h"
-#include "debug/debug_log.h"
-#include "game/roomstruct.h"
-#include "script/runtimescriptvalue.h"
-#include "media/audio/audio_system.h"
+#include "ags/engine/ac/audiochannel.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_audio.h"
+#include "ags/engine/ac/dynobj/cc_audioclip.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/shared/game/roomstruct.h"
+#include "ags/engine/script/runtimescriptvalue.h"
+#include "ags/engine/media/audio/audio_system.h"
 
 namespace AGS3 {
 
@@ -202,9 +202,9 @@ void AudioChannel_SetRoomLocation(ScriptAudioChannel *channel, int xPos, int yPo
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
 
 // int | ScriptAudioChannel *channel
 RuntimeScriptValue Sc_AudioChannel_GetID(void *self, const RuntimeScriptValue *params, int32_t param_count) {
diff --git a/engines/ags/engine/ac/audiochannel.h b/engines/ags/engine/ac/audiochannel.h
index 5cb30e14aa..da55ffa702 100644
--- a/engines/ags/engine/ac/audiochannel.h
+++ b/engines/ags/engine/ac/audiochannel.h
@@ -23,8 +23,8 @@
 #ifndef AGS_ENGINE_AC_AUDIOCHANNEL_H
 #define AGS_ENGINE_AC_AUDIOCHANNEL_H
 
-#include "ac/dynobj/scriptaudioclip.h"
-#include "ac/dynobj/scriptaudiochannel.h"
+#include "ags/shared/ac/dynobj/scriptaudioclip.h"
+#include "ags/engine/ac/dynobj/scriptaudiochannel.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/audioclip.cpp b/engines/ags/engine/ac/audioclip.cpp
index 993b72b1c6..412072b346 100644
--- a/engines/ags/engine/ac/audioclip.cpp
+++ b/engines/ags/engine/ac/audioclip.cpp
@@ -20,13 +20,13 @@
  *
  */
 
-#include "ac/asset_helper.h"
-#include "ac/audioclip.h"
-#include "ac/audiochannel.h"
-#include "ac/gamesetupstruct.h"
-#include "script/runtimescriptvalue.h"
-#include "ac/dynobj/cc_audiochannel.h"
-#include "media/audio/audio_system.h"
+#include "ags/engine/ac/asset_helper.h"
+#include "ags/engine/ac/audioclip.h"
+#include "ags/engine/ac/audiochannel.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/engine/script/runtimescriptvalue.h"
+#include "ags/engine/ac/dynobj/cc_audiochannel.h"
+#include "ags/engine/media/audio/audio_system.h"
 
 namespace AGS3 {
 
@@ -80,9 +80,9 @@ ScriptAudioChannel *AudioClip_PlayQueued(ScriptAudioClip *clip, int priority, in
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
 
 RuntimeScriptValue Sc_AudioClip_GetID(void *self, const RuntimeScriptValue *params, int32_t param_count) {
 	API_OBJCALL_INT(ScriptAudioClip, AudioClip_GetID);
diff --git a/engines/ags/engine/ac/audioclip.h b/engines/ags/engine/ac/audioclip.h
index 9f8fab8060..00d8075b97 100644
--- a/engines/ags/engine/ac/audioclip.h
+++ b/engines/ags/engine/ac/audioclip.h
@@ -23,8 +23,8 @@
 #ifndef AGS_ENGINE_AC_AUDIOCLIP_H
 #define AGS_ENGINE_AC_AUDIOCLIP_H
 
-#include "ac/dynobj/scriptaudioclip.h"
-#include "ac/dynobj/scriptaudiochannel.h"
+#include "ags/shared/ac/dynobj/scriptaudioclip.h"
+#include "ags/engine/ac/dynobj/scriptaudiochannel.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/button.cpp b/engines/ags/engine/ac/button.cpp
index 469414fbeb..e533a6384b 100644
--- a/engines/ags/engine/ac/button.cpp
+++ b/engines/ags/engine/ac/button.cpp
@@ -20,17 +20,22 @@
  *
  */
 
-#include "ac/button.h"
-#include "ac/common.h"
-#include "ac/gui.h"
-#include "ac/view.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/global_translation.h"
-#include "ac/string.h"
-#include "ac/viewframe.h"
-#include "debug/debug_log.h"
-#include "gui/animatingguibutton.h"
-#include "gui/guimain.h"
+#include "ags/engine/ac/button.h"
+#include "ags/shared/ac/common.h"
+#include "ags/engine/ac/gui.h"
+#include "ags/shared/ac/view.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/engine/ac/global_translation.h"
+#include "ags/engine/ac/string.h"
+#include "ags/engine/ac/viewframe.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/gui/animatingguibutton.h"
+#include "ags/shared/gui/guimain.h"
+
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
+#include "ags/engine/ac/dynobj/scriptstring.h"
 
 namespace AGS3 {
 
@@ -301,11 +306,6 @@ void Button_SetTextAlignment(GUIButton *butt, int align) {
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
-#include "ac/dynobj/scriptstring.h"
-
 extern ScriptString myScriptStringImpl;
 
 // void | GUIButton *butt, int view, int loop, int speed, int repeat
diff --git a/engines/ags/engine/ac/button.h b/engines/ags/engine/ac/button.h
index f8293b4056..64215f89fd 100644
--- a/engines/ags/engine/ac/button.h
+++ b/engines/ags/engine/ac/button.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_BUTTON_H
 #define AGS_ENGINE_AC_BUTTON_H
 
-#include "gui/guibutton.h"
+#include "ags/shared/gui/guibutton.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/cdaudio.cpp b/engines/ags/engine/ac/cdaudio.cpp
index 04feb2c3bc..fc8cbd26c6 100644
--- a/engines/ags/engine/ac/cdaudio.cpp
+++ b/engines/ags/engine/ac/cdaudio.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ac/cdaudio.h"
-#include "platform/base/agsplatformdriver.h"
+#include "ags/engine/ac/cdaudio.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/character.cpp b/engines/ags/engine/ac/character.cpp
index 34890ee440..ee3ea08a58 100644
--- a/engines/ags/engine/ac/character.cpp
+++ b/engines/ags/engine/ac/character.cpp
@@ -26,50 +26,50 @@
 //
 //=============================================================================
 
-#include "ac/character.h"
-#include "ac/common.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/view.h"
-#include "ac/display.h"
-#include "ac/draw.h"
-#include "ac/event.h"
-#include "ac/game.h"
-#include "ac/global_audio.h"
-#include "ac/global_character.h"
-#include "ac/global_game.h"
-#include "ac/global_object.h"
-#include "ac/global_region.h"
-#include "ac/global_room.h"
-#include "ac/global_translation.h"
-#include "ac/gui.h"
-#include "ac/lipsync.h"
-#include "ac/mouse.h"
-#include "ac/object.h"
-#include "ac/overlay.h"
-#include "ac/properties.h"
-#include "ac/room.h"
-#include "ac/screenoverlay.h"
-#include "ac/string.h"
-#include "ac/system.h"
-#include "ac/viewframe.h"
-#include "ac/walkablearea.h"
-#include "gui/guimain.h"
-#include "ac/route_finder.h"
-#include "ac/gamestate.h"
-#include "debug/debug_log.h"
-#include "main/game_run.h"
-#include "main/update.h"
-#include "ac/spritecache.h"
-#include "util/string_compat.h"
-#include <math.h>
-#include "gfx/graphicsdriver.h"
-#include "script/runtimescriptvalue.h"
-#include "ac/dynobj/cc_character.h"
-#include "ac/dynobj/cc_inventory.h"
-#include "script/script_runtime.h"
-#include "gfx/gfx_def.h"
-#include "media/audio/audio_system.h"
-#include "ac/movelist.h"
+#include "ags/shared/ac/character.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/view.h"
+#include "ags/shared/ac/display.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/event.h"
+#include "ags/shared/ac/game.h"
+#include "ags/shared/ac/global_audio.h"
+#include "ags/shared/ac/global_character.h"
+#include "ags/shared/ac/global_game.h"
+#include "ags/shared/ac/global_object.h"
+#include "ags/shared/ac/global_region.h"
+#include "ags/shared/ac/global_room.h"
+#include "ags/shared/ac/global_translation.h"
+#include "ags/shared/ac/gui.h"
+#include "ags/shared/ac/lipsync.h"
+#include "ags/shared/ac/mouse.h"
+#include "ags/shared/ac/object.h"
+#include "ags/shared/ac/overlay.h"
+#include "ags/shared/ac/properties.h"
+#include "ags/shared/ac/room.h"
+#include "ags/shared/ac/screenoverlay.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/ac/system.h"
+#include "ags/shared/ac/viewframe.h"
+#include "ags/shared/ac/walkablearea.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/ac/route_finder.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/main/game_run.h"
+#include "ags/shared/main/update.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/util/string_compat.h"
+//include <math.h>
+#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/shared/script/runtimescriptvalue.h"
+#include "ags/shared/ac/dynobj/cc_character.h"
+#include "ags/shared/ac/dynobj/cc_inventory.h"
+#include "ags/shared/script/script_runtime.h"
+#include "ags/shared/gfx/gfx_def.h"
+#include "ags/shared/media/audio/audio_system.h"
+#include "ags/shared/ac/movelist.h"
 
 namespace AGS3 {
 
@@ -2848,10 +2848,10 @@ PViewport FindNearestViewport(int charid) {
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
-#include "ac/dynobj/scriptstring.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
+#include "ags/shared/ac/dynobj/scriptstring.h"
 
 extern ScriptString myScriptStringImpl;
 
diff --git a/engines/ags/engine/ac/character.h b/engines/ags/engine/ac/character.h
index c275cfd237..c2ee1c668a 100644
--- a/engines/ags/engine/ac/character.h
+++ b/engines/ags/engine/ac/character.h
@@ -23,13 +23,13 @@
 #ifndef AGS_ENGINE_AC_CHARACTER_H
 #define AGS_ENGINE_AC_CHARACTER_H
 
-#include "ac/characterinfo.h"
-#include "ac/characterextras.h"
-#include "ac/dynobj/scriptobject.h"
-#include "ac/dynobj/scriptinvitem.h"
-#include "ac/dynobj/scriptoverlay.h"
-#include "game/viewport.h"
-#include "util/geometry.h"
+#include "ags/shared/ac/characterinfo.h"
+#include "ags/engine/ac/characterextras.h"
+#include "ags/engine/ac/dynobj/scriptobject.h"
+#include "ags/engine/ac/dynobj/scriptinvitem.h"
+#include "ags/engine/ac/dynobj/scriptoverlay.h"
+#include "ags/engine/game/viewport.h"
+#include "ags/shared/util/geometry.h"
 
 namespace AGS3 {
 
@@ -193,14 +193,14 @@ int  is_valid_character(int newchar);
 int  wantMoveNow(CharacterInfo *chi, CharacterExtras *chex);
 void setup_player_character(int charid);
 void CheckViewFrameForCharacter(CharacterInfo *chi);
-Common::Bitmap *GetCharacterImage(int charid, int *isFlipped);
+Shared::Bitmap *GetCharacterImage(int charid, int *isFlipped);
 CharacterInfo *GetCharacterAtScreen(int xx, int yy);
 // Get character ID at the given room coordinates
 int is_pos_on_character(int xx, int yy);
 void get_char_blocking_rect(int charid, int *x1, int *y1, int *width, int *y2);
 // Check whether the source char has walked onto character ww
 int is_char_on_another(int sourceChar, int ww, int *fromxptr, int *cwidptr);
-int my_getpixel(Common::Bitmap *blk, int x, int y);
+int my_getpixel(Shared::Bitmap *blk, int x, int y);
 // X and Y co-ordinates must be in 320x200 format
 int check_click_on_character(int xx, int yy, int mood);
 int is_pos_on_character(int xx, int yy);
diff --git a/engines/ags/engine/ac/charactercache.h b/engines/ags/engine/ac/charactercache.h
index 4d44bfeffd..1b1810fb4f 100644
--- a/engines/ags/engine/ac/charactercache.h
+++ b/engines/ags/engine/ac/charactercache.h
@@ -28,13 +28,14 @@ namespace AGS3 {
 namespace AGS {
 namespace Shared {
 class Bitmap;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 // stores cached info about the character
 struct CharacterCache {
-	Common::Bitmap *image;
+	Shared::Bitmap *image;
 	int sppic;
 	int scaling;
 	int inUse;
diff --git a/engines/ags/engine/ac/characterextras.cpp b/engines/ags/engine/ac/characterextras.cpp
index 6915dca2bc..e0e80a0bc5 100644
--- a/engines/ags/engine/ac/characterextras.cpp
+++ b/engines/ags/engine/ac/characterextras.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ac/characterextras.h"
-#include "util/stream.h"
+#include "ags/shared/ac/characterextras.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/characterextras.h b/engines/ags/engine/ac/characterextras.h
index a94ef18b43..906282b5f5 100644
--- a/engines/ags/engine/ac/characterextras.h
+++ b/engines/ags/engine/ac/characterextras.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_CHARACTEREXTRAS_H
 #define AGS_ENGINE_AC_CHARACTEREXTRAS_H
 
-#include "ac/runtime_defines.h"
+#include "ags/engine/ac/runtime_defines.h"
 
 namespace AGS3 {
 
@@ -56,8 +56,8 @@ struct CharacterExtras {
 	char  slow_move_counter;
 	short animwait;
 
-	void ReadFromFile(Common::Stream *in);
-	void WriteToFile(Common::Stream *out);
+	void ReadFromFile(Shared::Stream *in);
+	void WriteToFile(Shared::Stream *out);
 };
 
 } // namespace AGS3
diff --git a/engines/ags/engine/ac/characterinfo_engine.cpp b/engines/ags/engine/ac/characterinfo_engine.cpp
index e9e2bcff84..74118dce63 100644
--- a/engines/ags/engine/ac/characterinfo_engine.cpp
+++ b/engines/ags/engine/ac/characterinfo_engine.cpp
@@ -20,20 +20,20 @@
  *
  */
 
-#include "ac/characterinfo.h"
-#include "ac/common.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/character.h"
-#include "ac/characterextras.h"
-#include "ac/gamestate.h"
-#include "ac/global_character.h"
-#include "ac/math.h"
-#include "ac/viewframe.h"
-#include "debug/debug_log.h"
-#include "game/roomstruct.h"
-#include "main/maindefines_ex.h"    // RETURN_CONTINUE
-#include "main/update.h"
-#include "media/audio/audio_system.h"
+#include "ags/shared/ac/characterinfo.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/character.h"
+#include "ags/shared/ac/characterextras.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_character.h"
+#include "ags/shared/ac/math.h"
+#include "ags/shared/ac/viewframe.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/game/roomstruct.h"
+#include "ags/shared/main/maindefines_ex.h"    // RETURN_CONTINUE
+#include "ags/shared/main/update.h"
+#include "ags/shared/media/audio/audio_system.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/datetime.cpp b/engines/ags/engine/ac/datetime.cpp
index 9821802720..c46c458995 100644
--- a/engines/ags/engine/ac/datetime.cpp
+++ b/engines/ags/engine/ac/datetime.cpp
@@ -20,10 +20,10 @@
  *
  */
 
-#include <time.h>
-#include "ac/datetime.h"
-#include "platform/base/agsplatformdriver.h"
-#include "script/runtimescriptvalue.h"
+//include <time.h>
+#include "ags/shared/ac/datetime.h"
+#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/shared/script/runtimescriptvalue.h"
 
 namespace AGS3 {
 
@@ -75,9 +75,9 @@ int DateTime_GetRawTime(ScriptDateTime *sdt) {
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
 
 // ScriptDateTime* ()
 RuntimeScriptValue Sc_DateTime_Now(const RuntimeScriptValue *params, int32_t param_count) {
diff --git a/engines/ags/engine/ac/datetime.h b/engines/ags/engine/ac/datetime.h
index 6febc33f6a..8711739518 100644
--- a/engines/ags/engine/ac/datetime.h
+++ b/engines/ags/engine/ac/datetime.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DATETIME_H
 #define AGS_ENGINE_AC_DATETIME_H
 
-#include "ac/dynobj/scriptdatetime.h"
+#include "ags/engine/ac/dynobj/scriptdatetime.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dialog.cpp b/engines/ags/engine/ac/dialog.cpp
index 6d1f3e98b0..4f3522da9a 100644
--- a/engines/ags/engine/ac/dialog.cpp
+++ b/engines/ags/engine/ac/dialog.cpp
@@ -20,45 +20,45 @@
  *
  */
 
-#include "ac/dialog.h"
-#include "ac/common.h"
-#include "ac/character.h"
-#include "ac/characterinfo.h"
-#include "ac/dialogtopic.h"
-#include "ac/display.h"
-#include "ac/draw.h"
-#include "ac/gamestate.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/global_character.h"
-#include "ac/global_dialog.h"
-#include "ac/global_display.h"
-#include "ac/global_game.h"
-#include "ac/global_gui.h"
-#include "ac/global_room.h"
-#include "ac/global_translation.h"
-#include "ac/keycode.h"
-#include "ac/overlay.h"
-#include "ac/mouse.h"
-#include "ac/parser.h"
-#include "ac/sys_events.h"
-#include "ac/string.h"
-#include "ac/dynobj/scriptdialogoptionsrendering.h"
-#include "ac/dynobj/scriptdrawingsurface.h"
-#include "ac/system.h"
-#include "debug/debug_log.h"
-#include "font/fonts.h"
-#include "script/cc_instance.h"
-#include "gui/guimain.h"
-#include "gui/guitextbox.h"
-#include "main/game_run.h"
-#include "platform/base/agsplatformdriver.h"
-#include "script/script.h"
-#include "ac/spritecache.h"
-#include "gfx/ddb.h"
-#include "gfx/gfx_util.h"
-#include "gfx/graphicsdriver.h"
-#include "ac/mouse.h"
-#include "media/audio/audio_system.h"
+#include "ags/shared/ac/dialog.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/character.h"
+#include "ags/shared/ac/characterinfo.h"
+#include "ags/shared/ac/dialogtopic.h"
+#include "ags/shared/ac/display.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/global_character.h"
+#include "ags/shared/ac/global_dialog.h"
+#include "ags/shared/ac/global_display.h"
+#include "ags/shared/ac/global_game.h"
+#include "ags/shared/ac/global_gui.h"
+#include "ags/shared/ac/global_room.h"
+#include "ags/shared/ac/global_translation.h"
+#include "ags/shared/ac/keycode.h"
+#include "ags/shared/ac/overlay.h"
+#include "ags/shared/ac/mouse.h"
+#include "ags/shared/ac/parser.h"
+#include "ags/shared/ac/sys_events.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/ac/dynobj/scriptdialogoptionsrendering.h"
+#include "ags/shared/ac/dynobj/scriptdrawingsurface.h"
+#include "ags/shared/ac/system.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/font/fonts.h"
+#include "ags/shared/script/cc_instance.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/gui/guitextbox.h"
+#include "ags/shared/main/game_run.h"
+#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/shared/script/script.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/gfx/ddb.h"
+#include "ags/shared/gfx/gfx_util.h"
+#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/shared/ac/mouse.h"
+#include "ags/shared/media/audio/audio_system.h"
 
 namespace AGS3 {
 
@@ -1148,10 +1148,10 @@ void do_conversation(int dlgnum) {
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
-#include "ac/dynobj/scriptstring.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
+#include "ags/shared/ac/dynobj/scriptstring.h"
 
 extern ScriptString myScriptStringImpl;
 
diff --git a/engines/ags/engine/ac/dialog.h b/engines/ags/engine/ac/dialog.h
index 7436d41466..696c195b5e 100644
--- a/engines/ags/engine/ac/dialog.h
+++ b/engines/ags/engine/ac/dialog.h
@@ -23,8 +23,8 @@
 #ifndef AGS_ENGINE_AC_DIALOG_H
 #define AGS_ENGINE_AC_DIALOG_H
 
-#include <vector>
-#include "ac/dynobj/scriptdialog.h"
+#include "ags/std/vector.h"
+#include "ags/engine/ac/dynobj/scriptdialog.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dialogoptionsrendering.cpp b/engines/ags/engine/ac/dialogoptionsrendering.cpp
index 39b2b2c466..f7bf6a5453 100644
--- a/engines/ags/engine/ac/dialogoptionsrendering.cpp
+++ b/engines/ags/engine/ac/dialogoptionsrendering.cpp
@@ -20,13 +20,13 @@
  *
  */
 
-#include "ac/dialog.h"
-#include "ac/dialogtopic.h"
-#include "ac/dialogoptionsrendering.h"
-#include "ac/gamestructdefines.h"
-#include "debug/debug_log.h"
-#include "script/runtimescriptvalue.h"
-#include "ac/dynobj/cc_dialog.h"
+#include "ags/shared/ac/dialog.h"
+#include "ags/shared/ac/dialogtopic.h"
+#include "ags/shared/ac/dialogoptionsrendering.h"
+#include "ags/shared/ac/gamestructdefines.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/script/runtimescriptvalue.h"
+#include "ags/shared/ac/dynobj/cc_dialog.h"
 
 namespace AGS3 {
 
@@ -138,9 +138,9 @@ void DialogOptionsRendering_SetActiveOptionID(ScriptDialogOptionsRendering *dlgO
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
 
 RuntimeScriptValue Sc_DialogOptionsRendering_Update(void *self, const RuntimeScriptValue *params, int32_t param_count) {
 	API_OBJCALL_VOID(ScriptDialogOptionsRendering, DialogOptionsRendering_Update);
diff --git a/engines/ags/engine/ac/dialogoptionsrendering.h b/engines/ags/engine/ac/dialogoptionsrendering.h
index 4f8584c271..2ab24033e2 100644
--- a/engines/ags/engine/ac/dialogoptionsrendering.h
+++ b/engines/ags/engine/ac/dialogoptionsrendering.h
@@ -23,8 +23,8 @@
 #ifndef AGS_ENGINE_AC_DIALOGOPTIONSRENDERING_H
 #define AGS_ENGINE_AC_DIALOGOPTIONSRENDERING_H
 
-#include "ac/dynobj/scriptdialog.h"
-#include "ac/dynobj/scriptdialogoptionsrendering.h"
+#include "ags/engine/ac/dynobj/scriptdialog.h"
+#include "ags/engine/ac/dynobj/scriptdialogoptionsrendering.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/display.cpp b/engines/ags/engine/ac/display.cpp
index 017c573034..cfbc137cdf 100644
--- a/engines/ags/engine/ac/display.cpp
+++ b/engines/ags/engine/ac/display.cpp
@@ -20,40 +20,40 @@
  *
  */
 
-#include <math.h>
-
-#include "ac/display.h"
-#include "ac/common.h"
-#include "font/agsfontrenderer.h"
-#include "font/fonts.h"
-#include "ac/character.h"
-#include "ac/draw.h"
-#include "ac/game.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/global_audio.h"
-#include "ac/global_game.h"
-#include "ac/gui.h"
-#include "ac/mouse.h"
-#include "ac/overlay.h"
-#include "ac/sys_events.h"
-#include "ac/screenoverlay.h"
-#include "ac/speech.h"
-#include "ac/string.h"
-#include "ac/system.h"
-#include "ac/topbarsettings.h"
-#include "debug/debug_log.h"
-#include "gfx/blender.h"
-#include "gui/guibutton.h"
-#include "gui/guimain.h"
-#include "main/game_run.h"
-#include "platform/base/agsplatformdriver.h"
-#include "ac/spritecache.h"
-#include "gfx/gfx_util.h"
-#include "util/string_utils.h"
-#include "ac/mouse.h"
-#include "media/audio/audio_system.h"
-#include "ac/timer.h"
+//include <math.h>
+
+#include "ags/shared/ac/display.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/font/agsfontrenderer.h"
+#include "ags/shared/font/fonts.h"
+#include "ags/shared/ac/character.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/game.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_audio.h"
+#include "ags/shared/ac/global_game.h"
+#include "ags/shared/ac/gui.h"
+#include "ags/shared/ac/mouse.h"
+#include "ags/shared/ac/overlay.h"
+#include "ags/shared/ac/sys_events.h"
+#include "ags/shared/ac/screenoverlay.h"
+#include "ags/shared/ac/speech.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/ac/system.h"
+#include "ags/shared/ac/topbarsettings.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/gfx/blender.h"
+#include "ags/shared/gui/guibutton.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/main/game_run.h"
+#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/gfx/gfx_util.h"
+#include "ags/shared/util/string_utils.h"
+#include "ags/shared/ac/mouse.h"
+#include "ags/shared/media/audio/audio_system.h"
+#include "ags/shared/ac/timer.h"
 
 namespace AGS3 {
 
@@ -530,7 +530,7 @@ void wouttextxy_AutoOutline(Bitmap *ds, size_t font, int32_t color, const char *
 }
 
 // Draw an outline if requested, then draw the text on top
-void wouttext_outline(Common::Bitmap *ds, int xxp, int yyp, int font, color_t text_color, const char *texx) {
+void wouttext_outline(Shared::Bitmap *ds, int xxp, int yyp, int font, color_t text_color, const char *texx) {
 	size_t const text_font = static_cast<size_t>(font);
 	// Draw outline (a backdrop) if requested
 	color_t const outline_color = ds->GetCompatibleColor(play.speech_text_shadow);
diff --git a/engines/ags/engine/ac/display.h b/engines/ags/engine/ac/display.h
index 44a0df2479..d202c03fba 100644
--- a/engines/ags/engine/ac/display.h
+++ b/engines/ags/engine/ac/display.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DISPLAY_H
 #define AGS_ENGINE_AC_DISPLAY_H
 
-#include "gui/guimain.h"
+#include "ags/shared/gui/guimain.h"
 
 namespace AGS3 {
 
@@ -48,8 +48,8 @@ int GetTextDisplayLength(const char *text);
 // Calculates number of game loops for displaying a text on screen
 int GetTextDisplayTime(const char *text, int canberel = 0);
 // Draw an outline if requested, then draw the text on top
-void wouttext_outline(Common::Bitmap *ds, int xxp, int yyp, int usingfont, color_t text_color, const char *texx);
-void wouttext_aligned(Common::Bitmap *ds, int usexp, int yy, int oriwid, int usingfont, color_t text_color, const char *text, HorAlignment align);
+void wouttext_outline(Shared::Bitmap *ds, int xxp, int yyp, int usingfont, color_t text_color, const char *texx);
+void wouttext_aligned(Shared::Bitmap *ds, int usexp, int yy, int oriwid, int usingfont, color_t text_color, const char *text, HorAlignment align);
 // TODO: GUI classes located in Common library do not make use of outlining,
 // need to find a way to make all code use same functions.
 // Get the maximal height of the given font, with corresponding outlining
@@ -62,10 +62,10 @@ int getfontlinegap(int font);
 int getheightoflines(int font, int numlines);
 // Get the maximal width of the given font, with corresponding outlining
 int wgettextwidth_compensate(const char *tex, int font);
-void do_corner(Common::Bitmap *ds, int sprn, int xx1, int yy1, int typx, int typy);
+void do_corner(Shared::Bitmap *ds, int sprn, int xx1, int yy1, int typx, int typy);
 // Returns the image of a button control on the GUI under given child index
 int get_but_pic(GUIMain *guo, int indx);
-void draw_button_background(Common::Bitmap *ds, int xx1, int yy1, int xx2, int yy2, GUIMain *iep);
+void draw_button_background(Shared::Bitmap *ds, int xx1, int yy1, int xx2, int yy2, GUIMain *iep);
 // Calculate the width that the left and right border of the textwindow
 // GUI take up
 int get_textwindow_border_width(int twgui);
@@ -76,8 +76,8 @@ int get_textwindow_top_border_height(int twgui);
 //   point text_window_ds to it
 // returns text start x & y pos in parameters
 // Warning!: draw_text_window() and draw_text_window_and_bar() can create new text_window_ds
-void draw_text_window(Common::Bitmap **text_window_ds, bool should_free_ds, int *xins, int *yins, int *xx, int *yy, int *wii, color_t *set_text_color, int ovrheight, int ifnum);
-void draw_text_window_and_bar(Common::Bitmap **text_window_ds, bool should_free_ds,
+void draw_text_window(Shared::Bitmap **text_window_ds, bool should_free_ds, int *xins, int *yins, int *xx, int *yy, int *wii, color_t *set_text_color, int ovrheight, int ifnum);
+void draw_text_window_and_bar(Shared::Bitmap **text_window_ds, bool should_free_ds,
 	int *xins, int *yins, int *xx, int *yy, int *wii, color_t *set_text_color, int ovrheight = 0, int ifnum = -1);
 int get_textwindow_padding(int ifnum);
 
diff --git a/engines/ags/engine/ac/draw.cpp b/engines/ags/engine/ac/draw.cpp
index 374c218ba7..7ac126608e 100644
--- a/engines/ags/engine/ac/draw.cpp
+++ b/engines/ags/engine/ac/draw.cpp
@@ -20,56 +20,56 @@
  *
  */
 
-#include <algorithm>
-#include <cmath>
-#include "aastr.h"
-#include "core/platform.h"
-#include "ac/common.h"
-#include "util/compress.h"
-#include "ac/view.h"
-#include "ac/charactercache.h"
-#include "ac/characterextras.h"
-#include "ac/characterinfo.h"
-#include "ac/display.h"
-#include "ac/draw.h"
-#include "ac/draw_software.h"
-#include "ac/gamesetup.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/global_game.h"
-#include "ac/global_gui.h"
-#include "ac/global_region.h"
-#include "ac/gui.h"
-#include "ac/mouse.h"
-#include "ac/objectcache.h"
-#include "ac/overlay.h"
-#include "ac/sys_events.h"
-#include "ac/roomobject.h"
-#include "ac/roomstatus.h"
-#include "ac/runtime_defines.h"
-#include "ac/screenoverlay.h"
-#include "ac/sprite.h"
-#include "ac/spritelistentry.h"
-#include "ac/string.h"
-#include "ac/system.h"
-#include "ac/viewframe.h"
-#include "ac/walkablearea.h"
-#include "ac/walkbehind.h"
-#include "ac/dynobj/scriptsystem.h"
-#include "debug/debugger.h"
-#include "debug/debug_log.h"
-#include "font/fonts.h"
-#include "gui/guimain.h"
-#include "platform/base/agsplatformdriver.h"
-#include "plugin/agsplugin.h"
-#include "plugin/plugin_engine.h"
-#include "ac/spritecache.h"
-#include "gfx/gfx_util.h"
-#include "gfx/graphicsdriver.h"
-#include "gfx/ali3dexception.h"
-#include "gfx/blender.h"
-#include "media/audio/audio_system.h"
-#include "ac/game.h"
+//include <algorithm>
+//include <cmath>
+#include "ags/shared/aastr.h"
+#include "ags/shared/core/platform.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/util/compress.h"
+#include "ags/shared/ac/view.h"
+#include "ags/shared/ac/charactercache.h"
+#include "ags/shared/ac/characterextras.h"
+#include "ags/shared/ac/characterinfo.h"
+#include "ags/shared/ac/display.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/draw_software.h"
+#include "ags/shared/ac/gamesetup.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_game.h"
+#include "ags/shared/ac/global_gui.h"
+#include "ags/shared/ac/global_region.h"
+#include "ags/shared/ac/gui.h"
+#include "ags/shared/ac/mouse.h"
+#include "ags/shared/ac/objectcache.h"
+#include "ags/shared/ac/overlay.h"
+#include "ags/shared/ac/sys_events.h"
+#include "ags/shared/ac/roomobject.h"
+#include "ags/shared/ac/roomstatus.h"
+#include "ags/shared/ac/runtime_defines.h"
+#include "ags/shared/ac/screenoverlay.h"
+#include "ags/shared/ac/sprite.h"
+#include "ags/shared/ac/spritelistentry.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/ac/system.h"
+#include "ags/shared/ac/viewframe.h"
+#include "ags/shared/ac/walkablearea.h"
+#include "ags/shared/ac/walkbehind.h"
+#include "ags/shared/ac/dynobj/scriptsystem.h"
+#include "ags/shared/debug/debugger.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/font/fonts.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/shared/plugin/agsplugin.h"
+#include "ags/shared/plugin/plugin_engine.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/gfx/gfx_util.h"
+#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/shared/gfx/ali3dexception.h"
+#include "ags/shared/gfx/blender.h"
+#include "ags/shared/media/audio/audio_system.h"
+#include "ags/shared/ac/game.h"
 
 namespace AGS3 {
 
@@ -77,8 +77,8 @@ using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 #if AGS_PLATFORM_OS_ANDROID
-#include <sys/stat.h>
-#include <android/log.h>
+//include <sys/stat.h>
+//include <android/log.h>
 
 extern "C" void android_render();
 #endif
diff --git a/engines/ags/engine/ac/draw.h b/engines/ags/engine/ac/draw.h
index e100230c9b..42437b6f9d 100644
--- a/engines/ags/engine/ac/draw.h
+++ b/engines/ags/engine/ac/draw.h
@@ -23,18 +23,18 @@
 #ifndef AGS_ENGINE_AC_DRAW_H
 #define AGS_ENGINE_AC_DRAW_H
 
-#include <memory>
-#include "core/types.h"
-#include "ac/common_defines.h"
-#include "gfx/gfx_def.h"
-#include "util/wgt2allg.h"
+#include "ags/std/memory.h"
+#include "ags/shared/core/types.h"
+#include "ags/shared/ac/common_defines.h"
+#include "ags/shared/gfx/gfx_def.h"
+#include "ags/shared/util/wgt2allg.h"
 
 namespace AGS3 {
 
 namespace AGS {
 namespace Shared {
 class Bitmap;
-typedef std::shared_ptr<Common::Bitmap> PBitmap;
+typedef std::shared_ptr<Shared::Bitmap> PBitmap;
 }
 namespace Engine {
 class IDriverDependantBitmap;
@@ -104,8 +104,8 @@ void invalidate_rect(int x1, int y1, int x2, int y2, bool in_room);
 void mark_current_background_dirty();
 void invalidate_cached_walkbehinds();
 // Avoid freeing and reallocating the memory if possible
-Common::Bitmap *recycle_bitmap(Common::Bitmap *bimp, int coldep, int wid, int hit, bool make_transparent = false);
-Engine::IDriverDependantBitmap *recycle_ddb_bitmap(Engine::IDriverDependantBitmap *bimp, Common::Bitmap *source, bool hasAlpha = false, bool opaque = false);
+Shared::Bitmap *recycle_bitmap(Shared::Bitmap *bimp, int coldep, int wid, int hit, bool make_transparent = false);
+Engine::IDriverDependantBitmap *recycle_ddb_bitmap(Engine::IDriverDependantBitmap *bimp, Shared::Bitmap *source, bool hasAlpha = false, bool opaque = false);
 // Draw everything
 void render_graphics(Engine::IDriverDependantBitmap *extraBitmap = nullptr, int extraX = 0, int extraY = 0);
 // Construct game scene, scheduling drawing list for the renderer
@@ -115,27 +115,27 @@ void construct_game_screen_overlay(bool draw_mouse = true);
 // Construct engine overlay with debugging tools (fps, console)
 void construct_engine_overlay();
 void add_to_sprite_list(Engine::IDriverDependantBitmap *spp, int xx, int yy, int baseline, int trans, int sprNum, bool isWalkBehind = false);
-void tint_image(Common::Bitmap *g, Common::Bitmap *source, int red, int grn, int blu, int light_level, int luminance = 255);
-void draw_sprite_support_alpha(Common::Bitmap *ds, bool ds_has_alpha, int xpos, int ypos, Common::Bitmap *image, bool src_has_alpha,
-	Common::BlendMode blend_mode = Common::kBlendMode_Alpha, int alpha = 0xFF);
-void draw_sprite_slot_support_alpha(Common::Bitmap *ds, bool ds_has_alpha, int xpos, int ypos, int src_slot,
-	Common::BlendMode blend_mode = Common::kBlendMode_Alpha, int alpha = 0xFF);
-void draw_gui_sprite(Common::Bitmap *ds, int pic, int x, int y, bool use_alpha, Common::BlendMode blend_mode);
-void draw_gui_sprite_v330(Common::Bitmap *ds, int pic, int x, int y, bool use_alpha = true, Common::BlendMode blend_mode = Common::kBlendMode_Alpha);
+void tint_image(Shared::Bitmap *g, Shared::Bitmap *source, int red, int grn, int blu, int light_level, int luminance = 255);
+void draw_sprite_support_alpha(Shared::Bitmap *ds, bool ds_has_alpha, int xpos, int ypos, Shared::Bitmap *image, bool src_has_alpha,
+	Shared::BlendMode blend_mode = Shared::kBlendMode_Alpha, int alpha = 0xFF);
+void draw_sprite_slot_support_alpha(Shared::Bitmap *ds, bool ds_has_alpha, int xpos, int ypos, int src_slot,
+	Shared::BlendMode blend_mode = Shared::kBlendMode_Alpha, int alpha = 0xFF);
+void draw_gui_sprite(Shared::Bitmap *ds, int pic, int x, int y, bool use_alpha, Shared::BlendMode blend_mode);
+void draw_gui_sprite_v330(Shared::Bitmap *ds, int pic, int x, int y, bool use_alpha = true, Shared::BlendMode blend_mode = Shared::kBlendMode_Alpha);
 // Render game on screen
 void render_to_screen();
 // Callbacks for the graphics driver
 void draw_game_screen_callback();
 void GfxDriverOnInitCallback(void *data);
 bool GfxDriverNullSpriteCallback(int x, int y);
-void putpixel_compensate(Common::Bitmap *g, int xx, int yy, int col);
+void putpixel_compensate(Shared::Bitmap *g, int xx, int yy, int col);
 // create the actsps[aa] image with the object drawn correctly
 // returns 1 if nothing at all has changed and actsps is still
 // intact from last time; 0 otherwise
 int construct_object_gfx(int aa, int *drawnWidth, int *drawnHeight, bool alwaysUseSoftware);
 void clear_letterbox_borders();
 
-void draw_and_invalidate_text(Common::Bitmap *ds, int x1, int y1, int font, color_t text_color, const char *text);
+void draw_and_invalidate_text(Shared::Bitmap *ds, int x1, int y1, int font, color_t text_color, const char *text);
 
 void setpal();
 
@@ -167,17 +167,17 @@ extern AGS_INLINE void defgame_to_finalgame_coords(int &x, int &y);
 // TODO: this helper function was meant to remove bitmap deletion from the GraphicsDriver's
 // implementations while keeping code changes to minimum. The proper solution would probably
 // be to use shared pointers when storing Bitmaps, or make Bitmap reference-counted object.
-Common::Bitmap *ReplaceBitmapWithSupportedFormat(Common::Bitmap *bitmap);
+Shared::Bitmap *ReplaceBitmapWithSupportedFormat(Shared::Bitmap *bitmap);
 // Checks if the bitmap needs any kind of adjustments before it may be used
 // in AGS sprite operations. Also handles number of certain special cases
 // (old systems or uncommon gfx modes, and similar stuff).
 // Original bitmap **gets deleted** if a new bitmap had to be created.
-Common::Bitmap *PrepareSpriteForUse(Common::Bitmap *bitmap, bool has_alpha);
+Shared::Bitmap *PrepareSpriteForUse(Shared::Bitmap *bitmap, bool has_alpha);
 // Same as above, but compatible for std::shared_ptr.
-Common::PBitmap PrepareSpriteForUse(Common::PBitmap bitmap, bool has_alpha);
+Shared::PBitmap PrepareSpriteForUse(Shared::PBitmap bitmap, bool has_alpha);
 // Makes a screenshot corresponding to the last screen render and returns it as a bitmap
 // of the requested width and height and game's native color depth.
-Common::Bitmap *CopyScreenIntoBitmap(int width, int height, bool at_native_res = false);
+Shared::Bitmap *CopyScreenIntoBitmap(int width, int height, bool at_native_res = false);
 
 } // namespace AGS3
 
diff --git a/engines/ags/engine/ac/draw_software.cpp b/engines/ags/engine/ac/draw_software.cpp
index 917b4cd0ea..ab4412a427 100644
--- a/engines/ags/engine/ac/draw_software.cpp
+++ b/engines/ags/engine/ac/draw_software.cpp
@@ -46,11 +46,11 @@
 //
 //=============================================================================
 
-#include <string.h>
-#include <vector>
-#include "ac/draw_software.h"
-#include "gfx/bitmap.h"
-#include "util/scaling.h"
+//include <string.h>
+#include "ags/std/vector.h"
+#include "ags/shared/ac/draw_software.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/util/scaling.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/draw_software.h b/engines/ags/engine/ac/draw_software.h
index aee7079dde..7a28ca0d7c 100644
--- a/engines/ags/engine/ac/draw_software.h
+++ b/engines/ags/engine/ac/draw_software.h
@@ -30,9 +30,9 @@
 #ifndef AGS_ENGINE_AC_DRAWSOFTWARE_H
 #define AGS_ENGINE_AC_DRAWSOFTWARE_H
 
-#include "gfx/bitmap.h"
-#include "gfx/ddb.h"
-#include "util/geometry.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/engine/gfx/ddb.h"
+#include "ags/shared/util/geometry.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/drawingsurface.cpp b/engines/ags/engine/ac/drawingsurface.cpp
index d4fb8cd14b..a0a6f494f5 100644
--- a/engines/ags/engine/ac/drawingsurface.cpp
+++ b/engines/ags/engine/ac/drawingsurface.cpp
@@ -20,27 +20,27 @@
  *
  */
 
-#include "ac/draw.h"
-#include "ac/drawingsurface.h"
-#include "ac/common.h"
-#include "ac/charactercache.h"
-#include "ac/display.h"
-#include "ac/game.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/global_translation.h"
-#include "ac/objectcache.h"
-#include "ac/roomobject.h"
-#include "ac/roomstatus.h"
-#include "ac/string.h"
-#include "ac/walkbehind.h"
-#include "debug/debug_log.h"
-#include "font/fonts.h"
-#include "gui/guimain.h"
-#include "ac/spritecache.h"
-#include "script/runtimescriptvalue.h"
-#include "gfx/gfx_def.h"
-#include "gfx/gfx_util.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/drawingsurface.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/charactercache.h"
+#include "ags/shared/ac/display.h"
+#include "ags/shared/ac/game.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_translation.h"
+#include "ags/shared/ac/objectcache.h"
+#include "ags/shared/ac/roomobject.h"
+#include "ags/shared/ac/roomstatus.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/ac/walkbehind.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/font/fonts.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/script/runtimescriptvalue.h"
+#include "ags/shared/gfx/gfx_def.h"
+#include "ags/shared/gfx/gfx_util.h"
 
 namespace AGS3 {
 
@@ -447,9 +447,9 @@ int DrawingSurface_GetPixel(ScriptDrawingSurface *sds, int x, int y) {
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
 
 // void (ScriptDrawingSurface *sds, int colour)
 RuntimeScriptValue Sc_DrawingSurface_Clear(void *self, const RuntimeScriptValue *params, int32_t param_count) {
diff --git a/engines/ags/engine/ac/drawingsurface.h b/engines/ags/engine/ac/drawingsurface.h
index 511b73a98b..7ba6a87c55 100644
--- a/engines/ags/engine/ac/drawingsurface.h
+++ b/engines/ags/engine/ac/drawingsurface.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DRAWINGSURFACE_H
 #define AGS_ENGINE_AC_DRAWINGSURFACE_H
 
-#include "ac/dynobj/scriptdrawingsurface.h"
+#include "ags/engine/ac/dynobj/scriptdrawingsurface.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynamicsprite.cpp b/engines/ags/engine/ac/dynamicsprite.cpp
index 1e1a37db21..d5c635592d 100644
--- a/engines/ags/engine/ac/dynamicsprite.cpp
+++ b/engines/ags/engine/ac/dynamicsprite.cpp
@@ -20,26 +20,26 @@
  *
  */
 
-#include <math.h>
-#include "ac/dynamicsprite.h"
-#include "ac/common.h"
-#include "ac/charactercache.h"
-#include "ac/draw.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/global_dynamicsprite.h"
-#include "ac/global_game.h"
-#include "ac/math.h"    // M_PI
-#include "ac/objectcache.h"
-#include "ac/path_helper.h"
-#include "ac/roomobject.h"
-#include "ac/roomstatus.h"
-#include "ac/system.h"
-#include "debug/debug_log.h"
-#include "game/roomstruct.h"
-#include "gui/guibutton.h"
-#include "ac/spritecache.h"
-#include "gfx/graphicsdriver.h"
-#include "script/runtimescriptvalue.h"
+//include <math.h>
+#include "ags/shared/ac/dynamicsprite.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/charactercache.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/global_dynamicsprite.h"
+#include "ags/shared/ac/global_game.h"
+#include "ags/shared/ac/math.h"    // M_PI
+#include "ags/shared/ac/objectcache.h"
+#include "ags/shared/ac/path_helper.h"
+#include "ags/shared/ac/roomobject.h"
+#include "ags/shared/ac/roomstatus.h"
+#include "ags/shared/ac/system.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/game/roomstruct.h"
+#include "ags/shared/gui/guibutton.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/shared/script/runtimescriptvalue.h"
 
 namespace AGS3 {
 
@@ -504,9 +504,9 @@ void free_dynamic_sprite(int gotSlot) {
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
 
 // void (ScriptDynamicSprite *sds, int width, int height, int x, int y)
 RuntimeScriptValue Sc_DynamicSprite_ChangeCanvasSize(void *self, const RuntimeScriptValue *params, int32_t param_count) {
diff --git a/engines/ags/engine/ac/dynamicsprite.h b/engines/ags/engine/ac/dynamicsprite.h
index a78b50ee10..478407d22a 100644
--- a/engines/ags/engine/ac/dynamicsprite.h
+++ b/engines/ags/engine/ac/dynamicsprite.h
@@ -23,8 +23,8 @@
 #ifndef AGS_ENGINE_AC_DYNAMICSPRITE_H
 #define AGS_ENGINE_AC_DYNAMICSPRITE_H
 
-#include "ac/dynobj/scriptdynamicsprite.h"
-#include "ac/dynobj/scriptdrawingsurface.h"
+#include "ags/engine/ac/dynobj/scriptdynamicsprite.h"
+#include "ags/engine/ac/dynobj/scriptdrawingsurface.h"
 
 namespace AGS3 {
 
@@ -52,7 +52,7 @@ ScriptDynamicSprite *DynamicSprite_CreateFromExistingSprite_Old(int slot);
 ScriptDynamicSprite *DynamicSprite_CreateFromBackground(int frame, int x1, int y1, int width, int height);
 
 
-void    add_dynamic_sprite(int gotSlot, Common::Bitmap *redin, bool hasAlpha = false);
+void    add_dynamic_sprite(int gotSlot, Shared::Bitmap *redin, bool hasAlpha = false);
 void    free_dynamic_sprite(int gotSlot);
 
 } // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/all_dynamicclasses.h b/engines/ags/engine/ac/dynobj/all_dynamicclasses.h
index e9d32a1557..f597b28a47 100644
--- a/engines/ags/engine/ac/dynobj/all_dynamicclasses.h
+++ b/engines/ags/engine/ac/dynobj/all_dynamicclasses.h
@@ -23,18 +23,18 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_ALLDYNAMICCLASSES_H
 #define AGS_ENGINE_AC_DYNOBJ_ALLDYNAMICCLASSES_H
 
-#include "ac/dynobj/cc_agsdynamicobject.h"
-#include "ac/dynobj/cc_audiochannel.h"
-#include "ac/dynobj/cc_audioclip.h"
-#include "ac/dynobj/cc_character.h"
-#include "ac/dynobj/cc_dialog.h"
-#include "ac/dynobj/cc_gui.h"
-#include "ac/dynobj/cc_guiobject.h"
-#include "ac/dynobj/cc_hotspot.h"
-#include "ac/dynobj/cc_inventory.h"
-#include "ac/dynobj/cc_object.h"
-#include "ac/dynobj/cc_region.h"
+#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/shared/ac/dynobj/cc_audiochannel.h"
+#include "ags/shared/ac/dynobj/cc_audioclip.h"
+#include "ags/shared/ac/dynobj/cc_character.h"
+#include "ags/shared/ac/dynobj/cc_dialog.h"
+#include "ags/shared/ac/dynobj/cc_gui.h"
+#include "ags/shared/ac/dynobj/cc_guiobject.h"
+#include "ags/shared/ac/dynobj/cc_hotspot.h"
+#include "ags/shared/ac/dynobj/cc_inventory.h"
+#include "ags/shared/ac/dynobj/cc_object.h"
+#include "ags/shared/ac/dynobj/cc_region.h"
 
-#include "ac/dynobj/cc_serializer.h"
+#include "ags/shared/ac/dynobj/cc_serializer.h"
 
 #endif
diff --git a/engines/ags/engine/ac/dynobj/all_scriptclasses.h b/engines/ags/engine/ac/dynobj/all_scriptclasses.h
index 7c9776d2cb..7c3c72b9c5 100644
--- a/engines/ags/engine/ac/dynobj/all_scriptclasses.h
+++ b/engines/ags/engine/ac/dynobj/all_scriptclasses.h
@@ -23,20 +23,20 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_ALLSCRIPTCLASSES_H
 #define AGS_ENGINE_AC_DYNOBJ_ALLSCRIPTCLASSES_H
 
-#include "ac/dynobj/scriptdatetime.h"
-#include "ac/dynobj/scriptdialog.h"
-#include "ac/dynobj/scriptdialogoptionsrendering.h"
-#include "ac/dynobj/scriptdrawingsurface.h"
-#include "ac/dynobj/scriptdynamicsprite.h"
-#include "ac/dynobj/scriptgui.h"
-#include "ac/dynobj/scripthotspot.h"
-#include "ac/dynobj/scriptinvitem.h"
-#include "ac/dynobj/scriptmouse.h"
-#include "ac/dynobj/scriptobject.h"
-#include "ac/dynobj/scriptoverlay.h"
-#include "ac/dynobj/scriptregion.h"
-#include "ac/dynobj/scriptstring.h"
-#include "ac/dynobj/scriptsystem.h"
-#include "ac/dynobj/scriptviewframe.h"
+#include "ags/shared/ac/dynobj/scriptdatetime.h"
+#include "ags/shared/ac/dynobj/scriptdialog.h"
+#include "ags/shared/ac/dynobj/scriptdialogoptionsrendering.h"
+#include "ags/shared/ac/dynobj/scriptdrawingsurface.h"
+#include "ags/shared/ac/dynobj/scriptdynamicsprite.h"
+#include "ags/shared/ac/dynobj/scriptgui.h"
+#include "ags/shared/ac/dynobj/scripthotspot.h"
+#include "ags/shared/ac/dynobj/scriptinvitem.h"
+#include "ags/shared/ac/dynobj/scriptmouse.h"
+#include "ags/shared/ac/dynobj/scriptobject.h"
+#include "ags/shared/ac/dynobj/scriptoverlay.h"
+#include "ags/shared/ac/dynobj/scriptregion.h"
+#include "ags/shared/ac/dynobj/scriptstring.h"
+#include "ags/shared/ac/dynobj/scriptsystem.h"
+#include "ags/shared/ac/dynobj/scriptviewframe.h"
 
 #endif
diff --git a/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp b/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp
index fe3f70cb6d..f64397eec1 100644
--- a/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp
@@ -20,11 +20,11 @@
  *
  */
 
-#include <string.h>
-#include "core/types.h"
-#include "ac/dynobj/cc_agsdynamicobject.h"
-#include "ac/common.h"               // quit()
-#include "util/bbop.h"
+//include <string.h>
+#include "ags/shared/core/types.h"
+#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/shared/ac/common.h"               // quit()
+#include "ags/shared/util/bbop.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.h b/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.h
index af1263bfb7..da64242dc9 100644
--- a/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.h
+++ b/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_CC_AGSDYNAMICOBJECT_H
 #define AGS_ENGINE_AC_DYNOBJ_CC_AGSDYNAMICOBJECT_H
 
-#include "ac/dynobj/cc_dynamicobject.h"
+#include "ags/engine/ac/dynobj/cc_dynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_audiochannel.cpp b/engines/ags/engine/ac/dynobj/cc_audiochannel.cpp
index e5e89d620b..280486465f 100644
--- a/engines/ags/engine/ac/dynobj/cc_audiochannel.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_audiochannel.cpp
@@ -20,9 +20,9 @@
  *
  */
 
-#include "ac/dynobj/cc_audiochannel.h"
-#include "ac/dynobj/scriptaudiochannel.h"
-#include "media/audio/audio_system.h"
+#include "ags/shared/ac/dynobj/cc_audiochannel.h"
+#include "ags/shared/ac/dynobj/scriptaudiochannel.h"
+#include "ags/shared/media/audio/audio_system.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_audiochannel.h b/engines/ags/engine/ac/dynobj/cc_audiochannel.h
index caa77fe331..0013e82252 100644
--- a/engines/ags/engine/ac/dynobj/cc_audiochannel.h
+++ b/engines/ags/engine/ac/dynobj/cc_audiochannel.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_CC_AUDIOCHANNEL_H
 #define AGS_ENGINE_AC_DYNOBJ_CC_AUDIOCHANNEL_H
 
-#include "ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/engine/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_audioclip.cpp b/engines/ags/engine/ac/dynobj/cc_audioclip.cpp
index edcde5d34a..6f63f2fd64 100644
--- a/engines/ags/engine/ac/dynobj/cc_audioclip.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_audioclip.cpp
@@ -20,9 +20,9 @@
  *
  */
 
-#include "ac/dynobj/cc_audioclip.h"
-#include "ac/dynobj/scriptaudioclip.h"
-#include "ac/gamesetupstruct.h"
+#include "ags/shared/ac/dynobj/cc_audioclip.h"
+#include "ags/shared/ac/dynobj/scriptaudioclip.h"
+#include "ags/shared/ac/gamesetupstruct.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_audioclip.h b/engines/ags/engine/ac/dynobj/cc_audioclip.h
index 2f9b8bd8fe..32d2b8aa49 100644
--- a/engines/ags/engine/ac/dynobj/cc_audioclip.h
+++ b/engines/ags/engine/ac/dynobj/cc_audioclip.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_CCAUDIOCLIP_H
 #define AGS_ENGINE_AC_DYNOBJ_CCAUDIOCLIP_H
 
-#include "ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/engine/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_character.cpp b/engines/ags/engine/ac/dynobj/cc_character.cpp
index d00b9cea5a..6944fc652d 100644
--- a/engines/ags/engine/ac/dynobj/cc_character.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_character.cpp
@@ -20,11 +20,11 @@
  *
  */
 
-#include "ac/dynobj/cc_character.h"
-#include "ac/characterinfo.h"
-#include "ac/global_character.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/game_version.h"
+#include "ags/shared/ac/dynobj/cc_character.h"
+#include "ags/shared/ac/characterinfo.h"
+#include "ags/shared/ac/global_character.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/game_version.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_character.h b/engines/ags/engine/ac/dynobj/cc_character.h
index 7acb487099..b75cd6a351 100644
--- a/engines/ags/engine/ac/dynobj/cc_character.h
+++ b/engines/ags/engine/ac/dynobj/cc_character.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_CCCHARACTER_H
 #define AGS_ENGINE_AC_DYNOBJ_CCCHARACTER_H
 
-#include "ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_dialog.cpp b/engines/ags/engine/ac/dynobj/cc_dialog.cpp
index bfd8e835fa..622f6392ac 100644
--- a/engines/ags/engine/ac/dynobj/cc_dialog.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_dialog.cpp
@@ -20,10 +20,10 @@
  *
  */
 
-#include "ac/dynobj/cc_dialog.h"
-#include "ac/dialog.h"
-#include "ac/dialogtopic.h"
-#include "ac/gamestructdefines.h"
+#include "ags/shared/ac/dynobj/cc_dialog.h"
+#include "ags/shared/ac/dialog.h"
+#include "ags/shared/ac/dialogtopic.h"
+#include "ags/shared/ac/gamestructdefines.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_dialog.h b/engines/ags/engine/ac/dynobj/cc_dialog.h
index 9fbcdbe654..a7c4954af5 100644
--- a/engines/ags/engine/ac/dynobj/cc_dialog.h
+++ b/engines/ags/engine/ac/dynobj/cc_dialog.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_CCDIALOG_H
 #define AGS_ENGINE_AC_DYNOBJ_CCDIALOG_H
 
-#include "ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicarray.cpp b/engines/ags/engine/ac/dynobj/cc_dynamicarray.cpp
index d64343865e..118eb4e8a7 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicarray.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicarray.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include <string.h>
-#include "cc_dynamicarray.h"
+//include <string.h>
+#include "ags/shared/cc_dynamicarray.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicarray.h b/engines/ags/engine/ac/dynobj/cc_dynamicarray.h
index e89774ada4..327a0b1b78 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicarray.h
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicarray.h
@@ -23,8 +23,8 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_CCDYNAMICARRAY_H
 #define AGS_ENGINE_AC_DYNOBJ_CCDYNAMICARRAY_H
 
-#include <vector>
-#include "ac/dynobj/cc_dynamicobject.h"   // ICCDynamicObject
+#include "ags/std/vector.h"
+#include "ags/shared/ac/dynobj/cc_dynamicobject.h"   // ICCDynamicObject
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicobject.cpp b/engines/ags/engine/ac/dynobj/cc_dynamicobject.cpp
index 725545ed9f..7fb7290c00 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicobject.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicobject.cpp
@@ -36,14 +36,14 @@
 
 //#define DEBUG_MANAGED_OBJECTS
 
-#include <stdlib.h>
-#include <string.h>
-#include "ac/dynobj/cc_dynamicobject.h"
-#include "ac/dynobj/managedobjectpool.h"
-#include "debug/out.h"
-#include "script/cc_error.h"
-#include "script/script_common.h"
-#include "util/stream.h"
+//include <stdlib.h>
+//include <string.h>
+#include "ags/shared/ac/dynobj/cc_dynamicobject.h"
+#include "ags/shared/ac/dynobj/managedobjectpool.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/cc_error.h"
+#include "ags/shared/script/script_common.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicobject.h b/engines/ags/engine/ac/dynobj/cc_dynamicobject.h
index 9fc61a4518..8e73a593f3 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicobject.h
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicobject.h
@@ -29,8 +29,8 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_CCDYNAMICOBJECT_H
 #define AGS_ENGINE_AC_DYNOBJ_CCDYNAMICOBJECT_H
 
-#include <utility>
-#include "core/types.h"
+#include "ags/std/utility.h"
+#include "ags/shared/core/types.h"
 
 namespace AGS3 {
 
@@ -114,9 +114,9 @@ extern int   ccUnRegisterManagedObject(const void *object);
 // remove all registered objects
 extern void  ccUnregisterAllObjects();
 // serialize all objects to disk
-extern void  ccSerializeAllObjects(Common::Stream *out);
+extern void  ccSerializeAllObjects(Shared::Stream *out);
 // un-serialise all objects (will remove all currently registered ones)
-extern int   ccUnserializeAllObjects(Common::Stream *in, ICCObjectReader *callback);
+extern int   ccUnserializeAllObjects(Shared::Stream *in, ICCObjectReader *callback);
 // dispose the object if RefCount==0
 extern void  ccAttemptDisposeObject(int32_t handle);
 // translate between object handles and memory addresses
diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h b/engines/ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h
index 9087334e6b..416284c812 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h
@@ -23,8 +23,8 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_ADDR_AND_MANAGER_H
 #define AGS_ENGINE_AC_DYNOBJ_ADDR_AND_MANAGER_H
 
-#include "script/runtimescriptvalue.h"
-#include "ac/dynobj/cc_dynamicobject.h"
+#include "ags/shared/script/runtimescriptvalue.h"
+#include "ags/shared/ac/dynobj/cc_dynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_gui.cpp b/engines/ags/engine/ac/dynobj/cc_gui.cpp
index 3ef3e51fe9..9b2d472b5e 100644
--- a/engines/ags/engine/ac/dynobj/cc_gui.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_gui.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ac/dynobj/cc_gui.h"
-#include "ac/dynobj/scriptgui.h"
+#include "ags/shared/ac/dynobj/cc_gui.h"
+#include "ags/shared/ac/dynobj/scriptgui.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_gui.h b/engines/ags/engine/ac/dynobj/cc_gui.h
index fb0d6974cb..c338625807 100644
--- a/engines/ags/engine/ac/dynobj/cc_gui.h
+++ b/engines/ags/engine/ac/dynobj/cc_gui.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_CCGUI_H
 #define AGS_ENGINE_AC_DYNOBJ_CCGUI_H
 
-#include "ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_guiobject.cpp b/engines/ags/engine/ac/dynobj/cc_guiobject.cpp
index 8d344c7a7f..9bbb9352dc 100644
--- a/engines/ags/engine/ac/dynobj/cc_guiobject.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_guiobject.cpp
@@ -20,10 +20,10 @@
  *
  */
 
-#include "ac/dynobj/cc_guiobject.h"
-#include "ac/dynobj/scriptgui.h"
-#include "gui/guimain.h"
-#include "gui/guiobject.h"
+#include "ags/shared/ac/dynobj/cc_guiobject.h"
+#include "ags/shared/ac/dynobj/scriptgui.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/gui/guiobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_guiobject.h b/engines/ags/engine/ac/dynobj/cc_guiobject.h
index f56c5589a6..4da35e1394 100644
--- a/engines/ags/engine/ac/dynobj/cc_guiobject.h
+++ b/engines/ags/engine/ac/dynobj/cc_guiobject.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_CCGUI_H
 #define AGS_ENGINE_AC_DYNOBJ_CCGUI_H
 
-#include "ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_hotspot.cpp b/engines/ags/engine/ac/dynobj/cc_hotspot.cpp
index 8425c39eee..0bf87cf479 100644
--- a/engines/ags/engine/ac/dynobj/cc_hotspot.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_hotspot.cpp
@@ -20,10 +20,10 @@
  *
  */
 
-#include "ac/dynobj/cc_hotspot.h"
-#include "ac/dynobj/scripthotspot.h"
-#include "ac/common_defines.h"
-#include "game/roomstruct.h"
+#include "ags/shared/ac/dynobj/cc_hotspot.h"
+#include "ags/shared/ac/dynobj/scripthotspot.h"
+#include "ags/shared/ac/common_defines.h"
+#include "ags/shared/game/roomstruct.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_hotspot.h b/engines/ags/engine/ac/dynobj/cc_hotspot.h
index 5b93be4a2d..3a1beb8e61 100644
--- a/engines/ags/engine/ac/dynobj/cc_hotspot.h
+++ b/engines/ags/engine/ac/dynobj/cc_hotspot.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_CCHOTSPOT_H
 #define AGS_ENGINE_AC_DYNOBJ_CCHOTSPOT_H
 
-#include "ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_inventory.cpp b/engines/ags/engine/ac/dynobj/cc_inventory.cpp
index 732a4da44b..d213c84c2e 100644
--- a/engines/ags/engine/ac/dynobj/cc_inventory.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_inventory.cpp
@@ -20,9 +20,9 @@
  *
  */
 
-#include "ac/dynobj/cc_inventory.h"
-#include "ac/dynobj/scriptinvitem.h"
-#include "ac/characterinfo.h"
+#include "ags/shared/ac/dynobj/cc_inventory.h"
+#include "ags/shared/ac/dynobj/scriptinvitem.h"
+#include "ags/shared/ac/characterinfo.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_inventory.h b/engines/ags/engine/ac/dynobj/cc_inventory.h
index 8287600ccc..10edec6e0c 100644
--- a/engines/ags/engine/ac/dynobj/cc_inventory.h
+++ b/engines/ags/engine/ac/dynobj/cc_inventory.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_CCINVENTORY_H
 #define AGS_ENGINE_AC_DYNOBJ_CCINVENTORY_H
 
-#include "ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_object.cpp b/engines/ags/engine/ac/dynobj/cc_object.cpp
index 99c0d6f41b..092f5123db 100644
--- a/engines/ags/engine/ac/dynobj/cc_object.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_object.cpp
@@ -20,10 +20,10 @@
  *
  */
 
-#include "ac/dynobj/cc_object.h"
-#include "ac/dynobj/scriptobject.h"
-#include "ac/common_defines.h"
-#include "game/roomstruct.h"
+#include "ags/shared/ac/dynobj/cc_object.h"
+#include "ags/shared/ac/dynobj/scriptobject.h"
+#include "ags/shared/ac/common_defines.h"
+#include "ags/shared/game/roomstruct.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_object.h b/engines/ags/engine/ac/dynobj/cc_object.h
index b74c6ec2fc..789e8c196f 100644
--- a/engines/ags/engine/ac/dynobj/cc_object.h
+++ b/engines/ags/engine/ac/dynobj/cc_object.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_CCOBJECT_H
 #define AGS_ENGINE_AC_DYNOBJ_CCOBJECT_H
 
-#include "ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_region.cpp b/engines/ags/engine/ac/dynobj/cc_region.cpp
index fb140013f6..9d804eee84 100644
--- a/engines/ags/engine/ac/dynobj/cc_region.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_region.cpp
@@ -20,10 +20,10 @@
  *
  */
 
-#include "ac/dynobj/cc_region.h"
-#include "ac/dynobj/scriptregion.h"
-#include "ac/common_defines.h"
-#include "game/roomstruct.h"
+#include "ags/shared/ac/dynobj/cc_region.h"
+#include "ags/shared/ac/dynobj/scriptregion.h"
+#include "ags/shared/ac/common_defines.h"
+#include "ags/shared/game/roomstruct.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_region.h b/engines/ags/engine/ac/dynobj/cc_region.h
index 2251fe3c05..c0a21cffd4 100644
--- a/engines/ags/engine/ac/dynobj/cc_region.h
+++ b/engines/ags/engine/ac/dynobj/cc_region.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_CCREGION_H
 #define AGS_ENGINE_AC_DYNOBJ_CCREGION_H
 
-#include "ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_serializer.cpp b/engines/ags/engine/ac/dynobj/cc_serializer.cpp
index 53d6f42f87..fc932e3fcd 100644
--- a/engines/ags/engine/ac/dynobj/cc_serializer.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_serializer.cpp
@@ -20,19 +20,19 @@
  *
  */
 
-#include <string.h>
-#include "ac/dynobj/cc_serializer.h"
-#include "ac/dynobj/all_dynamicclasses.h"
-#include "ac/dynobj/all_scriptclasses.h"
-#include "ac/dynobj/scriptcamera.h"
-#include "ac/dynobj/scriptcontainers.h"
-#include "ac/dynobj/scriptfile.h"
-#include "ac/dynobj/scriptuserobject.h"
-#include "ac/dynobj/scriptviewport.h"
-#include "ac/game.h"
-#include "debug/debug_log.h"
-#include "plugin/agsplugin.h"
-#include "plugin/pluginobjectreader.h"
+//include <string.h>
+#include "ags/shared/ac/dynobj/cc_serializer.h"
+#include "ags/shared/ac/dynobj/all_dynamicclasses.h"
+#include "ags/shared/ac/dynobj/all_scriptclasses.h"
+#include "ags/shared/ac/dynobj/scriptcamera.h"
+#include "ags/shared/ac/dynobj/scriptcontainers.h"
+#include "ags/shared/ac/dynobj/scriptfile.h"
+#include "ags/shared/ac/dynobj/scriptuserobject.h"
+#include "ags/shared/ac/dynobj/scriptviewport.h"
+#include "ags/shared/ac/game.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/plugin/agsplugin.h"
+#include "ags/shared/plugin/pluginobjectreader.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_serializer.h b/engines/ags/engine/ac/dynobj/cc_serializer.h
index 5b43321ed4..2d16667228 100644
--- a/engines/ags/engine/ac/dynobj/cc_serializer.h
+++ b/engines/ags/engine/ac/dynobj/cc_serializer.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_CCSERIALIZER_H
 #define AGS_ENGINE_AC_DYNOBJ_CCSERIALIZER_H
 
-#include "ac/dynobj/cc_dynamicobject.h"
+#include "ags/shared/ac/dynobj/cc_dynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/managedobjectpool.cpp b/engines/ags/engine/ac/dynobj/managedobjectpool.cpp
index be2f46b4d2..d6a9d5b997 100644
--- a/engines/ags/engine/ac/dynobj/managedobjectpool.cpp
+++ b/engines/ags/engine/ac/dynobj/managedobjectpool.cpp
@@ -20,15 +20,15 @@
  *
  */
 
-#include <vector>
-#include <string.h>
-#include "ac/dynobj/managedobjectpool.h"
-#include "ac/dynobj/cc_dynamicarray.h" // globalDynamicArray, constants
-#include "debug/out.h"
-#include "util/string_utils.h"               // fputstring, etc
-#include "script/cc_error.h"
-#include "script/script_common.h"
-#include "util/stream.h"
+#include "ags/std/vector.h"
+//include <string.h>
+#include "ags/shared/ac/dynobj/managedobjectpool.h"
+#include "ags/shared/ac/dynobj/cc_dynamicarray.h" // globalDynamicArray, constants
+#include "ags/shared/debug/out.h"
+#include "ags/shared/util/string_utils.h"               // fputstring, etc
+#include "ags/shared/script/cc_error.h"
+#include "ags/shared/script/script_common.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/managedobjectpool.h b/engines/ags/engine/ac/dynobj/managedobjectpool.h
index e40ead0ac2..118df53d3f 100644
--- a/engines/ags/engine/ac/dynobj/managedobjectpool.h
+++ b/engines/ags/engine/ac/dynobj/managedobjectpool.h
@@ -23,12 +23,12 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_MANAGEDOBJECTPOOL_H
 #define AGS_ENGINE_AC_DYNOBJ_MANAGEDOBJECTPOOL_H
 
-#include <vector>
-#include <queue>
-#include <unordered_map>
+#include "ags/std/vector.h"
+//include <queue>
+//include <unordered_map>
 
-#include "script/runtimescriptvalue.h"
-#include "ac/dynobj/cc_dynamicobject.h"   // ICCDynamicObject
+#include "ags/shared/script/runtimescriptvalue.h"
+#include "ags/shared/ac/dynobj/cc_dynamicobject.h"   // ICCDynamicObject
 
 namespace AGS3 {
 namespace AGS {
@@ -87,8 +87,8 @@ public:
 	void RunGarbageCollectionIfAppropriate();
 	int AddObject(const char *address, ICCDynamicObject *callback, bool plugin_object);
 	int AddUnserializedObject(const char *address, ICCDynamicObject *callback, bool plugin_object, int handle);
-	void WriteToDisk(Common::Stream *out);
-	int ReadFromDisk(Common::Stream *in, ICCObjectReader *reader);
+	void WriteToDisk(Shared::Stream *out);
+	int ReadFromDisk(Shared::Stream *in, ICCObjectReader *reader);
 	void reset();
 	ManagedObjectPool();
 
diff --git a/engines/ags/engine/ac/dynobj/scriptcamera.cpp b/engines/ags/engine/ac/dynobj/scriptcamera.cpp
index f5c079d216..0eebc6177f 100644
--- a/engines/ags/engine/ac/dynobj/scriptcamera.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptcamera.cpp
@@ -20,9 +20,9 @@
  *
  */
 
-#include "ac/dynobj/scriptcamera.h"
-#include "ac/gamestate.h"
-#include "util/bbop.h"
+#include "ags/shared/ac/dynobj/scriptcamera.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/util/bbop.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptcamera.h b/engines/ags/engine/ac/dynobj/scriptcamera.h
index d0ff62acfd..019896fc68 100644
--- a/engines/ags/engine/ac/dynobj/scriptcamera.h
+++ b/engines/ags/engine/ac/dynobj/scriptcamera.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTCAMERA_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTCAMERA_H
 
-#include "ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptdatetime.cpp b/engines/ags/engine/ac/dynobj/scriptdatetime.cpp
index 83b71cd889..459cc717ac 100644
--- a/engines/ags/engine/ac/dynobj/scriptdatetime.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptdatetime.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ac/dynobj/scriptdatetime.h"
+#include "ags/shared/ac/dynobj/scriptdatetime.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptdatetime.h b/engines/ags/engine/ac/dynobj/scriptdatetime.h
index a714ff2cbe..e7a002d504 100644
--- a/engines/ags/engine/ac/dynobj/scriptdatetime.h
+++ b/engines/ags/engine/ac/dynobj/scriptdatetime.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTDATETIME_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTDATETIME_H
 
-#include "ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/engine/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.cpp b/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.cpp
index 1dcc21a77d..017aaf599c 100644
--- a/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ac/dynobj/scriptdialogoptionsrendering.h"
+#include "ags/shared/ac/dynobj/scriptdialogoptionsrendering.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.h b/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.h
index 00fb395f8a..7a6bdf2d8d 100644
--- a/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.h
+++ b/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTDIALOGOPTIONSRENDERING_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTDIALOGOPTIONSRENDERING_H
 
-#include "ac/dynobj/scriptdrawingsurface.h"
+#include "ags/shared/ac/dynobj/scriptdrawingsurface.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptdict.cpp b/engines/ags/engine/ac/dynobj/scriptdict.cpp
index 94dbb00cf9..9260e20332 100644
--- a/engines/ags/engine/ac/dynobj/scriptdict.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptdict.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ac/dynobj/scriptdict.h"
+#include "ags/shared/ac/dynobj/scriptdict.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptdict.h b/engines/ags/engine/ac/dynobj/scriptdict.h
index ce1fe13b15..85a0bdc7b3 100644
--- a/engines/ags/engine/ac/dynobj/scriptdict.h
+++ b/engines/ags/engine/ac/dynobj/scriptdict.h
@@ -36,12 +36,12 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTDICT_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTDICT_H
 
-#include <map>
-#include <unordered_map>
-#include <string.h>
-#include "ac/dynobj/cc_agsdynamicobject.h"
-#include "util/string.h"
-#include "util/string_types.h"
+//include <map>
+//include <unordered_map>
+//include <string.h>
+#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/shared/util/string.h"
+#include "ags/shared/util/string_types.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp b/engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp
index 703120f836..24cd01bc94 100644
--- a/engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp
@@ -20,15 +20,15 @@
  *
  */
 
-#include "ac/dynobj/scriptdrawingsurface.h"
-#include "ac/spritecache.h"
-#include "ac/runtime_defines.h"
-#include "ac/common.h"
-#include "ac/drawingsurface.h"
-#include "ac/gamestate.h"
-#include "ac/gamesetupstruct.h"
-#include "game/roomstruct.h"
-#include "gfx/bitmap.h"
+#include "ags/shared/ac/dynobj/scriptdrawingsurface.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/ac/runtime_defines.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/drawingsurface.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/game/roomstruct.h"
+#include "ags/shared/gfx/bitmap.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptdrawingsurface.h b/engines/ags/engine/ac/dynobj/scriptdrawingsurface.h
index 9d224c0bab..36385aa95a 100644
--- a/engines/ags/engine/ac/dynobj/scriptdrawingsurface.h
+++ b/engines/ags/engine/ac/dynobj/scriptdrawingsurface.h
@@ -23,8 +23,8 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTDRAWINGSURFACE_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTDRAWINGSURFACE_H
 
-#include "ac/dynobj/cc_agsdynamicobject.h"
-#include "game/roomstruct.h"
+#include "ags/engine/ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/shared/game/roomstruct.h"
 
 namespace AGS3 {
 
@@ -42,20 +42,20 @@ struct ScriptDrawingSurface final : AGSCCDynamicObject {
 	int dynamicSpriteNumber;
 	int dynamicSurfaceNumber;
 	bool isLinkedBitmapOnly;
-	Common::Bitmap *linkedBitmapOnly;
+	Shared::Bitmap *linkedBitmapOnly;
 	int currentColour;
 	int currentColourScript;
 	int highResCoordinates;
 	int modified;
 	int hasAlphaChannel;
-	//Common::Bitmap* abufBackup;
+	//Shared::Bitmap* abufBackup;
 
 	int Dispose(const char *address, bool force) override;
 	const char *GetType() override;
 	int Serialize(const char *address, char *buffer, int bufsize) override;
 	void Unserialize(int index, const char *serializedData, int dataSize) override;
-	Common::Bitmap *GetBitmapSurface();
-	Common::Bitmap *StartDrawing();
+	Shared::Bitmap *GetBitmapSurface();
+	Shared::Bitmap *StartDrawing();
 	void PointToGameResolution(int *xcoord, int *ycoord);
 	void SizeToGameResolution(int *width, int *height);
 	void SizeToGameResolution(int *adjustValue);
diff --git a/engines/ags/engine/ac/dynobj/scriptdynamicsprite.cpp b/engines/ags/engine/ac/dynobj/scriptdynamicsprite.cpp
index 69b7390540..83e94075f3 100644
--- a/engines/ags/engine/ac/dynobj/scriptdynamicsprite.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptdynamicsprite.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ac/dynobj/scriptdynamicsprite.h"
-#include "ac/dynamicsprite.h"
+#include "ags/shared/ac/dynobj/scriptdynamicsprite.h"
+#include "ags/shared/ac/dynamicsprite.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptdynamicsprite.h b/engines/ags/engine/ac/dynobj/scriptdynamicsprite.h
index 252c2fc8b2..3418840f05 100644
--- a/engines/ags/engine/ac/dynobj/scriptdynamicsprite.h
+++ b/engines/ags/engine/ac/dynobj/scriptdynamicsprite.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTDYNAMICSPRITE_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTDYNAMICSPRITE_H
 
-#include "ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptfile.cpp b/engines/ags/engine/ac/dynobj/scriptfile.cpp
index 203c94f0b0..8d75f62462 100644
--- a/engines/ags/engine/ac/dynobj/scriptfile.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptfile.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ac/dynobj/scriptfile.h"
-#include "ac/global_file.h"
+#include "ags/shared/ac/dynobj/scriptfile.h"
+#include "ags/shared/ac/global_file.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptfile.h b/engines/ags/engine/ac/dynobj/scriptfile.h
index 08e636a98b..b5085c2e5a 100644
--- a/engines/ags/engine/ac/dynobj/scriptfile.h
+++ b/engines/ags/engine/ac/dynobj/scriptfile.h
@@ -23,8 +23,8 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTFILE_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTFILE_H
 
-#include "ac/dynobj/cc_dynamicobject.h"
-#include "util/file.h"
+#include "ags/engine/ac/dynobj/cc_dynamicobject.h"
+#include "ags/shared/util/file.h"
 
 namespace AGS3 {
 
@@ -37,8 +37,8 @@ using namespace AGS; // FIXME later
 struct sc_File final : ICCDynamicObject {
 	int32_t             handle;
 
-	static const Common::FileOpenMode fopenModes[];
-	static const Common::FileWorkMode fworkModes[];
+	static const Shared::FileOpenMode fopenModes[];
+	static const Shared::FileWorkMode fworkModes[];
 
 	int Dispose(const char *address, bool force) override;
 
diff --git a/engines/ags/engine/ac/dynobj/scriptobject.h b/engines/ags/engine/ac/dynobj/scriptobject.h
index 3eb68dddd6..6292bbddb4 100644
--- a/engines/ags/engine/ac/dynobj/scriptobject.h
+++ b/engines/ags/engine/ac/dynobj/scriptobject.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTOBJECT_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTOBJECT_H
 
-#include "ac/roomobject.h"
+#include "ags/engine/ac/roomobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptoverlay.cpp b/engines/ags/engine/ac/dynobj/scriptoverlay.cpp
index 3beedc5c3a..0a8f3be675 100644
--- a/engines/ags/engine/ac/dynobj/scriptoverlay.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptoverlay.cpp
@@ -20,11 +20,11 @@
  *
  */
 
-#include "ac/dynobj/scriptoverlay.h"
-#include "ac/common.h"
-#include "ac/overlay.h"
-#include "ac/runtime_defines.h"
-#include "ac/screenoverlay.h"
+#include "ags/shared/ac/dynobj/scriptoverlay.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/overlay.h"
+#include "ags/shared/ac/runtime_defines.h"
+#include "ags/shared/ac/screenoverlay.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptoverlay.h b/engines/ags/engine/ac/dynobj/scriptoverlay.h
index ed1e7d81b2..df73fa8881 100644
--- a/engines/ags/engine/ac/dynobj/scriptoverlay.h
+++ b/engines/ags/engine/ac/dynobj/scriptoverlay.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTOVERLAY_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTOVERLAY_H
 
-#include "ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/engine/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptset.cpp b/engines/ags/engine/ac/dynobj/scriptset.cpp
index 626ce882c7..c3cc922ef9 100644
--- a/engines/ags/engine/ac/dynobj/scriptset.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptset.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ac/dynobj/scriptset.h"
+#include "ags/shared/ac/dynobj/scriptset.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptset.h b/engines/ags/engine/ac/dynobj/scriptset.h
index ca7ecbc154..f20a979c85 100644
--- a/engines/ags/engine/ac/dynobj/scriptset.h
+++ b/engines/ags/engine/ac/dynobj/scriptset.h
@@ -35,12 +35,12 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTSET_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTSET_H
 
-#include <set>
-#include <unordered_set>
-#include <string.h>
-#include "ac/dynobj/cc_agsdynamicobject.h"
-#include "util/string.h"
-#include "util/string_types.h"
+//include <set>
+//include <unordered_set>
+//include <string.h>
+#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/shared/util/string.h"
+#include "ags/shared/util/string_types.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptstring.cpp b/engines/ags/engine/ac/dynobj/scriptstring.cpp
index e752f3e97f..9f55a1c8f1 100644
--- a/engines/ags/engine/ac/dynobj/scriptstring.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptstring.cpp
@@ -20,10 +20,10 @@
  *
  */
 
-#include "ac/dynobj/scriptstring.h"
-#include "ac/string.h"
-#include <stdlib.h>
-#include <string.h>
+#include "ags/shared/ac/dynobj/scriptstring.h"
+#include "ags/shared/ac/string.h"
+//include <stdlib.h>
+//include <string.h>
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptstring.h b/engines/ags/engine/ac/dynobj/scriptstring.h
index 84bff3c322..200eb93b24 100644
--- a/engines/ags/engine/ac/dynobj/scriptstring.h
+++ b/engines/ags/engine/ac/dynobj/scriptstring.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTSTRING_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTSTRING_H
 
-#include "ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/engine/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptuserobject.cpp b/engines/ags/engine/ac/dynobj/scriptuserobject.cpp
index 55e2baa04a..e3d949c4be 100644
--- a/engines/ags/engine/ac/dynobj/scriptuserobject.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptuserobject.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include <memory.h>
-#include "scriptuserobject.h"
+//include <memory.h>
+#include "ags/shared/scriptuserobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptuserobject.h b/engines/ags/engine/ac/dynobj/scriptuserobject.h
index ee21880138..d54d32aaa5 100644
--- a/engines/ags/engine/ac/dynobj/scriptuserobject.h
+++ b/engines/ags/engine/ac/dynobj/scriptuserobject.h
@@ -29,7 +29,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTUSERSTRUCT_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTUSERSTRUCT_H
 
-#include "ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptviewframe.cpp b/engines/ags/engine/ac/dynobj/scriptviewframe.cpp
index 9a727afa60..d60d45733b 100644
--- a/engines/ags/engine/ac/dynobj/scriptviewframe.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptviewframe.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ac/dynobj/scriptviewframe.h"
+#include "ags/shared/ac/dynobj/scriptviewframe.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptviewframe.h b/engines/ags/engine/ac/dynobj/scriptviewframe.h
index 4a4721eb71..29edce6559 100644
--- a/engines/ags/engine/ac/dynobj/scriptviewframe.h
+++ b/engines/ags/engine/ac/dynobj/scriptviewframe.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTVIEWFRAME_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTVIEWFRAME_H
 
-#include "ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/engine/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptviewport.cpp b/engines/ags/engine/ac/dynobj/scriptviewport.cpp
index 7bca084f19..8783de7307 100644
--- a/engines/ags/engine/ac/dynobj/scriptviewport.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptviewport.cpp
@@ -20,9 +20,9 @@
  *
  */
 
-#include "ac/dynobj/scriptviewport.h"
-#include "ac/gamestate.h"
-#include "util/bbop.h"
+#include "ags/shared/ac/dynobj/scriptviewport.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/util/bbop.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptviewport.h b/engines/ags/engine/ac/dynobj/scriptviewport.h
index 61ae777aa9..9075190a09 100644
--- a/engines/ags/engine/ac/dynobj/scriptviewport.h
+++ b/engines/ags/engine/ac/dynobj/scriptviewport.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTVIEWPORT_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTVIEWPORT_H
 
-#include "ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/event.cpp b/engines/ags/engine/ac/event.cpp
index e7415dfe09..cf8d118ab9 100644
--- a/engines/ags/engine/ac/event.cpp
+++ b/engines/ags/engine/ac/event.cpp
@@ -20,27 +20,27 @@
  *
  */
 
-#include "event.h"
-#include "ac/common.h"
-#include "ac/draw.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/global_game.h"
-#include "ac/global_room.h"
-#include "ac/global_screen.h"
-#include "ac/gui.h"
-#include "ac/roomstatus.h"
-#include "ac/screen.h"
-#include "script/cc_error.h"
-#include "platform/base/agsplatformdriver.h"
-#include "plugin/agsplugin.h"
-#include "plugin/plugin_engine.h"
-#include "script/script.h"
-#include "gfx/bitmap.h"
-#include "gfx/ddb.h"
-#include "gfx/graphicsdriver.h"
-#include "media/audio/audio_system.h"
-#include "ac/timer.h"
+#include "ags/shared/event.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_game.h"
+#include "ags/shared/ac/global_room.h"
+#include "ags/shared/ac/global_screen.h"
+#include "ags/shared/ac/gui.h"
+#include "ags/shared/ac/roomstatus.h"
+#include "ags/shared/ac/screen.h"
+#include "ags/shared/script/cc_error.h"
+#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/shared/plugin/agsplugin.h"
+#include "ags/shared/plugin/plugin_engine.h"
+#include "ags/shared/script/script.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/gfx/ddb.h"
+#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/shared/media/audio/audio_system.h"
+#include "ags/shared/ac/timer.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/event.h b/engines/ags/engine/ac/event.h
index 21b265f27b..2e1fb955fe 100644
--- a/engines/ags/engine/ac/event.h
+++ b/engines/ags/engine/ac/event.h
@@ -23,8 +23,8 @@
 #ifndef AGS_ENGINE_AC_EVENT_H
 #define AGS_ENGINE_AC_EVENT_H
 
-#include "ac/runtime_defines.h"
-#include "script/runtimescriptvalue.h"
+#include "ags/engine/ac/runtime_defines.h"
+#include "ags/engine/script/runtimescriptvalue.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/file.cpp b/engines/ags/engine/ac/file.cpp
index 459e46dea9..6a6a30b0a8 100644
--- a/engines/ags/engine/ac/file.cpp
+++ b/engines/ags/engine/ac/file.cpp
@@ -20,31 +20,31 @@
  *
  */
 
-#include "aldumb.h"
-#include "ac/asset_helper.h"
-#include "ac/audiocliptype.h"
-#include "ac/file.h"
-#include "ac/common.h"
-#include "ac/game.h"
-#include "ac/gamesetup.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/global_file.h"
-#include "ac/path_helper.h"
-#include "ac/runtime_defines.h"
-#include "ac/string.h"
-#include "debug/debug_log.h"
-#include "debug/debugger.h"
-#include "util/misc.h"
-#include "platform/base/agsplatformdriver.h"
-#include "util/stream.h"
-#include "core/assetmanager.h"
-#include "core/asset.h"
-#include "main/engine.h"
-#include "main/game_file.h"
-#include "util/directory.h"
-#include "util/path.h"
-#include "util/string.h"
-#include "util/string_utils.h"
+#include "ags/shared/aldumb.h"
+#include "ags/shared/ac/asset_helper.h"
+#include "ags/shared/ac/audiocliptype.h"
+#include "ags/shared/ac/file.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/game.h"
+#include "ags/shared/ac/gamesetup.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/global_file.h"
+#include "ags/shared/ac/path_helper.h"
+#include "ags/shared/ac/runtime_defines.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/debug/debugger.h"
+#include "ags/shared/util/misc.h"
+#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/shared/util/stream.h"
+#include "ags/shared/core/assetmanager.h"
+#include "ags/shared/core/asset.h"
+#include "ags/shared/main/engine.h"
+#include "ags/shared/main/game_file.h"
+#include "ags/shared/util/directory.h"
+#include "ags/shared/util/path.h"
+#include "ags/shared/util/string.h"
+#include "ags/shared/util/string_utils.h"
 
 namespace AGS3 {
 
@@ -613,10 +613,10 @@ Stream *get_valid_file_stream_from_handle(int32_t handle, const char *operation_
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
-#include "ac/dynobj/scriptstring.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
+#include "ags/shared/ac/dynobj/scriptstring.h"
 
 extern ScriptString myScriptStringImpl;
 
diff --git a/engines/ags/engine/ac/file.h b/engines/ags/engine/ac/file.h
index c3e52dfbef..fb116d1213 100644
--- a/engines/ags/engine/ac/file.h
+++ b/engines/ags/engine/ac/file.h
@@ -29,8 +29,8 @@
 #ifndef AGS_ENGINE_AC_FILE_H
 #define AGS_ENGINE_AC_FILE_H
 
-#include "ac/dynobj/scriptfile.h"
-#include "ac/runtime_defines.h"
+#include "ags/engine/ac/dynobj/scriptfile.h"
+#include "ags/engine/ac/runtime_defines.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/game.cpp b/engines/ags/engine/ac/game.cpp
index da01664b11..928974a26e 100644
--- a/engines/ags/engine/ac/game.cpp
+++ b/engines/ags/engine/ac/game.cpp
@@ -20,83 +20,83 @@
  *
  */
 
-#include "ac/game.h"
-
-#include "ac/common.h"
-#include "ac/view.h"
-#include "ac/audiocliptype.h"
-#include "ac/audiochannel.h"
-#include "ac/character.h"
-#include "ac/charactercache.h"
-#include "ac/characterextras.h"
-#include "ac/dialogtopic.h"
-#include "ac/draw.h"
-#include "ac/dynamicsprite.h"
-#include "ac/event.h"
-#include "ac/gamesetup.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/global_audio.h"
-#include "ac/global_character.h"
-#include "ac/global_display.h"
-#include "ac/global_game.h"
-#include "ac/global_gui.h"
-#include "ac/global_object.h"
-#include "ac/global_translation.h"
-#include "ac/gui.h"
-#include "ac/hotspot.h"
-#include "ac/lipsync.h"
-#include "ac/mouse.h"
-#include "ac/movelist.h"
-#include "ac/objectcache.h"
-#include "ac/overlay.h"
-#include "ac/path_helper.h"
-#include "ac/sys_events.h"
-#include "ac/region.h"
-#include "ac/richgamemedia.h"
-#include "ac/room.h"
-#include "ac/roomobject.h"
-#include "ac/roomstatus.h"
-#include "ac/runtime_defines.h"
-#include "ac/screenoverlay.h"
-#include "ac/spritecache.h"
-#include "ac/string.h"
-#include "ac/system.h"
-#include "ac/timer.h"
-#include "ac/translation.h"
-#include "ac/dynobj/all_dynamicclasses.h"
-#include "ac/dynobj/all_scriptclasses.h"
-#include "ac/dynobj/cc_audiochannel.h"
-#include "ac/dynobj/cc_audioclip.h"
-#include "ac/dynobj/scriptcamera.h"
-#include "debug/debug_log.h"
-#include "debug/out.h"
-#include "device/mousew32.h"
-#include "font/fonts.h"
-#include "game/savegame.h"
-#include "game/savegame_components.h"
-#include "game/savegame_internal.h"
-#include "gui/animatingguibutton.h"
-#include "gfx/bitmap.h"
-#include "gfx/graphicsdriver.h"
-#include "gfx/gfxfilter.h"
-#include "gui/guidialog.h"
-#include "main/engine.h"
-#include "main/graphics_mode.h"
-#include "main/main.h"
-#include "media/audio/audio_system.h"
-#include "plugin/agsplugin.h"
-#include "plugin/plugin_engine.h"
-#include "script/cc_error.h"
-#include "script/runtimescriptvalue.h"
-#include "script/script.h"
-#include "script/script_runtime.h"
-#include "util/alignedstream.h"
-#include "util/directory.h"
-#include "util/filestream.h" // TODO: needed only because plugins expect file handle
-#include "util/path.h"
-#include "util/string_utils.h"
-#include "ac/keycode.h"
+#include "ags/shared/ac/game.h"
+
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/view.h"
+#include "ags/shared/ac/audiocliptype.h"
+#include "ags/shared/ac/audiochannel.h"
+#include "ags/shared/ac/character.h"
+#include "ags/shared/ac/charactercache.h"
+#include "ags/shared/ac/characterextras.h"
+#include "ags/shared/ac/dialogtopic.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/dynamicsprite.h"
+#include "ags/shared/ac/event.h"
+#include "ags/shared/ac/gamesetup.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_audio.h"
+#include "ags/shared/ac/global_character.h"
+#include "ags/shared/ac/global_display.h"
+#include "ags/shared/ac/global_game.h"
+#include "ags/shared/ac/global_gui.h"
+#include "ags/shared/ac/global_object.h"
+#include "ags/shared/ac/global_translation.h"
+#include "ags/shared/ac/gui.h"
+#include "ags/shared/ac/hotspot.h"
+#include "ags/shared/ac/lipsync.h"
+#include "ags/shared/ac/mouse.h"
+#include "ags/shared/ac/movelist.h"
+#include "ags/shared/ac/objectcache.h"
+#include "ags/shared/ac/overlay.h"
+#include "ags/shared/ac/path_helper.h"
+#include "ags/shared/ac/sys_events.h"
+#include "ags/shared/ac/region.h"
+#include "ags/shared/ac/richgamemedia.h"
+#include "ags/shared/ac/room.h"
+#include "ags/shared/ac/roomobject.h"
+#include "ags/shared/ac/roomstatus.h"
+#include "ags/shared/ac/runtime_defines.h"
+#include "ags/shared/ac/screenoverlay.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/ac/system.h"
+#include "ags/shared/ac/timer.h"
+#include "ags/shared/ac/translation.h"
+#include "ags/shared/ac/dynobj/all_dynamicclasses.h"
+#include "ags/shared/ac/dynobj/all_scriptclasses.h"
+#include "ags/shared/ac/dynobj/cc_audiochannel.h"
+#include "ags/shared/ac/dynobj/cc_audioclip.h"
+#include "ags/shared/ac/dynobj/scriptcamera.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/device/mousew32.h"
+#include "ags/shared/font/fonts.h"
+#include "ags/shared/game/savegame.h"
+#include "ags/shared/game/savegame_components.h"
+#include "ags/shared/game/savegame_internal.h"
+#include "ags/shared/gui/animatingguibutton.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/shared/gfx/gfxfilter.h"
+#include "ags/shared/gui/guidialog.h"
+#include "ags/shared/main/engine.h"
+#include "ags/shared/main/graphics_mode.h"
+#include "ags/shared/main/main.h"
+#include "ags/shared/media/audio/audio_system.h"
+#include "ags/shared/plugin/agsplugin.h"
+#include "ags/shared/plugin/plugin_engine.h"
+#include "ags/shared/script/cc_error.h"
+#include "ags/shared/script/runtimescriptvalue.h"
+#include "ags/shared/script/script.h"
+#include "ags/shared/script/script_runtime.h"
+#include "ags/shared/util/alignedstream.h"
+#include "ags/shared/util/directory.h"
+#include "ags/shared/util/filestream.h" // TODO: needed only because plugins expect file handle
+#include "ags/shared/util/path.h"
+#include "ags/shared/util/string_utils.h"
+#include "ags/shared/ac/keycode.h"
 
 namespace AGS3 {
 
@@ -890,7 +890,7 @@ void Game_SimulateKeyPress(int key) {
 
 
 
-void serialize_bitmap(const Common::Bitmap *thispic, Stream *out) {
+void serialize_bitmap(const Shared::Bitmap *thispic, Stream *out) {
 	if (thispic != nullptr) {
 		out->WriteInt32(thispic->GetWidth());
 		out->WriteInt32(thispic->GetHeight());
@@ -1604,7 +1604,7 @@ bool try_restore_save(int slot) {
 	return try_restore_save(get_save_game_path(slot), slot);
 }
 
-bool try_restore_save(const Common::String &path, int slot) {
+bool try_restore_save(const Shared::String &path, int slot) {
 	bool data_overwritten;
 	HSaveError err = load_game(path, slot, data_overwritten);
 	if (!err) {
@@ -1937,9 +1937,9 @@ bool unserialize_audio_script_object(int index, const char *objectType, const ch
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
 
 // int  (int audioType);
 RuntimeScriptValue Sc_Game_IsAudioPlaying(const RuntimeScriptValue *params, int32_t param_count) {
diff --git a/engines/ags/engine/ac/game.h b/engines/ags/engine/ac/game.h
index 15cb70ffe3..2d6c813805 100644
--- a/engines/ags/engine/ac/game.h
+++ b/engines/ags/engine/ac/game.h
@@ -29,9 +29,9 @@
 #ifndef AGS_ENGINE_AC_GAME_H
 #define AGS_ENGINE_AC_GAME_H
 
-#include "ac/dynobj/scriptviewframe.h"
-#include "main/game_file.h"
-#include "util/string.h"
+#include "ags/engine/ac/dynobj/scriptviewframe.h"
+#include "ags/engine/main/game_file.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 
@@ -94,7 +94,7 @@ int Game_GetDialogCount();
 
 // Defines a custom save parent directory, which will replace $MYDOCS$/GameName
 // when a new save directory is set from the script
-bool SetCustomSaveParent(const Common::String &path);
+bool SetCustomSaveParent(const Shared::String &path);
 // If explicit_path flag is false, the actual path will be constructed
 // as a relative to system's user saves directory
 bool SetSaveGameDirectoryPath(const char *newFolder, bool explicit_path = false);
@@ -149,28 +149,28 @@ void set_debug_mode(bool on);
 void set_game_speed(int new_fps);
 void setup_for_dialog();
 void restore_after_dialog();
-Common::String get_save_game_directory();
-Common::String get_save_game_suffix();
-void set_save_game_suffix(const Common::String &suffix);
-Common::String get_save_game_path(int slotNum);
+Shared::String get_save_game_directory();
+Shared::String get_save_game_suffix();
+void set_save_game_suffix(const Shared::String &suffix);
+Shared::String get_save_game_path(int slotNum);
 void restore_game_dialog();
 void save_game_dialog();
 void free_do_once_tokens();
 // Free all the memory associated with the game
 void unload_game_file();
 void save_game(int slotn, const char *descript);
-bool read_savedgame_description(const Common::String &savedgame, Common::String &description);
-bool read_savedgame_screenshot(const Common::String &savedgame, int &want_shot);
+bool read_savedgame_description(const Shared::String &savedgame, Shared::String &description);
+bool read_savedgame_screenshot(const Shared::String &savedgame, int &want_shot);
 // Tries to restore saved game and displays an error on failure; if the error occured
 // too late, when the game data was already overwritten, shuts engine down.
 bool try_restore_save(int slot);
-bool try_restore_save(const Common::String &path, int slot);
-void serialize_bitmap(const Common::Bitmap *thispic, Common::Stream *out);
+bool try_restore_save(const Shared::String &path, int slot);
+void serialize_bitmap(const Shared::Bitmap *thispic, Shared::Stream *out);
 // On Windows we could just use IIDFromString but this is platform-independant
 void convert_guid_from_text_to_binary(const char *guidText, unsigned char *buffer);
-Common::Bitmap *read_serialized_bitmap(Common::Stream *in);
-void skip_serialized_bitmap(Common::Stream *in);
-long write_screen_shot_for_vista(Common::Stream *out, Common::Bitmap *screenshot);
+Shared::Bitmap *read_serialized_bitmap(Shared::Stream *in);
+void skip_serialized_bitmap(Shared::Stream *in);
+long write_screen_shot_for_vista(Shared::Stream *out, Shared::Bitmap *screenshot);
 
 bool is_in_cutscene();
 CutsceneSkipStyle get_cutscene_skipstyle();
diff --git a/engines/ags/engine/ac/gamesetup.cpp b/engines/ags/engine/ac/gamesetup.cpp
index 8f197591b5..2bce8af2e1 100644
--- a/engines/ags/engine/ac/gamesetup.cpp
+++ b/engines/ags/engine/ac/gamesetup.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "util/wgt2allg.h" // DIGI_AUTODETECT & MIDI_AUTODETECT
-#include "ac/gamesetup.h"
+#include "ags/shared/util/wgt2allg.h" // DIGI_AUTODETECT & MIDI_AUTODETECT
+#include "ags/shared/ac/gamesetup.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/gamesetup.h b/engines/ags/engine/ac/gamesetup.h
index 5f1f48ad7c..2b207176b3 100644
--- a/engines/ags/engine/ac/gamesetup.h
+++ b/engines/ags/engine/ac/gamesetup.h
@@ -23,8 +23,8 @@
 #ifndef AGS_ENGINE_AC_GAMESETUP_H
 #define AGS_ENGINE_AC_GAMESETUP_H
 
-#include "main/graphics_mode.h"
-#include "util/string.h"
+#include "ags/engine/main/graphics_mode.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/gamestate.cpp b/engines/ags/engine/ac/gamestate.cpp
index aa1d3749d2..b6e186b610 100644
--- a/engines/ags/engine/ac/gamestate.cpp
+++ b/engines/ags/engine/ac/gamestate.cpp
@@ -20,24 +20,24 @@
  *
  */
 
-#include <algorithm>
-#include "ac/draw.h"
-#include "ac/game_version.h"
-#include "ac/gamestate.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/timer.h"
-#include "ac/dynobj/scriptcamera.h"
-#include "ac/dynobj/scriptsystem.h"
-#include "ac/dynobj/scriptviewport.h"
-#include "debug/debug_log.h"
-#include "device/mousew32.h"
-#include "game/customproperties.h"
-#include "game/roomstruct.h"
-#include "game/savegame_internal.h"
-#include "main/engine.h"
-#include "media/audio/audio_system.h"
-#include "util/alignedstream.h"
-#include "util/string_utils.h"
+//include <algorithm>
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/game_version.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/timer.h"
+#include "ags/shared/ac/dynobj/scriptcamera.h"
+#include "ags/shared/ac/dynobj/scriptsystem.h"
+#include "ags/shared/ac/dynobj/scriptviewport.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/device/mousew32.h"
+#include "ags/shared/game/customproperties.h"
+#include "ags/shared/game/roomstruct.h"
+#include "ags/shared/game/savegame_internal.h"
+#include "ags/shared/main/engine.h"
+#include "ags/shared/media/audio/audio_system.h"
+#include "ags/shared/util/alignedstream.h"
+#include "ags/shared/util/string_utils.h"
 
 namespace AGS3 {
 
@@ -372,7 +372,7 @@ bool GameState::ShouldPlayVoiceSpeech() const {
 		(play.want_speech >= 1) && (!ResPaths.SpeechPak.Name.IsEmpty());
 }
 
-void GameState::ReadFromSavegame(Common::Stream *in, GameStateSvgVersion svg_ver, RestoredData &r_data) {
+void GameState::ReadFromSavegame(Shared::Stream *in, GameStateSvgVersion svg_ver, RestoredData &r_data) {
 	const bool old_save = svg_ver < kGSSvgVersion_Initial;
 	score = in->ReadInt32();
 	usedmode = in->ReadInt32();
@@ -595,7 +595,7 @@ void GameState::ReadFromSavegame(Common::Stream *in, GameStateSvgVersion svg_ver
 	}
 }
 
-void GameState::WriteForSavegame(Common::Stream *out) const {
+void GameState::WriteForSavegame(Shared::Stream *out) const {
 	// NOTE: following parameters are never saved:
 	// recording, playback, gamestep, screen_is_faded_out, room_changes
 	out->WriteInt32(score);
@@ -776,7 +776,7 @@ void GameState::WriteForSavegame(Common::Stream *out) const {
 	out->WriteInt32(voice_speech_flags);
 }
 
-void GameState::ReadQueuedAudioItems_Aligned(Common::Stream *in) {
+void GameState::ReadQueuedAudioItems_Aligned(Shared::Stream *in) {
 	AlignedStream align_s(in, Common::kAligned_Read);
 	for (int i = 0; i < MAX_QUEUED_MUSIC; ++i) {
 		new_music_queue[i].ReadFromFile(&align_s);
@@ -807,7 +807,7 @@ void GameState::FreeViewportsAndCameras() {
 	_scCameraRefs.clear();
 }
 
-void GameState::ReadCustomProperties_v340(Common::Stream *in) {
+void GameState::ReadCustomProperties_v340(Shared::Stream *in) {
 	if (loaded_game_file_version >= kGameVersion_340_4) {
 		// After runtime property values were read we also copy missing default,
 		// because we do not keep defaults in the saved game, and also in case
@@ -820,7 +820,7 @@ void GameState::ReadCustomProperties_v340(Common::Stream *in) {
 	}
 }
 
-void GameState::WriteCustomProperties_v340(Common::Stream *out) const {
+void GameState::WriteCustomProperties_v340(Shared::Stream *out) const {
 	if (loaded_game_file_version >= kGameVersion_340_4) {
 		// We temporarily remove properties that kept default values
 		// just for the saving data time to avoid getting lots of
diff --git a/engines/ags/engine/ac/gamestate.h b/engines/ags/engine/ac/gamestate.h
index 617153b51b..cf6102581f 100644
--- a/engines/ags/engine/ac/gamestate.h
+++ b/engines/ags/engine/ac/gamestate.h
@@ -23,18 +23,17 @@
 #ifndef AGS_ENGINE_AC_GAMESTATE_H
 #define AGS_ENGINE_AC_GAMESTATE_H
 
-#include <memory>
-#include <vector>
-
-#include "ac/characterinfo.h"
-#include "ac/runtime_defines.h"
-#include "game/roomstruct.h"
-#include "game/viewport.h"
-#include "media/audio/queuedaudioitem.h"
-#include "util/geometry.h"
-#include "util/string_types.h"
-#include "util/string.h"
-#include "ac/timer.h"
+#include "ags/std/memory.h"
+#include "ags/std/vector.h"
+#include "ags/shared/ac/characterinfo.h"
+#include "ags/engine/ac/runtime_defines.h"
+#include "ags/shared/game/roomstruct.h"
+#include "ags/engine/game/viewport.h"
+#include "ags/engine/media/audio/queuedaudioitem.h"
+#include "ags/shared/util/geometry.h"
+#include "ags/shared/util/string_types.h"
+#include "ags/shared/util/string.h"
+#include "ags/engine/ac/timer.h"
 
 namespace AGS3 {
 
@@ -185,7 +184,7 @@ struct GameState {
 	char  bad_parsed_word[100];
 	int   raw_color;
 	int   raw_modified[MAX_ROOM_BGFRAMES];
-	Common::PBitmap raw_drawing_surface;
+	Shared::PBitmap raw_drawing_surface;
 	short filenumbers[MAXSAVEGAMES];
 	int   room_changes;
 	int   mouse_cursor_hidden;
@@ -354,11 +353,11 @@ struct GameState {
 	//
 	// Serialization
 	//
-	void ReadQueuedAudioItems_Aligned(Common::Stream *in);
-	void ReadCustomProperties_v340(Common::Stream *in);
-	void WriteCustomProperties_v340(Common::Stream *out) const;
-	void ReadFromSavegame(Common::Stream *in, GameStateSvgVersion svg_ver, AGS::Engine::RestoredData &r_data);
-	void WriteForSavegame(Common::Stream *out) const;
+	void ReadQueuedAudioItems_Aligned(Shared::Stream *in);
+	void ReadCustomProperties_v340(Shared::Stream *in);
+	void WriteCustomProperties_v340(Shared::Stream *out) const;
+	void ReadFromSavegame(Shared::Stream *in, GameStateSvgVersion svg_ver, AGS::Engine::RestoredData &r_data);
+	void WriteForSavegame(Shared::Stream *out) const;
 	void FreeProperties();
 	void FreeViewportsAndCameras();
 
diff --git a/engines/ags/engine/ac/global_api.cpp b/engines/ags/engine/ac/global_api.cpp
index 5a36bf5de6..ce894d675e 100644
--- a/engines/ags/engine/ac/global_api.cpp
+++ b/engines/ags/engine/ac/global_api.cpp
@@ -26,61 +26,61 @@
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
-
-#include "ac/cdaudio.h"
-#include "ac/display.h"
-#include "ac/dynamicsprite.h"
-#include "ac/event.h"
-#include "ac/game.h"
-#include "ac/global_audio.h"
-#include "ac/global_button.h"
-#include "ac/global_character.h"
-#include "ac/global_datetime.h"
-#include "ac/global_debug.h"
-#include "ac/global_dialog.h"
-#include "ac/global_display.h"
-#include "ac/global_drawingsurface.h"
-#include "ac/global_dynamicsprite.h"
-#include "ac/global_file.h"
-#include "ac/global_game.h"
-#include "ac/global_gui.h"
-#include "ac/global_hotspot.h"
-#include "ac/global_inventoryitem.h"
-#include "ac/global_invwindow.h"
-#include "ac/global_label.h"
-#include "ac/global_listbox.h"
-#include "ac/global_mouse.h"
-#include "ac/global_object.h"
-#include "ac/global_overlay.h"
-#include "ac/global_palette.h"
-#include "ac/global_parser.h"
-#include "ac/global_record.h"
-#include "ac/global_region.h"
-#include "ac/global_room.h"
-#include "ac/global_slider.h"
-#include "ac/global_screen.h"
-#include "ac/global_string.h"
-#include "ac/global_textbox.h"
-#include "ac/global_timer.h"
-#include "ac/global_translation.h"
-#include "ac/global_video.h"
-#include "ac/global_viewframe.h"
-#include "ac/global_viewport.h"
-#include "ac/global_walkablearea.h"
-#include "ac/global_walkbehind.h"
-#include "ac/math.h"
-#include "ac/mouse.h"
-#include "ac/parser.h"
-#include "ac/string.h"
-#include "ac/room.h"
-#include "media/video/video.h"
-#include "util/string_compat.h"
-#include "media/audio/audio_system.h"
-
-#include "ac/dynobj/scriptstring.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
+
+#include "ags/shared/ac/cdaudio.h"
+#include "ags/shared/ac/display.h"
+#include "ags/shared/ac/dynamicsprite.h"
+#include "ags/shared/ac/event.h"
+#include "ags/shared/ac/game.h"
+#include "ags/shared/ac/global_audio.h"
+#include "ags/shared/ac/global_button.h"
+#include "ags/shared/ac/global_character.h"
+#include "ags/shared/ac/global_datetime.h"
+#include "ags/shared/ac/global_debug.h"
+#include "ags/shared/ac/global_dialog.h"
+#include "ags/shared/ac/global_display.h"
+#include "ags/shared/ac/global_drawingsurface.h"
+#include "ags/shared/ac/global_dynamicsprite.h"
+#include "ags/shared/ac/global_file.h"
+#include "ags/shared/ac/global_game.h"
+#include "ags/shared/ac/global_gui.h"
+#include "ags/shared/ac/global_hotspot.h"
+#include "ags/shared/ac/global_inventoryitem.h"
+#include "ags/shared/ac/global_invwindow.h"
+#include "ags/shared/ac/global_label.h"
+#include "ags/shared/ac/global_listbox.h"
+#include "ags/shared/ac/global_mouse.h"
+#include "ags/shared/ac/global_object.h"
+#include "ags/shared/ac/global_overlay.h"
+#include "ags/shared/ac/global_palette.h"
+#include "ags/shared/ac/global_parser.h"
+#include "ags/shared/ac/global_record.h"
+#include "ags/shared/ac/global_region.h"
+#include "ags/shared/ac/global_room.h"
+#include "ags/shared/ac/global_slider.h"
+#include "ags/shared/ac/global_screen.h"
+#include "ags/shared/ac/global_string.h"
+#include "ags/shared/ac/global_textbox.h"
+#include "ags/shared/ac/global_timer.h"
+#include "ags/shared/ac/global_translation.h"
+#include "ags/shared/ac/global_video.h"
+#include "ags/shared/ac/global_viewframe.h"
+#include "ags/shared/ac/global_viewport.h"
+#include "ags/shared/ac/global_walkablearea.h"
+#include "ags/shared/ac/global_walkbehind.h"
+#include "ags/shared/ac/math.h"
+#include "ags/shared/ac/mouse.h"
+#include "ags/shared/ac/parser.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/ac/room.h"
+#include "ags/shared/media/video/video.h"
+#include "ags/shared/util/string_compat.h"
+#include "ags/shared/media/audio/audio_system.h"
+
+#include "ags/shared/ac/dynobj/scriptstring.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_audio.cpp b/engines/ags/engine/ac/global_audio.cpp
index 06de369d83..10ae491f76 100644
--- a/engines/ags/engine/ac/global_audio.cpp
+++ b/engines/ags/engine/ac/global_audio.cpp
@@ -20,21 +20,21 @@
  *
  */
 
-#include "ac/common.h"
-#include "ac/game.h"
-#include "ac/gamesetup.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/global_audio.h"
-#include "ac/lipsync.h"
-#include "ac/path_helper.h"
-#include "debug/debug_log.h"
-#include "debug/debugger.h"
-#include "game/roomstruct.h"
-#include "main/engine.h"
-#include "media/audio/audio_system.h"
-#include "ac/timer.h"
-#include "util/string_compat.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/game.h"
+#include "ags/shared/ac/gamesetup.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_audio.h"
+#include "ags/shared/ac/lipsync.h"
+#include "ags/shared/ac/path_helper.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/debug/debugger.h"
+#include "ags/shared/game/roomstruct.h"
+#include "ags/shared/main/engine.h"
+#include "ags/shared/media/audio/audio_system.h"
+#include "ags/shared/ac/timer.h"
+#include "ags/shared/util/string_compat.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_button.cpp b/engines/ags/engine/ac/global_button.cpp
index 5e78ed739a..3b6124ed11 100644
--- a/engines/ags/engine/ac/global_button.cpp
+++ b/engines/ags/engine/ac/global_button.cpp
@@ -20,13 +20,13 @@
  *
  */
 
-#include "ac/global_button.h"
-#include "ac/common.h"
-#include "ac/button.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/string.h"
-#include "gui/guimain.h"
-#include "gui/guibutton.h"
+#include "ags/shared/ac/global_button.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/button.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/gui/guibutton.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_character.cpp b/engines/ags/engine/ac/global_character.cpp
index e5098d258e..e1ea227556 100644
--- a/engines/ags/engine/ac/global_character.cpp
+++ b/engines/ags/engine/ac/global_character.cpp
@@ -26,26 +26,26 @@
 //
 //=============================================================================
 
-#include "ac/global_character.h"
-#include "ac/common.h"
-#include "ac/view.h"
-#include "ac/character.h"
-#include "ac/display.h"
-#include "ac/draw.h"
-#include "ac/event.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/global_overlay.h"
-#include "ac/global_translation.h"
-#include "ac/object.h"
-#include "ac/overlay.h"
-#include "ac/properties.h"
-#include "ac/screenoverlay.h"
-#include "ac/string.h"
-#include "debug/debug_log.h"
-#include "game/roomstruct.h"
-#include "main/game_run.h"
-#include "script/script.h"
+#include "ags/shared/ac/global_character.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/view.h"
+#include "ags/shared/ac/character.h"
+#include "ags/shared/ac/display.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/event.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_overlay.h"
+#include "ags/shared/ac/global_translation.h"
+#include "ags/shared/ac/object.h"
+#include "ags/shared/ac/overlay.h"
+#include "ags/shared/ac/properties.h"
+#include "ags/shared/ac/screenoverlay.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/game/roomstruct.h"
+#include "ags/shared/main/game_run.h"
+#include "ags/shared/script/script.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_character.h b/engines/ags/engine/ac/global_character.h
index ac9acb19d5..6745d410b5 100644
--- a/engines/ags/engine/ac/global_character.h
+++ b/engines/ags/engine/ac/global_character.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_GLOBALCHARACTER_H
 #define AGS_ENGINE_AC_GLOBALCHARACTER_H
 
-#include "ac/characterinfo.h"
+#include "ags/shared/ac/characterinfo.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_datetime.cpp b/engines/ags/engine/ac/global_datetime.cpp
index 11db83ec94..2151e00cc7 100644
--- a/engines/ags/engine/ac/global_datetime.cpp
+++ b/engines/ags/engine/ac/global_datetime.cpp
@@ -20,10 +20,10 @@
  *
  */
 
-#include <time.h>
-#include "ac/global_datetime.h"
-#include "ac/datetime.h"
-#include "ac/common.h"
+//include <time.h>
+#include "ags/shared/ac/global_datetime.h"
+#include "ags/shared/ac/datetime.h"
+#include "ags/shared/ac/common.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_debug.cpp b/engines/ags/engine/ac/global_debug.cpp
index 87f13bddf2..1472384150 100644
--- a/engines/ags/engine/ac/global_debug.cpp
+++ b/engines/ags/engine/ac/global_debug.cpp
@@ -20,32 +20,32 @@
  *
  */
 
-#include "ac/global_debug.h"
-#include "ac/common.h"
-#include "ac/characterinfo.h"
-#include "ac/draw.h"
-#include "ac/game.h"
-#include "ac/gamesetup.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/global_character.h"
-#include "ac/global_display.h"
-#include "ac/global_room.h"
-#include "ac/movelist.h"
-#include "ac/properties.h"
-#include "ac/sys_events.h"
-#include "ac/tree_map.h"
-#include "ac/walkablearea.h"
-#include "gfx/gfxfilter.h"
-#include "gui/guidialog.h"
-#include "script/cc_options.h"
-#include "debug/debug_log.h"
-#include "debug/debugger.h"
-#include "main/main.h"
-#include "ac/spritecache.h"
-#include "gfx/bitmap.h"
-#include "gfx/graphicsdriver.h"
-#include "main/graphics_mode.h"
+#include "ags/shared/ac/global_debug.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/characterinfo.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/game.h"
+#include "ags/shared/ac/gamesetup.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_character.h"
+#include "ags/shared/ac/global_display.h"
+#include "ags/shared/ac/global_room.h"
+#include "ags/shared/ac/movelist.h"
+#include "ags/shared/ac/properties.h"
+#include "ags/shared/ac/sys_events.h"
+#include "ags/shared/ac/tree_map.h"
+#include "ags/shared/ac/walkablearea.h"
+#include "ags/shared/gfx/gfxfilter.h"
+#include "ags/shared/gui/guidialog.h"
+#include "ags/shared/script/cc_options.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/debug/debugger.h"
+#include "ags/shared/main/main.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/shared/main/graphics_mode.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_debug.h b/engines/ags/engine/ac/global_debug.h
index bd60f9340b..f104c53fcc 100644
--- a/engines/ags/engine/ac/global_debug.h
+++ b/engines/ags/engine/ac/global_debug.h
@@ -23,8 +23,7 @@
 #ifndef AGS_ENGINE_AC_GLOBALDEBUG_H
 #define AGS_ENGINE_AC_GLOBALDEBUG_H
 
-#include <cstdio>
-#include "util/string.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_dialog.cpp b/engines/ags/engine/ac/global_dialog.cpp
index b2b95c497e..d5faa90097 100644
--- a/engines/ags/engine/ac/global_dialog.cpp
+++ b/engines/ags/engine/ac/global_dialog.cpp
@@ -20,16 +20,16 @@
  *
  */
 
-#include "ac/global_dialog.h"
-#include "ac/common.h"
-#include "ac/dialog.h"
-#include "ac/dialogtopic.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "debug/debug_log.h"
-#include "debug/debugger.h"
-#include "debug/out.h"
-#include "script/script.h"
+#include "ags/shared/ac/global_dialog.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/dialog.h"
+#include "ags/shared/ac/dialogtopic.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/debug/debugger.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_display.cpp b/engines/ags/engine/ac/global_display.cpp
index 7aa5326bc2..18658b6740 100644
--- a/engines/ags/engine/ac/global_display.cpp
+++ b/engines/ags/engine/ac/global_display.cpp
@@ -20,26 +20,26 @@
  *
  */
 
-#include <cstdio>
-#include <stdarg.h>
-#include "ac/common.h"
-#include "ac/character.h"
-#include "ac/display.h"
-#include "ac/draw.h"
-#include "ac/game.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/global_character.h"
-#include "ac/global_display.h"
-#include "ac/global_screen.h"
-#include "ac/global_translation.h"
-#include "ac/runtime_defines.h"
-#include "ac/speech.h"
-#include "ac/string.h"
-#include "ac/topbarsettings.h"
-#include "debug/debug_log.h"
-#include "game/roomstruct.h"
-#include "main/game_run.h"
+//include <cstdio>
+//include <stdarg.h>
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/character.h"
+#include "ags/shared/ac/display.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/game.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_character.h"
+#include "ags/shared/ac/global_display.h"
+#include "ags/shared/ac/global_screen.h"
+#include "ags/shared/ac/global_translation.h"
+#include "ags/shared/ac/runtime_defines.h"
+#include "ags/shared/ac/speech.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/ac/topbarsettings.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/game/roomstruct.h"
+#include "ags/shared/main/game_run.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_display.h b/engines/ags/engine/ac/global_display.h
index 29652e893b..1a813a9492 100644
--- a/engines/ags/engine/ac/global_display.h
+++ b/engines/ags/engine/ac/global_display.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_GLOBALDISPLAY_H
 #define AGS_ENGINE_AC_GLOBALDISPLAY_H
 
-#include "ac/speech.h"
+#include "ags/engine/ac/speech.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_drawingsurface.cpp b/engines/ags/engine/ac/global_drawingsurface.cpp
index 36d19cb0e8..acee470f8f 100644
--- a/engines/ags/engine/ac/global_drawingsurface.cpp
+++ b/engines/ags/engine/ac/global_drawingsurface.cpp
@@ -20,22 +20,22 @@
  *
  */
 
-#include "ac/common.h"
-#include "ac/display.h"
-#include "ac/draw.h"
-#include "ac/game.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/global_drawingsurface.h"
-#include "ac/global_translation.h"
-#include "ac/string.h"
-#include "debug/debug_log.h"
-#include "font/fonts.h"
-#include "game/roomstruct.h"
-#include "gui/guidefines.h"
-#include "ac/spritecache.h"
-#include "gfx/gfx_def.h"
-#include "gfx/gfx_util.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/display.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/game.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_drawingsurface.h"
+#include "ags/shared/ac/global_translation.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/font/fonts.h"
+#include "ags/shared/game/roomstruct.h"
+#include "ags/shared/gui/guidefines.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/gfx/gfx_def.h"
+#include "ags/shared/gfx/gfx_util.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_drawingsurface.h b/engines/ags/engine/ac/global_drawingsurface.h
index 05a1ce7145..f6f8b81623 100644
--- a/engines/ags/engine/ac/global_drawingsurface.h
+++ b/engines/ags/engine/ac/global_drawingsurface.h
@@ -27,7 +27,7 @@ namespace AGS3 {
 
 void RawSaveScreen();
 // RawRestoreScreen: copy backup bitmap back to screen; we
-// deliberately don't free the Common::Bitmap *cos they can multiple restore
+// deliberately don't free the Shared::Bitmap *cos they can multiple restore
 // and it gets freed on room exit anyway
 void RawRestoreScreen();
 // Restores the backup bitmap, but tints it to the specified level
diff --git a/engines/ags/engine/ac/global_dynamicsprite.cpp b/engines/ags/engine/ac/global_dynamicsprite.cpp
index b4019f1a35..e9cb5979f4 100644
--- a/engines/ags/engine/ac/global_dynamicsprite.cpp
+++ b/engines/ags/engine/ac/global_dynamicsprite.cpp
@@ -20,15 +20,15 @@
  *
  */
 
-#include "ac/global_dynamicsprite.h"
-#include "util/wgt2allg.h" // Allegro RGB, PALETTE
-#include "ac/draw.h"
-#include "ac/dynamicsprite.h"
-#include "ac/path_helper.h"
-#include "ac/spritecache.h"
-#include "ac/runtime_defines.h" //MAX_PATH
-#include "gfx/graphicsdriver.h"
-#include "gfx/bitmap.h"
+#include "ags/shared/ac/global_dynamicsprite.h"
+#include "ags/shared/util/wgt2allg.h" // Allegro RGB, PALETTE
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/dynamicsprite.h"
+#include "ags/shared/ac/path_helper.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/ac/runtime_defines.h" //MAX_PATH
+#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/shared/gfx/bitmap.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_file.cpp b/engines/ags/engine/ac/global_file.cpp
index 94b1c7ef46..0f3708b03f 100644
--- a/engines/ags/engine/ac/global_file.cpp
+++ b/engines/ags/engine/ac/global_file.cpp
@@ -20,17 +20,17 @@
  *
  */
 
-#include <string.h>
-#include "ac/global_file.h"
-#include "ac/common.h"
-#include "ac/file.h"
-#include "ac/path_helper.h"
-#include "ac/runtime_defines.h"
-#include "ac/string.h"
-#include "debug/debug_log.h"
-#include "util/directory.h"
-#include "util/path.h"
-#include "util/stream.h"
+//include <string.h>
+#include "ags/shared/ac/global_file.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/file.h"
+#include "ags/shared/ac/path_helper.h"
+#include "ags/shared/ac/runtime_defines.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/util/directory.h"
+#include "ags/shared/util/path.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_file.h b/engines/ags/engine/ac/global_file.h
index be068bf1cf..1392c5859b 100644
--- a/engines/ags/engine/ac/global_file.h
+++ b/engines/ags/engine/ac/global_file.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_FILE_H
 #define AGS_ENGINE_AC_GLOBAL_FILE_H
 
-#include "util/file.h"
+#include "ags/shared/util/file.h"
 
 namespace AGS3 {
 namespace AGS {
@@ -34,7 +34,7 @@ class Stream;
 
 using namespace AGS; // FIXME later
 
-int32_t FileOpen(const char *fnmm, Common::FileOpenMode open_mode, Common::FileWorkMode work_mode);
+int32_t FileOpen(const char *fnmm, Shared::FileOpenMode open_mode, Shared::FileWorkMode work_mode);
 // NOTE: FileOpenCMode is a backwards-compatible replacement for old-style global script function FileOpen
 int32_t FileOpenCMode(const char *fnmm, const char *cmode);
 void  FileClose(int32_t handle);
diff --git a/engines/ags/engine/ac/global_game.cpp b/engines/ags/engine/ac/global_game.cpp
index 8d2c9a36a5..b13d206904 100644
--- a/engines/ags/engine/ac/global_game.cpp
+++ b/engines/ags/engine/ac/global_game.cpp
@@ -20,54 +20,54 @@
  *
  */
 
-#include <math.h>
-
-#include "core/platform.h"
-#include "ac/audiocliptype.h"
-#include "ac/global_game.h"
-#include "ac/common.h"
-#include "ac/view.h"
-#include "ac/character.h"
-#include "ac/draw.h"
-#include "ac/dynamicsprite.h"
-#include "ac/event.h"
-#include "ac/game.h"
-#include "ac/gamesetup.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/global_character.h"
-#include "ac/global_gui.h"
-#include "ac/global_hotspot.h"
-#include "ac/global_inventoryitem.h"
-#include "ac/global_translation.h"
-#include "ac/gui.h"
-#include "ac/hotspot.h"
-#include "ac/keycode.h"
-#include "ac/mouse.h"
-#include "ac/object.h"
-#include "ac/path_helper.h"
-#include "ac/sys_events.h"
-#include "ac/room.h"
-#include "ac/roomstatus.h"
-#include "ac/string.h"
-#include "ac/system.h"
-#include "debug/debugger.h"
-#include "debug/debug_log.h"
-#include "gui/guidialog.h"
-#include "main/engine.h"
-#include "main/game_start.h"
-#include "main/game_run.h"
-#include "main/graphics_mode.h"
-#include "script/script.h"
-#include "script/script_runtime.h"
-#include "ac/spritecache.h"
-#include "gfx/bitmap.h"
-#include "gfx/graphicsdriver.h"
-#include "core/assetmanager.h"
-#include "main/config.h"
-#include "main/game_file.h"
-#include "util/string_utils.h"
-#include "media/audio/audio_system.h"
+//include <math.h>
+
+#include "ags/shared/core/platform.h"
+#include "ags/shared/ac/audiocliptype.h"
+#include "ags/shared/ac/global_game.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/view.h"
+#include "ags/shared/ac/character.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/dynamicsprite.h"
+#include "ags/shared/ac/event.h"
+#include "ags/shared/ac/game.h"
+#include "ags/shared/ac/gamesetup.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_character.h"
+#include "ags/shared/ac/global_gui.h"
+#include "ags/shared/ac/global_hotspot.h"
+#include "ags/shared/ac/global_inventoryitem.h"
+#include "ags/shared/ac/global_translation.h"
+#include "ags/shared/ac/gui.h"
+#include "ags/shared/ac/hotspot.h"
+#include "ags/shared/ac/keycode.h"
+#include "ags/shared/ac/mouse.h"
+#include "ags/shared/ac/object.h"
+#include "ags/shared/ac/path_helper.h"
+#include "ags/shared/ac/sys_events.h"
+#include "ags/shared/ac/room.h"
+#include "ags/shared/ac/roomstatus.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/ac/system.h"
+#include "ags/shared/debug/debugger.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/gui/guidialog.h"
+#include "ags/shared/main/engine.h"
+#include "ags/shared/main/game_start.h"
+#include "ags/shared/main/game_run.h"
+#include "ags/shared/main/graphics_mode.h"
+#include "ags/shared/script/script.h"
+#include "ags/shared/script/script_runtime.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/shared/core/assetmanager.h"
+#include "ags/shared/main/config.h"
+#include "ags/shared/main/game_file.h"
+#include "ags/shared/util/string_utils.h"
+#include "ags/shared/media/audio/audio_system.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_game.h b/engines/ags/engine/ac/global_game.h
index d60b9d8329..8280887aa5 100644
--- a/engines/ags/engine/ac/global_game.h
+++ b/engines/ags/engine/ac/global_game.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_GLOBAL_GAME_H
 #define AGS_ENGINE_AC_GLOBAL_GAME_H
 
-#include "util/string.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_gui.cpp b/engines/ags/engine/ac/global_gui.cpp
index e5481f541d..fcd7223b27 100644
--- a/engines/ags/engine/ac/global_gui.cpp
+++ b/engines/ags/engine/ac/global_gui.cpp
@@ -20,21 +20,21 @@
  *
  */
 
-#include "ac/common.h"
-#include "ac/display.h"
-#include "ac/draw.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/global_game.h"
-#include "ac/global_gui.h"
-#include "ac/gui.h"
-#include "ac/guicontrol.h"
-#include "ac/mouse.h"
-#include "ac/string.h"
-#include "debug/debug_log.h"
-#include "font/fonts.h"
-#include "gui/guimain.h"
-#include "script/runtimescriptvalue.h"
-#include "util/string_compat.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/display.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/global_game.h"
+#include "ags/shared/ac/global_gui.h"
+#include "ags/shared/ac/gui.h"
+#include "ags/shared/ac/guicontrol.h"
+#include "ags/shared/ac/mouse.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/font/fonts.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/script/runtimescriptvalue.h"
+#include "ags/shared/util/string_compat.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_hotspot.cpp b/engines/ags/engine/ac/global_hotspot.cpp
index 747b169670..b6021c650a 100644
--- a/engines/ags/engine/ac/global_hotspot.cpp
+++ b/engines/ags/engine/ac/global_hotspot.cpp
@@ -20,22 +20,22 @@
  *
  */
 
-#include "ac/global_hotspot.h"
-#include "ac/common.h"
-#include "ac/common_defines.h"
-#include "ac/characterinfo.h"
-#include "ac/draw.h"
-#include "ac/event.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/global_character.h"
-#include "ac/global_translation.h"
-#include "ac/hotspot.h"
-#include "ac/properties.h"
-#include "ac/roomstatus.h"
-#include "ac/string.h"
-#include "debug/debug_log.h"
-#include "game/roomstruct.h"
-#include "script/script.h"
+#include "ags/shared/ac/global_hotspot.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/common_defines.h"
+#include "ags/shared/ac/characterinfo.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/event.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/global_character.h"
+#include "ags/shared/ac/global_translation.h"
+#include "ags/shared/ac/hotspot.h"
+#include "ags/shared/ac/properties.h"
+#include "ags/shared/ac/roomstatus.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/game/roomstruct.h"
+#include "ags/shared/script/script.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_inventoryitem.cpp b/engines/ags/engine/ac/global_inventoryitem.cpp
index 45f2b1170d..7d2f7885d8 100644
--- a/engines/ags/engine/ac/global_inventoryitem.cpp
+++ b/engines/ags/engine/ac/global_inventoryitem.cpp
@@ -20,19 +20,19 @@
  *
  */
 
-#include "ac/common.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/global_gui.h"
-#include "ac/global_inventoryitem.h"
-#include "ac/global_translation.h"
-#include "ac/inventoryitem.h"
-#include "ac/invwindow.h"
-#include "ac/properties.h"
-#include "ac/string.h"
-#include "gui/guimain.h"
-#include "gui/guiinv.h"
-#include "ac/event.h"
-#include "ac/gamestate.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/global_gui.h"
+#include "ags/shared/ac/global_inventoryitem.h"
+#include "ags/shared/ac/global_translation.h"
+#include "ags/shared/ac/inventoryitem.h"
+#include "ags/shared/ac/invwindow.h"
+#include "ags/shared/ac/properties.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/gui/guiinv.h"
+#include "ags/shared/ac/event.h"
+#include "ags/shared/ac/gamestate.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_invwindow.cpp b/engines/ags/engine/ac/global_invwindow.cpp
index 64553f430f..cb3ef9ef1e 100644
--- a/engines/ags/engine/ac/global_invwindow.cpp
+++ b/engines/ags/engine/ac/global_invwindow.cpp
@@ -20,12 +20,12 @@
  *
  */
 
-#include "ac/gamestate.h"
-#include "ac/global_invwindow.h"
-#include "ac/global_translation.h"
-#include "ac/properties.h"
-#include "gui/guiinv.h"
-#include "script/executingscript.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_invwindow.h"
+#include "ags/shared/ac/global_translation.h"
+#include "ags/shared/ac/properties.h"
+#include "ags/shared/gui/guiinv.h"
+#include "ags/shared/script/executingscript.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_label.cpp b/engines/ags/engine/ac/global_label.cpp
index 770a1f971d..8c1b404bd4 100644
--- a/engines/ags/engine/ac/global_label.cpp
+++ b/engines/ags/engine/ac/global_label.cpp
@@ -20,12 +20,12 @@
  *
  */
 
-#include "ac/global_label.h"
-#include "ac/common.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/label.h"
-#include "ac/string.h"
-#include "gui/guimain.h"
+#include "ags/shared/ac/global_label.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/label.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/gui/guimain.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_listbox.cpp b/engines/ags/engine/ac/global_listbox.cpp
index 935927cbe5..ef607a52f7 100644
--- a/engines/ags/engine/ac/global_listbox.cpp
+++ b/engines/ags/engine/ac/global_listbox.cpp
@@ -20,10 +20,10 @@
  *
  */
 
-#include "ac/global_listbox.h"
-#include "ac/common.h"
-#include "ac/listbox.h"
-#include "ac/string.h"
+#include "ags/shared/ac/global_listbox.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/listbox.h"
+#include "ags/shared/ac/string.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_mouse.cpp b/engines/ags/engine/ac/global_mouse.cpp
index 8b0e30bf53..6310da0da3 100644
--- a/engines/ags/engine/ac/global_mouse.cpp
+++ b/engines/ags/engine/ac/global_mouse.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ac/global_mouse.h"
-#include "ac/gamestate.h"
+#include "ags/shared/ac/global_mouse.h"
+#include "ags/shared/ac/gamestate.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_object.cpp b/engines/ags/engine/ac/global_object.cpp
index 4feb25f4fa..3be568fa04 100644
--- a/engines/ags/engine/ac/global_object.cpp
+++ b/engines/ags/engine/ac/global_object.cpp
@@ -20,30 +20,30 @@
  *
  */
 
-#include "ac/global_object.h"
-#include "ac/common.h"
-#include "ac/object.h"
-#include "ac/view.h"
-#include "ac/character.h"
-#include "ac/draw.h"
-#include "ac/event.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/global_character.h"
-#include "ac/global_translation.h"
-#include "ac/object.h"
-#include "ac/objectcache.h"
-#include "ac/properties.h"
-#include "ac/roomobject.h"
-#include "ac/roomstatus.h"
-#include "ac/string.h"
-#include "ac/viewframe.h"
-#include "debug/debug_log.h"
-#include "main/game_run.h"
-#include "script/script.h"
-#include "ac/spritecache.h"
-#include "gfx/graphicsdriver.h"
-#include "gfx/bitmap.h"
-#include "gfx/gfx_def.h"
+#include "ags/shared/ac/global_object.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/object.h"
+#include "ags/shared/ac/view.h"
+#include "ags/shared/ac/character.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/event.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/global_character.h"
+#include "ags/shared/ac/global_translation.h"
+#include "ags/shared/ac/object.h"
+#include "ags/shared/ac/objectcache.h"
+#include "ags/shared/ac/properties.h"
+#include "ags/shared/ac/roomobject.h"
+#include "ags/shared/ac/roomstatus.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/ac/viewframe.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/main/game_run.h"
+#include "ags/shared/script/script.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/gfx/gfx_def.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_object.h b/engines/ags/engine/ac/global_object.h
index 4d192b82a9..7304322662 100644
--- a/engines/ags/engine/ac/global_object.h
+++ b/engines/ags/engine/ac/global_object.h
@@ -77,7 +77,7 @@ int  AreThingsOverlapping(int thing1, int thing2);
 int  GetObjectProperty(int hss, const char *property);
 void GetObjectPropertyText(int item, const char *property, char *bufer);
 
-Common::Bitmap *GetObjectImage(int obj, int *isFlipped);
+Shared::Bitmap *GetObjectImage(int obj, int *isFlipped);
 
 } // namespace AGS3
 
diff --git a/engines/ags/engine/ac/global_overlay.cpp b/engines/ags/engine/ac/global_overlay.cpp
index ddc79f0554..3f1c82ec10 100644
--- a/engines/ags/engine/ac/global_overlay.cpp
+++ b/engines/ags/engine/ac/global_overlay.cpp
@@ -20,20 +20,20 @@
  *
  */
 
-#include "ac/global_overlay.h"
-#include "ac/common.h"
-#include "ac/display.h"
-#include "ac/draw.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/global_translation.h"
-#include "ac/overlay.h"
-#include "ac/runtime_defines.h"
-#include "ac/screenoverlay.h"
-#include "ac/string.h"
-#include "ac/spritecache.h"
-#include "ac/system.h"
-#include "gfx/bitmap.h"
+#include "ags/shared/ac/global_overlay.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/display.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_translation.h"
+#include "ags/shared/ac/overlay.h"
+#include "ags/shared/ac/runtime_defines.h"
+#include "ags/shared/ac/screenoverlay.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/ac/system.h"
+#include "ags/shared/gfx/bitmap.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_palette.cpp b/engines/ags/engine/ac/global_palette.cpp
index 63a4f741e7..0d8bc049fb 100644
--- a/engines/ags/engine/ac/global_palette.cpp
+++ b/engines/ags/engine/ac/global_palette.cpp
@@ -20,11 +20,11 @@
  *
  */
 
-#include "ac/common.h"
-#include "ac/draw.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/global_palette.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_palette.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_parser.cpp b/engines/ags/engine/ac/global_parser.cpp
index 6ae278cd18..68635efc58 100644
--- a/engines/ags/engine/ac/global_parser.cpp
+++ b/engines/ags/engine/ac/global_parser.cpp
@@ -20,11 +20,11 @@
  *
  */
 
-#include <cstring> //strcpy()
-#include "ac/global_parser.h"
-#include "ac/common.h"
-#include "ac/gamestate.h"
-#include "ac/string.h"
+//include <cstring> //strcpy()
+#include "ags/shared/ac/global_parser.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/string.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_record.cpp b/engines/ags/engine/ac/global_record.cpp
index 9f2358045d..6e6e0c92f8 100644
--- a/engines/ags/engine/ac/global_record.cpp
+++ b/engines/ags/engine/ac/global_record.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ac/global_record.h"
-#include "ac/common.h"
+#include "ags/shared/ac/global_record.h"
+#include "ags/shared/ac/common.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_region.cpp b/engines/ags/engine/ac/global_region.cpp
index e607e353c5..e1307d3941 100644
--- a/engines/ags/engine/ac/global_region.cpp
+++ b/engines/ags/engine/ac/global_region.cpp
@@ -20,16 +20,16 @@
  *
  */
 
-#include "ac/global_region.h"
-#include "ac/common.h"
-#include "ac/game_version.h"
-#include "ac/region.h"
-#include "ac/room.h"
-#include "ac/roomstatus.h"
-#include "debug/debug_log.h"
-#include "game/roomstruct.h"
-#include "gfx/bitmap.h"
-#include "script/script.h"
+#include "ags/shared/ac/global_region.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/game_version.h"
+#include "ags/shared/ac/region.h"
+#include "ags/shared/ac/room.h"
+#include "ags/shared/ac/roomstatus.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/game/roomstruct.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/script/script.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_room.cpp b/engines/ags/engine/ac/global_room.cpp
index 7fadb5a72b..ff23f92d91 100644
--- a/engines/ags/engine/ac/global_room.cpp
+++ b/engines/ags/engine/ac/global_room.cpp
@@ -20,24 +20,24 @@
  *
  */
 
-#include "ac/global_room.h"
-#include "ac/common.h"
-#include "ac/character.h"
-#include "ac/characterinfo.h"
-#include "ac/draw.h"
-#include "ac/event.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/global_character.h"
-#include "ac/global_game.h"
-#include "ac/movelist.h"
-#include "ac/properties.h"
-#include "ac/room.h"
-#include "ac/roomstatus.h"
-#include "debug/debug_log.h"
-#include "debug/debugger.h"
-#include "script/script.h"
-#include "util/math.h"
+#include "ags/shared/ac/global_room.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/character.h"
+#include "ags/shared/ac/characterinfo.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/event.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_character.h"
+#include "ags/shared/ac/global_game.h"
+#include "ags/shared/ac/movelist.h"
+#include "ags/shared/ac/properties.h"
+#include "ags/shared/ac/room.h"
+#include "ags/shared/ac/roomstatus.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/debug/debugger.h"
+#include "ags/shared/script/script.h"
+#include "ags/shared/util/math.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_screen.cpp b/engines/ags/engine/ac/global_screen.cpp
index 8ae85266af..8014024203 100644
--- a/engines/ags/engine/ac/global_screen.cpp
+++ b/engines/ags/engine/ac/global_screen.cpp
@@ -20,20 +20,20 @@
  *
  */
 
-#include "ac/common.h"
-#include "ac/gamesetup.h"
-#include "ac/draw.h"
-#include "ac/gamesetup.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/global_game.h"
-#include "ac/global_screen.h"
-#include "ac/runtime_defines.h"
-#include "ac/screen.h"
-#include "debug/debug_log.h"
-#include "platform/base/agsplatformdriver.h"
-#include "gfx/graphicsdriver.h"
-#include "gfx/bitmap.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/gamesetup.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/gamesetup.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_game.h"
+#include "ags/shared/ac/global_screen.h"
+#include "ags/shared/ac/runtime_defines.h"
+#include "ags/shared/ac/screen.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/shared/gfx/bitmap.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_slider.cpp b/engines/ags/engine/ac/global_slider.cpp
index b05ddacc0f..f91e88660d 100644
--- a/engines/ags/engine/ac/global_slider.cpp
+++ b/engines/ags/engine/ac/global_slider.cpp
@@ -20,12 +20,12 @@
  *
  */
 
-#include "ac/global_slider.h"
-#include "ac/common.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/slider.h"
-#include "gui/guimain.h"
-#include "gui/guislider.h"
+#include "ags/shared/ac/global_slider.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/slider.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/gui/guislider.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_string.cpp b/engines/ags/engine/ac/global_string.cpp
index 974b6cea23..d64a4fae91 100644
--- a/engines/ags/engine/ac/global_string.cpp
+++ b/engines/ags/engine/ac/global_string.cpp
@@ -20,13 +20,13 @@
  *
  */
 
-#include <string.h>
-#include "ac/common.h"
-#include "ac/global_string.h"
-#include "ac/global_translation.h"
-#include "ac/runtime_defines.h"
-#include "ac/string.h"
-#include "util/string_compat.h"
+//include <string.h>
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/global_string.h"
+#include "ags/shared/ac/global_translation.h"
+#include "ags/shared/ac/runtime_defines.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/util/string_compat.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_textbox.cpp b/engines/ags/engine/ac/global_textbox.cpp
index 2f2bf556a0..aa78c0632c 100644
--- a/engines/ags/engine/ac/global_textbox.cpp
+++ b/engines/ags/engine/ac/global_textbox.cpp
@@ -20,13 +20,13 @@
  *
  */
 
-#include "ac/global_textbox.h"
-#include "ac/common.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/string.h"
-#include "ac/textbox.h"
-#include "gui/guimain.h"
-#include "gui/guitextbox.h"
+#include "ags/shared/ac/global_textbox.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/ac/textbox.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/gui/guitextbox.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_timer.cpp b/engines/ags/engine/ac/global_timer.cpp
index 04b325961e..d65d2befdf 100644
--- a/engines/ags/engine/ac/global_timer.cpp
+++ b/engines/ags/engine/ac/global_timer.cpp
@@ -20,10 +20,10 @@
  *
  */
 
-#include "ac/global_timer.h"
-#include "ac/runtime_defines.h"
-#include "ac/common.h"
-#include "ac/gamestate.h"
+#include "ags/shared/ac/global_timer.h"
+#include "ags/shared/ac/runtime_defines.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/gamestate.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_translation.cpp b/engines/ags/engine/ac/global_translation.cpp
index e27b75dee6..822ee3a735 100644
--- a/engines/ags/engine/ac/global_translation.cpp
+++ b/engines/ags/engine/ac/global_translation.cpp
@@ -20,18 +20,18 @@
  *
  */
 
-#include <string.h>
-#include "ac/common.h"
-#include "ac/display.h"
-#include "ac/gamestate.h"
-#include "ac/global_translation.h"
-#include "ac/string.h"
-#include "ac/tree_map.h"
-#include "platform/base/agsplatformdriver.h"
-#include "plugin/agsplugin.h"
-#include "plugin/plugin_engine.h"
-#include "util/memory.h"
-#include "core/types.h"
+//include <string.h>
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/display.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_translation.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/ac/tree_map.h"
+#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/shared/plugin/agsplugin.h"
+#include "ags/shared/plugin/plugin_engine.h"
+#include "ags/shared/util/memory.h"
+#include "ags/shared/core/types.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_video.cpp b/engines/ags/engine/ac/global_video.cpp
index 1629b1cf8f..a676765874 100644
--- a/engines/ags/engine/ac/global_video.cpp
+++ b/engines/ags/engine/ac/global_video.cpp
@@ -21,17 +21,17 @@
  */
 
 #include "ags/lib/allegro.h"
-#include "ac/gamesetup.h"
-#include "ac/gamestate.h"
-#include "ac/global_audio.h"
-#include "ac/global_game.h"
-#include "ac/global_video.h"
-#include "ac/path_helper.h"
-#include "debug/debugger.h"
-#include "media/video/video.h"
-#include "media/audio/audio_system.h"
-#include "platform/base/agsplatformdriver.h"
-#include "util/string_compat.h"
+#include "ags/shared/ac/gamesetup.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_audio.h"
+#include "ags/shared/ac/global_game.h"
+#include "ags/shared/ac/global_video.h"
+#include "ags/shared/ac/path_helper.h"
+#include "ags/shared/debug/debugger.h"
+#include "ags/shared/media/video/video.h"
+#include "ags/shared/media/audio/audio_system.h"
+#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/shared/util/string_compat.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_viewframe.cpp b/engines/ags/engine/ac/global_viewframe.cpp
index 8a8f2942cf..e57afccfb7 100644
--- a/engines/ags/engine/ac/global_viewframe.cpp
+++ b/engines/ags/engine/ac/global_viewframe.cpp
@@ -20,12 +20,12 @@
  *
  */
 
-#include "ac/global_viewframe.h"
-#include "ac/common.h"
-#include "ac/view.h"
-#include "ac/gamesetupstruct.h"
-#include "debug/debug_log.h"
-#include "media/audio/audio_system.h"
+#include "ags/shared/ac/global_viewframe.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/view.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/media/audio/audio_system.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_viewport.cpp b/engines/ags/engine/ac/global_viewport.cpp
index 456c582241..a76a4443fc 100644
--- a/engines/ags/engine/ac/global_viewport.cpp
+++ b/engines/ags/engine/ac/global_viewport.cpp
@@ -20,9 +20,9 @@
  *
  */
 
-#include "ac/global_viewport.h"
-#include "ac/draw.h"
-#include "debug/debug_log.h"
+#include "ags/shared/ac/global_viewport.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/debug/debug_log.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_walkablearea.cpp b/engines/ags/engine/ac/global_walkablearea.cpp
index ca23e25a35..8bf3df756a 100644
--- a/engines/ags/engine/ac/global_walkablearea.cpp
+++ b/engines/ags/engine/ac/global_walkablearea.cpp
@@ -20,13 +20,13 @@
  *
  */
 
-#include "ac/global_walkablearea.h"
-#include "ac/common.h"
-#include "ac/common_defines.h"
-#include "ac/draw.h"
-#include "ac/walkablearea.h"
-#include "debug/debug_log.h"
-#include "game/roomstruct.h"
+#include "ags/shared/ac/global_walkablearea.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/common_defines.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/walkablearea.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/game/roomstruct.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_walkbehind.cpp b/engines/ags/engine/ac/global_walkbehind.cpp
index d49685c54b..315c3ac4d9 100644
--- a/engines/ags/engine/ac/global_walkbehind.cpp
+++ b/engines/ags/engine/ac/global_walkbehind.cpp
@@ -20,13 +20,13 @@
  *
  */
 
-#include "ac/global_walkbehind.h"
-#include "ac/common.h"
-#include "ac/common_defines.h"
-#include "ac/draw.h"
-#include "ac/roomstatus.h"
-#include "ac/walkbehind.h"
-#include "debug/debug_log.h"
+#include "ags/shared/ac/global_walkbehind.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/common_defines.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/roomstatus.h"
+#include "ags/shared/ac/walkbehind.h"
+#include "ags/shared/debug/debug_log.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/gui.cpp b/engines/ags/engine/ac/gui.cpp
index 0d5d481f0f..fa00a425ff 100644
--- a/engines/ags/engine/ac/gui.cpp
+++ b/engines/ags/engine/ac/gui.cpp
@@ -20,40 +20,40 @@
  *
  */
 
-#include <cstdio>
-#include "ac/gui.h"
-#include "ac/common.h"
-#include "ac/draw.h"
-#include "ac/event.h"
-#include "ac/gamesetup.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/global_character.h"
-#include "ac/global_game.h"
-#include "ac/global_gui.h"
-#include "ac/global_inventoryitem.h"
-#include "ac/global_screen.h"
-#include "ac/guicontrol.h"
-#include "ac/interfacebutton.h"
-#include "ac/invwindow.h"
-#include "ac/mouse.h"
-#include "ac/runtime_defines.h"
-#include "ac/system.h"
-#include "ac/dynobj/cc_guiobject.h"
-#include "ac/dynobj/scriptgui.h"
-#include "script/cc_instance.h"
-#include "debug/debug_log.h"
-#include "device/mousew32.h"
-#include "gfx/gfxfilter.h"
-#include "gui/guibutton.h"
-#include "gui/guimain.h"
-#include "script/script.h"
-#include "script/script_runtime.h"
-#include "gfx/graphicsdriver.h"
-#include "gfx/bitmap.h"
-#include "ac/dynobj/cc_gui.h"
-#include "ac/dynobj/cc_guiobject.h"
-#include "script/runtimescriptvalue.h"
-#include "util/string_compat.h"
+//include <cstdio>
+#include "ags/shared/ac/gui.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/event.h"
+#include "ags/shared/ac/gamesetup.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/global_character.h"
+#include "ags/shared/ac/global_game.h"
+#include "ags/shared/ac/global_gui.h"
+#include "ags/shared/ac/global_inventoryitem.h"
+#include "ags/shared/ac/global_screen.h"
+#include "ags/shared/ac/guicontrol.h"
+#include "ags/shared/ac/interfacebutton.h"
+#include "ags/shared/ac/invwindow.h"
+#include "ags/shared/ac/mouse.h"
+#include "ags/shared/ac/runtime_defines.h"
+#include "ags/shared/ac/system.h"
+#include "ags/shared/ac/dynobj/cc_guiobject.h"
+#include "ags/shared/ac/dynobj/scriptgui.h"
+#include "ags/shared/script/cc_instance.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/device/mousew32.h"
+#include "ags/shared/gfx/gfxfilter.h"
+#include "ags/shared/gui/guibutton.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/script/script.h"
+#include "ags/shared/script/script_runtime.h"
+#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/ac/dynobj/cc_gui.h"
+#include "ags/shared/ac/dynobj/cc_guiobject.h"
+#include "ags/shared/script/runtimescriptvalue.h"
+#include "ags/shared/util/string_compat.h"
 
 namespace AGS3 {
 
@@ -685,9 +685,9 @@ void gui_on_mouse_down(const int guin, const int mbut) {
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
 
 // void GUI_Centre(ScriptGUI *sgui)
 RuntimeScriptValue Sc_GUI_Centre(void *self, const RuntimeScriptValue *params, int32_t param_count) {
diff --git a/engines/ags/engine/ac/gui.h b/engines/ags/engine/ac/gui.h
index e8e179f9f2..d871b601a2 100644
--- a/engines/ags/engine/ac/gui.h
+++ b/engines/ags/engine/ac/gui.h
@@ -23,8 +23,8 @@
 #ifndef AGS_ENGINE_AC_GUI_H
 #define AGS_ENGINE_AC_GUI_H
 
-#include "ac/dynobj/scriptgui.h"
-#include "gui/guimain.h"
+#include "ags/engine/ac/dynobj/scriptgui.h"
+#include "ags/shared/gui/guimain.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/guicontrol.cpp b/engines/ags/engine/ac/guicontrol.cpp
index 99cde3bd0e..90907e7748 100644
--- a/engines/ags/engine/ac/guicontrol.cpp
+++ b/engines/ags/engine/ac/guicontrol.cpp
@@ -20,20 +20,20 @@
  *
  */
 
-#include "ac/common.h"
-#include "ac/guicontrol.h"
-#include "ac/global_gui.h"
-#include "debug/debug_log.h"
-#include "gui/guibutton.h"
-#include "gui/guiinv.h"
-#include "gui/guilabel.h"
-#include "gui/guilistbox.h"
-#include "gui/guimain.h"
-#include "gui/guislider.h"
-#include "gui/guitextbox.h"
-#include "script/runtimescriptvalue.h"
-#include "ac/dynobj/cc_gui.h"
-#include "ac/dynobj/cc_guiobject.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/guicontrol.h"
+#include "ags/shared/ac/global_gui.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/gui/guibutton.h"
+#include "ags/shared/gui/guiinv.h"
+#include "ags/shared/gui/guilabel.h"
+#include "ags/shared/gui/guilistbox.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/gui/guislider.h"
+#include "ags/shared/gui/guitextbox.h"
+#include "ags/shared/script/runtimescriptvalue.h"
+#include "ags/shared/ac/dynobj/cc_gui.h"
+#include "ags/shared/ac/dynobj/cc_guiobject.h"
 
 namespace AGS3 {
 
@@ -237,9 +237,9 @@ void GUIControl_BringToFront(GUIObject *guio) {
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
 
 // void (GUIObject *guio)
 RuntimeScriptValue Sc_GUIControl_BringToFront(void *self, const RuntimeScriptValue *params, int32_t param_count) {
diff --git a/engines/ags/engine/ac/guicontrol.h b/engines/ags/engine/ac/guicontrol.h
index 1159917394..006c52859b 100644
--- a/engines/ags/engine/ac/guicontrol.h
+++ b/engines/ags/engine/ac/guicontrol.h
@@ -23,14 +23,14 @@
 #ifndef AGS_ENGINE_AC_GUICONTROL_H
 #define AGS_ENGINE_AC_GUICONTROL_H
 
-#include "gui/guiobject.h"
-#include "gui/guibutton.h"
-#include "gui/guiinv.h"
-#include "gui/guilabel.h"
-#include "gui/guilistbox.h"
-#include "gui/guislider.h"
-#include "gui/guitextbox.h"
-#include "ac/dynobj/scriptgui.h"
+#include "ags/shared/gui/guiobject.h"
+#include "ags/shared/gui/guibutton.h"
+#include "ags/shared/gui/guiinv.h"
+#include "ags/shared/gui/guilabel.h"
+#include "ags/shared/gui/guilistbox.h"
+#include "ags/shared/gui/guislider.h"
+#include "ags/shared/gui/guitextbox.h"
+#include "ags/engine/ac/dynobj/scriptgui.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/guiinv.cpp b/engines/ags/engine/ac/guiinv.cpp
index 8110cc71ce..18a08c034c 100644
--- a/engines/ags/engine/ac/guiinv.cpp
+++ b/engines/ags/engine/ac/guiinv.cpp
@@ -20,14 +20,14 @@
  *
  */
 
-#include "gui/guiinv.h"
-#include "gui/guimain.h"
-#include "ac/draw.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/characterextras.h"
-#include "ac/spritecache.h"
-#include "gfx/bitmap.h"
+#include "ags/shared/gui/guiinv.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/characterextras.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/gfx/bitmap.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/hotspot.cpp b/engines/ags/engine/ac/hotspot.cpp
index f839323f7c..ddaee7ce85 100644
--- a/engines/ags/engine/ac/hotspot.cpp
+++ b/engines/ags/engine/ac/hotspot.cpp
@@ -20,18 +20,18 @@
  *
  */
 
-#include "ac/dynobj/cc_hotspot.h"
-#include "ac/hotspot.h"
-#include "ac/gamestate.h"
-#include "ac/global_hotspot.h"
-#include "ac/global_translation.h"
-#include "ac/properties.h"
-#include "ac/room.h"
-#include "ac/roomstatus.h"
-#include "ac/string.h"
-#include "game/roomstruct.h"
-#include "gfx/bitmap.h"
-#include "script/runtimescriptvalue.h"
+#include "ags/shared/ac/dynobj/cc_hotspot.h"
+#include "ags/shared/ac/hotspot.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_hotspot.h"
+#include "ags/shared/ac/global_translation.h"
+#include "ags/shared/ac/properties.h"
+#include "ags/shared/ac/room.h"
+#include "ags/shared/ac/roomstatus.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/game/roomstruct.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/script/runtimescriptvalue.h"
 
 namespace AGS3 {
 
@@ -128,10 +128,10 @@ int get_hotspot_at(int xpp, int ypp) {
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
-#include "ac/dynobj/scriptstring.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
+#include "ags/shared/ac/dynobj/scriptstring.h"
 
 extern ScriptString myScriptStringImpl;
 
diff --git a/engines/ags/engine/ac/hotspot.h b/engines/ags/engine/ac/hotspot.h
index a495b0df2f..4882543097 100644
--- a/engines/ags/engine/ac/hotspot.h
+++ b/engines/ags/engine/ac/hotspot.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_HOTSPOT_H
 #define AGS_ENGINE_AC_HOTSPOT_H
 
-#include "ac/dynobj/scripthotspot.h"
+#include "ags/engine/ac/dynobj/scripthotspot.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/interfacebutton.cpp b/engines/ags/engine/ac/interfacebutton.cpp
index 293870287d..3ec3d84824 100644
--- a/engines/ags/engine/ac/interfacebutton.cpp
+++ b/engines/ags/engine/ac/interfacebutton.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ac/interfacebutton.h"
+#include "ags/shared/ac/interfacebutton.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/interfaceelement.cpp b/engines/ags/engine/ac/interfaceelement.cpp
index 5da22509f5..ea8f5d483c 100644
--- a/engines/ags/engine/ac/interfaceelement.cpp
+++ b/engines/ags/engine/ac/interfaceelement.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include <string.h>
-#include "ac/interfaceelement.h"
+//include <string.h>
+#include "ags/shared/ac/interfaceelement.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/inventoryitem.cpp b/engines/ags/engine/ac/inventoryitem.cpp
index e71a20ad60..c04585e3af 100644
--- a/engines/ags/engine/ac/inventoryitem.cpp
+++ b/engines/ags/engine/ac/inventoryitem.cpp
@@ -20,18 +20,18 @@
  *
  */
 
-#include "ac/inventoryitem.h"
-#include "ac/characterinfo.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/global_inventoryitem.h"
-#include "ac/global_translation.h"
-#include "ac/mouse.h"
-#include "ac/properties.h"
-#include "ac/runtime_defines.h"
-#include "ac/string.h"
-#include "script/runtimescriptvalue.h"
-#include "ac/dynobj/cc_inventory.h"
+#include "ags/shared/ac/inventoryitem.h"
+#include "ags/shared/ac/characterinfo.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_inventoryitem.h"
+#include "ags/shared/ac/global_translation.h"
+#include "ags/shared/ac/mouse.h"
+#include "ags/shared/ac/properties.h"
+#include "ags/shared/ac/runtime_defines.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/script/runtimescriptvalue.h"
+#include "ags/shared/ac/dynobj/cc_inventory.h"
 
 namespace AGS3 {
 
@@ -126,10 +126,10 @@ void set_inv_item_cursorpic(int invItemId, int piccy) {
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
-#include "ac/dynobj/scriptstring.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
+#include "ags/shared/ac/dynobj/scriptstring.h"
 
 extern ScriptString myScriptStringImpl;
 
diff --git a/engines/ags/engine/ac/inventoryitem.h b/engines/ags/engine/ac/inventoryitem.h
index 991526059d..58c2d51cef 100644
--- a/engines/ags/engine/ac/inventoryitem.h
+++ b/engines/ags/engine/ac/inventoryitem.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_INVENTORYITEM_H
 #define AGS_ENGINE_AC_INVENTORYITEM_H
 
-#include "ac/dynobj/scriptinvitem.h"
+#include "ags/engine/ac/dynobj/scriptinvitem.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/invwindow.cpp b/engines/ags/engine/ac/invwindow.cpp
index 1c9b860255..87b10255e7 100644
--- a/engines/ags/engine/ac/invwindow.cpp
+++ b/engines/ags/engine/ac/invwindow.cpp
@@ -20,30 +20,30 @@
  *
  */
 
-#include "ac/invwindow.h"
-#include "ac/common.h"
-#include "ac/characterextras.h"
-#include "ac/characterinfo.h"
-#include "ac/draw.h"
-#include "ac/event.h"
-#include "ac/gamestate.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/global_character.h"
-#include "ac/global_display.h"
-#include "ac/global_room.h"
-#include "ac/mouse.h"
-#include "ac/sys_events.h"
-#include "debug/debug_log.h"
-#include "gui/guidialog.h"
-#include "main/game_run.h"
-#include "platform/base/agsplatformdriver.h"
-#include "ac/spritecache.h"
-#include "script/runtimescriptvalue.h"
-#include "ac/dynobj/cc_character.h"
-#include "ac/dynobj/cc_inventory.h"
-#include "util/math.h"
-#include "media/audio/audio_system.h"
-#include "ac/timer.h"
+#include "ags/shared/ac/invwindow.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/characterextras.h"
+#include "ags/shared/ac/characterinfo.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/event.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/global_character.h"
+#include "ags/shared/ac/global_display.h"
+#include "ags/shared/ac/global_room.h"
+#include "ags/shared/ac/mouse.h"
+#include "ags/shared/ac/sys_events.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/gui/guidialog.h"
+#include "ags/shared/main/game_run.h"
+#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/script/runtimescriptvalue.h"
+#include "ags/shared/ac/dynobj/cc_character.h"
+#include "ags/shared/ac/dynobj/cc_inventory.h"
+#include "ags/shared/util/math.h"
+#include "ags/shared/media/audio/audio_system.h"
+#include "ags/shared/ac/timer.h"
 
 namespace AGS3 {
 
@@ -526,9 +526,9 @@ int invscreen() {
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
 
 // void (GUIInvWindow *guii)
 RuntimeScriptValue Sc_InvWindow_ScrollDown(void *self, const RuntimeScriptValue *params, int32_t param_count) {
diff --git a/engines/ags/engine/ac/invwindow.h b/engines/ags/engine/ac/invwindow.h
index ebb7fc8822..6f830a8eb3 100644
--- a/engines/ags/engine/ac/invwindow.h
+++ b/engines/ags/engine/ac/invwindow.h
@@ -23,9 +23,9 @@
 #ifndef AGS_ENGINE_AC_INVWINDOW_H
 #define AGS_ENGINE_AC_INVWINDOW_H
 
-#include "ac/characterinfo.h"
-#include "ac/dynobj/scriptinvitem.h"
-#include "gui/guiinv.h"
+#include "ags/shared/ac/characterinfo.h"
+#include "ags/engine/ac/dynobj/scriptinvitem.h"
+#include "ags/shared/gui/guiinv.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/keycode.cpp b/engines/ags/engine/ac/keycode.cpp
index e938b14ef6..c3a790e9cf 100644
--- a/engines/ags/engine/ac/keycode.cpp
+++ b/engines/ags/engine/ac/keycode.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ac/keycode.h"
+#include "ags/shared/ac/keycode.h"
 
 #include "ags/lib/allegro.h"
 
diff --git a/engines/ags/engine/ac/keycode.h b/engines/ags/engine/ac/keycode.h
index ddfcf071d6..b1086a9214 100644
--- a/engines/ags/engine/ac/keycode.h
+++ b/engines/ags/engine/ac/keycode.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_KEYCODE_H
 #define AGS_ENGINE_AC_KEYCODE_H
 
-#include "core/platform.h"
+#include "ags/shared/core/platform.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/label.cpp b/engines/ags/engine/ac/label.cpp
index 8935c71abe..de5c06fa84 100644
--- a/engines/ags/engine/ac/label.cpp
+++ b/engines/ags/engine/ac/label.cpp
@@ -20,12 +20,12 @@
  *
  */
 
-#include <string.h>
-#include "ac/label.h"
-#include "ac/common.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/global_translation.h"
-#include "ac/string.h"
+//include <string.h>
+#include "ags/shared/ac/label.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/global_translation.h"
+#include "ags/shared/ac/string.h"
 
 namespace AGS3 {
 
@@ -92,10 +92,10 @@ void Label_SetFont(GUILabel *guil, int fontnum) {
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
-#include "ac/dynobj/scriptstring.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
+#include "ags/shared/ac/dynobj/scriptstring.h"
 
 extern ScriptString myScriptStringImpl;
 
diff --git a/engines/ags/engine/ac/label.h b/engines/ags/engine/ac/label.h
index 27453a5bcd..fc43c0d063 100644
--- a/engines/ags/engine/ac/label.h
+++ b/engines/ags/engine/ac/label.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_LABEL_H
 #define AGS_ENGINE_AC_LABEL_H
 
-#include "gui/guilabel.h"
+#include "ags/shared/gui/guilabel.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/listbox.cpp b/engines/ags/engine/ac/listbox.cpp
index eec074c65f..4753e933c3 100644
--- a/engines/ags/engine/ac/listbox.cpp
+++ b/engines/ags/engine/ac/listbox.cpp
@@ -20,17 +20,17 @@
  *
  */
 
-#include <set>
-#include "ac/listbox.h"
-#include "ac/common.h"
-#include "ac/game.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/global_game.h"
-#include "ac/path_helper.h"
-#include "ac/string.h"
-#include "gui/guimain.h"
-#include "debug/debug_log.h"
+//include <set>
+#include "ags/shared/ac/listbox.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/game.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_game.h"
+#include "ags/shared/ac/path_helper.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/debug/debug_log.h"
 
 namespace AGS3 {
 
@@ -384,10 +384,10 @@ GUIListBox *is_valid_listbox(int guin, int objn) {
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
-#include "ac/dynobj/scriptstring.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
+#include "ags/shared/ac/dynobj/scriptstring.h"
 
 extern ScriptString myScriptStringImpl;
 
diff --git a/engines/ags/engine/ac/listbox.h b/engines/ags/engine/ac/listbox.h
index 7642a9dfba..c2be166f56 100644
--- a/engines/ags/engine/ac/listbox.h
+++ b/engines/ags/engine/ac/listbox.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_LISTBOX_H
 #define AGS_ENGINE_AC_LISTBOX_H
 
-#include "gui/guilistbox.h"
+#include "ags/shared/gui/guilistbox.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/math.cpp b/engines/ags/engine/ac/math.cpp
index de2d521978..431e6bddb4 100644
--- a/engines/ags/engine/ac/math.cpp
+++ b/engines/ags/engine/ac/math.cpp
@@ -20,10 +20,10 @@
  *
  */
 
-#include <cmath>
-#include "ac/math.h"
-#include "ac/common.h" // quit
-#include "util/math.h"
+//include <cmath>
+#include "ags/shared/ac/math.h"
+#include "ags/shared/ac/common.h" // quit
+#include "ags/shared/util/math.h"
 
 namespace AGS3 {
 
@@ -148,9 +148,9 @@ int __Rand(int upto) {
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
 
 // float (float value)
 RuntimeScriptValue Sc_Math_ArcCos(const RuntimeScriptValue *params, int32_t param_count) {
diff --git a/engines/ags/engine/ac/math.h b/engines/ags/engine/ac/math.h
index 07e3ae45b1..8ec93ce28a 100644
--- a/engines/ags/engine/ac/math.h
+++ b/engines/ags/engine/ac/math.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_MATH_H
 #define AGS_ENGINE_AC_MATH_H
 
-#include "core/types.h"
+#include "ags/shared/core/types.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/mouse.cpp b/engines/ags/engine/ac/mouse.cpp
index 8fe2714039..fbfa84fa89 100644
--- a/engines/ags/engine/ac/mouse.cpp
+++ b/engines/ags/engine/ac/mouse.cpp
@@ -20,27 +20,27 @@
  *
  */
 
-#include "ac/mouse.h"
-#include "ac/common.h"
-#include "ac/characterinfo.h"
-#include "ac/draw.h"
-#include "ac/dynobj/scriptmouse.h"
-#include "ac/dynobj/scriptsystem.h"
-#include "ac/gamesetup.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/global_mouse.h"
-#include "ac/global_plugin.h"
-#include "ac/global_screen.h"
-#include "ac/system.h"
-#include "ac/viewframe.h"
-#include "debug/debug_log.h"
-#include "gui/guibutton.h"
-#include "gui/guimain.h"
-#include "device/mousew32.h"
-#include "ac/spritecache.h"
-#include "gfx/graphicsdriver.h"
-#include "gfx/gfxfilter.h"
+#include "ags/shared/ac/mouse.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/characterinfo.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/dynobj/scriptmouse.h"
+#include "ags/shared/ac/dynobj/scriptsystem.h"
+#include "ags/shared/ac/gamesetup.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_mouse.h"
+#include "ags/shared/ac/global_plugin.h"
+#include "ags/shared/ac/global_screen.h"
+#include "ags/shared/ac/system.h"
+#include "ags/shared/ac/viewframe.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/gui/guibutton.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/device/mousew32.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/shared/gfx/gfxfilter.h"
 
 namespace AGS3 {
 
@@ -455,10 +455,10 @@ int find_previous_enabled_cursor(int startwith) {
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
-#include "ac/global_game.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
+#include "ags/shared/ac/global_game.h"
 
 // void  (int curs, int newslot)
 RuntimeScriptValue Sc_ChangeCursorGraphic(const RuntimeScriptValue *params, int32_t param_count) {
diff --git a/engines/ags/engine/ac/mouse.h b/engines/ags/engine/ac/mouse.h
index 455df017f4..95e455fdf6 100644
--- a/engines/ags/engine/ac/mouse.h
+++ b/engines/ags/engine/ac/mouse.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_MOUSE_H
 #define AGS_ENGINE_AC_MOUSE_H
 
-#include "ac/dynobj/scriptmouse.h"
+#include "ags/engine/ac/dynobj/scriptmouse.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/movelist.cpp b/engines/ags/engine/ac/movelist.cpp
index 0b46fbf8fd..5b6154fc15 100644
--- a/engines/ags/engine/ac/movelist.cpp
+++ b/engines/ags/engine/ac/movelist.cpp
@@ -20,9 +20,9 @@
  *
  */
 
-#include "ac/movelist.h"
-#include "ac/common.h"
-#include "util/stream.h"
+#include "ags/shared/ac/movelist.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/movelist.h b/engines/ags/engine/ac/movelist.h
index 06aa462fc3..b950ffe44b 100644
--- a/engines/ags/engine/ac/movelist.h
+++ b/engines/ags/engine/ac/movelist.h
@@ -23,8 +23,8 @@
 #ifndef AGS_ENGINE_AC_MOVE_H
 #define AGS_ENGINE_AC_MOVE_H
 
-#include "util/wgt2allg.h" // fixed type
-#include "game/savegame.h"
+#include "ags/shared/util/wgt2allg.h" // fixed type
+#include "ags/engine/game/savegame.h"
 
 namespace AGS3 {
 
@@ -49,9 +49,9 @@ struct MoveList {
 	char  doneflag;
 	char  direct;  // MoveCharDirect was used or not
 
-	void ReadFromFile_Legacy(Common::Stream *in);
-	AGS::Engine::HSaveError ReadFromFile(Common::Stream *in, int32_t cmp_ver);
-	void WriteToFile(Common::Stream *out);
+	void ReadFromFile_Legacy(Shared::Stream *in);
+	AGS::Engine::HSaveError ReadFromFile(Shared::Stream *in, int32_t cmp_ver);
+	void WriteToFile(Shared::Stream *out);
 };
 
 } // namespace AGS3
diff --git a/engines/ags/engine/ac/object.cpp b/engines/ags/engine/ac/object.cpp
index 3fb358320a..bc982e325f 100644
--- a/engines/ags/engine/ac/object.cpp
+++ b/engines/ags/engine/ac/object.cpp
@@ -20,31 +20,31 @@
  *
  */
 
-#include "ac/object.h"
-#include "ac/common.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/draw.h"
-#include "ac/character.h"
-#include "ac/global_object.h"
-#include "ac/global_translation.h"
-#include "ac/objectcache.h"
-#include "ac/properties.h"
-#include "ac/room.h"
-#include "ac/roomstatus.h"
-#include "ac/runtime_defines.h"
-#include "ac/string.h"
-#include "ac/system.h"
-#include "ac/view.h"
-#include "ac/walkablearea.h"
-#include "debug/debug_log.h"
-#include "main/game_run.h"
-#include "ac/route_finder.h"
-#include "gfx/graphicsdriver.h"
-#include "gfx/bitmap.h"
-#include "gfx/gfx_def.h"
-#include "script/runtimescriptvalue.h"
-#include "ac/dynobj/cc_object.h"
-#include "ac/movelist.h"
+#include "ags/shared/ac/object.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/character.h"
+#include "ags/shared/ac/global_object.h"
+#include "ags/shared/ac/global_translation.h"
+#include "ags/shared/ac/objectcache.h"
+#include "ags/shared/ac/properties.h"
+#include "ags/shared/ac/room.h"
+#include "ags/shared/ac/roomstatus.h"
+#include "ags/shared/ac/runtime_defines.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/ac/system.h"
+#include "ags/shared/ac/view.h"
+#include "ags/shared/ac/walkablearea.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/main/game_run.h"
+#include "ags/shared/ac/route_finder.h"
+#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/gfx/gfx_def.h"
+#include "ags/shared/script/runtimescriptvalue.h"
+#include "ags/shared/ac/dynobj/cc_object.h"
+#include "ags/shared/ac/movelist.h"
 
 namespace AGS3 {
 
@@ -558,10 +558,10 @@ int check_click_on_object(int roomx, int roomy, int mood) {
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
-#include "ac/dynobj/scriptstring.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
+#include "ags/shared/ac/dynobj/scriptstring.h"
 
 extern ScriptString myScriptStringImpl;
 
diff --git a/engines/ags/engine/ac/object.h b/engines/ags/engine/ac/object.h
index 39b3126ae9..a376b8f0ba 100644
--- a/engines/ags/engine/ac/object.h
+++ b/engines/ags/engine/ac/object.h
@@ -31,8 +31,8 @@
 #ifndef AGS_ENGINE_AC_OBJECT_H
 #define AGS_ENGINE_AC_OBJECT_H
 
-#include "ac/common_defines.h"
-#include "ac/dynobj/scriptobject.h"
+#include "ags/shared/ac/common_defines.h"
+#include "ags/engine/ac/dynobj/scriptobject.h"
 
 namespace AGS3 {
 
@@ -98,7 +98,7 @@ const char *Object_GetTextProperty(ScriptObject *objj, const char *property);
 void    move_object(int objj, int tox, int toy, int spee, int ignwal);
 void    get_object_blocking_rect(int objid, int *x1, int *y1, int *width, int *y2);
 int     isposinbox(int mmx, int mmy, int lf, int tp, int rt, int bt);
-int     is_pos_in_sprite(int xx, int yy, int arx, int ary, Common::Bitmap *sprit, int spww, int sphh, int flipped = 0);
+int     is_pos_in_sprite(int xx, int yy, int arx, int ary, Shared::Bitmap *sprit, int spww, int sphh, int flipped = 0);
 // X and Y co-ordinates must be in native format
 // X and Y are ROOM coordinates
 int     check_click_on_object(int roomx, int roomy, int mood);
diff --git a/engines/ags/engine/ac/objectcache.h b/engines/ags/engine/ac/objectcache.h
index 6621698ed2..7f2d994e15 100644
--- a/engines/ags/engine/ac/objectcache.h
+++ b/engines/ags/engine/ac/objectcache.h
@@ -27,7 +27,7 @@ namespace AGS3 {
 
 // stores cached object info
 struct ObjectCache {
-	Common::Bitmap *image;
+	Shared::Bitmap *image;
 	int   sppic;
 	short tintredwas, tintgrnwas, tintbluwas, tintamntwas, tintlightwas;
 	short lightlevwas, mirroredWas, zoomWas;
diff --git a/engines/ags/engine/ac/overlay.cpp b/engines/ags/engine/ac/overlay.cpp
index f9b40cbec4..5edd4a2554 100644
--- a/engines/ags/engine/ac/overlay.cpp
+++ b/engines/ags/engine/ac/overlay.cpp
@@ -20,23 +20,23 @@
  *
  */
 
-#include "ac/overlay.h"
-#include "ac/common.h"
-#include "ac/view.h"
-#include "ac/character.h"
-#include "ac/characterextras.h"
-#include "ac/display.h"
-#include "ac/draw.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/global_overlay.h"
-#include "ac/global_translation.h"
-#include "ac/runtime_defines.h"
-#include "ac/screenoverlay.h"
-#include "ac/string.h"
-#include "gfx/graphicsdriver.h"
-#include "gfx/bitmap.h"
-#include "script/runtimescriptvalue.h"
+#include "ags/shared/ac/overlay.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/view.h"
+#include "ags/shared/ac/character.h"
+#include "ags/shared/ac/characterextras.h"
+#include "ags/shared/ac/display.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_overlay.h"
+#include "ags/shared/ac/global_translation.h"
+#include "ags/shared/ac/runtime_defines.h"
+#include "ags/shared/ac/screenoverlay.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/script/runtimescriptvalue.h"
 
 namespace AGS3 {
 
@@ -197,7 +197,7 @@ size_t add_screen_overlay(int x, int y, int type, Bitmap *piccy, bool alphaChann
 	return add_screen_overlay(x, y, type, piccy, 0, 0, alphaChannel);
 }
 
-size_t add_screen_overlay(int x, int y, int type, Common::Bitmap *piccy, int pic_offx, int pic_offy, bool alphaChannel) {
+size_t add_screen_overlay(int x, int y, int type, Shared::Bitmap *piccy, int pic_offx, int pic_offy, bool alphaChannel) {
 	if (type == OVER_COMPLETE) is_complete_overlay++;
 	if (type == OVER_TEXTMSG) is_text_overlay++;
 	if (type == OVER_CUSTOM) {
@@ -287,9 +287,9 @@ void recreate_overlay_ddbs() {
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
 
 // ScriptOverlay* (int x, int y, int slot, int transparent)
 RuntimeScriptValue Sc_Overlay_CreateGraphical(const RuntimeScriptValue *params, int32_t param_count) {
diff --git a/engines/ags/engine/ac/overlay.h b/engines/ags/engine/ac/overlay.h
index 683f9a489e..8300596c6f 100644
--- a/engines/ags/engine/ac/overlay.h
+++ b/engines/ags/engine/ac/overlay.h
@@ -23,9 +23,9 @@
 #ifndef AGS_ENGINE_AC_OVERLAY_H
 #define AGS_ENGINE_AC_OVERLAY_H
 
-#include <vector>
-#include "ac/screenoverlay.h"
-#include "ac/dynobj/scriptoverlay.h"
+#include "ags/std/vector.h"
+#include "ags/engine/ac/screenoverlay.h"
+#include "ags/engine/ac/dynobj/scriptoverlay.h"
 
 namespace AGS3 {
 
@@ -51,8 +51,8 @@ int  find_overlay_of_type(int type);
 void remove_screen_overlay(int type);
 // Calculates overlay position in screen coordinates
 void get_overlay_position(const ScreenOverlay &over, int *x, int *y);
-size_t add_screen_overlay(int x, int y, int type, Common::Bitmap *piccy, bool alphaChannel = false);
-size_t add_screen_overlay(int x, int y, int type, Common::Bitmap *piccy, int pic_offx, int pic_offy, bool alphaChannel = false);
+size_t add_screen_overlay(int x, int y, int type, Shared::Bitmap *piccy, bool alphaChannel = false);
+size_t add_screen_overlay(int x, int y, int type, Shared::Bitmap *piccy, int pic_offx, int pic_offy, bool alphaChannel = false);
 void remove_screen_overlay_index(size_t over_idx);
 void recreate_overlay_ddbs();
 
diff --git a/engines/ags/engine/ac/parser.cpp b/engines/ags/engine/ac/parser.cpp
index 66fc367497..bddd826e70 100644
--- a/engines/ags/engine/ac/parser.cpp
+++ b/engines/ags/engine/ac/parser.cpp
@@ -20,17 +20,17 @@
  *
  */
 
-#include <cctype> //isalnum()
-#include <cstdio>
-#include "ac/common.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/parser.h"
-#include "ac/string.h"
-#include "ac/wordsdictionary.h"
-#include "debug/debug_log.h"
-#include "util/string.h"
-#include "util/string_compat.h"
+//include <cctype> //isalnum()
+//include <cstdio>
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/parser.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/ac/wordsdictionary.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/util/string.h"
+#include "ags/shared/util/string_compat.h"
 
 namespace AGS3 {
 
@@ -301,10 +301,10 @@ int parse_sentence(const char *src_text, int *numwords, short *wordarray, short
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
-#include "ac/dynobj/scriptstring.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
+#include "ags/shared/ac/dynobj/scriptstring.h"
 
 extern ScriptString myScriptStringImpl;
 
diff --git a/engines/ags/engine/ac/path_helper.h b/engines/ags/engine/ac/path_helper.h
index 8630e82351..46349386ac 100644
--- a/engines/ags/engine/ac/path_helper.h
+++ b/engines/ags/engine/ac/path_helper.h
@@ -29,7 +29,7 @@
 #ifndef AGS_ENGINE_AC_PATHHELPER_H
 #define AGS_ENGINE_AC_PATHHELPER_H
 
-#include "util/string.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/properties.cpp b/engines/ags/engine/ac/properties.cpp
index 84082a6e8e..9e1f221546 100644
--- a/engines/ags/engine/ac/properties.cpp
+++ b/engines/ags/engine/ac/properties.cpp
@@ -20,13 +20,13 @@
  *
  */
 
-#include "ac/common.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/properties.h"
-#include "ac/string.h"
-#include "ac/dynobj/scriptstring.h"
-#include "script/runtimescriptvalue.h"
-#include "util/string_utils.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/properties.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/ac/dynobj/scriptstring.h"
+#include "ags/shared/script/runtimescriptvalue.h"
+#include "ags/shared/util/string_utils.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/properties.h b/engines/ags/engine/ac/properties.h
index aa877441da..ac40ab5b2a 100644
--- a/engines/ags/engine/ac/properties.h
+++ b/engines/ags/engine/ac/properties.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_PROPERTIES_H
 #define AGS_ENGINE_AC_PROPERTIES_H
 
-#include "game/customproperties.h"
+#include "ags/engine/game/customproperties.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/region.cpp b/engines/ags/engine/ac/region.cpp
index 9e12a5b705..0716dd7d5c 100644
--- a/engines/ags/engine/ac/region.cpp
+++ b/engines/ags/engine/ac/region.cpp
@@ -20,17 +20,17 @@
  *
  */
 
-#include "ac/region.h"
-#include "ac/common_defines.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/global_region.h"
-#include "ac/room.h"
-#include "ac/roomstatus.h"
-#include "ac/dynobj/cc_region.h"
-#include "ac/dynobj/scriptdrawingsurface.h"
-#include "game/roomstruct.h"
-#include "script/runtimescriptvalue.h"
+#include "ags/shared/ac/region.h"
+#include "ags/shared/ac/common_defines.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_region.h"
+#include "ags/shared/ac/room.h"
+#include "ags/shared/ac/roomstatus.h"
+#include "ags/shared/ac/dynobj/cc_region.h"
+#include "ags/shared/ac/dynobj/scriptdrawingsurface.h"
+#include "ags/shared/game/roomstruct.h"
+#include "ags/shared/script/runtimescriptvalue.h"
 
 namespace AGS3 {
 
@@ -136,9 +136,9 @@ void generate_light_table() {
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
 
 // ScriptRegion *(int xx, int yy)
 RuntimeScriptValue Sc_GetRegionAtRoom(const RuntimeScriptValue *params, int32_t param_count) {
diff --git a/engines/ags/engine/ac/region.h b/engines/ags/engine/ac/region.h
index a5db946f13..58b3fa4589 100644
--- a/engines/ags/engine/ac/region.h
+++ b/engines/ags/engine/ac/region.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_REGION_H
 #define AGS_ENGINE_AC_REGION_H
 
-#include "ac/dynobj/scriptregion.h"
+#include "ags/engine/ac/dynobj/scriptregion.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/richgamemedia.cpp b/engines/ags/engine/ac/richgamemedia.cpp
index 0c15a3f702..4409f1b855 100644
--- a/engines/ags/engine/ac/richgamemedia.cpp
+++ b/engines/ags/engine/ac/richgamemedia.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ac/richgamemedia.h"
-#include "util/stream.h"
+#include "ags/shared/ac/richgamemedia.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/richgamemedia.h b/engines/ags/engine/ac/richgamemedia.h
index 420903aacb..f28cd454ae 100644
--- a/engines/ags/engine/ac/richgamemedia.h
+++ b/engines/ags/engine/ac/richgamemedia.h
@@ -54,8 +54,8 @@ typedef struct _RICH_GAME_MEDIA_HEADER {
 	unsigned short szLevelName[RM_MAXLENGTH];
 	unsigned short szComments[RM_MAXLENGTH];
 
-	void ReadFromFile(Common::Stream *in);
-	void WriteToFile(Common::Stream *out);
+	void ReadFromFile(Shared::Stream *in);
+	void WriteToFile(Shared::Stream *out);
 } RICH_GAME_MEDIA_HEADER;
 #pragma pack(pop)
 
diff --git a/engines/ags/engine/ac/room.cpp b/engines/ags/engine/ac/room.cpp
index 8b7b4276d0..12ce1ec851 100644
--- a/engines/ags/engine/ac/room.cpp
+++ b/engines/ags/engine/ac/room.cpp
@@ -20,62 +20,62 @@
  *
  */
 
-#include <ctype.h> // for toupper
-
-#include "core/platform.h"
-#include "util/string_utils.h" //strlwr()
-#include "ac/common.h"
-#include "ac/charactercache.h"
-#include "ac/characterextras.h"
-#include "ac/draw.h"
-#include "ac/event.h"
-#include "ac/game.h"
-#include "ac/gamesetup.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/global_audio.h"
-#include "ac/global_character.h"
-#include "ac/global_game.h"
-#include "ac/global_object.h"
-#include "ac/global_translation.h"
-#include "ac/movelist.h"
-#include "ac/mouse.h"
-#include "ac/objectcache.h"
-#include "ac/overlay.h"
-#include "ac/properties.h"
-#include "ac/region.h"
-#include "ac/sys_events.h"
-#include "ac/room.h"
-#include "ac/roomobject.h"
-#include "ac/roomstatus.h"
-#include "ac/screen.h"
-#include "ac/string.h"
-#include "ac/system.h"
-#include "ac/walkablearea.h"
-#include "ac/walkbehind.h"
-#include "ac/dynobj/scriptobject.h"
-#include "ac/dynobj/scripthotspot.h"
-#include "gui/guidefines.h"
-#include "script/cc_instance.h"
-#include "debug/debug_log.h"
-#include "debug/debugger.h"
-#include "debug/out.h"
-#include "game/room_version.h"
-#include "platform/base/agsplatformdriver.h"
-#include "plugin/agsplugin.h"
-#include "plugin/plugin_engine.h"
-#include "script/cc_error.h"
-#include "script/script.h"
-#include "script/script_runtime.h"
-#include "ac/spritecache.h"
-#include "util/stream.h"
-#include "gfx/graphicsdriver.h"
-#include "core/assetmanager.h"
-#include "ac/dynobj/all_dynamicclasses.h"
-#include "gfx/bitmap.h"
-#include "gfx/gfxfilter.h"
-#include "util/math.h"
-#include "media/audio/audio_system.h"
+//include <ctype.h> // for toupper
+
+#include "ags/shared/core/platform.h"
+#include "ags/shared/util/string_utils.h" //strlwr()
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/charactercache.h"
+#include "ags/shared/ac/characterextras.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/event.h"
+#include "ags/shared/ac/game.h"
+#include "ags/shared/ac/gamesetup.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_audio.h"
+#include "ags/shared/ac/global_character.h"
+#include "ags/shared/ac/global_game.h"
+#include "ags/shared/ac/global_object.h"
+#include "ags/shared/ac/global_translation.h"
+#include "ags/shared/ac/movelist.h"
+#include "ags/shared/ac/mouse.h"
+#include "ags/shared/ac/objectcache.h"
+#include "ags/shared/ac/overlay.h"
+#include "ags/shared/ac/properties.h"
+#include "ags/shared/ac/region.h"
+#include "ags/shared/ac/sys_events.h"
+#include "ags/shared/ac/room.h"
+#include "ags/shared/ac/roomobject.h"
+#include "ags/shared/ac/roomstatus.h"
+#include "ags/shared/ac/screen.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/ac/system.h"
+#include "ags/shared/ac/walkablearea.h"
+#include "ags/shared/ac/walkbehind.h"
+#include "ags/shared/ac/dynobj/scriptobject.h"
+#include "ags/shared/ac/dynobj/scripthotspot.h"
+#include "ags/shared/gui/guidefines.h"
+#include "ags/shared/script/cc_instance.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/debug/debugger.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/game/room_version.h"
+#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/shared/plugin/agsplugin.h"
+#include "ags/shared/plugin/plugin_engine.h"
+#include "ags/shared/script/cc_error.h"
+#include "ags/shared/script/script.h"
+#include "ags/shared/script/script_runtime.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/util/stream.h"
+#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/shared/core/assetmanager.h"
+#include "ags/shared/ac/dynobj/all_dynamicclasses.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/gfx/gfxfilter.h"
+#include "ags/shared/util/math.h"
+#include "ags/shared/media/audio/audio_system.h"
 
 namespace AGS3 {
 
@@ -1102,10 +1102,10 @@ void convert_move_path_to_room_resolution(MoveList *ml) {
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
-#include "ac/dynobj/scriptstring.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
+#include "ags/shared/ac/dynobj/scriptstring.h"
 
 extern ScriptString myScriptStringImpl;
 
diff --git a/engines/ags/engine/ac/room.h b/engines/ags/engine/ac/room.h
index 05f36efe87..e90fda831c 100644
--- a/engines/ags/engine/ac/room.h
+++ b/engines/ags/engine/ac/room.h
@@ -23,10 +23,10 @@
 #ifndef AGS_ENGINE_AC_ROOM_H
 #define AGS_ENGINE_AC_ROOM_H
 
-#include "ac/dynobj/scriptdrawingsurface.h"
-#include "ac/characterinfo.h"
-#include "script/runtimescriptvalue.h"
-#include "game/roomstruct.h"
+#include "ags/engine/ac/dynobj/scriptdrawingsurface.h"
+#include "ags/shared/ac/characterinfo.h"
+#include "ags/engine/script/runtimescriptvalue.h"
+#include "ags/shared/game/roomstruct.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/roomobject.cpp b/engines/ags/engine/ac/roomobject.cpp
index 92947e3db7..06ae948f4c 100644
--- a/engines/ags/engine/ac/roomobject.cpp
+++ b/engines/ags/engine/ac/roomobject.cpp
@@ -20,15 +20,15 @@
  *
  */
 
-#include "ac/roomobject.h"
-#include "ac/common.h"
-#include "ac/common_defines.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/runtime_defines.h"
-#include "ac/viewframe.h"
-#include "main/update.h"
-#include "util/stream.h"
+#include "ags/shared/ac/roomobject.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/common_defines.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/runtime_defines.h"
+#include "ags/shared/ac/viewframe.h"
+#include "ags/shared/main/update.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/roomobject.h b/engines/ags/engine/ac/roomobject.h
index b78f9a80d5..d14c5a33fd 100644
--- a/engines/ags/engine/ac/roomobject.h
+++ b/engines/ags/engine/ac/roomobject.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_ROOMOBJECT_H
 #define AGS_ENGINE_AC_ROOMOBJECT_H
 
-#include "ac/common_defines.h"
+#include "ags/shared/ac/common_defines.h"
 
 namespace AGS3 {
 
@@ -71,8 +71,8 @@ struct RoomObject {
 	void update_cycle_view_forwards();
 	void update_cycle_view_backwards();
 
-	void ReadFromFile(Common::Stream *in);
-	void WriteToFile(Common::Stream *out) const;
+	void ReadFromFile(Shared::Stream *in);
+	void WriteToFile(Shared::Stream *out) const;
 };
 
 } // namespace AGS3
diff --git a/engines/ags/engine/ac/roomstatus.cpp b/engines/ags/engine/ac/roomstatus.cpp
index 3687e476b5..d523a8d006 100644
--- a/engines/ags/engine/ac/roomstatus.cpp
+++ b/engines/ags/engine/ac/roomstatus.cpp
@@ -20,14 +20,14 @@
  *
  */
 
-#include <string.h> // memset
-#include <stdlib.h> // free
-#include "ac/common.h"
-#include "ac/game_version.h"
-#include "ac/roomstatus.h"
-#include "game/customproperties.h"
-#include "game/savegame_components.h"
-#include "util/alignedstream.h"
+//include <string.h> // memset
+//include <stdlib.h> // free
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/game_version.h"
+#include "ags/shared/ac/roomstatus.h"
+#include "ags/shared/game/customproperties.h"
+#include "ags/shared/game/savegame_components.h"
+#include "ags/shared/util/alignedstream.h"
 
 namespace AGS3 {
 
@@ -102,7 +102,7 @@ void RoomStatus::ReadFromFile_v321(Stream *in) {
 	}
 }
 
-void RoomStatus::ReadRoomObjects_Aligned(Common::Stream *in) {
+void RoomStatus::ReadRoomObjects_Aligned(Shared::Stream *in) {
 	AlignedStream align_s(in, Common::kAligned_Read);
 	for (int i = 0; i < MAX_ROOM_OBJECTS; ++i) {
 		obj[i].ReadFromFile(&align_s);
diff --git a/engines/ags/engine/ac/roomstatus.h b/engines/ags/engine/ac/roomstatus.h
index f23e71dfd8..89d982539a 100644
--- a/engines/ags/engine/ac/roomstatus.h
+++ b/engines/ags/engine/ac/roomstatus.h
@@ -23,10 +23,10 @@
 #ifndef AGS_ENGINE_AC_ROOMSTATUS_H
 #define AGS_ENGINE_AC_ROOMSTATUS_H
 
-#include "ac/roomobject.h"
-#include "game/roomstruct.h"
-#include "game/interactions.h"
-#include "util/string_types.h"
+#include "ags/engine/ac/roomobject.h"
+#include "ags/shared/game/roomstruct.h"
+#include "ags/shared/game/interactions.h"
+#include "ags/shared/util/string_types.h"
 
 namespace AGS3 {
 
@@ -54,9 +54,9 @@ struct RoomStatus {
 	Interaction intrRegion[MAX_ROOM_REGIONS];
 	Interaction intrRoom;
 
-	Common::StringIMap roomProps;
-	Common::StringIMap hsProps[MAX_ROOM_HOTSPOTS];
-	Common::StringIMap objProps[MAX_ROOM_OBJECTS];
+	Shared::StringIMap roomProps;
+	Shared::StringIMap hsProps[MAX_ROOM_HOTSPOTS];
+	Shared::StringIMap objProps[MAX_ROOM_OBJECTS];
 	// [IKM] 2012-06-22: not used anywhere
 #ifdef UNUSED_CODE
 	EventBlock hscond[MAX_ROOM_HOTSPOTS];
@@ -74,10 +74,10 @@ struct RoomStatus {
 	void FreeScriptData();
 	void FreeProperties();
 
-	void ReadFromFile_v321(Common::Stream *in);
-	void ReadRoomObjects_Aligned(Common::Stream *in);
-	void ReadFromSavegame(Common::Stream *in);
-	void WriteToSavegame(Common::Stream *out) const;
+	void ReadFromFile_v321(Shared::Stream *in);
+	void ReadRoomObjects_Aligned(Shared::Stream *in);
+	void ReadFromSavegame(Shared::Stream *in);
+	void WriteToSavegame(Shared::Stream *out) const;
 };
 
 // Replaces all accesses to the roomstats array
diff --git a/engines/ags/engine/ac/route_finder.cpp b/engines/ags/engine/ac/route_finder.cpp
index 44fa3464fd..2daaff186f 100644
--- a/engines/ags/engine/ac/route_finder.cpp
+++ b/engines/ags/engine/ac/route_finder.cpp
@@ -20,12 +20,12 @@
  *
  */
 
-#include "ac/route_finder.h"
+#include "ags/shared/ac/route_finder.h"
 
-#include "ac/route_finder_impl.h"
-#include "ac/route_finder_impl_legacy.h"
+#include "ags/shared/ac/route_finder_impl.h"
+#include "ags/shared/ac/route_finder_impl_legacy.h"
 
-#include "debug/out.h"
+#include "ags/shared/debug/out.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/route_finder.h b/engines/ags/engine/ac/route_finder.h
index 5759034843..69f0023ed4 100644
--- a/engines/ags/engine/ac/route_finder.h
+++ b/engines/ags/engine/ac/route_finder.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_ROUTEFND_H
 #define AGS_ENGINE_AC_ROUTEFND_H
 
-#include "ac/game_version.h"
+#include "ags/shared/ac/game_version.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/route_finder_impl.cpp b/engines/ags/engine/ac/route_finder_impl.cpp
index a9d93a6bb5..b62bd5cfb8 100644
--- a/engines/ags/engine/ac/route_finder_impl.cpp
+++ b/engines/ags/engine/ac/route_finder_impl.cpp
@@ -26,18 +26,18 @@
 //
 //=============================================================================
 
-#include "ac/route_finder_impl.h"
+#include "ags/shared/ac/route_finder_impl.h"
 
-#include <string.h>
-#include <math.h>
+//include <string.h>
+//include <math.h>
 
-#include "ac/common.h"   // quit()
-#include "ac/movelist.h"     // MoveList
-#include "ac/common_defines.h"
-#include "gfx/bitmap.h"
-#include "debug/out.h"
+#include "ags/shared/ac/common.h"   // quit()
+#include "ags/shared/ac/movelist.h"     // MoveList
+#include "ags/shared/ac/common_defines.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/debug/out.h"
 
-#include "route_finder_jps.inl"
+#include "ags/shared/route_finder_jps.inl"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/route_finder_impl.h b/engines/ags/engine/ac/route_finder_impl.h
index cfd44228e0..39b78e56ce 100644
--- a/engines/ags/engine/ac/route_finder_impl.h
+++ b/engines/ags/engine/ac/route_finder_impl.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_ROUTE_FINDER_IMPL
 #define AGS_ENGINE_AC_ROUTE_FINDER_IMPL
 
-#include "ac/game_version.h"
+#include "ags/shared/ac/game_version.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/route_finder_impl_legacy.cpp b/engines/ags/engine/ac/route_finder_impl_legacy.cpp
index be4c99a9d1..88c30f5fd8 100644
--- a/engines/ags/engine/ac/route_finder_impl_legacy.cpp
+++ b/engines/ags/engine/ac/route_finder_impl_legacy.cpp
@@ -27,17 +27,17 @@
 //
 //=============================================================================
 
-#include "ac/route_finder_impl_legacy.h"
+#include "ags/shared/ac/route_finder_impl_legacy.h"
 
-#include <string.h>
-#include <math.h>
+//include <string.h>
+//include <math.h>
 
-#include "ac/common.h"   // quit()
-#include "ac/common_defines.h"
-#include "game/roomstruct.h"
-#include "ac/movelist.h"     // MoveList
-#include "gfx/bitmap.h"
-#include "debug/out.h"
+#include "ags/shared/ac/common.h"   // quit()
+#include "ags/shared/ac/common_defines.h"
+#include "ags/shared/game/roomstruct.h"
+#include "ags/shared/ac/movelist.h"     // MoveList
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/debug/out.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/route_finder_jps.inl b/engines/ags/engine/ac/route_finder_jps.inl
index e78db1b576..5172e59538 100644
--- a/engines/ags/engine/ac/route_finder_jps.inl
+++ b/engines/ags/engine/ac/route_finder_jps.inl
@@ -17,13 +17,13 @@
 //
 //=============================================================================
 
-#include <queue>
-#include <vector>
-#include <algorithm>
-#include <functional>
-#include <assert.h>
-#include <stddef.h>
-#include <math.h>
+//include <queue>
+#include "ags/std/vector.h"
+//include <algorithm>
+//include <functional>
+//include <assert.h>
+//include <stddef.h>
+//include <math.h>
 
 // TODO: this could be cleaned up/simplified ...
 
diff --git a/engines/ags/engine/ac/runtime_defines.h b/engines/ags/engine/ac/runtime_defines.h
index 7e2e9d544b..5de5e34542 100644
--- a/engines/ags/engine/ac/runtime_defines.h
+++ b/engines/ags/engine/ac/runtime_defines.h
@@ -159,6 +159,6 @@ const int LegacyRoomVolumeFactor = 30;
 
 } // namespace AGS3
 
-#include "ac/common_defines.h"
+#include "ags/shared/ac/common_defines.h"
 
 #endif
diff --git a/engines/ags/engine/ac/screen.cpp b/engines/ags/engine/ac/screen.cpp
index ccdba13745..15ddac6f35 100644
--- a/engines/ags/engine/ac/screen.cpp
+++ b/engines/ags/engine/ac/screen.cpp
@@ -20,21 +20,21 @@
  *
  */
 
-#include "ac/common.h"
-#include "ac/draw.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/global_game.h"
-#include "ac/global_screen.h"
-#include "ac/screen.h"
-#include "ac/dynobj/scriptviewport.h"
-#include "ac/dynobj/scriptuserobject.h"
-#include "script/script_runtime.h"
-#include "platform/base/agsplatformdriver.h"
-#include "plugin/agsplugin.h"
-#include "plugin/plugin_engine.h"
-#include "gfx/bitmap.h"
-#include "gfx/graphicsdriver.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_game.h"
+#include "ags/shared/ac/global_screen.h"
+#include "ags/shared/ac/screen.h"
+#include "ags/shared/ac/dynobj/scriptviewport.h"
+#include "ags/shared/ac/dynobj/scriptuserobject.h"
+#include "ags/shared/script/script_runtime.h"
+#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/shared/plugin/agsplugin.h"
+#include "ags/shared/plugin/plugin_engine.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/gfx/graphicsdriver.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/screenoverlay.cpp b/engines/ags/engine/ac/screenoverlay.cpp
index ed1a886f52..fadd6e6c2e 100644
--- a/engines/ags/engine/ac/screenoverlay.cpp
+++ b/engines/ags/engine/ac/screenoverlay.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "screenoverlay.h"
-#include "util/stream.h"
+#include "ags/shared/screenoverlay.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/screenoverlay.h b/engines/ags/engine/ac/screenoverlay.h
index 64a04906bf..97787c34ba 100644
--- a/engines/ags/engine/ac/screenoverlay.h
+++ b/engines/ags/engine/ac/screenoverlay.h
@@ -23,7 +23,8 @@
 #ifndef AGS_ENGINE_AC_SCREENOVERLAY_H
 #define AGS_ENGINE_AC_SCREENOVERLAY_H
 
-#include <stdint.h>
+//include <stdint.h>
+#include "ags/shared/core/types.h"
 
 namespace AGS3 {
 
@@ -46,7 +47,7 @@ using namespace AGS; // FIXME later
 
 struct ScreenOverlay {
 	Engine::IDriverDependantBitmap *bmp = nullptr;
-	Common::Bitmap *pic = nullptr;
+	Shared::Bitmap *pic = nullptr;
 	int type = 0, x = 0, y = 0, timeout = 0;
 	int bgSpeechForChar = 0;
 	int associatedOverlayHandle = 0;
@@ -55,8 +56,8 @@ struct ScreenOverlay {
 	bool hasSerializedBitmap = false;
 	int _offsetX = 0, _offsetY = 0;
 
-	void ReadFromFile(Common::Stream *in, int32_t cmp_ver);
-	void WriteToFile(Common::Stream *out) const;
+	void ReadFromFile(Shared::Stream *in, int32_t cmp_ver);
+	void WriteToFile(Shared::Stream *out) const;
 };
 
 } // namespace AGS3
diff --git a/engines/ags/engine/ac/scriptcontainers.cpp b/engines/ags/engine/ac/scriptcontainers.cpp
index 5b33fdd3a3..148832bda5 100644
--- a/engines/ags/engine/ac/scriptcontainers.cpp
+++ b/engines/ags/engine/ac/scriptcontainers.cpp
@@ -26,16 +26,16 @@
 //
 //=============================================================================
 
-#include "ac/common.h" // quit
-#include "ac/string.h"
-#include "ac/dynobj/cc_dynamicarray.h"
-#include "ac/dynobj/cc_dynamicobject.h"
-#include "ac/dynobj/scriptdict.h"
-#include "ac/dynobj/scriptset.h"
-#include "ac/dynobj/scriptstring.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
-#include "util/bbop.h"
+#include "ags/shared/ac/common.h" // quit
+#include "ags/shared/ac/string.h"
+#include "ags/shared/ac/dynobj/cc_dynamicarray.h"
+#include "ags/shared/ac/dynobj/cc_dynamicobject.h"
+#include "ags/shared/ac/dynobj/scriptdict.h"
+#include "ags/shared/ac/dynobj/scriptset.h"
+#include "ags/shared/ac/dynobj/scriptstring.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
+#include "ags/shared/util/bbop.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/slider.cpp b/engines/ags/engine/ac/slider.cpp
index 66273367ba..89589b80e3 100644
--- a/engines/ags/engine/ac/slider.cpp
+++ b/engines/ags/engine/ac/slider.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ac/slider.h"
-#include "ac/common.h"
+#include "ags/shared/ac/slider.h"
+#include "ags/shared/ac/common.h"
 
 namespace AGS3 {
 
@@ -118,9 +118,9 @@ void Slider_SetHandleOffset(GUISlider *guisl, int newOffset) {
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
 
 // int (GUISlider *guisl)
 RuntimeScriptValue Sc_Slider_GetBackgroundGraphic(void *self, const RuntimeScriptValue *params, int32_t param_count) {
diff --git a/engines/ags/engine/ac/slider.h b/engines/ags/engine/ac/slider.h
index d5d8af96d4..3c94e485e2 100644
--- a/engines/ags/engine/ac/slider.h
+++ b/engines/ags/engine/ac/slider.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_SLIDER_H
 #define AGS_ENGINE_AC_SLIDER_H
 
-#include "gui/guislider.h"
+#include "ags/shared/gui/guislider.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/speech.cpp b/engines/ags/engine/ac/speech.cpp
index e91694c826..08b2584ebc 100644
--- a/engines/ags/engine/ac/speech.cpp
+++ b/engines/ags/engine/ac/speech.cpp
@@ -20,10 +20,10 @@
  *
  */
 
-#include "ac/common.h"
-#include "ac/runtime_defines.h"
-#include "ac/speech.h"
-#include "debug/debug_log.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/runtime_defines.h"
+#include "ags/shared/ac/speech.h"
+#include "ags/shared/debug/debug_log.h"
 
 namespace AGS3 {
 
@@ -78,13 +78,13 @@ SkipSpeechStyle internal_skip_speech_to_user(int internal_val) {
 //
 //=============================================================================
 
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/global_audio.h"
-#include "ac/global_display.h"
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_audio.h"
+#include "ags/shared/ac/global_display.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
 
 extern GameSetupStruct game;
 extern GameState play;
diff --git a/engines/ags/engine/ac/sprite.cpp b/engines/ags/engine/ac/sprite.cpp
index 25457a4963..4220305ce9 100644
--- a/engines/ags/engine/ac/sprite.cpp
+++ b/engines/ags/engine/ac/sprite.cpp
@@ -20,17 +20,17 @@
  *
  */
 
-#include "ac/common.h"
-#include "ac/draw.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/sprite.h"
-#include "ac/system.h"
-#include "platform/base/agsplatformdriver.h"
-#include "plugin/agsplugin.h"
-#include "plugin/plugin_engine.h"
-#include "ac/spritecache.h"
-#include "gfx/bitmap.h"
-#include "gfx/graphicsdriver.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/sprite.h"
+#include "ags/shared/ac/system.h"
+#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/shared/plugin/agsplugin.h"
+#include "ags/shared/plugin/plugin_engine.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/gfx/graphicsdriver.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/sprite.h b/engines/ags/engine/ac/sprite.h
index 09f841e005..8995e76fec 100644
--- a/engines/ags/engine/ac/sprite.h
+++ b/engines/ags/engine/ac/sprite.h
@@ -28,9 +28,9 @@ namespace AGS3 {
 void get_new_size_for_sprite(int ee, int ww, int hh, int &newwid, int &newhit);
 // set any alpha-transparent pixels in the image to the appropriate
 // RGB mask value so that the ->Blit calls work correctly
-void set_rgb_mask_using_alpha_channel(Common::Bitmap *image);
+void set_rgb_mask_using_alpha_channel(Shared::Bitmap *image);
 // from is a 32-bit RGBA image, to is a 15/16/24-bit destination image
-Common::Bitmap *remove_alpha_channel(Common::Bitmap *from);
+Shared::Bitmap *remove_alpha_channel(Shared::Bitmap *from);
 void pre_save_sprite(int ee);
 void initialize_sprite(int ee);
 
diff --git a/engines/ags/engine/ac/spritecache_engine.cpp b/engines/ags/engine/ac/spritecache_engine.cpp
index 9f5ae3388e..e31443c64d 100644
--- a/engines/ags/engine/ac/spritecache_engine.cpp
+++ b/engines/ags/engine/ac/spritecache_engine.cpp
@@ -33,9 +33,9 @@
 #pragma warning (disable: 4996 4312)  // disable deprecation warnings
 #endif
 
-#include "ac/gamestructdefines.h"
-#include "ac/spritecache.h"
-#include "util/compress.h"
+#include "ags/shared/ac/gamestructdefines.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/util/compress.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/spritelistentry.h b/engines/ags/engine/ac/spritelistentry.h
index cbf0a049be..6db4ca3c3b 100644
--- a/engines/ags/engine/ac/spritelistentry.h
+++ b/engines/ags/engine/ac/spritelistentry.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_SPRITELISTENTRY_H
 #define AGS_ENGINE_AC_SPRITELISTENTRY_H
 
-#include "gfx/ddb.h"
+#include "ags/engine/gfx/ddb.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/statobj/agsstaticobject.cpp b/engines/ags/engine/ac/statobj/agsstaticobject.cpp
index 54f975ee76..db55c0bcb3 100644
--- a/engines/ags/engine/ac/statobj/agsstaticobject.cpp
+++ b/engines/ags/engine/ac/statobj/agsstaticobject.cpp
@@ -20,10 +20,10 @@
  *
  */
 
-#include <string.h>
-#include "ac/statobj/agsstaticobject.h"
-#include "ac/game.h"
-#include "ac/gamestate.h"
+//include <string.h>
+#include "ags/shared/ac/statobj/agsstaticobject.h"
+#include "ags/shared/ac/game.h"
+#include "ags/shared/ac/gamestate.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/statobj/agsstaticobject.h b/engines/ags/engine/ac/statobj/agsstaticobject.h
index adaddac4ab..6b6a0224e6 100644
--- a/engines/ags/engine/ac/statobj/agsstaticobject.h
+++ b/engines/ags/engine/ac/statobj/agsstaticobject.h
@@ -23,7 +23,7 @@
 #ifndef _AGS_ENGINE_AC_STATICOBJ_AGSSTATICOBJECT_H
 #define _AGS_ENGINE_AC_STATICOBJ_AGSSTATICOBJECT_H
 
-#include "ac/statobj/staticobject.h"
+#include "ags/engine/ac/statobj/staticobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/statobj/staticarray.cpp b/engines/ags/engine/ac/statobj/staticarray.cpp
index a55758eac6..73fd3b27f8 100644
--- a/engines/ags/engine/ac/statobj/staticarray.cpp
+++ b/engines/ags/engine/ac/statobj/staticarray.cpp
@@ -20,9 +20,9 @@
  *
  */
 
-#include <string.h>
-#include "ac/statobj/staticarray.h"
-#include "ac/dynobj/cc_dynamicobject.h"
+//include <string.h>
+#include "ags/shared/ac/statobj/staticarray.h"
+#include "ags/shared/ac/dynobj/cc_dynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/statobj/staticarray.h b/engines/ags/engine/ac/statobj/staticarray.h
index 1941cc603b..3940708f10 100644
--- a/engines/ags/engine/ac/statobj/staticarray.h
+++ b/engines/ags/engine/ac/statobj/staticarray.h
@@ -23,7 +23,7 @@
 #ifndef _AGS_ENGINE_AC_STATICOBJ_STATICARRAY_H
 #define _AGS_ENGINE_AC_STATICOBJ_STATICARRAY_H
 
-#include "ac/statobj/staticobject.h"
+#include "ags/shared/ac/statobj/staticobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/statobj/staticobject.h b/engines/ags/engine/ac/statobj/staticobject.h
index 5653222d77..a38e521c00 100644
--- a/engines/ags/engine/ac/statobj/staticobject.h
+++ b/engines/ags/engine/ac/statobj/staticobject.h
@@ -31,7 +31,7 @@
 #ifndef AGS_ENGINE_AC_STATICOBJ_STATICOBJECT_H
 #define AGS_ENGINE_AC_STATICOBJ_STATICOBJECT_H
 
-#include "core/types.h"
+#include "ags/shared/core/types.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/string.cpp b/engines/ags/engine/ac/string.cpp
index 3380f56c7d..60a963a50a 100644
--- a/engines/ags/engine/ac/string.cpp
+++ b/engines/ags/engine/ac/string.cpp
@@ -20,19 +20,19 @@
  *
  */
 
-#include <cstdio>
-#include "ac/string.h"
-#include "ac/common.h"
-#include "ac/display.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/global_translation.h"
-#include "ac/runtime_defines.h"
-#include "ac/dynobj/scriptstring.h"
-#include "font/fonts.h"
-#include "debug/debug_log.h"
-#include "script/runtimescriptvalue.h"
-#include "util/string_compat.h"
+//include <cstdio>
+#include "ags/shared/ac/string.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/display.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_translation.h"
+#include "ags/shared/ac/runtime_defines.h"
+#include "ags/shared/ac/dynobj/scriptstring.h"
+#include "ags/shared/font/fonts.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/script/runtimescriptvalue.h"
+#include "ags/shared/util/string_compat.h"
 
 namespace AGS3 {
 
@@ -298,10 +298,10 @@ void my_strncpy(char *dest, const char *src, int len) {
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
-#include "ac/math.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
+#include "ags/shared/ac/math.h"
 
 // int (const char *thisString)
 RuntimeScriptValue Sc_String_IsNullOrEmpty(const RuntimeScriptValue *params, int32_t param_count) {
diff --git a/engines/ags/engine/ac/string.h b/engines/ags/engine/ac/string.h
index e27bd213a4..1d606e9a2d 100644
--- a/engines/ags/engine/ac/string.h
+++ b/engines/ags/engine/ac/string.h
@@ -23,8 +23,8 @@
 #ifndef AGS_ENGINE_AC_STRING_H
 #define AGS_ENGINE_AC_STRING_H
 
-#include <stdarg.h>
-#include "ac/dynobj/cc_dynamicobject.h"
+//include <stdarg.h>
+#include "ags/engine/ac/dynobj/cc_dynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/sys_events.cpp b/engines/ags/engine/ac/sys_events.cpp
index fc20cdbd98..467e80a13d 100644
--- a/engines/ags/engine/ac/sys_events.cpp
+++ b/engines/ags/engine/ac/sys_events.cpp
@@ -20,16 +20,16 @@
  *
  */
 
-#include "core/platform.h"
-#include "ac/common.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/keycode.h"
-#include "ac/mouse.h"
-#include "ac/sys_events.h"
-#include "device/mousew32.h"
-#include "platform/base/agsplatformdriver.h"
-#include "ac/timer.h"
+#include "ags/shared/core/platform.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/keycode.h"
+#include "ags/shared/ac/mouse.h"
+#include "ags/shared/ac/sys_events.h"
+#include "ags/shared/device/mousew32.h"
+#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/shared/ac/timer.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/system.cpp b/engines/ags/engine/ac/system.cpp
index 33be22fd38..873b11ee98 100644
--- a/engines/ags/engine/ac/system.cpp
+++ b/engines/ags/engine/ac/system.cpp
@@ -20,26 +20,26 @@
  *
  */
 
-#include "ac/common.h"
-#include "ac/draw.h"
-#include "ac/gamesetup.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/mouse.h"
-#include "ac/string.h"
-#include "ac/system.h"
-#include "ac/dynobj/scriptsystem.h"
-#include "debug/debug_log.h"
-#include "debug/out.h"
-#include "main/engine.h"
-#include "main/main.h"
-#include "gfx/graphicsdriver.h"
-#include "ac/dynobj/cc_audiochannel.h"
-#include "main/graphics_mode.h"
-#include "ac/global_debug.h"
-#include "ac/global_translation.h"
-#include "media/audio/audio_system.h"
-#include "util/string_compat.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/gamesetup.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/mouse.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/ac/system.h"
+#include "ags/shared/ac/dynobj/scriptsystem.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/main/engine.h"
+#include "ags/shared/main/main.h"
+#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/shared/ac/dynobj/cc_audiochannel.h"
+#include "ags/shared/main/graphics_mode.h"
+#include "ags/shared/ac/global_debug.h"
+#include "ags/shared/ac/global_translation.h"
+#include "ags/shared/media/audio/audio_system.h"
+#include "ags/shared/util/string_compat.h"
 
 namespace AGS3 {
 
@@ -227,10 +227,10 @@ void System_SetRenderAtScreenResolution(int enable) {
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
-#include "ac/dynobj/scriptstring.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
+#include "ags/shared/ac/dynobj/scriptstring.h"
 
 extern ScriptString myScriptStringImpl;
 
diff --git a/engines/ags/engine/ac/system.h b/engines/ags/engine/ac/system.h
index 280ec92ec7..0b8708d1a2 100644
--- a/engines/ags/engine/ac/system.h
+++ b/engines/ags/engine/ac/system.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_SYSTEMAUDIO_H
 #define AGS_ENGINE_AC_SYSTEMAUDIO_H
 
-#include "ac/dynobj/scriptaudiochannel.h"
+#include "ags/engine/ac/dynobj/scriptaudiochannel.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/textbox.cpp b/engines/ags/engine/ac/textbox.cpp
index 64f68cc217..f4dfa5809b 100644
--- a/engines/ags/engine/ac/textbox.cpp
+++ b/engines/ags/engine/ac/textbox.cpp
@@ -20,11 +20,11 @@
  *
  */
 
-#include <string.h>
-#include "ac/textbox.h"
-#include "ac/common.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/string.h"
+//include <string.h>
+#include "ags/shared/ac/textbox.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/string.h"
 
 namespace AGS3 {
 
@@ -90,10 +90,10 @@ void TextBox_SetShowBorder(GUITextBox *guit, bool on) {
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
-#include "ac/dynobj/scriptstring.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
+#include "ags/shared/ac/dynobj/scriptstring.h"
 
 extern ScriptString myScriptStringImpl;
 
diff --git a/engines/ags/engine/ac/textbox.h b/engines/ags/engine/ac/textbox.h
index 45271c0d67..c1bb80801c 100644
--- a/engines/ags/engine/ac/textbox.h
+++ b/engines/ags/engine/ac/textbox.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_TEXTBOX_H
 #define AGS_ENGINE_AC_TEXTBOX_H
 
-#include "gui/guitextbox.h"
+#include "ags/shared/gui/guitextbox.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/timer.cpp b/engines/ags/engine/ac/timer.cpp
index 2e2f9b472b..08f475228f 100644
--- a/engines/ags/engine/ac/timer.cpp
+++ b/engines/ags/engine/ac/timer.cpp
@@ -20,16 +20,16 @@
  *
  */
 
-#include "ac/timer.h"
+#include "ags/shared/ac/timer.h"
 
-#include "core/platform.h"
+#include "ags/shared/core/platform.h"
 #if AGS_PLATFORM_DEBUG && defined (__GNUC__)
-#include <stdio.h>
-#include <execinfo.h>
-#include <unistd.h>
+//include <stdio.h>
+//include <execinfo.h>
+//include <unistd.h>
 #endif
-#include <thread>
-#include "platform/base/agsplatformdriver.h"
+//include <thread>
+#include "ags/shared/platform/base/agsplatformdriver.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/timer.h b/engines/ags/engine/ac/timer.h
index fa0ecb8801..b737923aee 100644
--- a/engines/ags/engine/ac/timer.h
+++ b/engines/ags/engine/ac/timer.h
@@ -23,14 +23,15 @@
 #ifndef AGS_ENGINE_AC_TIMER_H
 #define AGS_ENGINE_AC_TIMER_H
 
-#include <type_traits>
-#include <chrono>
+#include "ags/std/type_traits.h"
+#include "ags/std/chrono.h"
+#include "ags/std/xtr1common.h"
 
 namespace AGS3 {
 
 // use high resolution clock only if we know it is monotonic/steady.
 // refer to https://stackoverflow.com/a/38253266/84262
-using AGS_Clock = std::conditional <
+using AGS_Clock = std::conditional<
 	std::chrono::high_resolution_clock::is_steady,
 	std::chrono::high_resolution_clock, std::chrono::steady_clock
 >::type;
diff --git a/engines/ags/engine/ac/translation.cpp b/engines/ags/engine/ac/translation.cpp
index 4ca6ac1577..3c2892b583 100644
--- a/engines/ags/engine/ac/translation.cpp
+++ b/engines/ags/engine/ac/translation.cpp
@@ -20,21 +20,21 @@
  *
  */
 
-#include <cstdio>
-#include "ac/asset_helper.h"
-#include "ac/common.h"
-#include "ac/gamesetup.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/global_game.h"
-#include "ac/runtime_defines.h"
-#include "ac/translation.h"
-#include "ac/tree_map.h"
-#include "ac/wordsdictionary.h"
-#include "debug/out.h"
-#include "util/misc.h"
-#include "util/stream.h"
-#include "core/assetmanager.h"
+//include <cstdio>
+#include "ags/shared/ac/asset_helper.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/gamesetup.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/global_game.h"
+#include "ags/shared/ac/runtime_defines.h"
+#include "ags/shared/ac/translation.h"
+#include "ags/shared/ac/tree_map.h"
+#include "ags/shared/ac/wordsdictionary.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/util/misc.h"
+#include "ags/shared/util/stream.h"
+#include "ags/shared/core/assetmanager.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/translation.h b/engines/ags/engine/ac/translation.h
index 30e638befe..1dbc27c3a2 100644
--- a/engines/ags/engine/ac/translation.h
+++ b/engines/ags/engine/ac/translation.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_TRANSLATION_H
 #define AGS_ENGINE_AC_TRANSLATION_H
 
-#include "util/string.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/tree_map.cpp b/engines/ags/engine/ac/tree_map.cpp
index 0f8680d14a..d81be33d3b 100644
--- a/engines/ags/engine/ac/tree_map.cpp
+++ b/engines/ags/engine/ac/tree_map.cpp
@@ -20,10 +20,10 @@
  *
  */
 
-#include <string.h>
-#include <stdlib.h>
-#include "ac/common.h"
-#include "ac/tree_map.h"
+//include <string.h>
+//include <stdlib.h>
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/tree_map.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/viewframe.cpp b/engines/ags/engine/ac/viewframe.cpp
index 6f749c52c2..41ab83b027 100644
--- a/engines/ags/engine/ac/viewframe.cpp
+++ b/engines/ags/engine/ac/viewframe.cpp
@@ -20,16 +20,16 @@
  *
  */
 
-#include "ac/gamesetupstruct.h"
-#include "ac/viewframe.h"
-#include "debug/debug_log.h"
-#include "ac/spritecache.h"
-#include "gfx/bitmap.h"
-#include "script/runtimescriptvalue.h"
-#include "ac/dynobj/cc_audioclip.h"
-#include "ac/draw.h"
-#include "ac/game_version.h"
-#include "media/audio/audio_system.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/viewframe.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/script/runtimescriptvalue.h"
+#include "ags/shared/ac/dynobj/cc_audioclip.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/game_version.h"
+#include "ags/shared/media/audio/audio_system.h"
 
 } // namespace AGS3
 
@@ -178,9 +178,9 @@ void DrawViewFrame(Bitmap *ds, const ViewFrame *vframe, int x, int y, bool alpha
 //
 //=============================================================================
 
-#include "debug/out.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
 
 // int (ScriptViewFrame *svf)
 RuntimeScriptValue Sc_ViewFrame_GetFlipped(void *self, const RuntimeScriptValue *params, int32_t param_count) {
diff --git a/engines/ags/engine/ac/viewframe.h b/engines/ags/engine/ac/viewframe.h
index 7e2c4edbf5..d169d83cdc 100644
--- a/engines/ags/engine/ac/viewframe.h
+++ b/engines/ags/engine/ac/viewframe.h
@@ -23,11 +23,11 @@
 #ifndef AGS_ENGINE_AC_VIEWFRAME_H
 #define AGS_ENGINE_AC_VIEWFRAME_H
 
-#include "ac/runtime_defines.h"
-#include "ac/view.h"
-#include "ac/dynobj/scriptaudioclip.h"
-#include "ac/dynobj/scriptviewframe.h"
-#include "gfx/bitmap.h"
+#include "ags/engine/ac/runtime_defines.h"
+#include "ags/shared/ac/view.h"
+#include "ags/shared/ac/dynobj/scriptaudioclip.h"
+#include "ags/engine/ac/dynobj/scriptviewframe.h"
+#include "ags/shared/gfx/bitmap.h"
 
 namespace AGS3 {
 
@@ -54,7 +54,7 @@ int  ViewFrame_GetFrame(ScriptViewFrame *svf);
 void precache_view(int view);
 void CheckViewFrame(int view, int loop, int frame, int sound_volume = SCR_NO_VALUE);
 // draws a view frame, flipped if appropriate
-void DrawViewFrame(Common::Bitmap *ds, const ViewFrame *vframe, int x, int y, bool alpha_blend = false);
+void DrawViewFrame(Shared::Bitmap *ds, const ViewFrame *vframe, int x, int y, bool alpha_blend = false);
 
 } // namespace AGS3
 
diff --git a/engines/ags/engine/ac/viewport_script.cpp b/engines/ags/engine/ac/viewport_script.cpp
index d4f405ab76..e145c78d96 100644
--- a/engines/ags/engine/ac/viewport_script.cpp
+++ b/engines/ags/engine/ac/viewport_script.cpp
@@ -26,14 +26,14 @@
 //
 //=============================================================================
 
-#include "ac/dynobj/scriptcamera.h"
-#include "ac/dynobj/scriptviewport.h"
-#include "ac/dynobj/scriptuserobject.h"
-#include "ac/draw.h"
-#include "ac/gamestate.h"
-#include "debug/debug_log.h"
-#include "script/script_api.h"
-#include "script/script_runtime.h"
+#include "ags/shared/ac/dynobj/scriptcamera.h"
+#include "ags/shared/ac/dynobj/scriptviewport.h"
+#include "ags/shared/ac/dynobj/scriptuserobject.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/walkablearea.cpp b/engines/ags/engine/ac/walkablearea.cpp
index 93d6d5c07f..8d9a62caf2 100644
--- a/engines/ags/engine/ac/walkablearea.cpp
+++ b/engines/ags/engine/ac/walkablearea.cpp
@@ -20,18 +20,18 @@
  *
  */
 
-#include "ac/common.h"
-#include "ac/object.h"
-#include "ac/character.h"
-#include "ac/gamestate.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/object.h"
-#include "ac/room.h"
-#include "ac/roomobject.h"
-#include "ac/roomstatus.h"
-#include "ac/walkablearea.h"
-#include "game/roomstruct.h"
-#include "gfx/bitmap.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/object.h"
+#include "ags/shared/ac/character.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/object.h"
+#include "ags/shared/ac/room.h"
+#include "ags/shared/ac/roomobject.h"
+#include "ags/shared/ac/roomstatus.h"
+#include "ags/shared/ac/walkablearea.h"
+#include "ags/shared/game/roomstruct.h"
+#include "ags/shared/gfx/bitmap.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/walkablearea.h b/engines/ags/engine/ac/walkablearea.h
index 922f90af10..68717ddb8d 100644
--- a/engines/ags/engine/ac/walkablearea.h
+++ b/engines/ags/engine/ac/walkablearea.h
@@ -31,7 +31,7 @@ int   get_area_scaling(int onarea, int xx, int yy);
 void  scale_sprite_size(int sppic, int zoom_level, int *newwidth, int *newheight);
 void  remove_walkable_areas_from_temp(int fromx, int cwidth, int starty, int endy);
 int   is_point_in_rect(int x, int y, int left, int top, int right, int bottom);
-Common::Bitmap *prepare_walkable_areas(int sourceChar);
+Shared::Bitmap *prepare_walkable_areas(int sourceChar);
 int   get_walkable_area_at_location(int xx, int yy);
 int   get_walkable_area_at_character(int charnum);
 
diff --git a/engines/ags/engine/ac/walkbehind.cpp b/engines/ags/engine/ac/walkbehind.cpp
index 9074446185..27b36e1ec4 100644
--- a/engines/ags/engine/ac/walkbehind.cpp
+++ b/engines/ags/engine/ac/walkbehind.cpp
@@ -20,12 +20,12 @@
  *
  */
 
-#include "ac/walkbehind.h"
-#include "ac/common.h"
-#include "ac/common_defines.h"
-#include "ac/gamestate.h"
-#include "gfx/graphicsdriver.h"
-#include "gfx/bitmap.h"
+#include "ags/shared/ac/walkbehind.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/common_defines.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/shared/gfx/bitmap.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/debugging/consoleoutputtarget.cpp b/engines/ags/engine/debugging/consoleoutputtarget.cpp
index 6f638edd7b..cc9a72e452 100644
--- a/engines/ags/engine/debugging/consoleoutputtarget.cpp
+++ b/engines/ags/engine/debugging/consoleoutputtarget.cpp
@@ -20,9 +20,9 @@
  *
  */
 
-#include <string.h>
-#include "consoleoutputtarget.h"
-#include "debug/debug_log.h"
+//include <string.h>
+#include "ags/engine/debugging/consoleoutputtarget.h"
+#include "ags/engine/debugging/debug_log.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/debugging/consoleoutputtarget.h b/engines/ags/engine/debugging/consoleoutputtarget.h
index 7772d45de0..e3caefa6e1 100644
--- a/engines/ags/engine/debugging/consoleoutputtarget.h
+++ b/engines/ags/engine/debugging/consoleoutputtarget.h
@@ -30,14 +30,14 @@
 #ifndef AGS_ENGINE_DEBUGGING_CONSOLEOUTPUTTARGET_H
 #define AGS_ENGINE_DEBUGGING_CONSOLEOUTPUTTARGET_H
 
-#include "debug/outputhandler.h"
+#include "ags/shared/debugging/outputhandler.h"
 
 namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
-using Common::String;
-using Common::DebugMessage;
+using Shared::String;
+using Shared::DebugMessage;
 
 class ConsoleOutputTarget : public AGS::Shared::IOutputHandler {
 public:
diff --git a/engines/ags/engine/debugging/debug.cpp b/engines/ags/engine/debugging/debug.cpp
index a974ff2995..903787665d 100644
--- a/engines/ags/engine/debugging/debug.cpp
+++ b/engines/ags/engine/debugging/debug.cpp
@@ -20,32 +20,33 @@
  *
  */
 
-#include <memory>
-#include <limits>
-#include "core/platform.h"
-#include "ac/common.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/runtime_defines.h"
-#include "debug/agseditordebugger.h"
-#include "debug/debug_log.h"
-#include "debug/debugger.h"
-#include "debug/debugmanager.h"
-#include "debug/out.h"
-#include "debug/consoleoutputtarget.h"
-#include "debug/logfile.h"
-#include "debug/messagebuffer.h"
-#include "main/config.h"
-#include "media/audio/audio_system.h"
-#include "platform/base/agsplatformdriver.h"
-#include "plugin/plugin_engine.h"
-#include "script/script.h"
-#include "script/script_common.h"
-#include "script/cc_error.h"
-#include "util/string_utils.h"
-#include "util/textstreamwriter.h"
+#include "ags/std/initializer_list.h"
+#include "ags/std/limits.h"
+#include "ags/std/memory.h"
+#include "ags/shared/core/platform.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/engine/ac/runtime_defines.h"
+#include "ags/engine/debugging/agseditordebugger.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/debugging/debugger.h"
+#include "ags/shared/debugging/debugmanager.h"
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/debugging/consoleoutputtarget.h"
+#include "ags/engine/debugging/logfile.h"
+#include "ags/engine/debugging/messagebuffer.h"
+#include "ags/engine/main/config.h"
+#include "ags/engine/media/audio/audio_system.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
+#include "ags/engine/plugin/plugin_engine.h"
+#include "ags/engine/script/script.h"
+#include "ags/shared/script/script_common.h"
+#include "ags/shared/script/cc_error.h"
+#include "ags/shared/util/string_utils.h"
+#include "ags/shared/util/textstreamwriter.h"
 
 #if AGS_PLATFORM_OS_WINDOWS
-#include <winalleg.h>
+//include <winalleg.h>
 #endif
 
 namespace AGS3 {
@@ -70,7 +71,7 @@ volatile int game_paused_in_debugger = 0;
 
 #if AGS_PLATFORM_OS_WINDOWS
 
-#include "platform/windows/debug/namedpipesagsdebugger.h"
+#include "ags/shared/platform/windows/debug/namedpipesagsdebugger.h"
 
 HWND editor_window_handle = 0;
 
@@ -167,8 +168,8 @@ MessageType get_messagetype_from_string(const String &mt) {
 typedef std::pair<CommonDebugGroup, MessageType> DbgGroupOption;
 
 void apply_log_config(const ConfigTree &cfg, const String &log_id,
-	bool def_enabled,
-	std::initializer_list<DbgGroupOption> def_opts) {
+		bool def_enabled,
+		std::initializer_list<DbgGroupOption> def_opts) {
 	String value = INIreadstring(cfg, "log", log_id);
 	if (value.IsEmpty() && !def_enabled)
 		return;
diff --git a/engines/ags/engine/debugging/debug_log.h b/engines/ags/engine/debugging/debug_log.h
index 729fafabac..9525086218 100644
--- a/engines/ags/engine/debugging/debug_log.h
+++ b/engines/ags/engine/debugging/debug_log.h
@@ -23,11 +23,11 @@
 #ifndef AGS_ENGINE_DEBUGGING_LOG_H
 #define AGS_ENGINE_DEBUGGING_LOG_H
 
-#include "script/cc_instance.h"
-#include "ac/runtime_defines.h"
-#include "ac/gamestate.h"
-#include "platform/base/agsplatformdriver.h"
-#include "util/ini_util.h"
+#include "ags/engine/script/cc_instance.h"
+#include "ags/engine/ac/runtime_defines.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
+#include "ags/shared/util/ini_util.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/debugging/debugger.h b/engines/ags/engine/debugging/debugger.h
index 5f97124f5e..8e87d71f22 100644
--- a/engines/ags/engine/debugging/debugger.h
+++ b/engines/ags/engine/debugging/debugger.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_DEBUGGING_DEBUGGER_H
 #define AGS_ENGINE_DEBUGGING_DEBUGGER_H
 
-#include "util/string.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/debugging/dummyagsdebugger.h b/engines/ags/engine/debugging/dummyagsdebugger.h
index 2845e28a9e..cc1158755a 100644
--- a/engines/ags/engine/debugging/dummyagsdebugger.h
+++ b/engines/ags/engine/debugging/dummyagsdebugger.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_DEBUGGING_DUMMYAGSDEBUGGER_H
 #define AGS_ENGINE_DEBUGGING_DUMMYAGSDEBUGGER_H
 
-#include "debug/debugger.h"
+#include "ags/shared/debug/debugger.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/debugging/filebasedagsdebugger.cpp b/engines/ags/engine/debugging/filebasedagsdebugger.cpp
index 891fac1155..c8e6b42022 100644
--- a/engines/ags/engine/debugging/filebasedagsdebugger.cpp
+++ b/engines/ags/engine/debugging/filebasedagsdebugger.cpp
@@ -20,13 +20,15 @@
  *
  */
 
-#include <cstdio>
-#include "debug/filebasedagsdebugger.h"
-#include "ac/file.h"                    // filelength()
-#include "util/stream.h"
-#include "util/textstreamwriter.h"
-#include "util/wgt2allg.h"              // exists()
-#include "platform/base/agsplatformdriver.h"
+//include <cstdio>
+#include "ags/engine/debugging/filebasedagsdebugger.h"
+#include "ags/engine/ac/file.h"                    // filelength()
+#include "ags/shared/util/stream.h"
+#include "ags/shared/util/textstreamwriter.h"
+#include "ags/shared/util/wgt2allg.h"              // exists()
+#include "ags/engine/platform/base/agsplatformdriver.h"
+#include "common/system.h"
+#include "common/savefile.h"
 
 namespace AGS3 {
 
@@ -35,9 +37,21 @@ using AGS::Shared::TextStreamWriter;
 
 const char *SENT_MESSAGE_FILE_NAME = "dbgrecv.tmp";
 
+static bool exists(const char *filename) {
+	Common::InSaveFile *save = g_system->getSavefileManager()->openForLoading(filename);
+	bool result = save != nullptr;
+	delete save;
+
+	return result;
+}
+
+static bool remove(const char *filename) {
+	return g_system->getSavefileManager()->removeSavefile(filename);
+}
+
 bool FileBasedAGSDebugger::Initialize() {
 	if (exists(SENT_MESSAGE_FILE_NAME)) {
-		::remove(SENT_MESSAGE_FILE_NAME);
+		remove(SENT_MESSAGE_FILE_NAME);
 	}
 	return true;
 }
@@ -50,7 +64,7 @@ bool FileBasedAGSDebugger::SendMessageToEditor(const char *message) {
 		platform->YieldCPU();
 	}
 
-	Stream *out = Common::File::CreateFile(SENT_MESSAGE_FILE_NAME);
+	Stream *out = Shared::File::CreateFile(SENT_MESSAGE_FILE_NAME);
 	// CHECKME: originally the file was opened as "wb" for some reason,
 	// which means the message should be written as a binary array;
 	// or shouldn't it?
@@ -64,7 +78,7 @@ bool FileBasedAGSDebugger::IsMessageAvailable() {
 }
 
 char *FileBasedAGSDebugger::GetNextMessage() {
-	Stream *in = Common::File::OpenFileRead("dbgsend.tmp");
+	Stream *in = Shared::File::OpenFileRead("dbgsend.tmp");
 	if (in == nullptr) {
 		// check again, because the editor might have deleted the file in the meantime
 		return nullptr;
diff --git a/engines/ags/engine/debugging/filebasedagsdebugger.h b/engines/ags/engine/debugging/filebasedagsdebugger.h
index 3ba6b4acf7..eae9a7aa91 100644
--- a/engines/ags/engine/debugging/filebasedagsdebugger.h
+++ b/engines/ags/engine/debugging/filebasedagsdebugger.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_DEBUGGING_FILEBASEDAGSDEBUGGER_H
 #define AGS_ENGINE_DEBUGGING_FILEBASEDAGSDEBUGGER_H
 
-#include "debug/agseditordebugger.h"
+#include "ags/engine/debugging/agseditordebugger.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/debugging/logfile.cpp b/engines/ags/engine/debugging/logfile.cpp
index 6e237e6f48..2117fae27c 100644
--- a/engines/ags/engine/debugging/logfile.cpp
+++ b/engines/ags/engine/debugging/logfile.cpp
@@ -20,10 +20,10 @@
  *
  */
 
-#include <string.h>
-#include "debug/logfile.h"
-#include "util/file.h"
-#include "util/stream.h"
+//include <string.h>
+#include "ags/engine/debugging/logfile.h"
+#include "ags/shared/util/file.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 namespace AGS {
@@ -39,8 +39,8 @@ void LogFile::PrintMessage(const DebugMessage &msg) {
 	if (!_file.get()) {
 		if (_filePath.IsEmpty())
 			return;
-		_file.reset(File::OpenFile(_filePath, _openMode == kLogFile_Append ? Common::kFile_Create : Common::kFile_CreateAlways,
-			Common::kFile_Write));
+		_file.reset(File::OpenFile(_filePath, _openMode == kLogFile_Append ? Shared::kFile_Create : Shared::kFile_CreateAlways,
+			Shared::kFile_Write));
 		if (!_file) {
 			Debug::Printf("Unable to write log to '%s'.", _filePath.GetCStr());
 			_filePath = "";
@@ -69,8 +69,8 @@ bool LogFile::OpenFile(const String &file_path, OpenMode open_mode) {
 		return File::TestWriteFile(_filePath);
 	} else {
 		_file.reset(File::OpenFile(file_path,
-			open_mode == kLogFile_Append ? Common::kFile_Create : Common::kFile_CreateAlways,
-			Common::kFile_Write));
+			open_mode == kLogFile_Append ? Shared::kFile_Create : Shared::kFile_CreateAlways,
+			Shared::kFile_Write));
 		return _file.get() != nullptr;
 	}
 }
diff --git a/engines/ags/engine/debugging/logfile.h b/engines/ags/engine/debugging/logfile.h
index 45298067d1..18a4356342 100644
--- a/engines/ags/engine/debugging/logfile.h
+++ b/engines/ags/engine/debugging/logfile.h
@@ -35,8 +35,8 @@
 #ifndef AGS_ENGINE_DEBUGGING_LOGFILE_H
 #define AGS_ENGINE_DEBUGGING_LOGFILE_H
 
-#include <memory>
-#include "debug/outputhandler.h"
+#include "ags/std/memory.h"
+#include "ags/shared/debugging/outputhandler.h"
 
 namespace AGS3 {
 namespace AGS {
@@ -47,9 +47,9 @@ class Stream;
 
 namespace Engine {
 
-using Common::DebugMessage;
-using Common::Stream;
-using Common::String;
+using Shared::DebugMessage;
+using Shared::Stream;
+using Shared::String;
 
 class LogFile : public AGS::Shared::IOutputHandler {
 public:
@@ -62,7 +62,7 @@ public:
 public:
 	LogFile();
 
-	void PrintMessage(const Common::DebugMessage &msg) override;
+	void PrintMessage(const Shared::DebugMessage &msg) override;
 
 	// Open file using given file path, optionally appending if one exists
 	//
diff --git a/engines/ags/engine/debugging/messagebuffer.cpp b/engines/ags/engine/debugging/messagebuffer.cpp
index 24fe07705d..d946c2a2af 100644
--- a/engines/ags/engine/debugging/messagebuffer.cpp
+++ b/engines/ags/engine/debugging/messagebuffer.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "debug/debugmanager.h"
-#include "debug/messagebuffer.h"
+#include "ags/shared/debugging/debugmanager.h"
+#include "ags/engine/debugging/messagebuffer.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/debugging/messagebuffer.h b/engines/ags/engine/debugging/messagebuffer.h
index 4c5d822e3e..57016fe611 100644
--- a/engines/ags/engine/debugging/messagebuffer.h
+++ b/engines/ags/engine/debugging/messagebuffer.h
@@ -31,15 +31,15 @@
 #ifndef AGS_ENGINE_DEBUGGING_MESSAGEBUFFER_H
 #define AGS_ENGINE_DEBUGGING_MESSAGEBUFFER_H
 
-#include <vector>
-#include "debug/outputhandler.h"
+#include "ags/std/vector.h"
+#include "ags/shared/debugging/outputhandler.h"
 
 namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
-using Common::String;
-using Common::DebugMessage;
+using Shared::String;
+using Shared::DebugMessage;
 
 class MessageBuffer : public AGS::Shared::IOutputHandler {
 public:
diff --git a/engines/ags/engine/device/mousew32.cpp b/engines/ags/engine/device/mousew32.cpp
index 7192299bae..5544601fd8 100644
--- a/engines/ags/engine/device/mousew32.cpp
+++ b/engines/ags/engine/device/mousew32.cpp
@@ -31,33 +31,33 @@
 //
 //=============================================================================
 
-#include "core/platform.h"
+#include "ags/shared/core/platform.h"
 
 #define AGS_SIMULATE_RIGHT_CLICK (AGS_PLATFORM_OS_MACOS)
 
 #if AGS_PLATFORM_OS_WINDOWS
-#include <dos.h>
-#include <conio.h>
-#include <process.h>
+//include <dos.h>
+//include <conio.h>
+//include <process.h>
 #endif
 
-#include "util/wgt2allg.h"
+#include "ags/shared/util/wgt2allg.h"
 
 #ifndef TRUE
 #define TRUE 1
 #define FALSE 0
 #endif
 
-#include "ac/gamestate.h"
-#include "debug/out.h"
-#include "device/mousew32.h"
-#include "gfx/bitmap.h"
-#include "gfx/gfx_util.h"
-#include "main/graphics_mode.h"
-#include "platform/base/agsplatformdriver.h"
-#include "util/math.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/device/mousew32.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/gfx/gfx_util.h"
+#include "ags/shared/main/graphics_mode.h"
+#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/shared/util/math.h"
 #if AGS_SIMULATE_RIGHT_CLICK
-#include "ac/sys_events.h" // j for ags_iskeypressed
+#include "ags/shared/ac/sys_events.h" // j for ags_iskeypressed
 #endif
 
 namespace AGS3 {
diff --git a/engines/ags/engine/device/mousew32.h b/engines/ags/engine/device/mousew32.h
index 128782ea04..6662320676 100644
--- a/engines/ags/engine/device/mousew32.h
+++ b/engines/ags/engine/device/mousew32.h
@@ -31,11 +31,11 @@
 //
 //=============================================================================
 
-#include "util/geometry.h"
+#include "ags/shared/util/geometry.h"
 
 #define MAXCURSORS 20
 
-#include "util/geometry.h"
+#include "ags/shared/util/geometry.h"
 
 namespace AGS3 {
 namespace AGS {
@@ -101,6 +101,6 @@ extern int hotx, hoty;
 extern int disable_mgetgraphpos;
 extern char currentcursor;
 
-extern Common::Bitmap *mousecurs[MAXCURSORS];
+extern Shared::Bitmap *mousecurs[MAXCURSORS];
 
 } // namespace AGS3
diff --git a/engines/ags/engine/font/fonts_engine.cpp b/engines/ags/engine/font/fonts_engine.cpp
index 2b77e3d496..b52947b26c 100644
--- a/engines/ags/engine/font/fonts_engine.cpp
+++ b/engines/ags/engine/font/fonts_engine.cpp
@@ -26,8 +26,8 @@
 //
 //=============================================================================
 
-#include <alfont.h>
-#include "ac/gamesetupstruct.h"
+//include <alfont.h>
+#include "ags/shared/ac/gamesetupstruct.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/game/game_init.cpp b/engines/ags/engine/game/game_init.cpp
index 3df894addc..3836f46af7 100644
--- a/engines/ags/engine/game/game_init.cpp
+++ b/engines/ags/engine/game/game_init.cpp
@@ -20,36 +20,36 @@
  *
  */
 
-#include "ac/character.h"
-#include "ac/charactercache.h"
-#include "ac/dialog.h"
-#include "ac/draw.h"
-#include "ac/file.h"
-#include "ac/game.h"
-#include "ac/gamesetup.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/gui.h"
-#include "ac/movelist.h"
-#include "ac/dynobj/all_dynamicclasses.h"
-#include "ac/dynobj/all_scriptclasses.h"
-#include "ac/statobj/agsstaticobject.h"
-#include "ac/statobj/staticarray.h"
-#include "debug/debug_log.h"
-#include "debug/out.h"
-#include "font/agsfontrenderer.h"
-#include "font/fonts.h"
-#include "game/game_init.h"
-#include "gfx/bitmap.h"
-#include "gfx/ddb.h"
-#include "gui/guilabel.h"
-#include "plugin/plugin_engine.h"
-#include "script/cc_error.h"
-#include "script/exports.h"
-#include "script/script.h"
-#include "script/script_runtime.h"
-#include "util/string_utils.h"
-#include "media/audio/audio_system.h"
+#include "ags/shared/ac/character.h"
+#include "ags/shared/ac/charactercache.h"
+#include "ags/shared/ac/dialog.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/file.h"
+#include "ags/shared/ac/game.h"
+#include "ags/shared/ac/gamesetup.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/gui.h"
+#include "ags/shared/ac/movelist.h"
+#include "ags/shared/ac/dynobj/all_dynamicclasses.h"
+#include "ags/shared/ac/dynobj/all_scriptclasses.h"
+#include "ags/shared/ac/statobj/agsstaticobject.h"
+#include "ags/shared/ac/statobj/staticarray.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/font/agsfontrenderer.h"
+#include "ags/shared/font/fonts.h"
+#include "ags/shared/game/game_init.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/gfx/ddb.h"
+#include "ags/shared/gui/guilabel.h"
+#include "ags/shared/plugin/plugin_engine.h"
+#include "ags/shared/script/cc_error.h"
+#include "ags/shared/script/exports.h"
+#include "ags/shared/script/script.h"
+#include "ags/shared/script/script_runtime.h"
+#include "ags/shared/util/string_utils.h"
+#include "ags/shared/media/audio/audio_system.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/game/game_init.h b/engines/ags/engine/game/game_init.h
index ec905d981e..0591548fbb 100644
--- a/engines/ags/engine/game/game_init.h
+++ b/engines/ags/engine/game/game_init.h
@@ -30,8 +30,8 @@
 #ifndef AGS_ENGINE_GAME_GAMEINIT_H
 #define AGS_ENGINE_GAME_GAMEINIT_H
 
-#include "game/main_game_file.h"
-#include "util/string.h"
+#include "ags/shared/game/main_game_file.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/game/savegame.cpp b/engines/ags/engine/game/savegame.cpp
index 1b55a38210..cc8f5bbd88 100644
--- a/engines/ags/engine/game/savegame.cpp
+++ b/engines/ags/engine/game/savegame.cpp
@@ -20,47 +20,47 @@
  *
  */
 
-#include "ac/character.h"
-#include "ac/common.h"
-#include "ac/draw.h"
-#include "ac/dynamicsprite.h"
-#include "ac/event.h"
-#include "ac/game.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/gamesetup.h"
-#include "ac/global_audio.h"
-#include "ac/global_character.h"
-#include "ac/gui.h"
-#include "ac/mouse.h"
-#include "ac/overlay.h"
-#include "ac/region.h"
-#include "ac/richgamemedia.h"
-#include "ac/room.h"
-#include "ac/roomstatus.h"
-#include "ac/spritecache.h"
-#include "ac/system.h"
-#include "ac/timer.h"
-#include "debug/out.h"
-#include "device/mousew32.h"
-#include "gfx/bitmap.h"
-#include "gfx/ddb.h"
-#include "gfx/graphicsdriver.h"
-#include "game/savegame.h"
-#include "game/savegame_components.h"
-#include "game/savegame_internal.h"
-#include "main/engine.h"
-#include "main/main.h"
-#include "platform/base/agsplatformdriver.h"
-#include "plugin/agsplugin.h"
-#include "plugin/plugin_engine.h"
-#include "script/script.h"
-#include "script/cc_error.h"
-#include "util/alignedstream.h"
-#include "util/file.h"
-#include "util/stream.h"
-#include "util/string_utils.h"
-#include "media/audio/audio_system.h"
+#include "ags/shared/ac/character.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/dynamicsprite.h"
+#include "ags/shared/ac/event.h"
+#include "ags/shared/ac/game.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/gamesetup.h"
+#include "ags/shared/ac/global_audio.h"
+#include "ags/shared/ac/global_character.h"
+#include "ags/shared/ac/gui.h"
+#include "ags/shared/ac/mouse.h"
+#include "ags/shared/ac/overlay.h"
+#include "ags/shared/ac/region.h"
+#include "ags/shared/ac/richgamemedia.h"
+#include "ags/shared/ac/room.h"
+#include "ags/shared/ac/roomstatus.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/ac/system.h"
+#include "ags/shared/ac/timer.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/device/mousew32.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/gfx/ddb.h"
+#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/shared/game/savegame.h"
+#include "ags/shared/game/savegame_components.h"
+#include "ags/shared/game/savegame_internal.h"
+#include "ags/shared/main/engine.h"
+#include "ags/shared/main/main.h"
+#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/shared/plugin/agsplugin.h"
+#include "ags/shared/plugin/plugin_engine.h"
+#include "ags/shared/script/script.h"
+#include "ags/shared/script/cc_error.h"
+#include "ags/shared/util/alignedstream.h"
+#include "ags/shared/util/file.h"
+#include "ags/shared/util/stream.h"
+#include "ags/shared/util/string_utils.h"
+#include "ags/shared/media/audio/audio_system.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/game/savegame.h b/engines/ags/engine/game/savegame.h
index 1445d07907..53b7d355d2 100644
--- a/engines/ags/engine/game/savegame.h
+++ b/engines/ags/engine/game/savegame.h
@@ -23,10 +23,10 @@
 #ifndef AGS_ENGINE_GAME_SAVEGAME_H
 #define AGS_ENGINE_GAME_SAVEGAME_H
 
-#include <memory>
-#include "ac/game_version.h"
-#include "util/error.h"
-#include "util/version.h"
+#include "ags/std/memory.h"
+#include "ags/shared/ac/game_version.h"
+#include "ags/shared/util/error.h"
+#include "ags/shared/util/version.h"
 
 namespace AGS3 {
 
@@ -38,12 +38,12 @@ class Stream;
 
 namespace Engine {
 
-using Common::Bitmap;
-using Common::ErrorHandle;
-using Common::TypedCodeError;
-using Common::Stream;
-using Common::String;
-using Common::Version;
+using Shared::Bitmap;
+using Shared::ErrorHandle;
+using Shared::TypedCodeError;
+using Shared::Stream;
+using Shared::String;
+using Shared::Version;
 
 typedef std::shared_ptr<Stream> PStream;
 
diff --git a/engines/ags/engine/game/savegame_components.cpp b/engines/ags/engine/game/savegame_components.cpp
index c0bef7a568..1e558819f9 100644
--- a/engines/ags/engine/game/savegame_components.cpp
+++ b/engines/ags/engine/game/savegame_components.cpp
@@ -20,45 +20,45 @@
  *
  */
 
-#include <map>
-
-#include "ac/audiocliptype.h"
-#include "ac/character.h"
-#include "ac/common.h"
-#include "ac/dialogtopic.h"
-#include "ac/draw.h"
-#include "ac/dynamicsprite.h"
-#include "ac/game.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/gui.h"
-#include "ac/mouse.h"
-#include "ac/movelist.h"
-#include "ac/overlay.h"
-#include "ac/roomstatus.h"
-#include "ac/screenoverlay.h"
-#include "ac/spritecache.h"
-#include "ac/view.h"
-#include "ac/system.h"
-#include "ac/dynobj/cc_serializer.h"
-#include "debug/out.h"
-#include "game/savegame_components.h"
-#include "game/savegame_internal.h"
-#include "gfx/bitmap.h"
-#include "gui/animatingguibutton.h"
-#include "gui/guibutton.h"
-#include "gui/guiinv.h"
-#include "gui/guilabel.h"
-#include "gui/guilistbox.h"
-#include "gui/guimain.h"
-#include "gui/guislider.h"
-#include "gui/guitextbox.h"
-#include "plugin/agsplugin.h"
-#include "plugin/plugin_engine.h"
-#include "script/cc_error.h"
-#include "script/script.h"
-#include "util/filestream.h" // TODO: needed only because plugins expect file handle
-#include "media/audio/audio_system.h"
+//include <map>
+
+#include "ags/shared/ac/audiocliptype.h"
+#include "ags/shared/ac/character.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/dialogtopic.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/dynamicsprite.h"
+#include "ags/shared/ac/game.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/gui.h"
+#include "ags/shared/ac/mouse.h"
+#include "ags/shared/ac/movelist.h"
+#include "ags/shared/ac/overlay.h"
+#include "ags/shared/ac/roomstatus.h"
+#include "ags/shared/ac/screenoverlay.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/ac/view.h"
+#include "ags/shared/ac/system.h"
+#include "ags/shared/ac/dynobj/cc_serializer.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/game/savegame_components.h"
+#include "ags/shared/game/savegame_internal.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/gui/animatingguibutton.h"
+#include "ags/shared/gui/guibutton.h"
+#include "ags/shared/gui/guiinv.h"
+#include "ags/shared/gui/guilabel.h"
+#include "ags/shared/gui/guilistbox.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/gui/guislider.h"
+#include "ags/shared/gui/guitextbox.h"
+#include "ags/shared/plugin/agsplugin.h"
+#include "ags/shared/plugin/plugin_engine.h"
+#include "ags/shared/script/cc_error.h"
+#include "ags/shared/script/script.h"
+#include "ags/shared/util/filestream.h" // TODO: needed only because plugins expect file handle
+#include "ags/shared/media/audio/audio_system.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/game/savegame_components.h b/engines/ags/engine/game/savegame_components.h
index 009516e505..18cfb46a6f 100644
--- a/engines/ags/engine/game/savegame_components.h
+++ b/engines/ags/engine/game/savegame_components.h
@@ -23,8 +23,8 @@
 #ifndef AGS_ENGINE_GAME_SAVEGAMECOMPONENTS_H
 #define AGS_ENGINE_GAME_SAVEGAMECOMPONENTS_H
 
-#include "game/savegame.h"
-#include "util/stream.h"
+#include "ags/shared/game/savegame.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 namespace AGS {
@@ -35,7 +35,7 @@ struct Interaction;
 
 namespace Engine {
 
-using Common::Stream;
+using Shared::Stream;
 typedef std::shared_ptr<Stream> PStream;
 
 struct PreservedParams;
diff --git a/engines/ags/engine/game/savegame_internal.h b/engines/ags/engine/game/savegame_internal.h
index 11cdd70762..713c662d9d 100644
--- a/engines/ags/engine/game/savegame_internal.h
+++ b/engines/ags/engine/game/savegame_internal.h
@@ -23,11 +23,11 @@
 #ifndef AGS_ENGINE_GAME_SAVEGAMEINTERNAL_H
 #define AGS_ENGINE_GAME_SAVEGAMEINTERNAL_H
 
-#include <memory>
-#include <vector>
-#include "ac/common_defines.h"
-#include "gfx/bitmap.h"
-#include "media/audio/audiodefines.h"
+#include "ags/std/memory.h"
+#include "ags/std/vector.h"
+#include "ags/shared/ac/common_defines.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/media/audio/audiodefines.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/game/viewport.cpp b/engines/ags/engine/game/viewport.cpp
index ddbed3d8be..cc5415f8b3 100644
--- a/engines/ags/engine/game/viewport.cpp
+++ b/engines/ags/engine/game/viewport.cpp
@@ -20,11 +20,11 @@
  *
  */
 
-#include "ac/draw.h"
-#include "ac/gamestate.h"
-#include "debug/debug_log.h"
-#include "game/roomstruct.h"
-#include "game/viewport.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/game/roomstruct.h"
+#include "ags/shared/game/viewport.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/game/viewport.h b/engines/ags/engine/game/viewport.h
index f39040cfdb..3834dd9e0a 100644
--- a/engines/ags/engine/game/viewport.h
+++ b/engines/ags/engine/game/viewport.h
@@ -29,10 +29,10 @@
 #ifndef AGS_ENGINE_GAME_VIEWPORT_H
 #define AGS_ENGINE_GAME_VIEWPORT_H
 
-#include <memory>
-#include <vector>
-#include "util/geometry.h"
-#include "util/scaling.h"
+#include "ags/std/memory.h"
+#include "ags/std/vector.h"
+#include "ags/shared/util/geometry.h"
+#include "ags/engine/util/scaling.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gfx/ali3dogl.cpp b/engines/ags/engine/gfx/ali3dogl.cpp
index 5b275a592b..06355a0fa6 100644
--- a/engines/ags/engine/gfx/ali3dogl.cpp
+++ b/engines/ags/engine/gfx/ali3dogl.cpp
@@ -20,20 +20,20 @@
  *
  */
 
-#include "core/platform.h"
+#include "ags/shared/core/platform.h"
 
 #if AGS_PLATFORM_OS_WINDOWS || AGS_PLATFORM_OS_ANDROID || AGS_PLATFORM_OS_IOS || AGS_PLATFORM_OS_LINUX
 
-#include <algorithm>
-#include "gfx/ali3dexception.h"
-#include "gfx/ali3dogl.h"
-#include "gfx/gfxfilter_ogl.h"
-#include "gfx/gfxfilter_aaogl.h"
-#include "gfx/gfx_util.h"
-#include "main/main_allegro.h"
-#include "platform/base/agsplatformdriver.h"
-#include "util/math.h"
-#include "ac/timer.h"
+//include <algorithm>
+#include "ags/shared/gfx/ali3dexception.h"
+#include "ags/shared/gfx/ali3dogl.h"
+#include "ags/shared/gfx/gfxfilter_ogl.h"
+#include "ags/shared/gfx/gfxfilter_aaogl.h"
+#include "ags/shared/gfx/gfx_util.h"
+#include "ags/shared/main/main_allegro.h"
+#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/shared/util/math.h"
+#include "ags/shared/ac/timer.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gfx/ali3dogl.h b/engines/ags/engine/gfx/ali3dogl.h
index 171817bcdb..fde7c439aa 100644
--- a/engines/ags/engine/gfx/ali3dogl.h
+++ b/engines/ags/engine/gfx/ali3dogl.h
@@ -29,15 +29,15 @@
 #ifndef AGS_ENGINE_GFX_ALI3DOGL_H
 #define AGS_ENGINE_GFX_ALI3DOGL_H
 
-#include <memory>
-#include "gfx/bitmap.h"
-#include "gfx/ddb.h"
-#include "gfx/gfxdriverfactorybase.h"
-#include "gfx/gfxdriverbase.h"
-#include "util/string.h"
-#include "util/version.h"
+#include "ags/std/memory.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/gfx/ddb.h"
+#include "ags/shared/gfx/gfxdriverfactorybase.h"
+#include "ags/shared/gfx/gfxdriverbase.h"
+#include "ags/shared/util/string.h"
+#include "ags/shared/util/version.h"
 
-#include "ogl_headers.h"
+#include "ags/shared/ogl_headers.h"
 
 namespace AGS3 {
 namespace AGS {
@@ -45,8 +45,8 @@ namespace Engine {
 
 namespace OGL {
 
-using Common::Bitmap;
-using Common::String;
+using Shared::Bitmap;
+using Shared::String;
 using Common::Version;
 
 typedef struct _OGLVECTOR {
diff --git a/engines/ags/engine/gfx/ali3dsw.cpp b/engines/ags/engine/gfx/ali3dsw.cpp
index 85b121ced9..ec380f7c12 100644
--- a/engines/ags/engine/gfx/ali3dsw.cpp
+++ b/engines/ags/engine/gfx/ali3dsw.cpp
@@ -26,16 +26,16 @@
 //
 //=============================================================================
 
-#include "gfx/ali3dsw.h"
+#include "ags/shared/gfx/ali3dsw.h"
 
-#include "core/platform.h"
-#include "gfx/ali3dexception.h"
-#include "gfx/gfxfilter_allegro.h"
-#include "gfx/gfxfilter_hqx.h"
-#include "gfx/gfx_util.h"
-#include "main/main_allegro.h"
-#include "platform/base/agsplatformdriver.h"
-#include "ac/timer.h"
+#include "ags/shared/core/platform.h"
+#include "ags/shared/gfx/ali3dexception.h"
+#include "ags/shared/gfx/gfxfilter_allegro.h"
+#include "ags/shared/gfx/gfxfilter_hqx.h"
+#include "ags/shared/gfx/gfx_util.h"
+#include "ags/shared/main/main_allegro.h"
+#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/shared/ac/timer.h"
 
 namespace AGS3 {
 
@@ -449,7 +449,7 @@ void ALSoftwareGraphicsDriver::RenderToBackBuffer() {
 	ClearDrawLists();
 }
 
-void ALSoftwareGraphicsDriver::RenderSpriteBatch(const ALSpriteBatch &batch, Common::Bitmap *surface, int surf_offx, int surf_offy) {
+void ALSoftwareGraphicsDriver::RenderSpriteBatch(const ALSpriteBatch &batch, Shared::Bitmap *surface, int surf_offx, int surf_offy) {
 	const std::vector<ALDrawListEntry> &drawlist = batch.List;
 	for (size_t i = 0; i < drawlist.size(); i++) {
 		if (drawlist[i].bitmap == nullptr) {
diff --git a/engines/ags/engine/gfx/ali3dsw.h b/engines/ags/engine/gfx/ali3dsw.h
index 54bfc93d90..91b192782e 100644
--- a/engines/ags/engine/gfx/ali3dsw.h
+++ b/engines/ags/engine/gfx/ali3dsw.h
@@ -29,22 +29,22 @@
 #ifndef AGS_ENGINE_GFX_ALI3DSW_H
 #define AGS_ENGINE_GFX_ALI3DSW_H
 
-#include <memory>
+#include "ags/std/memory.h"
 
-#include "core/platform.h"
+#include "ags/shared/core/platform.h"
 #define AGS_DDRAW_GAMMA_CONTROL (AGS_PLATFORM_OS_WINDOWS)
 
 #include "ags/lib/allegro.h"
 
 #if AGS_DDRAW_GAMMA_CONTROL
-#include <winalleg.h>
-#include <ddraw.h>
+//include <winalleg.h>
+//include <ddraw.h>
 #endif
 
-#include "gfx/bitmap.h"
-#include "gfx/ddb.h"
-#include "gfx/gfxdriverfactorybase.h"
-#include "gfx/gfxdriverbase.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/gfx/ddb.h"
+#include "ags/shared/gfx/gfxdriverfactorybase.h"
+#include "ags/shared/gfx/gfxdriverbase.h"
 
 namespace AGS3 {
 namespace AGS {
@@ -263,7 +263,7 @@ private:
 	// Unset parameters and release resources related to the display mode
 	void ReleaseDisplayMode();
 	// Renders single sprite batch on the precreated surface
-	void RenderSpriteBatch(const ALSpriteBatch &batch, Common::Bitmap *surface, int surf_offx, int surf_offy);
+	void RenderSpriteBatch(const ALSpriteBatch &batch, Shared::Bitmap *surface, int surf_offx, int surf_offy);
 
 	void highcolor_fade_in(Bitmap *vs, void(*draw_callback)(), int offx, int offy, int speed, int targetColourRed, int targetColourGreen, int targetColourBlue);
 	void highcolor_fade_out(Bitmap *vs, void(*draw_callback)(), int offx, int offy, int speed, int targetColourRed, int targetColourGreen, int targetColourBlue);
diff --git a/engines/ags/engine/gfx/blender.cpp b/engines/ags/engine/gfx/blender.cpp
index 736768836e..e4eb457e7a 100644
--- a/engines/ags/engine/gfx/blender.cpp
+++ b/engines/ags/engine/gfx/blender.cpp
@@ -20,9 +20,9 @@
  *
  */
 
-#include "core/types.h"
-#include "gfx/blender.h"
-#include "util/wgt2allg.h"
+#include "ags/shared/core/types.h"
+#include "ags/shared/gfx/blender.h"
+#include "ags/shared/util/wgt2allg.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gfx/color_engine.cpp b/engines/ags/engine/gfx/color_engine.cpp
index ae3ec5e192..4726d0f677 100644
--- a/engines/ags/engine/gfx/color_engine.cpp
+++ b/engines/ags/engine/gfx/color_engine.cpp
@@ -26,10 +26,10 @@
 //
 //=============================================================================
 
-#include "core/platform.h"
+#include "ags/shared/core/platform.h"
 
-#include "util/wgt2allg.h"
-#include "gfx/bitmap.h"
+#include "ags/shared/util/wgt2allg.h"
+#include "ags/shared/gfx/bitmap.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gfx/gfx_util.cpp b/engines/ags/engine/gfx/gfx_util.cpp
index dd309c0cef..aadbb940a4 100644
--- a/engines/ags/engine/gfx/gfx_util.cpp
+++ b/engines/ags/engine/gfx/gfx_util.cpp
@@ -20,9 +20,9 @@
  *
  */
 
-#include "core/platform.h"
-#include "gfx/gfx_util.h"
-#include "gfx/blender.h"
+#include "ags/shared/core/platform.h"
+#include "ags/shared/gfx/gfx_util.h"
+#include "ags/shared/gfx/blender.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gfx/gfx_util.h b/engines/ags/engine/gfx/gfx_util.h
index e9b9f17199..7e8f1e6f03 100644
--- a/engines/ags/engine/gfx/gfx_util.h
+++ b/engines/ags/engine/gfx/gfx_util.h
@@ -35,14 +35,14 @@
 #ifndef AGS_ENGINE_GFX_GFXUTIL_H
 #define AGS_ENGINE_GFX_GFXUTIL_H
 
-#include "gfx/bitmap.h"
-#include "gfx/gfx_def.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/gfx/gfx_def.h"
 
 namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
-using Common::Bitmap;
+using Shared::Bitmap;
 
 namespace GfxUtil {
 // Creates a COPY of the source bitmap, converted to the given format.
diff --git a/engines/ags/engine/gfx/gfxdefines.h b/engines/ags/engine/gfx/gfxdefines.h
index cbb4fab496..0f2e2cf458 100644
--- a/engines/ags/engine/gfx/gfxdefines.h
+++ b/engines/ags/engine/gfx/gfxdefines.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_GFX_GFXDEFINES_H
 #define AGS_ENGINE_GFX_GFXDEFINES_H
 
-#include "core/types.h"
+#include "ags/shared/core/types.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/gfxdriverbase.cpp b/engines/ags/engine/gfx/gfxdriverbase.cpp
index 7de8c33ed2..d1dd038ab8 100644
--- a/engines/ags/engine/gfx/gfxdriverbase.cpp
+++ b/engines/ags/engine/gfx/gfxdriverbase.cpp
@@ -20,12 +20,12 @@
  *
  */
 
-#include "util/wgt2allg.h"
-#include "gfx/ali3dexception.h"
-#include "gfx/bitmap.h"
-#include "gfx/gfxfilter.h"
-#include "gfx/gfxdriverbase.h"
-#include "gfx/gfx_util.h"
+#include "ags/shared/util/wgt2allg.h"
+#include "ags/shared/gfx/ali3dexception.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/gfx/gfxfilter.h"
+#include "ags/shared/gfx/gfxdriverbase.h"
+#include "ags/shared/gfx/gfx_util.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gfx/gfxdriverbase.h b/engines/ags/engine/gfx/gfxdriverbase.h
index 14012a9577..b845de3b4a 100644
--- a/engines/ags/engine/gfx/gfxdriverbase.h
+++ b/engines/ags/engine/gfx/gfxdriverbase.h
@@ -29,16 +29,16 @@
 #ifndef AGS_ENGINE_GFX_GFXDRIVERBASE_H
 #define AGS_ENGINE_GFX_GFXDRIVERBASE_H
 
-#include <vector>
-#include "gfx/ddb.h"
-#include "gfx/graphicsdriver.h"
-#include "util/scaling.h"
+#include "ags/std/vector.h"
+#include "ags/shared/gfx/ddb.h"
+#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/shared/util/scaling.h"
 
 namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
-using Common::Bitmap;
+using Shared::Bitmap;
 
 // Sprite batch, defines viewport and an optional model transformation for the list of sprites
 struct SpriteBatchDesc {
diff --git a/engines/ags/engine/gfx/gfxdriverfactory.cpp b/engines/ags/engine/gfx/gfxdriverfactory.cpp
index d2469785df..00dcbf5211 100644
--- a/engines/ags/engine/gfx/gfxdriverfactory.cpp
+++ b/engines/ags/engine/gfx/gfxdriverfactory.cpp
@@ -20,27 +20,27 @@
  *
  */
 
-#include "gfx/gfxdriverfactory.h"
+#include "ags/shared/gfx/gfxdriverfactory.h"
 
-#include "core/platform.h"
+#include "ags/shared/core/platform.h"
 
 #define AGS_HAS_DIRECT3D (AGS_PLATFORM_OS_WINDOWS)
 #define AGS_HAS_OPENGL (AGS_PLATFORM_OS_WINDOWS || AGS_PLATFORM_OS_ANDROID || AGS_PLATFORM_OS_IOS || AGS_PLATFORM_OS_LINUX)
 
-#include "gfx/ali3dsw.h"
-#include "gfx/gfxfilter_allegro.h"
+#include "ags/shared/gfx/ali3dsw.h"
+#include "ags/shared/gfx/gfxfilter_allegro.h"
 
 #if AGS_HAS_OPENGL
-#include "gfx/ali3dogl.h"
-#include "gfx/gfxfilter_ogl.h"
+#include "ags/shared/gfx/ali3dogl.h"
+#include "ags/shared/gfx/gfxfilter_ogl.h"
 #endif
 
 #if AGS_HAS_DIRECT3D
-#include "platform/windows/gfx/ali3dd3d.h"
-#include "gfx/gfxfilter_d3d.h"
+#include "ags/shared/platform/windows/gfx/ali3dd3d.h"
+#include "ags/shared/gfx/gfxfilter_d3d.h"
 #endif
 
-#include "main/main_allegro.h"
+#include "ags/shared/main/main_allegro.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/gfxdriverfactory.h b/engines/ags/engine/gfx/gfxdriverfactory.h
index eb6bae49ee..b28560d765 100644
--- a/engines/ags/engine/gfx/gfxdriverfactory.h
+++ b/engines/ags/engine/gfx/gfxdriverfactory.h
@@ -33,16 +33,16 @@
 #ifndef AGS_ENGINE_GFX_GFXDRIVERFACTORY_H
 #define AGS_ENGINE_GFX_GFXDRIVERFACTORY_H
 
-#include <memory>
-#include "util/string.h"
-#include "util/string_types.h"
+#include "ags/std/memory.h"
+#include "ags/shared/util/string.h"
+#include "ags/shared/util/string_types.h"
 
 namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
-using Common::String;
-using Common::StringV;
+using Shared::String;
+using Shared::StringV;
 class IGraphicsDriver;
 class IGfxFilter;
 struct GfxFilterInfo;
diff --git a/engines/ags/engine/gfx/gfxdriverfactorybase.h b/engines/ags/engine/gfx/gfxdriverfactorybase.h
index 337901ca80..5424ea7c89 100644
--- a/engines/ags/engine/gfx/gfxdriverfactorybase.h
+++ b/engines/ags/engine/gfx/gfxdriverfactorybase.h
@@ -33,9 +33,9 @@
 #ifndef AGS_ENGINE_GFX_GFXDRIVERFACTORYBASE_H
 #define AGS_ENGINE_GFX_GFXDRIVERFACTORYBASE_H
 
-#include <vector>
-#include "gfx/gfxdriverfactory.h"
-#include "gfx/gfxfilter.h"
+#include "ags/std/vector.h"
+#include "ags/shared/gfx/gfxdriverfactory.h"
+#include "ags/shared/gfx/gfxfilter.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/gfxfilter.h b/engines/ags/engine/gfx/gfxfilter.h
index a8fc9b4da6..7b0f636215 100644
--- a/engines/ags/engine/gfx/gfxfilter.h
+++ b/engines/ags/engine/gfx/gfxfilter.h
@@ -29,15 +29,15 @@
 #ifndef AGS_ENGINE_GFX_GFXFILTER_H
 #define AGS_ENGINE_GFX_GFXFILTER_H
 
-#include <memory>
-#include "util/geometry.h"
-#include "util/string.h"
+#include "ags/std/memory.h"
+#include "ags/shared/util/geometry.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
-using Common::String;
+using Shared::String;
 
 struct GfxFilterInfo {
 	String   Id;
diff --git a/engines/ags/engine/gfx/gfxfilter_aad3d.cpp b/engines/ags/engine/gfx/gfxfilter_aad3d.cpp
index bdbde84b75..eebfbbbed5 100644
--- a/engines/ags/engine/gfx/gfxfilter_aad3d.cpp
+++ b/engines/ags/engine/gfx/gfxfilter_aad3d.cpp
@@ -20,12 +20,12 @@
  *
  */
 
-#include "core/platform.h"
-#include "stdio.h"
-#include "gfx/gfxfilter_aad3d.h"
+#include "ags/shared/core/platform.h"
+#include "ags/shared/stdio.h"
+#include "ags/shared/gfx/gfxfilter_aad3d.h"
 
 #if AGS_PLATFORM_OS_WINDOWS
-#include <d3d9.h>
+//include <d3d9.h>
 #endif
 
 namespace AGS3 {
diff --git a/engines/ags/engine/gfx/gfxfilter_aad3d.h b/engines/ags/engine/gfx/gfxfilter_aad3d.h
index 84c376ec07..351cfa22b6 100644
--- a/engines/ags/engine/gfx/gfxfilter_aad3d.h
+++ b/engines/ags/engine/gfx/gfxfilter_aad3d.h
@@ -29,7 +29,7 @@
 #ifndef AGS_ENGINE_GFX_AAD3DGFXFILTER_H
 #define AGS_ENGINE_GFX_AAD3DGFXFILTER_H
 
-#include "gfx/gfxfilter_d3d.h"
+#include "ags/shared/gfx/gfxfilter_d3d.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/gfxfilter_aaogl.cpp b/engines/ags/engine/gfx/gfxfilter_aaogl.cpp
index 70d5e869a3..0bec89329c 100644
--- a/engines/ags/engine/gfx/gfxfilter_aaogl.cpp
+++ b/engines/ags/engine/gfx/gfxfilter_aaogl.cpp
@@ -20,12 +20,12 @@
  *
  */
 
-#include "core/platform.h"
+#include "ags/shared/core/platform.h"
 
 #if AGS_PLATFORM_OS_WINDOWS || AGS_PLATFORM_OS_ANDROID || AGS_PLATFORM_OS_IOS || AGS_PLATFORM_OS_LINUX
 
-#include "gfx/gfxfilter_aaogl.h"
-#include "ogl_headers.h"
+#include "ags/shared/gfx/gfxfilter_aaogl.h"
+#include "ags/shared/ogl_headers.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/gfxfilter_aaogl.h b/engines/ags/engine/gfx/gfxfilter_aaogl.h
index 3d77922736..6c40365494 100644
--- a/engines/ags/engine/gfx/gfxfilter_aaogl.h
+++ b/engines/ags/engine/gfx/gfxfilter_aaogl.h
@@ -29,7 +29,7 @@
 #ifndef AGS_ENGINE_GFX_AAOGLGFXFILTER_H
 #define AGS_ENGINE_GFX_AAOGLGFXFILTER_H
 
-#include "gfx/gfxfilter_ogl.h"
+#include "ags/shared/gfx/gfxfilter_ogl.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/gfxfilter_allegro.cpp b/engines/ags/engine/gfx/gfxfilter_allegro.cpp
index 8385ef783d..b1f1a93ed1 100644
--- a/engines/ags/engine/gfx/gfxfilter_allegro.cpp
+++ b/engines/ags/engine/gfx/gfxfilter_allegro.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "gfx/gfxfilter_allegro.h"
+#include "ags/shared/gfx/gfxfilter_allegro.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/gfxfilter_allegro.h b/engines/ags/engine/gfx/gfxfilter_allegro.h
index fe2b856c8b..e0906d41d5 100644
--- a/engines/ags/engine/gfx/gfxfilter_allegro.h
+++ b/engines/ags/engine/gfx/gfxfilter_allegro.h
@@ -29,16 +29,16 @@
 #ifndef AGS_ENGINE_GFX_ALLEGROGFXFILTER_H
 #define AGS_ENGINE_GFX_ALLEGROGFXFILTER_H
 
-#include "gfx/bitmap.h"
-#include "gfx/gfxfilter_scaling.h"
-#include "gfx/gfxdefines.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/gfx/gfxfilter_scaling.h"
+#include "ags/shared/gfx/gfxdefines.h"
 
 namespace AGS3 {
 namespace AGS {
 namespace Engine {
 namespace ALSW {
 
-using Common::Bitmap;
+using Shared::Bitmap;
 
 class AllegroGfxFilter : public ScalingGfxFilter {
 public:
diff --git a/engines/ags/engine/gfx/gfxfilter_d3d.cpp b/engines/ags/engine/gfx/gfxfilter_d3d.cpp
index 8156af57ee..9e4eb302e5 100644
--- a/engines/ags/engine/gfx/gfxfilter_d3d.cpp
+++ b/engines/ags/engine/gfx/gfxfilter_d3d.cpp
@@ -20,10 +20,10 @@
  *
  */
 
-#include "core/platform.h"
-#include "gfx/gfxfilter_d3d.h"
+#include "ags/shared/core/platform.h"
+#include "ags/shared/gfx/gfxfilter_d3d.h"
 #if AGS_PLATFORM_OS_WINDOWS
-#include <d3d9.h>
+//include <d3d9.h>
 #endif
 
 namespace AGS3 {
diff --git a/engines/ags/engine/gfx/gfxfilter_d3d.h b/engines/ags/engine/gfx/gfxfilter_d3d.h
index ead9ae305e..e5cd2b2395 100644
--- a/engines/ags/engine/gfx/gfxfilter_d3d.h
+++ b/engines/ags/engine/gfx/gfxfilter_d3d.h
@@ -29,7 +29,7 @@
 #ifndef AGS_ENGINE_GFX_D3DGFXFILTER_H
 #define AGS_ENGINE_GFX_D3DGFXFILTER_H
 
-#include "gfx/gfxfilter_scaling.h"
+#include "ags/shared/gfx/gfxfilter_scaling.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/gfxfilter_hqx.cpp b/engines/ags/engine/gfx/gfxfilter_hqx.cpp
index 1974779a7c..2acd26f0d4 100644
--- a/engines/ags/engine/gfx/gfxfilter_hqx.cpp
+++ b/engines/ags/engine/gfx/gfxfilter_hqx.cpp
@@ -20,9 +20,9 @@
  *
  */
 
-#include "gfx/bitmap.h"
-#include "gfx/gfxfilter_hqx.h"
-#include "gfx/hq2x3x.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/gfx/gfxfilter_hqx.h"
+#include "ags/shared/gfx/hq2x3x.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/gfxfilter_hqx.h b/engines/ags/engine/gfx/gfxfilter_hqx.h
index 232e180520..8cc897357f 100644
--- a/engines/ags/engine/gfx/gfxfilter_hqx.h
+++ b/engines/ags/engine/gfx/gfxfilter_hqx.h
@@ -29,7 +29,7 @@
 #ifndef AGS_ENGINE_GFX_HQ2XGFXFILTER_H
 #define AGS_ENGINE_GFX_HQ2XGFXFILTER_H
 
-#include "gfx/gfxfilter_allegro.h"
+#include "ags/shared/gfx/gfxfilter_allegro.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/gfxfilter_ogl.cpp b/engines/ags/engine/gfx/gfxfilter_ogl.cpp
index 9d480c0de5..3615d025b1 100644
--- a/engines/ags/engine/gfx/gfxfilter_ogl.cpp
+++ b/engines/ags/engine/gfx/gfxfilter_ogl.cpp
@@ -20,12 +20,12 @@
  *
  */
 
-#include "core/platform.h"
+#include "ags/shared/core/platform.h"
 
 #if AGS_PLATFORM_OS_WINDOWS || AGS_PLATFORM_OS_ANDROID || AGS_PLATFORM_OS_IOS || AGS_PLATFORM_OS_LINUX
 
-#include "gfx/gfxfilter_ogl.h"
-#include "ogl_headers.h"
+#include "ags/shared/gfx/gfxfilter_ogl.h"
+#include "ags/shared/ogl_headers.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/gfxfilter_ogl.h b/engines/ags/engine/gfx/gfxfilter_ogl.h
index 863dc0a5e5..786dba62c2 100644
--- a/engines/ags/engine/gfx/gfxfilter_ogl.h
+++ b/engines/ags/engine/gfx/gfxfilter_ogl.h
@@ -29,7 +29,7 @@
 #ifndef AGS_ENGINE_GFX_OGLGFXFILTER_H
 #define AGS_ENGINE_GFX_OGLGFXFILTER_H
 
-#include "gfx/gfxfilter_scaling.h"
+#include "ags/shared/gfx/gfxfilter_scaling.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/gfxfilter_scaling.cpp b/engines/ags/engine/gfx/gfxfilter_scaling.cpp
index 7b013e1309..71cbb5af3b 100644
--- a/engines/ags/engine/gfx/gfxfilter_scaling.cpp
+++ b/engines/ags/engine/gfx/gfxfilter_scaling.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "gfx/gfxfilter_scaling.h"
+#include "ags/shared/gfx/gfxfilter_scaling.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/gfxfilter_scaling.h b/engines/ags/engine/gfx/gfxfilter_scaling.h
index f6be6a1729..52f420979e 100644
--- a/engines/ags/engine/gfx/gfxfilter_scaling.h
+++ b/engines/ags/engine/gfx/gfxfilter_scaling.h
@@ -29,8 +29,8 @@
 #ifndef AGS_ENGINE_GFX_SCALINGGFXFILTER_H
 #define AGS_ENGINE_GFX_SCALINGGFXFILTER_H
 
-#include "gfx/gfxfilter.h"
-#include "util/scaling.h"
+#include "ags/shared/gfx/gfxfilter.h"
+#include "ags/shared/util/scaling.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/gfxmodelist.h b/engines/ags/engine/gfx/gfxmodelist.h
index 718ea5ce4f..c49c1a1e52 100644
--- a/engines/ags/engine/gfx/gfxmodelist.h
+++ b/engines/ags/engine/gfx/gfxmodelist.h
@@ -29,8 +29,8 @@
 #ifndef AGS_ENGINE_GFX_GFXMODELIST_H
 #define AGS_ENGINE_GFX_GFXMODELIST_H
 
-#include "core/types.h"
-#include "gfx/gfxdefines.h"
+#include "ags/shared/core/types.h"
+#include "ags/engine/gfx/gfxdefines.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/graphicsdriver.h b/engines/ags/engine/gfx/graphicsdriver.h
index 4af864a39b..1024addc12 100644
--- a/engines/ags/engine/gfx/graphicsdriver.h
+++ b/engines/ags/engine/gfx/graphicsdriver.h
@@ -29,17 +29,17 @@
 #ifndef AGS_ENGINE_GFX_GRAPHICSDRIVER_H
 #define AGS_ENGINE_GFX_GRAPHICSDRIVER_H
 
-#include <memory>
-#include "gfx/gfxdefines.h"
-#include "gfx/gfxmodelist.h"
-#include "util/geometry.h"
+#include "ags/std/memory.h"
+#include "ags/engine/gfx/gfxdefines.h"
+#include "ags/engine/gfx/gfxmodelist.h"
+#include "ags/shared/util/geometry.h"
 
 namespace AGS3 {
 namespace AGS {
 
 namespace Shared {
 class Bitmap;
-typedef std::shared_ptr<Common::Bitmap> PBitmap;
+typedef std::shared_ptr<Shared::Bitmap> PBitmap;
 } // namespace Shared
 
 namespace Engine {
@@ -48,7 +48,7 @@ namespace Engine {
 class IDriverDependantBitmap;
 class IGfxFilter;
 typedef std::shared_ptr<IGfxFilter> PGfxFilter;
-using Common::PBitmap;
+using Shared::PBitmap;
 
 enum TintMethod {
 	TintReColourise = 0,
@@ -124,8 +124,8 @@ public:
 	// Gets closest recommended bitmap format (currently - only color depth) for the given original format.
 	// Engine needs to have game bitmaps brought to the certain range of formats, easing conversion into the video bitmaps.
 	virtual int  GetCompatibleBitmapFormat(int color_depth) = 0;
-	virtual IDriverDependantBitmap *CreateDDBFromBitmap(Common::Bitmap *bitmap, bool hasAlpha, bool opaque = false) = 0;
-	virtual void UpdateDDBFromBitmap(IDriverDependantBitmap *bitmapToUpdate, Common::Bitmap *bitmap, bool hasAlpha) = 0;
+	virtual IDriverDependantBitmap *CreateDDBFromBitmap(Shared::Bitmap *bitmap, bool hasAlpha, bool opaque = false) = 0;
+	virtual void UpdateDDBFromBitmap(IDriverDependantBitmap *bitmapToUpdate, Shared::Bitmap *bitmap, bool hasAlpha) = 0;
 	virtual void DestroyDDB(IDriverDependantBitmap *bitmap) = 0;
 
 	// Prepares next sprite batch, a list of sprites with defined viewport and optional
@@ -151,7 +151,7 @@ public:
 	// Copies contents of the game screen into bitmap using simple blit or pixel copy.
 	// Bitmap must be of supported size and pixel format. If it's not the method will
 	// fail and optionally write wanted destination format into 'want_fmt' pointer.
-	virtual bool GetCopyOfScreenIntoBitmap(Common::Bitmap *destination, bool at_native_res, GraphicResolution *want_fmt = nullptr) = 0;
+	virtual bool GetCopyOfScreenIntoBitmap(Shared::Bitmap *destination, bool at_native_res, GraphicResolution *want_fmt = nullptr) = 0;
 	virtual void EnableVsyncBeforeRender(bool enabled) = 0;
 	virtual void Vsync() = 0;
 	// Enables or disables rendering mode that draws sprite list directly into
@@ -178,14 +178,14 @@ public:
 	virtual void SetGamma(int newGamma) = 0;
 	// Returns the virtual screen. Will return NULL if renderer does not support memory backbuffer.
 	// In normal case you should use GetStageBackBuffer() instead.
-	virtual Common::Bitmap *GetMemoryBackBuffer() = 0;
+	virtual Shared::Bitmap *GetMemoryBackBuffer() = 0;
 	// Sets custom backbuffer bitmap to render to.
 	// Passing NULL pointer will tell renderer to switch back to its original virtual screen.
 	// Note that only software renderer supports this.
-	virtual void SetMemoryBackBuffer(Common::Bitmap *backBuffer) = 0;
+	virtual void SetMemoryBackBuffer(Shared::Bitmap *backBuffer) = 0;
 	// Returns memory backbuffer for the current rendering stage (or base virtual screen if called outside of render pass).
 	// All renderers should support this.
-	virtual Common::Bitmap *GetStageBackBuffer() = 0;
+	virtual Shared::Bitmap *GetStageBackBuffer() = 0;
 	virtual bool RequiresFullRedrawEachFrame() = 0;
 	virtual bool HasAcceleratedTransform() = 0;
 	virtual bool UsesMemoryBackBuffer() = 0;
diff --git a/engines/ags/engine/gfx/hq2x3x.h b/engines/ags/engine/gfx/hq2x3x.h
index 4d679e86f2..ff6a962274 100644
--- a/engines/ags/engine/gfx/hq2x3x.h
+++ b/engines/ags/engine/gfx/hq2x3x.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_GFX_HQ2X3X_H
 #define AGS_ENGINE_GFX_HQ2X3X_H
 
-#include "core/platform.h"
+#include "ags/shared/core/platform.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gfx/ogl_headers.h b/engines/ags/engine/gfx/ogl_headers.h
index b4f3c2f222..6fa7e481b8 100644
--- a/engines/ags/engine/gfx/ogl_headers.h
+++ b/engines/ags/engine/gfx/ogl_headers.h
@@ -26,35 +26,35 @@
 //
 //=============================================================================
 
-#include "core/platform.h"
+#include "ags/shared/core/platform.h"
 
 #if AGS_PLATFORM_OS_WINDOWS
 #include "ags/lib/allegro.h"
-#include <winalleg.h>
-#include <allegro/platform/aintwin.h>
+//include <winalleg.h>
+//include <allegro/platform/aintwin.h>
 
-#include "glad/glad.h"
-#include "glad/glad_wgl.h"
+#include "ags/shared/glad/glad.h"
+#include "ags/shared/glad/glad_wgl.h"
 
 #elif AGS_PLATFORM_OS_LINUX
 #include "ags/lib/allegro.h"
-#include <xalleg.h>
-#include <X11/Xatom.h>
+//include <xalleg.h>
+//include <X11/Xatom.h>
 
-#include "glad/glad.h"
-#include "glad/glad_glx.h"
+#include "ags/shared/glad/glad.h"
+#include "ags/shared/glad/glad_glx.h"
 
 #elif AGS_PLATFORM_OS_ANDROID
 
-#include <GLES/gl.h>
-#include <GLES2/gl2.h>
+//include <GLES/gl.h>
+//include <GLES2/gl2.h>
 
 #ifndef GL_GLEXT_PROTOTYPES
 #define GL_GLEXT_PROTOTYPES
 #endif
 
 // TODO: we probably should not use GLExt since we use GLES2
-#include <GLES/glext.h>
+//include <GLES/glext.h>
 
 #define HDC void*
 #define HGLRC void*
@@ -63,14 +63,14 @@
 
 #elif AGS_PLATFORM_OS_IOS
 
-#include <OpenGLES/ES1/gl.h>
-#include <OpenGLES/ES2/gl.h>
+//include <OpenGLES/ES1/gl.h>
+//include <OpenGLES/ES2/gl.h>
 
 #ifndef GL_GLEXT_PROTOTYPES
 #define GL_GLEXT_PROTOTYPES
 #endif
 
-#include <OpenGLES/ES1/glext.h>
+//include <OpenGLES/ES1/glext.h>
 
 #define HDC void*
 #define HGLRC void*
diff --git a/engines/ags/engine/gui/animatingguibutton.cpp b/engines/ags/engine/gui/animatingguibutton.cpp
index bac2621ab4..8534a9ced2 100644
--- a/engines/ags/engine/gui/animatingguibutton.cpp
+++ b/engines/ags/engine/gui/animatingguibutton.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "gui/animatingguibutton.h"
-#include "util/stream.h"
+#include "ags/shared/gui/animatingguibutton.h"
+#include "ags/shared/util/stream.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gui/animatingguibutton.h b/engines/ags/engine/gui/animatingguibutton.h
index f0610f8d62..4fcaacadd9 100644
--- a/engines/ags/engine/gui/animatingguibutton.h
+++ b/engines/ags/engine/gui/animatingguibutton.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_GUI_ANIMATINGGUIBUTTON_H
 #define AGS_ENGINE_GUI_ANIMATINGGUIBUTTON_H
 
-#include "ac/runtime_defines.h"
+#include "ags/engine/ac/runtime_defines.h"
 
 namespace AGS3 {
 
@@ -42,8 +42,8 @@ struct AnimatingGUIButton {
 	short view, loop, frame;
 	short speed, repeat, wait;
 
-	void ReadFromFile(Common::Stream *in);
-	void WriteToFile(Common::Stream *out);
+	void ReadFromFile(Shared::Stream *in);
+	void WriteToFile(Shared::Stream *out);
 };
 
 } // namespace AGS3
diff --git a/engines/ags/engine/gui/cscidialog.cpp b/engines/ags/engine/gui/cscidialog.cpp
index 9dc7a079d3..89929fb4ed 100644
--- a/engines/ags/engine/gui/cscidialog.cpp
+++ b/engines/ags/engine/gui/cscidialog.cpp
@@ -20,28 +20,28 @@
  *
  */
 
-#include <cctype>
-#include "util/wgt2allg.h"
-#include "ac/common.h"
-#include "ac/draw.h"
-#include "ac/gamesetup.h"
-#include "ac/gamestate.h"
-#include "ac/gui.h"
-#include "ac/keycode.h"
-#include "ac/mouse.h"
-#include "ac/sys_events.h"
-#include "ac/runtime_defines.h"
-#include "font/fonts.h"
-#include "gui/cscidialog.h"
-#include "gui/guidialog.h"
-#include "gui/guimain.h"
-#include "gui/mycontrols.h"
-#include "main/game_run.h"
-#include "gfx/graphicsdriver.h"
-#include "gfx/bitmap.h"
-#include "media/audio/audio_system.h"
-#include "platform/base/agsplatformdriver.h"
-#include "ac/timer.h"
+//include <cctype>
+#include "ags/shared/util/wgt2allg.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/gamesetup.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/ac/gui.h"
+#include "ags/shared/ac/keycode.h"
+#include "ags/shared/ac/mouse.h"
+#include "ags/shared/ac/sys_events.h"
+#include "ags/shared/ac/runtime_defines.h"
+#include "ags/shared/font/fonts.h"
+#include "ags/shared/gui/cscidialog.h"
+#include "ags/shared/gui/guidialog.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/gui/mycontrols.h"
+#include "ags/shared/main/game_run.h"
+#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/media/audio/audio_system.h"
+#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/shared/ac/timer.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gui/cscidialog.h b/engines/ags/engine/gui/cscidialog.h
index 47d5c6327d..05b5057b90 100644
--- a/engines/ags/engine/gui/cscidialog.h
+++ b/engines/ags/engine/gui/cscidialog.h
@@ -29,7 +29,7 @@
 #ifndef AGS_ENGINE_GUI_CSCIDIALOG_H
 #define AGS_ENGINE_GUI_CSCIDIALOG_H
 
-#include "gui/guidialoginternaldefs.h"
+#include "ags/shared/gui/guidialoginternaldefs.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gui/gui_engine.cpp b/engines/ags/engine/gui/gui_engine.cpp
index c5a7e1b650..1644445c46 100644
--- a/engines/ags/engine/gui/gui_engine.cpp
+++ b/engines/ags/engine/gui/gui_engine.cpp
@@ -28,21 +28,21 @@
 
 // Headers, as they are in acgui.cpp
 #pragma unmanaged
-#include "ac/game_version.h"
-#include "ac/system.h"
-#include "font/fonts.h"
-#include "gui/guimain.h"
-#include "gui/guibutton.h"
-#include "gui/guilabel.h"
-#include "gui/guilistbox.h"
-#include "gui/guitextbox.h"
-#include <ctype.h>
-#include "ac/gamesetupstruct.h"
-#include "ac/global_translation.h"
-#include "ac/string.h"
-#include "ac/spritecache.h"
-#include "gfx/bitmap.h"
-#include "gfx/blender.h"
+#include "ags/shared/ac/game_version.h"
+#include "ags/shared/ac/system.h"
+#include "ags/shared/font/fonts.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/gui/guibutton.h"
+#include "ags/shared/gui/guilabel.h"
+#include "ags/shared/gui/guilistbox.h"
+#include "ags/shared/gui/guitextbox.h"
+//include <ctype.h>
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/ac/global_translation.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/gfx/blender.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gui/guidialog.cpp b/engines/ags/engine/gui/guidialog.cpp
index b793a689ca..261a43e17d 100644
--- a/engines/ags/engine/gui/guidialog.cpp
+++ b/engines/ags/engine/gui/guidialog.cpp
@@ -20,19 +20,19 @@
  *
  */
 
-#include <cstdio>
-#include "gui/guidialog.h"
-
-#include "ac/common.h"
-#include "ac/draw.h"
-#include "ac/game.h"
-#include "ac/gamesetup.h"
-#include "ac/gamesetupstruct.h"
-#include "gui/cscidialog.h"
-#include <cctype> //isdigit()
-#include "gfx/bitmap.h"
-#include "gfx/graphicsdriver.h"
-#include "debug/debug_log.h"
+//include <cstdio>
+#include "ags/shared/gui/guidialog.h"
+
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/draw.h"
+#include "ags/shared/ac/game.h"
+#include "ags/shared/ac/gamesetup.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/gui/cscidialog.h"
+//include <cctype> //isdigit()
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/shared/debug/debug_log.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gui/guidialogdefines.h b/engines/ags/engine/gui/guidialogdefines.h
index 3b92cf62e8..45404757b3 100644
--- a/engines/ags/engine/gui/guidialogdefines.h
+++ b/engines/ags/engine/gui/guidialogdefines.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_GUI_GUIDIALOGDEFINES_H
 #define AGS_ENGINE_GUI_GUIDIALOGDEFINES_H
 
-#include "ac/gamesetup.h"
+#include "ags/shared/ac/gamesetup.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gui/guidialoginternaldefs.h b/engines/ags/engine/gui/guidialoginternaldefs.h
index fd4e0777f8..22c5373317 100644
--- a/engines/ags/engine/gui/guidialoginternaldefs.h
+++ b/engines/ags/engine/gui/guidialoginternaldefs.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_GUI_GUIDIALOGINTERNALDEFS_H
 #define AGS_ENGINE_GUI_GUIDIALOGINTERNALDEFS_H
 
-#include "gui/guidialogdefines.h"
+#include "ags/shared/gui/guidialogdefines.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gui/mycontrols.h b/engines/ags/engine/gui/mycontrols.h
index d0fd99a808..5a1abee694 100644
--- a/engines/ags/engine/gui/mycontrols.h
+++ b/engines/ags/engine/gui/mycontrols.h
@@ -29,9 +29,9 @@
 #ifndef AGS_ENGINE_GUI_MYCONTROLS_H
 #define AGS_ENGINE_GUI_MYCONTROLS_H
 
-#include "gui/mylabel.h"
-#include "gui/mylistbox.h"
-#include "gui/mypushbutton.h"
-#include "gui/mytextbox.h"
+#include "ags/shared/gui/mylabel.h"
+#include "ags/shared/gui/mylistbox.h"
+#include "ags/shared/gui/mypushbutton.h"
+#include "ags/shared/gui/mytextbox.h"
 
 #endif
diff --git a/engines/ags/engine/gui/mylabel.cpp b/engines/ags/engine/gui/mylabel.cpp
index 74bd80ab2a..8af6ee0729 100644
--- a/engines/ags/engine/gui/mylabel.cpp
+++ b/engines/ags/engine/gui/mylabel.cpp
@@ -20,14 +20,14 @@
  *
  */
 
-#include <string.h>
-#include "ac/display.h"
-#include "ac/gamesetup.h"
-#include "ac/string.h"
-#include "font/fonts.h"
-#include "gui/guidefines.h"
-#include "gui/mylabel.h"
-#include "gui/guidialoginternaldefs.h"
+//include <string.h>
+#include "ags/shared/ac/display.h"
+#include "ags/shared/ac/gamesetup.h"
+#include "ags/shared/ac/string.h"
+#include "ags/shared/font/fonts.h"
+#include "ags/shared/gui/guidefines.h"
+#include "ags/shared/gui/mylabel.h"
+#include "ags/shared/gui/guidialoginternaldefs.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gui/mylabel.h b/engines/ags/engine/gui/mylabel.h
index cb4905cd0b..b0b5ec733e 100644
--- a/engines/ags/engine/gui/mylabel.h
+++ b/engines/ags/engine/gui/mylabel.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_GUI_MYLABEL_H
 #define AGS_ENGINE_GUI_MYLABEL_H
 
-#include "gui/newcontrol.h"
+#include "ags/shared/gui/newcontrol.h"
 
 namespace AGS3 {
 
@@ -31,7 +31,7 @@ struct MyLabel : public NewControl {
 	char text[150];
 	MyLabel(int xx, int yy, int wii, const char *tee);
 
-	void draw(Common::Bitmap *ds) override;
+	void draw(Shared::Bitmap *ds) override;
 
 	int pressedon(int mousex, int mousey) override;
 
diff --git a/engines/ags/engine/gui/mylistbox.cpp b/engines/ags/engine/gui/mylistbox.cpp
index 37d24a4dbe..07e6ec1951 100644
--- a/engines/ags/engine/gui/mylistbox.cpp
+++ b/engines/ags/engine/gui/mylistbox.cpp
@@ -20,15 +20,15 @@
  *
  */
 
-#include <string.h>
-#include "util/wgt2allg.h"
-#include "ac/common.h"
-#include "ac/gamesetup.h"
-#include "font/fonts.h"
-#include "gfx/bitmap.h"
-#include "gui/guidialog.h"
-#include "gui/guidialoginternaldefs.h"
-#include "gui/mylistbox.h"
+//include <string.h>
+#include "ags/shared/util/wgt2allg.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/gamesetup.h"
+#include "ags/shared/font/fonts.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/gui/guidialog.h"
+#include "ags/shared/gui/guidialoginternaldefs.h"
+#include "ags/shared/gui/mylistbox.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gui/mylistbox.h b/engines/ags/engine/gui/mylistbox.h
index 128447bcc0..4c54e317fa 100644
--- a/engines/ags/engine/gui/mylistbox.h
+++ b/engines/ags/engine/gui/mylistbox.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_GUI_MYLISTBOX_H
 #define AGS_ENGINE_GUI_MYLISTBOX_H
 
-#include "gui/newcontrol.h"
+#include "ags/shared/gui/newcontrol.h"
 
 namespace AGS3 {
 
@@ -37,7 +37,7 @@ struct MyListBox : public NewControl {
 	void clearlist();
 	~MyListBox() override;
 
-	void draw(Common::Bitmap *ds) override;
+	void draw(Shared::Bitmap *ds) override;
 	int pressedon(int mousex, int mousey) override;
 	void additem(char *texx);
 	int processmessage(int mcode, int wParam, long lParam) override;
diff --git a/engines/ags/engine/gui/mypushbutton.cpp b/engines/ags/engine/gui/mypushbutton.cpp
index 77e68a829b..6cdf81386b 100644
--- a/engines/ags/engine/gui/mypushbutton.cpp
+++ b/engines/ags/engine/gui/mypushbutton.cpp
@@ -20,18 +20,18 @@
  *
  */
 
-#include <string.h>
-#include "util/wgt2allg.h"
-#include "ac/common.h"
-#include "ac/mouse.h"
-#include "font/fonts.h"
-#include "gui/mypushbutton.h"
-#include "gui/guidialog.h"
-#include "gui/guidialoginternaldefs.h"
-#include "main/game_run.h"
-#include "gfx/bitmap.h"
-#include "platform/base/agsplatformdriver.h"
-#include "ac/timer.h"
+//include <string.h>
+#include "ags/shared/util/wgt2allg.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/mouse.h"
+#include "ags/shared/font/fonts.h"
+#include "ags/shared/gui/mypushbutton.h"
+#include "ags/shared/gui/guidialog.h"
+#include "ags/shared/gui/guidialoginternaldefs.h"
+#include "ags/shared/main/game_run.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/shared/ac/timer.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gui/mypushbutton.h b/engines/ags/engine/gui/mypushbutton.h
index a1870bcc22..5569656021 100644
--- a/engines/ags/engine/gui/mypushbutton.h
+++ b/engines/ags/engine/gui/mypushbutton.h
@@ -23,14 +23,14 @@
 #ifndef AGS_ENGINE_GUI_PUSHBUTTON_H
 #define AGS_ENGINE_GUI_PUSHBUTTON_H
 
-#include "gui/newcontrol.h"
+#include "ags/shared/gui/newcontrol.h"
 
 namespace AGS3 {
 
 struct MyPushButton : public NewControl {
 	char text[50];
 	MyPushButton(int xx, int yy, int wi, int hi, const char *tex);
-	void draw(Common::Bitmap *ds) override;
+	void draw(Shared::Bitmap *ds) override;
 	int pressedon(int mousex, int mousey) override;
 	int processmessage(int mcode, int wParam, long lParam) override;
 };
diff --git a/engines/ags/engine/gui/mytextbox.cpp b/engines/ags/engine/gui/mytextbox.cpp
index 74e740bc84..898e8d7432 100644
--- a/engines/ags/engine/gui/mytextbox.cpp
+++ b/engines/ags/engine/gui/mytextbox.cpp
@@ -20,12 +20,12 @@
  *
  */
 
-#include <string.h>
-#include "util/wgt2allg.h"
-#include "font/fonts.h"
-#include "gui/mytextbox.h"
-#include "gui/guidialoginternaldefs.h"
-#include "gfx/bitmap.h"
+//include <string.h>
+#include "ags/shared/util/wgt2allg.h"
+#include "ags/shared/font/fonts.h"
+#include "ags/shared/gui/mytextbox.h"
+#include "ags/shared/gui/guidialoginternaldefs.h"
+#include "ags/shared/gfx/bitmap.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gui/mytextbox.h b/engines/ags/engine/gui/mytextbox.h
index 3a69094d4a..46f9e7728b 100644
--- a/engines/ags/engine/gui/mytextbox.h
+++ b/engines/ags/engine/gui/mytextbox.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_GUI_MYTEXTBOX_H
 #define AGS_ENGINE_GUI_MYTEXTBOX_H
 
-#include "gui/newcontrol.h"
+#include "ags/shared/gui/newcontrol.h"
 
 namespace AGS3 {
 
@@ -31,7 +31,7 @@ namespace AGS3 {
 struct MyTextBox : public NewControl {
 	char text[TEXTBOX_MAXLEN + 1];
 	MyTextBox(int xx, int yy, int wii, const char *tee);
-	void draw(Common::Bitmap *ds) override;
+	void draw(Shared::Bitmap *ds) override;
 	int pressedon(int mousex, int mousey) override;
 	int processmessage(int mcode, int wParam, long lParam) override;
 };
diff --git a/engines/ags/engine/gui/newcontrol.cpp b/engines/ags/engine/gui/newcontrol.cpp
index cdc052d114..6337fddbce 100644
--- a/engines/ags/engine/gui/newcontrol.cpp
+++ b/engines/ags/engine/gui/newcontrol.cpp
@@ -20,9 +20,9 @@
  *
  */
 
-#include "gui/newcontrol.h"
-#include "gui/guidialog.h"
-#include "gui/guidialoginternaldefs.h"
+#include "ags/shared/gui/newcontrol.h"
+#include "ags/shared/gui/guidialog.h"
+#include "ags/shared/gui/guidialoginternaldefs.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gui/newcontrol.h b/engines/ags/engine/gui/newcontrol.h
index 690e93a0e9..cfb19f128c 100644
--- a/engines/ags/engine/gui/newcontrol.h
+++ b/engines/ags/engine/gui/newcontrol.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_GUI_NEWCONTROL_H
 #define AGS_ENGINE_GUI_NEWCONTROL_H
 
-#include "gfx/bitmap.h"
+#include "ags/shared/gfx/bitmap.h"
 
 namespace AGS3 {
 
@@ -33,7 +33,7 @@ struct NewControl {
 	int x, y, wid, hit, state, typeandflags, wlevel;
 	char visible, enabled;        // not implemented
 	char needredraw;
-	virtual void draw(Common::Bitmap *ds) = 0;
+	virtual void draw(Shared::Bitmap *ds) = 0;
 	virtual int pressedon(int mousex, int mousey) = 0;
 	virtual int processmessage(int, int, long) = 0;
 
diff --git a/engines/ags/engine/main/config.cpp b/engines/ags/engine/main/config.cpp
index 58949bf10a..d2095f1b29 100644
--- a/engines/ags/engine/main/config.cpp
+++ b/engines/ags/engine/main/config.cpp
@@ -23,27 +23,27 @@
 //
 // Game configuration
 //
-#include <ctype.h> // toupper
-
-#include "core/platform.h"
-#include "ac/gamesetup.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/global_translation.h"
-#include "ac/path_helper.h"
-#include "ac/spritecache.h"
-#include "ac/system.h"
-#include "debug/debugger.h"
-#include "debug/debug_log.h"
-#include "main/mainheader.h"
-#include "main/config.h"
-#include "platform/base/agsplatformdriver.h"
-#include "util/directory.h"
-#include "util/ini_util.h"
-#include "util/textstreamreader.h"
-#include "util/path.h"
-#include "util/string_utils.h"
-#include "media/audio/audio_system.h"
+//include <ctype.h> // toupper
+
+#include "ags/shared/core/platform.h"
+#include "ags/engine/ac/gamesetup.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_translation.h"
+#include "ags/engine/ac/path_helper.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/engine/ac/system.h"
+#include "ags/engine/debugging/debugger.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/main/mainheader.h"
+#include "ags/engine/main/config.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
+#include "ags/shared/util/directory.h"
+#include "ags/shared/util/ini_util.h"
+#include "ags/shared/util/textstreamreader.h"
+#include "ags/shared/util/path.h"
+#include "ags/shared/util/string_utils.h"
+#include "ags/engine/media/audio/audio_system.h"
 
 namespace AGS3 {
 
@@ -85,9 +85,9 @@ void INIgetdirec(char *wasgv, const char *inifil) {
 bool INIreaditem(const ConfigTree &cfg, const String &sectn, const String &item, String &value) {
 	ConfigNode sec_it = cfg.find(sectn);
 	if (sec_it != cfg.end()) {
-		StrStrOIter item_it = sec_it->second.find(item);
-		if (item_it != sec_it->second.end()) {
-			value = item_it->second;
+		StrStrOIter item_it = sec_it->_value.find(item);
+		if (item_it != sec_it->_value.end()) {
+			value = item_it->_value;
 			return true;
 		}
 	}
@@ -272,7 +272,7 @@ void graphics_mode_get_defaults(bool windowed, ScreenSizeSetup &scsz_setup, Game
 String find_default_cfg_file(const char *alt_cfg_file) {
 	// Try current directory for config first; else try exe dir
 	String filename = String::FromFormat("%s/%s", Directory::GetCurrentDirectory().GetCStr(), DefaultConfigFileName.GetCStr());
-	if (!Common::File::TestReadFile(filename)) {
+	if (!Shared::File::TestReadFile(filename)) {
 		char conffilebuf[512];
 		strcpy(conffilebuf, alt_cfg_file);
 		fix_filename_case(conffilebuf);
diff --git a/engines/ags/engine/main/config.h b/engines/ags/engine/main/config.h
index 62ff8c98fb..9c9c10ec6e 100644
--- a/engines/ags/engine/main/config.h
+++ b/engines/ags/engine/main/config.h
@@ -23,8 +23,8 @@
 #ifndef AGS_ENGINE_MAIN_CONFIG_H
 #define AGS_ENGINE_MAIN_CONFIG_H
 
-#include "main/graphics_mode.h"
-#include "util/ini_util.h"
+#include "ags/engine/main/graphics_mode.h"
+#include "ags/shared/util/ini_util.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/main/engine.cpp b/engines/ags/engine/main/engine.cpp
index 31cf7bca1a..516483f3ba 100644
--- a/engines/ags/engine/main/engine.cpp
+++ b/engines/ags/engine/main/engine.cpp
@@ -24,60 +24,63 @@
 // Engine initialization
 //
 
-#include "core/platform.h"
+#include "ags/shared/core/platform.h"
 
-#include <errno.h>
+//include <errno.h>
 #if AGS_PLATFORM_OS_WINDOWS
-#include <process.h>  // _spawnl
+//include <process.h>  // _spawnl
 #endif
 
-#include "main/mainheader.h"
-#include "ac/asset_helper.h"
-#include "ac/common.h"
-#include "ac/character.h"
-#include "ac/characterextras.h"
-#include "ac/characterinfo.h"
-#include "ac/draw.h"
-#include "ac/game.h"
-#include "ac/gamesetup.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/global_character.h"
-#include "ac/global_game.h"
-#include "ac/gui.h"
-#include "ac/lipsync.h"
-#include "ac/objectcache.h"
-#include "ac/path_helper.h"
-#include "ac/sys_events.h"
-#include "ac/roomstatus.h"
-#include "ac/speech.h"
-#include "ac/spritecache.h"
-#include "ac/translation.h"
-#include "ac/viewframe.h"
-#include "ac/dynobj/scriptobject.h"
-#include "ac/dynobj/scriptsystem.h"
-#include "core/assetmanager.h"
-#include "debug/debug_log.h"
-#include "debug/debugger.h"
-#include "debug/out.h"
-#include "font/agsfontrenderer.h"
-#include "font/fonts.h"
-#include "gfx/graphicsdriver.h"
-#include "gfx/gfxdriverfactory.h"
-#include "gfx/ddb.h"
-#include "main/config.h"
-#include "main/game_file.h"
-#include "main/game_start.h"
-#include "main/engine.h"
-#include "main/engine_setup.h"
-#include "main/graphics_mode.h"
-#include "main/main.h"
-#include "main/main_allegro.h"
-#include "media/audio/audio_system.h"
-#include "platform/util/pe.h"
-#include "util/directory.h"
-#include "util/error.h"
-#include "util/misc.h"
-#include "util/path.h"
+#include "ags/engine/main/mainheader.h"
+#include "ags/engine/ac/asset_helper.h"
+#include "ags/shared/ac/common.h"
+#include "ags/engine/ac/character.h"
+#include "ags/engine/ac/characterextras.h"
+#include "ags/shared/ac/characterinfo.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/game.h"
+#include "ags/engine/ac/gamesetup.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/engine/ac/global_character.h"
+#include "ags/engine/ac/global_game.h"
+#include "ags/engine/ac/gui.h"
+#include "ags/engine/ac/lipsync.h"
+#include "ags/engine/ac/objectcache.h"
+#include "ags/engine/ac/path_helper.h"
+#include "ags/engine/ac/sys_events.h"
+#include "ags/engine/ac/roomstatus.h"
+#include "ags/engine/ac/speech.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/engine/ac/translation.h"
+#include "ags/engine/ac/viewframe.h"
+#include "ags/engine/ac/dynobj/scriptobject.h"
+#include "ags/engine/ac/dynobj/scriptsystem.h"
+#include "ags/shared/core/assetmanager.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/debugging/debugger.h"
+#include "ags/shared/debugging/out.h"
+#include "ags/shared/font/agsfontrenderer.h"
+#include "ags/shared/font/fonts.h"
+#include "ags/engine/gfx/graphicsdriver.h"
+#include "ags/engine/gfx/gfxdriverfactory.h"
+#include "ags/engine/gfx/ddb.h"
+#include "ags/engine/main/config.h"
+#include "ags/engine/main/game_file.h"
+#include "ags/engine/main/game_start.h"
+#include "ags/engine/main/engine.h"
+#include "ags/engine/main/engine_setup.h"
+#include "ags/engine/main/graphics_mode.h"
+#include "ags/engine/main/main.h"
+#include "ags/engine/main/main_allegro.h"
+#include "ags/engine/media/audio/audio_system.h"
+#include "ags/engine/platform/util/pe.h"
+#include "ags/shared/gfx/image.h"
+#include "ags/shared/util/directory.h"
+#include "ags/shared/util/error.h"
+#include "ags/shared/util/misc.h"
+#include "ags/shared/util/path.h"
+#include "ags/ags.h"
+#include "common/fs.h"
 
 namespace AGS3 {
 
@@ -122,7 +125,7 @@ bool engine_init_allegro() {
 	our_eip = -199;
 	// Initialize allegro
 	set_uformat(U_ASCII);
-	if (install_allegro(SYSTEM_AUTODETECT, &errno, atexit)) {
+	if (install_allegro()) {
 		const char *al_err = get_allegro_error();
 		const char *user_hint = platform->GetAllegroFailUserHint();
 		platform->DisplayAlert("Unable to initialize Allegro system driver.\n%s\n\n%s",
@@ -150,7 +153,7 @@ void engine_setup_window() {
 	Debug::Printf(kDbgMsg_Info, "Setting up window");
 
 	our_eip = -198;
-	set_window_title("Adventure Game Studio");
+	//set_window_title("Adventure Game Studio");
 	set_close_button_callback(winclosehook);
 	our_eip = -197;
 
@@ -208,44 +211,44 @@ void engine_force_window() {
 }
 
 String find_game_data_in_directory(const String &path) {
-	al_ffblk ff;
-	String test_file;
+	Common::String test_file;
 	String first_nonstd_fn;
-	String pattern = path;
-	pattern.Append("/*");
-
-	if (al_findfirst(pattern, &ff, FA_ALL & ~(FA_DIREC)) != 0)
-		return "";
-	// Select first found data file; files with standart names (*.ags) have
-	// higher priority over files with custom names.
-	do {
-		test_file = ff.name;
-		// Add a bit of sanity and do not parse contents of the 10k-files-large
-		// digital sound libraries.
-		// NOTE: we could certainly benefit from any kind of flag in file lib
-		// that would tell us this is the main lib without extra parsing.
-		if (test_file.CompareRightNoCase(".vox") == 0)
-			continue;
-
-		// *.ags is a standart cross-platform file pattern for AGS games,
-		// ac2game.dat is a legacy file name for very old games,
-		// *.exe is a MS Win executable; it is included to this case because
-		// users often run AGS ports with Windows versions of games.
-		bool is_std_name = test_file.CompareRightNoCase(".ags") == 0 ||
-		                   test_file.CompareNoCase("ac2game.dat") == 0 ||
-		                   test_file.CompareRightNoCase(".exe") == 0;
-		if (is_std_name || first_nonstd_fn.IsEmpty()) {
-			test_file.Format("%s/%s", path.GetCStr(), ff.name);
-			if (IsMainGameLibrary(test_file)) {
-				if (is_std_name) {
-					al_findclose(&ff);
-					return test_file;
-				} else
-					first_nonstd_fn = test_file;
+
+	Common::FSNode folder(path);
+	Common::FSList files;
+	if (folder.getChildren(files, Common::FSNode::kListFilesOnly)) {
+		// Select first found data file; files with standart names (*.ags) have
+		// higher priority over files with custom names.
+		for (Common::FSList::iterator it = files.begin(); it != files.end(); ++it) {
+			test_file = it->getName();
+
+			// Add a bit of sanity and do not parse contents of the 10k-files-large
+			// digital sound libraries.
+			// NOTE: we could certainly benefit from any kind of flag in file lib
+			// that would tell us this is the main lib without extra parsing.
+			if (test_file.hasSuffixIgnoreCase(".vox"))
+				continue;
+
+			// *.ags is a standart cross-platform file pattern for AGS games,
+			// ac2game.dat is a legacy file name for very old games,
+			// *.exe is a MS Win executable; it is included to this case because
+			// users often run AGS ports with Windows versions of games.
+			bool is_std_name = test_file.hasSuffixIgnoreCase(".ags") ||
+				test_file.equalsIgnoreCase("ac2game.dat") ||
+				test_file.hasSuffixIgnoreCase(".exe");
+			if (is_std_name || first_nonstd_fn.IsEmpty()) {
+				test_file = it->getName();
+
+				if (IsMainGameLibrary(test_file)) {
+					if (is_std_name) {
+						return test_file;
+					} else
+						first_nonstd_fn = test_file;
+				}
 			}
 		}
-	} while (al_findnext(&ff) == 0);
-	al_findclose(&ff);
+	}
+
 	return first_nonstd_fn;
 }
 
@@ -271,7 +274,7 @@ bool search_for_game_data_file(String &filename, String &search_path) {
 		//
 		// this will use argument zero, the executable's name
 		filename = GetPathFromCmdArg(0);
-		if (filename.IsEmpty() || !Common::AssetManager::IsDataFile(filename)) {
+		if (filename.IsEmpty() || !Shared::AssetManager::IsDataFile(filename)) {
 			// 3.2 Look in current directory
 			search_path = Directory::GetCurrentDirectory();
 			filename = find_game_data_in_directory(search_path);
@@ -329,7 +332,7 @@ void engine_locate_speech_pak() {
 		String speech_filepath = find_assetlib(speech_file);
 		if (!speech_filepath.IsEmpty()) {
 			Debug::Printf("Initializing speech vox");
-			if (AssetManager::SetDataFile(speech_filepath) != Common::kAssetNoError) {
+			if (AssetManager::SetDataFile(speech_filepath) != Shared::kAssetNoError) {
 				platform->DisplayAlert("Unable to read voice pack, file could be corrupted or of unknown format.\nSpeech voice-over will be disabled.");
 				AssetManager::SetDataFile(ResPaths.GamePak.Path); // switch back to the main data pack
 				return;
@@ -393,7 +396,7 @@ void engine_init_keyboard() {
 	install_keyboard();
 #endif
 #if AGS_PLATFORM_OS_LINUX
-	setlocale(LC_NUMERIC, "C"); // needed in X platform because install keyboard affects locale of printfs
+//	setlocale(LC_NUMERIC, "C"); // needed in X platform because install keyboard affects locale of printfs
 #endif
 }
 
@@ -567,8 +570,8 @@ void engine_init_exit_handler() {
 }
 
 void engine_init_rand() {
-	play.randseed = time(nullptr);
-	srand(play.randseed);
+	play.randseed = g_system->getMillis();
+	::AGS::g_vm->setRandomNumberSeed(play.randseed);
 }
 
 void engine_init_pathfinder() {
@@ -612,7 +615,7 @@ int engine_check_register_game() {
 
 void engine_init_title() {
 	our_eip = -91;
-	set_window_title(game.gamename);
+	::AGS::g_vm->set_window_title(game.gamename);
 	Debug::Printf(kDbgMsg_Info, "Game title: '%s'", game.gamename);
 }
 
@@ -631,7 +634,7 @@ void engine_init_directories() {
 
 	ResPaths.DataDir = usetup.data_files_dir;
 	ResPaths.GamePak.Path = usetup.main_data_filepath;
-	ResPaths.GamePak.Name = get_filename(usetup.main_data_filepath);
+	ResPaths.GamePak.Name = Shared::Path::get_filename(usetup.main_data_filepath);
 
 	set_install_dir(usetup.install_dir, usetup.install_audio_dir, usetup.install_voice_dir);
 	if (!usetup.install_dir.IsEmpty()) {
@@ -671,14 +674,14 @@ int check_write_access() {
 	// The Save Game Dir is the only place that we should write to
 	String svg_dir = get_save_game_directory();
 	String tempPath = String::FromFormat("%s""tmptest.tmp", svg_dir.GetCStr());
-	Stream *temp_s = Common::File::CreateFile(tempPath);
+	Stream *temp_s = Shared::File::CreateFile(tempPath);
 	if (!temp_s)
 		// TODO: move this somewhere else (Android platform driver init?)
 #if AGS_PLATFORM_OS_ANDROID
 	{
-		put_backslash(android_base_directory);
+//		put_backslash(android_base_directory);
 		tempPath.Format("%s""tmptest.tmp", android_base_directory);
-		temp_s = Common::File::CreateFile(tempPath);
+		temp_s = Shared::File::CreateFile(tempPath);
 		if (temp_s == NULL) return 0;
 		else SetCustomSaveParent(android_base_directory);
 	}
@@ -1154,7 +1157,7 @@ bool define_gamedata_location(const String &exe_path) {
 	// On success: set all the necessary path and filename settings,
 	// derive missing ones from available.
 	if (usetup.main_data_filename.IsEmpty()) {
-		usetup.main_data_filename = get_filename(usetup.main_data_filepath);
+		usetup.main_data_filename = Shared::Path::get_filename(usetup.main_data_filepath);
 	} else if (usetup.main_data_filepath.IsEmpty()) {
 		if (usetup.data_files_dir.IsEmpty() || !is_relative_filename(usetup.main_data_filename))
 			usetup.main_data_filepath = usetup.main_data_filename;
@@ -1221,8 +1224,8 @@ void engine_prepare_config(ConfigTree &cfg, const String &exe_path, const Config
 	engine_read_config(exe_path, cfg);
 	// Merge startup options in
 	for (const auto &sectn : startup_opts)
-		for (const auto &opt : sectn.second)
-			cfg[sectn.first][opt.first] = opt.second;
+		for (const auto &opt : sectn._value)
+			cfg[sectn._key][opt._key] = opt._value;
 
 	// Add "meta" config settings to let setup application(s)
 	// display correct properties to the user
@@ -1278,9 +1281,9 @@ static void engine_print_info(const std::set<String> &keys, const String &exe_pa
 	}
 	if ((all || keys.count("config") > 0) && user_cfg) {
 		for (const auto &sectn : *user_cfg) {
-			String cfg_sectn = String::FromFormat("config@%s", sectn.first.GetCStr());
-			for (const auto &opt : sectn.second)
-				data[cfg_sectn][opt.first] = opt.second;
+			String cfg_sectn = String::FromFormat("config@%s", sectn._key.GetCStr());
+			for (const auto &opt : sectn._value)
+				data[cfg_sectn][opt._key] = opt._value;
 		}
 	}
 	if (all || keys.count("data") > 0) {
diff --git a/engines/ags/engine/main/engine.h b/engines/ags/engine/main/engine.h
index d27e4fe89d..f08af9fa99 100644
--- a/engines/ags/engine/main/engine.h
+++ b/engines/ags/engine/main/engine.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_MAIN_ENGINE_H
 #define AGS_ENGINE_MAIN_ENGINE_H
 
-#include "util/ini_util.h"
+#include "ags/shared/util/ini_util.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/main/engine_setup.cpp b/engines/ags/engine/main/engine_setup.cpp
index 9168a24f7d..72a46c96c6 100644
--- a/engines/ags/engine/main/engine_setup.cpp
+++ b/engines/ags/engine/main/engine_setup.cpp
@@ -20,29 +20,29 @@
  *
  */
 
-#include "core/platform.h"
-#include "ac/common.h"
-#include "ac/display.h"
-#include "ac/draw.h"
-#include "ac/game_version.h"
-#include "ac/gamesetup.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/mouse.h"
-#include "ac/runtime_defines.h"
-#include "ac/walkbehind.h"
-#include "ac/dynobj/scriptsystem.h"
-#include "debug/out.h"
-#include "device/mousew32.h"
-#include "font/fonts.h"
-#include "gfx/ali3dexception.h"
-#include "gfx/graphicsdriver.h"
-#include "gui/guimain.h"
-#include "gui/guiinv.h"
-#include "main/graphics_mode.h"
-#include "main/engine_setup.h"
-#include "media/video/video.h"
-#include "platform/base/agsplatformdriver.h"
+#include "ags/shared/core/platform.h"
+#include "ags/shared/ac/common.h"
+#include "ags/engine/ac/display.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/shared/ac/game_version.h"
+#include "ags/engine/ac/gamesetup.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/mouse.h"
+#include "ags/engine/ac/runtime_defines.h"
+#include "ags/engine/ac/walkbehind.h"
+#include "ags/engine/ac/dynobj/scriptsystem.h"
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/device/mousew32.h"
+#include "ags/shared/font/fonts.h"
+#include "ags/engine/gfx/ali3dexception.h"
+#include "ags/engine/gfx/graphicsdriver.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/gui/guiinv.h"
+#include "ags/engine/main/graphics_mode.h"
+#include "ags/engine/main/engine_setup.h"
+#include "ags/engine/media/video/video.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/main/engine_setup.h b/engines/ags/engine/main/engine_setup.h
index feca62e0ef..cc20398114 100644
--- a/engines/ags/engine/main/engine_setup.h
+++ b/engines/ags/engine/main/engine_setup.h
@@ -23,8 +23,8 @@
 #ifndef AGS_ENGINE_MAIN_ENGINESETUP_H
 #define AGS_ENGINE_MAIN_ENGINESETUP_H
 
-#include "util/geometry.h"
-#include "gfx/gfxdefines.h"
+#include "ags/shared/util/geometry.h"
+#include "ags/engine/gfx/gfxdefines.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/main/game_file.cpp b/engines/ags/engine/main/game_file.cpp
index a1590ca036..545ef80b75 100644
--- a/engines/ags/engine/main/game_file.cpp
+++ b/engines/ags/engine/main/game_file.cpp
@@ -24,34 +24,34 @@
 // Game data file management
 //
 
-#include "main/mainheader.h"
-#include "main/game_file.h"
-#include "ac/common.h"
-#include "ac/character.h"
-#include "ac/charactercache.h"
-#include "ac/dialogtopic.h"
-#include "ac/draw.h"
-#include "ac/game.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/gamestructdefines.h"
-#include "ac/gui.h"
-#include "ac/viewframe.h"
-#include "debug/debug_log.h"
-#include "debug/out.h"
-#include "gui/guilabel.h"
-#include "main/main.h"
-#include "platform/base/agsplatformdriver.h"
-#include "util/stream.h"
-#include "gfx/bitmap.h"
-#include "gfx/blender.h"
-#include "core/assetmanager.h"
-#include "util/alignedstream.h"
-#include "ac/gamesetup.h"
-#include "game/main_game_file.h"
-#include "game/game_init.h"
-#include "plugin/agsplugin.h"
-#include "script/script.h"
+#include "ags/engine/main/mainheader.h"
+#include "ags/engine/main/game_file.h"
+#include "ags/shared/ac/common.h"
+#include "ags/engine/ac/character.h"
+#include "ags/engine/ac/charactercache.h"
+#include "ags/shared/ac/dialogtopic.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/game.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/shared/ac/gamestructdefines.h"
+#include "ags/engine/ac/gui.h"
+#include "ags/engine/ac/viewframe.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/shared/debugging/out.h"
+#include "ags/shared/gui/guilabel.h"
+#include "ags/engine/main/main.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
+#include "ags/shared/util/stream.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/engine/gfx/blender.h"
+#include "ags/shared/core/assetmanager.h"
+#include "ags/shared/util/alignedstream.h"
+#include "ags/engine/ac/gamesetup.h"
+#include "ags/shared/game/main_game_file.h"
+#include "ags/engine/game/game_init.h"
+#include "ags/engine/plugin/agsplugin.h"
+#include "ags/engine/script/script.h"
 
 namespace AGS3 {
 
@@ -72,7 +72,7 @@ extern int numScriptModules;
 bool test_game_caps(const std::set<String> &caps, std::set<String> &failed_caps) {
 	// Currently we support nothing special
 	failed_caps = caps;
-	return caps.size() == 0;
+	return caps.empty();
 }
 
 // Forms a simple list of capability names
@@ -97,7 +97,7 @@ HGameFileError game_file_first_open(MainGameSource &src) {
 		Debug::Printf(kDbgMsg_Info, "Opened game data file: %s", src.Filename.GetCStr());
 		Debug::Printf(kDbgMsg_Info, "Game data version: %d", src.DataVersion);
 		Debug::Printf(kDbgMsg_Info, "Compiled with: %s", src.CompiledWith.GetCStr());
-		if (src.Caps.size() > 0) {
+		if (!src.Caps.empty()) {
 			String caps_list = get_caps_list(src.Caps);
 			Debug::Printf(kDbgMsg_Info, "Requested engine caps: %s", caps_list.GetCStr());
 		}
@@ -116,7 +116,7 @@ HGameFileError game_file_first_open(MainGameSource &src) {
 }
 
 void PreReadSaveFileInfo(Stream *in, GameDataVersion data_ver) {
-	AlignedStream align_s(in, Common::kAligned_Read);
+	AlignedStream align_s(in, Shared::kAligned_Read);
 	game.ReadFromFile(&align_s);
 	// Discard game messages we do not need here
 	delete[] game.load_messages;
diff --git a/engines/ags/engine/main/game_file.h b/engines/ags/engine/main/game_file.h
index d1487c9a64..9a9f818279 100644
--- a/engines/ags/engine/main/game_file.h
+++ b/engines/ags/engine/main/game_file.h
@@ -23,8 +23,8 @@
 #ifndef AGS_ENGINE_MAIN_GAMEFILE_H
 #define AGS_ENGINE_MAIN_GAMEFILE_H
 
-#include "util/error.h"
-#include "util/string.h"
+#include "ags/shared/util/error.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/main/game_run.cpp b/engines/ags/engine/main/game_run.cpp
index 63816c8cbe..d6ae725152 100644
--- a/engines/ags/engine/main/game_run.cpp
+++ b/engines/ags/engine/main/game_run.cpp
@@ -24,47 +24,48 @@
 // Game loop
 //
 
-#include <limits>
-#include <chrono>
-#include "ac/common.h"
-#include "ac/characterextras.h"
-#include "ac/characterinfo.h"
-#include "ac/draw.h"
-#include "ac/event.h"
-#include "ac/game.h"
-#include "ac/gamesetup.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/global_debug.h"
-#include "ac/global_display.h"
-#include "ac/global_game.h"
-#include "ac/global_gui.h"
-#include "ac/global_region.h"
-#include "ac/gui.h"
-#include "ac/hotspot.h"
-#include "ac/keycode.h"
-#include "ac/mouse.h"
-#include "ac/overlay.h"
-#include "ac/sys_events.h"
-#include "ac/room.h"
-#include "ac/roomobject.h"
-#include "ac/roomstatus.h"
-#include "debug/debugger.h"
-#include "debug/debug_log.h"
-#include "gui/guiinv.h"
-#include "gui/guimain.h"
-#include "gui/guitextbox.h"
-#include "main/mainheader.h"
-#include "main/engine.h"
-#include "main/game_run.h"
-#include "main/update.h"
-#include "plugin/agsplugin.h"
-#include "plugin/plugin_engine.h"
-#include "script/script.h"
-#include "ac/spritecache.h"
-#include "media/audio/audio_system.h"
-#include "platform/base/agsplatformdriver.h"
-#include "ac/timer.h"
-#include "ac/keycode.h"
+#include "ags/std/limits.h"
+#include "ags/std/chrono.h"
+#include "ags/shared/ac/common.h"
+#include "ags/engine/ac/characterextras.h"
+#include "ags/shared/ac/characterinfo.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/event.h"
+#include "ags/engine/ac/game.h"
+#include "ags/engine/ac/gamesetup.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/engine/ac/global_debug.h"
+#include "ags/engine/ac/global_display.h"
+#include "ags/engine/ac/global_game.h"
+#include "ags/engine/ac/global_gui.h"
+#include "ags/engine/ac/global_region.h"
+#include "ags/engine/ac/gui.h"
+#include "ags/engine/ac/hotspot.h"
+#include "ags/engine/ac/keycode.h"
+#include "ags/engine/ac/mouse.h"
+#include "ags/engine/ac/overlay.h"
+#include "ags/engine/ac/sys_events.h"
+#include "ags/engine/ac/room.h"
+#include "ags/engine/ac/roomobject.h"
+#include "ags/engine/ac/roomstatus.h"
+#include "ags/engine/debugging/debugger.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/shared/gui/guiinv.h"
+#include "ags/shared/gui/guimain.h"
+#include "ags/shared/gui/guitextbox.h"
+#include "ags/engine/main/mainheader.h"
+#include "ags/engine/main/engine.h"
+#include "ags/engine/main/game_run.h"
+#include "ags/engine/main/update.h"
+#include "ags/engine/plugin/agsplugin.h"
+#include "ags/engine/plugin/plugin_engine.h"
+#include "ags/engine/script/script.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/engine/media/audio/audio_system.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
+#include "ags/engine/ac/timer.h"
+#include "ags/engine/ac/keycode.h"
+#include "ags/lib/allegro/keyboard.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/main/game_start.cpp b/engines/ags/engine/main/game_start.cpp
index 244f007a35..df57f42753 100644
--- a/engines/ags/engine/main/game_start.cpp
+++ b/engines/ags/engine/main/game_start.cpp
@@ -24,25 +24,26 @@
 // Game initialization
 //
 
-#include "ac/common.h"
-#include "ac/characterinfo.h"
-#include "ac/game.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/gamestate.h"
-#include "ac/global_game.h"
-#include "ac/mouse.h"
-#include "ac/room.h"
-#include "ac/screen.h"
-#include "debug/debug_log.h"
-#include "debug/debugger.h"
-#include "debug/out.h"
-#include "gfx/ali3dexception.h"
-#include "main/mainheader.h"
-#include "main/game_run.h"
-#include "main/game_start.h"
-#include "script/script.h"
-#include "media/audio/audio_system.h"
-#include "ac/timer.h"
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/characterinfo.h"
+#include "ags/engine/ac/game.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_game.h"
+#include "ags/engine/ac/mouse.h"
+#include "ags/engine/ac/room.h"
+#include "ags/engine/ac/screen.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/debugging/debugger.h"
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/gfx/ali3dexception.h"
+#include "ags/engine/main/mainheader.h"
+#include "ags/engine/main/game_run.h"
+#include "ags/engine/main/game_start.h"
+#include "ags/engine/script/script.h"
+#include "ags/engine/media/audio/audio_system.h"
+#include "ags/engine/ac/timer.h"
+#include "ags/ags.h"
 
 namespace AGS3 {
 
@@ -123,7 +124,7 @@ void do_start_game() {
 		start_game();
 }
 
-void initialize_start_and_play_game(int override_start_room, const char *loadSaveGameOnStartup) {
+void initialize_start_and_play_game(int override_start_room, const char *loadSaveOnStartup) {
 	try { // BEGIN try for ALI3DEXception
 
 		set_cursor_mode(MODE_WALK);
@@ -138,7 +139,7 @@ void initialize_start_and_play_game(int override_start_room, const char *loadSav
 			game.options[OPT_ALWAYSSPCH] = oldalways;
 		}
 
-		srand(play.randseed);
+		::AGS::g_vm->setRandomNumberSeed(play.randseed);
 		if (override_start_room)
 			playerchar->room = override_start_room;
 
diff --git a/engines/ags/engine/main/graphics_mode.cpp b/engines/ags/engine/main/graphics_mode.cpp
index 2700ea1986..7020a0ada6 100644
--- a/engines/ags/engine/main/graphics_mode.cpp
+++ b/engines/ags/engine/main/graphics_mode.cpp
@@ -24,21 +24,21 @@
 // Graphics initialization
 //
 
-#include <algorithm>
-#include "core/platform.h"
-#include "ac/draw.h"
-#include "debug/debugger.h"
-#include "debug/out.h"
-#include "gfx/ali3dexception.h"
-#include "gfx/bitmap.h"
-#include "gfx/gfxdriverfactory.h"
-#include "gfx/gfxfilter.h"
-#include "gfx/graphicsdriver.h"
-#include "main/config.h"
-#include "main/engine_setup.h"
-#include "main/graphics_mode.h"
-#include "main/main_allegro.h"
-#include "platform/base/agsplatformdriver.h"
+//include <algorithm>
+#include "ags/shared/core/platform.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/debugging/debugger.h"
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/gfx/ali3dexception.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/engine/gfx/gfxdriverfactory.h"
+#include "ags/engine/gfx/gfxfilter.h"
+#include "ags/engine/gfx/graphicsdriver.h"
+#include "ags/engine/main/config.h"
+#include "ags/engine/main/engine_setup.h"
+#include "ags/engine/main/graphics_mode.h"
+#include "ags/engine/main/main_allegro.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
 
 namespace AGS3 {
 
@@ -469,20 +469,20 @@ bool graphics_mode_init_any(const Size game_size, const ScreenSetup &setup, cons
 		if (it->CompareNoCase(setup.DriverID) == 0) break;
 	}
 	if (it != ids.end())
-		std::rotate(ids.begin(), it, ids.end());
+		ids.rotate(it);
 	else
 		Debug::Printf(kDbgMsg_Error, "Requested graphics driver '%s' not found, will try existing drivers instead", setup.DriverID.GetCStr());
 
 	// Try to create renderer and init gfx mode, choosing one factory at a time
 	bool result = false;
-	for (StringV::const_iterator it = ids.begin(); it != ids.end(); ++it) {
+	for (StringV::const_iterator sit = ids.begin(); sit != ids.end(); ++sit) {
 		result =
 #ifdef USE_SIMPLE_GFX_INIT
 			simple_create_gfx_driver_and_init_mode
 #else
 			create_gfx_driver_and_init_mode_any
 #endif
-			(*it, game_size, setup.DisplayMode, color_depth, gameframe, setup.Filter);
+			(*sit, game_size, setup.DisplayMode, color_depth, gameframe, setup.Filter);
 
 		if (result)
 			break;
diff --git a/engines/ags/engine/main/graphics_mode.h b/engines/ags/engine/main/graphics_mode.h
index 26c377f04f..0576b90f70 100644
--- a/engines/ags/engine/main/graphics_mode.h
+++ b/engines/ags/engine/main/graphics_mode.h
@@ -23,9 +23,9 @@
 #ifndef AGS_ENGINE_MAIN_GRAPHICSMODE_H
 #define AGS_ENGINE_MAIN_GRAPHICSMODE_H
 
-#include "gfx/gfxdefines.h"
-#include "util/scaling.h"
-#include "util/string.h"
+#include "ags/engine/gfx/gfxdefines.h"
+#include "ags/engine/util/scaling.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 
@@ -85,7 +85,7 @@ enum ScreenSizeDefinition {
 // Configuration that is used to determine the size of the screen
 struct ScreenSizeSetup {
 	ScreenSizeDefinition SizeDef;       // a method used to determine screen size
-	::Size               Size;          // explicitly defined screen metrics
+	AGS3::Size           Size;          // explicitly defined screen metrics
 	bool                 MatchDeviceRatio; // whether to choose resolution matching device aspect ratio
 
 	ScreenSizeSetup();
diff --git a/engines/ags/engine/main/main.cpp b/engines/ags/engine/main/main.cpp
index 91f12195fc..a70fb04f86 100644
--- a/engines/ags/engine/main/main.cpp
+++ b/engines/ags/engine/main/main.cpp
@@ -30,33 +30,33 @@
 // What about other platforms?
 //
 
-#include "core/platform.h"
+#include "ags/shared/core/platform.h"
 #define AGS_PLATFORM_DEFINES_PSP_VARS (AGS_PLATFORM_OS_IOS || AGS_PLATFORM_OS_ANDROID)
 
-#include <set>
-#include "ac/common.h"
-#include "ac/gamesetup.h"
-#include "ac/gamestate.h"
-#include "core/def_version.h"
-#include "debug/debugger.h"
-#include "debug/debug_log.h"
-#include "debug/out.h"
-#include "main/config.h"
-#include "main/engine.h"
-#include "main/mainheader.h"
-#include "main/main.h"
-#include "platform/base/agsplatformdriver.h"
-#include "ac/route_finder.h"
-#include "core/assetmanager.h"
-#include "util/directory.h"
-#include "util/path.h"
-#include "util/string_compat.h"
+//include <set>
+#include "ags/shared/ac/common.h"
+#include "ags/shared/ac/gamesetup.h"
+#include "ags/shared/ac/gamestate.h"
+#include "ags/shared/core/def_version.h"
+#include "ags/shared/debug/debugger.h"
+#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/debug/out.h"
+#include "ags/shared/main/config.h"
+#include "ags/shared/main/engine.h"
+#include "ags/shared/main/mainheader.h"
+#include "ags/shared/main/main.h"
+#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/shared/ac/route_finder.h"
+#include "ags/shared/core/assetmanager.h"
+#include "ags/shared/util/directory.h"
+#include "ags/shared/util/path.h"
+#include "ags/shared/util/string_compat.h"
 
 #if AGS_PLATFORM_OS_WINDOWS
-#include "platform/windows/win_ex_handling.h"
+#include "ags/shared/platform/windows/win_ex_handling.h"
 #endif
 #if AGS_PLATFORM_DEBUG
-#include "test/test_all.h"
+#include "ags/shared/test/test_all.h"
 #endif
 
 #if AGS_PLATFORM_OS_WINDOWS && !AGS_PLATFORM_DEBUG
diff --git a/engines/ags/engine/main/main.h b/engines/ags/engine/main/main.h
index a3da94db6a..d0efac6425 100644
--- a/engines/ags/engine/main/main.h
+++ b/engines/ags/engine/main/main.h
@@ -23,8 +23,8 @@
 #ifndef AGS_ENGINE_MAIN_MAIN_H
 #define AGS_ENGINE_MAIN_MAIN_H
 
-#include "core/platform.h"
-#include "util/version.h"
+#include "ags/shared/core/platform.h"
+#include "ags/shared/util/version.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/main/mainheader.h b/engines/ags/engine/main/mainheader.h
index 10064e6425..b2166d2874 100644
--- a/engines/ags/engine/main/mainheader.h
+++ b/engines/ags/engine/main/mainheader.h
@@ -23,27 +23,27 @@
 #ifndef AGS_ENGINE_MAIN_MAINHEADER_H
 #define AGS_ENGINE_MAIN_MAINHEADER_H
 
-#include "core/platform.h"
+#include "ags/shared/core/platform.h"
 
-#include "main/maindefines_ex.h"
+#include "ags/engine/main/maindefines_ex.h"
 
-#include "ac/math.h"
-#include "script/script_runtime.h"
-#include "gui/animatingguibutton.h"
-#include "gui/guibutton.h"
-#include "gfx/gfxfilter.h"
-#include "util/string_utils.h"
-#include "device/mousew32.h"
-#include "ac/route_finder.h"
-#include "util/misc.h"
-#include "script/cc_error.h"
+#include "ags/engine/ac/math.h"
+#include "ags/engine/script/script_runtime.h"
+#include "ags/engine/gui/animatingguibutton.h"
+#include "ags/shared/gui/guibutton.h"
+#include "ags/engine/gfx/gfxfilter.h"
+#include "ags/shared/util/string_utils.h"
+#include "ags/engine/device/mousew32.h"
+#include "ags/engine/ac/route_finder.h"
+#include "ags/shared/util/misc.h"
+#include "ags/shared/script/cc_error.h"
 
 // include last since we affect windows includes
-#include "ac/file.h"
+#include "ags/engine/ac/file.h"
 
 #if AGS_PLATFORM_OS_ANDROID
-#include <sys/stat.h>
-#include <android/log.h>
+//include <sys/stat.h>
+//include <android/log.h>
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/main/quit.cpp b/engines/ags/engine/main/quit.cpp
index e76439281f..9158366712 100644
--- a/engines/ags/engine/main/quit.cpp
+++ b/engines/ags/engine/main/quit.cpp
@@ -24,28 +24,29 @@
 // Quit game procedure
 //
 
-#include "core/platform.h"
-#include "ac/cdaudio.h"
-#include "ac/gamesetup.h"
-#include "ac/gamesetupstruct.h"
-#include "ac/roomstatus.h"
-#include "ac/translation.h"
-#include "debug/agseditordebugger.h"
-#include "debug/debug_log.h"
-#include "debug/debugger.h"
-#include "debug/out.h"
-#include "font/fonts.h"
-#include "main/config.h"
-#include "main/engine.h"
-#include "main/main.h"
-#include "main/mainheader.h"
-#include "main/quit.h"
-#include "ac/spritecache.h"
-#include "gfx/graphicsdriver.h"
-#include "gfx/bitmap.h"
-#include "core/assetmanager.h"
-#include "plugin/plugin_engine.h"
-#include "media/audio/audio_system.h"
+#include "ags/shared/core/platform.h"
+#include "ags/engine/ac/cdaudio.h"
+#include "ags/engine/ac/gamesetup.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/engine/ac/roomstatus.h"
+#include "ags/engine/ac/translation.h"
+#include "ags/engine/debugging/agseditordebugger.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/debugging/debugger.h"
+#include "ags/shared/debugging/out.h"
+#include "ags/shared/font/fonts.h"
+#include "ags/engine/main/config.h"
+#include "ags/engine/main/engine.h"
+#include "ags/engine/main/main.h"
+#include "ags/engine/main/mainheader.h"
+#include "ags/engine/main/quit.h"
+#include "ags/shared/ac/spritecache.h"
+#include "ags/engine/gfx/graphicsdriver.h"
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/shared/core/assetmanager.h"
+#include "ags/engine/plugin/plugin_engine.h"
+#include "ags/engine/media/audio/audio_system.h"
+#include "ags/ags.h"
 


Commit: d8cb72494c7c54861aac8d3d18177256065a7082
    https://github.com/scummvm/scummvm/commit/d8cb72494c7c54861aac8d3d18177256065a7082
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added engine/gui/ folder

Changed paths:
    engines/ags/engine/gui/animatingguibutton.cpp
    engines/ags/engine/gui/animatingguibutton.h
    engines/ags/engine/gui/cscidialog.cpp
    engines/ags/engine/gui/cscidialog.h
    engines/ags/engine/gui/gui_engine.cpp
    engines/ags/engine/gui/guidialog.cpp
    engines/ags/engine/gui/guidialog.h
    engines/ags/engine/gui/guidialogdefines.h
    engines/ags/engine/gui/guidialoginternaldefs.h
    engines/ags/engine/gui/mycontrols.h
    engines/ags/engine/gui/mylabel.cpp
    engines/ags/engine/gui/mylabel.h
    engines/ags/engine/gui/mylistbox.cpp
    engines/ags/engine/gui/mylistbox.h
    engines/ags/engine/gui/mypushbutton.cpp
    engines/ags/engine/gui/mypushbutton.h
    engines/ags/engine/gui/mytextbox.cpp
    engines/ags/engine/gui/mytextbox.h
    engines/ags/engine/gui/newcontrol.cpp
    engines/ags/engine/media/audio/audio.h
    engines/ags/module.mk
    engines/ags/shared/game/room_file.cpp
    engines/ags/shared/util/wgt2allg.h


diff --git a/engines/ags/engine/gui/animatingguibutton.cpp b/engines/ags/engine/gui/animatingguibutton.cpp
index 8534a9ced2..88d55b0ed0 100644
--- a/engines/ags/engine/gui/animatingguibutton.cpp
+++ b/engines/ags/engine/gui/animatingguibutton.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/shared/gui/animatingguibutton.h"
+#include "ags/engine/gui/animatingguibutton.h"
 #include "ags/shared/util/stream.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/gui/animatingguibutton.h b/engines/ags/engine/gui/animatingguibutton.h
index 4fcaacadd9..1a0053601a 100644
--- a/engines/ags/engine/gui/animatingguibutton.h
+++ b/engines/ags/engine/gui/animatingguibutton.h
@@ -31,8 +31,9 @@ namespace AGS3 {
 namespace AGS {
 namespace Shared {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 struct AnimatingGUIButton {
diff --git a/engines/ags/engine/gui/cscidialog.cpp b/engines/ags/engine/gui/cscidialog.cpp
index 89929fb4ed..25f4c7db18 100644
--- a/engines/ags/engine/gui/cscidialog.cpp
+++ b/engines/ags/engine/gui/cscidialog.cpp
@@ -23,25 +23,25 @@
 //include <cctype>
 #include "ags/shared/util/wgt2allg.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/gamesetup.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/gui.h"
-#include "ags/shared/ac/keycode.h"
-#include "ags/shared/ac/mouse.h"
-#include "ags/shared/ac/sys_events.h"
-#include "ags/shared/ac/runtime_defines.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/gamesetup.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/gui.h"
+#include "ags/engine/ac/keycode.h"
+#include "ags/engine/ac/mouse.h"
+#include "ags/engine/ac/sys_events.h"
+#include "ags/engine/ac/runtime_defines.h"
 #include "ags/shared/font/fonts.h"
-#include "ags/shared/gui/cscidialog.h"
-#include "ags/shared/gui/guidialog.h"
+#include "ags/engine/gui/cscidialog.h"
+#include "ags/engine/gui/guidialog.h"
 #include "ags/shared/gui/guimain.h"
-#include "ags/shared/gui/mycontrols.h"
-#include "ags/shared/main/game_run.h"
-#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/engine/gui/mycontrols.h"
+#include "ags/engine/main/game_run.h"
+#include "ags/engine/gfx/graphicsdriver.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/media/audio/audio_system.h"
-#include "ags/shared/platform/base/agsplatformdriver.h"
-#include "ags/shared/ac/timer.h"
+#include "ags/engine/media/audio/audio_system.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
+#include "ags/engine/ac/timer.h"
 
 namespace AGS3 {
 
@@ -275,15 +275,15 @@ void multiply_up(int *x1, int *y1, int *x2, int *y2) {
 
 int checkcontrols() {
 	// NOTE: this is because old code was working with full game screen
-	const int mousex = ::mousex - win_x;
-	const int mousey = ::mousey - win_y;
+	const int mouseX = AGS3::mousex - win_x;
+	const int mouseY = AGS3::mousey - win_y;
 
 	smcode = 0;
 	for (int kk = 0; kk < MAXCONTROLS; kk++) {
 		if (vobjs[kk] != nullptr) {
-			if (vobjs[kk]->mouseisinarea(mousex, mousey)) {
+			if (vobjs[kk]->mouseisinarea(mouseX, mouseY)) {
 				controlid = kk;
-				return vobjs[kk]->pressedon(mousex, mousey);
+				return vobjs[kk]->pressedon(mouseX, mouseY);
 			}
 		}
 	}
diff --git a/engines/ags/engine/gui/cscidialog.h b/engines/ags/engine/gui/cscidialog.h
index 05b5057b90..5a360b1faa 100644
--- a/engines/ags/engine/gui/cscidialog.h
+++ b/engines/ags/engine/gui/cscidialog.h
@@ -29,7 +29,7 @@
 #ifndef AGS_ENGINE_GUI_CSCIDIALOG_H
 #define AGS_ENGINE_GUI_CSCIDIALOG_H
 
-#include "ags/shared/gui/guidialoginternaldefs.h"
+#include "ags/engine/gui/guidialoginternaldefs.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gui/gui_engine.cpp b/engines/ags/engine/gui/gui_engine.cpp
index 1644445c46..97258f53ae 100644
--- a/engines/ags/engine/gui/gui_engine.cpp
+++ b/engines/ags/engine/gui/gui_engine.cpp
@@ -29,7 +29,7 @@
 // Headers, as they are in acgui.cpp
 #pragma unmanaged
 #include "ags/shared/ac/game_version.h"
-#include "ags/shared/ac/system.h"
+#include "ags/engine/ac/system.h"
 #include "ags/shared/font/fonts.h"
 #include "ags/shared/gui/guimain.h"
 #include "ags/shared/gui/guibutton.h"
@@ -38,11 +38,11 @@
 #include "ags/shared/gui/guitextbox.h"
 //include <ctype.h>
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/global_translation.h"
-#include "ags/shared/ac/string.h"
+#include "ags/engine/ac/global_translation.h"
+#include "ags/engine/ac/string.h"
 #include "ags/shared/ac/spritecache.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/gfx/blender.h"
+#include "ags/engine/gfx/blender.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gui/guidialog.cpp b/engines/ags/engine/gui/guidialog.cpp
index 261a43e17d..d2d2b71111 100644
--- a/engines/ags/engine/gui/guidialog.cpp
+++ b/engines/ags/engine/gui/guidialog.cpp
@@ -21,18 +21,20 @@
  */
 
 //include <cstdio>
-#include "ags/shared/gui/guidialog.h"
+#include "ags/engine/gui/guidialog.h"
 
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/game.h"
-#include "ags/shared/ac/gamesetup.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/game.h"
+#include "ags/engine/ac/gamesetup.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/gui/cscidialog.h"
+#include "ags/engine/gui/cscidialog.h"
 //include <cctype> //isdigit()
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/gfx/graphicsdriver.h"
-#include "ags/shared/debug/debug_log.h"
+#include "ags/engine/gfx/graphicsdriver.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "engines/savestate.h"
+#include "ags/ags.h"
 
 namespace AGS3 {
 
@@ -295,46 +297,24 @@ int savegamedialog() {
 void preparesavegamelist(int ctrllist) {
 	numsaves = 0;
 	toomanygames = 0;
-	al_ffblk ffb;
-	int bufix = 0;
-
-	String svg_dir = get_save_game_directory();
-	String svg_suff = get_save_game_suffix();
-	String searchPath = String::FromFormat("%s""agssave.*%s", svg_dir.GetCStr(), svg_suff.GetCStr());
-
-	int don = al_findfirst(searchPath, &ffb, -1);
-	while (!don) {
-		bufix = 0;
-		if (numsaves >= MAXSAVEGAMES) {
-			toomanygames = 1;
-			break;
-		}
 
-		// only list games .000 to .099 (to allow higher slots for other purposes)
-		if (strstr(ffb.name, ".0") == nullptr) {
-			don = al_findnext(&ffb);
-			continue;
-		}
+	// Get a list of savegames
+	SaveStateList saveList = ::AGS::g_vm->listSaves();
 
-		const char *numberExtension = strstr(ffb.name, ".0") + 1;
-		int sgNumber = atoi(numberExtension);
+	for (SaveStateList::iterator it = saveList.begin(); it != saveList.end(); ++it) {
+		Common::String desc = it->getDescription();
 
-		String thisGamePath = get_save_game_path(sgNumber);
+		// TODO: Casting pointer to long is nasty
+		CSCISendControlMessage(ctrllist, CLB_ADDITEM, 0, (long)desc.c_str());
 
-		// get description
-		String description;
-		read_savedgame_description(thisGamePath, description);
-
-		CSCISendControlMessage(ctrllist, CLB_ADDITEM, 0, (long)description.GetCStr());
 		// Select the first item
 		CSCISendControlMessage(ctrllist, CLB_SETCURSEL, 0, 0);
-		filenumbers[numsaves] = sgNumber;
-		filedates[numsaves] = (long int)ffb.time;
-		numsaves++;
-		don = al_findnext(&ffb);
+		filenumbers[numsaves] = it->getSaveSlot();
+		filedates[numsaves] = 0;		// TODO: How to handle file dates in ScummVM
+
+		++numsaves;
 	}
 
-	al_findclose(&ffb);
 	if (numsaves >= MAXSAVEGAMES)
 		toomanygames = 1;
 
@@ -442,7 +422,7 @@ int roomSelectorWindow(int currentRoom, int numRooms, int *roomNumbers, char **r
 		if (mes.code == CM_COMMAND) {
 			if (mes.id == ctrlok) {
 				CSCISendControlMessage(ctrltbox, CTB_GETTEXT, 0, (long)&buffer2[0]);
-				if (isdigit(buffer2[0])) {
+				if (Common::isDigit(buffer2[0])) {
 					toret = atoi(buffer2);
 				}
 			} else if (mes.id == ctrlcancel) {
diff --git a/engines/ags/engine/gui/guidialog.h b/engines/ags/engine/gui/guidialog.h
index dcca3af214..32d45ca77e 100644
--- a/engines/ags/engine/gui/guidialog.h
+++ b/engines/ags/engine/gui/guidialog.h
@@ -27,8 +27,8 @@ namespace AGS3 {
 namespace AGS {
 namespace Shared {
 class Bitmap;
-}
-}
+} // namespace Shared
+} // namespace AGS
 
 // Functions for handling hard-coded GUIs
 // Prepares GUI bitmaps which will be passed to the renderer's draw chain
diff --git a/engines/ags/engine/gui/guidialogdefines.h b/engines/ags/engine/gui/guidialogdefines.h
index 45404757b3..851257e110 100644
--- a/engines/ags/engine/gui/guidialogdefines.h
+++ b/engines/ags/engine/gui/guidialogdefines.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_GUI_GUIDIALOGDEFINES_H
 #define AGS_ENGINE_GUI_GUIDIALOGDEFINES_H
 
-#include "ags/shared/ac/gamesetup.h"
+#include "ags/engine/ac/gamesetup.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gui/guidialoginternaldefs.h b/engines/ags/engine/gui/guidialoginternaldefs.h
index 22c5373317..ea363da5d8 100644
--- a/engines/ags/engine/gui/guidialoginternaldefs.h
+++ b/engines/ags/engine/gui/guidialoginternaldefs.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_GUI_GUIDIALOGINTERNALDEFS_H
 #define AGS_ENGINE_GUI_GUIDIALOGINTERNALDEFS_H
 
-#include "ags/shared/gui/guidialogdefines.h"
+#include "ags/engine/gui/guidialogdefines.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gui/mycontrols.h b/engines/ags/engine/gui/mycontrols.h
index 5a1abee694..46b492cb85 100644
--- a/engines/ags/engine/gui/mycontrols.h
+++ b/engines/ags/engine/gui/mycontrols.h
@@ -29,9 +29,9 @@
 #ifndef AGS_ENGINE_GUI_MYCONTROLS_H
 #define AGS_ENGINE_GUI_MYCONTROLS_H
 
-#include "ags/shared/gui/mylabel.h"
-#include "ags/shared/gui/mylistbox.h"
-#include "ags/shared/gui/mypushbutton.h"
-#include "ags/shared/gui/mytextbox.h"
+#include "ags/engine/gui/mylabel.h"
+#include "ags/engine/gui/mylistbox.h"
+#include "ags/engine/gui/mypushbutton.h"
+#include "ags/engine/gui/mytextbox.h"
 
 #endif
diff --git a/engines/ags/engine/gui/mylabel.cpp b/engines/ags/engine/gui/mylabel.cpp
index 8af6ee0729..69a330b984 100644
--- a/engines/ags/engine/gui/mylabel.cpp
+++ b/engines/ags/engine/gui/mylabel.cpp
@@ -21,13 +21,13 @@
  */
 
 //include <string.h>
-#include "ags/shared/ac/display.h"
-#include "ags/shared/ac/gamesetup.h"
-#include "ags/shared/ac/string.h"
+#include "ags/engine/ac/display.h"
+#include "ags/engine/ac/gamesetup.h"
+#include "ags/engine/ac/string.h"
 #include "ags/shared/font/fonts.h"
 #include "ags/shared/gui/guidefines.h"
-#include "ags/shared/gui/mylabel.h"
-#include "ags/shared/gui/guidialoginternaldefs.h"
+#include "ags/engine/gui/mylabel.h"
+#include "ags/engine/gui/guidialoginternaldefs.h"
 
 namespace AGS3 {
 
@@ -59,7 +59,7 @@ void MyLabel::draw(Bitmap *ds) {
 	}
 }
 
-int MyLabel::pressedon(int mousex, int mousey) {
+int MyLabel::pressedon(int mouseX, int mouseY) {
 	return 0;
 }
 
diff --git a/engines/ags/engine/gui/mylabel.h b/engines/ags/engine/gui/mylabel.h
index b0b5ec733e..67cdc55082 100644
--- a/engines/ags/engine/gui/mylabel.h
+++ b/engines/ags/engine/gui/mylabel.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_GUI_MYLABEL_H
 #define AGS_ENGINE_GUI_MYLABEL_H
 
-#include "ags/shared/gui/newcontrol.h"
+#include "ags/engine/gui/newcontrol.h"
 
 namespace AGS3 {
 
@@ -33,7 +33,7 @@ struct MyLabel : public NewControl {
 
 	void draw(Shared::Bitmap *ds) override;
 
-	int pressedon(int mousex, int mousey) override;
+	int pressedon(int mouseX, int mouseY) override;
 
 	int processmessage(int mcode, int wParam, long lParam) override;
 };
diff --git a/engines/ags/engine/gui/mylistbox.cpp b/engines/ags/engine/gui/mylistbox.cpp
index 07e6ec1951..339cabce10 100644
--- a/engines/ags/engine/gui/mylistbox.cpp
+++ b/engines/ags/engine/gui/mylistbox.cpp
@@ -23,12 +23,12 @@
 //include <string.h>
 #include "ags/shared/util/wgt2allg.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/gamesetup.h"
+#include "ags/engine/ac/gamesetup.h"
 #include "ags/shared/font/fonts.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/gui/guidialog.h"
-#include "ags/shared/gui/guidialoginternaldefs.h"
-#include "ags/shared/gui/mylistbox.h"
+#include "ags/engine/gui/guidialog.h"
+#include "ags/engine/gui/guidialoginternaldefs.h"
+#include "ags/engine/gui/mylistbox.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gui/mylistbox.h b/engines/ags/engine/gui/mylistbox.h
index 4c54e317fa..b70b45ee4f 100644
--- a/engines/ags/engine/gui/mylistbox.h
+++ b/engines/ags/engine/gui/mylistbox.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_GUI_MYLISTBOX_H
 #define AGS_ENGINE_GUI_MYLISTBOX_H
 
-#include "ags/shared/gui/newcontrol.h"
+#include "ags/engine/gui/newcontrol.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gui/mypushbutton.cpp b/engines/ags/engine/gui/mypushbutton.cpp
index 6cdf81386b..7f462063e6 100644
--- a/engines/ags/engine/gui/mypushbutton.cpp
+++ b/engines/ags/engine/gui/mypushbutton.cpp
@@ -23,15 +23,15 @@
 //include <string.h>
 #include "ags/shared/util/wgt2allg.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/mouse.h"
+#include "ags/engine/ac/mouse.h"
 #include "ags/shared/font/fonts.h"
-#include "ags/shared/gui/mypushbutton.h"
-#include "ags/shared/gui/guidialog.h"
-#include "ags/shared/gui/guidialoginternaldefs.h"
-#include "ags/shared/main/game_run.h"
+#include "ags/engine/gui/mypushbutton.h"
+#include "ags/engine/gui/guidialog.h"
+#include "ags/engine/gui/guidialoginternaldefs.h"
+#include "ags/engine/main/game_run.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/platform/base/agsplatformdriver.h"
-#include "ags/shared/ac/timer.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
+#include "ags/engine/ac/timer.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gui/mypushbutton.h b/engines/ags/engine/gui/mypushbutton.h
index 5569656021..2ba6ca11ca 100644
--- a/engines/ags/engine/gui/mypushbutton.h
+++ b/engines/ags/engine/gui/mypushbutton.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_GUI_PUSHBUTTON_H
 #define AGS_ENGINE_GUI_PUSHBUTTON_H
 
-#include "ags/shared/gui/newcontrol.h"
+#include "ags/engine/gui/newcontrol.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gui/mytextbox.cpp b/engines/ags/engine/gui/mytextbox.cpp
index 898e8d7432..b0d45b0218 100644
--- a/engines/ags/engine/gui/mytextbox.cpp
+++ b/engines/ags/engine/gui/mytextbox.cpp
@@ -23,8 +23,8 @@
 //include <string.h>
 #include "ags/shared/util/wgt2allg.h"
 #include "ags/shared/font/fonts.h"
-#include "ags/shared/gui/mytextbox.h"
-#include "ags/shared/gui/guidialoginternaldefs.h"
+#include "ags/engine/gui/mytextbox.h"
+#include "ags/engine/gui/guidialoginternaldefs.h"
 #include "ags/shared/gfx/bitmap.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/gui/mytextbox.h b/engines/ags/engine/gui/mytextbox.h
index 46f9e7728b..a2a3e7d166 100644
--- a/engines/ags/engine/gui/mytextbox.h
+++ b/engines/ags/engine/gui/mytextbox.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_GUI_MYTEXTBOX_H
 #define AGS_ENGINE_GUI_MYTEXTBOX_H
 
-#include "ags/shared/gui/newcontrol.h"
+#include "ags/engine/gui/newcontrol.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gui/newcontrol.cpp b/engines/ags/engine/gui/newcontrol.cpp
index 6337fddbce..57f593ec54 100644
--- a/engines/ags/engine/gui/newcontrol.cpp
+++ b/engines/ags/engine/gui/newcontrol.cpp
@@ -20,9 +20,9 @@
  *
  */
 
-#include "ags/shared/gui/newcontrol.h"
-#include "ags/shared/gui/guidialog.h"
-#include "ags/shared/gui/guidialoginternaldefs.h"
+#include "ags/engine/gui/newcontrol.h"
+#include "ags/engine/gui/guidialog.h"
+#include "ags/engine/gui/guidialoginternaldefs.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/media/audio/audio.h b/engines/ags/engine/media/audio/audio.h
index 69d4bc71a4..42471bfd76 100644
--- a/engines/ags/engine/media/audio/audio.h
+++ b/engines/ags/engine/media/audio/audio.h
@@ -156,7 +156,7 @@ extern int crossFadeVolumeAtStart;
 extern SOUNDCLIP *cachedQueuedMusic;
 
 // TODO: double check that ambient sounds array actually needs +1
-extern std::array<AmbientSound> ambient(MAX_SOUND_CHANNELS + 1);
+extern std::array<AmbientSound> ambient;
 
 } // namespace AGS3
 
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index ad3dda27dd..86ff892941 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -77,6 +77,15 @@ MODULE_OBJS = \
 	shared/util/textstreamwriter.o \
 	shared/util/version.o \
 	shared/util/wgt2allg.o \
+	engine/gui/animatingguibutton.o \
+	engine/gui/cscidialog.o \
+	engine/gui/guidialog.o \
+	engine/gui/gui_engine.o \
+	engine/gui/mylabel.o \
+	engine/gui/mylistbox.o \
+	engine/gui/mypushbutton.o \
+	engine/gui/mytextbox.o \
+	engine/gui/newcontrol.o \
 	engine/main/config.o \
 	engine/main/engine.o \
 	engine/main/engine_setup.o \
diff --git a/engines/ags/shared/game/room_file.cpp b/engines/ags/shared/game/room_file.cpp
index 7ea092b11a..b39bb7059d 100644
--- a/engines/ags/shared/game/room_file.cpp
+++ b/engines/ags/shared/game/room_file.cpp
@@ -427,7 +427,7 @@ HRoomFileError ReadObjNamesBlock(RoomStruct *room, Stream *in, RoomFileVersion d
 // Room object script names
 HRoomFileError ReadObjScNamesBlock(RoomStruct *room, Stream *in, RoomFileVersion data_ver) {
 	int name_count = in->ReadByte();
-	if (name_count != room->ObjectCount)
+	if (name_count != (int)room->ObjectCount)
 		return new RoomFileError(kRoomFileErr_InconsistentData,
 			String::FromFormat("In the object script names block, expected name count: %d, got %d", room->ObjectCount, name_count));
 
diff --git a/engines/ags/shared/util/wgt2allg.h b/engines/ags/shared/util/wgt2allg.h
index 6126da9591..4ac8a969ed 100644
--- a/engines/ags/shared/util/wgt2allg.h
+++ b/engines/ags/shared/util/wgt2allg.h
@@ -34,6 +34,7 @@
 #define _WGT45_
 
 #include "ags/shared/core/platform.h"
+#include "ags/shared/core/types.h"
 #include "ags/lib/allegro.h"
 
 namespace AGS3 {


Commit: 68b3eb52d4a80d7d1dfe0fabce8fa9dd2814f0b5
    https://github.com/scummvm/scummvm/commit/68b3eb52d4a80d7d1dfe0fabce8fa9dd2814f0b5
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added engine/game/ folder

Changed paths:
    engines/ags/engine/ac/asset_helper.h
    engines/ags/engine/ac/characterextras.h
    engines/ags/engine/ac/draw.h
    engines/ags/engine/ac/dynobj/all_dynamicclasses.h
    engines/ags/engine/ac/dynobj/all_scriptclasses.h
    engines/ags/engine/ac/dynobj/cc_character.h
    engines/ags/engine/ac/dynobj/cc_dialog.h
    engines/ags/engine/ac/dynobj/cc_dynamicobject.h
    engines/ags/engine/ac/dynobj/cc_gui.h
    engines/ags/engine/ac/dynobj/cc_guiobject.h
    engines/ags/engine/ac/dynobj/cc_hotspot.h
    engines/ags/engine/ac/dynobj/cc_inventory.h
    engines/ags/engine/ac/dynobj/cc_object.h
    engines/ags/engine/ac/dynobj/cc_region.h
    engines/ags/engine/ac/dynobj/cc_serializer.h
    engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.h
    engines/ags/engine/ac/dynobj/scriptdynamicsprite.h
    engines/ags/engine/ac/movelist.h
    engines/ags/engine/ac/statobj/staticarray.h
    engines/ags/engine/device/mousew32.h
    engines/ags/engine/game/game_init.cpp
    engines/ags/engine/game/savegame.cpp
    engines/ags/engine/game/savegame_components.cpp
    engines/ags/engine/game/savegame_components.h
    engines/ags/engine/game/savegame_internal.h
    engines/ags/engine/game/viewport.cpp
    engines/ags/engine/media/audio/ambientsound.h
    engines/ags/engine/util/thread_pthread.h
    engines/ags/module.mk


diff --git a/engines/ags/engine/ac/asset_helper.h b/engines/ags/engine/ac/asset_helper.h
index 84604052ed..7c6160af7b 100644
--- a/engines/ags/engine/ac/asset_helper.h
+++ b/engines/ags/engine/ac/asset_helper.h
@@ -38,8 +38,9 @@ namespace AGS3 {
 namespace AGS {
 namespace Shared {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using AGS::Shared::Stream;
 using AGS::Shared::String;
 
diff --git a/engines/ags/engine/ac/characterextras.h b/engines/ags/engine/ac/characterextras.h
index 906282b5f5..67e6e568c2 100644
--- a/engines/ags/engine/ac/characterextras.h
+++ b/engines/ags/engine/ac/characterextras.h
@@ -31,8 +31,9 @@ namespace AGS3 {
 namespace AGS {
 namespace Shared {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 struct CharacterExtras {
diff --git a/engines/ags/engine/ac/draw.h b/engines/ags/engine/ac/draw.h
index 42437b6f9d..03901e7884 100644
--- a/engines/ags/engine/ac/draw.h
+++ b/engines/ags/engine/ac/draw.h
@@ -35,11 +35,13 @@ namespace AGS {
 namespace Shared {
 class Bitmap;
 typedef std::shared_ptr<Shared::Bitmap> PBitmap;
-}
+} // namespace Shared
+
 namespace Engine {
 class IDriverDependantBitmap;
-}
-}
+} // namespace Engine
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 #define IS_ANTIALIAS_SPRITES usetup.enable_antialiasing && (play.disable_antialiasing == 0)
diff --git a/engines/ags/engine/ac/dynobj/all_dynamicclasses.h b/engines/ags/engine/ac/dynobj/all_dynamicclasses.h
index f597b28a47..da01ed1ce1 100644
--- a/engines/ags/engine/ac/dynobj/all_dynamicclasses.h
+++ b/engines/ags/engine/ac/dynobj/all_dynamicclasses.h
@@ -23,18 +23,18 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_ALLDYNAMICCLASSES_H
 #define AGS_ENGINE_AC_DYNOBJ_ALLDYNAMICCLASSES_H
 
-#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
-#include "ags/shared/ac/dynobj/cc_audiochannel.h"
-#include "ags/shared/ac/dynobj/cc_audioclip.h"
-#include "ags/shared/ac/dynobj/cc_character.h"
-#include "ags/shared/ac/dynobj/cc_dialog.h"
-#include "ags/shared/ac/dynobj/cc_gui.h"
-#include "ags/shared/ac/dynobj/cc_guiobject.h"
-#include "ags/shared/ac/dynobj/cc_hotspot.h"
-#include "ags/shared/ac/dynobj/cc_inventory.h"
-#include "ags/shared/ac/dynobj/cc_object.h"
-#include "ags/shared/ac/dynobj/cc_region.h"
+#include "ags/engine/ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/engine/ac/dynobj/cc_audiochannel.h"
+#include "ags/engine/ac/dynobj/cc_audioclip.h"
+#include "ags/engine/ac/dynobj/cc_character.h"
+#include "ags/engine/ac/dynobj/cc_dialog.h"
+#include "ags/engine/ac/dynobj/cc_gui.h"
+#include "ags/engine/ac/dynobj/cc_guiobject.h"
+#include "ags/engine/ac/dynobj/cc_hotspot.h"
+#include "ags/engine/ac/dynobj/cc_inventory.h"
+#include "ags/engine/ac/dynobj/cc_object.h"
+#include "ags/engine/ac/dynobj/cc_region.h"
 
-#include "ags/shared/ac/dynobj/cc_serializer.h"
+#include "ags/engine/ac/dynobj/cc_serializer.h"
 
 #endif
diff --git a/engines/ags/engine/ac/dynobj/all_scriptclasses.h b/engines/ags/engine/ac/dynobj/all_scriptclasses.h
index 7c3c72b9c5..5d533fa9b9 100644
--- a/engines/ags/engine/ac/dynobj/all_scriptclasses.h
+++ b/engines/ags/engine/ac/dynobj/all_scriptclasses.h
@@ -23,20 +23,20 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_ALLSCRIPTCLASSES_H
 #define AGS_ENGINE_AC_DYNOBJ_ALLSCRIPTCLASSES_H
 
-#include "ags/shared/ac/dynobj/scriptdatetime.h"
-#include "ags/shared/ac/dynobj/scriptdialog.h"
-#include "ags/shared/ac/dynobj/scriptdialogoptionsrendering.h"
-#include "ags/shared/ac/dynobj/scriptdrawingsurface.h"
-#include "ags/shared/ac/dynobj/scriptdynamicsprite.h"
-#include "ags/shared/ac/dynobj/scriptgui.h"
-#include "ags/shared/ac/dynobj/scripthotspot.h"
-#include "ags/shared/ac/dynobj/scriptinvitem.h"
-#include "ags/shared/ac/dynobj/scriptmouse.h"
-#include "ags/shared/ac/dynobj/scriptobject.h"
-#include "ags/shared/ac/dynobj/scriptoverlay.h"
-#include "ags/shared/ac/dynobj/scriptregion.h"
-#include "ags/shared/ac/dynobj/scriptstring.h"
-#include "ags/shared/ac/dynobj/scriptsystem.h"
-#include "ags/shared/ac/dynobj/scriptviewframe.h"
+#include "ags/engine/ac/dynobj/scriptdatetime.h"
+#include "ags/engine/ac/dynobj/scriptdialog.h"
+#include "ags/engine/ac/dynobj/scriptdialogoptionsrendering.h"
+#include "ags/engine/ac/dynobj/scriptdrawingsurface.h"
+#include "ags/engine/ac/dynobj/scriptdynamicsprite.h"
+#include "ags/engine/ac/dynobj/scriptgui.h"
+#include "ags/engine/ac/dynobj/scripthotspot.h"
+#include "ags/engine/ac/dynobj/scriptinvitem.h"
+#include "ags/engine/ac/dynobj/scriptmouse.h"
+#include "ags/engine/ac/dynobj/scriptobject.h"
+#include "ags/engine/ac/dynobj/scriptoverlay.h"
+#include "ags/engine/ac/dynobj/scriptregion.h"
+#include "ags/engine/ac/dynobj/scriptstring.h"
+#include "ags/engine/ac/dynobj/scriptsystem.h"
+#include "ags/engine/ac/dynobj/scriptviewframe.h"
 
 #endif
diff --git a/engines/ags/engine/ac/dynobj/cc_character.h b/engines/ags/engine/ac/dynobj/cc_character.h
index b75cd6a351..8c800ec846 100644
--- a/engines/ags/engine/ac/dynobj/cc_character.h
+++ b/engines/ags/engine/ac/dynobj/cc_character.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_CCCHARACTER_H
 #define AGS_ENGINE_AC_DYNOBJ_CCCHARACTER_H
 
-#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/engine/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_dialog.h b/engines/ags/engine/ac/dynobj/cc_dialog.h
index a7c4954af5..061892734d 100644
--- a/engines/ags/engine/ac/dynobj/cc_dialog.h
+++ b/engines/ags/engine/ac/dynobj/cc_dialog.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_CCDIALOG_H
 #define AGS_ENGINE_AC_DYNOBJ_CCDIALOG_H
 
-#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/engine/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicobject.h b/engines/ags/engine/ac/dynobj/cc_dynamicobject.h
index 8e73a593f3..469aaa3503 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicobject.h
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicobject.h
@@ -38,8 +38,9 @@ namespace AGS3 {
 namespace AGS {
 namespace Shared {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 // A pair of managed handle and abstract object pointer
diff --git a/engines/ags/engine/ac/dynobj/cc_gui.h b/engines/ags/engine/ac/dynobj/cc_gui.h
index c338625807..311684d656 100644
--- a/engines/ags/engine/ac/dynobj/cc_gui.h
+++ b/engines/ags/engine/ac/dynobj/cc_gui.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_CCGUI_H
 #define AGS_ENGINE_AC_DYNOBJ_CCGUI_H
 
-#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/engine/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_guiobject.h b/engines/ags/engine/ac/dynobj/cc_guiobject.h
index 4da35e1394..6f1911e867 100644
--- a/engines/ags/engine/ac/dynobj/cc_guiobject.h
+++ b/engines/ags/engine/ac/dynobj/cc_guiobject.h
@@ -20,10 +20,10 @@
  *
  */
 
-#ifndef AGS_ENGINE_AC_DYNOBJ_CCGUI_H
-#define AGS_ENGINE_AC_DYNOBJ_CCGUI_H
+#ifndef AGS_ENGINE_AC_DYNOBJ_CCGUIOBJECT_H
+#define AGS_ENGINE_AC_DYNOBJ_CCGUIOBJECT_H
 
-#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/engine/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_hotspot.h b/engines/ags/engine/ac/dynobj/cc_hotspot.h
index 3a1beb8e61..1677a49295 100644
--- a/engines/ags/engine/ac/dynobj/cc_hotspot.h
+++ b/engines/ags/engine/ac/dynobj/cc_hotspot.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_CCHOTSPOT_H
 #define AGS_ENGINE_AC_DYNOBJ_CCHOTSPOT_H
 
-#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/engine/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_inventory.h b/engines/ags/engine/ac/dynobj/cc_inventory.h
index 10edec6e0c..0687ebb54c 100644
--- a/engines/ags/engine/ac/dynobj/cc_inventory.h
+++ b/engines/ags/engine/ac/dynobj/cc_inventory.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_CCINVENTORY_H
 #define AGS_ENGINE_AC_DYNOBJ_CCINVENTORY_H
 
-#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/engine/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_object.h b/engines/ags/engine/ac/dynobj/cc_object.h
index 789e8c196f..a6d77cc759 100644
--- a/engines/ags/engine/ac/dynobj/cc_object.h
+++ b/engines/ags/engine/ac/dynobj/cc_object.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_CCOBJECT_H
 #define AGS_ENGINE_AC_DYNOBJ_CCOBJECT_H
 
-#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/engine/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_region.h b/engines/ags/engine/ac/dynobj/cc_region.h
index c0a21cffd4..927b2e874b 100644
--- a/engines/ags/engine/ac/dynobj/cc_region.h
+++ b/engines/ags/engine/ac/dynobj/cc_region.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_CCREGION_H
 #define AGS_ENGINE_AC_DYNOBJ_CCREGION_H
 
-#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/engine/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_serializer.h b/engines/ags/engine/ac/dynobj/cc_serializer.h
index 2d16667228..54458ead27 100644
--- a/engines/ags/engine/ac/dynobj/cc_serializer.h
+++ b/engines/ags/engine/ac/dynobj/cc_serializer.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_CCSERIALIZER_H
 #define AGS_ENGINE_AC_DYNOBJ_CCSERIALIZER_H
 
-#include "ags/shared/ac/dynobj/cc_dynamicobject.h"
+#include "ags/engine/ac/dynobj/cc_dynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.h b/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.h
index 7a6bdf2d8d..43d34d9f2c 100644
--- a/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.h
+++ b/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTDIALOGOPTIONSRENDERING_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTDIALOGOPTIONSRENDERING_H
 
-#include "ags/shared/ac/dynobj/scriptdrawingsurface.h"
+#include "ags/engine/ac/dynobj/scriptdrawingsurface.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptdynamicsprite.h b/engines/ags/engine/ac/dynobj/scriptdynamicsprite.h
index 3418840f05..82bb60d7f3 100644
--- a/engines/ags/engine/ac/dynobj/scriptdynamicsprite.h
+++ b/engines/ags/engine/ac/dynobj/scriptdynamicsprite.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTDYNAMICSPRITE_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTDYNAMICSPRITE_H
 
-#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/engine/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/movelist.h b/engines/ags/engine/ac/movelist.h
index b950ffe44b..d9672b1d80 100644
--- a/engines/ags/engine/ac/movelist.h
+++ b/engines/ags/engine/ac/movelist.h
@@ -34,6 +34,7 @@ namespace Shared {
 class Stream;
 } // namespace Shared
 } // namespace AGS
+
 using namespace AGS; // FIXME later
 
 #define MAXNEEDSTAGES 256
diff --git a/engines/ags/engine/ac/statobj/staticarray.h b/engines/ags/engine/ac/statobj/staticarray.h
index 3940708f10..6176dc4384 100644
--- a/engines/ags/engine/ac/statobj/staticarray.h
+++ b/engines/ags/engine/ac/statobj/staticarray.h
@@ -23,7 +23,7 @@
 #ifndef _AGS_ENGINE_AC_STATICOBJ_STATICARRAY_H
 #define _AGS_ENGINE_AC_STATICOBJ_STATICARRAY_H
 
-#include "ags/shared/ac/statobj/staticobject.h"
+#include "ags/engine/ac/statobj/staticobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/device/mousew32.h b/engines/ags/engine/device/mousew32.h
index 6662320676..87185517de 100644
--- a/engines/ags/engine/device/mousew32.h
+++ b/engines/ags/engine/device/mousew32.h
@@ -61,6 +61,7 @@ void msethotspot(int xx, int yy);
 int minstalled();
 
 namespace Mouse {
+
 // Get if mouse is locked to the game window
 bool IsLockedToWindow();
 // Try locking mouse to the game window
@@ -82,9 +83,11 @@ float GetSpeedUnit();
 void SetSpeed(float speed);
 // Get speed factor
 float GetSpeed();
-}
+
+} // namespace Mouse
 
 namespace Mouse {
+
 // Updates limits of the area inside which the standard OS cursor is not shown;
 // uses game's main viewport (in native coordinates) to calculate real area on screen
 void SetGraphicArea();
@@ -93,7 +96,8 @@ void SetGraphicArea();
 void SetMoveLimit(const Rect &r);
 // Set actual OS cursor position on screen; parameter must be in native game coordinates
 void SetPosition(const Point p);
-}
+
+} // namespace Mouse
 
 
 extern int mousex, mousey;
diff --git a/engines/ags/engine/game/game_init.cpp b/engines/ags/engine/game/game_init.cpp
index 3836f46af7..8de53db9a1 100644
--- a/engines/ags/engine/game/game_init.cpp
+++ b/engines/ags/engine/game/game_init.cpp
@@ -20,36 +20,36 @@
  *
  */
 
-#include "ags/shared/ac/character.h"
-#include "ags/shared/ac/charactercache.h"
-#include "ags/shared/ac/dialog.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/file.h"
-#include "ags/shared/ac/game.h"
-#include "ags/shared/ac/gamesetup.h"
+#include "ags/engine/ac/character.h"
+#include "ags/engine/ac/charactercache.h"
+#include "ags/engine/ac/dialog.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/file.h"
+#include "ags/engine/ac/game.h"
+#include "ags/engine/ac/gamesetup.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/gui.h"
-#include "ags/shared/ac/movelist.h"
-#include "ags/shared/ac/dynobj/all_dynamicclasses.h"
-#include "ags/shared/ac/dynobj/all_scriptclasses.h"
-#include "ags/shared/ac/statobj/agsstaticobject.h"
-#include "ags/shared/ac/statobj/staticarray.h"
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/debug/out.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/gui.h"
+#include "ags/engine/ac/movelist.h"
+#include "ags/engine/ac/dynobj/all_dynamicclasses.h"
+#include "ags/engine/ac/dynobj/all_scriptclasses.h"
+#include "ags/engine/ac/statobj/agsstaticobject.h"
+#include "ags/engine/ac/statobj/staticarray.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/shared/debugging/out.h"
 #include "ags/shared/font/agsfontrenderer.h"
 #include "ags/shared/font/fonts.h"
-#include "ags/shared/game/game_init.h"
+#include "ags/engine/game/game_init.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/gfx/ddb.h"
+#include "ags/engine/gfx/ddb.h"
 #include "ags/shared/gui/guilabel.h"
-#include "ags/shared/plugin/plugin_engine.h"
+#include "ags/engine/plugin/plugin_engine.h"
 #include "ags/shared/script/cc_error.h"
-#include "ags/shared/script/exports.h"
-#include "ags/shared/script/script.h"
-#include "ags/shared/script/script_runtime.h"
+#include "ags/engine/script/exports.h"
+#include "ags/engine/script/script.h"
+#include "ags/engine/script/script_runtime.h"
 #include "ags/shared/util/string_utils.h"
-#include "ags/shared/media/audio/audio_system.h"
+#include "ags/engine/media/audio/audio_system.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/game/savegame.cpp b/engines/ags/engine/game/savegame.cpp
index cc8f5bbd88..b9678c25e6 100644
--- a/engines/ags/engine/game/savegame.cpp
+++ b/engines/ags/engine/game/savegame.cpp
@@ -20,47 +20,48 @@
  *
  */
 
-#include "ags/shared/ac/character.h"
+#include "ags/engine/ac/character.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/dynamicsprite.h"
-#include "ags/shared/ac/event.h"
-#include "ags/shared/ac/game.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/dynamicsprite.h"
+#include "ags/engine/ac/event.h"
+#include "ags/engine/ac/game.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/gamesetup.h"
-#include "ags/shared/ac/global_audio.h"
-#include "ags/shared/ac/global_character.h"
-#include "ags/shared/ac/gui.h"
-#include "ags/shared/ac/mouse.h"
-#include "ags/shared/ac/overlay.h"
-#include "ags/shared/ac/region.h"
-#include "ags/shared/ac/richgamemedia.h"
-#include "ags/shared/ac/room.h"
-#include "ags/shared/ac/roomstatus.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/gamesetup.h"
+#include "ags/engine/ac/global_audio.h"
+#include "ags/engine/ac/global_character.h"
+#include "ags/engine/ac/gui.h"
+#include "ags/engine/ac/mouse.h"
+#include "ags/engine/ac/overlay.h"
+#include "ags/engine/ac/region.h"
+#include "ags/engine/ac/richgamemedia.h"
+#include "ags/engine/ac/room.h"
+#include "ags/engine/ac/roomstatus.h"
 #include "ags/shared/ac/spritecache.h"
-#include "ags/shared/ac/system.h"
-#include "ags/shared/ac/timer.h"
-#include "ags/shared/debug/out.h"
-#include "ags/shared/device/mousew32.h"
+#include "ags/engine/ac/system.h"
+#include "ags/engine/ac/timer.h"
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/device/mousew32.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/gfx/ddb.h"
-#include "ags/shared/gfx/graphicsdriver.h"
-#include "ags/shared/game/savegame.h"
-#include "ags/shared/game/savegame_components.h"
-#include "ags/shared/game/savegame_internal.h"
-#include "ags/shared/main/engine.h"
-#include "ags/shared/main/main.h"
-#include "ags/shared/platform/base/agsplatformdriver.h"
-#include "ags/shared/plugin/agsplugin.h"
-#include "ags/shared/plugin/plugin_engine.h"
-#include "ags/shared/script/script.h"
+#include "ags/engine/gfx/ddb.h"
+#include "ags/engine/gfx/graphicsdriver.h"
+#include "ags/engine/game/savegame.h"
+#include "ags/engine/game/savegame_components.h"
+#include "ags/engine/game/savegame_internal.h"
+#include "ags/engine/main/engine.h"
+#include "ags/engine/main/main.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
+#include "ags/engine/plugin/agsplugin.h"
+#include "ags/engine/plugin/plugin_engine.h"
+#include "ags/engine/script/script.h"
 #include "ags/shared/script/cc_error.h"
 #include "ags/shared/util/alignedstream.h"
 #include "ags/shared/util/file.h"
 #include "ags/shared/util/stream.h"
 #include "ags/shared/util/string_utils.h"
-#include "ags/shared/media/audio/audio_system.h"
+#include "ags/engine/media/audio/audio_system.h"
+#include "ags/ags.h"
 
 namespace AGS3 {
 
@@ -507,7 +508,7 @@ HSaveError DoAfterRestore(const PreservedParams &pp, const RestoredData &r_data)
 	// ensure that the current cursor is locked
 	spriteset.Precache(game.mcurs[r_data.CursorID].pic);
 
-	set_window_title(play.game_name);
+	::AGS::g_vm->set_window_title(play.game_name);
 
 	update_polled_stuff_if_runtime();
 
@@ -680,8 +681,16 @@ void WriteDescription(Stream *out, const String &user_text, const Bitmap *user_i
 	WriteSaveImage(out, user_image);
 }
 
+static void uconvert(const char *src, unsigned short *dest, int maxSize) {
+	do {
+		*dest++ = *src;
+	} while (*src++ != 0 && --maxSize > 1);
+
+	*dest = '\0';
+}
+
 PStream StartSavegame(const String &filename, const String &user_text, const Bitmap *user_image) {
-	Stream *out = Common::File::CreateFile(filename);
+	Stream *out = Shared::File::CreateFile(filename);
 	if (!out)
 		return PStream();
 
@@ -695,8 +704,15 @@ PStream StartSavegame(const String &filename, const String &user_text, const Bit
 	vistaHeader.dwThumbnailOffsetLowerDword = 0;
 	vistaHeader.dwThumbnailSize = 0;
 	convert_guid_from_text_to_binary(game.guid, &vistaHeader.guidGameId[0]);
+
+#if 1
+	Common::String name = Common::String::format("%s %s", game.gamename, user_text.GetNullableCStr());
+	uconvert(name.c_str(), vistaHeader.szSaveName, RM_MAXLENGTH);
+#else
 	uconvert(game.gamename, U_ASCII, (char *)&vistaHeader.szGameName[0], U_UNICODE, RM_MAXLENGTH);
 	uconvert(user_text, U_ASCII, (char *)&vistaHeader.szSaveName[0], U_UNICODE, RM_MAXLENGTH);
+#endif
+
 	vistaHeader.szLevelName[0] = 0;
 	vistaHeader.szComments[0] = 0;
 	// MS Windows Vista rich media header
diff --git a/engines/ags/engine/game/savegame_components.cpp b/engines/ags/engine/game/savegame_components.cpp
index 1e558819f9..55c30b4417 100644
--- a/engines/ags/engine/game/savegame_components.cpp
+++ b/engines/ags/engine/game/savegame_components.cpp
@@ -23,29 +23,29 @@
 //include <map>
 
 #include "ags/shared/ac/audiocliptype.h"
-#include "ags/shared/ac/character.h"
+#include "ags/engine/ac/character.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/dialogtopic.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/dynamicsprite.h"
-#include "ags/shared/ac/game.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/dynamicsprite.h"
+#include "ags/engine/ac/game.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/gui.h"
-#include "ags/shared/ac/mouse.h"
-#include "ags/shared/ac/movelist.h"
-#include "ags/shared/ac/overlay.h"
-#include "ags/shared/ac/roomstatus.h"
-#include "ags/shared/ac/screenoverlay.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/gui.h"
+#include "ags/engine/ac/mouse.h"
+#include "ags/engine/ac/movelist.h"
+#include "ags/engine/ac/overlay.h"
+#include "ags/engine/ac/roomstatus.h"
+#include "ags/engine/ac/screenoverlay.h"
 #include "ags/shared/ac/spritecache.h"
 #include "ags/shared/ac/view.h"
-#include "ags/shared/ac/system.h"
-#include "ags/shared/ac/dynobj/cc_serializer.h"
-#include "ags/shared/debug/out.h"
-#include "ags/shared/game/savegame_components.h"
-#include "ags/shared/game/savegame_internal.h"
+#include "ags/engine/ac/system.h"
+#include "ags/engine/ac/dynobj/cc_serializer.h"
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/game/savegame_components.h"
+#include "ags/engine/game/savegame_internal.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/gui/animatingguibutton.h"
+#include "ags/engine/gui/animatingguibutton.h"
 #include "ags/shared/gui/guibutton.h"
 #include "ags/shared/gui/guiinv.h"
 #include "ags/shared/gui/guilabel.h"
@@ -53,12 +53,12 @@
 #include "ags/shared/gui/guimain.h"
 #include "ags/shared/gui/guislider.h"
 #include "ags/shared/gui/guitextbox.h"
-#include "ags/shared/plugin/agsplugin.h"
-#include "ags/shared/plugin/plugin_engine.h"
+#include "ags/engine/plugin/agsplugin.h"
+#include "ags/engine/plugin/plugin_engine.h"
 #include "ags/shared/script/cc_error.h"
-#include "ags/shared/script/script.h"
+#include "ags/engine/script/script.h"
 #include "ags/shared/util/filestream.h" // TODO: needed only because plugins expect file handle
-#include "ags/shared/media/audio/audio_system.h"
+#include "ags/engine/media/audio/audio_system.h"
 
 namespace AGS3 {
 
@@ -1183,7 +1183,7 @@ HSaveError ReadComponent(PStream in, SvgCmpReadHelper &hlp, ComponentInfo &info)
 	const ComponentHandler *handler = nullptr;
 	std::map<String, ComponentHandler>::const_iterator it_hdr = hlp.Handlers.find(info.Name);
 	if (it_hdr != hlp.Handlers.end())
-		handler = &it_hdr->second;
+		handler = &it_hdr->_value;
 
 	if (!handler || !handler->Unserialize)
 		return new SavegameError(kSvgErr_UnsupportedComponent);
diff --git a/engines/ags/engine/game/savegame_components.h b/engines/ags/engine/game/savegame_components.h
index 18cfb46a6f..db3b2b4442 100644
--- a/engines/ags/engine/game/savegame_components.h
+++ b/engines/ags/engine/game/savegame_components.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_GAME_SAVEGAMECOMPONENTS_H
 #define AGS_ENGINE_GAME_SAVEGAMECOMPONENTS_H
 
-#include "ags/shared/game/savegame.h"
+#include "ags/engine/game/savegame.h"
 #include "ags/shared/util/stream.h"
 
 namespace AGS3 {
@@ -60,5 +60,6 @@ void ReadLegacyCameraState(Stream *in, RestoredData &r_data);
 
 } // namespace Engine
 } // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/game/savegame_internal.h b/engines/ags/engine/game/savegame_internal.h
index 713c662d9d..5db638911e 100644
--- a/engines/ags/engine/game/savegame_internal.h
+++ b/engines/ags/engine/game/savegame_internal.h
@@ -27,13 +27,13 @@
 #include "ags/std/vector.h"
 #include "ags/shared/ac/common_defines.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/media/audio/audiodefines.h"
+#include "ags/engine/media/audio/audiodefines.h"
 
 namespace AGS3 {
 namespace AGS {
 namespace Engine {
 
-using AGS::Shared::Bitmap;
+using Shared::Bitmap;
 
 typedef std::shared_ptr<Bitmap> PBitmap;
 
diff --git a/engines/ags/engine/game/viewport.cpp b/engines/ags/engine/game/viewport.cpp
index cc5415f8b3..c4484dd765 100644
--- a/engines/ags/engine/game/viewport.cpp
+++ b/engines/ags/engine/game/viewport.cpp
@@ -20,11 +20,11 @@
  *
  */
 
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/debug/debug_log.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/debugging/debug_log.h"
 #include "ags/shared/game/roomstruct.h"
-#include "ags/shared/game/viewport.h"
+#include "ags/engine/game/viewport.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/media/audio/ambientsound.h b/engines/ags/engine/media/audio/ambientsound.h
index 3d042ccb98..fe24a81ce7 100644
--- a/engines/ags/engine/media/audio/ambientsound.h
+++ b/engines/ags/engine/media/audio/ambientsound.h
@@ -29,8 +29,9 @@ namespace AGS3 {
 namespace AGS {
 namespace Shared {
 class Stream;
-}
-}
+} // namespace Shared
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 #define AMBIENCE_FULL_DIST 25
diff --git a/engines/ags/engine/util/thread_pthread.h b/engines/ags/engine/util/thread_pthread.h
index 66b73e80b6..83108f5c6e 100644
--- a/engines/ags/engine/util/thread_pthread.h
+++ b/engines/ags/engine/util/thread_pthread.h
@@ -28,7 +28,8 @@
 namespace AGS3 {
 namespace AGS {
 namespace Engine {
-//include <class PThreadThread : public BaseThread {
+
+class PThreadThread : public BaseThread {
 public:
 	PThreadThread() {
 		_thread = 0;
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 86ff892941..da2c5b0612 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -77,6 +77,10 @@ MODULE_OBJS = \
 	shared/util/textstreamwriter.o \
 	shared/util/version.o \
 	shared/util/wgt2allg.o \
+	engine/game/game_init.o \
+	engine/game/savegame.o \
+	engine/game/savegame_components.o \
+	engine/game/viewport.o \
 	engine/gui/animatingguibutton.o \
 	engine/gui/cscidialog.o \
 	engine/gui/guidialog.o \


Commit: 6ce1206bbd2c42004a792fa807d5d086ea118051
    https://github.com/scummvm/scummvm/commit/6ce1206bbd2c42004a792fa807d5d086ea118051
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added engine/font/ folder

Changed paths:
    engines/ags/module.mk


diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index da2c5b0612..e8c6b7639a 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -77,6 +77,7 @@ MODULE_OBJS = \
 	shared/util/textstreamwriter.o \
 	shared/util/version.o \
 	shared/util/wgt2allg.o \
+	engine/font/fonts_engine.o \
 	engine/game/game_init.o \
 	engine/game/savegame.o \
 	engine/game/savegame_components.o \


Commit: ee48881da4e08845b38d217c7631b28741037e15
    https://github.com/scummvm/scummvm/commit/ee48881da4e08845b38d217c7631b28741037e15
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added engine/platform/ folder

Changed paths:
  A engines/ags/lib/system/datetime.cpp
  A engines/ags/lib/system/datetime.h
    engines/ags/engine/main/game_start.cpp
    engines/ags/engine/platform/base/agsplatformdriver.cpp
    engines/ags/engine/platform/base/agsplatformdriver.h
    engines/ags/lib/allegro.h
    engines/ags/lib/allegro/keyboard.h
    engines/ags/module.mk
    engines/ags/std/thread.h


diff --git a/engines/ags/engine/main/game_start.cpp b/engines/ags/engine/main/game_start.cpp
index df57f42753..681ee8f858 100644
--- a/engines/ags/engine/main/game_start.cpp
+++ b/engines/ags/engine/main/game_start.cpp
@@ -125,7 +125,7 @@ void do_start_game() {
 }
 
 void initialize_start_and_play_game(int override_start_room, const char *loadSaveOnStartup) {
-	try { // BEGIN try for ALI3DEXception
+//	try { // BEGIN try for ALI3DEXception
 
 		set_cursor_mode(MODE_WALK);
 
@@ -154,9 +154,9 @@ void initialize_start_and_play_game(int override_start_room, const char *loadSav
 
 		RunGameUntilAborted();
 
-	} catch (Ali3DException gfxException) {
-		quit((char *)gfxException._message);
-	}
+//	} catch (Ali3DException gfxException) {
+//		quit((char *)gfxException._message);
+//	}
 }
 
 } // namespace AGS3
diff --git a/engines/ags/engine/platform/base/agsplatformdriver.cpp b/engines/ags/engine/platform/base/agsplatformdriver.cpp
index 0d0a624ffc..11d4e585eb 100644
--- a/engines/ags/engine/platform/base/agsplatformdriver.cpp
+++ b/engines/ags/engine/platform/base/agsplatformdriver.cpp
@@ -26,27 +26,28 @@
 //
 //=============================================================================
 
-//include <thread>
 #include "ags/shared/util/wgt2allg.h"
-#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/runtime_defines.h"
+#include "ags/engine/ac/runtime_defines.h"
 #include "ags/shared/util/string_utils.h"
 #include "ags/shared/util/stream.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/plugin/agsplugin.h"
-#include "ags/shared/ac/timer.h"
-#include "ags/shared/media/audio/audio_system.h"
+#include "ags/engine/plugin/agsplugin.h"
+#include "ags/engine/ac/timer.h"
+#include "ags/engine/media/audio/audio_system.h"
+#include "ags/lib/system/datetime.h"
+#include "ags/std/algorithm.h"
+
+#if defined (AGS_HAS_CD_AUDIO)
+#include "libcda.h"
+#endif
 
 namespace AGS3 {
 
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
-#if defined (AGS_HAS_CD_AUDIO)
-#include "ags/shared/libcda.h"
-#endif
-
 // We don't have many places where we delay longer than a frame, but where we
 // do, we should give the audio layer a chance to update.
 // 16 milliseconds is rough period for 60fps
@@ -99,36 +100,37 @@ const char *AGSPlatformDriver::GetDiskWriteAccessTroubleshootingText() {
 }
 
 void AGSPlatformDriver::GetSystemTime(ScriptDateTime *sdt) {
-	time_t t = time(nullptr);
+	time_t t = getUnixTime();
 
 	//note: subject to year 2038 problem due to shoving time_t in an integer
 	sdt->rawUnixTime = static_cast<int>(t);
 
-	struct tm *newtime = localtime(&t);
-	sdt->hour = newtime->tm_hour;
-	sdt->minute = newtime->tm_min;
-	sdt->second = newtime->tm_sec;
-	sdt->day = newtime->tm_mday;
-	sdt->month = newtime->tm_mon + 1;
-	sdt->year = newtime->tm_year + 1900;
+	tm newTime;
+	localTime(&newTime);
+	sdt->hour = newTime.tm_hour;
+	sdt->minute = newTime.tm_min;
+	sdt->second = newTime.tm_sec;
+	sdt->day = newTime.tm_mday;
+	sdt->month = newTime.tm_mon + 1;
+	sdt->year = newTime.tm_year + 1900;
 }
 
 void AGSPlatformDriver::WriteStdOut(const char *fmt, ...) {
 	va_list args;
 	va_start(args, fmt);
-	vprintf(fmt, args);
+	Common::String str = Common::String::vformat(fmt, args);
 	va_end(args);
-	printf("\n");
-	fflush(stdout);
+
+	debug("%s\n", str.c_str());
 }
 
 void AGSPlatformDriver::WriteStdErr(const char *fmt, ...) {
 	va_list args;
 	va_start(args, fmt);
-	vfprintf(stderr, fmt, args);
+	Common::String str = Common::String::vformat(fmt, args);
 	va_end(args);
-	fprintf(stderr, "\n");
-	fflush(stdout);
+
+	debug("ERROR: %s\n", str.c_str());
 }
 
 void AGSPlatformDriver::YieldCPU() {
@@ -242,7 +244,7 @@ void AGSPlatformDriver::Delay(int millis) {
 			break;
 		}
 
-		auto duration = std::min<std::chrono::nanoseconds>(delayUntil - now, MaximumDelayBetweenPolling);
+		auto duration = std::min<std::chrono::milliseconds>(delayUntil - now, MaximumDelayBetweenPolling);
 		std::this_thread::sleep_for(duration);
 		now = AGS_Clock::now(); // update now
 
diff --git a/engines/ags/engine/platform/base/agsplatformdriver.h b/engines/ags/engine/platform/base/agsplatformdriver.h
index 4363cb7fbb..5a2023c6cc 100644
--- a/engines/ags/engine/platform/base/agsplatformdriver.h
+++ b/engines/ags/engine/platform/base/agsplatformdriver.h
@@ -40,11 +40,13 @@ namespace AGS3 {
 namespace AGS {
 namespace Shared {
 class Stream;
-}
+} // namespace Shared
+
 namespace Engine {
 struct DisplayMode;
-}
-}
+} // namespace Engine
+} // namespace AGS
+
 using namespace AGS; // FIXME later
 
 enum eScriptSystemOSID {
diff --git a/engines/ags/lib/allegro.h b/engines/ags/lib/allegro.h
index 662c673958..4667540d0f 100644
--- a/engines/ags/lib/allegro.h
+++ b/engines/ags/lib/allegro.h
@@ -20,7 +20,9 @@
  *
  */
 
-#ifndef ALLEGRO_H
+#ifndef AGS_LIB_ALLEGRO_H
+#define AGS_LIB_ALLEGRO_H
+
 #define ALLEGRO_H
 
 #include "ags/lib/allegro/alconfig.h"
diff --git a/engines/ags/lib/allegro/keyboard.h b/engines/ags/lib/allegro/keyboard.h
index cd6d804ec3..06187120f6 100644
--- a/engines/ags/lib/allegro/keyboard.h
+++ b/engines/ags/lib/allegro/keyboard.h
@@ -38,6 +38,7 @@ namespace AGS3 {
 #define KEY_RCONTROL Common::KEYCODE_RCTRL
 #define KEY_ALTGR 0
 #define KEY_F9 Common::KEYCODE_F9
+#define KEY_A Common::KEYCODE_a
 
 #define __allegro_KEY_LSHIFT Common::KEYCODE_LSHIFT
 #define __allegro_KEY_RSHIFT Common::KEYCODE_RSHIFT
diff --git a/engines/ags/lib/system/datetime.cpp b/engines/ags/lib/system/datetime.cpp
new file mode 100644
index 0000000000..e95978d0dd
--- /dev/null
+++ b/engines/ags/lib/system/datetime.cpp
@@ -0,0 +1,80 @@
+/* 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 "ags/lib/system/datetime.h"
+
+namespace AGS3 {
+
+/*
+ * Converts a date/time structure to Unix timestamp
+ * @author Oryx Embedded SARL (www.oryx-embedded.com)
+ * @version 2.0.0
+ */
+time_t convertDateToUnixTime(const TimeDate *date) {
+	uint y;
+	uint m;
+	uint d;
+	time_t t;
+
+	// Year
+	y = date->tm_year;
+	// Month of year
+	m = date->tm_mon;
+	// Day of month
+	d = date->tm_mday;
+
+	// January and February are counted as months 13 and 14 of the previous year
+	if (m <= 2) {
+		m += 12;
+		y -= 1;
+	}
+
+	// Convert years to days
+	t = (365 * y) + (y / 4) - (y / 100) + (y / 400);
+	// Convert months to days
+	t += (30 * m) + (3 * (m + 1) / 5) + d;
+	// Unix time starts on January 1st, 1970
+	t -= 719561;
+	// Convert days to seconds
+	t *= 86400;
+	// Add hours, minutes and seconds
+	t += (3600 * date->tm_hour) + (60 * date->tm_min) + date->tm_sec;
+
+	// Return Unix time
+	return t;
+}
+
+void localTime(tm *time) {
+	g_system->getTimeAndDate(*time);
+
+	time->tm_yday = 0;
+	time->tm_isdst = 0;
+}
+
+time_t getUnixTime() {
+	tm time;
+	localTime(&time);
+
+	return convertDateToUnixTime(&time);
+}
+
+} // namespace AGS3
diff --git a/engines/ags/lib/system/datetime.h b/engines/ags/lib/system/datetime.h
new file mode 100644
index 0000000000..ba2bea9880
--- /dev/null
+++ b/engines/ags/lib/system/datetime.h
@@ -0,0 +1,50 @@
+/* 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 AGS_LIB_SYSTEM_DATETIME_H
+#define AGS_LIB_SYSTEM_DATETIME_H
+
+#include "common/scummsys.h"
+#include "common/system.h"
+
+namespace AGS3 {
+
+struct tm : public TimeDate {
+	int tm_yday;  // days since January 1 - [0, 365]
+	int tm_isdst; // daylight savings time flag
+};
+
+typedef int64 time_t;
+
+/**
+ * Returns the current date and time
+ */
+extern void localTime(tm *time);
+
+/**
+ * Returns the Unix 2038-end time
+ */
+extern time_t getUnixTime();
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index e8c6b7639a..47674e6642 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -20,6 +20,7 @@ MODULE_OBJS = \
 	lib/allegro/sound.o \
 	lib/allegro/system.o \
 	lib/allegro/unicode.o \
+	lib/system/datetime.o \
 	shared/ac/dynobj/scriptaudioclip.o \
 	shared/ac/audiocliptype.o \
 	shared/ac/characterinfo.o \
@@ -99,7 +100,12 @@ MODULE_OBJS = \
 	engine/main/game_start.o \
 	engine/main/graphics_mode.o \
 	engine/main/quit.o \
-	engine/main/update.o
+	engine/main/update.o \
+	engine/platform/base/agsplatformdriver.o \
+	engine/platform/windows/acplwin.o \
+	engine/platform/windows/minidump.o \
+	engine/platform/windows/win_ex_handling.o
+
 
 # This module can be built as a plugin
 ifeq ($(ENABLE_AGS), DYNAMIC_PLUGIN)
diff --git a/engines/ags/std/thread.h b/engines/ags/std/thread.h
index 46be465c51..53455e9dd0 100644
--- a/engines/ags/std/thread.h
+++ b/engines/ags/std/thread.h
@@ -23,6 +23,7 @@
 #ifndef AGS_STD_THREAD_H
 #define AGS_STD_THREAD_H
 
+#include "ags/std/chrono.h"
 #include "common/textconsole.h"
 
 namespace AGS3 {
@@ -53,6 +54,12 @@ public:
 	static void yield() {
 		warning("TODO: this_thread::yield");
 	}
+
+	static void sleep_for(uint32 milli) {
+		g_system->delayMillis(milli);
+	}
+//	template <class Rep, class Period>
+//	static void sleep_for(const chrono::duration<Rep, Period> &rel_time);
 };
 
 } // namespace std


Commit: 65a2cf6687130ac0a41d1492592d90cbaee4a6f6
    https://github.com/scummvm/scummvm/commit/65a2cf6687130ac0a41d1492592d90cbaee4a6f6
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added engine/plugin/ folder

Changed paths:
  A engines/ags/engine/plugin/library.cpp
  A engines/ags/engine/plugin/library.h
    engines/ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h
    engines/ags/engine/gfx/gfx_util.h
    engines/ags/engine/gui/gui_engine.cpp
    engines/ags/engine/plugin/agsplugin.cpp
    engines/ags/engine/plugin/plugin_builtin.h
    engines/ags/engine/plugin/pluginobjectreader.cpp
    engines/ags/engine/util/library.h
    engines/ags/engine/util/library_posix.h
    engines/ags/lib/allegro/color.cpp
    engines/ags/lib/allegro/color.h
    engines/ags/lib/allegro/gfx.cpp
    engines/ags/lib/allegro/gfx.h
    engines/ags/module.mk


diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h b/engines/ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h
index 416284c812..91830bee0e 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h
@@ -23,8 +23,8 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_ADDR_AND_MANAGER_H
 #define AGS_ENGINE_AC_DYNOBJ_ADDR_AND_MANAGER_H
 
-#include "ags/shared/script/runtimescriptvalue.h"
-#include "ags/shared/ac/dynobj/cc_dynamicobject.h"
+#include "ags/engine/script/runtimescriptvalue.h"
+#include "ags/engine/ac/dynobj/cc_dynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gfx/gfx_util.h b/engines/ags/engine/gfx/gfx_util.h
index 7e8f1e6f03..c0ce244f90 100644
--- a/engines/ags/engine/gfx/gfx_util.h
+++ b/engines/ags/engine/gfx/gfx_util.h
@@ -53,7 +53,7 @@ Bitmap *ConvertBitmap(Bitmap *src, int dst_color_depth);
 // or fallbacks to common "magic pink" transparency mode;
 // optionally uses blending alpha (overall image transparency).
 void DrawSpriteBlend(Bitmap *ds, const Point &ds_at, Bitmap *sprite,
-	Common::BlendMode blend_mode, bool dst_has_alpha = true, bool src_has_alpha = true, int blend_alpha = 0xFF);
+	Shared::BlendMode blend_mode, bool dst_has_alpha = true, bool src_has_alpha = true, int blend_alpha = 0xFF);
 
 // Draws a bitmap over another one with given alpha level (0 - 255),
 // takes account of the bitmap's mask color,
diff --git a/engines/ags/engine/gui/gui_engine.cpp b/engines/ags/engine/gui/gui_engine.cpp
index 97258f53ae..3a76b334fc 100644
--- a/engines/ags/engine/gui/gui_engine.cpp
+++ b/engines/ags/engine/gui/gui_engine.cpp
@@ -27,7 +27,7 @@
 //=============================================================================
 
 // Headers, as they are in acgui.cpp
-#pragma unmanaged
+//pragma unmanaged
 #include "ags/shared/ac/game_version.h"
 #include "ags/engine/ac/system.h"
 #include "ags/shared/font/fonts.h"
diff --git a/engines/ags/engine/plugin/agsplugin.cpp b/engines/ags/engine/plugin/agsplugin.cpp
index 5837511a6c..6019f9525d 100644
--- a/engines/ags/engine/plugin/agsplugin.cpp
+++ b/engines/ags/engine/plugin/agsplugin.cpp
@@ -28,58 +28,52 @@
 #include "ags/shared/util/wgt2allg.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/view.h"
-#include "ags/shared/ac/charactercache.h"
-#include "ags/shared/ac/display.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/dynamicsprite.h"
-#include "ags/shared/ac/gamesetup.h"
+#include "ags/engine/ac/charactercache.h"
+#include "ags/engine/ac/display.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/dynamicsprite.h"
+#include "ags/engine/ac/gamesetup.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/global_audio.h"
-#include "ags/shared/ac/global_plugin.h"
-#include "ags/shared/ac/global_walkablearea.h"
-#include "ags/shared/ac/keycode.h"
-#include "ags/shared/ac/mouse.h"
-#include "ags/shared/ac/movelist.h"
-#include "ags/shared/ac/objectcache.h"
-#include "ags/shared/ac/parser.h"
-#include "ags/shared/ac/path_helper.h"
-#include "ags/shared/ac/roomstatus.h"
-#include "ags/shared/ac/string.h"
-#include "ags/shared/ac/dynobj/cc_dynamicobject_addr_and_manager.h"
+#include "ags/engine/ac/global_audio.h"
+#include "ags/engine/ac/global_plugin.h"
+#include "ags/engine/ac/global_walkablearea.h"
+#include "ags/engine/ac/keycode.h"
+#include "ags/engine/ac/mouse.h"
+#include "ags/engine/ac/movelist.h"
+#include "ags/engine/ac/objectcache.h"
+#include "ags/engine/ac/parser.h"
+#include "ags/engine/ac/path_helper.h"
+#include "ags/engine/ac/roomstatus.h"
+#include "ags/engine/ac/string.h"
+#include "ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h"
 #include "ags/shared/font/fonts.h"
 #include "ags/shared/util/string_compat.h"
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/debug/debugger.h"
-#include "ags/shared/device/mousew32.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/debugging/debugger.h"
+#include "ags/engine/device/mousew32.h"
 #include "ags/shared/gui/guidefines.h"
-#include "ags/shared/main/game_run.h"
-#include "ags/shared/main/engine.h"
-#include "ags/shared/plugin/agsplugin.h"
-#include "ags/shared/plugin/plugin_engine.h"
-#include "ags/shared/plugin/plugin_builtin.h"
-#include "ags/shared/plugin/pluginobjectreader.h"
-#include "ags/shared/script/script.h"
-#include "ags/shared/script/script_runtime.h"
+#include "ags/engine/main/game_run.h"
+#include "ags/engine/main/engine.h"
+#include "ags/engine/plugin/agsplugin.h"
+#include "ags/engine/plugin/plugin_engine.h"
+#include "ags/engine/plugin/plugin_builtin.h"
+#include "ags/engine/plugin/pluginobjectreader.h"
+#include "ags/engine/script/script.h"
+#include "ags/engine/script/script_runtime.h"
 #include "ags/shared/ac/spritecache.h"
 #include "ags/shared/util/stream.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/gfx/graphicsdriver.h"
-#include "ags/shared/gfx/gfxfilter.h"
-#include "ags/shared/script/runtimescriptvalue.h"
-#include "ags/shared/debug/out.h"
-#include "ags/shared/ac/dynobj/scriptstring.h"
-#include "ags/shared/main/graphics_mode.h"
-#include "ags/shared/gfx/gfx_util.h"
+#include "ags/engine/gfx/graphicsdriver.h"
+#include "ags/engine/gfx/gfxfilter.h"
+#include "ags/engine/script/runtimescriptvalue.h"
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/ac/dynobj/scriptstring.h"
+#include "ags/engine/main/graphics_mode.h"
+#include "ags/engine/gfx/gfx_util.h"
 #include "ags/shared/util/memory.h"
 #include "ags/shared/util/filestream.h"
-#include "ags/shared/media/audio/audio_system.h"
-
-namespace AGS3 {
-
-using namespace AGS::Shared;
-using namespace AGS::Shared::Memory;
-using namespace AGS::Engine;
-
+#include "ags/engine/media/audio/audio_system.h"
+#include "ags/engine/util/library.h"
 
 #if defined(BUILTIN_PLUGINS)
 #include "ags/shared/../Plugins/AGSflashlight/agsflashlight.h"
@@ -92,6 +86,11 @@ using namespace AGS::Engine;
 #endif // AGS_PLATFORM_OS_IOS
 #endif // BUILTIN_PLUGINS
 
+namespace AGS3 {
+
+using namespace AGS::Shared;
+using namespace AGS::Shared::Memory;
+using namespace AGS::Engine;
 
 extern IGraphicsDriver *gfxDriver;
 extern int mousex, mousey;
@@ -117,9 +116,6 @@ extern ScriptString myScriptStringImpl;
 // **************** PLUGIN IMPLEMENTATION ****************
 
 
-#include "ags/shared/util/library.h"
-
-
 
 
 struct EnginePlugin {
@@ -260,7 +256,7 @@ unsigned char **IAGSEngine::GetRawBitmapSurface(BITMAP *bmp) {
 	if (stage && bmp == stage->GetAllegroBitmap())
 		plugins[this->pluginId].invalidatedRegion = 0;
 
-	return bmp->line;
+	return (unsigned char **)bmp->getPixels();
 }
 
 void IAGSEngine::ReleaseBitmapSurface(BITMAP *bmp) {
@@ -554,7 +550,7 @@ void IAGSEngine::PrintDebugConsole(const char *text) {
 	platform->WriteStdOut("[PLUGIN] %s", text);
 }
 int IAGSEngine::IsChannelPlaying(int32 channel) {
-	return ::IsChannelPlaying(channel);
+	return AGS3::IsChannelPlaying(channel);
 }
 void IAGSEngine::PlaySoundChannel(int32 channel, int32 soundType, int32 volume, int32 loop, const char *filename) {
 	stop_and_destroy_channel(channel);
@@ -752,19 +748,19 @@ void IAGSEngine::AddManagedObjectReader(const char *typeName, IAGSManagedObjectR
 	numPluginReaders++;
 }
 
-void IAGSEngine::RegisterUnserializedObject(int key, const void *object, IAGSScriptManagedObject *callback) {
+void IAGSEngine::RegisterUnserializedObject(int key_, const void *object, IAGSScriptManagedObject *callback) {
 	GlobalReturnValue.SetPluginObject((void *)object, (ICCDynamicObject *)callback);
-	ccRegisterUnserializedObject(key, object, (ICCDynamicObject *)callback, true);
+	ccRegisterUnserializedObject(key_, object, (ICCDynamicObject *)callback, true);
 }
 
 int IAGSEngine::GetManagedObjectKeyByAddress(const char *address) {
 	return ccGetObjectHandleFromAddress(address);
 }
 
-void *IAGSEngine::GetManagedObjectAddressByKey(int key) {
+void *IAGSEngine::GetManagedObjectAddressByKey(int key_) {
 	void *object;
 	ICCDynamicObject *manager;
-	ScriptValueType obj_type = ccGetObjectAddressAndManagerFromHandle(key, object, manager);
+	ScriptValueType obj_type = ccGetObjectAddressAndManagerFromHandle(key_, object, manager);
 	if (obj_type == kScValPluginObject) {
 		GlobalReturnValue.SetPluginObject(object, manager);
 	} else {
@@ -977,10 +973,10 @@ bool pl_use_builtin_plugin(EnginePlugin *apl) {
 	return false;
 }
 
-Engine::GameInitError pl_register_plugins(const std::vector<Common::PluginInfo> &infos) {
+Engine::GameInitError pl_register_plugins(const std::vector<Shared::PluginInfo> &infos) {
 	numPlugins = 0;
 	for (size_t inf_index = 0; inf_index < infos.size(); ++inf_index) {
-		const Common::PluginInfo &info = infos[inf_index];
+		const Shared::PluginInfo &info = infos[inf_index];
 		String name = info.Name;
 		if (name.GetLast() == '!')
 			continue; // editor-only plugin, ignore it
diff --git a/engines/ags/engine/plugin/library.cpp b/engines/ags/engine/plugin/library.cpp
new file mode 100644
index 0000000000..44c6e1a06a
--- /dev/null
+++ b/engines/ags/engine/plugin/library.cpp
@@ -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.
+ *
+ */
+
+#include "ags/engine/plugin/library.h"
+
+namespace AGS3 {
+
+void *dlopen(const char *filename, bool) {
+	// TODO: Reimplement plugins as C++ code that's part of the project
+	return nullptr;
+}
+
+int dlclose(void *) {
+	return 0;
+}
+
+void *dlsym(void *lib, const char *method) {
+	return nullptr;
+}
+
+const char *dlerror() {
+	return nullptr;
+}
+
+} // namespace AGS3
diff --git a/engines/ags/engine/plugin/library.h b/engines/ags/engine/plugin/library.h
new file mode 100644
index 0000000000..4679f9c642
--- /dev/null
+++ b/engines/ags/engine/plugin/library.h
@@ -0,0 +1,40 @@
+/* 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 AGS_ENGINE_PLUGIN_LIBRARY_H
+#define AGS_ENGINE_PLUGIN_LIBRARY_H
+
+namespace AGS3 {
+
+#define RTLD_LAZY true
+
+extern void *dlopen(const char *filename, bool);
+
+extern int dlclose(void *lib);
+
+extern void *dlsym(void *lib, const char *method);
+
+extern const char *dlerror();
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/engine/plugin/plugin_builtin.h b/engines/ags/engine/plugin/plugin_builtin.h
index 13538f8a60..3db0f06e60 100644
--- a/engines/ags/engine/plugin/plugin_builtin.h
+++ b/engines/ags/engine/plugin/plugin_builtin.h
@@ -35,8 +35,6 @@ namespace AGS3 {
 
 class IAGSEngine;
 
-using namespace AGS; // FIXME later
-
 //  Initial implementation for apps to register their own inbuilt plugins
 
 struct InbuiltPluginDetails {
diff --git a/engines/ags/engine/plugin/pluginobjectreader.cpp b/engines/ags/engine/plugin/pluginobjectreader.cpp
index 237c7e9370..c01edae79b 100644
--- a/engines/ags/engine/plugin/pluginobjectreader.cpp
+++ b/engines/ags/engine/plugin/pluginobjectreader.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ags/shared/plugin/pluginobjectreader.h"
-#include "ags/shared/ac/runtime_defines.h"
+#include "ags/engine/plugin/pluginobjectreader.h"
+#include "ags/engine/ac/runtime_defines.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/util/library.h b/engines/ags/engine/util/library.h
index 41d53f5a43..2fe01f2003 100644
--- a/engines/ags/engine/util/library.h
+++ b/engines/ags/engine/util/library.h
@@ -56,10 +56,10 @@ public:
 #elif AGS_PLATFORM_OS_LINUX \
    || AGS_PLATFORM_OS_MACOS \
    || AGS_PLATFORM_OS_ANDROID
-#include "ags/shared/library_posix.h"
+#include "ags/engine/util/library_posix.h"
 
 #elif AGS_PLATFORM_OS_IOS
-#include "ags/shared/library_dummy.h"
+#include "ags/engine/util/library_dummy.h"
 
 #endif
 
diff --git a/engines/ags/engine/util/library_posix.h b/engines/ags/engine/util/library_posix.h
index 53692c1f33..ceb39cf21b 100644
--- a/engines/ags/engine/util/library_posix.h
+++ b/engines/ags/engine/util/library_posix.h
@@ -26,7 +26,8 @@
 //include <dlfcn.h>
 #include "ags/shared/core/platform.h"
 #include "ags/shared/util/string.h"
-#include "ags/shared/debug/out.h"
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/plugin/library.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/lib/allegro/color.cpp b/engines/ags/lib/allegro/color.cpp
index 45a994e7f7..6756d1ab2c 100644
--- a/engines/ags/lib/allegro/color.cpp
+++ b/engines/ags/lib/allegro/color.cpp
@@ -71,6 +71,13 @@ void set_palette_range(const PALETTE p, int from, int to, int retracesync) {
 	g_system->getPaletteManager()->setPalette(&palette[from], from, to - from + 1);
 }
 
+int makeacol(int r, int g, int b, int a) {
+	error("TODO: makeacol");
+}
+
+int makeacol_depth(int color_depth, int r, int g, int b, int a) {
+	error("makeacol_depth");
+}
 
 int makecol15(int r, int g, int b) {
 	return (((r >> 3) << _rgb_r_shift_15) |
@@ -123,4 +130,20 @@ int makecol8(byte r, byte g, byte b) {
 	return (b) | (g << 8) | (r << 16);
 }
 
+int getr_depth(int color_depth, int c) {
+	error("TOD: getr_depth");
+}
+
+int getg_depth(int color_depth, int c) {
+	error("TOD: getg_depth");
+}
+
+int getb_depth(int color_depth, int c) {
+	error("TOD: getb_depth");
+}
+
+int geta_depth(int color_depth, int c) {
+	error("TOD: geta_depth");
+}
+
 } // namespace AGS3
diff --git a/engines/ags/lib/allegro/color.h b/engines/ags/lib/allegro/color.h
index ddb7ae1e8d..cc1c86a95e 100644
--- a/engines/ags/lib/allegro/color.h
+++ b/engines/ags/lib/allegro/color.h
@@ -70,6 +70,8 @@ AL_FUNC(void, set_color, (int idx, AL_CONST RGB *p));
 AL_FUNC(void, set_palette, (AL_CONST PALETTE p));
 AL_FUNC(void, set_palette_range, (AL_CONST PALETTE p, int from, int to, int retracesync));
 
+extern int makeacol(int r, int g, int b, int a);
+extern int makeacol_depth(int color_depth, int r, int g, int b, int a);
 
 extern int makecol15(int r, int g, int b);
 extern int makecol16(int r, int g, int b);
@@ -82,6 +84,11 @@ extern int getb8(int c);
 extern int makecol(byte r, byte g, byte b);
 extern int makecol8(byte r, byte g, byte b);
 
+extern int getr_depth(int color_depth, int c);
+extern int getg_depth(int color_depth, int c);
+extern int getb_depth(int color_depth, int c);
+extern int geta_depth(int color_depth, int c);
+
 } // namespace AGS3
 
 #endif
diff --git a/engines/ags/lib/allegro/gfx.cpp b/engines/ags/lib/allegro/gfx.cpp
index e5ccd68ec8..153a00be72 100644
--- a/engines/ags/lib/allegro/gfx.cpp
+++ b/engines/ags/lib/allegro/gfx.cpp
@@ -244,6 +244,10 @@ bool is_planar_bitmap(BITMAP *bmp) {
 	return false;
 }
 
+bool is_linear_bitmap(BITMAP *bmp) {
+	return true;
+}
+
 void bmp_select(BITMAP *bmp) {
 	// No implementation needed
 }
diff --git a/engines/ags/lib/allegro/gfx.h b/engines/ags/lib/allegro/gfx.h
index 737ddb3802..95cd8104c8 100644
--- a/engines/ags/lib/allegro/gfx.h
+++ b/engines/ags/lib/allegro/gfx.h
@@ -236,6 +236,7 @@ extern void pivot_sprite(BITMAP *bmp, const BITMAP *sprite, int x, int y, int cx
 
 extern bool is_screen_bitmap(BITMAP *bmp);
 extern bool is_video_bitmap(BITMAP *bmp);
+extern bool is_linear_bitmap(BITMAP *bmp);
 extern bool is_planar_bitmap(BITMAP *bmp);
 extern void bmp_select(BITMAP *bmp);
 extern long bmp_write_line(BITMAP *bmp, int line);
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 47674e6642..8df0808d72 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -104,7 +104,9 @@ MODULE_OBJS = \
 	engine/platform/base/agsplatformdriver.o \
 	engine/platform/windows/acplwin.o \
 	engine/platform/windows/minidump.o \
-	engine/platform/windows/win_ex_handling.o
+	engine/platform/windows/win_ex_handling.o \
+	engine/plugin/agsplugin.o \
+	engine/plugin/pluginobjectreader.o
 
 
 # This module can be built as a plugin


Commit: c16efc3a1dcc68b93819659059705dbea8a311c8
    https://github.com/scummvm/scummvm/commit/c16efc3a1dcc68b93819659059705dbea8a311c8
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Adding engine/script/ folder

Changed paths:
  A engines/ags/std/queue.h
    engines/ags/engine/ac/dynobj/cc_dynamicarray.h
    engines/ags/engine/ac/dynobj/cc_serializer.h
    engines/ags/engine/ac/dynobj/managedobjectpool.h
    engines/ags/engine/ac/dynobj/scriptuserobject.h
    engines/ags/engine/platform/base/agsplatformdriver.h
    engines/ags/engine/script/cc_instance.cpp
    engines/ags/engine/script/executingscript.cpp
    engines/ags/engine/script/runtimescriptvalue.cpp
    engines/ags/engine/script/script.cpp
    engines/ags/engine/script/script_api.cpp
    engines/ags/engine/script/script_engine.cpp
    engines/ags/engine/script/script_runtime.cpp
    engines/ags/engine/script/systemimports.cpp
    engines/ags/engine/script/systemimports.h
    engines/ags/lib/aastr-0.1.1/aarot.cpp
    engines/ags/lib/aastr-0.1.1/aastr.cpp
    engines/ags/module.mk
    engines/ags/shared/ac/gamesetupstructbase.cpp
    engines/ags/shared/ac/spritecache.cpp
    engines/ags/shared/core/types.h
    engines/ags/shared/debugging/debugmanager.cpp
    engines/ags/shared/game/roomstruct.cpp
    engines/ags/shared/gfx/allegrobitmap.cpp
    engines/ags/shared/util/memory.h
    engines/ags/std/map.h


diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicarray.h b/engines/ags/engine/ac/dynobj/cc_dynamicarray.h
index 327a0b1b78..309a8adbcf 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicarray.h
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicarray.h
@@ -24,7 +24,7 @@
 #define AGS_ENGINE_AC_DYNOBJ_CCDYNAMICARRAY_H
 
 #include "ags/std/vector.h"
-#include "ags/shared/ac/dynobj/cc_dynamicobject.h"   // ICCDynamicObject
+#include "ags/engine/ac/dynobj/cc_dynamicobject.h"   // ICCDynamicObject
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_serializer.h b/engines/ags/engine/ac/dynobj/cc_serializer.h
index 54458ead27..963c65d1d2 100644
--- a/engines/ags/engine/ac/dynobj/cc_serializer.h
+++ b/engines/ags/engine/ac/dynobj/cc_serializer.h
@@ -28,7 +28,7 @@
 namespace AGS3 {
 
 struct AGSDeSerializer : ICCObjectReader {
-
+	virtual ~AGSDeSerializer() {}
 	void Unserialize(int index, const char *objectType, const char *serializedData, int dataSize) override;
 };
 
diff --git a/engines/ags/engine/ac/dynobj/managedobjectpool.h b/engines/ags/engine/ac/dynobj/managedobjectpool.h
index 118df53d3f..31366b02fa 100644
--- a/engines/ags/engine/ac/dynobj/managedobjectpool.h
+++ b/engines/ags/engine/ac/dynobj/managedobjectpool.h
@@ -24,11 +24,11 @@
 #define AGS_ENGINE_AC_DYNOBJ_MANAGEDOBJECTPOOL_H
 
 #include "ags/std/vector.h"
-//include <queue>
-//include <unordered_map>
-
-#include "ags/shared/script/runtimescriptvalue.h"
-#include "ags/shared/ac/dynobj/cc_dynamicobject.h"   // ICCDynamicObject
+#include "ags/std/queue.h"
+#include "ags/std/map.h"
+#include "ags/engine/script/runtimescriptvalue.h"
+#include "ags/engine/ac/dynobj/cc_dynamicobject.h"   // ICCDynamicObject
+#include "ags/shared/util/string_types.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/ac/dynobj/scriptuserobject.h b/engines/ags/engine/ac/dynobj/scriptuserobject.h
index d54d32aaa5..b4ff5418df 100644
--- a/engines/ags/engine/ac/dynobj/scriptuserobject.h
+++ b/engines/ags/engine/ac/dynobj/scriptuserobject.h
@@ -29,7 +29,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTUSERSTRUCT_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTUSERSTRUCT_H
 
-#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/engine/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/platform/base/agsplatformdriver.h b/engines/ags/engine/platform/base/agsplatformdriver.h
index 5a2023c6cc..1975d94353 100644
--- a/engines/ags/engine/platform/base/agsplatformdriver.h
+++ b/engines/ags/engine/platform/base/agsplatformdriver.h
@@ -29,11 +29,11 @@
 #ifndef AGS_ENGINE_PLATFORM_BASE_AGSPLATFORMDRIVER_H
 #define AGS_ENGINE_PLATFORM_BASE_AGSPLATFORMDRIVER_H
 
-//include <errno.h>
 #include "ags/std/vector.h"
 #include "ags/engine/ac/datetime.h"
 #include "ags/shared/debugging/outputhandler.h"
 #include "ags/shared/util/ini_util.h"
+#include "ags/lib/allegro/error.h"
 
 namespace AGS3 {
 
@@ -73,7 +73,7 @@ struct AGSPlatformDriver
 	virtual void DisplayAlert(const char *, ...) = 0;
 	virtual void AttachToParentConsole();
 	virtual int  GetLastSystemError() {
-		return errno;
+		return errnum;
 	}
 	// Get root directory for storing per-game shared data
 	virtual const char *GetAllUsersDataDirectory() {
diff --git a/engines/ags/engine/script/cc_instance.cpp b/engines/ags/engine/script/cc_instance.cpp
index 2effb0fd1f..b76ee2cfdc 100644
--- a/engines/ags/engine/script/cc_instance.cpp
+++ b/engines/ags/engine/script/cc_instance.cpp
@@ -23,26 +23,26 @@
 //include <cstdio>
 //include <string.h>
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/dynobj/cc_dynamicarray.h"
-#include "ags/shared/ac/dynobj/managedobjectpool.h"
+#include "ags/engine/ac/dynobj/cc_dynamicarray.h"
+#include "ags/engine/ac/dynobj/managedobjectpool.h"
 #include "ags/shared/gui/guidefines.h"
 #include "ags/shared/script/cc_error.h"
-#include "ags/shared/script/cc_instance.h"
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/debug/out.h"
+#include "ags/engine/script/cc_instance.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/shared/debugging/out.h"
 #include "ags/shared/script/cc_options.h"
-#include "ags/shared/script/script.h"
-#include "ags/shared/script/script_runtime.h"
-#include "ags/shared/script/systemimports.h"
+#include "ags/engine/script/script.h"
+#include "ags/engine/script/script_runtime.h"
+#include "ags/engine/script/systemimports.h"
 #include "ags/shared/util/bbop.h"
 #include "ags/shared/util/stream.h"
 #include "ags/shared/util/misc.h"
 #include "ags/shared/util/textstreamwriter.h"
-#include "ags/shared/ac/dynobj/scriptstring.h"
-#include "ags/shared/ac/dynobj/scriptuserobject.h"
-#include "ags/shared/ac/statobj/agsstaticobject.h"
-#include "ags/shared/ac/statobj/staticarray.h"
-#include "ags/shared/ac/dynobj/cc_dynamicobject_addr_and_manager.h"
+#include "ags/engine/ac/dynobj/scriptstring.h"
+#include "ags/engine/ac/dynobj/scriptuserobject.h"
+#include "ags/engine/ac/statobj/agsstaticobject.h"
+#include "ags/engine/ac/statobj/staticarray.h"
+#include "ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h"
 #include "ags/shared/util/memory.h"
 #include "ags/shared/util/string_utils.h" // linux strnicmp definition
 
@@ -1319,8 +1319,8 @@ bool ccInstance::_Create(PScript scri, ccInstance *joined) {
 			code = (intptr_t *)malloc(codesize * sizeof(intptr_t));
 			// 64 bit: Read code into 8 byte array, necessary for being able to perform
 			// relocations on the references.
-			for (int i = 0; i < codesize; ++i)
-				code[i] = scri->code[i];
+			for (int idx = 0; idx < codesize; ++idx)
+				code[idx] = scri->code[idx];
 		}
 	}
 
@@ -1558,7 +1558,7 @@ ScriptVariable *ccInstance::FindGlobalVar(int32_t var_addr) {
 		Debug::Printf(kDbgMsg_Warn, "WARNING: looking up for global variable beyond allocated buffer (%d, %d)", var_addr, globaldatasize);
 	}
 	ScVarMap::iterator it = globalvars->find(var_addr);
-	return it != globalvars->end() ? &it->second : nullptr;
+	return it != globalvars->end() ? &it->_value : nullptr;
 }
 
 bool ccInstance::CreateRuntimeCodeFixups(PScript scri) {
diff --git a/engines/ags/engine/script/executingscript.cpp b/engines/ags/engine/script/executingscript.cpp
index 190f4464dc..2924a0b8ed 100644
--- a/engines/ags/engine/script/executingscript.cpp
+++ b/engines/ags/engine/script/executingscript.cpp
@@ -21,9 +21,9 @@
  */
 
 //include <string.h>
-#include "ags/shared/executingscript.h"
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/debug/debugger.h"
+#include "ags/engine/script/executingscript.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/debugging/debugger.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/script/runtimescriptvalue.cpp b/engines/ags/engine/script/runtimescriptvalue.cpp
index 2ac47d71cf..5a943734f1 100644
--- a/engines/ags/engine/script/runtimescriptvalue.cpp
+++ b/engines/ags/engine/script/runtimescriptvalue.cpp
@@ -21,9 +21,9 @@
  */
 
 #include "ags/shared/script/cc_error.h"
-#include "ags/shared/script/runtimescriptvalue.h"
-#include "ags/shared/ac/dynobj/cc_dynamicobject.h"
-#include "ags/shared/ac/statobj/staticobject.h"
+#include "ags/engine/script/runtimescriptvalue.h"
+#include "ags/engine/ac/dynobj/cc_dynamicobject.h"
+#include "ags/engine/ac/statobj/staticobject.h"
 #include "ags/shared/util/memory.h"
 
 //include <string.h> // for memcpy()
diff --git a/engines/ags/engine/script/script.cpp b/engines/ags/engine/script/script.cpp
index 45d52a2754..72217c857d 100644
--- a/engines/ags/engine/script/script.cpp
+++ b/engines/ags/engine/script/script.cpp
@@ -21,36 +21,36 @@
  */
 
 //include <string.h>
-#include "ags/shared/script/script.h"
+#include "ags/engine/script/script.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/character.h"
-#include "ags/shared/ac/dialog.h"
-#include "ags/shared/ac/event.h"
-#include "ags/shared/ac/game.h"
+#include "ags/engine/ac/character.h"
+#include "ags/engine/ac/dialog.h"
+#include "ags/engine/ac/event.h"
+#include "ags/engine/ac/game.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_audio.h"
-#include "ags/shared/ac/global_character.h"
-#include "ags/shared/ac/global_dialog.h"
-#include "ags/shared/ac/global_display.h"
-#include "ags/shared/ac/global_game.h"
-#include "ags/shared/ac/global_gui.h"
-#include "ags/shared/ac/global_hotspot.h"
-#include "ags/shared/ac/global_object.h"
-#include "ags/shared/ac/global_room.h"
-#include "ags/shared/ac/invwindow.h"
-#include "ags/shared/ac/mouse.h"
-#include "ags/shared/ac/room.h"
-#include "ags/shared/ac/roomobject.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_audio.h"
+#include "ags/engine/ac/global_character.h"
+#include "ags/engine/ac/global_dialog.h"
+#include "ags/engine/ac/global_display.h"
+#include "ags/engine/ac/global_game.h"
+#include "ags/engine/ac/global_gui.h"
+#include "ags/engine/ac/global_hotspot.h"
+#include "ags/engine/ac/global_object.h"
+#include "ags/engine/ac/global_room.h"
+#include "ags/engine/ac/invwindow.h"
+#include "ags/engine/ac/mouse.h"
+#include "ags/engine/ac/room.h"
+#include "ags/engine/ac/roomobject.h"
 #include "ags/shared/script/cc_error.h"
 #include "ags/shared/script/cc_options.h"
-#include "ags/shared/debug/debugger.h"
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/main/game_run.h"
-#include "ags/shared/media/video/video.h"
-#include "ags/shared/script/script_runtime.h"
+#include "ags/engine/debugging/debugger.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/main/game_run.h"
+#include "ags/engine/media/video/video.h"
+#include "ags/engine/script/script_runtime.h"
 #include "ags/shared/util/string_compat.h"
-#include "ags/shared/media/audio/audio_system.h"
+#include "ags/engine/media/audio/audio_system.h"
 
 namespace AGS3 {
 
@@ -718,11 +718,11 @@ int run_interaction_commandlist(InteractionCommandList *nicl, int *timesrun, int
 			break;
 		case 9:
 		{ // Run Dialog
-			int room_was = play.room_changes;
+			int roomWas = play.room_changes;
 			RunDialog(IPARAM1);
 			// if they changed room within the dialog script,
 			// the interaction command list is no longer valid
-			if (room_was != play.room_changes)
+			if (roomWas != play.room_changes)
 				return -1;
 		}
 		break;
diff --git a/engines/ags/engine/script/script_api.cpp b/engines/ags/engine/script/script_api.cpp
index 50f37f883d..ecf8192db5 100644
--- a/engines/ags/engine/script/script_api.cpp
+++ b/engines/ags/engine/script/script_api.cpp
@@ -24,8 +24,8 @@
 //include <string.h>
 #include "ags/shared/ac/game_version.h"
 #include "ags/shared/script/cc_error.h"
-#include "ags/shared/script/runtimescriptvalue.h"
-#include "ags/shared/script/script_api.h"
+#include "ags/engine/script/runtimescriptvalue.h"
+#include "ags/engine/script/script_api.h"
 #include "ags/shared/util/math.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/script/script_engine.cpp b/engines/ags/engine/script/script_engine.cpp
index 234ed39bd4..fdbe1fc56a 100644
--- a/engines/ags/engine/script/script_engine.cpp
+++ b/engines/ags/engine/script/script_engine.cpp
@@ -32,7 +32,7 @@
 //=============================================================================
 
 //include <stdlib.h>
-#include "ags/shared/script/cc_instance.h"
+#include "ags/engine/script/cc_instance.h"
 #include "ags/shared/script/cc_error.h"
 #include "ags/shared/util/file.h"
 #include "ags/shared/util/stream.h"
diff --git a/engines/ags/engine/script/script_runtime.cpp b/engines/ags/engine/script/script_runtime.cpp
index 117162d359..f460eb5807 100644
--- a/engines/ags/engine/script/script_runtime.cpp
+++ b/engines/ags/engine/script/script_runtime.cpp
@@ -37,13 +37,13 @@
 //include <stdlib.h>
 //include <stdarg.h>
 //include <string.h>
-#include "ags/shared/script/script_runtime.h"
+#include "ags/engine/script/script_runtime.h"
 #include "ags/shared/script/script_common.h"
 #include "ags/shared/script/cc_error.h"
 #include "ags/shared/script/cc_options.h"
-#include "ags/shared/ac/dynobj/cc_dynamicarray.h"
-#include "ags/shared/script/systemimports.h"
-#include "ags/shared/ac/statobj/staticobject.h"
+#include "ags/engine/ac/dynobj/cc_dynamicarray.h"
+#include "ags/engine/script/systemimports.h"
+#include "ags/engine/ac/statobj/staticobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/script/systemimports.cpp b/engines/ags/engine/script/systemimports.cpp
index 850458aa5a..cc94b15d5f 100644
--- a/engines/ags/engine/script/systemimports.cpp
+++ b/engines/ags/engine/script/systemimports.cpp
@@ -22,7 +22,7 @@
 
 //include <stdlib.h>
 //include <string.h>
-#include "ags/shared/script/systemimports.h"
+#include "ags/engine/script/systemimports.h"
 
 namespace AGS3 {
 
@@ -52,7 +52,7 @@ int SystemImports::add(const String &name, const RuntimeScriptValue &value, ccIn
 	}
 
 	btree[name] = ixof;
-	if (ixof == imports.size())
+	if (ixof == (int)imports.size())
 		imports.push_back(ScriptImport());
 	imports[ixof].Name = name; // TODO: rather make a string copy here for safety reasons
 	imports[ixof].Value = value;
@@ -88,14 +88,14 @@ const ScriptImport *SystemImports::getByIndex(int index) {
 int SystemImports::get_index_of(const String &name) {
 	IndexMap::const_iterator it = btree.find(name);
 	if (it != btree.end())
-		return it->second;
+		return it->_value;
 
 	// CHECKME: what are "mangled names" and where do they come from?
 	String mangled_name = String::FromFormat("%s$", name.GetCStr());
 	// if it's a function with a mangled name, allow it
 	it = btree.lower_bound(mangled_name);
-	if (it != btree.end() && it->first.CompareLeft(mangled_name) == 0)
-		return it->second;
+	if (it != btree.end() && it->_key.CompareLeft(mangled_name) == 0)
+		return it->_value;
 
 	if (name.GetLength() > 3) {
 		size_t c = name.FindCharReverse('^');
diff --git a/engines/ags/engine/script/systemimports.h b/engines/ags/engine/script/systemimports.h
index 7d8d9cb34c..4bf2238dd9 100644
--- a/engines/ags/engine/script/systemimports.h
+++ b/engines/ags/engine/script/systemimports.h
@@ -23,8 +23,9 @@
 #ifndef AGS_ENGINE_SCRIPT_SYSTEMIMPORTS_H
 #define AGS_ENGINE_SCRIPT_SYSTEMIMPORTS_H
 
-//include <map>
-#include "ags/shared/script/cc_instance.h"    // ccInstance
+#include "ags/std/map.h"
+#include "ags/engine/script/cc_instance.h"    // ccInstance
+#include "ags/shared/util/string_types.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/lib/aastr-0.1.1/aarot.cpp b/engines/ags/lib/aastr-0.1.1/aarot.cpp
index e2bd4f325b..0c9a364da9 100644
--- a/engines/ags/lib/aastr-0.1.1/aarot.cpp
+++ b/engines/ags/lib/aastr-0.1.1/aarot.cpp
@@ -126,13 +126,13 @@ _aa_rotate_bitmap(BITMAP *_src, BITMAP *_dst, int _x, int _y, fixed _angle,
 
 	sw <<= aa_BITS;
 	dsx = sw / dw;
-	if (dsx < aa_SIZE)
+	if (dsx < (int)aa_SIZE)
 		dsx = aa_SIZE;
 	sw -= dsx;
 
 	sh <<= aa_BITS;
 	dsy = sh / dh;
-	if (dsy < aa_SIZE)
+	if (dsy < (int)aa_SIZE)
 		dsy = aa_SIZE;
 	sh -= dsy;
 
@@ -140,9 +140,9 @@ _aa_rotate_bitmap(BITMAP *_src, BITMAP *_dst, int _x, int _y, fixed _angle,
 
 	/* Avoid overflow.  */
 	if (num > aa_MAX_NUM) {
-		if (dsx > aa_MAX_SIZE)
+		if (dsx > (int)aa_MAX_SIZE)
 			dsx = aa_MAX_SIZE;
-		if (dsy > aa_MAX_SIZE)
+		if (dsy > (int)aa_MAX_SIZE)
 			dsy = aa_MAX_SIZE;
 		num = dsx * dsy;
 	}
diff --git a/engines/ags/lib/aastr-0.1.1/aastr.cpp b/engines/ags/lib/aastr-0.1.1/aastr.cpp
index e62bbf7020..b753d9e5f2 100644
--- a/engines/ags/lib/aastr-0.1.1/aastr.cpp
+++ b/engines/ags/lib/aastr-0.1.1/aastr.cpp
@@ -80,7 +80,7 @@ _aa_stretch_blit(BITMAP *_src, BITMAP *_dst,
 	_sw <<= aa_BITS;
 	dsx = _sw / _dw;
 
-	if (dsx < aa_SIZE) {
+	if (dsx < (int)aa_SIZE) {
 		/* Exploding by x.  */
 		_dw--;
 		_sw -= aa_SIZE;
@@ -91,7 +91,7 @@ _aa_stretch_blit(BITMAP *_src, BITMAP *_dst,
 	_sh <<= aa_BITS;
 	dsy = _sh / _dh;
 
-	if (dsy < aa_SIZE) {
+	if (dsy < (int)aa_SIZE) {
 		/* Exploding by y.  */
 		_dh--;
 		_sh -= aa_SIZE;
@@ -101,9 +101,9 @@ _aa_stretch_blit(BITMAP *_src, BITMAP *_dst,
 	num = dsx * dsy;
 
 	if (num > aa_MAX_NUM) {
-		if (dsx > aa_MAX_SIZE)
+		if (dsx > (int)aa_MAX_SIZE)
 			dsx = aa_MAX_SIZE;
-		if (dsy > aa_MAX_SIZE)
+		if (dsy > (int)aa_MAX_SIZE)
 			dsy = aa_MAX_SIZE;
 		num = dsx * dsy;
 	}
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 8df0808d72..793bc264d9 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -106,7 +106,16 @@ MODULE_OBJS = \
 	engine/platform/windows/minidump.o \
 	engine/platform/windows/win_ex_handling.o \
 	engine/plugin/agsplugin.o \
-	engine/plugin/pluginobjectreader.o
+	engine/plugin/pluginobjectreader.o \
+	engine/script/cc_instance.o \
+	engine/script/executingscript.o \
+	engine/script/exports.o \
+	engine/script/runtimescriptvalue.o \
+	engine/script/script.o \
+	engine/script/script_api.o \
+	engine/script/script_engine.o \
+	engine/script/script_runtime.o \
+	engine/script/systemimports.o
 
 
 # This module can be built as a plugin
diff --git a/engines/ags/shared/ac/gamesetupstructbase.cpp b/engines/ags/shared/ac/gamesetupstructbase.cpp
index 2b03a199b9..8c665fb5f5 100644
--- a/engines/ags/shared/ac/gamesetupstructbase.cpp
+++ b/engines/ags/shared/ac/gamesetupstructbase.cpp
@@ -250,6 +250,8 @@ Size ResolutionTypeToSize(GameResolutionType resolution, bool letterbox) {
 		return Size(1024, 768);
 	case kGameResolution_1280x720:
 		return Size(1280, 720);
+	default:
+		break;
 	}
 	return Size();
 }
diff --git a/engines/ags/shared/ac/spritecache.cpp b/engines/ags/shared/ac/spritecache.cpp
index 496ba10b51..8258e79028 100644
--- a/engines/ags/shared/ac/spritecache.cpp
+++ b/engines/ags/shared/ac/spritecache.cpp
@@ -489,10 +489,10 @@ void SpriteCache::CompressSprite(Bitmap *sprite, Stream *out) {
 			cpackbitl(&sprite->GetScanLineForWriting(y)[0], sprite->GetWidth(), out);
 	} else if (depth == 2) {
 		for (int y = 0; y < sprite->GetHeight(); y++)
-			cpackbitl16((unsigned short *)&sprite->GetScanLine(y)[0], sprite->GetWidth(), out);
+			cpackbitl16((const unsigned short *)&sprite->GetScanLine(y)[0], sprite->GetWidth(), out);
 	} else {
 		for (int y = 0; y < sprite->GetHeight(); y++)
-			cpackbitl32((unsigned int *)&sprite->GetScanLine(y)[0], sprite->GetWidth(), out);
+			cpackbitl32((const unsigned int *)&sprite->GetScanLine(y)[0], sprite->GetWidth(), out);
 	}
 }
 
@@ -856,7 +856,7 @@ void SpriteCache::DetachFile() {
 }
 
 int SpriteCache::AttachFile(const char *filename) {
-	_stream.reset(Shared::AssetManager::OpenAsset((char *)filename));
+	_stream.reset(Shared::AssetManager::OpenAsset((const char *)filename));
 	if (_stream == nullptr)
 		return -1;
 	return 0;
diff --git a/engines/ags/shared/core/types.h b/engines/ags/shared/core/types.h
index 7370da5934..3bf23121d9 100644
--- a/engines/ags/shared/core/types.h
+++ b/engines/ags/shared/core/types.h
@@ -67,10 +67,11 @@ typedef int16 int16_t;
 typedef int32 int32_t;
 typedef int64 int64_t;
 
-// Stream offset type
-typedef int64 soff_t;
+typedef int64 soff_t;		// Stream offset type
+typedef int64 intptr_t;
 
-#define fixed_t int32_t // fixed point type
+// fixed point type
+#define fixed_t int32_t
 #define color_t int
 
 #undef INT32_MIN
diff --git a/engines/ags/shared/debugging/debugmanager.cpp b/engines/ags/shared/debugging/debugmanager.cpp
index f1889e2ab8..f54484a66d 100644
--- a/engines/ags/shared/debugging/debugmanager.cpp
+++ b/engines/ags/shared/debugging/debugmanager.cpp
@@ -54,7 +54,7 @@ void DebugOutput::SetEnabled(bool enable) {
 
 void DebugOutput::SetGroupFilter(DebugGroupID id, MessageType verbosity) {
 	uint32_t key = DbgMgr.GetGroup(id).UID.ID;
-	if (key != kDbgGroup_None)
+	if (key != (uint32_t)kDbgGroup_None)
 		_groupFilter[key] = verbosity;
 	else
 		_unresolvedGroups.insert(std::make_pair(id.SID, verbosity));
@@ -91,7 +91,7 @@ void DebugOutput::ResolveGroupID(DebugGroupID id) {
 
 bool DebugOutput::TestGroup(DebugGroupID id, MessageType mt) const {
 	DebugGroupID real_id = DbgMgr.GetGroup(id).UID;
-	if (real_id.ID == kDbgGroup_None || real_id.ID >= _groupFilter.size())
+	if (real_id.ID == (uint32_t)kDbgGroup_None || real_id.ID >= _groupFilter.size())
 		return false;
 	return (_groupFilter[real_id.ID] >= mt) != 0;
 }
@@ -108,7 +108,7 @@ DebugManager::DebugManager() {
 }
 
 DebugGroup DebugManager::GetGroup(DebugGroupID id) {
-	if (id.ID != kDbgGroup_None) {
+	if (id.ID != (uint32_t)kDbgGroup_None) {
 		return id.ID < _groups.size() ? _groups[id.ID] : DebugGroup();
 	} else if (!id.SID.IsEmpty()) {
 		GroupByStringMap::const_iterator it = _groupByStrLookup.find(id.SID);
diff --git a/engines/ags/shared/game/roomstruct.cpp b/engines/ags/shared/game/roomstruct.cpp
index 3d17591816..d467f2a01d 100644
--- a/engines/ags/shared/game/roomstruct.cpp
+++ b/engines/ags/shared/game/roomstruct.cpp
@@ -201,6 +201,8 @@ Bitmap *RoomStruct::GetMask(RoomAreaMask mask) const {
 		return WalkAreaMask.get();
 	case kRoomAreaRegion:
 		return RegionMask.get();
+	default:
+		break;
 	}
 	return nullptr;
 }
@@ -213,6 +215,8 @@ float RoomStruct::GetMaskScale(RoomAreaMask mask) const {
 	case kRoomAreaWalkable:
 	case kRoomAreaRegion:
 		return 1.f / MaskResolution;
+	default:
+		break;
 	}
 	return 0.f;
 }
diff --git a/engines/ags/shared/gfx/allegrobitmap.cpp b/engines/ags/shared/gfx/allegrobitmap.cpp
index cb471b43e7..9071308340 100644
--- a/engines/ags/shared/gfx/allegrobitmap.cpp
+++ b/engines/ags/shared/gfx/allegrobitmap.cpp
@@ -231,7 +231,7 @@ void Bitmap::AAStretchBlt(Bitmap *src, const Rect &src_rc, const Rect &dst_rc, B
 		// TODO: aastr lib does not expose method for masked stretch blit; should do that at some point since
 		// the source code is a gift-ware anyway
 		// aa_masked_blit(_alBitmap, al_src_bmp, src_rc.Left, src_rc.Top, src_rc.GetWidth(), src_rc.GetHeight(), dst_rc.Left, dst_rc.Top, dst_rc.GetWidth(), dst_rc.GetHeight());
-		throw "aa_masked_blit is not yet supported!";
+		error("aa_masked_blit is not yet supported!");
 	} else {
 		aa_stretch_blit(al_src_bmp, _alBitmap,
 			src_rc.Left, src_rc.Top, src_rc.GetWidth(), src_rc.GetHeight(),
diff --git a/engines/ags/shared/util/memory.h b/engines/ags/shared/util/memory.h
index 29c6b791b5..b5cd1c1aed 100644
--- a/engines/ags/shared/util/memory.h
+++ b/engines/ags/shared/util/memory.h
@@ -32,6 +32,7 @@
 //include <string.h>
 #include "ags/shared/util/bbop.h"
 #include "ags/shared/util/math.h"
+#include "common/textconsole.h"
 
 namespace AGS3 {
 
@@ -50,11 +51,13 @@ namespace Memory {
 //-------------------------------------------------------------------------
 template <typename T>
 inline int32_t PtrToInt32(T *ptr) {
-	return static_cast<int32_t>(reinterpret_cast<intptr_t>(ptr));
+	error("TODO: Handle 32-bit pointers in ScummVM if needed");
+	//return static_cast<int32_t>(reinterpret_cast<intptr_t>(ptr));
 }
 template <typename T>
 inline T *Int32ToPtr(int32_t value) {
-	return reinterpret_cast<T *>(static_cast<intptr_t>(value));
+	error("TODO: Handle 32-bit pointers in ScummVM if needed");
+	//return reinterpret_cast<T *>(static_cast<intptr_t>(value));
 }
 
 //-------------------------------------------------------------------------
@@ -71,7 +74,7 @@ inline int16_t ReadInt16(const void *ptr) {
 	return (b[1] << 8) | b[0];
 #endif
 #else
-	return *(int16_t *)ptr;
+	return *(const int16_t *)ptr;
 #endif
 }
 
@@ -84,7 +87,7 @@ inline int32_t ReadInt32(const void *ptr) {
 	return (b[3] << 24) | (b[2] << 16) | (b[1] << 8) | b[0];
 #endif
 #else
-	return *(int32_t *)ptr;
+	return *(const int32_t *)ptr;
 #endif
 }
 
@@ -99,7 +102,7 @@ inline int64_t ReadInt64(const void *ptr) {
 		(b[3] << 24) | (b[2] << 16) | (b[1] << 8) | b[0];
 #endif
 #else
-	return *(int64_t *)ptr;
+	return *(const int64_t *)ptr;
 #endif
 }
 
diff --git a/engines/ags/std/map.h b/engines/ags/std/map.h
index 028cb7b71e..0c015ccaba 100644
--- a/engines/ags/std/map.h
+++ b/engines/ags/std/map.h
@@ -33,9 +33,22 @@ template<class Key, class Val, class HashFunc = Common::Hash<Key>,
          class EqualFunc = Common::EqualTo<Key> >
 class map : public Common::HashMap<Key, Val, HashFunc, EqualFunc> {
 public:
+	using iterator = typename Common::HashMap<Key, Val, HashFunc, EqualFunc>::iterator;
+
 	void insert(pair<Key, Val> elem) {
 		this->operator[](elem.first) = elem.second;
 	}
+
+	// FUNCTION TEMPLATE lower_bound
+	iterator lower_bound(Key &val) {
+		iterator it;
+		for (it = this->begin(); it != this->end(); ++it) {
+			if (it->_key >= val)
+				break;
+		}
+
+		return it;
+	}
 };
 
 template<class Key, class Val, class HashFunc = Common::Hash<Key>,
diff --git a/engines/ags/std/queue.h b/engines/ags/std/queue.h
new file mode 100644
index 0000000000..41c0653464
--- /dev/null
+++ b/engines/ags/std/queue.h
@@ -0,0 +1,37 @@
+/* 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 AGS_STD_QUEUE_H
+#define AGS_STD_QUEUE_H
+
+#include "common/queue.h"
+
+namespace AGS3 {
+namespace std {
+
+template<class T>
+using queue = Common::Queue<T>;
+
+} // namespace std
+} // namespace AGS3
+
+#endif


Commit: 3a8ce070887286ca1599da979cf8e6779b51c7b9
    https://github.com/scummvm/scummvm/commit/3a8ce070887286ca1599da979cf8e6779b51c7b9
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: gcc compilation fixes

Changed paths:
    engines/ags/engine/ac/dynobj/cc_dynamicarray.h
    engines/ags/engine/ac/dynobj/cc_dynamicobject.h
    engines/ags/engine/ac/dynobj/managedobjectpool.h
    engines/ags/engine/ac/dynobj/scriptuserobject.h
    engines/ags/engine/ac/statobj/staticarray.cpp
    engines/ags/engine/ac/statobj/staticarray.h
    engines/ags/engine/game/savegame.cpp
    engines/ags/engine/plugin/agsplugin.h
    engines/ags/engine/script/cc_instance.cpp
    engines/ags/engine/script/script.cpp
    engines/ags/engine/script/systemimports.cpp


diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicarray.h b/engines/ags/engine/ac/dynobj/cc_dynamicarray.h
index 309a8adbcf..aea7d06935 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicarray.h
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicarray.h
@@ -60,9 +60,11 @@ extern CCDynamicArray globalDynamicArray;
 
 // Helper functions for setting up dynamic arrays.
 namespace DynamicArrayHelpers {
+
 // Create array of managed strings
 DynObjectRef CreateStringArray(const std::vector<const char *>);
-};
+
+} // namespace DynamicArrayHelpers
 
 } // namespace AGS3
 
diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicobject.h b/engines/ags/engine/ac/dynobj/cc_dynamicobject.h
index 469aaa3503..93bc659351 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicobject.h
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicobject.h
@@ -96,10 +96,12 @@ protected:
 };
 
 struct ICCObjectReader {
+	virtual ~ICCObjectReader() {}
 	// TODO: pass savegame format version
 	virtual void Unserialize(int index, const char *objectType, const char *serializedData, int dataSize) = 0;
 };
 struct ICCStringClass {
+	virtual ~ICCStringClass() {}
 	virtual DynObjectRef CreateString(const char *fromText) = 0;
 };
 
diff --git a/engines/ags/engine/ac/dynobj/managedobjectpool.h b/engines/ags/engine/ac/dynobj/managedobjectpool.h
index 31366b02fa..a66f23c869 100644
--- a/engines/ags/engine/ac/dynobj/managedobjectpool.h
+++ b/engines/ags/engine/ac/dynobj/managedobjectpool.h
@@ -58,8 +58,8 @@ private:
 		ManagedObject()
 			: obj_type(kScValUndefined), handle(0), addr(nullptr), callback(nullptr), refCount(0) {
 		}
-		ManagedObject(ScriptValueType obj_type, int32_t handle, const char *addr, ICCDynamicObject *callback)
-			: obj_type(obj_type), handle(handle), addr(addr), callback(callback), refCount(0) {
+		ManagedObject(ScriptValueType obj_type_, int32_t handle_, const char *addr_, ICCDynamicObject *callback_)
+			: obj_type(obj_type_), handle(handle_), addr(addr_), callback(callback_), refCount(0) {
 		}
 	};
 
diff --git a/engines/ags/engine/ac/dynobj/scriptuserobject.h b/engines/ags/engine/ac/dynobj/scriptuserobject.h
index b4ff5418df..44ae8bf68c 100644
--- a/engines/ags/engine/ac/dynobj/scriptuserobject.h
+++ b/engines/ags/engine/ac/dynobj/scriptuserobject.h
@@ -79,9 +79,11 @@ private:
 
 // Helper functions for setting up custom managed structs based on ScriptUserObject.
 namespace ScriptStructHelpers {
+
 // Creates a managed Point object, represented as a pair of X and Y coordinates.
 ScriptUserObject *CreatePoint(int x, int y);
-};
+
+} // namespace ScriptStructHelpers
 
 } // namespace AGS3
 
diff --git a/engines/ags/engine/ac/statobj/staticarray.cpp b/engines/ags/engine/ac/statobj/staticarray.cpp
index 73fd3b27f8..d2fada026d 100644
--- a/engines/ags/engine/ac/statobj/staticarray.cpp
+++ b/engines/ags/engine/ac/statobj/staticarray.cpp
@@ -50,7 +50,11 @@ void StaticArray::Create(ICCDynamicObject *dynmgr, int elem_legacy_size, int ele
 	_elemCount = elem_count;
 }
 
-const char *StaticArray::GetElementPtr(const char *address, intptr_t legacy_offset) {
+const char *StaticArray::GetElementPtr(const char *address, intptr_t legacy_offset) const {
+	return address + (legacy_offset / _elemLegacySize) * _elemRealSize;
+}
+
+char *StaticArray::GetElementPtr(char *address, intptr_t legacy_offset) {
 	return address + (legacy_offset / _elemLegacySize) * _elemRealSize;
 }
 
diff --git a/engines/ags/engine/ac/statobj/staticarray.h b/engines/ags/engine/ac/statobj/staticarray.h
index 6176dc4384..1c9309c9da 100644
--- a/engines/ags/engine/ac/statobj/staticarray.h
+++ b/engines/ags/engine/ac/statobj/staticarray.h
@@ -44,7 +44,8 @@ public:
 		return _dynamicMgr;
 	}
 	// Legacy support for reading and writing object values by their relative offset
-	virtual const char *GetElementPtr(const char *address, intptr_t legacy_offset);
+	virtual const char *GetElementPtr(const char *address, intptr_t legacy_offset) const;
+	virtual char *GetElementPtr(char *address, intptr_t legacy_offset);
 
 	const char *GetFieldPtr(const char *address, intptr_t offset) override;
 	void    Read(const char *address, intptr_t offset, void *dest, int size) override;
diff --git a/engines/ags/engine/game/savegame.cpp b/engines/ags/engine/game/savegame.cpp
index b9678c25e6..f9adcdb69f 100644
--- a/engines/ags/engine/game/savegame.cpp
+++ b/engines/ags/engine/game/savegame.cpp
@@ -162,6 +162,8 @@ String GetSavegameErrorText(SavegameErrorType err) {
 		return "Saved with the engine running at a different colour depth.";
 	case kSvgErr_GameObjectInitFailed:
 		return "Game object initialization failed after save restoration.";
+	default:
+		break;
 	}
 	return "Unknown error.";
 }
@@ -449,7 +451,7 @@ HSaveError DoAfterRestore(const PreservedParams &pp, const RestoredData &r_data)
 	}
 
 	// restore these to the ones retrieved from the save game
-	const size_t dynsurf_num = Math::Min((size_t)MAX_DYNAMIC_SURFACES, r_data.DynamicSurfaces.size());
+	const size_t dynsurf_num = Math::Min((uint)MAX_DYNAMIC_SURFACES, r_data.DynamicSurfaces.size());
 	for (size_t i = 0; i < dynsurf_num; ++i) {
 		dynamicallyCreatedSurfaces[i] = r_data.DynamicSurfaces[i];
 	}
diff --git a/engines/ags/engine/plugin/agsplugin.h b/engines/ags/engine/plugin/agsplugin.h
index da60dda284..6b40b888a4 100644
--- a/engines/ags/engine/plugin/agsplugin.h
+++ b/engines/ags/engine/plugin/agsplugin.h
@@ -218,6 +218,8 @@ public:
 	int32 pluginId;   // used internally, do not touch this
 
 public:
+	virtual ~IAGSEditor() {}
+
 	// get the HWND of the main editor frame
 	AGSIFUNC(HWND) GetEditorHandle();
 	// get the HWND of the current active window
@@ -326,6 +328,8 @@ public:
 	int32 pluginId;   // used internally, do not touch
 
 public:
+	virtual ~IAGSEngine() {}
+
 	// quit the game
 	AGSIFUNC(void) AbortGame(const char *reason);
 	// get engine version
diff --git a/engines/ags/engine/script/cc_instance.cpp b/engines/ags/engine/script/cc_instance.cpp
index b76ee2cfdc..4bc07dde52 100644
--- a/engines/ags/engine/script/cc_instance.cpp
+++ b/engines/ags/engine/script/cc_instance.cpp
@@ -832,10 +832,10 @@ int ccInstance::Run(int32_t curpc) {
 		case SCMD_MEMWRITEPTR: {
 
 			int32_t handle = registers[SREG_MAR].ReadInt32();
-			char *address = nullptr;
+			const char *address = nullptr;
 
 			if (reg1.Type == kScValStaticArray && reg1.StcArr->GetDynamicManager()) {
-				address = (char *)reg1.StcArr->GetElementPtr(reg1.Ptr, reg1.IValue);
+				address = (const char *)reg1.StcArr->GetElementPtr(reg1.Ptr, reg1.IValue);
 			} else if (reg1.Type == kScValDynamicObject ||
 			           reg1.Type == kScValPluginObject) {
 				address = reg1.Ptr;
@@ -1152,7 +1152,7 @@ int ccInstance::Run(int32_t curpc) {
 				int currentStackSize = registers[SREG_SP].RValue - &stack[0];
 				int currentDataSize = stackdata_ptr - stackdata;
 				if (currentStackSize + 1 >= CC_STACK_SIZE ||
-				        currentDataSize + arg1.IValue >= CC_STACK_DATA_SIZE) {
+				        currentDataSize + arg1.IValue >= (int)CC_STACK_DATA_SIZE) {
 					cc_error("stack overflow, attempted grow to %d bytes", currentDataSize + arg1.IValue);
 					return -1;
 				}
diff --git a/engines/ags/engine/script/script.cpp b/engines/ags/engine/script/script.cpp
index 72217c857d..999d250427 100644
--- a/engines/ags/engine/script/script.cpp
+++ b/engines/ags/engine/script/script.cpp
@@ -322,7 +322,7 @@ bool DoRunScriptFuncCantBlock(ccInstance *sci, NonBlockingScriptFunction *funcTo
 	int result = 0;
 
 	if (funcToRun->numParameters < 3) {
-		result = sci->CallScriptFunction((char *)funcToRun->functionName, funcToRun->numParameters, funcToRun->params);
+		result = sci->CallScriptFunction((const char *)funcToRun->functionName, funcToRun->numParameters, funcToRun->params);
 	} else
 		quit("DoRunScriptFuncCantBlock called with too many parameters");
 
@@ -503,10 +503,10 @@ String GetScriptName(ccInstance *sci) {
 char bname[MAX_FUNCTION_NAME_LEN + 1], bne[MAX_FUNCTION_NAME_LEN + 1];
 char *make_ts_func_name(const char *base, int iii, int subd) {
 	int err = snprintf(bname, MAX_FUNCTION_NAME_LEN, base, iii);
-	if (err >= sizeof(bname))
+	if (err >= (int)sizeof(bname))
 		debug_script_warn("Function name length limit exceeded: %s (%d)", base, iii);
 	err = snprintf(bne, MAX_FUNCTION_NAME_LEN, "%s_%c", bname, subd + 'a');
-	if (err >= sizeof(bne))
+	if (err >= (int)sizeof(bne))
 		debug_script_warn("Function name length limit exceeded: %s", bname);
 	return &bne[0];
 }
diff --git a/engines/ags/engine/script/systemimports.cpp b/engines/ags/engine/script/systemimports.cpp
index cc94b15d5f..843e9f0119 100644
--- a/engines/ags/engine/script/systemimports.cpp
+++ b/engines/ags/engine/script/systemimports.cpp
@@ -99,7 +99,7 @@ int SystemImports::get_index_of(const String &name) {
 
 	if (name.GetLength() > 3) {
 		size_t c = name.FindCharReverse('^');
-		if (c != -1 && (c == name.GetLength() - 2 || c == name.GetLength() - 3)) {
+		if (c != String::npos && (c == name.GetLength() - 2 || c == name.GetLength() - 3)) {
 			// Function with number of prametrs on the end
 			// attempt to find it without the param count
 			return get_index_of(name.Left(c));


Commit: 76618e6d388edb435a1661a1cd6c8b173414c4a2
    https://github.com/scummvm/scummvm/commit/76618e6d388edb435a1661a1cd6c8b173414c4a2
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added engine/gfx/ folder

Changed paths:
  A engines/ags/lib/opengl/opengl.cpp
  A engines/ags/lib/opengl/opengl.h
    engines/ags/ags.cpp
    engines/ags/ags.h
    engines/ags/engine/gfx/ali3dogl.cpp
    engines/ags/engine/gfx/ali3dogl.h
    engines/ags/engine/gfx/ali3dsw.cpp
    engines/ags/engine/gfx/ali3dsw.h
    engines/ags/engine/gfx/blender.cpp
    engines/ags/engine/gfx/gfx_util.cpp
    engines/ags/engine/gfx/gfxdriverbase.cpp
    engines/ags/engine/gfx/gfxdriverbase.h
    engines/ags/engine/gfx/gfxdriverfactory.cpp
    engines/ags/engine/gfx/gfxdriverfactorybase.h
    engines/ags/engine/gfx/gfxfilter_aad3d.cpp
    engines/ags/engine/gfx/gfxfilter_aad3d.h
    engines/ags/engine/gfx/gfxfilter_aaogl.h
    engines/ags/engine/gfx/gfxfilter_allegro.cpp
    engines/ags/engine/gfx/gfxfilter_allegro.h
    engines/ags/engine/gfx/gfxfilter_d3d.cpp
    engines/ags/engine/gfx/gfxfilter_d3d.h
    engines/ags/engine/gfx/gfxfilter_hqx.cpp
    engines/ags/engine/gfx/gfxfilter_hqx.h
    engines/ags/engine/gfx/gfxfilter_ogl.cpp
    engines/ags/engine/gfx/gfxfilter_ogl.h
    engines/ags/engine/gfx/gfxfilter_scaling.cpp
    engines/ags/engine/gfx/gfxfilter_scaling.h
    engines/ags/engine/gfx/ogl_headers.h
    engines/ags/lib/aastr-0.1.1/aautil.cpp
    engines/ags/lib/allegro/alconfig.h
    engines/ags/lib/allegro/color.cpp
    engines/ags/lib/allegro/color.h
    engines/ags/lib/allegro/system.cpp
    engines/ags/lib/allegro/system.h
    engines/ags/module.mk
    engines/ags/shared/core/platform.h
    engines/ags/shared/core/types.h
    engines/ags/std/algorithm.h
    engines/ags/std/memory.h


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index ce3961461c..c5dc3afa71 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -35,7 +35,7 @@ AGSEngine *g_vm;
 /*------------------------------------------------------------------*/
 
 AGSEngine::AGSEngine(OSystem *syst, const AGSGameDescription *gameDesc) : Engine(syst),
-	_gameDescription(gameDesc), _randomSource("AGS") {
+	_gameDescription(gameDesc), _randomSource("AGS"), _screen(nullptr), _gfxDriver(nullptr) {
 	g_vm = this;
 	DebugMan.addDebugChannel(kDebugPath, "Path", "Pathfinding debug level");
 	DebugMan.addDebugChannel(kDebugGraphics, "Graphics", "Graphics debug level");
diff --git a/engines/ags/ags.h b/engines/ags/ags.h
index fce049973e..6e947b7c63 100644
--- a/engines/ags/ags.h
+++ b/engines/ags/ags.h
@@ -33,6 +33,9 @@
 #include "engines/savestate.h"
 #include "graphics/surface.h"
 
+#include "ags/shared/gfx/bitmap.h"
+#include "ags/lib/allegro/system.h"
+
 namespace AGS {
 
 #define SCREEN_WIDTH 320
@@ -49,6 +52,9 @@ class AGSEngine : public Engine {
 private:
 	const AGSGameDescription *_gameDescription;
 	Common::RandomSource _randomSource;
+public:
+	::AGS3::BITMAP *_screen;
+	::AGS3::GFX_DRIVER *_gfxDriver;
 protected:
 	// Engine APIs
 	virtual Common::Error run();
@@ -84,6 +90,8 @@ public:
 };
 
 extern AGSEngine *g_vm;
+#define screen ::AGS::g_vm->_screen
+#define gfx_driver ::AGS::g_vm->_gfxDriver
 
 } // namespace AGS
 
diff --git a/engines/ags/engine/gfx/ali3dogl.cpp b/engines/ags/engine/gfx/ali3dogl.cpp
index 06355a0fa6..11e19838f6 100644
--- a/engines/ags/engine/gfx/ali3dogl.cpp
+++ b/engines/ags/engine/gfx/ali3dogl.cpp
@@ -24,16 +24,17 @@
 
 #if AGS_PLATFORM_OS_WINDOWS || AGS_PLATFORM_OS_ANDROID || AGS_PLATFORM_OS_IOS || AGS_PLATFORM_OS_LINUX
 
-//include <algorithm>
-#include "ags/shared/gfx/ali3dexception.h"
-#include "ags/shared/gfx/ali3dogl.h"
-#include "ags/shared/gfx/gfxfilter_ogl.h"
-#include "ags/shared/gfx/gfxfilter_aaogl.h"
-#include "ags/shared/gfx/gfx_util.h"
-#include "ags/shared/main/main_allegro.h"
-#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/std/algorithm.h"
+#include "ags/engine/gfx/ali3dexception.h"
+#include "ags/engine/gfx/ali3dogl.h"
+#include "ags/engine/gfx/gfxfilter_ogl.h"
+#include "ags/engine/gfx/gfxfilter_aaogl.h"
+#include "ags/engine/gfx/gfx_util.h"
+#include "ags/engine/main/main_allegro.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
 #include "ags/shared/util/math.h"
-#include "ags/shared/ac/timer.h"
+#include "ags/engine/ac/timer.h"
+#include "ags/ags.h"
 
 namespace AGS3 {
 
@@ -132,6 +133,8 @@ void ogl_dummy_vsync() { }
 
 #define GFX_OPENGL  AL_ID('O','G','L',' ')
 
+static const char *empty_string = "";
+
 GFX_DRIVER gfx_opengl = {
 	GFX_OPENGL,
 	empty_string,
@@ -335,6 +338,7 @@ void OGLGraphicsDriver::FirstTimeInit() {
 	_firstTimeInit = true;
 }
 
+#if !AGS_PLATFORM_SCUMMVM
 #if AGS_PLATFORM_OS_LINUX
 Atom get_x_atom(const char *atom_name) {
 	Atom atom = XInternAtom(_xwin.display, atom_name, False);
@@ -344,6 +348,7 @@ Atom get_x_atom(const char *atom_name) {
 	return atom;
 }
 #endif
+#endif
 
 bool OGLGraphicsDriver::InitGlScreen(const DisplayMode &mode) {
 #if AGS_PLATFORM_OS_ANDROID
@@ -397,6 +402,9 @@ bool OGLGraphicsDriver::InitGlScreen(const DisplayMode &mode) {
 
 	CreateDesktopScreen(mode.Width, mode.Height, mode.ColorDepth);
 	win_grab_input();
+#elif AGS_PLATFORM_SCUMMVM
+	warning("TODO: InitGlScreen");
+
 #elif AGS_PLATFORM_OS_LINUX
 	if (!_have_window) {
 		// Use Allegro to create our window. We don't care what size Allegro uses
@@ -516,7 +524,9 @@ void OGLGraphicsDriver::InitGlParams(const DisplayMode &mode) {
 	glEnableClientState(GL_VERTEX_ARRAY);
 	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
 
+#if !AGS_PLATFORM_SCUMMVM
 	auto interval = mode.Vsync ? 1 : 0;
+#endif
 	bool vsyncEnabled = false;
 
 #if AGS_PLATFORM_OS_WINDOWS
@@ -525,6 +535,7 @@ void OGLGraphicsDriver::InitGlParams(const DisplayMode &mode) {
 	}
 #endif
 
+#if !AGS_PLATFORM_SCUMMVM
 #if AGS_PLATFORM_OS_LINUX
 	if (GLAD_GLX_EXT_swap_control) {
 		glXSwapIntervalEXT(_xwin.display, _xwin.window, interval);
@@ -535,6 +546,7 @@ void OGLGraphicsDriver::InitGlParams(const DisplayMode &mode) {
 	} else if (GLAD_GLX_SGI_swap_control) {
 		vsyncEnabled = glXSwapIntervalSGI(interval) == 0;
 	}
+#endif
 #endif
 
 	// TODO: find out how to implement SwapInterval on other platforms, and how to check if it's supported
@@ -559,7 +571,9 @@ void OGLGraphicsDriver::InitGlParams(const DisplayMode &mode) {
 }
 
 bool OGLGraphicsDriver::CreateGlContext(const DisplayMode &mode) {
-#if AGS_PLATFORM_OS_WINDOWS
+#if AGS_PLATFORM_SCUMMVM
+	warning("TODO: CreateGlContext");
+#elif AGS_PLATFORM_OS_WINDOWS
 	PIXELFORMATDESCRIPTOR pfd = {
 		sizeof(PIXELFORMATDESCRIPTOR),
 		1,
@@ -594,8 +608,7 @@ bool OGLGraphicsDriver::CreateGlContext(const DisplayMode &mode) {
 
 	if (!wglMakeCurrent(_hDC, _hRC))
 		return false;
-#endif // AGS_PLATFORM_OS_WINDOWS
-#if AGS_PLATFORM_OS_LINUX
+#elif AGS_PLATFORM_OS_LINUX
 	int attrib[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
 	XVisualInfo *vi = glXChooseVisual(_xwin.display, DefaultScreen(_xwin.display), attrib);
 	if (!vi) {
@@ -617,7 +630,9 @@ bool OGLGraphicsDriver::CreateGlContext(const DisplayMode &mode) {
 }
 
 void OGLGraphicsDriver::DeleteGlContext() {
-#if AGS_PLATFORM_OS_WINDOWS
+#if AGS_PLATFORM_SCUMMVM
+	warning("TODO: DeleteGlContext");
+#elif AGS_PLATFORM_OS_WINDOWS
 	if (_hRC) {
 		wglMakeCurrent(NULL, NULL);
 		wglDeleteContext(_hRC);
@@ -663,6 +678,7 @@ void OGLGraphicsDriver::TestRenderToTexture() {
 }
 
 void OGLGraphicsDriver::TestSupersampling() {
+#if !AGS_PLATFORM_SCUMMVM
 	if (!_can_render_to_texture)
 		return;
 	// Disable super-sampling if it would cause a too large texture size
@@ -672,6 +688,7 @@ void OGLGraphicsDriver::TestSupersampling() {
 		if ((max < _srcRect.GetWidth() * _super_sampling) || (max < _srcRect.GetHeight() * _super_sampling))
 			_super_sampling = 1;
 	}
+#endif
 }
 
 void OGLGraphicsDriver::CreateShaders() {
@@ -768,6 +785,7 @@ void OGLGraphicsDriver::CreateLightShader() {
 
 void OGLGraphicsDriver::CreateShaderProgram(ShaderProgram &prg, const char *name, const char *fragment_shader_src,
         const char *sampler_var, const char *color_var, const char *aux_var) {
+#if !AGS_PLATFORM_SCUMMVM
 	GLint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
 	glShaderSource(fragment_shader, 1, &fragment_shader_src, nullptr);
 	glCompileShader(fragment_shader);
@@ -797,6 +815,7 @@ void OGLGraphicsDriver::CreateShaderProgram(ShaderProgram &prg, const char *name
 	prg.ColorVar = glGetUniformLocation(program, color_var);
 	prg.AuxVar = glGetUniformLocation(program, aux_var);
 	Debug::Printf("OGL: %s shader program created successfully", name);
+#endif
 }
 
 void OGLGraphicsDriver::DeleteShaderProgram(ShaderProgram &prg) {
@@ -806,6 +825,7 @@ void OGLGraphicsDriver::DeleteShaderProgram(ShaderProgram &prg) {
 }
 
 void OGLGraphicsDriver::OutputShaderError(GLuint obj_id, const String &obj_name, bool is_shader) {
+#ifdef TODO
 	GLint log_len;
 	if (is_shader)
 		glGetShaderiv(obj_id, GL_INFO_LOG_LENGTH, &log_len);
@@ -827,6 +847,9 @@ void OGLGraphicsDriver::OutputShaderError(GLuint obj_id, const String &obj_name,
 	} else {
 		Debug::Printf(kDbgMsg_Error, "Shader info log was empty.");
 	}
+#else
+	error("Obj Id=%u, Name=%s, Is Shader=%d", obj_id, obj_name.GetNullableCStr(), (int)is_shader);
+#endif
 }
 
 void OGLGraphicsDriver::SetupBackbufferTexture() {
@@ -835,7 +858,7 @@ void OGLGraphicsDriver::SetupBackbufferTexture() {
 	// both native size set and context capabilities test passed.
 	if (!IsNativeSizeValid() || !_can_render_to_texture)
 		return;
-
+#if !AGS_PLATFORM_SCUMMVM
 	DeleteBackbufferTexture();
 
 	// _backbuffer_texture_coordinates defines translation from wanted texture size to actual supported texture size
@@ -863,7 +886,7 @@ void OGLGraphicsDriver::SetupBackbufferTexture() {
 	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, _backbuffer, 0);
 
 	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
-
+#endif
 	// Assign vertices of the backbuffer texture position in the scene
 	_backbuffer_vertices[0] = _backbuffer_vertices[4] = 0;
 	_backbuffer_vertices[2] = _backbuffer_vertices[6] = _srcRect.GetWidth();
@@ -901,17 +924,17 @@ bool OGLGraphicsDriver::SetDisplayMode(const DisplayMode &mode, volatile int *lo
 		return false;
 	}
 
-	try {
+//	try {
 		if (!InitGlScreen(mode))
 			return false;
 		if (!_firstTimeInit)
 			FirstTimeInit();
 		InitGlParams(mode);
-	} catch (Ali3DException exception) {
+/*	} catch (Ali3DException exception) {
 		if (exception._message != get_allegro_error())
 			set_allegro_error(exception._message);
 		return false;
-	}
+	}*/
 
 	OnInit(loopTimer);
 
@@ -1307,7 +1330,9 @@ void OGLGraphicsDriver::_render(bool clearDrawListAfterwards) {
 
 	glFinish();
 
-#if AGS_PLATFORM_OS_WINDOWS
+#if AGS_PLATFORM_SCUMMVM
+	g_system->updateScreen();
+#elif AGS_PLATFORM_OS_WINDOWS
 	SwapBuffers(_hDC);
 #elif AGS_PLATFORM_OS_LINUX
 	glXSwapBuffers(_xwin.display, _xwin.window);
diff --git a/engines/ags/engine/gfx/ali3dogl.h b/engines/ags/engine/gfx/ali3dogl.h
index fde7c439aa..c3f944d358 100644
--- a/engines/ags/engine/gfx/ali3dogl.h
+++ b/engines/ags/engine/gfx/ali3dogl.h
@@ -31,13 +31,13 @@
 
 #include "ags/std/memory.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/gfx/ddb.h"
-#include "ags/shared/gfx/gfxdriverfactorybase.h"
-#include "ags/shared/gfx/gfxdriverbase.h"
+#include "ags/engine/gfx/ddb.h"
+#include "ags/engine/gfx/gfxdriverfactorybase.h"
+#include "ags/engine/gfx/gfxdriverbase.h"
 #include "ags/shared/util/string.h"
 #include "ags/shared/util/version.h"
 
-#include "ags/shared/ogl_headers.h"
+#include "ags/engine/gfx/ogl_headers.h"
 
 namespace AGS3 {
 namespace AGS {
@@ -47,7 +47,7 @@ namespace OGL {
 
 using Shared::Bitmap;
 using Shared::String;
-using Common::Version;
+using Shared::Version;
 
 typedef struct _OGLVECTOR {
 	float x;
diff --git a/engines/ags/engine/gfx/ali3dsw.cpp b/engines/ags/engine/gfx/ali3dsw.cpp
index ec380f7c12..e56761a422 100644
--- a/engines/ags/engine/gfx/ali3dsw.cpp
+++ b/engines/ags/engine/gfx/ali3dsw.cpp
@@ -26,16 +26,19 @@
 //
 //=============================================================================
 
-#include "ags/shared/gfx/ali3dsw.h"
-
+#include "ags/engine/gfx/ali3dsw.h"
 #include "ags/shared/core/platform.h"
-#include "ags/shared/gfx/ali3dexception.h"
-#include "ags/shared/gfx/gfxfilter_allegro.h"
-#include "ags/shared/gfx/gfxfilter_hqx.h"
-#include "ags/shared/gfx/gfx_util.h"
-#include "ags/shared/main/main_allegro.h"
-#include "ags/shared/platform/base/agsplatformdriver.h"
-#include "ags/shared/ac/timer.h"
+#include "ags/engine/gfx/ali3dexception.h"
+#include "ags/engine/gfx/gfxfilter_allegro.h"
+#include "ags/engine/gfx/gfxfilter_hqx.h"
+#include "ags/engine/gfx/gfx_util.h"
+#include "ags/engine/main/main_allegro.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
+#include "ags/engine/ac/timer.h"
+#include "ags/lib/allegro/color.h"
+#include "ags/lib/opengl/opengl.h"
+#include "ags/std/algorithm.h"
+#include "ags/ags.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gfx/ali3dsw.h b/engines/ags/engine/gfx/ali3dsw.h
index 91b192782e..a9e2a4fb29 100644
--- a/engines/ags/engine/gfx/ali3dsw.h
+++ b/engines/ags/engine/gfx/ali3dsw.h
@@ -42,9 +42,9 @@
 #endif
 
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/gfx/ddb.h"
-#include "ags/shared/gfx/gfxdriverfactorybase.h"
-#include "ags/shared/gfx/gfxdriverbase.h"
+#include "ags/engine/gfx/ddb.h"
+#include "ags/engine/gfx/gfxdriverfactorybase.h"
+#include "ags/engine/gfx/gfxdriverbase.h"
 
 namespace AGS3 {
 namespace AGS {
@@ -124,7 +124,7 @@ public:
 
 class ALSoftwareGfxModeList : public IGfxModeList {
 public:
-	ALSoftwareGfxModeList(GFX_MODE_LIST *alsw_gfx_mode_list)
+	ALSoftwareGfxModeList(const GFX_MODE_LIST *alsw_gfx_mode_list)
 		: _gfxModeList(alsw_gfx_mode_list) {
 	}
 
@@ -135,7 +135,7 @@ public:
 	bool GetMode(int index, DisplayMode &mode) const override;
 
 private:
-	GFX_MODE_LIST *_gfxModeList;
+	const GFX_MODE_LIST *_gfxModeList;
 };
 
 
diff --git a/engines/ags/engine/gfx/blender.cpp b/engines/ags/engine/gfx/blender.cpp
index e4eb457e7a..549c74f53c 100644
--- a/engines/ags/engine/gfx/blender.cpp
+++ b/engines/ags/engine/gfx/blender.cpp
@@ -21,8 +21,9 @@
  */
 
 #include "ags/shared/core/types.h"
-#include "ags/shared/gfx/blender.h"
+#include "ags/engine/gfx/blender.h"
 #include "ags/shared/util/wgt2allg.h"
+#include "ags/lib/allegro/color.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gfx/gfx_util.cpp b/engines/ags/engine/gfx/gfx_util.cpp
index aadbb940a4..d6ff6d19ae 100644
--- a/engines/ags/engine/gfx/gfx_util.cpp
+++ b/engines/ags/engine/gfx/gfx_util.cpp
@@ -21,8 +21,8 @@
  */
 
 #include "ags/shared/core/platform.h"
-#include "ags/shared/gfx/gfx_util.h"
-#include "ags/shared/gfx/blender.h"
+#include "ags/engine/gfx/gfx_util.h"
+#include "ags/engine/gfx/blender.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gfx/gfxdriverbase.cpp b/engines/ags/engine/gfx/gfxdriverbase.cpp
index d1dd038ab8..b8947b7617 100644
--- a/engines/ags/engine/gfx/gfxdriverbase.cpp
+++ b/engines/ags/engine/gfx/gfxdriverbase.cpp
@@ -21,11 +21,12 @@
  */
 
 #include "ags/shared/util/wgt2allg.h"
-#include "ags/shared/gfx/ali3dexception.h"
+#include "ags/engine/gfx/ali3dexception.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/gfx/gfxfilter.h"
-#include "ags/shared/gfx/gfxdriverbase.h"
-#include "ags/shared/gfx/gfx_util.h"
+#include "ags/engine/gfx/gfxfilter.h"
+#include "ags/engine/gfx/gfxdriverbase.h"
+#include "ags/engine/gfx/gfx_util.h"
+#include "ags/engine/ac/draw.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/gfx/gfxdriverbase.h b/engines/ags/engine/gfx/gfxdriverbase.h
index b845de3b4a..88f83fa6b0 100644
--- a/engines/ags/engine/gfx/gfxdriverbase.h
+++ b/engines/ags/engine/gfx/gfxdriverbase.h
@@ -30,9 +30,9 @@
 #define AGS_ENGINE_GFX_GFXDRIVERBASE_H
 
 #include "ags/std/vector.h"
-#include "ags/shared/gfx/ddb.h"
-#include "ags/shared/gfx/graphicsdriver.h"
-#include "ags/shared/util/scaling.h"
+#include "ags/engine/gfx/ddb.h"
+#include "ags/engine/gfx/graphicsdriver.h"
+#include "ags/engine/util/scaling.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/gfxdriverfactory.cpp b/engines/ags/engine/gfx/gfxdriverfactory.cpp
index 00dcbf5211..61954f52d2 100644
--- a/engines/ags/engine/gfx/gfxdriverfactory.cpp
+++ b/engines/ags/engine/gfx/gfxdriverfactory.cpp
@@ -20,27 +20,27 @@
  *
  */
 
-#include "ags/shared/gfx/gfxdriverfactory.h"
+#include "ags/engine/gfx/gfxdriverfactory.h"
 
 #include "ags/shared/core/platform.h"
 
 #define AGS_HAS_DIRECT3D (AGS_PLATFORM_OS_WINDOWS)
 #define AGS_HAS_OPENGL (AGS_PLATFORM_OS_WINDOWS || AGS_PLATFORM_OS_ANDROID || AGS_PLATFORM_OS_IOS || AGS_PLATFORM_OS_LINUX)
 
-#include "ags/shared/gfx/ali3dsw.h"
-#include "ags/shared/gfx/gfxfilter_allegro.h"
+#include "ags/engine/gfx/ali3dsw.h"
+#include "ags/engine/gfx/gfxfilter_allegro.h"
 
 #if AGS_HAS_OPENGL
-#include "ags/shared/gfx/ali3dogl.h"
-#include "ags/shared/gfx/gfxfilter_ogl.h"
+#include "ags/engine/gfx/ali3dogl.h"
+#include "ags/engine/gfx/gfxfilter_ogl.h"
 #endif
 
 #if AGS_HAS_DIRECT3D
-#include "ags/shared/platform/windows/gfx/ali3dd3d.h"
-#include "ags/shared/gfx/gfxfilter_d3d.h"
+#include "ags/engine/platform/windows/gfx/ali3dd3d.h"
+#include "ags/engine/gfx/gfxfilter_d3d.h"
 #endif
 
-#include "ags/shared/main/main_allegro.h"
+#include "ags/engine/main/main_allegro.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/gfxdriverfactorybase.h b/engines/ags/engine/gfx/gfxdriverfactorybase.h
index 5424ea7c89..8a1d66d567 100644
--- a/engines/ags/engine/gfx/gfxdriverfactorybase.h
+++ b/engines/ags/engine/gfx/gfxdriverfactorybase.h
@@ -34,8 +34,8 @@
 #define AGS_ENGINE_GFX_GFXDRIVERFACTORYBASE_H
 
 #include "ags/std/vector.h"
-#include "ags/shared/gfx/gfxdriverfactory.h"
-#include "ags/shared/gfx/gfxfilter.h"
+#include "ags/engine/gfx/gfxdriverfactory.h"
+#include "ags/engine/gfx/gfxfilter.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/gfxfilter_aad3d.cpp b/engines/ags/engine/gfx/gfxfilter_aad3d.cpp
index eebfbbbed5..fd2161174f 100644
--- a/engines/ags/engine/gfx/gfxfilter_aad3d.cpp
+++ b/engines/ags/engine/gfx/gfxfilter_aad3d.cpp
@@ -21,8 +21,7 @@
  */
 
 #include "ags/shared/core/platform.h"
-#include "ags/shared/stdio.h"
-#include "ags/shared/gfx/gfxfilter_aad3d.h"
+#include "ags/engine/gfx/gfxfilter_aad3d.h"
 
 #if AGS_PLATFORM_OS_WINDOWS
 //include <d3d9.h>
diff --git a/engines/ags/engine/gfx/gfxfilter_aad3d.h b/engines/ags/engine/gfx/gfxfilter_aad3d.h
index 351cfa22b6..5396e749cc 100644
--- a/engines/ags/engine/gfx/gfxfilter_aad3d.h
+++ b/engines/ags/engine/gfx/gfxfilter_aad3d.h
@@ -29,7 +29,7 @@
 #ifndef AGS_ENGINE_GFX_AAD3DGFXFILTER_H
 #define AGS_ENGINE_GFX_AAD3DGFXFILTER_H
 
-#include "ags/shared/gfx/gfxfilter_d3d.h"
+#include "ags/engine/gfx/gfxfilter_d3d.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/gfxfilter_aaogl.h b/engines/ags/engine/gfx/gfxfilter_aaogl.h
index 6c40365494..071cfc7b91 100644
--- a/engines/ags/engine/gfx/gfxfilter_aaogl.h
+++ b/engines/ags/engine/gfx/gfxfilter_aaogl.h
@@ -29,7 +29,7 @@
 #ifndef AGS_ENGINE_GFX_AAOGLGFXFILTER_H
 #define AGS_ENGINE_GFX_AAOGLGFXFILTER_H
 
-#include "ags/shared/gfx/gfxfilter_ogl.h"
+#include "ags/engine/gfx/gfxfilter_ogl.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/gfxfilter_allegro.cpp b/engines/ags/engine/gfx/gfxfilter_allegro.cpp
index b1f1a93ed1..94640f0dae 100644
--- a/engines/ags/engine/gfx/gfxfilter_allegro.cpp
+++ b/engines/ags/engine/gfx/gfxfilter_allegro.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/shared/gfx/gfxfilter_allegro.h"
+#include "ags/engine/gfx/gfxfilter_allegro.h"
 
 namespace AGS3 {
 namespace AGS {
@@ -98,13 +98,13 @@ void AllegroGfxFilter::RenderScreenFlipped(Bitmap *toRender, int x, int y, Globa
 
 	switch (flipType) {
 	case kFlip_Horizontal:
-		virtualScreen->FlipBlt(toRender, 0, 0, Common::kBitmap_HFlip);
+		virtualScreen->FlipBlt(toRender, 0, 0, Shared::kBitmap_HFlip);
 		break;
 	case kFlip_Vertical:
-		virtualScreen->FlipBlt(toRender, 0, 0, Common::kBitmap_VFlip);
+		virtualScreen->FlipBlt(toRender, 0, 0, Shared::kBitmap_VFlip);
 		break;
 	case kFlip_Both:
-		virtualScreen->FlipBlt(toRender, 0, 0, Common::kBitmap_HVFlip);
+		virtualScreen->FlipBlt(toRender, 0, 0, Shared::kBitmap_HVFlip);
 		break;
 	default:
 		virtualScreen->Blit(toRender, 0, 0);
diff --git a/engines/ags/engine/gfx/gfxfilter_allegro.h b/engines/ags/engine/gfx/gfxfilter_allegro.h
index e0906d41d5..d1aba15421 100644
--- a/engines/ags/engine/gfx/gfxfilter_allegro.h
+++ b/engines/ags/engine/gfx/gfxfilter_allegro.h
@@ -30,8 +30,8 @@
 #define AGS_ENGINE_GFX_ALLEGROGFXFILTER_H
 
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/gfx/gfxfilter_scaling.h"
-#include "ags/shared/gfx/gfxdefines.h"
+#include "ags/engine/gfx/gfxfilter_scaling.h"
+#include "ags/engine/gfx/gfxdefines.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/gfxfilter_d3d.cpp b/engines/ags/engine/gfx/gfxfilter_d3d.cpp
index 9e4eb302e5..ecba7a45c6 100644
--- a/engines/ags/engine/gfx/gfxfilter_d3d.cpp
+++ b/engines/ags/engine/gfx/gfxfilter_d3d.cpp
@@ -21,7 +21,7 @@
  */
 
 #include "ags/shared/core/platform.h"
-#include "ags/shared/gfx/gfxfilter_d3d.h"
+#include "ags/engine/gfx/gfxfilter_d3d.h"
 #if AGS_PLATFORM_OS_WINDOWS
 //include <d3d9.h>
 #endif
diff --git a/engines/ags/engine/gfx/gfxfilter_d3d.h b/engines/ags/engine/gfx/gfxfilter_d3d.h
index e5cd2b2395..c4be89a8ca 100644
--- a/engines/ags/engine/gfx/gfxfilter_d3d.h
+++ b/engines/ags/engine/gfx/gfxfilter_d3d.h
@@ -29,7 +29,7 @@
 #ifndef AGS_ENGINE_GFX_D3DGFXFILTER_H
 #define AGS_ENGINE_GFX_D3DGFXFILTER_H
 
-#include "ags/shared/gfx/gfxfilter_scaling.h"
+#include "ags/engine/gfx/gfxfilter_scaling.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/gfxfilter_hqx.cpp b/engines/ags/engine/gfx/gfxfilter_hqx.cpp
index 2acd26f0d4..cd46a97c50 100644
--- a/engines/ags/engine/gfx/gfxfilter_hqx.cpp
+++ b/engines/ags/engine/gfx/gfxfilter_hqx.cpp
@@ -21,8 +21,8 @@
  */
 
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/gfx/gfxfilter_hqx.h"
-#include "ags/shared/gfx/hq2x3x.h"
+#include "ags/engine/gfx/gfxfilter_hqx.h"
+#include "ags/engine/gfx/hq2x3x.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/gfxfilter_hqx.h b/engines/ags/engine/gfx/gfxfilter_hqx.h
index 8cc897357f..06a1e45bfd 100644
--- a/engines/ags/engine/gfx/gfxfilter_hqx.h
+++ b/engines/ags/engine/gfx/gfxfilter_hqx.h
@@ -29,7 +29,7 @@
 #ifndef AGS_ENGINE_GFX_HQ2XGFXFILTER_H
 #define AGS_ENGINE_GFX_HQ2XGFXFILTER_H
 
-#include "ags/shared/gfx/gfxfilter_allegro.h"
+#include "ags/engine/gfx/gfxfilter_allegro.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/gfxfilter_ogl.cpp b/engines/ags/engine/gfx/gfxfilter_ogl.cpp
index 3615d025b1..44edd0db5f 100644
--- a/engines/ags/engine/gfx/gfxfilter_ogl.cpp
+++ b/engines/ags/engine/gfx/gfxfilter_ogl.cpp
@@ -24,8 +24,8 @@
 
 #if AGS_PLATFORM_OS_WINDOWS || AGS_PLATFORM_OS_ANDROID || AGS_PLATFORM_OS_IOS || AGS_PLATFORM_OS_LINUX
 
-#include "ags/shared/gfx/gfxfilter_ogl.h"
-#include "ags/shared/ogl_headers.h"
+#include "ags/engine/gfx/gfxfilter_ogl.h"
+#include "ags/engine/gfx/ogl_headers.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/gfxfilter_ogl.h b/engines/ags/engine/gfx/gfxfilter_ogl.h
index 786dba62c2..a6d5b9bbdb 100644
--- a/engines/ags/engine/gfx/gfxfilter_ogl.h
+++ b/engines/ags/engine/gfx/gfxfilter_ogl.h
@@ -29,7 +29,7 @@
 #ifndef AGS_ENGINE_GFX_OGLGFXFILTER_H
 #define AGS_ENGINE_GFX_OGLGFXFILTER_H
 
-#include "ags/shared/gfx/gfxfilter_scaling.h"
+#include "ags/engine/gfx/gfxfilter_scaling.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/gfxfilter_scaling.cpp b/engines/ags/engine/gfx/gfxfilter_scaling.cpp
index 71cbb5af3b..d57aa8c5ec 100644
--- a/engines/ags/engine/gfx/gfxfilter_scaling.cpp
+++ b/engines/ags/engine/gfx/gfxfilter_scaling.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/shared/gfx/gfxfilter_scaling.h"
+#include "ags/engine/gfx/gfxfilter_scaling.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/gfxfilter_scaling.h b/engines/ags/engine/gfx/gfxfilter_scaling.h
index 52f420979e..21020f15cc 100644
--- a/engines/ags/engine/gfx/gfxfilter_scaling.h
+++ b/engines/ags/engine/gfx/gfxfilter_scaling.h
@@ -29,8 +29,8 @@
 #ifndef AGS_ENGINE_GFX_SCALINGGFXFILTER_H
 #define AGS_ENGINE_GFX_SCALINGGFXFILTER_H
 
-#include "ags/shared/gfx/gfxfilter.h"
-#include "ags/shared/util/scaling.h"
+#include "ags/engine/gfx/gfxfilter.h"
+#include "ags/engine/util/scaling.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/gfx/ogl_headers.h b/engines/ags/engine/gfx/ogl_headers.h
index 6fa7e481b8..b3591766c3 100644
--- a/engines/ags/engine/gfx/ogl_headers.h
+++ b/engines/ags/engine/gfx/ogl_headers.h
@@ -28,7 +28,9 @@
 
 #include "ags/shared/core/platform.h"
 
-#if AGS_PLATFORM_OS_WINDOWS
+#if AGS_PLATFORM_SCUMMVM
+#include "ags/lib/opengl/opengl.h"
+#elif AGS_PLATFORM_OS_WINDOWS
 #include "ags/lib/allegro.h"
 //include <winalleg.h>
 //include <allegro/platform/aintwin.h>
@@ -41,8 +43,8 @@
 //include <xalleg.h>
 //include <X11/Xatom.h>
 
-#include "ags/shared/glad/glad.h"
-#include "ags/shared/glad/glad_glx.h"
+//include "glad/glad.h"
+//include "glad/glad_glx.h"
 
 #elif AGS_PLATFORM_OS_ANDROID
 
diff --git a/engines/ags/lib/aastr-0.1.1/aautil.cpp b/engines/ags/lib/aastr-0.1.1/aautil.cpp
index 25b789c36f..ebd0889cf3 100644
--- a/engines/ags/lib/aastr-0.1.1/aautil.cpp
+++ b/engines/ags/lib/aastr-0.1.1/aautil.cpp
@@ -725,7 +725,7 @@ _aa_add_rgb32 (BITMAP *_src, int _sx1, int _sx2, int _sy1, int _sy2, unsigned lo
 void
 _aa_put_rgb8 (unsigned long _addr, int _x)
 {
-  bmp_write8 (_addr + _x, makecol8 (_aa.r, _aa.g, _aa.b));
+  bmp_write8 (_addr + _x, makecol8(_aa.r, _aa.g, _aa.b));
 }
 #ifdef ALLEGRO_COLOR16
 void
diff --git a/engines/ags/lib/allegro/alconfig.h b/engines/ags/lib/allegro/alconfig.h
index c6dc71b84f..7e390ee09c 100644
--- a/engines/ags/lib/allegro/alconfig.h
+++ b/engines/ags/lib/allegro/alconfig.h
@@ -39,7 +39,7 @@ namespace AGS3 {
 #endif
 
 #ifndef AL_CONST
-#define AL_CONST
+#define AL_CONST                                const
 #endif
 
 #ifndef AL_VAR
diff --git a/engines/ags/lib/allegro/color.cpp b/engines/ags/lib/allegro/color.cpp
index 6756d1ab2c..5126e5c62e 100644
--- a/engines/ags/lib/allegro/color.cpp
+++ b/engines/ags/lib/allegro/color.cpp
@@ -41,6 +41,9 @@ int _rgb_g_shift_32 = 0;
 int _rgb_b_shift_32 = 0;
 int _rgb_a_shift_32 = 0;
 
+AL_ARRAY(int, _rgb_scale_5);
+AL_ARRAY(int, _rgb_scale_6);
+
 PALETTE _current_palette;
 
 int bestfit_color(const PALETTE pal, int r, int g, int b) {
@@ -53,9 +56,9 @@ void set_color(int idx, const RGB *p) {
 }
 
 void set_palette(const PALETTE p) {
-	for (int idx = 0; idx < PALETTE_COUNT; ++idx)
+	for (int idx = 0; idx < PAL_SIZE; ++idx)
 		_current_palette[idx] = p[idx];
-	g_system->getPaletteManager()->setPalette((const byte *)p, 0, PALETTE_COUNT);
+	g_system->getPaletteManager()->setPalette((const byte *)p, 0, PAL_SIZE);
 }
 
 void set_palette_range(const PALETTE p, int from, int to, int retracesync) {
@@ -76,7 +79,15 @@ int makeacol(int r, int g, int b, int a) {
 }
 
 int makeacol_depth(int color_depth, int r, int g, int b, int a) {
-	error("makeacol_depth");
+	error("TODO: makeacol_depth");
+}
+
+void hsv_to_rgb(float h, float s, float v, int *r, int *g, int *b) {
+	error("TODO: hsv_to_rgb");
+}
+
+void rgb_to_hsv(int r, int g, int b, float *h, float *s, float *v) {
+	error("TODO: rgb_to_hsv");
 }
 
 int makecol15(int r, int g, int b) {
@@ -122,6 +133,46 @@ int getb8(int c) {
 	return (int)_current_palette[c].b;
 }
 
+int getr15(int c) {
+   return _rgb_scale_5[(c >> _rgb_r_shift_15) & 0x1F];
+}
+
+int getg15(int c) {
+	return _rgb_scale_5[(c >> _rgb_g_shift_15) & 0x1F];
+}
+
+int getb15(int c) {
+   return _rgb_scale_5[(c >> _rgb_b_shift_15) & 0x1F];
+}
+
+int getr16(int c) {
+   return _rgb_scale_5[(c >> _rgb_r_shift_16) & 0x1F];
+}
+
+int getg16(int c) {
+   return _rgb_scale_6[(c >> _rgb_g_shift_16) & 0x3F];
+}
+
+int getb16(int c) {
+   return _rgb_scale_5[(c >> _rgb_b_shift_16) & 0x1F];
+}
+
+int getr32(int c) {
+	error("TODO: getr32");
+}
+
+int getg32(int c) {
+	error("TODO: getg32");
+}
+
+int getb32(int c) {
+	error("TODO: getb32");
+}
+
+int geta32(int c) {
+	error("TODO: geta32");
+}
+
 int makecol(byte r, byte g, byte b) {
 	return (b) | (g << 8) | (r << 16);
 }
diff --git a/engines/ags/lib/allegro/color.h b/engines/ags/lib/allegro/color.h
index cc1c86a95e..c5b92444f4 100644
--- a/engines/ags/lib/allegro/color.h
+++ b/engines/ags/lib/allegro/color.h
@@ -28,13 +28,15 @@
 
 namespace AGS3 {
 
-#define PALETTE_COUNT 256
+#define PAL_SIZE     256
 #define MASK_COLOR_8       0
 #define MASK_COLOR_15      0x7C1F
 #define MASK_COLOR_16      0xF81F
 #define MASK_COLOR_24      0xFF00FF
 #define MASK_COLOR_32      0xFF00FF
 
+class BITMAP;
+
 #include "common/pack-start.h"  // START STRUCT PACKING
 
 struct color {
@@ -42,15 +44,28 @@ struct color {
 } PACKED_STRUCT;
 
 typedef color RGB;
-typedef color PALETTE[PALETTE_COUNT];
+typedef RGB PALETTE[PAL_SIZE];
 
 AL_VAR(PALETTE, _current_palette);
 
 #include "common/pack-end.h"    // END STRUCT PACKING
 
-//define RGB(r,g,b)          ((COLORREF)(((BYTE)(r)|((WORD)((BYTE)(g))<<8))|(((DWORD)(BYTE)(b))<<16)))
+struct RGB_MAP {
+	byte data[32][32][32];
+};
+
+struct COLOR_MAP {
+	byte data[PAL_SIZE][PAL_SIZE];
+};
+
+AL_VAR(PALETTE, black_palette);
+AL_VAR(PALETTE, desktop_palette);
+AL_VAR(PALETTE, default_palette);
 
-extern int bestfit_color(const PALETTE pal, int r, int g, int b);
+AL_VAR(RGB_MAP *, rgb_map);
+AL_VAR(COLOR_MAP *, color_map);
+
+AL_VAR(PALETTE, _current_palette);
 
 extern int _rgb_r_shift_15;
 extern int _rgb_g_shift_15;
@@ -66,12 +81,82 @@ extern int _rgb_g_shift_32;
 extern int _rgb_b_shift_32;
 extern int _rgb_a_shift_32;
 
+AL_ARRAY(int, _rgb_scale_5);
+AL_ARRAY(int, _rgb_scale_6);
+
 AL_FUNC(void, set_color, (int idx, AL_CONST RGB *p));
 AL_FUNC(void, set_palette, (AL_CONST PALETTE p));
 AL_FUNC(void, set_palette_range, (AL_CONST PALETTE p, int from, int to, int retracesync));
 
-extern int makeacol(int r, int g, int b, int a);
-extern int makeacol_depth(int color_depth, int r, int g, int b, int a);
+AL_FUNC(void, get_color, (int idx, RGB *p));
+AL_FUNC(void, get_palette, (PALETTE p));
+AL_FUNC(void, get_palette_range, (PALETTE p, int from, int to));
+
+AL_FUNC(void, fade_interpolate, (AL_CONST PALETTE source, AL_CONST PALETTE dest, PALETTE output, int pos, int from, int to));
+AL_FUNC(void, fade_from_range, (AL_CONST PALETTE source, AL_CONST PALETTE dest, int speed, int from, int to));
+AL_FUNC(void, fade_in_range, (AL_CONST PALETTE p, int speed, int from, int to));
+AL_FUNC(void, fade_out_range, (int speed, int from, int to));
+AL_FUNC(void, fade_from, (AL_CONST PALETTE source, AL_CONST PALETTE dest, int speed));
+AL_FUNC(void, fade_in, (AL_CONST PALETTE p, int speed));
+AL_FUNC(void, fade_out, (int speed));
+
+AL_FUNC(void, select_palette, (AL_CONST PALETTE p));
+AL_FUNC(void, unselect_palette, (void));
+
+AL_FUNC(void, generate_332_palette, (PALETTE pal));
+AL_FUNC(int, generate_optimized_palette, (BITMAP *image, PALETTE pal, AL_CONST signed char rsvdcols[256]));
+
+AL_FUNC(void, create_rgb_table, (RGB_MAP *table, AL_CONST PALETTE pal, AL_METHOD(void, callback, (int pos))));
+AL_FUNC(void, create_light_table, (COLOR_MAP *table, AL_CONST PALETTE pal, int r, int g, int b, AL_METHOD(void, callback, (int pos))));
+AL_FUNC(void, create_trans_table, (COLOR_MAP *table, AL_CONST PALETTE pal, int r, int g, int b, AL_METHOD(void, callback, (int pos))));
+AL_FUNC(void, create_color_table, (COLOR_MAP *table, AL_CONST PALETTE pal, AL_METHOD(void, blend, (AL_CONST PALETTE pal, int x, int y, RGB *rgb)), AL_METHOD(void, callback, (int pos))));
+AL_FUNC(void, create_blender_table, (COLOR_MAP *table, AL_CONST PALETTE pal, AL_METHOD(void, callback, (int pos))));
+
+typedef AL_METHOD(unsigned long, BLENDER_FUNC, (unsigned long x, unsigned long y, unsigned long n));
+
+AL_FUNC(void, set_blender_mode, (BLENDER_FUNC b15, BLENDER_FUNC b16, BLENDER_FUNC b24, int r, int g, int b, int a));
+AL_FUNC(void, set_blender_mode_ex, (BLENDER_FUNC b15, BLENDER_FUNC b16, BLENDER_FUNC b24, BLENDER_FUNC b32, BLENDER_FUNC b15x, BLENDER_FUNC b16x, BLENDER_FUNC b24x, int r, int g, int b, int a));
+
+AL_FUNC(void, set_alpha_blender, (void));
+AL_FUNC(void, set_write_alpha_blender, (void));
+AL_FUNC(void, set_trans_blender, (int r, int g, int b, int a));
+AL_FUNC(void, set_add_blender, (int r, int g, int b, int a));
+AL_FUNC(void, set_burn_blender, (int r, int g, int b, int a));
+AL_FUNC(void, set_color_blender, (int r, int g, int b, int a));
+AL_FUNC(void, set_difference_blender, (int r, int g, int b, int a));
+AL_FUNC(void, set_dissolve_blender, (int r, int g, int b, int a));
+AL_FUNC(void, set_dodge_blender, (int r, int g, int b, int a));
+AL_FUNC(void, set_hue_blender, (int r, int g, int b, int a));
+AL_FUNC(void, set_invert_blender, (int r, int g, int b, int a));
+AL_FUNC(void, set_luminance_blender, (int r, int g, int b, int a));
+AL_FUNC(void, set_multiply_blender, (int r, int g, int b, int a));
+AL_FUNC(void, set_saturation_blender, (int r, int g, int b, int a));
+AL_FUNC(void, set_screen_blender, (int r, int g, int b, int a));
+
+AL_FUNC(void, hsv_to_rgb, (float h, float s, float v, int *r, int *g, int *b));
+AL_FUNC(void, rgb_to_hsv, (int r, int g, int b, float *h, float *s, float *v));
+
+AL_FUNC(int, bestfit_color, (AL_CONST PALETTE pal, int r, int g, int b));
+
+AL_FUNC(int, makecol, (int r, int g, int b));
+AL_FUNC(int, makecol8, (int r, int g, int b));
+AL_FUNC(int, makecol_depth, (int color_depth, int r, int g, int b));
+
+AL_FUNC(int, makeacol, (int r, int g, int b, int a));
+AL_FUNC(int, makeacol_depth, (int color_depth, int r, int g, int b, int a));
+
+AL_FUNC(int, makecol15_dither, (int r, int g, int b, int x, int y));
+AL_FUNC(int, makecol16_dither, (int r, int g, int b, int x, int y));
+
+AL_FUNC(int, getr, (int c));
+AL_FUNC(int, getg, (int c));
+AL_FUNC(int, getb, (int c));
+AL_FUNC(int, geta, (int c));
+
+AL_FUNC(int, getr_depth, (int color_depth, int c));
+AL_FUNC(int, getg_depth, (int color_depth, int c));
+AL_FUNC(int, getb_depth, (int color_depth, int c));
+AL_FUNC(int, geta_depth, (int color_depth, int c));
 
 extern int makecol15(int r, int g, int b);
 extern int makecol16(int r, int g, int b);
@@ -81,8 +166,16 @@ extern int makeacol32(int r, int g, int b, int a);
 extern int getr8(int c);
 extern int getg8(int c);
 extern int getb8(int c);
-extern int makecol(byte r, byte g, byte b);
-extern int makecol8(byte r, byte g, byte b);
+extern int getr15(int c);
+extern int getg15(int c);
+extern int getb15(int c);
+extern int getr16(int c);
+extern int getg16(int c);
+extern int getb16(int c);
+extern int getr32(int c);
+extern int getg32(int c);
+extern int getb32(int c);
+extern int geta32(int c);
 
 extern int getr_depth(int color_depth, int c);
 extern int getg_depth(int color_depth, int c);
diff --git a/engines/ags/lib/allegro/system.cpp b/engines/ags/lib/allegro/system.cpp
index 67a6d806a4..b372b7ebdd 100644
--- a/engines/ags/lib/allegro/system.cpp
+++ b/engines/ags/lib/allegro/system.cpp
@@ -31,12 +31,31 @@ SYSTEM_DRIVER system_none;
 SYSTEM_DRIVER *system_driver;
 
 _DRIVER_INFO _system_driver_list[] = {
-//	{ SYSTEM_IOS, &system_none, true  },
 	{ SYSTEM_NONE, &system_none, false },
 	{ 0, nullptr , 0     }
 };
 
 
+GFX_MODE_LIST *get_gfx_mode_list(int card) {
+	assert(card == 0);
+
+	GFX_MODE_LIST *list = new GFX_MODE_LIST();
+	list->num_modes = 1;
+	list->mode = new GFX_MODE[1];
+
+	GFX_MODE &gm = list->mode[0];
+	gm.width = 320;
+	gm.height = 200;
+	gm.bpp = 16;
+
+	return list;
+}
+
+void destroy_gfx_mode_list(GFX_MODE_LIST *list) {
+	delete[] list->mode;
+	delete list;
+}
+
 void set_color_depth(int depth) {
 	color_depth = depth;
 }
diff --git a/engines/ags/lib/allegro/system.h b/engines/ags/lib/allegro/system.h
index fbd1f10429..be5759b02f 100644
--- a/engines/ags/lib/allegro/system.h
+++ b/engines/ags/lib/allegro/system.h
@@ -43,7 +43,7 @@ struct GFX_MODE {
 
 struct GFX_MODE_LIST {
 	int num_modes;                /* number of gfx modes */
-	GFX_MODE *mode;               /* pointer to the actual mode list array */
+	GFX_MODE *mode;         /* pointer to the actual mode list array */
 };
 
 struct SYSTEM_DRIVER {
@@ -88,6 +88,44 @@ struct SYSTEM_DRIVER {
 	AL_METHOD(_DRIVER_INFO *, timer_drivers, (void));
 };
 
+/* creates and manages the screen bitmap */
+struct GFX_DRIVER {
+	int  id;
+	AL_CONST char *name;
+	AL_CONST char *desc;
+	AL_CONST char *ascii_name;
+	AL_METHOD(BITMAP *, init, (int w, int h, int v_w, int v_h, int color_depth));
+	AL_METHOD(void, exit, (BITMAP *b));
+	AL_METHOD(int, scroll, (int x, int y));
+	AL_METHOD(void, vsync, (void));
+	AL_METHOD(void, set_palette, (AL_CONST RGB *p, int from, int to, int retracesync));
+	AL_METHOD(int, request_scroll, (int x, int y));
+	AL_METHOD(int, poll_scroll, (void));
+	AL_METHOD(void, enable_triple_buffer, (void));
+	AL_METHOD(BITMAP *, create_video_bitmap, (int width, int height));
+	AL_METHOD(void, destroy_video_bitmap, (BITMAP *bitmap));
+	AL_METHOD(int, show_video_bitmap, (BITMAP *bitmap));
+	AL_METHOD(int, request_video_bitmap, (BITMAP *bitmap));
+	AL_METHOD( BITMAP *, create_system_bitmap, (int width, int height));
+	AL_METHOD(void, destroy_system_bitmap, (BITMAP *bitmap));
+	AL_METHOD(int, set_mouse_sprite, (BITMAP *sprite, int xfocus, int yfocus));
+	AL_METHOD(int, show_mouse, (BITMAP *bmp, int x, int y));
+	AL_METHOD(void, hide_mouse, (void));
+	AL_METHOD(void, move_mouse, (int x, int y));
+	AL_METHOD(void, drawing_mode, (void));
+	AL_METHOD(void, save_video_state, (void));
+	AL_METHOD(void, restore_video_state, (void));
+	AL_METHOD(void, set_blender_mode, (int mode, int r, int g, int b, int a));
+	AL_METHOD(GFX_MODE_LIST *, fetch_mode_list, (void));
+	int w, h;                     /* physical (not virtual!) screen size */
+	int linear;                   /* true if video memory is linear */
+	long bank_size;               /* bank size, in bytes */
+	long bank_gran;               /* bank granularity, in bytes */
+	long vid_mem;                 /* video memory size, in bytes */
+	long vid_phys_base;           /* physical address of video memory */
+	int windowed;                 /* true if driver runs windowed */
+};
+
 extern SYSTEM_DRIVER system_none;
 extern SYSTEM_DRIVER *system_driver;
 extern _DRIVER_INFO _system_driver_list[];
@@ -98,6 +136,11 @@ extern int get_desktop_resolution(int *width, int *height);
 extern void request_refresh_rate(int rate);
 extern void set_close_button_callback(void(*proc)());
 
+extern GFX_MODE_LIST *get_gfx_mode_list(int card);
+extern void destroy_gfx_mode_list(GFX_MODE_LIST *list);
+
+inline void vsync() {}
+
 } // namespace AGS3
 
 #endif
diff --git a/engines/ags/lib/opengl/opengl.cpp b/engines/ags/lib/opengl/opengl.cpp
new file mode 100644
index 0000000000..ba367d0067
--- /dev/null
+++ b/engines/ags/lib/opengl/opengl.cpp
@@ -0,0 +1,117 @@
+/* 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 "ags/lib/opengl/opengl.h"
+#include "common/array.h"
+#include "graphics/managed_surface.h"
+#include "common/system.h"
+
+namespace AGS3 {
+
+Common::Array<Graphics::ManagedSurface> texturesArray;
+uint32 currentColor, clearColor;
+
+const GLubyte *glGetString(GLenum name) {
+	switch (name) {
+	case GL_VERSION:
+		return (const GLubyte *)"ScummVM";
+	case GL_EXTENSIONS:
+		return (const GLubyte *)"ScummVM Extensions";
+	default:
+		return nullptr;
+	}
+}
+
+void glTexParameteri(GLenum target, GLenum pname, GLint param) {
+	// No implementation
+}
+
+void glDeleteTextures(GLsizei n, const GLuint *textures) {
+	for (; n > 0; --n, ++textures) {
+		texturesArray[*textures].clear();
+	}
+}
+
+GLint glGetUniformLocation(GLuint program, const GLchar *name) {
+	error("TODO: glGetUniformLocation");
+}
+
+void glShadeModel(GLenum mode) {
+	error("TODO: glShadeMode");
+}
+
+void glGetProgramiv(GLuint program, GLenum pname, GLint *params) {
+	assert(pname == GL_LINK_STATUS);
+	*params = GL_TRUE;
+}
+
+void glColor4f(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) {
+	Graphics::PixelFormat format = g_system->getScreenFormat();
+	currentColor = format.RGBToColor((byte)(red * 255), (byte)(green * 255), (byte)(blue * 255));
+}
+
+void glClearColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) {
+	Graphics::PixelFormat format = g_system->getScreenFormat();
+	clearColor = format.RGBToColor((byte)(red * 255), (byte)(green * 255), (byte)(blue * 255));
+}
+
+void glClear(GLbitfield mask) {
+	warning("TODO: glClear");
+}
+
+void glDrawArrays(GLenum mode, GLint first, GLsizei count) {
+	warning("TODO: glDrawArrays");
+}
+
+void glReadBuffer(GLenum mode) {
+	warning("TODO: glReadBuffer");
+}
+
+void glReadPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *data) {
+	warning("TODO: glReadPixels");
+}
+
+void glGetIntegerv(GLenum pname, GLint *data) {
+	// TODO: glGetIntegerv
+	*data = 0;
+}
+
+void glGetFloatv(GLenum pname, GLfloat *params) {
+	// TODO: glGetFloatv
+	*params = 0.0;
+}
+
+void glTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
+	GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels) {
+	warning("TODO: glTexSubImage2D");
+}
+
+void glTexImage2D(GLenum target, GLint level, GLint internalformat,
+	GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *data) {
+	warning("TODO: glTexImage2D");
+}
+
+void glGenTextures(GLsizei n, GLuint *textures) {
+	warning("TODO: glGenTextures");
+}
+
+} // namespace AGS3
diff --git a/engines/ags/lib/opengl/opengl.h b/engines/ags/lib/opengl/opengl.h
new file mode 100644
index 0000000000..3e6ecd89cf
--- /dev/null
+++ b/engines/ags/lib/opengl/opengl.h
@@ -0,0 +1,166 @@
+/* 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 AGS_LIB_OPENGL_OPENGL_H
+#define AGS_LIB_OPENGL_OPENGL_H
+
+#include "common/scummsys.h"
+
+namespace AGS3 {
+
+#define GL_TRUE   1
+#define GL_FALSE  2
+
+#define GFX_XWINDOWS MKTAG('S', 'C', 'V', 'M')
+#define GFX_XWINDOWS_FULLSCREEN MKTAG('S', 'C', 'V', 'M')
+#define GL_FLOAT 1
+
+// glEnable/glDisable
+#define GL_BLEND 1
+#define GL_SCISSOR_TEST 2
+#define GL_CULL_FACE 3
+#define GL_DEPTH_TEST 4
+#define GL_LIGHTING 5
+#define GL_TEXTURE_2D         0x0DE1
+#define GL_NEAREST            0x2600
+#define GL_TEXTURE_MAG_FILTER 0x2800
+#define GL_TEXTURE_MIN_FILTER 0x2801
+
+// glBlendFunc
+#define GL_SRC_ALPHA 1
+#define GL_ONE_MINUS_SRC_ALPHA 2
+
+// glShadeModel
+#define GL_FLAT 1
+
+// glGetString
+#define GL_VERSION 1
+#define GL_EXTENSIONS 2
+
+// glGetProgramiv
+#define GL_LINK_STATUS 1
+
+// glClear
+#define GL_COLOR_BUFFER_BIT 1
+
+// glMatrixMode
+#define GL_PROJECTION 1
+#define GL_MODELVIEW 2
+
+// glEnableClientState/glDisableClientState
+#define GL_COLOR_ARRAY 1
+#define GL_NORMAL_ARRAY 2
+#define GL_VERTEX_ARRAY 3
+#define GL_TEXTURE_COORD_ARRAY 4
+
+// glTexParameteri
+#define GL_LINEAR 1
+#define GL_CLAMP 2
+#define GL_TEXTURE_WRAP_T 3
+#define GL_TEXTURE_WRAP_S 4
+
+// glBindFramebufferEXT
+#define GL_FRAMEBUFFER_EXT 1
+
+// glReadBuffer
+#define GL_FRONT 1
+
+// glReadPixels
+#define GL_RGBA 1
+#define GL_UNSIGNED_BYTE 2
+
+// glDrawArrays
+#define GL_TRIANGLE_STRIP 1
+
+// glGetIntegerv/glGetFloatv
+#define GL_MAX_TEXTURE_SIZE 1
+#define GL_MODELVIEW_MATRIX 2
+
+
+typedef char GLchar;
+typedef byte GLubyte;
+typedef uint GLenum;
+typedef int GLint;
+typedef uint32 GLuint;
+typedef uint GLbitfield;
+typedef float GLfloat;
+typedef double GLdouble;
+typedef size_t GLsizei;
+
+struct GLXContextStruct {
+};
+typedef GLXContextStruct *GLXContext;
+
+inline bool gladLoadGL() { return true; }
+inline void glFinish() {}
+
+inline int glCreateProgram() { return 1; }
+inline void glDeleteProgram(int prog) {}
+inline void glEnable(GLenum cap) {}
+inline void glDisable(GLenum cap) {}
+inline void glBlendFunc(GLenum sfactor, GLenum dfactor) {}
+inline void glViewport(GLint x, GLint y, GLsizei width, GLsizei height) {}
+inline void glMatrixMode(GLenum mode) {}
+inline void glLoadIdentity() {}
+inline void glOrtho(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top,
+	GLdouble nearVal, GLdouble farVal);
+inline void glEnableClientState(GLenum arr) {}
+inline void glDisableClientState(GLenum arr) {}
+inline void glUseProgram(GLuint program) {}
+inline void glUniform1f(GLint location, GLfloat v0) {}
+inline void glUniform3f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2) {}
+inline void glUniform1i(GLint location, GLint v0) {}
+inline void glTranslatef(GLfloat x, GLfloat y, GLfloat z) {}
+inline void glMultMatrixf(const GLfloat *m) {}
+inline void glRotatef(GLfloat angle, GLfloat x, GLfloat y, GLfloat z);
+inline void glScalef(GLfloat x, GLfloat y, GLfloat z);
+inline void glBindTexture(GLenum target, GLuint texture) {}
+inline void glTexCoordPointer(GLint size, GLenum type, GLsizei stride, const void *pointer);
+inline void glVertexPointer(GLint size, GLenum type, GLsizei stride, const void *pointer) {}
+inline void glBindFramebufferEXT(GLenum v1, uint v2) {}
+inline void glDeleteFramebuffersEXT(int v1, uint *v2) {}
+inline void glScissor(GLint x, GLint y, GLsizei width, GLsizei height) {}
+
+extern const GLubyte *glGetString(GLenum name);
+extern void glTexParameteri(GLenum target, GLenum pname, GLint param);
+extern void glDeleteTextures(GLsizei n, const GLuint *textures);
+extern GLint glGetUniformLocation(GLuint program, const GLchar *name);
+extern void glShadeModel(GLenum mode);
+extern void glGetProgramiv(GLuint program, GLenum pname, GLint *params);
+
+extern void glColor4f(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+extern void glClearColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+extern void glClear(GLbitfield mask);
+extern void glDrawArrays(GLenum mode, GLint first, GLsizei count);
+extern void glReadBuffer(GLenum mode);
+extern void glReadPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *data);
+extern void glGetIntegerv(GLenum pname, GLint *data);
+extern void glGetFloatv(GLenum  pname, GLfloat *params);
+extern void glTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
+	GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels);
+extern void glTexImage2D(GLenum target, GLint level, GLint internalformat,
+	GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *data);
+extern void glGenTextures(GLsizei n, GLuint *textures);
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 793bc264d9..037cda3400 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -20,6 +20,7 @@ MODULE_OBJS = \
 	lib/allegro/sound.o \
 	lib/allegro/system.o \
 	lib/allegro/unicode.o \
+	lib/opengl/opengl.o \
 	lib/system/datetime.o \
 	shared/ac/dynobj/scriptaudioclip.o \
 	shared/ac/audiocliptype.o \
@@ -83,6 +84,20 @@ MODULE_OBJS = \
 	engine/game/savegame.o \
 	engine/game/savegame_components.o \
 	engine/game/viewport.o \
+	engine/gfx/all3dd3d.o \
+	engine/gfx/ali3dogl.o \
+	engine/gfx/ali3dsw.o \
+	engine/gfx/blender.o \
+	engine/gfx/color_engine.o \
+	engine/gfx/gfx_util.o \
+	engine/gfx/gfxdriverbase.o \
+	engine/gfx/gfxdriverfactory.o \
+	engine/gfx/gfxfilter_aad3d.o \
+	engine/gfx/gfxfilter_allegro.o \
+	engine/gfx/gfxfilter_d3d.o \
+	engine/gfx/gfxfilter_hqx.o \
+	engine/gfx/gfxfilter_ogl.o \
+	engine/gfx/gfxfilter_scaling.o \
 	engine/gui/animatingguibutton.o \
 	engine/gui/cscidialog.o \
 	engine/gui/guidialog.o \
diff --git a/engines/ags/shared/core/platform.h b/engines/ags/shared/core/platform.h
index 67ded4ac4b..bcac2025a1 100644
--- a/engines/ags/shared/core/platform.h
+++ b/engines/ags/shared/core/platform.h
@@ -29,14 +29,16 @@ namespace AGS3 {
 
 // ScummVM implementation is identifying as Linux for now
 #if 1
+#define AGS_PLATFORM_SCUMMVM    (1)
 #define AGS_PLATFORM_OS_WINDOWS (0)
 #define AGS_PLATFORM_OS_LINUX   (1)
 #define AGS_PLATFORM_OS_MACOS   (0)
-#define AGS_PLATFORM_OS_ANDROID (1)
+#define AGS_PLATFORM_OS_ANDROID (0)
 #define AGS_PLATFORM_OS_IOS     (0)
 #define AGS_PLATFORM_OS_PSP     (0)
 // check Android first because sometimes it can get confused with host OS
 #elif defined(__ANDROID__) || defined(ANDROID)
+#define AGS_PLATFORM_SCUMMVM    (0)
 #define AGS_PLATFORM_OS_WINDOWS (0)
 #define AGS_PLATFORM_OS_LINUX   (0)
 #define AGS_PLATFORM_OS_MACOS   (0)
@@ -45,6 +47,7 @@ namespace AGS3 {
 #define AGS_PLATFORM_OS_PSP     (0)
 #elif defined(_WIN32)
 //define something for Windows (32-bit and 64-bit)
+#define AGS_PLATFORM_SCUMMVM    (0)
 #define AGS_PLATFORM_OS_WINDOWS (1)
 #define AGS_PLATFORM_OS_LINUX   (0)
 #define AGS_PLATFORM_OS_MACOS   (0)
@@ -52,6 +55,7 @@ namespace AGS3 {
 #define AGS_PLATFORM_OS_IOS     (0)
 #define AGS_PLATFORM_OS_PSP     (0)
 #elif defined(__APPLE__)
+#define AGS_PLATFORM_SCUMMVM    (0)
 #include "ags/shared/TargetConditionals.h"
 #ifndef TARGET_OS_SIMULATOR
 #define TARGET_OS_SIMULATOR (0)
diff --git a/engines/ags/shared/core/types.h b/engines/ags/shared/core/types.h
index 3bf23121d9..f1e3dd1b54 100644
--- a/engines/ags/shared/core/types.h
+++ b/engines/ags/shared/core/types.h
@@ -87,6 +87,11 @@ typedef int64 intptr_t;
 #define UINT_MAX      0xffffffff
 #define SIZE_MAX      0xffffffff
 
+#undef TRUE
+#undef FALSE
+#define TRUE true
+#define FALSE false
+
 // TODO: use distinct fixed point class
 enum {
 	kShift = 16,
diff --git a/engines/ags/std/algorithm.h b/engines/ags/std/algorithm.h
index 8b5f070125..8599dc0878 100644
--- a/engines/ags/std/algorithm.h
+++ b/engines/ags/std/algorithm.h
@@ -36,6 +36,11 @@ template<typename T> inline T clip(T v, T amin, T amax) { return CLIP(v, amin, a
 template<typename T> inline T sqrt(T x) { return ::sqrt(x); }
 template<typename T> inline void swap(T a, T b) { SWAP(a, b); }
 
+template<class In, class Value>
+In fill(In first, In last, const Value &val) {
+	return Common::fill(first, last, val);
+}
+
 template<typename T, class StrictWeakOrdering>
 void sort(T first, T last, StrictWeakOrdering comp) {
 	Common::sort<T, StrictWeakOrdering>(first, last, comp);
diff --git a/engines/ags/std/memory.h b/engines/ags/std/memory.h
index 99c85916a0..7efe2c16f6 100644
--- a/engines/ags/std/memory.h
+++ b/engines/ags/std/memory.h
@@ -43,6 +43,12 @@ T *memcpy(T *dest, const T *src, size_t n) {
 	return (T *)::memcpy(dest, src, n);
 }
 
+template<class T>
+shared_ptr<T> static_pointer_cast(const shared_ptr<T> &src) {
+	T *ptr = src.get();
+	return shared_ptr<T>(ptr);
+}
+
 } // namespace std
 } // namespace AGS3
 


Commit: 969f4b507ccdd0372ecf9e00925a8af4d5b8c0df
    https://github.com/scummvm/scummvm/commit/969f4b507ccdd0372ecf9e00925a8af4d5b8c0df
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Warning fixes

Changed paths:
    engines/ags/engine/ac/hotspot.h
    engines/ags/engine/gfx/ali3dogl.cpp
    engines/ags/engine/gfx/ali3dsw.cpp
    engines/ags/engine/gfx/gfxdriverbase.cpp
    engines/ags/engine/gui/mypushbutton.cpp
    engines/ags/engine/gui/newcontrol.cpp
    engines/ags/engine/main/config.cpp
    engines/ags/engine/main/engine.cpp
    engines/ags/engine/main/game_run.cpp
    engines/ags/engine/main/graphics_mode.cpp
    engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
    engines/ags/engine/plugin/agsplugin.cpp
    engines/ags/module.mk
    engines/ags/shared/gfx/bitmap.cpp


diff --git a/engines/ags/engine/ac/hotspot.h b/engines/ags/engine/ac/hotspot.h
index 4882543097..90cf192dff 100644
--- a/engines/ags/engine/ac/hotspot.h
+++ b/engines/ags/engine/ac/hotspot.h
@@ -31,7 +31,7 @@ void    Hotspot_SetEnabled(ScriptHotspot *hss, int newval);
 int     Hotspot_GetEnabled(ScriptHotspot *hss);
 int     Hotspot_GetID(ScriptHotspot *hss);
 ScriptHotspot *GetHotspotAtScreen(int xx, int yy);
-int     Hotspot_GetWalkToX(ScriptHotspot *hss);;
+int     Hotspot_GetWalkToX(ScriptHotspot *hss);
 int     Hotspot_GetWalkToY(ScriptHotspot *hss);
 void    Hotspot_GetName(ScriptHotspot *hss, char *buffer);
 const char *Hotspot_GetName_New(ScriptHotspot *hss);
diff --git a/engines/ags/engine/gfx/ali3dogl.cpp b/engines/ags/engine/gfx/ali3dogl.cpp
index 11e19838f6..ec1b2825c1 100644
--- a/engines/ags/engine/gfx/ali3dogl.cpp
+++ b/engines/ags/engine/gfx/ali3dogl.cpp
@@ -1087,7 +1087,7 @@ bool OGLGraphicsDriver::GetCopyOfScreenIntoBitmap(Bitmap *destination, bool at_n
 }
 
 void OGLGraphicsDriver::RenderToBackBuffer() {
-	throw Ali3DException("OGL driver does not have a back buffer");
+	error("OGL driver does not have a back buffer");
 }
 
 void OGLGraphicsDriver::Render() {
@@ -1565,10 +1565,10 @@ void OGLGraphicsDriver::UpdateTextureRegion(OGLTextureTile *tile, Bitmap *bitmap
 void OGLGraphicsDriver::UpdateDDBFromBitmap(IDriverDependantBitmap *bitmapToUpdate, Bitmap *bitmap, bool hasAlpha) {
 	OGLBitmap *target = (OGLBitmap *)bitmapToUpdate;
 	if (target->_width != bitmap->GetWidth() || target->_height != bitmap->GetHeight())
-		throw Ali3DException("UpdateDDBFromBitmap: mismatched bitmap size");
+		error("UpdateDDBFromBitmap: mismatched bitmap size");
 	const int color_depth = bitmap->GetColorDepth();
 	if (color_depth != target->_colDepth)
-		throw Ali3DException("UpdateDDBFromBitmap: mismatched colour depths");
+		error("UpdateDDBFromBitmap: mismatched colour depths");
 
 	target->_hasAlpha = hasAlpha;
 	if (color_depth == 8)
@@ -1620,7 +1620,7 @@ IDriverDependantBitmap *OGLGraphicsDriver::CreateDDBFromBitmap(Bitmap *bitmap, b
 	int allocatedHeight = bitmap->GetHeight();
 	// NOTE: original bitmap object is not modified in this function
 	if (bitmap->GetColorDepth() != GetCompatibleBitmapFormat(bitmap->GetColorDepth()))
-		throw Ali3DException("CreateDDBFromBitmap: bitmap colour depth not supported");
+		error("CreateDDBFromBitmap: bitmap colour depth not supported");
 	int colourDepth = bitmap->GetColorDepth();
 
 	OGLBitmap *ddb = new OGLBitmap(bitmap->GetWidth(), bitmap->GetHeight(), colourDepth, opaque);
diff --git a/engines/ags/engine/gfx/ali3dsw.cpp b/engines/ags/engine/gfx/ali3dsw.cpp
index e56761a422..9d82d3cb42 100644
--- a/engines/ags/engine/gfx/ali3dsw.cpp
+++ b/engines/ags/engine/gfx/ali3dsw.cpp
@@ -459,7 +459,7 @@ void ALSoftwareGraphicsDriver::RenderSpriteBatch(const ALSpriteBatch &batch, Sha
 			if (_nullSpriteCallback)
 				_nullSpriteCallback(drawlist[i].x, drawlist[i].y);
 			else
-				throw Ali3DException("Unhandled attempt to draw null sprite");
+				error("Unhandled attempt to draw null sprite");
 
 			continue;
 		} else if (drawlist[i].bitmap == (ALSoftwareBitmap *)0x1) {
@@ -727,7 +727,7 @@ void ALSoftwareGraphicsDriver::BoxOutEffect(bool blackingOut, int speed, int del
 		delete bmp_buff;
 		SetMemoryBackBuffer(bmp_orig);
 	} else {
-		throw Ali3DException("BoxOut fade-in not implemented in sw gfx driver");
+		error("BoxOut fade-in not implemented in sw gfx driver");
 	}
 }
 // end fading routines
diff --git a/engines/ags/engine/gfx/gfxdriverbase.cpp b/engines/ags/engine/gfx/gfxdriverbase.cpp
index b8947b7617..ce75c9b1ed 100644
--- a/engines/ags/engine/gfx/gfxdriverbase.cpp
+++ b/engines/ags/engine/gfx/gfxdriverbase.cpp
@@ -189,7 +189,7 @@ void VideoMemoryGraphicsDriver::DestroyAllStageScreens() {
 
 bool VideoMemoryGraphicsDriver::DoNullSpriteCallback(int x, int y) {
 	if (!_nullSpriteCallback)
-		throw Ali3DException("Unhandled attempt to draw null sprite");
+		error("Unhandled attempt to draw null sprite");
 	_stageScreenDirty = false;
 	_stageVirtualScreen->ClearTransparent();
 	// NOTE: this is not clear whether return value of callback may be
@@ -362,11 +362,11 @@ void VideoMemoryGraphicsDriver::BitmapToVideoMem(const Bitmap *bitmap, const boo
 					}
 				}
 			} else if (src_depth == 32) {
-				unsigned int *memPtrLong = (unsigned int *)dst_ptr;
+				unsigned int *ptrLong = (unsigned int *)dst_ptr;
 				unsigned int *srcData = (unsigned int *)&scanline_at[(x + tile->x) * sizeof(int)];
 				if (*srcData == MASK_COLOR_32) {
 					if (!usingLinearFiltering)
-						memPtrLong[x] = 0;
+						ptrLong[x] = 0;
 					// set to transparent, but use the colour from the neighbouring
 					// pixel to stop the linear filter doing black outlines
 					else {
@@ -380,19 +380,19 @@ void VideoMemoryGraphicsDriver::BitmapToVideoMem(const Bitmap *bitmap, const boo
 						if (y < tile->height - 1)
 							get_pixel_if_not_transparent32((unsigned int *)&scanline_after[(x + tile->x) * sizeof(int)], &red, &green, &blue, &divisor);
 						if (divisor > 0)
-							memPtrLong[x] = VMEMCOLOR_RGBA(red / divisor, green / divisor, blue / divisor, 0);
+							ptrLong[x] = VMEMCOLOR_RGBA(red / divisor, green / divisor, blue / divisor, 0);
 						else
-							memPtrLong[x] = 0;
+							ptrLong[x] = 0;
 					}
 					lastPixelWasTransparent = true;
 				} else if (has_alpha) {
-					memPtrLong[x] = VMEMCOLOR_RGBA(algetr32(*srcData), algetg32(*srcData), algetb32(*srcData), algeta32(*srcData));
+					ptrLong[x] = VMEMCOLOR_RGBA(algetr32(*srcData), algetg32(*srcData), algetb32(*srcData), algeta32(*srcData));
 				} else {
-					memPtrLong[x] = VMEMCOLOR_RGBA(algetr32(*srcData), algetg32(*srcData), algetb32(*srcData), 0xFF);
+					ptrLong[x] = VMEMCOLOR_RGBA(algetr32(*srcData), algetg32(*srcData), algetb32(*srcData), 0xFF);
 					if (lastPixelWasTransparent) {
 						// update the colour of the previous tranparent pixel, to
 						// stop black outlines when linear filtering
-						memPtrLong[x - 1] = memPtrLong[x] & 0x00FFFFFF;
+						ptrLong[x - 1] = ptrLong[x] & 0x00FFFFFF;
 						lastPixelWasTransparent = false;
 					}
 				}
@@ -418,7 +418,7 @@ void VideoMemoryGraphicsDriver::BitmapToVideoMemOpaque(const Bitmap *bitmap, con
 				unsigned short *srcData = (unsigned short *)&scanline_at[(x + tile->x) * sizeof(short)];
 				memPtrLong[x] = VMEMCOLOR_RGBA(algetr16(*srcData), algetg16(*srcData), algetb16(*srcData), 0xFF);
 			} else if (src_depth == 32) {
-				unsigned int *memPtrLong = (unsigned int *)dst_ptr;
+				//unsigned int *memPtrLong = (unsigned int *)dst_ptr;
 				unsigned int *srcData = (unsigned int *)&scanline_at[(x + tile->x) * sizeof(int)];
 				if (has_alpha)
 					memPtrLong[x] = VMEMCOLOR_RGBA(algetr32(*srcData), algetg32(*srcData), algetb32(*srcData), algeta32(*srcData));
diff --git a/engines/ags/engine/gui/mypushbutton.cpp b/engines/ags/engine/gui/mypushbutton.cpp
index 7f462063e6..b5bb5a5da7 100644
--- a/engines/ags/engine/gui/mypushbutton.cpp
+++ b/engines/ags/engine/gui/mypushbutton.cpp
@@ -50,7 +50,7 @@ MyPushButton::MyPushButton(int xx, int yy, int wi, int hi, const char *tex) {
 	state = 0;
 	strncpy(text, tex, 50);
 	text[49] = 0;
-};
+}
 
 void MyPushButton::draw(Bitmap *ds) {
 	color_t text_color = ds->GetCompatibleColor(0);
diff --git a/engines/ags/engine/gui/newcontrol.cpp b/engines/ags/engine/gui/newcontrol.cpp
index 57f593ec54..f17d444ed4 100644
--- a/engines/ags/engine/gui/newcontrol.cpp
+++ b/engines/ags/engine/gui/newcontrol.cpp
@@ -39,7 +39,8 @@ NewControl::NewControl(int xx, int yy, int wi, int hi) {
 	visible = 1;
 	enabled = 1;
 	needredraw = 1;
-};
+}
+
 NewControl::NewControl() {
 	x = y = wid = hit = 0;
 	state = 0;
@@ -49,6 +50,7 @@ NewControl::NewControl() {
 	enabled = 1;
 	needredraw = 1;
 }
+
 int NewControl::mouseisinarea(int mousex, int mousey) {
 	if (topwindowhandle != wlevel)
 		return 0;
@@ -58,6 +60,7 @@ int NewControl::mouseisinarea(int mousex, int mousey) {
 
 	return 0;
 }
+
 void NewControl::drawifneeded() {
 	if (topwindowhandle != wlevel)
 		return;
@@ -66,6 +69,7 @@ void NewControl::drawifneeded() {
 		draw(get_gui_screen());
 	}
 }
+
 void NewControl::drawandmouse() {
 	//    ags_domouse(DOMOUSE_DISABLE);
 	draw(get_gui_screen());
diff --git a/engines/ags/engine/main/config.cpp b/engines/ags/engine/main/config.cpp
index d2095f1b29..97d54ac784 100644
--- a/engines/ags/engine/main/config.cpp
+++ b/engines/ags/engine/main/config.cpp
@@ -175,6 +175,8 @@ String make_scaling_option(FrameScaleDefinition scale_def, int scale_factor) {
 		return "stretch";
 	case kFrame_MaxProportional:
 		return "proportional";
+	default:
+		break;
 	}
 	return String::FromFormat("%d", scale_factor);
 }
diff --git a/engines/ags/engine/main/engine.cpp b/engines/ags/engine/main/engine.cpp
index 516483f3ba..a2cf6c6f3d 100644
--- a/engines/ags/engine/main/engine.cpp
+++ b/engines/ags/engine/main/engine.cpp
@@ -488,7 +488,7 @@ void engine_init_audio() {
 	digi_id = digi_drv.first;
 	midi_id = midi_drv.first;
 	const int max_digi_voices = digi_drv.second;
-	const int max_midi_voices = midi_drv.second;
+	//const int max_midi_voices = midi_drv.second;
 	if (digi_voices > max_digi_voices)
 		digi_voices = max_digi_voices;
 	// NOTE: we do not specify number of MIDI voices, so don't have to calculate available here
diff --git a/engines/ags/engine/main/game_run.cpp b/engines/ags/engine/main/game_run.cpp
index d6ae725152..541b1ab719 100644
--- a/engines/ags/engine/main/game_run.cpp
+++ b/engines/ags/engine/main/game_run.cpp
@@ -841,24 +841,24 @@ static int ShouldStayInWaitMode() {
 	int retval = restrict_until;
 
 	if (restrict_until == UNTIL_MOVEEND) {
-		short *wkptr = (short *)user_disabled_data;
+		const short *wkptr = (const short *)user_disabled_data;
 		if (wkptr[0] < 1) retval = 0;
 	} else if (restrict_until == UNTIL_CHARIS0) {
-		char *chptr = (char *)user_disabled_data;
+		const char *chptr = (const char *)user_disabled_data;
 		if (chptr[0] == 0) retval = 0;
 	} else if (restrict_until == UNTIL_NEGATIVE) {
-		short *wkptr = (short *)user_disabled_data;
+		const short *wkptr = (const short *)user_disabled_data;
 		if (wkptr[0] < 0) retval = 0;
 	} else if (restrict_until == UNTIL_INTISNEG) {
-		int *wkptr = (int *)user_disabled_data;
+		const int *wkptr = (const int *)user_disabled_data;
 		if (wkptr[0] < 0) retval = 0;
 	} else if (restrict_until == UNTIL_NOOVERLAY) {
 		if (is_text_overlay < 1) retval = 0;
 	} else if (restrict_until == UNTIL_INTIS0) {
-		int *wkptr = (int *)user_disabled_data;
+		const int *wkptr = (const int *)user_disabled_data;
 		if (wkptr[0] == 0) retval = 0;
 	} else if (restrict_until == UNTIL_SHORTIS0) {
-		short *wkptr = (short *)user_disabled_data;
+		const short *wkptr = (const short *)user_disabled_data;
 		if (wkptr[0] == 0) retval = 0;
 	} else quit("loop_until: unknown until event");
 
diff --git a/engines/ags/engine/main/graphics_mode.cpp b/engines/ags/engine/main/graphics_mode.cpp
index 7020a0ada6..63490180e9 100644
--- a/engines/ags/engine/main/graphics_mode.cpp
+++ b/engines/ags/engine/main/graphics_mode.cpp
@@ -260,6 +260,8 @@ Size precalc_screen_size(const Size &game_size, const DisplayModeSetup &dm_setup
 		// Set as big as current device size
 		screen_size = device_size;
 		break;
+	default:
+		break;
 	}
 	return screen_size;
 }
diff --git a/engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp b/engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
index e099493b9f..3a28afb3ba 100644
--- a/engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
+++ b/engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
@@ -433,7 +433,7 @@ int D3DGraphicsDriver::FirstTimeInit() {
 
 void D3DGraphicsDriver::initD3DDLL(const DisplayMode &mode) {
 	if (!IsModeSupported(mode)) {
-		throw Ali3DException(get_allegro_error());
+		error(get_allegro_error());
 	}
 
 	_enter_critical();
@@ -442,7 +442,7 @@ void D3DGraphicsDriver::initD3DDLL(const DisplayMode &mode) {
 	// Set the display mode in the window's thread
 	if (wnd_call_proc(wnd_create_device)) {
 		_exit_critical();
-		throw Ali3DException(get_allegro_error());
+		error(get_allegro_error());
 	}
 
 	availableVideoMemory = direct3ddevice->GetAvailableTextureMem();
@@ -845,10 +845,10 @@ void D3DGraphicsDriver::CreateVirtualScreen() {
 	            D3DPOOL_DEFAULT,
 	            &pNativeTexture,
 	            NULL) != D3D_OK) {
-		throw Ali3DException("CreateTexture failed");
+		error("CreateTexture failed");
 	}
 	if (pNativeTexture->GetSurfaceLevel(0, &pNativeSurface) != D3D_OK) {
-		throw Ali3DException("GetSurfaceLevel failed");
+		error("GetSurfaceLevel failed");
 	}
 
 	direct3ddevice->ColorFill(pNativeSurface, NULL, 0);
@@ -1000,16 +1000,16 @@ bool D3DGraphicsDriver::GetCopyOfScreenIntoBitmap(Bitmap *destination, bool at_n
 			            D3DPOOL_SYSTEMMEM,
 			            &surface,
 			            NULL) != D3D_OK) {
-				throw Ali3DException("CreateOffscreenPlainSurface failed");
+				error("CreateOffscreenPlainSurface failed");
 			}
 			if (direct3ddevice->GetRenderTargetData(pNativeSurface, surface) != D3D_OK) {
-				throw Ali3DException("GetRenderTargetData failed");
+				error("GetRenderTargetData failed");
 			}
 
 		}
 		// Get the back buffer surface
 		else if (direct3ddevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &surface) != D3D_OK) {
-			throw Ali3DException("IDirect3DDevice9::GetBackBuffer failed");
+			error("IDirect3DDevice9::GetBackBuffer failed");
 		}
 
 		if (_pollingCallback)
@@ -1017,7 +1017,7 @@ bool D3DGraphicsDriver::GetCopyOfScreenIntoBitmap(Bitmap *destination, bool at_n
 
 		D3DLOCKED_RECT lockedRect;
 		if (surface->LockRect(&lockedRect, (at_native_res ? NULL : &viewport_rect), D3DLOCK_READONLY) != D3D_OK) {
-			throw Ali3DException("IDirect3DSurface9::LockRect failed");
+			error("IDirect3DSurface9::LockRect failed");
 		}
 
 		BitmapHelper::ReadPixelsFromMemory(destination, (uint8_t *)lockedRect.pBits, lockedRect.Pitch);
@@ -1032,7 +1032,7 @@ bool D3DGraphicsDriver::GetCopyOfScreenIntoBitmap(Bitmap *destination, bool at_n
 }
 
 void D3DGraphicsDriver::RenderToBackBuffer() {
-	throw Ali3DException("D3D driver does not have a back buffer");
+	error("D3D driver does not have a back buffer");
 }
 
 void D3DGraphicsDriver::Render() {
@@ -1139,7 +1139,7 @@ void D3DGraphicsDriver::_renderSprite(const D3DDrawListEntry *drawListEntry, con
 		hr = direct3ddevice->SetStreamSource(0, bmpToDraw->_vertex, 0, sizeof(CUSTOMVERTEX));
 	}
 	if (hr != D3D_OK) {
-		throw Ali3DException("IDirect3DDevice9::SetStreamSource failed");
+		error("IDirect3DDevice9::SetStreamSource failed");
 	}
 
 	float width = bmpToDraw->GetWidthToRender();
@@ -1195,7 +1195,7 @@ void D3DGraphicsDriver::_renderSprite(const D3DDrawListEntry *drawListEntry, con
 
 		hr = direct3ddevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, ti * 4, 2);
 		if (hr != D3D_OK) {
-			throw Ali3DException("IDirect3DDevice9::DrawPrimitive failed");
+			error("IDirect3DDevice9::DrawPrimitive failed");
 		}
 
 	}
@@ -1203,7 +1203,7 @@ void D3DGraphicsDriver::_renderSprite(const D3DDrawListEntry *drawListEntry, con
 
 void D3DGraphicsDriver::_renderFromTexture() {
 	if (direct3ddevice->SetStreamSource(0, vertexbuffer, 0, sizeof(CUSTOMVERTEX)) != D3D_OK) {
-		throw Ali3DException("IDirect3DDevice9::SetStreamSource failed");
+		error("IDirect3DDevice9::SetStreamSource failed");
 	}
 
 	float width = _srcRect.GetWidth();
@@ -1224,7 +1224,7 @@ void D3DGraphicsDriver::_renderFromTexture() {
 	direct3ddevice->SetTexture(0, pNativeTexture);
 
 	if (direct3ddevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2) != D3D_OK) {
-		throw Ali3DException("IDirect3DDevice9::DrawPrimitive failed");
+		error("IDirect3DDevice9::DrawPrimitive failed");
 	}
 }
 
@@ -1237,19 +1237,19 @@ void D3DGraphicsDriver::_render(bool clearDrawListAfterwards) {
 	IDirect3DSurface9 *pBackBuffer = NULL;
 
 	if (direct3ddevice->GetRenderTarget(0, &pBackBuffer) != D3D_OK) {
-		throw Ali3DException("IDirect3DSurface9::GetRenderTarget failed");
+		error("IDirect3DSurface9::GetRenderTarget failed");
 	}
 	direct3ddevice->ColorFill(pBackBuffer, nullptr, D3DCOLOR_RGBA(0, 0, 0, 255));
 
 	if (!_renderSprAtScreenRes) {
 		if (direct3ddevice->SetRenderTarget(0, pNativeSurface) != D3D_OK) {
-			throw Ali3DException("IDirect3DSurface9::SetRenderTarget failed");
+			error("IDirect3DSurface9::SetRenderTarget failed");
 		}
 	}
 
 	direct3ddevice->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_RGBA(0, 0, 0, 255), 0.5f, 0);
 	if (direct3ddevice->BeginScene() != D3D_OK)
-		throw Ali3DException("IDirect3DDevice9::BeginScene failed");
+		error("IDirect3DDevice9::BeginScene failed");
 
 	// if showing at 2x size, the sprite can get distorted otherwise
 	direct3ddevice->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
@@ -1260,7 +1260,7 @@ void D3DGraphicsDriver::_render(bool clearDrawListAfterwards) {
 
 	if (!_renderSprAtScreenRes) {
 		if (direct3ddevice->SetRenderTarget(0, pBackBuffer) != D3D_OK) {
-			throw Ali3DException("IDirect3DSurface9::SetRenderTarget failed");
+			error("IDirect3DSurface9::SetRenderTarget failed");
 		}
 		direct3ddevice->SetViewport(&_d3dViewport);
 		_renderFromTexture();
@@ -1426,7 +1426,7 @@ void D3DGraphicsDriver::UpdateTextureRegion(D3DTextureTile *tile, Bitmap *bitmap
 	D3DLOCKED_RECT lockedRegion;
 	HRESULT hr = newTexture->LockRect(0, &lockedRegion, NULL, D3DLOCK_NOSYSLOCK | D3DLOCK_DISCARD);
 	if (hr != D3D_OK) {
-		throw Ali3DException("Unable to lock texture");
+		error("Unable to lock texture");
 	}
 
 	bool usingLinearFiltering = _filter->NeedToColourEdgeLines();
@@ -1443,10 +1443,10 @@ void D3DGraphicsDriver::UpdateTextureRegion(D3DTextureTile *tile, Bitmap *bitmap
 void D3DGraphicsDriver::UpdateDDBFromBitmap(IDriverDependantBitmap *bitmapToUpdate, Bitmap *bitmap, bool hasAlpha) {
 	D3DBitmap *target = (D3DBitmap *)bitmapToUpdate;
 	if (target->_width != bitmap->GetWidth() || target->_height != bitmap->GetHeight())
-		throw Ali3DException("UpdateDDBFromBitmap: mismatched bitmap size");
+		error("UpdateDDBFromBitmap: mismatched bitmap size");
 	const int color_depth = bitmap->GetColorDepth();
 	if (color_depth != target->_colDepth)
-		throw Ali3DException("UpdateDDBFromBitmap: mismatched colour depths");
+		error("UpdateDDBFromBitmap: mismatched colour depths");
 
 	target->_hasAlpha = hasAlpha;
 	if (color_depth == 8)
@@ -1516,7 +1516,7 @@ IDriverDependantBitmap *D3DGraphicsDriver::CreateDDBFromBitmap(Bitmap *bitmap, b
 	int allocatedWidth = bitmap->GetWidth();
 	int allocatedHeight = bitmap->GetHeight();
 	if (bitmap->GetColorDepth() != GetCompatibleBitmapFormat(bitmap->GetColorDepth()))
-		throw Ali3DException("CreateDDBFromBitmap: bitmap colour depth not supported");
+		error("CreateDDBFromBitmap: bitmap colour depth not supported");
 	int colourDepth = bitmap->GetColorDepth();
 
 	D3DBitmap *ddb = new D3DBitmap(bitmap->GetWidth(), bitmap->GetHeight(), colourDepth, opaque);
@@ -1563,12 +1563,12 @@ IDriverDependantBitmap *D3DGraphicsDriver::CreateDDBFromBitmap(Bitmap *bitmap, b
 			free(tiles);
 			char errorMessage[200];
 			sprintf(errorMessage, "Direct3DDevice9::CreateVertexBuffer(Length=%d) for texture failed: error code %08X", vertexBufferSize, hr);
-			throw Ali3DException(errorMessage);
+			error(errorMessage);
 		}
 
 		if (ddb->_vertex->Lock(0, 0, (void **)&vertices, D3DLOCK_DISCARD) != D3D_OK) {
 			free(tiles);
-			throw Ali3DException("Failed to lock vertex buffer");
+			error("Failed to lock vertex buffer");
 		}
 	}
 
@@ -1614,7 +1614,7 @@ IDriverDependantBitmap *D3DGraphicsDriver::CreateDDBFromBitmap(Bitmap *bitmap, b
 			if (hr != D3D_OK) {
 				char errorMessage[200];
 				sprintf(errorMessage, "Direct3DDevice9::CreateTexture(X=%d, Y=%d, FMT=%d) failed: error code %08X", thisAllocatedWidth, thisAllocatedHeight, textureFormat, hr);
-				throw Ali3DException(errorMessage);
+				error(errorMessage);
 			}
 
 		}
diff --git a/engines/ags/engine/plugin/agsplugin.cpp b/engines/ags/engine/plugin/agsplugin.cpp
index 6019f9525d..648bf89d5d 100644
--- a/engines/ags/engine/plugin/agsplugin.cpp
+++ b/engines/ags/engine/plugin/agsplugin.cpp
@@ -154,7 +154,7 @@ int pluginsWantingDebugHooks = 0;
 std::vector<InbuiltPluginDetails> _registered_builtin_plugins;
 
 void IAGSEngine::AbortGame(const char *reason) {
-	quit((char *)reason);
+	quit((const char *)reason);
 }
 const char *IAGSEngine::GetEngineVersion() {
 	return get_engine_version();
@@ -368,7 +368,7 @@ void IAGSEngine::SetVirtualScreen(BITMAP *bmp) {
 }
 
 int IAGSEngine::LookupParserWord(const char *word) {
-	return find_word_in_dictionary((char *)word);
+	return find_word_in_dictionary((const char *)word);
 }
 
 void IAGSEngine::BlitBitmap(int32 x, int32 y, BITMAP *bmp, int32 masked) {
@@ -515,7 +515,7 @@ int IAGSEngine::GetWalkbehindBaseline(int32 wa) {
 	return croom->walkbehind_base[wa];
 }
 void *IAGSEngine::GetScriptFunctionAddress(const char *funcName) {
-	return ccGetSymbolAddressForPlugin((char *)funcName);
+	return ccGetSymbolAddressForPlugin((const char *)funcName);
 }
 int IAGSEngine::GetBitmapTransparentColor(BITMAP *bmp) {
 	return bitmap_mask_color(bmp);
@@ -543,7 +543,7 @@ void IAGSEngine::GetTextExtent(int32 font, const char *text, int32 *width, int32
 	if (width != nullptr)
 		width[0] = wgettextwidth_compensate(text, font);
 	if (height != nullptr)
-		height[0] = wgettextheight((char *)text, font);
+		height[0] = wgettextheight((const char *)text, font);
 }
 void IAGSEngine::PrintDebugConsole(const char *text) {
 	debug_script_log("[PLUGIN] %s", text);
@@ -681,7 +681,7 @@ int IAGSEngine::CallGameScriptFunction(const char *name, int32 globalScript, int
 	params[0].SetPluginArgument(arg1);
 	params[1].SetPluginArgument(arg2);
 	params[2].SetPluginArgument(arg3);
-	int toret = RunScriptFunctionIfExists(toRun, (char *)name, numArgs, params);
+	int toret = RunScriptFunctionIfExists(toRun, (const char *)name, numArgs, params);
 	return toret;
 }
 
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 037cda3400..1ccbbe3178 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -84,7 +84,6 @@ MODULE_OBJS = \
 	engine/game/savegame.o \
 	engine/game/savegame_components.o \
 	engine/game/viewport.o \
-	engine/gfx/all3dd3d.o \
 	engine/gfx/ali3dogl.o \
 	engine/gfx/ali3dsw.o \
 	engine/gfx/blender.o \
diff --git a/engines/ags/shared/gfx/bitmap.cpp b/engines/ags/shared/gfx/bitmap.cpp
index 01ee210b60..332e652815 100644
--- a/engines/ags/shared/gfx/bitmap.cpp
+++ b/engines/ags/shared/gfx/bitmap.cpp
@@ -88,7 +88,7 @@ template <class TPx, size_t BPP_>
 struct PixelTransCpy {
 	static const size_t BPP = BPP_;
 	inline void operator()(uint8_t *dst, const uint8_t *src, color_t mask_color, bool use_alpha) const {
-		if (*(TPx *)src == mask_color)
+		if (*(const TPx *)src == mask_color)
 			*(TPx *)dst = mask_color;
 	}
 };


Commit: 3b2728cd52eb663b0b6477e113791c4a1b3de47c
    https://github.com/scummvm/scummvm/commit/3b2728cd52eb663b0b6477e113791c4a1b3de47c
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix some const loss warnings

Changed paths:
    engines/ags/engine/plugin/agsplugin.cpp


diff --git a/engines/ags/engine/plugin/agsplugin.cpp b/engines/ags/engine/plugin/agsplugin.cpp
index 648bf89d5d..5307263fd9 100644
--- a/engines/ags/engine/plugin/agsplugin.cpp
+++ b/engines/ags/engine/plugin/agsplugin.cpp
@@ -727,7 +727,8 @@ void IAGSEngine::QueueGameScriptFunction(const char *name, int32 globalScript, i
 }
 
 int IAGSEngine::RegisterManagedObject(const void *object, IAGSScriptManagedObject *callback) {
-	GlobalReturnValue.SetPluginObject((void *)object, (ICCDynamicObject *)callback);
+	// TODO: handle loss of const better
+	GlobalReturnValue.SetPluginObject(const_cast<void *>(object), (ICCDynamicObject *)callback);
 	return ccRegisterManagedObject(object, (ICCDynamicObject *)callback, true);
 }
 
@@ -749,7 +750,8 @@ void IAGSEngine::AddManagedObjectReader(const char *typeName, IAGSManagedObjectR
 }
 
 void IAGSEngine::RegisterUnserializedObject(int key_, const void *object, IAGSScriptManagedObject *callback) {
-	GlobalReturnValue.SetPluginObject((void *)object, (ICCDynamicObject *)callback);
+	// TODO: handle loss of const better
+	GlobalReturnValue.SetPluginObject(const_cast<void *>(object), (ICCDynamicObject *)callback);
 	ccRegisterUnserializedObject(key_, object, (ICCDynamicObject *)callback, true);
 }
 
@@ -772,7 +774,8 @@ void *IAGSEngine::GetManagedObjectAddressByKey(int key_) {
 const char *IAGSEngine::CreateScriptString(const char *fromText) {
 	const char *string = CreateNewScriptString(fromText);
 	// Should be still standard dynamic object, because not managed by plugin
-	GlobalReturnValue.SetDynamicObject((void *)string, &myScriptStringImpl);
+	// TODO: handle loss of const better
+	GlobalReturnValue.SetDynamicObject(const_cast<char *>(string), &myScriptStringImpl);
 	return string;
 }
 


Commit: 32eb934454d85c6645c6d7d88e9946a78d303340
    https://github.com/scummvm/scummvm/commit/32eb934454d85c6645c6d7d88e9946a78d303340
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added engine/device/ folder

Changed paths:
    engines/ags/engine/device/mousew32.cpp
    engines/ags/module.mk


diff --git a/engines/ags/engine/device/mousew32.cpp b/engines/ags/engine/device/mousew32.cpp
index 5544601fd8..05454731bb 100644
--- a/engines/ags/engine/device/mousew32.cpp
+++ b/engines/ags/engine/device/mousew32.cpp
@@ -48,13 +48,13 @@
 #define FALSE 0
 #endif
 
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/debug/out.h"
-#include "ags/shared/device/mousew32.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/device/mousew32.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/gfx/gfx_util.h"
-#include "ags/shared/main/graphics_mode.h"
-#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/engine/gfx/gfx_util.h"
+#include "ags/engine/main/graphics_mode.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
 #include "ags/shared/util/math.h"
 #if AGS_SIMULATE_RIGHT_CLICK
 #include "ags/shared/ac/sys_events.h" // j for ags_iskeypressed
@@ -200,7 +200,7 @@ void domouse(int str) {
 	*/
 	int poow = mousecurs[currentcursor]->GetWidth();
 	int pooh = mousecurs[currentcursor]->GetHeight();
-	int smx = mousex - hotxwas, smy = mousey - hotywas;
+	//int smx = mousex - hotxwas, smy = mousey - hotywas;
 	const Rect &viewport = play.GetMainViewport();
 
 	mgetgraphpos();
@@ -238,8 +238,7 @@ void mfreemem() {
 void mloadwcursor(char *namm) {
 	color dummypal[256];
 	if (wloadsprites(&dummypal[0], namm, mousecurs, 0, MAXCURSORS)) {
-		//printf("C_Load_wCursor: Error reading mouse cursor file\n");
-		exit(1);
+		error("mloadwcursor: Error reading mouse cursor file");
 	}
 }
 
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 1ccbbe3178..996f9b6a07 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -79,6 +79,7 @@ MODULE_OBJS = \
 	shared/util/textstreamwriter.o \
 	shared/util/version.o \
 	shared/util/wgt2allg.o \
+	engine/device/mousew32.o \
 	engine/font/fonts_engine.o \
 	engine/game/game_init.o \
 	engine/game/savegame.o \


Commit: 9dda780dc604e4eceb07856ce598584be9d903c7
    https://github.com/scummvm/scummvm/commit/9dda780dc604e4eceb07856ce598584be9d903c7
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added engine/debugging/ folder

Changed paths:
    engines/ags/lib/allegro/keyboard.h
    engines/ags/module.mk
    engines/ags/std/initializer_list.h


diff --git a/engines/ags/lib/allegro/keyboard.h b/engines/ags/lib/allegro/keyboard.h
index 06187120f6..0634eec0ab 100644
--- a/engines/ags/lib/allegro/keyboard.h
+++ b/engines/ags/lib/allegro/keyboard.h
@@ -36,6 +36,7 @@ namespace AGS3 {
 #define KEY_ALT Common::KEYCODE_LALT
 #define KEY_LCONTROL Common::KEYCODE_LCTRL
 #define KEY_RCONTROL Common::KEYCODE_RCTRL
+#define KEY_SCRLOCK Common::KEYCODE_SCROLLOCK
 #define KEY_ALTGR 0
 #define KEY_F9 Common::KEYCODE_F9
 #define KEY_A Common::KEYCODE_a
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 996f9b6a07..8d6dda1c6e 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -79,6 +79,12 @@ MODULE_OBJS = \
 	shared/util/textstreamwriter.o \
 	shared/util/version.o \
 	shared/util/wgt2allg.o \
+	engine/debugging/consoleoutputtarget.o \
+	engine/debugging/debug.o \
+	engine/debugging/filebasedagsdebugger.o \
+	engine/debugging/logfile.o \
+	engine/debugging/messagebuffer.o \
+	engine/debugging/namedpipesagsdebugger.o \
 	engine/device/mousew32.o \
 	engine/font/fonts_engine.o \
 	engine/game/game_init.o \
diff --git a/engines/ags/std/initializer_list.h b/engines/ags/std/initializer_list.h
index 0b07f56eaa..21e7c2f643 100644
--- a/engines/ags/std/initializer_list.h
+++ b/engines/ags/std/initializer_list.h
@@ -23,44 +23,13 @@
 #ifndef AGS_STD_INITIALIZER_LIST_H
 #define AGS_STD_INITIALIZER_LIST_H
 
+#include <initializer_list>
+
 namespace AGS3 {
 namespace std {
 
-// CLASS TEMPLATE initializer_list
-template <class _Elem>
-class initializer_list {
-public:
-	using value_type = _Elem;
-	using reference = const _Elem &;
-	using const_reference = const _Elem &;
-	using size_type = size_t;
-
-	using iterator = const _Elem *;
-	using const_iterator = const _Elem *;
-
-	constexpr initializer_list() : _First(nullptr), _Last(nullptr) {
-	}
-
-	constexpr initializer_list(const _Elem *_First_arg, const _Elem *_Last_arg) noexcept
-		: _First(_First_arg), _Last(_Last_arg) {
-	}
-
-	constexpr const _Elem *begin() const {
-		return _First;
-	}
-
-	constexpr const _Elem *end() const {
-		return _Last;
-	}
-
-	constexpr size_t size() const {
-		return static_cast<size_t>(_Last - _First);
-	}
-
-private:
-	const _Elem *_First;
-	const _Elem *_Last;
-};
+template<class T>
+using initializer_list = ::std::initializer_list<T>;
 
 } // namespace std
 } // namespace AGS3


Commit: ed3476151a8cd8c068723f470934be74f375fe75
    https://github.com/scummvm/scummvm/commit/ed3476151a8cd8c068723f470934be74f375fe75
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: gcc warning fixes

Changed paths:
    engines/ags/engine/device/mousew32.cpp
    engines/ags/engine/gfx/gfxdriverbase.cpp
    engines/ags/engine/gui/guidialog.cpp
    engines/ags/module.mk


diff --git a/engines/ags/engine/device/mousew32.cpp b/engines/ags/engine/device/mousew32.cpp
index 05454731bb..16e65d813b 100644
--- a/engines/ags/engine/device/mousew32.cpp
+++ b/engines/ags/engine/device/mousew32.cpp
@@ -198,8 +198,8 @@ void domouse(int str) {
 	   TO USE THIS ROUTINE YOU MUST LOAD A MOUSE CURSOR USING mloadcursor.
 	   YOU MUST ALSO REMEMBER TO CALL mfreemem AT THE END OF THE PROGRAM.
 	*/
-	int poow = mousecurs[currentcursor]->GetWidth();
-	int pooh = mousecurs[currentcursor]->GetHeight();
+	int poow = mousecurs[(int)currentcursor]->GetWidth();
+	int pooh = mousecurs[(int)currentcursor]->GetHeight();
 	//int smx = mousex - hotxwas, smy = mousey - hotywas;
 	const Rect &viewport = play.GetMainViewport();
 
diff --git a/engines/ags/engine/gfx/gfxdriverbase.cpp b/engines/ags/engine/gfx/gfxdriverbase.cpp
index ce75c9b1ed..4b458a78b6 100644
--- a/engines/ags/engine/gfx/gfxdriverbase.cpp
+++ b/engines/ags/engine/gfx/gfxdriverbase.cpp
@@ -253,7 +253,7 @@ void VideoMemoryGraphicsDriver::DestroyFxPool() {
 #define algetb8(c)  getb8(c)
 
 
-__inline void get_pixel_if_not_transparent8(unsigned char *pixel, unsigned char *red, unsigned char *green, unsigned char *blue, unsigned char *divisor) {
+__inline void get_pixel_if_not_transparent8(const unsigned char *pixel, unsigned char *red, unsigned char *green, unsigned char *blue, unsigned char *divisor) {
 	if (pixel[0] != MASK_COLOR_8) {
 		*red += algetr8(pixel[0]);
 		*green += algetg8(pixel[0]);
@@ -262,7 +262,7 @@ __inline void get_pixel_if_not_transparent8(unsigned char *pixel, unsigned char
 	}
 }
 
-__inline void get_pixel_if_not_transparent16(unsigned short *pixel, unsigned short *red, unsigned short *green, unsigned short *blue, unsigned short *divisor) {
+__inline void get_pixel_if_not_transparent16(const unsigned short *pixel, unsigned short *red, unsigned short *green, unsigned short *blue, unsigned short *divisor) {
 	if (pixel[0] != MASK_COLOR_16) {
 		*red += algetr16(pixel[0]);
 		*green += algetg16(pixel[0]);
@@ -271,7 +271,7 @@ __inline void get_pixel_if_not_transparent16(unsigned short *pixel, unsigned sho
 	}
 }
 
-__inline void get_pixel_if_not_transparent32(unsigned int *pixel, unsigned int *red, unsigned int *green, unsigned int *blue, unsigned int *divisor) {
+__inline void get_pixel_if_not_transparent32(const unsigned int *pixel, unsigned int *red, unsigned int *green, unsigned int *blue, unsigned int *divisor) {
 	if (pixel[0] != MASK_COLOR_32) {
 		*red += algetr32(pixel[0]);
 		*green += algetg32(pixel[0]);
@@ -298,7 +298,7 @@ void VideoMemoryGraphicsDriver::BitmapToVideoMem(const Bitmap *bitmap, const boo
 
 		for (int x = 0; x < tile->width; x++) {
 			if (src_depth == 8) {
-				unsigned char *srcData = (unsigned char *)&scanline_at[(x + tile->x) * sizeof(char)];
+				const unsigned char *srcData = (const unsigned char *)&scanline_at[(x + tile->x) * sizeof(char)];
 				if (*srcData == MASK_COLOR_8) {
 					if (!usingLinearFiltering)
 						memPtrLong[x] = 0;
@@ -311,9 +311,9 @@ void VideoMemoryGraphicsDriver::BitmapToVideoMem(const Bitmap *bitmap, const boo
 						if (x < tile->width - 1)
 							get_pixel_if_not_transparent8(&srcData[1], &red, &green, &blue, &divisor);
 						if (y > 0)
-							get_pixel_if_not_transparent8((unsigned char *)&scanline_before[(x + tile->x) * sizeof(char)], &red, &green, &blue, &divisor);
+							get_pixel_if_not_transparent8((const unsigned char *)&scanline_before[(x + tile->x) * sizeof(char)], &red, &green, &blue, &divisor);
 						if (y < tile->height - 1)
-							get_pixel_if_not_transparent8((unsigned char *)&scanline_after[(x + tile->x) * sizeof(char)], &red, &green, &blue, &divisor);
+							get_pixel_if_not_transparent8((const unsigned char *)&scanline_after[(x + tile->x) * sizeof(char)], &red, &green, &blue, &divisor);
 						if (divisor > 0)
 							memPtrLong[x] = VMEMCOLOR_RGBA(red / divisor, green / divisor, blue / divisor, 0);
 						else
@@ -330,7 +330,7 @@ void VideoMemoryGraphicsDriver::BitmapToVideoMem(const Bitmap *bitmap, const boo
 					}
 				}
 			} else if (src_depth == 16) {
-				unsigned short *srcData = (unsigned short *)&scanline_at[(x + tile->x) * sizeof(short)];
+				const unsigned short *srcData = (const unsigned short *)&scanline_at[(x + tile->x) * sizeof(short)];
 				if (*srcData == MASK_COLOR_16) {
 					if (!usingLinearFiltering)
 						memPtrLong[x] = 0;
@@ -343,9 +343,9 @@ void VideoMemoryGraphicsDriver::BitmapToVideoMem(const Bitmap *bitmap, const boo
 						if (x < tile->width - 1)
 							get_pixel_if_not_transparent16(&srcData[1], &red, &green, &blue, &divisor);
 						if (y > 0)
-							get_pixel_if_not_transparent16((unsigned short *)&scanline_before[(x + tile->x) * sizeof(short)], &red, &green, &blue, &divisor);
+							get_pixel_if_not_transparent16((const unsigned short *)&scanline_before[(x + tile->x) * sizeof(short)], &red, &green, &blue, &divisor);
 						if (y < tile->height - 1)
-							get_pixel_if_not_transparent16((unsigned short *)&scanline_after[(x + tile->x) * sizeof(short)], &red, &green, &blue, &divisor);
+							get_pixel_if_not_transparent16((const unsigned short *)&scanline_after[(x + tile->x) * sizeof(short)], &red, &green, &blue, &divisor);
 						if (divisor > 0)
 							memPtrLong[x] = VMEMCOLOR_RGBA(red / divisor, green / divisor, blue / divisor, 0);
 						else
@@ -363,7 +363,7 @@ void VideoMemoryGraphicsDriver::BitmapToVideoMem(const Bitmap *bitmap, const boo
 				}
 			} else if (src_depth == 32) {
 				unsigned int *ptrLong = (unsigned int *)dst_ptr;
-				unsigned int *srcData = (unsigned int *)&scanline_at[(x + tile->x) * sizeof(int)];
+				const unsigned int *srcData = (const unsigned int *)&scanline_at[(x + tile->x) * sizeof(int)];
 				if (*srcData == MASK_COLOR_32) {
 					if (!usingLinearFiltering)
 						ptrLong[x] = 0;
@@ -376,9 +376,9 @@ void VideoMemoryGraphicsDriver::BitmapToVideoMem(const Bitmap *bitmap, const boo
 						if (x < tile->width - 1)
 							get_pixel_if_not_transparent32(&srcData[1], &red, &green, &blue, &divisor);
 						if (y > 0)
-							get_pixel_if_not_transparent32((unsigned int *)&scanline_before[(x + tile->x) * sizeof(int)], &red, &green, &blue, &divisor);
+							get_pixel_if_not_transparent32((const unsigned int *)&scanline_before[(x + tile->x) * sizeof(int)], &red, &green, &blue, &divisor);
 						if (y < tile->height - 1)
-							get_pixel_if_not_transparent32((unsigned int *)&scanline_after[(x + tile->x) * sizeof(int)], &red, &green, &blue, &divisor);
+							get_pixel_if_not_transparent32((const unsigned int *)&scanline_after[(x + tile->x) * sizeof(int)], &red, &green, &blue, &divisor);
 						if (divisor > 0)
 							ptrLong[x] = VMEMCOLOR_RGBA(red / divisor, green / divisor, blue / divisor, 0);
 						else
@@ -412,14 +412,14 @@ void VideoMemoryGraphicsDriver::BitmapToVideoMemOpaque(const Bitmap *bitmap, con
 
 		for (int x = 0; x < tile->width; x++) {
 			if (src_depth == 8) {
-				unsigned char *srcData = (unsigned char *)&scanline_at[(x + tile->x) * sizeof(char)];
+				const unsigned char *srcData = (const unsigned char *)&scanline_at[(x + tile->x) * sizeof(char)];
 				memPtrLong[x] = VMEMCOLOR_RGBA(algetr8(*srcData), algetg8(*srcData), algetb8(*srcData), 0xFF);
 			} else if (src_depth == 16) {
-				unsigned short *srcData = (unsigned short *)&scanline_at[(x + tile->x) * sizeof(short)];
+				const unsigned short *srcData = (const unsigned short *)&scanline_at[(x + tile->x) * sizeof(short)];
 				memPtrLong[x] = VMEMCOLOR_RGBA(algetr16(*srcData), algetg16(*srcData), algetb16(*srcData), 0xFF);
 			} else if (src_depth == 32) {
 				//unsigned int *memPtrLong = (unsigned int *)dst_ptr;
-				unsigned int *srcData = (unsigned int *)&scanline_at[(x + tile->x) * sizeof(int)];
+				const unsigned int *srcData = (const unsigned int *)&scanline_at[(x + tile->x) * sizeof(int)];
 				if (has_alpha)
 					memPtrLong[x] = VMEMCOLOR_RGBA(algetr32(*srcData), algetg32(*srcData), algetb32(*srcData), algeta32(*srcData));
 				else
diff --git a/engines/ags/engine/gui/guidialog.cpp b/engines/ags/engine/gui/guidialog.cpp
index d2d2b71111..56002f6bb1 100644
--- a/engines/ags/engine/gui/guidialog.cpp
+++ b/engines/ags/engine/gui/guidialog.cpp
@@ -54,7 +54,7 @@ IDriverDependantBitmap *dialogDDB;
 
 #undef MAXSAVEGAMES
 #define MAXSAVEGAMES 20
-DisplayProperties dispp;
+//DisplayProperties dispp;
 char *lpTemp, *lpTemp2;
 char bufTemp[260], buffer2[260];
 int numsaves = 0, toomanygames;
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 8d6dda1c6e..d3a5f53859 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -84,7 +84,6 @@ MODULE_OBJS = \
 	engine/debugging/filebasedagsdebugger.o \
 	engine/debugging/logfile.o \
 	engine/debugging/messagebuffer.o \
-	engine/debugging/namedpipesagsdebugger.o \
 	engine/device/mousew32.o \
 	engine/font/fonts_engine.o \
 	engine/game/game_init.o \


Commit: c7793a82fb97f2fc6f3ca6f43a6bbc7c38b2b728
    https://github.com/scummvm/scummvm/commit/c7793a82fb97f2fc6f3ca6f43a6bbc7c38b2b728
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: std::set implementation now derives from Common::SortedArray

Changed paths:
    engines/ags/std/set.h


diff --git a/engines/ags/std/set.h b/engines/ags/std/set.h
index 18d30e2bdb..5df72295ce 100644
--- a/engines/ags/std/set.h
+++ b/engines/ags/std/set.h
@@ -23,102 +23,39 @@
 #ifndef AGS_STD_SET_H
 #define AGS_STD_SET_H
 
+#include "common/array.h"
+
 namespace AGS3 {
 namespace std {
 
-template<class T>
-class set {
-	struct Comparitor {
-		bool operator()(const T &a, const T &b) const {
-			return a == b;
-		}
-	};
-
-	class Items : public Common::Array<T> {
-	public:
-		void swap(Items &arr) {
-			SWAP(this->_capacity, arr._capacity);
-			SWAP(this->_size, arr._size);
-			SWAP(this->_storage, arr._storage);
-		}
-	};
+/**
+ * Derives the ScummVM SortedArray to match the std::set class
+ */
+template<class T, class EqualFunc = Common::Less<T> >
+class set : public Common::SortedArray<T, const T &> {
 private:
-	Items _items;
-	Comparitor _comparitor;
-public:
-	typedef T *iterator;
-	typedef const T *const_iterator;
-
-	iterator begin() {
-		return _items.begin();
-	}
-	iterator end() {
-		return _items.end();
-	}
-	const_iterator begin() const {
-		return _items.begin();
-	}
-	const_iterator end() const {
-		return _items.end();
-	}
-
-	/**
-	 * Clear the set
-	 */
-	void clear() {
-		_items.clear();
-	}
-
-	/**
-	 * Inserts a new item
-	 */
-	void insert(T val) {
-		_items.push_back(val);
-		Common::sort(begin(), end(), _comparitor);
-	}
-
-	/**
-	 * Inserts a range of items
-	 */
-	void insert(iterator first, iterator last) {
-		for (; first != last; ++first)
-			_items.push_back(*first);
-		Common::sort(begin(), end(), _comparitor);
-	}
-
-	/**
-	 * Swaps a set
-	 */
-	void swap(set<T> &arr) {
-		_items.swap(arr);
+	static int ComparatorFn(const T &a, const T &b) {
+		return EqualFunc()(a, b) ? -1 : 0;
 	}
+public:
+	using const_iterator = typename Common::SortedArray<T, const T &>::const_iterator;
 
 	/**
-	 * Find an item
+	 * Constructor
 	 */
-	iterator find(const T item) {
-		iterator it = begin();
-		for (; it != end() && *it != item; ++it) {}
-		return it;
-	}
-	const_iterator find(const T item) const {
-		const_iterator it = begin();
-		for (; it != end() && *it != item; ++it) {
-		}
-		return it;
-	}
-	bool empty() const {
-		return _items.empty();
-	}
+	set() : Common::SortedArray<T, const T &>(ComparatorFn) {}
 
 	/**
-	 * Returns the number of matching entries
+	 * Returns the number of keys that match the specified key
 	 */
 	size_t count(const T item) const {
 		size_t total = 0;
-		for (const_iterator it = begin(); it != end(); ++it) {
+		for (const_iterator it = this->begin(); it != this->end(); ++it) {
 			if (*it == item)
 				++total;
+			else if (!ComparatorFn(item, *it))
+				// Passed beyond possibility of matches
+				break;
 		}
 
 		return total;


Commit: ba9bf10d50b64a0a01a39ba5a482ac290590a423
    https://github.com/scummvm/scummvm/commit/ba9bf10d50b64a0a01a39ba5a482ac290590a423
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added engine/ac/dynobj/ folder

Changed paths:
  A engines/ags/std/unordered_set.h
    engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp
    engines/ags/engine/ac/dynobj/cc_audiochannel.cpp
    engines/ags/engine/ac/dynobj/cc_audioclip.cpp
    engines/ags/engine/ac/dynobj/cc_character.cpp
    engines/ags/engine/ac/dynobj/cc_dialog.cpp
    engines/ags/engine/ac/dynobj/cc_dynamicarray.cpp
    engines/ags/engine/ac/dynobj/cc_dynamicobject.cpp
    engines/ags/engine/ac/dynobj/cc_gui.cpp
    engines/ags/engine/ac/dynobj/cc_guiobject.cpp
    engines/ags/engine/ac/dynobj/cc_hotspot.cpp
    engines/ags/engine/ac/dynobj/cc_inventory.cpp
    engines/ags/engine/ac/dynobj/cc_object.cpp
    engines/ags/engine/ac/dynobj/cc_region.cpp
    engines/ags/engine/ac/dynobj/cc_serializer.cpp
    engines/ags/engine/ac/dynobj/managedobjectpool.cpp
    engines/ags/engine/ac/dynobj/scriptcamera.cpp
    engines/ags/engine/ac/dynobj/scriptcamera.h
    engines/ags/engine/ac/dynobj/scriptdatetime.cpp
    engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.cpp
    engines/ags/engine/ac/dynobj/scriptdict.cpp
    engines/ags/engine/ac/dynobj/scriptdict.h
    engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp
    engines/ags/engine/ac/dynobj/scriptdynamicsprite.cpp
    engines/ags/engine/ac/dynobj/scriptfile.cpp
    engines/ags/engine/ac/dynobj/scriptoverlay.cpp
    engines/ags/engine/ac/dynobj/scriptset.cpp
    engines/ags/engine/ac/dynobj/scriptset.h
    engines/ags/engine/ac/dynobj/scriptstring.cpp
    engines/ags/engine/ac/dynobj/scriptuserobject.cpp
    engines/ags/engine/ac/dynobj/scriptviewframe.cpp
    engines/ags/engine/ac/dynobj/scriptviewport.cpp
    engines/ags/engine/ac/dynobj/scriptviewport.h
    engines/ags/module.mk
    engines/ags/shared/util/string_types.h
    engines/ags/std/map.h
    engines/ags/std/set.h


diff --git a/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp b/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp
index f64397eec1..c0d4d780f0 100644
--- a/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp
@@ -22,7 +22,7 @@
 
 //include <string.h>
 #include "ags/shared/core/types.h"
-#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/engine/ac/dynobj/cc_agsdynamicobject.h"
 #include "ags/shared/ac/common.h"               // quit()
 #include "ags/shared/util/bbop.h"
 
diff --git a/engines/ags/engine/ac/dynobj/cc_audiochannel.cpp b/engines/ags/engine/ac/dynobj/cc_audiochannel.cpp
index 280486465f..ae636d4de8 100644
--- a/engines/ags/engine/ac/dynobj/cc_audiochannel.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_audiochannel.cpp
@@ -20,9 +20,9 @@
  *
  */
 
-#include "ags/shared/ac/dynobj/cc_audiochannel.h"
-#include "ags/shared/ac/dynobj/scriptaudiochannel.h"
-#include "ags/shared/media/audio/audio_system.h"
+#include "ags/engine/ac/dynobj/cc_audiochannel.h"
+#include "ags/engine/ac/dynobj/scriptaudiochannel.h"
+#include "ags/engine/media/audio/audio_system.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_audioclip.cpp b/engines/ags/engine/ac/dynobj/cc_audioclip.cpp
index 6f63f2fd64..cebe70e779 100644
--- a/engines/ags/engine/ac/dynobj/cc_audioclip.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_audioclip.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/shared/ac/dynobj/cc_audioclip.h"
+#include "ags/engine/ac/dynobj/cc_audioclip.h"
 #include "ags/shared/ac/dynobj/scriptaudioclip.h"
 #include "ags/shared/ac/gamesetupstruct.h"
 
diff --git a/engines/ags/engine/ac/dynobj/cc_character.cpp b/engines/ags/engine/ac/dynobj/cc_character.cpp
index 6944fc652d..c114d94801 100644
--- a/engines/ags/engine/ac/dynobj/cc_character.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_character.cpp
@@ -20,9 +20,9 @@
  *
  */
 
-#include "ags/shared/ac/dynobj/cc_character.h"
+#include "ags/engine/ac/dynobj/cc_character.h"
 #include "ags/shared/ac/characterinfo.h"
-#include "ags/shared/ac/global_character.h"
+#include "ags/engine/ac/global_character.h"
 #include "ags/shared/ac/gamesetupstruct.h"
 #include "ags/shared/ac/game_version.h"
 
diff --git a/engines/ags/engine/ac/dynobj/cc_dialog.cpp b/engines/ags/engine/ac/dynobj/cc_dialog.cpp
index 622f6392ac..6be1090ecc 100644
--- a/engines/ags/engine/ac/dynobj/cc_dialog.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_dialog.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ags/shared/ac/dynobj/cc_dialog.h"
-#include "ags/shared/ac/dialog.h"
+#include "ags/engine/ac/dynobj/cc_dialog.h"
+#include "ags/engine/ac/dialog.h"
 #include "ags/shared/ac/dialogtopic.h"
 #include "ags/shared/ac/gamestructdefines.h"
 
diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicarray.cpp b/engines/ags/engine/ac/dynobj/cc_dynamicarray.cpp
index 118eb4e8a7..03fe679707 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicarray.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicarray.cpp
@@ -21,7 +21,7 @@
  */
 
 //include <string.h>
-#include "ags/shared/cc_dynamicarray.h"
+#include "ags/engine/ac/dynobj/cc_dynamicarray.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicobject.cpp b/engines/ags/engine/ac/dynobj/cc_dynamicobject.cpp
index 7fb7290c00..8492137105 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicobject.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicobject.cpp
@@ -38,9 +38,9 @@
 
 //include <stdlib.h>
 //include <string.h>
-#include "ags/shared/ac/dynobj/cc_dynamicobject.h"
-#include "ags/shared/ac/dynobj/managedobjectpool.h"
-#include "ags/shared/debug/out.h"
+#include "ags/engine/ac/dynobj/cc_dynamicobject.h"
+#include "ags/engine/ac/dynobj/managedobjectpool.h"
+#include "ags/shared/debugging/out.h"
 #include "ags/shared/script/cc_error.h"
 #include "ags/shared/script/script_common.h"
 #include "ags/shared/util/stream.h"
diff --git a/engines/ags/engine/ac/dynobj/cc_gui.cpp b/engines/ags/engine/ac/dynobj/cc_gui.cpp
index 9b2d472b5e..4c9b46482f 100644
--- a/engines/ags/engine/ac/dynobj/cc_gui.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_gui.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ags/shared/ac/dynobj/cc_gui.h"
-#include "ags/shared/ac/dynobj/scriptgui.h"
+#include "ags/engine/ac/dynobj/cc_gui.h"
+#include "ags/engine/ac/dynobj/scriptgui.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/cc_guiobject.cpp b/engines/ags/engine/ac/dynobj/cc_guiobject.cpp
index 9bbb9352dc..e8c0e35091 100644
--- a/engines/ags/engine/ac/dynobj/cc_guiobject.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_guiobject.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ags/shared/ac/dynobj/cc_guiobject.h"
-#include "ags/shared/ac/dynobj/scriptgui.h"
+#include "ags/engine/ac/dynobj/cc_guiobject.h"
+#include "ags/engine/ac/dynobj/scriptgui.h"
 #include "ags/shared/gui/guimain.h"
 #include "ags/shared/gui/guiobject.h"
 
diff --git a/engines/ags/engine/ac/dynobj/cc_hotspot.cpp b/engines/ags/engine/ac/dynobj/cc_hotspot.cpp
index 0bf87cf479..8a46774042 100644
--- a/engines/ags/engine/ac/dynobj/cc_hotspot.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_hotspot.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ags/shared/ac/dynobj/cc_hotspot.h"
-#include "ags/shared/ac/dynobj/scripthotspot.h"
+#include "ags/engine/ac/dynobj/cc_hotspot.h"
+#include "ags/engine/ac/dynobj/scripthotspot.h"
 #include "ags/shared/ac/common_defines.h"
 #include "ags/shared/game/roomstruct.h"
 
diff --git a/engines/ags/engine/ac/dynobj/cc_inventory.cpp b/engines/ags/engine/ac/dynobj/cc_inventory.cpp
index d213c84c2e..60cae380be 100644
--- a/engines/ags/engine/ac/dynobj/cc_inventory.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_inventory.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ags/shared/ac/dynobj/cc_inventory.h"
-#include "ags/shared/ac/dynobj/scriptinvitem.h"
+#include "ags/engine/ac/dynobj/cc_inventory.h"
+#include "ags/engine/ac/dynobj/scriptinvitem.h"
 #include "ags/shared/ac/characterinfo.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/ac/dynobj/cc_object.cpp b/engines/ags/engine/ac/dynobj/cc_object.cpp
index 092f5123db..abcd84f8dc 100644
--- a/engines/ags/engine/ac/dynobj/cc_object.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_object.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ags/shared/ac/dynobj/cc_object.h"
-#include "ags/shared/ac/dynobj/scriptobject.h"
+#include "ags/engine/ac/dynobj/cc_object.h"
+#include "ags/engine/ac/dynobj/scriptobject.h"
 #include "ags/shared/ac/common_defines.h"
 #include "ags/shared/game/roomstruct.h"
 
diff --git a/engines/ags/engine/ac/dynobj/cc_region.cpp b/engines/ags/engine/ac/dynobj/cc_region.cpp
index 9d804eee84..a6fc8910b5 100644
--- a/engines/ags/engine/ac/dynobj/cc_region.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_region.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ags/shared/ac/dynobj/cc_region.h"
-#include "ags/shared/ac/dynobj/scriptregion.h"
+#include "ags/engine/ac/dynobj/cc_region.h"
+#include "ags/engine/ac/dynobj/scriptregion.h"
 #include "ags/shared/ac/common_defines.h"
 #include "ags/shared/game/roomstruct.h"
 
diff --git a/engines/ags/engine/ac/dynobj/cc_serializer.cpp b/engines/ags/engine/ac/dynobj/cc_serializer.cpp
index fc932e3fcd..1e91c8c8e6 100644
--- a/engines/ags/engine/ac/dynobj/cc_serializer.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_serializer.cpp
@@ -21,18 +21,18 @@
  */
 
 //include <string.h>
-#include "ags/shared/ac/dynobj/cc_serializer.h"
-#include "ags/shared/ac/dynobj/all_dynamicclasses.h"
-#include "ags/shared/ac/dynobj/all_scriptclasses.h"
-#include "ags/shared/ac/dynobj/scriptcamera.h"
-#include "ags/shared/ac/dynobj/scriptcontainers.h"
-#include "ags/shared/ac/dynobj/scriptfile.h"
-#include "ags/shared/ac/dynobj/scriptuserobject.h"
-#include "ags/shared/ac/dynobj/scriptviewport.h"
-#include "ags/shared/ac/game.h"
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/plugin/agsplugin.h"
-#include "ags/shared/plugin/pluginobjectreader.h"
+#include "ags/engine/ac/dynobj/cc_serializer.h"
+#include "ags/engine/ac/dynobj/all_dynamicclasses.h"
+#include "ags/engine/ac/dynobj/all_scriptclasses.h"
+#include "ags/engine/ac/dynobj/scriptcamera.h"
+#include "ags/engine/ac/dynobj/scriptcontainers.h"
+#include "ags/engine/ac/dynobj/scriptfile.h"
+#include "ags/engine/ac/dynobj/scriptuserobject.h"
+#include "ags/engine/ac/dynobj/scriptviewport.h"
+#include "ags/engine/ac/game.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/plugin/agsplugin.h"
+#include "ags/engine/plugin/pluginobjectreader.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/managedobjectpool.cpp b/engines/ags/engine/ac/dynobj/managedobjectpool.cpp
index d6a9d5b997..d7b30f4ef9 100644
--- a/engines/ags/engine/ac/dynobj/managedobjectpool.cpp
+++ b/engines/ags/engine/ac/dynobj/managedobjectpool.cpp
@@ -22,9 +22,9 @@
 
 #include "ags/std/vector.h"
 //include <string.h>
-#include "ags/shared/ac/dynobj/managedobjectpool.h"
-#include "ags/shared/ac/dynobj/cc_dynamicarray.h" // globalDynamicArray, constants
-#include "ags/shared/debug/out.h"
+#include "ags/engine/ac/dynobj/managedobjectpool.h"
+#include "ags/engine/ac/dynobj/cc_dynamicarray.h" // globalDynamicArray, constants
+#include "ags/shared/debugging/out.h"
 #include "ags/shared/util/string_utils.h"               // fputstring, etc
 #include "ags/shared/script/cc_error.h"
 #include "ags/shared/script/script_common.h"
@@ -116,7 +116,7 @@ int32_t ManagedObjectPool::AddressToHandle(const char *addr) {
 	if (it == handleByAddress.end()) {
 		return 0;
 	}
-	return it->second;
+	return it->_value;
 }
 
 // this function is called often (whenever a pointer is used)
@@ -155,7 +155,7 @@ int ManagedObjectPool::RemoveObject(const char *address) {
 		return 0;
 	}
 
-	auto &o = objects[it->second];
+	auto &o = objects[it->_value];
 	return Remove(o, true);
 }
 
diff --git a/engines/ags/engine/ac/dynobj/scriptcamera.cpp b/engines/ags/engine/ac/dynobj/scriptcamera.cpp
index 0eebc6177f..aa7aa5d8bd 100644
--- a/engines/ags/engine/ac/dynobj/scriptcamera.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptcamera.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ags/shared/ac/dynobj/scriptcamera.h"
-#include "ags/shared/ac/gamestate.h"
+#include "ags/engine/ac/dynobj/scriptcamera.h"
+#include "ags/engine/ac/gamestate.h"
 #include "ags/shared/util/bbop.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/ac/dynobj/scriptcamera.h b/engines/ags/engine/ac/dynobj/scriptcamera.h
index 019896fc68..8d77f9d205 100644
--- a/engines/ags/engine/ac/dynobj/scriptcamera.h
+++ b/engines/ags/engine/ac/dynobj/scriptcamera.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTCAMERA_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTCAMERA_H
 
-#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/engine/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptdatetime.cpp b/engines/ags/engine/ac/dynobj/scriptdatetime.cpp
index 459cc717ac..b055e380e1 100644
--- a/engines/ags/engine/ac/dynobj/scriptdatetime.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptdatetime.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/shared/ac/dynobj/scriptdatetime.h"
+#include "ags/engine/ac/dynobj/scriptdatetime.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.cpp b/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.cpp
index 017aaf599c..d442b16e8f 100644
--- a/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptdialogoptionsrendering.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/shared/ac/dynobj/scriptdialogoptionsrendering.h"
+#include "ags/engine/ac/dynobj/scriptdialogoptionsrendering.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptdict.cpp b/engines/ags/engine/ac/dynobj/scriptdict.cpp
index 9260e20332..7991471e11 100644
--- a/engines/ags/engine/ac/dynobj/scriptdict.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptdict.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/shared/ac/dynobj/scriptdict.h"
+#include "ags/engine/ac/dynobj/scriptdict.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptdict.h b/engines/ags/engine/ac/dynobj/scriptdict.h
index 85a0bdc7b3..08740845c6 100644
--- a/engines/ags/engine/ac/dynobj/scriptdict.h
+++ b/engines/ags/engine/ac/dynobj/scriptdict.h
@@ -36,10 +36,9 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTDICT_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTDICT_H
 
-//include <map>
-//include <unordered_map>
 //include <string.h>
-#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/std/map.h"
+#include "ags/engine/ac/dynobj/cc_agsdynamicobject.h"
 #include "ags/shared/util/string.h"
 #include "ags/shared/util/string_types.h"
 
@@ -183,9 +182,9 @@ private:
 };
 
 typedef ScriptDictImpl< std::map<String, String>, true, true > ScriptDict;
-typedef ScriptDictImpl< std::map<String, String, StrLessNoCase>, true, false > ScriptDictCI;
+typedef ScriptDictImpl< std::map<String, String, IgnoreCase_LessThan>, true, false > ScriptDictCI;
 typedef ScriptDictImpl< std::unordered_map<String, String>, false, true > ScriptHashDict;
-typedef ScriptDictImpl< std::unordered_map<String, String, HashStrNoCase, StrEqNoCase>, false, false > ScriptHashDictCI;
+typedef ScriptDictImpl< std::unordered_map<String, String, IgnoreCase_Hash, IgnoreCase_EqualTo>, false, false > ScriptHashDictCI;
 
 } // namespace AGS3
 
diff --git a/engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp b/engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp
index 24cd01bc94..041a9f7aad 100644
--- a/engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp
@@ -20,12 +20,12 @@
  *
  */
 
-#include "ags/shared/ac/dynobj/scriptdrawingsurface.h"
+#include "ags/engine/ac/dynobj/scriptdrawingsurface.h"
 #include "ags/shared/ac/spritecache.h"
-#include "ags/shared/ac/runtime_defines.h"
+#include "ags/engine/ac/runtime_defines.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/drawingsurface.h"
-#include "ags/shared/ac/gamestate.h"
+#include "ags/engine/ac/drawingsurface.h"
+#include "ags/engine/ac/gamestate.h"
 #include "ags/shared/ac/gamesetupstruct.h"
 #include "ags/shared/game/roomstruct.h"
 #include "ags/shared/gfx/bitmap.h"
diff --git a/engines/ags/engine/ac/dynobj/scriptdynamicsprite.cpp b/engines/ags/engine/ac/dynobj/scriptdynamicsprite.cpp
index 83e94075f3..d21f430d9b 100644
--- a/engines/ags/engine/ac/dynobj/scriptdynamicsprite.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptdynamicsprite.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ags/shared/ac/dynobj/scriptdynamicsprite.h"
-#include "ags/shared/ac/dynamicsprite.h"
+#include "ags/engine/ac/dynobj/scriptdynamicsprite.h"
+#include "ags/engine/ac/dynamicsprite.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptfile.cpp b/engines/ags/engine/ac/dynobj/scriptfile.cpp
index 8d75f62462..8798d2bb41 100644
--- a/engines/ags/engine/ac/dynobj/scriptfile.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptfile.cpp
@@ -20,16 +20,16 @@
  *
  */
 
-#include "ags/shared/ac/dynobj/scriptfile.h"
-#include "ags/shared/ac/global_file.h"
+#include "ags/engine/ac/dynobj/scriptfile.h"
+#include "ags/engine/ac/global_file.h"
 
 namespace AGS3 {
 
 // CHECKME: actually NULLs here will be equal to kFile_Open & kFile_Read
-const Common::FileOpenMode sc_File::fopenModes[] =
-{ Common::kFile_Open/*CHECKME, was undefined*/, Common::kFile_Open, Common::kFile_CreateAlways, Common::kFile_Create };
-const Common::FileWorkMode sc_File::fworkModes[] =
-{ Common::kFile_Read/*CHECKME, was undefined*/, Common::kFile_Read, Common::kFile_Write, Common::kFile_Write };
+const Shared::FileOpenMode sc_File::fopenModes[] =
+{ Shared::kFile_Open/*CHECKME, was undefined*/, Shared::kFile_Open, Shared::kFile_CreateAlways, Shared::kFile_Create };
+const Shared::FileWorkMode sc_File::fworkModes[] =
+{ Shared::kFile_Read/*CHECKME, was undefined*/, Shared::kFile_Read, Shared::kFile_Write, Shared::kFile_Write };
 
 int sc_File::Dispose(const char *address, bool force) {
 	Close();
diff --git a/engines/ags/engine/ac/dynobj/scriptoverlay.cpp b/engines/ags/engine/ac/dynobj/scriptoverlay.cpp
index 0a8f3be675..918538a426 100644
--- a/engines/ags/engine/ac/dynobj/scriptoverlay.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptoverlay.cpp
@@ -20,11 +20,11 @@
  *
  */
 
-#include "ags/shared/ac/dynobj/scriptoverlay.h"
+#include "ags/engine/ac/dynobj/scriptoverlay.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/overlay.h"
-#include "ags/shared/ac/runtime_defines.h"
-#include "ags/shared/ac/screenoverlay.h"
+#include "ags/engine/ac/overlay.h"
+#include "ags/engine/ac/runtime_defines.h"
+#include "ags/engine/ac/screenoverlay.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptset.cpp b/engines/ags/engine/ac/dynobj/scriptset.cpp
index c3cc922ef9..8141fc8913 100644
--- a/engines/ags/engine/ac/dynobj/scriptset.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptset.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/shared/ac/dynobj/scriptset.h"
+#include "ags/engine/ac/dynobj/scriptset.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptset.h b/engines/ags/engine/ac/dynobj/scriptset.h
index f20a979c85..e6ca5068f7 100644
--- a/engines/ags/engine/ac/dynobj/scriptset.h
+++ b/engines/ags/engine/ac/dynobj/scriptset.h
@@ -35,10 +35,10 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTSET_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTSET_H
 
-//include <set>
-//include <unordered_set>
-//include <string.h>
-#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/std/set.h"
+#include "ags/std/unordered_set.h"
+#include "ags/std/map.h"
+#include "ags/engine/ac/dynobj/cc_agsdynamicobject.h"
 #include "ags/shared/util/string.h"
 #include "ags/shared/util/string_types.h"
 
@@ -148,9 +148,9 @@ private:
 };
 
 typedef ScriptSetImpl< std::set<String>, true, true > ScriptSet;
-typedef ScriptSetImpl< std::set<String, StrLessNoCase>, true, false > ScriptSetCI;
+typedef ScriptSetImpl< std::set<String, IgnoreCase_LessThan>, true, false > ScriptSetCI;
 typedef ScriptSetImpl< std::unordered_set<String>, false, true > ScriptHashSet;
-typedef ScriptSetImpl< std::unordered_set<String, HashStrNoCase, StrEqNoCase>, false, false > ScriptHashSetCI;
+typedef ScriptSetImpl< std::unordered_set<String, IgnoreCase_Hash, IgnoreCase_EqualTo>, false, false > ScriptHashSetCI;
 
 } // namespace AGS3
 
diff --git a/engines/ags/engine/ac/dynobj/scriptstring.cpp b/engines/ags/engine/ac/dynobj/scriptstring.cpp
index 9f55a1c8f1..695f94bfb6 100644
--- a/engines/ags/engine/ac/dynobj/scriptstring.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptstring.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ags/shared/ac/dynobj/scriptstring.h"
-#include "ags/shared/ac/string.h"
+#include "ags/engine/ac/dynobj/scriptstring.h"
+#include "ags/engine/ac/string.h"
 //include <stdlib.h>
 //include <string.h>
 
diff --git a/engines/ags/engine/ac/dynobj/scriptuserobject.cpp b/engines/ags/engine/ac/dynobj/scriptuserobject.cpp
index e3d949c4be..ae02f3cb91 100644
--- a/engines/ags/engine/ac/dynobj/scriptuserobject.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptuserobject.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-//include <memory.h>
-#include "ags/shared/scriptuserobject.h"
+#include "ags/std/memory.h"
+#include "ags/engine/ac/dynobj/scriptuserobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptviewframe.cpp b/engines/ags/engine/ac/dynobj/scriptviewframe.cpp
index d60d45733b..44e2d7271c 100644
--- a/engines/ags/engine/ac/dynobj/scriptviewframe.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptviewframe.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/shared/ac/dynobj/scriptviewframe.h"
+#include "ags/engine/ac/dynobj/scriptviewframe.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/dynobj/scriptviewport.cpp b/engines/ags/engine/ac/dynobj/scriptviewport.cpp
index 8783de7307..e578dce594 100644
--- a/engines/ags/engine/ac/dynobj/scriptviewport.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptviewport.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ags/shared/ac/dynobj/scriptviewport.h"
-#include "ags/shared/ac/gamestate.h"
+#include "ags/engine/ac/dynobj/scriptviewport.h"
+#include "ags/engine/ac/gamestate.h"
 #include "ags/shared/util/bbop.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/ac/dynobj/scriptviewport.h b/engines/ags/engine/ac/dynobj/scriptviewport.h
index 9075190a09..fc4ea1a258 100644
--- a/engines/ags/engine/ac/dynobj/scriptviewport.h
+++ b/engines/ags/engine/ac/dynobj/scriptviewport.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTVIEWPORT_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTVIEWPORT_H
 
-#include "ags/shared/ac/dynobj/cc_agsdynamicobject.h"
+#include "ags/engine/ac/dynobj/cc_agsdynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index d3a5f53859..5598eb3491 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -79,6 +79,34 @@ MODULE_OBJS = \
 	shared/util/textstreamwriter.o \
 	shared/util/version.o \
 	shared/util/wgt2allg.o \
+	engine/ac/dynobj/cc_agsdynamicobject.o \
+	engine/ac/dynobj/cc_audiochannel.o \
+	engine/ac/dynobj/cc_audioclip.o \
+	engine/ac/dynobj/cc_character.o \
+	engine/ac/dynobj/cc_dialog.o \
+	engine/ac/dynobj/cc_dynamicarray.o \
+	engine/ac/dynobj/cc_dynamicobject.o \
+	engine/ac/dynobj/cc_gui.o \
+	engine/ac/dynobj/cc_guiobject.o \
+	engine/ac/dynobj/cc_hotspot.o \
+	engine/ac/dynobj/cc_inventory.o \
+	engine/ac/dynobj/cc_object.o \
+	engine/ac/dynobj/cc_region.o \
+	engine/ac/dynobj/cc_serializer.o \
+	engine/ac/dynobj/managedobjectpool.o \
+	engine/ac/dynobj/scriptcamera.o \
+	engine/ac/dynobj/scriptdatetime.o \
+	engine/ac/dynobj/scriptdialogoptionsrendering.o \
+	engine/ac/dynobj/scriptdict.o \
+	engine/ac/dynobj/scriptdrawingsurface.o \
+	engine/ac/dynobj/scriptdynamicsprite.o \
+	engine/ac/dynobj/scriptfile.o \
+	engine/ac/dynobj/scriptoverlay.o \
+	engine/ac/dynobj/scriptstring.o \
+	engine/ac/dynobj/scriptuserobject.o \
+	engine/ac/dynobj/scriptviewframe.o \
+	engine/ac/dynobj/scriptviewport.o \
+	engine/ac/dynobj/scriptset.o \
 	engine/debugging/consoleoutputtarget.o \
 	engine/debugging/debug.o \
 	engine/debugging/filebasedagsdebugger.o \
diff --git a/engines/ags/shared/util/string_types.h b/engines/ags/shared/util/string_types.h
index 13b4c4c5f9..0e65ce084e 100644
--- a/engines/ags/shared/util/string_types.h
+++ b/engines/ags/shared/util/string_types.h
@@ -78,6 +78,12 @@ struct IgnoreCase_Hash {
 	}
 };
 
+struct IgnoreCase_LessThan {
+	bool operator()(const AGS3::AGS::Shared::String &x, const AGS3::AGS::Shared::String &y) const {
+		return x.CompareNoCase(y) < 0;
+	}
+};
+
 } // namespace AGS3
 
 namespace Common {
@@ -101,33 +107,6 @@ namespace AGS3 {
 namespace AGS {
 namespace Shared {
 
-#if 0
-//
-// Various comparison functors
-//
-
-// Test case-insensitive String equality
-struct StrEqNoCase : public std::binary_function<String, String, bool> {
-	bool operator()(const String &s1, const String &s2) const {
-		return s1.CompareNoCase(s2) == 0;
-	}
-};
-
-// Case-insensitive String less
-struct StrLessNoCase : public std::binary_function<String, String, bool> {
-	bool operator()(const String &s1, const String &s2) const {
-		return s1.CompareNoCase(s2) < 0;
-	}
-};
-
-// Compute case-insensitive hash for a String object
-struct HashStrNoCase : public std::unary_function<String, size_t> {
-	size_t operator()(const String &key) const {
-		return FNV::Hash_LowerCase(key.GetCStr(), key.GetLength());
-	}
-};
-#endif
-
 typedef std::vector<String> StringV;
 typedef std::unordered_map<String, String> StringMap;
 typedef std::unordered_map<String, String, IgnoreCase_Hash, IgnoreCase_EqualTo> StringIMap;
diff --git a/engines/ags/std/map.h b/engines/ags/std/map.h
index 0c015ccaba..34a27bb7d1 100644
--- a/engines/ags/std/map.h
+++ b/engines/ags/std/map.h
@@ -58,6 +58,10 @@ public:
 	void insert(pair<Key, Val> elem) {
 		this->operator[](elem.first) = elem.second;
 	}
+
+	void reserve(size_t size) {
+		// No implementation
+	}
 };
 
 } // namespace std
diff --git a/engines/ags/std/set.h b/engines/ags/std/set.h
index 5df72295ce..f50a8f87e0 100644
--- a/engines/ags/std/set.h
+++ b/engines/ags/std/set.h
@@ -31,11 +31,11 @@ namespace std {
 /**
  * Derives the ScummVM SortedArray to match the std::set class
  */
-template<class T, class EqualFunc = Common::Less<T> >
+template<class T, class Comparitor = Common::Less<T> >
 class set : public Common::SortedArray<T, const T &> {
 private:
 	static int ComparatorFn(const T &a, const T &b) {
-		return EqualFunc()(a, b) ? -1 : 0;
+		return Comparitor()(a, b) ? -1 : 0;
 	}
 public:
 	using const_iterator = typename Common::SortedArray<T, const T &>::const_iterator;
diff --git a/engines/ags/std/unordered_set.h b/engines/ags/std/unordered_set.h
new file mode 100644
index 0000000000..9ef12dd3e5
--- /dev/null
+++ b/engines/ags/std/unordered_set.h
@@ -0,0 +1,46 @@
+/* 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 AGS_STD_UNORDERED_SET_H
+#define AGS_STD_UNORDERED_SET_H
+
+#include "common/array.h"
+//#include <unordered_set>
+
+namespace AGS3 {
+namespace std {
+
+template <class Key, class Hash = Common::Hash<Key>, class Pred = Common::EqualTo<Key> >
+class unordered_set {
+private:
+	Hash _hash;
+	Pred _comparitor;
+public:
+	unordered_set() {}
+
+	// TODO: Implement whatever unordered_set methods are needed
+};
+
+} // namespace std
+} // namespace AGS3
+
+#endif


Commit: 5448c998407fb2be72f12e691941bd2f74e3ceb7
    https://github.com/scummvm/scummvm/commit/5448c998407fb2be72f12e691941bd2f74e3ceb7
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added engine/ac/statobj/ folder

Changed paths:
    engines/ags/engine/ac/statobj/agsstaticobject.cpp
    engines/ags/engine/ac/statobj/staticarray.cpp
    engines/ags/module.mk


diff --git a/engines/ags/engine/ac/statobj/agsstaticobject.cpp b/engines/ags/engine/ac/statobj/agsstaticobject.cpp
index db55c0bcb3..1351b69952 100644
--- a/engines/ags/engine/ac/statobj/agsstaticobject.cpp
+++ b/engines/ags/engine/ac/statobj/agsstaticobject.cpp
@@ -21,9 +21,9 @@
  */
 
 //include <string.h>
-#include "ags/shared/ac/statobj/agsstaticobject.h"
-#include "ags/shared/ac/game.h"
-#include "ags/shared/ac/gamestate.h"
+#include "ags/engine/ac/statobj/agsstaticobject.h"
+#include "ags/engine/ac/game.h"
+#include "ags/engine/ac/gamestate.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/statobj/staticarray.cpp b/engines/ags/engine/ac/statobj/staticarray.cpp
index d2fada026d..b70c029d2e 100644
--- a/engines/ags/engine/ac/statobj/staticarray.cpp
+++ b/engines/ags/engine/ac/statobj/staticarray.cpp
@@ -21,8 +21,8 @@
  */
 
 //include <string.h>
-#include "ags/shared/ac/statobj/staticarray.h"
-#include "ags/shared/ac/dynobj/cc_dynamicobject.h"
+#include "ags/engine/ac/statobj/staticarray.h"
+#include "ags/engine/ac/dynobj/cc_dynamicobject.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 5598eb3491..b455f9916d 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -107,6 +107,8 @@ MODULE_OBJS = \
 	engine/ac/dynobj/scriptviewframe.o \
 	engine/ac/dynobj/scriptviewport.o \
 	engine/ac/dynobj/scriptset.o \
+	engine/ac/statobj/agsstaticobject.o \
+    engine/ac/statobj/staticarray.o \
 	engine/debugging/consoleoutputtarget.o \
 	engine/debugging/debug.o \
 	engine/debugging/filebasedagsdebugger.o \


Commit: fe46be92233f7835a368b9ec450e2f7deb0469f2
    https://github.com/scummvm/scummvm/commit/fe46be92233f7835a368b9ec450e2f7deb0469f2
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added engine/ac/ folder

Changed paths:
  A engines/ags/lib/aldumb.h
  A engines/ags/lib/allegro/draw.cpp
  A engines/ags/lib/allegro/draw.h
  A engines/ags/lib/allegro/fmaths.cpp
  A engines/ags/lib/allegro/fmaths.h
  A engines/ags/lib/dumb.h
  A engines/ags/std/math.h
    engines/ags/engine/ac/audiochannel.cpp
    engines/ags/engine/ac/audioclip.cpp
    engines/ags/engine/ac/character.cpp
    engines/ags/engine/ac/characterextras.cpp
    engines/ags/engine/ac/characterinfo_engine.cpp
    engines/ags/engine/ac/datetime.cpp
    engines/ags/engine/ac/dialog.cpp
    engines/ags/engine/ac/dialogoptionsrendering.cpp
    engines/ags/engine/ac/display.cpp
    engines/ags/engine/ac/draw.cpp
    engines/ags/engine/ac/draw_software.cpp
    engines/ags/engine/ac/drawingsurface.cpp
    engines/ags/engine/ac/dynamicsprite.cpp
    engines/ags/engine/ac/dynobj/scriptdict.h
    engines/ags/engine/ac/dynobj/scriptset.h
    engines/ags/engine/ac/event.cpp
    engines/ags/engine/ac/file.cpp
    engines/ags/engine/ac/game.cpp
    engines/ags/engine/ac/gamesetup.cpp
    engines/ags/engine/ac/gamestate.cpp
    engines/ags/engine/ac/global_api.cpp
    engines/ags/engine/ac/global_audio.cpp
    engines/ags/engine/ac/global_button.cpp
    engines/ags/engine/ac/global_character.cpp
    engines/ags/engine/ac/global_datetime.cpp
    engines/ags/engine/ac/global_datetime.h
    engines/ags/engine/ac/global_debug.cpp
    engines/ags/engine/ac/global_dialog.cpp
    engines/ags/engine/ac/global_display.cpp
    engines/ags/engine/ac/global_drawingsurface.cpp
    engines/ags/engine/ac/global_dynamicsprite.cpp
    engines/ags/engine/ac/global_file.cpp
    engines/ags/engine/ac/global_game.cpp
    engines/ags/engine/ac/global_gui.cpp
    engines/ags/engine/ac/global_hotspot.cpp
    engines/ags/engine/ac/global_inventoryitem.cpp
    engines/ags/engine/ac/global_invwindow.cpp
    engines/ags/engine/ac/global_label.cpp
    engines/ags/engine/ac/global_listbox.cpp
    engines/ags/engine/ac/global_mouse.cpp
    engines/ags/engine/ac/global_object.cpp
    engines/ags/engine/ac/global_overlay.cpp
    engines/ags/engine/ac/global_palette.cpp
    engines/ags/engine/ac/global_parser.cpp
    engines/ags/engine/ac/global_record.cpp
    engines/ags/engine/ac/global_region.cpp
    engines/ags/engine/ac/global_room.cpp
    engines/ags/engine/ac/global_screen.cpp
    engines/ags/engine/ac/global_slider.cpp
    engines/ags/engine/ac/global_string.cpp
    engines/ags/engine/ac/global_textbox.cpp
    engines/ags/engine/ac/global_timer.cpp
    engines/ags/engine/ac/global_translation.cpp
    engines/ags/engine/ac/global_video.cpp
    engines/ags/engine/ac/global_viewframe.cpp
    engines/ags/engine/ac/global_viewport.cpp
    engines/ags/engine/ac/global_walkablearea.cpp
    engines/ags/engine/ac/global_walkbehind.cpp
    engines/ags/engine/ac/gui.cpp
    engines/ags/engine/ac/guicontrol.cpp
    engines/ags/engine/ac/guiinv.cpp
    engines/ags/engine/ac/hotspot.cpp
    engines/ags/engine/ac/interfaceelement.cpp
    engines/ags/engine/ac/inventoryitem.cpp
    engines/ags/engine/ac/invwindow.cpp
    engines/ags/engine/ac/keycode.cpp
    engines/ags/engine/ac/label.cpp
    engines/ags/engine/ac/listbox.cpp
    engines/ags/engine/ac/math.cpp
    engines/ags/engine/ac/mouse.cpp
    engines/ags/engine/ac/movelist.cpp
    engines/ags/engine/ac/object.cpp
    engines/ags/engine/ac/overlay.cpp
    engines/ags/engine/ac/parser.cpp
    engines/ags/engine/ac/properties.cpp
    engines/ags/engine/ac/properties.h
    engines/ags/engine/ac/region.cpp
    engines/ags/engine/ac/richgamemedia.cpp
    engines/ags/engine/ac/room.cpp
    engines/ags/engine/ac/roomobject.cpp
    engines/ags/engine/ac/roomstatus.cpp
    engines/ags/engine/ac/route_finder.cpp
    engines/ags/engine/ac/route_finder_impl.cpp
    engines/ags/engine/ac/route_finder_impl_legacy.cpp
    engines/ags/engine/ac/route_finder_jps.inl
    engines/ags/engine/ac/screen.cpp
    engines/ags/engine/ac/screenoverlay.cpp
    engines/ags/engine/ac/scriptcontainers.cpp
    engines/ags/engine/ac/slider.cpp
    engines/ags/engine/ac/speech.cpp
    engines/ags/engine/ac/sprite.cpp
    engines/ags/engine/ac/string.cpp
    engines/ags/engine/ac/sys_events.cpp
    engines/ags/engine/ac/system.cpp
    engines/ags/engine/ac/textbox.cpp
    engines/ags/engine/ac/translation.cpp
    engines/ags/engine/ac/viewframe.cpp
    engines/ags/engine/ac/viewport_script.cpp
    engines/ags/engine/debugging/dummyagsdebugger.h
    engines/ags/engine/main/main.cpp
    engines/ags/engine/media/audio/audio.cpp
    engines/ags/engine/media/audio/soundcache.cpp
    engines/ags/engine/media/video/video.cpp
    engines/ags/engine/platform/linux/acpllnx.cpp
    engines/ags/engine/platform/windows/acplwin.cpp
    engines/ags/engine/platform/windows/debugging/namedpipesagsdebugger.h
    engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
    engines/ags/engine/platform/windows/win_ex_handling.cpp
    engines/ags/engine/util/library_psp.h
    engines/ags/engine/util/library_windows.h
    engines/ags/lib/allegro.h
    engines/ags/lib/allegro/file.cpp
    engines/ags/lib/allegro/file.h
    engines/ags/lib/allegro/fixed.h
    engines/ags/lib/allegro/gfx.cpp
    engines/ags/lib/allegro/gfx.h
    engines/ags/lib/allegro/keyboard.cpp
    engines/ags/lib/allegro/keyboard.h
    engines/ags/lib/allegro/system.h
    engines/ags/module.mk
    engines/ags/shared/core/types.h
    engines/ags/std/algorithm.h
    engines/ags/std/map.h
    engines/ags/std/queue.h
    engines/ags/std/set.h
    engines/ags/std/unordered_set.h
    engines/ags/std/vector.h
    engines/ags/std/xutility.h


diff --git a/engines/ags/engine/ac/audiochannel.cpp b/engines/ags/engine/ac/audiochannel.cpp
index 9773f5f2b0..31bb032c9a 100644
--- a/engines/ags/engine/ac/audiochannel.cpp
+++ b/engines/ags/engine/ac/audiochannel.cpp
@@ -29,6 +29,10 @@
 #include "ags/engine/script/runtimescriptvalue.h"
 #include "ags/engine/media/audio/audio_system.h"
 
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
+
 namespace AGS3 {
 
 using namespace AGS::Shared;
@@ -202,10 +206,6 @@ void AudioChannel_SetRoomLocation(ScriptAudioChannel *channel, int xPos, int yPo
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-
 // int | ScriptAudioChannel *channel
 RuntimeScriptValue Sc_AudioChannel_GetID(void *self, const RuntimeScriptValue *params, int32_t param_count) {
 	API_OBJCALL_INT(ScriptAudioChannel, AudioChannel_GetID);
diff --git a/engines/ags/engine/ac/audioclip.cpp b/engines/ags/engine/ac/audioclip.cpp
index 412072b346..cd40476752 100644
--- a/engines/ags/engine/ac/audioclip.cpp
+++ b/engines/ags/engine/ac/audioclip.cpp
@@ -25,6 +25,7 @@
 #include "ags/engine/ac/audiochannel.h"
 #include "ags/shared/ac/gamesetupstruct.h"
 #include "ags/engine/script/runtimescriptvalue.h"
+#include "ags/engine/script/script_runtime.h"
 #include "ags/engine/ac/dynobj/cc_audiochannel.h"
 #include "ags/engine/media/audio/audio_system.h"
 
@@ -80,9 +81,9 @@ ScriptAudioChannel *AudioClip_PlayQueued(ScriptAudioClip *clip, int priority, in
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
 
 RuntimeScriptValue Sc_AudioClip_GetID(void *self, const RuntimeScriptValue *params, int32_t param_count) {
 	API_OBJCALL_INT(ScriptAudioClip, AudioClip_GetID);
diff --git a/engines/ags/engine/ac/character.cpp b/engines/ags/engine/ac/character.cpp
index ee3ea08a58..4d0dc7434c 100644
--- a/engines/ags/engine/ac/character.cpp
+++ b/engines/ags/engine/ac/character.cpp
@@ -26,50 +26,55 @@
 //
 //=============================================================================
 
-#include "ags/shared/ac/character.h"
+#include "ags/engine/ac/character.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/gamesetupstruct.h"
 #include "ags/shared/ac/view.h"
-#include "ags/shared/ac/display.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/event.h"
-#include "ags/shared/ac/game.h"
-#include "ags/shared/ac/global_audio.h"
-#include "ags/shared/ac/global_character.h"
-#include "ags/shared/ac/global_game.h"
-#include "ags/shared/ac/global_object.h"
-#include "ags/shared/ac/global_region.h"
-#include "ags/shared/ac/global_room.h"
-#include "ags/shared/ac/global_translation.h"
-#include "ags/shared/ac/gui.h"
-#include "ags/shared/ac/lipsync.h"
-#include "ags/shared/ac/mouse.h"
-#include "ags/shared/ac/object.h"
-#include "ags/shared/ac/overlay.h"
-#include "ags/shared/ac/properties.h"
-#include "ags/shared/ac/room.h"
-#include "ags/shared/ac/screenoverlay.h"
-#include "ags/shared/ac/string.h"
-#include "ags/shared/ac/system.h"
-#include "ags/shared/ac/viewframe.h"
-#include "ags/shared/ac/walkablearea.h"
+#include "ags/engine/ac/display.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/event.h"
+#include "ags/engine/ac/game.h"
+#include "ags/engine/ac/global_audio.h"
+#include "ags/engine/ac/global_character.h"
+#include "ags/engine/ac/global_game.h"
+#include "ags/engine/ac/global_object.h"
+#include "ags/engine/ac/global_region.h"
+#include "ags/engine/ac/global_room.h"
+#include "ags/engine/ac/global_translation.h"
+#include "ags/engine/ac/gui.h"
+#include "ags/engine/ac/lipsync.h"
+#include "ags/engine/ac/mouse.h"
+#include "ags/engine/ac/object.h"
+#include "ags/engine/ac/overlay.h"
+#include "ags/engine/ac/properties.h"
+#include "ags/engine/ac/room.h"
+#include "ags/engine/ac/screenoverlay.h"
+#include "ags/engine/ac/string.h"
+#include "ags/engine/ac/system.h"
+#include "ags/engine/ac/viewframe.h"
+#include "ags/engine/ac/walkablearea.h"
 #include "ags/shared/gui/guimain.h"
-#include "ags/shared/ac/route_finder.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/main/game_run.h"
-#include "ags/shared/main/update.h"
+#include "ags/engine/ac/route_finder.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/main/game_run.h"
+#include "ags/engine/main/update.h"
 #include "ags/shared/ac/spritecache.h"
 #include "ags/shared/util/string_compat.h"
 //include <math.h>
-#include "ags/shared/gfx/graphicsdriver.h"
-#include "ags/shared/script/runtimescriptvalue.h"
-#include "ags/shared/ac/dynobj/cc_character.h"
-#include "ags/shared/ac/dynobj/cc_inventory.h"
-#include "ags/shared/script/script_runtime.h"
+#include "ags/engine/gfx/graphicsdriver.h"
+#include "ags/engine/script/runtimescriptvalue.h"
+#include "ags/engine/ac/dynobj/cc_character.h"
+#include "ags/engine/ac/dynobj/cc_inventory.h"
+#include "ags/engine/script/script_runtime.h"
 #include "ags/shared/gfx/gfx_def.h"
-#include "ags/shared/media/audio/audio_system.h"
-#include "ags/shared/ac/movelist.h"
+#include "ags/engine/media/audio/audio_system.h"
+#include "ags/engine/ac/movelist.h"
+
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
+#include "ags/engine/ac/dynobj/scriptstring.h"
 
 namespace AGS3 {
 
@@ -2236,7 +2241,7 @@ int my_getpixel(Bitmap *blk, int x, int y) {
 	// strip the alpha channel
 	// TODO: is there a way to do this vtable thing with Bitmap?
 	BITMAP *al_bmp = (BITMAP *)blk->GetAllegroBitmap();
-	return al_bmp->vtable->getpixel(al_bmp, x, y) & 0x00ffffff;
+	return al_bmp->getpixel(x, y) & 0x00ffffff;
 }
 
 int check_click_on_character(int xx, int yy, int mood) {
@@ -2848,11 +2853,6 @@ PViewport FindNearestViewport(int charid) {
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-#include "ags/shared/ac/dynobj/scriptstring.h"
-
 extern ScriptString myScriptStringImpl;
 
 // void | CharacterInfo *chaa, ScriptInvItem *invi, int addIndex
diff --git a/engines/ags/engine/ac/characterextras.cpp b/engines/ags/engine/ac/characterextras.cpp
index e0e80a0bc5..2fec603b6d 100644
--- a/engines/ags/engine/ac/characterextras.cpp
+++ b/engines/ags/engine/ac/characterextras.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/shared/ac/characterextras.h"
+#include "ags/engine/ac/characterextras.h"
 #include "ags/shared/util/stream.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/ac/characterinfo_engine.cpp b/engines/ags/engine/ac/characterinfo_engine.cpp
index 74118dce63..9264f21b38 100644
--- a/engines/ags/engine/ac/characterinfo_engine.cpp
+++ b/engines/ags/engine/ac/characterinfo_engine.cpp
@@ -23,17 +23,18 @@
 #include "ags/shared/ac/characterinfo.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/character.h"
-#include "ags/shared/ac/characterextras.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_character.h"
-#include "ags/shared/ac/math.h"
-#include "ags/shared/ac/viewframe.h"
-#include "ags/shared/debug/debug_log.h"
+#include "ags/engine/ac/character.h"
+#include "ags/engine/ac/characterextras.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_character.h"
+#include "ags/engine/ac/math.h"
+#include "ags/engine/ac/viewframe.h"
+#include "ags/engine/debugging/debug_log.h"
 #include "ags/shared/game/roomstruct.h"
-#include "ags/shared/main/maindefines_ex.h"    // RETURN_CONTINUE
-#include "ags/shared/main/update.h"
-#include "ags/shared/media/audio/audio_system.h"
+#include "ags/engine/main/maindefines_ex.h"    // RETURN_CONTINUE
+#include "ags/engine/main/update.h"
+#include "ags/engine/media/audio/audio_system.h"
+#include "ags/ags.h"
 
 namespace AGS3 {
 
@@ -470,7 +471,7 @@ void CharacterInfo::update_character_idle(CharacterExtras *chex, int &doing_noth
 			// if there arent enough loops to do the current one.
 			if ((idletime > 0) && (useloop >= maxLoops)) {
 				do {
-					useloop = rand() % maxLoops;
+					useloop = ::AGS::g_vm->getRandomNumber(maxLoops - 1);
 					// don't select a loop which is a continuation of a previous one
 				} while ((useloop > 0) && (views[idleview].loops[useloop - 1].RunNextLoop()));
 			}
diff --git a/engines/ags/engine/ac/datetime.cpp b/engines/ags/engine/ac/datetime.cpp
index c46c458995..fd07d3050a 100644
--- a/engines/ags/engine/ac/datetime.cpp
+++ b/engines/ags/engine/ac/datetime.cpp
@@ -21,9 +21,13 @@
  */
 
 //include <time.h>
-#include "ags/shared/ac/datetime.h"
-#include "ags/shared/platform/base/agsplatformdriver.h"
-#include "ags/shared/script/runtimescriptvalue.h"
+#include "ags/engine/ac/datetime.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
+#include "ags/engine/script/runtimescriptvalue.h"
+
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
 
 namespace AGS3 {
 
@@ -75,10 +79,6 @@ int DateTime_GetRawTime(ScriptDateTime *sdt) {
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-
 // ScriptDateTime* ()
 RuntimeScriptValue Sc_DateTime_Now(const RuntimeScriptValue *params, int32_t param_count) {
 	API_SCALL_OBJAUTO(ScriptDateTime, DateTime_Now);
diff --git a/engines/ags/engine/ac/dialog.cpp b/engines/ags/engine/ac/dialog.cpp
index 4f3522da9a..4ccb896ed4 100644
--- a/engines/ags/engine/ac/dialog.cpp
+++ b/engines/ags/engine/ac/dialog.cpp
@@ -20,45 +20,50 @@
  *
  */
 
-#include "ags/shared/ac/dialog.h"
+#include "ags/engine/ac/dialog.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/character.h"
+#include "ags/engine/ac/character.h"
 #include "ags/shared/ac/characterinfo.h"
 #include "ags/shared/ac/dialogtopic.h"
-#include "ags/shared/ac/display.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/gamestate.h"
+#include "ags/engine/ac/display.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/gamestate.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/global_character.h"
-#include "ags/shared/ac/global_dialog.h"
-#include "ags/shared/ac/global_display.h"
-#include "ags/shared/ac/global_game.h"
-#include "ags/shared/ac/global_gui.h"
-#include "ags/shared/ac/global_room.h"
-#include "ags/shared/ac/global_translation.h"
-#include "ags/shared/ac/keycode.h"
-#include "ags/shared/ac/overlay.h"
-#include "ags/shared/ac/mouse.h"
-#include "ags/shared/ac/parser.h"
-#include "ags/shared/ac/sys_events.h"
-#include "ags/shared/ac/string.h"
-#include "ags/shared/ac/dynobj/scriptdialogoptionsrendering.h"
-#include "ags/shared/ac/dynobj/scriptdrawingsurface.h"
-#include "ags/shared/ac/system.h"
-#include "ags/shared/debug/debug_log.h"
+#include "ags/engine/ac/global_character.h"
+#include "ags/engine/ac/global_dialog.h"
+#include "ags/engine/ac/global_display.h"
+#include "ags/engine/ac/global_game.h"
+#include "ags/engine/ac/global_gui.h"
+#include "ags/engine/ac/global_room.h"
+#include "ags/engine/ac/global_translation.h"
+#include "ags/engine/ac/keycode.h"
+#include "ags/engine/ac/overlay.h"
+#include "ags/engine/ac/mouse.h"
+#include "ags/engine/ac/parser.h"
+#include "ags/engine/ac/sys_events.h"
+#include "ags/engine/ac/string.h"
+#include "ags/engine/ac/dynobj/scriptdialogoptionsrendering.h"
+#include "ags/engine/ac/dynobj/scriptdrawingsurface.h"
+#include "ags/engine/ac/system.h"
+#include "ags/engine/debugging/debug_log.h"
 #include "ags/shared/font/fonts.h"
-#include "ags/shared/script/cc_instance.h"
+#include "ags/engine/script/cc_instance.h"
 #include "ags/shared/gui/guimain.h"
 #include "ags/shared/gui/guitextbox.h"
-#include "ags/shared/main/game_run.h"
-#include "ags/shared/platform/base/agsplatformdriver.h"
-#include "ags/shared/script/script.h"
+#include "ags/engine/main/game_run.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
+#include "ags/engine/script/script.h"
 #include "ags/shared/ac/spritecache.h"
-#include "ags/shared/gfx/ddb.h"
-#include "ags/shared/gfx/gfx_util.h"
-#include "ags/shared/gfx/graphicsdriver.h"
-#include "ags/shared/ac/mouse.h"
-#include "ags/shared/media/audio/audio_system.h"
+#include "ags/engine/gfx/ddb.h"
+#include "ags/engine/gfx/gfx_util.h"
+#include "ags/engine/gfx/graphicsdriver.h"
+#include "ags/engine/ac/mouse.h"
+#include "ags/engine/media/audio/audio_system.h"
+
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
+#include "ags/engine/ac/dynobj/scriptstring.h"
 
 namespace AGS3 {
 
@@ -582,16 +587,16 @@ void DialogOptions::Show() {
 		}
 	} else {
 		//dlgyp=(play.viewport.GetHeight()-numdisp*txthit)-1;
-		const Rect &ui_view = play.GetUIViewport();
-		areawid = ui_view.GetWidth() - 5;
+		const Rect &uiView = play.GetUIViewport();
+		areawid = uiView.GetWidth() - 5;
 		padding = TEXTWINDOW_PADDING_DEFAULT;
 		GET_OPTIONS_HEIGHT
-		dlgyp = ui_view.GetHeight() - needheight;
+		dlgyp = uiView.GetHeight() - needheight;
 
 		dirtyx = 0;
 		dirtyy = dlgyp - 1;
-		dirtywidth = ui_view.GetWidth();
-		dirtyheight = ui_view.GetHeight() - dirtyy;
+		dirtywidth = uiView.GetWidth();
+		dirtyheight = uiView.GetHeight() - dirtyy;
 		dialog_abs_x = 0;
 	}
 	if (!is_textwindow)
@@ -1148,11 +1153,6 @@ void do_conversation(int dlgnum) {
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-#include "ags/shared/ac/dynobj/scriptstring.h"
-
 extern ScriptString myScriptStringImpl;
 
 // int (ScriptDialog *sd)
diff --git a/engines/ags/engine/ac/dialogoptionsrendering.cpp b/engines/ags/engine/ac/dialogoptionsrendering.cpp
index f7bf6a5453..059d6aa07e 100644
--- a/engines/ags/engine/ac/dialogoptionsrendering.cpp
+++ b/engines/ags/engine/ac/dialogoptionsrendering.cpp
@@ -20,13 +20,14 @@
  *
  */
 
-#include "ags/shared/ac/dialog.h"
+#include "ags/engine/ac/dialog.h"
 #include "ags/shared/ac/dialogtopic.h"
-#include "ags/shared/ac/dialogoptionsrendering.h"
+#include "ags/engine/ac/dialogoptionsrendering.h"
 #include "ags/shared/ac/gamestructdefines.h"
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/script/runtimescriptvalue.h"
-#include "ags/shared/ac/dynobj/cc_dialog.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/script/runtimescriptvalue.h"
+#include "ags/engine/script/script_runtime.h"
+#include "ags/engine/ac/dynobj/cc_dialog.h"
 
 namespace AGS3 {
 
@@ -138,9 +139,9 @@ void DialogOptionsRendering_SetActiveOptionID(ScriptDialogOptionsRendering *dlgO
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
 
 RuntimeScriptValue Sc_DialogOptionsRendering_Update(void *self, const RuntimeScriptValue *params, int32_t param_count) {
 	API_OBJCALL_VOID(ScriptDialogOptionsRendering, DialogOptionsRendering_Update);
diff --git a/engines/ags/engine/ac/display.cpp b/engines/ags/engine/ac/display.cpp
index cfbc137cdf..7f4574138a 100644
--- a/engines/ags/engine/ac/display.cpp
+++ b/engines/ags/engine/ac/display.cpp
@@ -22,38 +22,38 @@
 
 //include <math.h>
 
-#include "ags/shared/ac/display.h"
+#include "ags/engine/ac/display.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/font/agsfontrenderer.h"
 #include "ags/shared/font/fonts.h"
-#include "ags/shared/ac/character.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/game.h"
+#include "ags/engine/ac/character.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/game.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_audio.h"
-#include "ags/shared/ac/global_game.h"
-#include "ags/shared/ac/gui.h"
-#include "ags/shared/ac/mouse.h"
-#include "ags/shared/ac/overlay.h"
-#include "ags/shared/ac/sys_events.h"
-#include "ags/shared/ac/screenoverlay.h"
-#include "ags/shared/ac/speech.h"
-#include "ags/shared/ac/string.h"
-#include "ags/shared/ac/system.h"
-#include "ags/shared/ac/topbarsettings.h"
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/gfx/blender.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_audio.h"
+#include "ags/engine/ac/global_game.h"
+#include "ags/engine/ac/gui.h"
+#include "ags/engine/ac/mouse.h"
+#include "ags/engine/ac/overlay.h"
+#include "ags/engine/ac/sys_events.h"
+#include "ags/engine/ac/screenoverlay.h"
+#include "ags/engine/ac/speech.h"
+#include "ags/engine/ac/string.h"
+#include "ags/engine/ac/system.h"
+#include "ags/engine/ac/topbarsettings.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/gfx/blender.h"
 #include "ags/shared/gui/guibutton.h"
 #include "ags/shared/gui/guimain.h"
-#include "ags/shared/main/game_run.h"
-#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/engine/main/game_run.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
 #include "ags/shared/ac/spritecache.h"
-#include "ags/shared/gfx/gfx_util.h"
+#include "ags/engine/gfx/gfx_util.h"
 #include "ags/shared/util/string_utils.h"
-#include "ags/shared/ac/mouse.h"
-#include "ags/shared/media/audio/audio_system.h"
-#include "ags/shared/ac/timer.h"
+#include "ags/engine/ac/mouse.h"
+#include "ags/engine/media/audio/audio_system.h"
+#include "ags/engine/ac/timer.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/draw.cpp b/engines/ags/engine/ac/draw.cpp
index 7ac126608e..6e451c414d 100644
--- a/engines/ags/engine/ac/draw.cpp
+++ b/engines/ags/engine/ac/draw.cpp
@@ -20,56 +20,56 @@
  *
  */
 
-//include <algorithm>
-//include <cmath>
-#include "ags/shared/aastr.h"
+#include "ags/std/algorithm.h"
+#include "ags/std/math.h"
+#include "ags/lib/aastr-0.1.1/aastr.h"
 #include "ags/shared/core/platform.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/util/compress.h"
 #include "ags/shared/ac/view.h"
-#include "ags/shared/ac/charactercache.h"
-#include "ags/shared/ac/characterextras.h"
+#include "ags/engine/ac/charactercache.h"
+#include "ags/engine/ac/characterextras.h"
 #include "ags/shared/ac/characterinfo.h"
-#include "ags/shared/ac/display.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/draw_software.h"
-#include "ags/shared/ac/gamesetup.h"
+#include "ags/engine/ac/display.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/draw_software.h"
+#include "ags/engine/ac/gamesetup.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_game.h"
-#include "ags/shared/ac/global_gui.h"
-#include "ags/shared/ac/global_region.h"
-#include "ags/shared/ac/gui.h"
-#include "ags/shared/ac/mouse.h"
-#include "ags/shared/ac/objectcache.h"
-#include "ags/shared/ac/overlay.h"
-#include "ags/shared/ac/sys_events.h"
-#include "ags/shared/ac/roomobject.h"
-#include "ags/shared/ac/roomstatus.h"
-#include "ags/shared/ac/runtime_defines.h"
-#include "ags/shared/ac/screenoverlay.h"
-#include "ags/shared/ac/sprite.h"
-#include "ags/shared/ac/spritelistentry.h"
-#include "ags/shared/ac/string.h"
-#include "ags/shared/ac/system.h"
-#include "ags/shared/ac/viewframe.h"
-#include "ags/shared/ac/walkablearea.h"
-#include "ags/shared/ac/walkbehind.h"
-#include "ags/shared/ac/dynobj/scriptsystem.h"
-#include "ags/shared/debug/debugger.h"
-#include "ags/shared/debug/debug_log.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_game.h"
+#include "ags/engine/ac/global_gui.h"
+#include "ags/engine/ac/global_region.h"
+#include "ags/engine/ac/gui.h"
+#include "ags/engine/ac/mouse.h"
+#include "ags/engine/ac/objectcache.h"
+#include "ags/engine/ac/overlay.h"
+#include "ags/engine/ac/sys_events.h"
+#include "ags/engine/ac/roomobject.h"
+#include "ags/engine/ac/roomstatus.h"
+#include "ags/engine/ac/runtime_defines.h"
+#include "ags/engine/ac/screenoverlay.h"
+#include "ags/engine/ac/sprite.h"
+#include "ags/engine/ac/spritelistentry.h"
+#include "ags/engine/ac/string.h"
+#include "ags/engine/ac/system.h"
+#include "ags/engine/ac/viewframe.h"
+#include "ags/engine/ac/walkablearea.h"
+#include "ags/engine/ac/walkbehind.h"
+#include "ags/engine/ac/dynobj/scriptsystem.h"
+#include "ags/engine/debugging/debugger.h"
+#include "ags/engine/debugging/debug_log.h"
 #include "ags/shared/font/fonts.h"
 #include "ags/shared/gui/guimain.h"
-#include "ags/shared/platform/base/agsplatformdriver.h"
-#include "ags/shared/plugin/agsplugin.h"
-#include "ags/shared/plugin/plugin_engine.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
+#include "ags/engine/plugin/agsplugin.h"
+#include "ags/engine/plugin/plugin_engine.h"
 #include "ags/shared/ac/spritecache.h"
-#include "ags/shared/gfx/gfx_util.h"
-#include "ags/shared/gfx/graphicsdriver.h"
-#include "ags/shared/gfx/ali3dexception.h"
-#include "ags/shared/gfx/blender.h"
-#include "ags/shared/media/audio/audio_system.h"
-#include "ags/shared/ac/game.h"
+#include "ags/engine/gfx/gfx_util.h"
+#include "ags/engine/gfx/graphicsdriver.h"
+#include "ags/engine/gfx/ali3dexception.h"
+#include "ags/engine/gfx/blender.h"
+#include "ags/engine/media/audio/audio_system.h"
+#include "ags/engine/ac/game.h"
 
 namespace AGS3 {
 
@@ -447,16 +447,16 @@ AGS_INLINE void defgame_to_finalgame_coords(int &x, int &y) {
 void create_blank_image(int coldepth) {
 	// this is the first time that we try to use the graphics driver,
 	// so it's the most likey place for a crash
-	try {
+//	try {
 		Bitmap *blank = BitmapHelper::CreateBitmap(16, 16, coldepth);
 		blank = ReplaceBitmapWithSupportedFormat(blank);
 		blank->Clear();
 		blankImage = gfxDriver->CreateDDBFromBitmap(blank, false, true);
 		blankSidebarImage = gfxDriver->CreateDDBFromBitmap(blank, false, true);
 		delete blank;
-	} catch (Ali3DException gfxException) {
+/*	} catch (Ali3DException gfxException) {
 		quit((char *)gfxException._message);
-	}
+	}*/
 }
 
 void destroy_blank_image() {
@@ -703,7 +703,7 @@ void render_to_screen() {
 
 	bool succeeded = false;
 	while (!succeeded) {
-		try {
+//		try {
 			// For software renderer, need to blacken upper part of the game frame when shaking screen moves image down
 			const Rect &viewport = play.GetMainViewport();
 			if (play.shake_screen_yoff > 0 && !gfxDriver->RequiresFullRedrawEachFrame())
@@ -719,9 +719,9 @@ void render_to_screen() {
 #endif
 
 			succeeded = true;
-		} catch (Ali3DFullscreenLostException) {
+/*		} catch (Ali3DFullscreenLostException) {
 			platform->Delay(500);
-		}
+		}*/
 	}
 }
 
@@ -1255,15 +1255,15 @@ int scale_and_flip_sprite(int useindx, int coldept, int zoom_level,
 			Bitmap *tempspr = BitmapHelper::CreateBitmap(newwidth, newheight, coldept);
 			tempspr->Fill(actsps[useindx]->GetMaskColor());
 			if ((IS_ANTIALIAS_SPRITES) && ((game.SpriteInfos[sppic].Flags & SPF_ALPHACHANNEL) == 0))
-				tempspr->AAStretchBlt(spriteset[sppic], RectWH(0, 0, newwidth, newheight), Common::kBitmap_Transparency);
+				tempspr->AAStretchBlt(spriteset[sppic], RectWH(0, 0, newwidth, newheight), Shared::kBitmap_Transparency);
 			else
-				tempspr->StretchBlt(spriteset[sppic], RectWH(0, 0, newwidth, newheight), Common::kBitmap_Transparency);
-			active_spr->FlipBlt(tempspr, 0, 0, Common::kBitmap_HFlip);
+				tempspr->StretchBlt(spriteset[sppic], RectWH(0, 0, newwidth, newheight), Shared::kBitmap_Transparency);
+			active_spr->FlipBlt(tempspr, 0, 0, Shared::kBitmap_HFlip);
 			delete tempspr;
 		} else if ((IS_ANTIALIAS_SPRITES) && ((game.SpriteInfos[sppic].Flags & SPF_ALPHACHANNEL) == 0))
-			active_spr->AAStretchBlt(spriteset[sppic], RectWH(0, 0, newwidth, newheight), Common::kBitmap_Transparency);
+			active_spr->AAStretchBlt(spriteset[sppic], RectWH(0, 0, newwidth, newheight), Shared::kBitmap_Transparency);
 		else
-			active_spr->StretchBlt(spriteset[sppic], RectWH(0, 0, newwidth, newheight), Common::kBitmap_Transparency);
+			active_spr->StretchBlt(spriteset[sppic], RectWH(0, 0, newwidth, newheight), Shared::kBitmap_Transparency);
 
 		/*  AASTR2 version of code (doesn't work properly, gives black borders)
 		if (IS_ANTIALIAS_SPRITES) {
@@ -1280,7 +1280,7 @@ int scale_and_flip_sprite(int useindx, int coldept, int zoom_level,
 		Bitmap *tempspr = BitmapHelper::CreateBitmap_ (coldept, newwidth, newheight);
 		->Clear (tempspr, ->GetMaskColor(actsps[useindx]));
 		->StretchBlt (tempspr, spriteset[sppic], 0, 0, newwidth, newheight);
-		->FlipBlt(Common::kBitmap_HFlip, (actsps[useindx], tempspr, 0, 0);
+		->FlipBlt(Shared::kBitmap_HFlip, (actsps[useindx], tempspr, 0, 0);
 		wfreeblock (tempspr);
 		}
 		else
@@ -1295,7 +1295,7 @@ int scale_and_flip_sprite(int useindx, int coldept, int zoom_level,
 		our_eip = 339;
 
 		if (isMirrored)
-			active_spr->FlipBlt(spriteset[sppic], 0, 0, Common::kBitmap_HFlip);
+			active_spr->FlipBlt(spriteset[sppic], 0, 0, Shared::kBitmap_HFlip);
 		else
 			actsps_used = 0;
 		//->Blit (spriteset[sppic], actsps[useindx], 0, 0, 0, 0, actsps[useindx]->GetWidth(), actsps[useindx]->GetHeight());
diff --git a/engines/ags/engine/ac/draw_software.cpp b/engines/ags/engine/ac/draw_software.cpp
index ab4412a427..999d9b4a7b 100644
--- a/engines/ags/engine/ac/draw_software.cpp
+++ b/engines/ags/engine/ac/draw_software.cpp
@@ -46,11 +46,11 @@
 //
 //=============================================================================
 
-//include <string.h>
+#include "ags/std/utility.h"
 #include "ags/std/vector.h"
-#include "ags/shared/ac/draw_software.h"
+#include "ags/engine/ac/draw_software.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/util/scaling.h"
+#include "ags/engine/util/scaling.h"
 
 namespace AGS3 {
 
@@ -288,7 +288,7 @@ void invalidate_rect_on_surf(int x1, int y1, int x2, int y2, DirtyRects &rects)
 			dirtyRow[a].numSpans++;
 		} else {
 			// didn't fit in an existing span, and there are none spare
-			int nearestDist = 99999, nearestWas = -1, extendLeft;
+			int nearestDist = 99999, nearestWas = -1, extendLeft = 0;
 			int tleft, tright;
 			// find the nearest span, and enlarge that to include this rect
 			for (s = 0; s < dirtyRow[a].numSpans; s++) {
diff --git a/engines/ags/engine/ac/drawingsurface.cpp b/engines/ags/engine/ac/drawingsurface.cpp
index a0a6f494f5..13b86da26a 100644
--- a/engines/ags/engine/ac/drawingsurface.cpp
+++ b/engines/ags/engine/ac/drawingsurface.cpp
@@ -20,27 +20,32 @@
  *
  */
 
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/drawingsurface.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/drawingsurface.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/charactercache.h"
-#include "ags/shared/ac/display.h"
-#include "ags/shared/ac/game.h"
+#include "ags/engine/ac/charactercache.h"
+#include "ags/engine/ac/display.h"
+#include "ags/engine/ac/game.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_translation.h"
-#include "ags/shared/ac/objectcache.h"
-#include "ags/shared/ac/roomobject.h"
-#include "ags/shared/ac/roomstatus.h"
-#include "ags/shared/ac/string.h"
-#include "ags/shared/ac/walkbehind.h"
-#include "ags/shared/debug/debug_log.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_translation.h"
+#include "ags/engine/ac/objectcache.h"
+#include "ags/engine/ac/roomobject.h"
+#include "ags/engine/ac/roomstatus.h"
+#include "ags/engine/ac/runtime_defines.h"
+#include "ags/engine/ac/string.h"
+#include "ags/engine/ac/walkbehind.h"
+#include "ags/engine/debugging/debug_log.h"
 #include "ags/shared/font/fonts.h"
 #include "ags/shared/gui/guimain.h"
 #include "ags/shared/ac/spritecache.h"
-#include "ags/shared/script/runtimescriptvalue.h"
+#include "ags/engine/script/runtimescriptvalue.h"
 #include "ags/shared/gfx/gfx_def.h"
-#include "ags/shared/gfx/gfx_util.h"
+#include "ags/engine/gfx/gfx_util.h"
+
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
 
 namespace AGS3 {
 
@@ -427,13 +432,13 @@ int DrawingSurface_GetPixel(ScriptDrawingSurface *sds, int x, int y) {
 	int colDepth = ds->GetColorDepth();
 
 	if (rawPixel == maskColor) {
-		rawPixel = SCR_COLOR_TRANSPARENT;
+		rawPixel = (unsigned int)SCR_COLOR_TRANSPARENT;
 	} else if (colDepth > 8) {
 		int r = getr_depth(colDepth, rawPixel);
-		int ds = getg_depth(colDepth, rawPixel);
+		int g = getg_depth(colDepth, rawPixel);
 		int b = getb_depth(colDepth, rawPixel);
 
-		rawPixel = Game_GetColorFromRGB(r, ds, b);
+		rawPixel = Game_GetColorFromRGB(r, g, b);
 	}
 
 	sds->FinishedDrawingReadOnly();
@@ -447,10 +452,6 @@ int DrawingSurface_GetPixel(ScriptDrawingSurface *sds, int x, int y) {
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-
 // void (ScriptDrawingSurface *sds, int colour)
 RuntimeScriptValue Sc_DrawingSurface_Clear(void *self, const RuntimeScriptValue *params, int32_t param_count) {
 	API_OBJCALL_VOID_PINT(ScriptDrawingSurface, DrawingSurface_Clear);
diff --git a/engines/ags/engine/ac/dynamicsprite.cpp b/engines/ags/engine/ac/dynamicsprite.cpp
index d5c635592d..2d78b61869 100644
--- a/engines/ags/engine/ac/dynamicsprite.cpp
+++ b/engines/ags/engine/ac/dynamicsprite.cpp
@@ -21,25 +21,29 @@
  */
 
 //include <math.h>
-#include "ags/shared/ac/dynamicsprite.h"
+#include "ags/engine/ac/dynamicsprite.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/charactercache.h"
-#include "ags/shared/ac/draw.h"
+#include "ags/engine/ac/charactercache.h"
+#include "ags/engine/ac/draw.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/global_dynamicsprite.h"
-#include "ags/shared/ac/global_game.h"
-#include "ags/shared/ac/math.h"    // M_PI
-#include "ags/shared/ac/objectcache.h"
-#include "ags/shared/ac/path_helper.h"
-#include "ags/shared/ac/roomobject.h"
-#include "ags/shared/ac/roomstatus.h"
-#include "ags/shared/ac/system.h"
-#include "ags/shared/debug/debug_log.h"
+#include "ags/engine/ac/global_dynamicsprite.h"
+#include "ags/engine/ac/global_game.h"
+#include "ags/engine/ac/math.h"    // M_PI
+#include "ags/engine/ac/objectcache.h"
+#include "ags/engine/ac/path_helper.h"
+#include "ags/engine/ac/roomobject.h"
+#include "ags/engine/ac/roomstatus.h"
+#include "ags/engine/ac/system.h"
+#include "ags/engine/debugging/debug_log.h"
 #include "ags/shared/game/roomstruct.h"
 #include "ags/shared/gui/guibutton.h"
 #include "ags/shared/ac/spritecache.h"
-#include "ags/shared/gfx/graphicsdriver.h"
-#include "ags/shared/script/runtimescriptvalue.h"
+#include "ags/engine/gfx/graphicsdriver.h"
+#include "ags/engine/script/runtimescriptvalue.h"
+
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
 
 namespace AGS3 {
 
@@ -135,11 +139,11 @@ void DynamicSprite_Flip(ScriptDynamicSprite *sds, int direction) {
 	Bitmap *newPic = BitmapHelper::CreateTransparentBitmap(game.SpriteInfos[sds->slot].Width, game.SpriteInfos[sds->slot].Height, spriteset[sds->slot]->GetColorDepth());
 
 	if (direction == 1)
-		newPic->FlipBlt(spriteset[sds->slot], 0, 0, Common::kBitmap_HFlip);
+		newPic->FlipBlt(spriteset[sds->slot], 0, 0, Shared::kBitmap_HFlip);
 	else if (direction == 2)
-		newPic->FlipBlt(spriteset[sds->slot], 0, 0, Common::kBitmap_VFlip);
+		newPic->FlipBlt(spriteset[sds->slot], 0, 0, Shared::kBitmap_VFlip);
 	else if (direction == 3)
-		newPic->FlipBlt(spriteset[sds->slot], 0, 0, Common::kBitmap_HVFlip);
+		newPic->FlipBlt(spriteset[sds->slot], 0, 0, Shared::kBitmap_HVFlip);
 
 	delete spriteset[sds->slot];
 
@@ -504,10 +508,6 @@ void free_dynamic_sprite(int gotSlot) {
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-
 // void (ScriptDynamicSprite *sds, int width, int height, int x, int y)
 RuntimeScriptValue Sc_DynamicSprite_ChangeCanvasSize(void *self, const RuntimeScriptValue *params, int32_t param_count) {
 	API_OBJCALL_VOID_PINT4(ScriptDynamicSprite, DynamicSprite_ChangeCanvasSize);
diff --git a/engines/ags/engine/ac/dynobj/scriptdict.h b/engines/ags/engine/ac/dynobj/scriptdict.h
index 08740845c6..e560fccf9e 100644
--- a/engines/ags/engine/ac/dynobj/scriptdict.h
+++ b/engines/ags/engine/ac/dynobj/scriptdict.h
@@ -91,12 +91,16 @@ public:
 		_dic.clear();
 	}
 	bool Contains(const char *key) override {
+#ifdef AGS_PLATFORM_SCUMMVM
+		return _dic.find(String::Wrapper(key)) != _dic.end();
+#else
 		return _dic.count(String::Wrapper(key)) != 0;
+#endif
 	}
 	const char *Get(const char *key) override {
 		auto it = _dic.find(String::Wrapper(key));
 		if (it == _dic.end()) return nullptr;
-		return it->second.GetNullableCStr();
+		return it->_value.GetNullableCStr();
 	}
 	bool Remove(const char *key) override {
 		auto it = _dic.find(String::Wrapper(key));
@@ -116,11 +120,11 @@ public:
 	}
 	void GetKeys(std::vector<const char *> &buf) const override {
 		for (auto it = _dic.begin(); it != _dic.end(); ++it)
-			buf.push_back(it->first.GetCStr()); // keys cannot be null
+			buf.push_back(it->_key.GetCStr()); // keys cannot be null
 	}
 	void GetValues(std::vector<const char *> &buf) const override {
 		for (auto it = _dic.begin(); it != _dic.end(); ++it)
-			buf.push_back(it->second.GetNullableCStr()); // values may be null
+			buf.push_back(it->_value.GetNullableCStr()); // values may be null
 	}
 
 private:
@@ -139,8 +143,8 @@ private:
 	size_t CalcSerializeSize() override {
 		size_t total_sz = sizeof(int32_t);
 		for (auto it = _dic.begin(); it != _dic.end(); ++it) {
-			total_sz += sizeof(int32_t) + it->first.GetLength();
-			total_sz += sizeof(int32_t) + it->second.GetLength();
+			total_sz += sizeof(int32_t) + it->_key.GetLength();
+			total_sz += sizeof(int32_t) + it->_value.GetLength();
 		}
 		return total_sz;
 	}
@@ -148,13 +152,13 @@ private:
 	void SerializeContainer() override {
 		SerializeInt((int)_dic.size());
 		for (auto it = _dic.begin(); it != _dic.end(); ++it) {
-			SerializeInt((int)it->first.GetLength());
-			memcpy(&serbuffer[bytesSoFar], it->first.GetCStr(), it->first.GetLength());
-			bytesSoFar += it->first.GetLength();
-			if (it->second.GetNullableCStr()) { // values may be null
-				SerializeInt((int)it->second.GetLength());
-				memcpy(&serbuffer[bytesSoFar], it->second.GetCStr(), it->second.GetLength());
-				bytesSoFar += it->second.GetLength();
+			SerializeInt((int)it->_key.GetLength());
+			memcpy(&serbuffer[bytesSoFar], it->_key.GetCStr(), it->_key.GetLength());
+			bytesSoFar += it->_key.GetLength();
+			if (it->_value.GetNullableCStr()) { // values may be null
+				SerializeInt((int)it->_value.GetLength());
+				memcpy(&serbuffer[bytesSoFar], it->_value.GetCStr(), it->_value.GetLength());
+				bytesSoFar += it->_value.GetLength();
 			} else {
 				SerializeInt(-1);
 			}
@@ -182,7 +186,8 @@ private:
 };
 
 typedef ScriptDictImpl< std::map<String, String>, true, true > ScriptDict;
-typedef ScriptDictImpl< std::map<String, String, IgnoreCase_LessThan>, true, false > ScriptDictCI;
+// TODO: Not sure if current std::map implement works for LessThan to give a key ordering
+typedef ScriptDictImpl< std::map<String, String, IgnoreCase_Hash, IgnoreCase_LessThan>, true, false > ScriptDictCI;
 typedef ScriptDictImpl< std::unordered_map<String, String>, false, true > ScriptHashDict;
 typedef ScriptDictImpl< std::unordered_map<String, String, IgnoreCase_Hash, IgnoreCase_EqualTo>, false, false > ScriptHashDictCI;
 
diff --git a/engines/ags/engine/ac/dynobj/scriptset.h b/engines/ags/engine/ac/dynobj/scriptset.h
index e6ca5068f7..10a00757ac 100644
--- a/engines/ags/engine/ac/dynobj/scriptset.h
+++ b/engines/ags/engine/ac/dynobj/scriptset.h
@@ -113,7 +113,7 @@ public:
 
 private:
 	bool TryAddItem(const char *item, size_t len) {
-		return _set.insert(String(item, len)).second;
+		return _set.insert(String(item, len))._value;
 	}
 	void DeleteItem(ConstIterator it) {
 		/* do nothing */
diff --git a/engines/ags/engine/ac/event.cpp b/engines/ags/engine/ac/event.cpp
index cf8d118ab9..bb7d9b23aa 100644
--- a/engines/ags/engine/ac/event.cpp
+++ b/engines/ags/engine/ac/event.cpp
@@ -20,27 +20,27 @@
  *
  */
 
-#include "ags/shared/event.h"
+#include "ags/engine/ac/event.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/draw.h"
+#include "ags/engine/ac/draw.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_game.h"
-#include "ags/shared/ac/global_room.h"
-#include "ags/shared/ac/global_screen.h"
-#include "ags/shared/ac/gui.h"
-#include "ags/shared/ac/roomstatus.h"
-#include "ags/shared/ac/screen.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_game.h"
+#include "ags/engine/ac/global_room.h"
+#include "ags/engine/ac/global_screen.h"
+#include "ags/engine/ac/gui.h"
+#include "ags/engine/ac/roomstatus.h"
+#include "ags/engine/ac/screen.h"
 #include "ags/shared/script/cc_error.h"
-#include "ags/shared/platform/base/agsplatformdriver.h"
-#include "ags/shared/plugin/agsplugin.h"
-#include "ags/shared/plugin/plugin_engine.h"
-#include "ags/shared/script/script.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
+#include "ags/engine/plugin/agsplugin.h"
+#include "ags/engine/plugin/plugin_engine.h"
+#include "ags/engine/script/script.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/gfx/ddb.h"
-#include "ags/shared/gfx/graphicsdriver.h"
-#include "ags/shared/media/audio/audio_system.h"
-#include "ags/shared/ac/timer.h"
+#include "ags/engine/gfx/ddb.h"
+#include "ags/engine/gfx/graphicsdriver.h"
+#include "ags/engine/media/audio/audio_system.h"
+#include "ags/engine/ac/timer.h"
 
 namespace AGS3 {
 
@@ -121,12 +121,12 @@ void run_room_event(int id) {
 	}
 }
 
-void run_event_block_inv(int invNum, int event) {
+void run_event_block_inv(int invNum, int event_) {
 	evblockbasename = "inventory%d";
 	if (loaded_game_file_version > kGameVersion_272) {
-		run_interaction_script(game.invScripts[invNum].get(), event);
+		run_interaction_script(game.invScripts[invNum].get(), event_);
 	} else {
-		run_interaction_event(game.intrInv[invNum].get(), event);
+		run_interaction_event(game.intrInv[invNum].get(), event_);
 	}
 
 }
@@ -238,7 +238,7 @@ void process_event(EventHappened *evp) {
 		}
 
 		// TODO: use normal coordinates instead of "native_size" and multiply_up_*?
-		const Size &data_res = game.GetDataRes();
+		//const Size &data_res = game.GetDataRes();
 		const Rect &viewport = play.GetMainViewport();
 
 		if ((theTransition == FADE_INSTANT) || ignore_transition)
diff --git a/engines/ags/engine/ac/file.cpp b/engines/ags/engine/ac/file.cpp
index 6a6a30b0a8..cfee54d31c 100644
--- a/engines/ags/engine/ac/file.cpp
+++ b/engines/ags/engine/ac/file.cpp
@@ -20,32 +20,37 @@
  *
  */
 
-#include "ags/shared/aldumb.h"
-#include "ags/shared/ac/asset_helper.h"
+#include "ags/lib/aldumb.h"
+#include "ags/engine/ac/asset_helper.h"
 #include "ags/shared/ac/audiocliptype.h"
-#include "ags/shared/ac/file.h"
+#include "ags/engine/ac/file.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/game.h"
-#include "ags/shared/ac/gamesetup.h"
+#include "ags/engine/ac/game.h"
+#include "ags/engine/ac/gamesetup.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/global_file.h"
-#include "ags/shared/ac/path_helper.h"
-#include "ags/shared/ac/runtime_defines.h"
-#include "ags/shared/ac/string.h"
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/debug/debugger.h"
+#include "ags/engine/ac/global_file.h"
+#include "ags/engine/ac/path_helper.h"
+#include "ags/engine/ac/runtime_defines.h"
+#include "ags/engine/ac/string.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/debugging/debugger.h"
 #include "ags/shared/util/misc.h"
-#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
 #include "ags/shared/util/stream.h"
 #include "ags/shared/core/assetmanager.h"
 #include "ags/shared/core/asset.h"
-#include "ags/shared/main/engine.h"
-#include "ags/shared/main/game_file.h"
+#include "ags/engine/main/engine.h"
+#include "ags/engine/main/game_file.h"
 #include "ags/shared/util/directory.h"
 #include "ags/shared/util/path.h"
 #include "ags/shared/util/string.h"
 #include "ags/shared/util/string_utils.h"
 
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
+#include "ags/engine/ac/dynobj/scriptstring.h"
+
 namespace AGS3 {
 
 using namespace AGS::Shared;
@@ -85,7 +90,7 @@ int File_Delete(const char *fnmm) {
 
 	if (::remove(rp.FullPath) == 0)
 		return 1;
-	if (errno == ENOENT && !rp.AltPath.IsEmpty() && rp.AltPath.Compare(rp.FullPath) != 0)
+	if (errnum == ENOENT && !rp.AltPath.IsEmpty() && rp.AltPath.Compare(rp.FullPath) != 0)
 		return ::remove(rp.AltPath) == 0 ? 1 : 0;
 	return 0;
 }
@@ -535,7 +540,7 @@ String get_known_assetlib(const String &filename) {
 }
 
 Stream *find_open_asset(const String &filename) {
-	Stream *asset_s = Common::AssetManager::OpenAsset(filename);
+	Stream *asset_s = Shared::AssetManager::OpenAsset(filename);
 	if (!asset_s && Path::ComparePaths(ResPaths.DataDir, installDirectory) != 0) {
 		// Just in case they're running in Debug, try standalone file in compiled folder
 		asset_s = ci_fopen(String::FromFormat("%s/%s", installDirectory.GetCStr(), filename.GetCStr()));
@@ -613,11 +618,6 @@ Stream *get_valid_file_stream_from_handle(int32_t handle, const char *operation_
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-#include "ags/shared/ac/dynobj/scriptstring.h"
-
 extern ScriptString myScriptStringImpl;
 
 // int (const char *fnmm)
diff --git a/engines/ags/engine/ac/game.cpp b/engines/ags/engine/ac/game.cpp
index 928974a26e..4b988ef1c3 100644
--- a/engines/ags/engine/ac/game.cpp
+++ b/engines/ags/engine/ac/game.cpp
@@ -20,83 +20,88 @@
  *
  */
 
-#include "ags/shared/ac/game.h"
+#include "ags/engine/ac/game.h"
 
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/view.h"
 #include "ags/shared/ac/audiocliptype.h"
-#include "ags/shared/ac/audiochannel.h"
-#include "ags/shared/ac/character.h"
-#include "ags/shared/ac/charactercache.h"
-#include "ags/shared/ac/characterextras.h"
+#include "ags/engine/ac/audiochannel.h"
+#include "ags/engine/ac/character.h"
+#include "ags/engine/ac/charactercache.h"
+#include "ags/engine/ac/characterextras.h"
 #include "ags/shared/ac/dialogtopic.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/dynamicsprite.h"
-#include "ags/shared/ac/event.h"
-#include "ags/shared/ac/gamesetup.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/dynamicsprite.h"
+#include "ags/engine/ac/event.h"
+#include "ags/engine/ac/gamesetup.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_audio.h"
-#include "ags/shared/ac/global_character.h"
-#include "ags/shared/ac/global_display.h"
-#include "ags/shared/ac/global_game.h"
-#include "ags/shared/ac/global_gui.h"
-#include "ags/shared/ac/global_object.h"
-#include "ags/shared/ac/global_translation.h"
-#include "ags/shared/ac/gui.h"
-#include "ags/shared/ac/hotspot.h"
-#include "ags/shared/ac/lipsync.h"
-#include "ags/shared/ac/mouse.h"
-#include "ags/shared/ac/movelist.h"
-#include "ags/shared/ac/objectcache.h"
-#include "ags/shared/ac/overlay.h"
-#include "ags/shared/ac/path_helper.h"
-#include "ags/shared/ac/sys_events.h"
-#include "ags/shared/ac/region.h"
-#include "ags/shared/ac/richgamemedia.h"
-#include "ags/shared/ac/room.h"
-#include "ags/shared/ac/roomobject.h"
-#include "ags/shared/ac/roomstatus.h"
-#include "ags/shared/ac/runtime_defines.h"
-#include "ags/shared/ac/screenoverlay.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_audio.h"
+#include "ags/engine/ac/global_character.h"
+#include "ags/engine/ac/global_display.h"
+#include "ags/engine/ac/global_game.h"
+#include "ags/engine/ac/global_gui.h"
+#include "ags/engine/ac/global_object.h"
+#include "ags/engine/ac/global_translation.h"
+#include "ags/engine/ac/gui.h"
+#include "ags/engine/ac/hotspot.h"
+#include "ags/engine/ac/lipsync.h"
+#include "ags/engine/ac/mouse.h"
+#include "ags/engine/ac/movelist.h"
+#include "ags/engine/ac/objectcache.h"
+#include "ags/engine/ac/overlay.h"
+#include "ags/engine/ac/path_helper.h"
+#include "ags/engine/ac/sys_events.h"
+#include "ags/engine/ac/region.h"
+#include "ags/engine/ac/richgamemedia.h"
+#include "ags/engine/ac/room.h"
+#include "ags/engine/ac/roomobject.h"
+#include "ags/engine/ac/roomstatus.h"
+#include "ags/engine/ac/runtime_defines.h"
+#include "ags/engine/ac/screenoverlay.h"
 #include "ags/shared/ac/spritecache.h"
-#include "ags/shared/ac/string.h"
-#include "ags/shared/ac/system.h"
-#include "ags/shared/ac/timer.h"
-#include "ags/shared/ac/translation.h"
-#include "ags/shared/ac/dynobj/all_dynamicclasses.h"
-#include "ags/shared/ac/dynobj/all_scriptclasses.h"
-#include "ags/shared/ac/dynobj/cc_audiochannel.h"
-#include "ags/shared/ac/dynobj/cc_audioclip.h"
-#include "ags/shared/ac/dynobj/scriptcamera.h"
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/debug/out.h"
-#include "ags/shared/device/mousew32.h"
+#include "ags/engine/ac/string.h"
+#include "ags/engine/ac/system.h"
+#include "ags/engine/ac/timer.h"
+#include "ags/engine/ac/translation.h"
+#include "ags/engine/ac/dynobj/all_dynamicclasses.h"
+#include "ags/engine/ac/dynobj/all_scriptclasses.h"
+#include "ags/engine/ac/dynobj/cc_audiochannel.h"
+#include "ags/engine/ac/dynobj/cc_audioclip.h"
+#include "ags/engine/ac/dynobj/scriptcamera.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/device/mousew32.h"
 #include "ags/shared/font/fonts.h"
-#include "ags/shared/game/savegame.h"
-#include "ags/shared/game/savegame_components.h"
-#include "ags/shared/game/savegame_internal.h"
-#include "ags/shared/gui/animatingguibutton.h"
+#include "ags/engine/game/savegame.h"
+#include "ags/engine/game/savegame_components.h"
+#include "ags/engine/game/savegame_internal.h"
+#include "ags/engine/gui/animatingguibutton.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/gfx/graphicsdriver.h"
-#include "ags/shared/gfx/gfxfilter.h"
-#include "ags/shared/gui/guidialog.h"
-#include "ags/shared/main/engine.h"
-#include "ags/shared/main/graphics_mode.h"
-#include "ags/shared/main/main.h"
-#include "ags/shared/media/audio/audio_system.h"
-#include "ags/shared/plugin/agsplugin.h"
-#include "ags/shared/plugin/plugin_engine.h"
+#include "ags/engine/gfx/graphicsdriver.h"
+#include "ags/engine/gfx/gfxfilter.h"
+#include "ags/engine/gui/guidialog.h"
+#include "ags/engine/main/engine.h"
+#include "ags/engine/main/graphics_mode.h"
+#include "ags/engine/main/main.h"
+#include "ags/engine/media/audio/audio_system.h"
+#include "ags/engine/plugin/agsplugin.h"
+#include "ags/engine/plugin/plugin_engine.h"
 #include "ags/shared/script/cc_error.h"
-#include "ags/shared/script/runtimescriptvalue.h"
-#include "ags/shared/script/script.h"
-#include "ags/shared/script/script_runtime.h"
+#include "ags/engine/script/runtimescriptvalue.h"
+#include "ags/engine/script/script.h"
+#include "ags/engine/script/script_runtime.h"
 #include "ags/shared/util/alignedstream.h"
 #include "ags/shared/util/directory.h"
 #include "ags/shared/util/filestream.h" // TODO: needed only because plugins expect file handle
 #include "ags/shared/util/path.h"
 #include "ags/shared/util/string_utils.h"
-#include "ags/shared/ac/keycode.h"
+#include "ags/engine/ac/keycode.h"
+
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
+#include "ags/ags.h"
 
 namespace AGS3 {
 
@@ -436,12 +441,12 @@ bool SetSaveGameDirectoryPath(const char *newFolder, bool explicit_path) {
 	}
 
 	String newFolderTempFile = String::FromFormat("%s""agstmp.tmp", newSaveGameDir.GetCStr());
-	if (!Common::File::TestCreateFile(newFolderTempFile))
+	if (!Shared::File::TestCreateFile(newFolderTempFile))
 		return false;
 
 	// copy the Restart Game file, if applicable
 	String restartGamePath = String::FromFormat("%s""agssave.%d%s", saveGameDirectory.GetCStr(), RESTART_POINT_SAVE_GAME_NUMBER, saveGameSuffix.GetCStr());
-	Stream *restartGameFile = Common::File::OpenFileRead(restartGamePath);
+	Stream *restartGameFile = Shared::File::OpenFileRead(restartGamePath);
 	if (restartGameFile != nullptr) {
 		long fileSize = restartGameFile->GetLength();
 		char *mbuffer = (char *)malloc(fileSize);
@@ -449,7 +454,7 @@ bool SetSaveGameDirectoryPath(const char *newFolder, bool explicit_path) {
 		delete restartGameFile;
 
 		restartGamePath.Format("%s""agssave.%d%s", newSaveGameDir.GetCStr(), RESTART_POINT_SAVE_GAME_NUMBER, saveGameSuffix.GetCStr());
-		restartGameFile = Common::File::CreateFile(restartGamePath);
+		restartGameFile = Shared::File::CreateFile(restartGamePath);
 		restartGameFile->Write(mbuffer, fileSize);
 		delete restartGameFile;
 		free(mbuffer);
@@ -771,7 +776,7 @@ const char *Game_GetName() {
 void Game_SetName(const char *newName) {
 	strncpy(play.game_name, newName, 99);
 	play.game_name[99] = 0;
-	set_window_title(play.game_name);
+	::AGS::g_vm->set_window_title(play.game_name);
 }
 
 int Game_GetSkippingCutscene() {
@@ -876,8 +881,8 @@ ScriptCamera *Game_GetAnyCamera(int index) {
 	return play.GetScriptCamera(index);
 }
 
-void Game_SimulateKeyPress(int key) {
-	int platformKey = GetKeyForKeyPressCb(key);
+void Game_SimulateKeyPress(int key_) {
+	int platformKey = GetKeyForKeyPressCb(key_);
 	platformKey = PlatformKeyFromAgsKey(platformKey);
 	if (platformKey >= 0) {
 		simulate_keypress(platformKey);
@@ -985,6 +990,7 @@ void skip_serialized_bitmap(Stream *in) {
 }
 
 long write_screen_shot_for_vista(Stream *out, Bitmap *screenshot) {
+#ifdef TODO
 	long fileSize = 0;
 	String tempFileName = String::FromFormat("%s""_tmpscht.bmp", saveGameDirectory.GetCStr());
 
@@ -996,7 +1002,7 @@ long write_screen_shot_for_vista(Stream *out, Bitmap *screenshot) {
 		fileSize = file_size_ex(tempFileName);
 		char *buffer = (char *)malloc(fileSize);
 
-		Stream *temp_in = Common::File::OpenFileRead(tempFileName);
+		Stream *temp_in = Shared::File::OpenFileRead(tempFileName);
 		temp_in->Read(buffer, fileSize);
 		delete temp_in;
 		::remove(tempFileName);
@@ -1005,10 +1011,13 @@ long write_screen_shot_for_vista(Stream *out, Bitmap *screenshot) {
 		free(buffer);
 	}
 	return fileSize;
+#else
+	error("TODO: write_screen_shot_for_vista");
+#endif
 }
 
 void WriteGameSetupStructBase_Aligned(Stream *out) {
-	AlignedStream align_s(out, Common::kAligned_Write);
+	AlignedStream align_s(out, Shared::kAligned_Write);
 	game.GameSetupStructBase::WriteToFile(&align_s);
 }
 
@@ -1056,7 +1065,7 @@ void save_game(int slotn, const char *descript) {
 	// Screenshot
 	create_savegame_screenshot(screenShot);
 
-	Common::PStream out = StartSavegame(nametouse, descript, screenShot);
+	Shared::PStream out = StartSavegame(nametouse, descript, screenShot);
 	if (out == nullptr)
 		quit("save_game: unable to open savegame file for writing");
 
@@ -1071,7 +1080,7 @@ void save_game(int slotn, const char *descript) {
 
 		update_polled_stuff_if_runtime();
 
-		out.reset(Common::File::OpenFile(nametouse, Common::kFile_Open, Common::kFile_ReadWrite));
+		out.reset(Shared::File::OpenFile(nametouse, Shared::kFile_Open, Shared::kFile_ReadWrite));
 		out->Seek(12, kSeekBegin);
 		out->WriteInt32(screenShotOffset);
 		out->Seek(4);
@@ -1121,7 +1130,7 @@ HSaveError restore_game_scripts(Stream *in, const PreservedParams &pp, RestoredD
 	r_data.ScriptModules.resize(numScriptModules);
 	for (int i = 0; i < numScriptModules; ++i) {
 		size_t module_size = in->ReadInt32();
-		if (pp.ScMdDataSize[i] != module_size) {
+		if (pp.ScMdDataSize[i] != (int)module_size) {
 			return new SavegameError(kSvgErr_GameContentAssertion, String::FromFormat("Mismatching size of script module data, module %d.", i));
 		}
 		r_data.ScriptModules[i].Len = module_size;
@@ -1132,7 +1141,7 @@ HSaveError restore_game_scripts(Stream *in, const PreservedParams &pp, RestoredD
 }
 
 void ReadRoomStatus_Aligned(RoomStatus *roomstat, Stream *in) {
-	AlignedStream align_s(in, Common::kAligned_Read);
+	AlignedStream align_s(in, Shared::kAligned_Read);
 	roomstat->ReadFromFile_v321(&align_s);
 }
 
@@ -1162,7 +1171,7 @@ void restore_game_room_state(Stream *in) {
 }
 
 void ReadGameState_Aligned(Stream *in, RestoredData &r_data) {
-	AlignedStream align_s(in, Common::kAligned_Read);
+	AlignedStream align_s(in, Shared::kAligned_Read);
 	play.ReadFromSavegame(&align_s, kGSSvgVersion_OldFormat, r_data);
 }
 
@@ -1193,7 +1202,7 @@ void restore_game_play(Stream *in, RestoredData &r_data) {
 }
 
 void ReadMoveList_Aligned(Stream *in) {
-	AlignedStream align_s(in, Common::kAligned_Read);
+	AlignedStream align_s(in, Shared::kAligned_Read);
 	for (int i = 0; i < game.numcharacters + MAX_ROOM_OBJECTS + 1; ++i) {
 		mls[i].ReadFromFile_Legacy(&align_s);
 
@@ -1202,12 +1211,12 @@ void ReadMoveList_Aligned(Stream *in) {
 }
 
 void ReadGameSetupStructBase_Aligned(Stream *in) {
-	AlignedStream align_s(in, Common::kAligned_Read);
+	AlignedStream align_s(in, Shared::kAligned_Read);
 	game.GameSetupStructBase::ReadFromFile(&align_s);
 }
 
 void ReadCharacterExtras_Aligned(Stream *in) {
-	AlignedStream align_s(in, Common::kAligned_Read);
+	AlignedStream align_s(in, Shared::kAligned_Read);
 	for (int i = 0; i < game.numcharacters; ++i) {
 		charextra[i].ReadFromFile(&align_s);
 		align_s.Reset();
@@ -1232,7 +1241,7 @@ void restore_game_more_dynamic_values(Stream *in) {
 }
 
 void ReadAnimatedButtons_Aligned(Stream *in) {
-	AlignedStream align_s(in, Common::kAligned_Read);
+	AlignedStream align_s(in, Shared::kAligned_Read);
 	for (int i = 0; i < numAnimButs; ++i) {
 		animbuts[i].ReadFromFile(&align_s);
 		align_s.Reset();
@@ -1255,7 +1264,7 @@ HSaveError restore_game_gui(Stream *in, int numGuisWas) {
 }
 
 HSaveError restore_game_audiocliptypes(Stream *in) {
-	if (in->ReadInt32() != game.audioClipTypes.size()) {
+	if (in->ReadInt32() != (int)game.audioClipTypes.size()) {
 		return new SavegameError(kSvgErr_GameContentAssertion, "Mismatching number of Audio Clip Types.");
 	}
 
@@ -1288,7 +1297,7 @@ void restore_game_ambientsounds(Stream *in, RestoredData &r_data) {
 }
 
 void ReadOverlays_Aligned(Stream *in) {
-	AlignedStream align_s(in, Common::kAligned_Read);
+	AlignedStream align_s(in, Shared::kAligned_Read);
 	for (auto &over : screenover) {
 		over.ReadFromFile(&align_s, 0);
 		align_s.Reset();
@@ -1374,7 +1383,7 @@ HSaveError restore_game_views(Stream *in) {
 }
 
 HSaveError restore_game_audioclips_and_crossfade(Stream *in, RestoredData &r_data) {
-	if (in->ReadInt32() != game.audioClips.size()) {
+	if (in->ReadInt32() != (int)game.audioClips.size()) {
 		return new SavegameError(kSvgErr_GameContentAssertion, "Mismatching number of Audio Clips.");
 	}
 
@@ -1383,7 +1392,7 @@ HSaveError restore_game_audioclips_and_crossfade(Stream *in, RestoredData &r_dat
 		chan_info.Pos = 0;
 		chan_info.ClipID = in->ReadInt32();
 		if (chan_info.ClipID >= 0) {
-			if ((size_t)chan_info.ClipID >= game.audioClips.size()) {
+			if ((size_t)chan_info.ClipID >= (int)game.audioClips.size()) {
 				return new SavegameError(kSvgErr_GameObjectInitFailed, "Invalid audio clip index.");
 			}
 
@@ -1576,12 +1585,12 @@ HSaveError load_game(const String &path, int slotNumber, bool &data_overwritten)
 		// Try to find wanted game's executable; if it does not exist,
 		// continue loading savedgame in current game, and pray for the best
 		get_install_dir_path(gamefilenamebuf, desc.MainDataFilename);
-		if (Common::File::TestReadFile(gamefilenamebuf)) {
+		if (Shared::File::TestReadFile(gamefilenamebuf)) {
 			RunAGSGame(desc.MainDataFilename, 0, 0);
 			load_new_game_restore = slotNumber;
 			return HSaveError::None();
 		}
-		Common::Debug::Printf(kDbgMsg_Warn, "WARNING: the saved game '%s' references game file '%s', but it cannot be found in the current directory. Trying to restore in the running game instead.",
+		Shared::Debug::Printf(kDbgMsg_Warn, "WARNING: the saved game '%s' references game file '%s', but it cannot be found in the current directory. Trying to restore in the running game instead.",
 		                      path.GetCStr(), desc.MainDataFilename.GetCStr());
 	}
 
@@ -1937,10 +1946,6 @@ bool unserialize_audio_script_object(int index, const char *objectType, const ch
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-
 // int  (int audioType);
 RuntimeScriptValue Sc_Game_IsAudioPlaying(const RuntimeScriptValue *params, int32_t param_count) {
 	API_SCALL_INT_PINT(Game_IsAudioPlaying);
diff --git a/engines/ags/engine/ac/gamesetup.cpp b/engines/ags/engine/ac/gamesetup.cpp
index 2bce8af2e1..3c7a2b8a7f 100644
--- a/engines/ags/engine/ac/gamesetup.cpp
+++ b/engines/ags/engine/ac/gamesetup.cpp
@@ -21,7 +21,7 @@
  */
 
 #include "ags/shared/util/wgt2allg.h" // DIGI_AUTODETECT & MIDI_AUTODETECT
-#include "ags/shared/ac/gamesetup.h"
+#include "ags/engine/ac/gamesetup.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/gamestate.cpp b/engines/ags/engine/ac/gamestate.cpp
index b6e186b610..889c3a5d45 100644
--- a/engines/ags/engine/ac/gamestate.cpp
+++ b/engines/ags/engine/ac/gamestate.cpp
@@ -20,22 +20,22 @@
  *
  */
 
-//include <algorithm>
-#include "ags/shared/ac/draw.h"
+#include "ags/std/algorithm.h"
+#include "ags/engine/ac/draw.h"
 #include "ags/shared/ac/game_version.h"
-#include "ags/shared/ac/gamestate.h"
+#include "ags/engine/ac/gamestate.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/timer.h"
-#include "ags/shared/ac/dynobj/scriptcamera.h"
-#include "ags/shared/ac/dynobj/scriptsystem.h"
-#include "ags/shared/ac/dynobj/scriptviewport.h"
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/device/mousew32.h"
+#include "ags/engine/ac/timer.h"
+#include "ags/engine/ac/dynobj/scriptcamera.h"
+#include "ags/engine/ac/dynobj/scriptsystem.h"
+#include "ags/engine/ac/dynobj/scriptviewport.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/device/mousew32.h"
 #include "ags/shared/game/customproperties.h"
 #include "ags/shared/game/roomstruct.h"
-#include "ags/shared/game/savegame_internal.h"
-#include "ags/shared/main/engine.h"
-#include "ags/shared/media/audio/audio_system.h"
+#include "ags/engine/game/savegame_internal.h"
+#include "ags/engine/main/engine.h"
+#include "ags/engine/media/audio/audio_system.h"
 #include "ags/shared/util/alignedstream.h"
 #include "ags/shared/util/string_utils.h"
 
@@ -130,7 +130,7 @@ void GameState::UpdateViewports() {
 		}
 		_roomViewportZOrderChanged = false;
 	}
-	size_t vp_changed = -1;
+	size_t vp_changed = (size_t)-1;
 	for (size_t i = _roomViewportsSorted.size(); i-- > 0;) {
 		auto vp = _roomViewportsSorted[i];
 		if (vp->HasChangedSize() || vp->HasChangedPosition() || vp->HasChangedVisible()) {
@@ -777,7 +777,7 @@ void GameState::WriteForSavegame(Shared::Stream *out) const {
 }
 
 void GameState::ReadQueuedAudioItems_Aligned(Shared::Stream *in) {
-	AlignedStream align_s(in, Common::kAligned_Read);
+	AlignedStream align_s(in, Shared::kAligned_Read);
 	for (int i = 0; i < MAX_QUEUED_MUSIC; ++i) {
 		new_music_queue[i].ReadFromFile(&align_s);
 		align_s.Reset();
diff --git a/engines/ags/engine/ac/global_api.cpp b/engines/ags/engine/ac/global_api.cpp
index ce894d675e..49d411b5e8 100644
--- a/engines/ags/engine/ac/global_api.cpp
+++ b/engines/ags/engine/ac/global_api.cpp
@@ -26,61 +26,61 @@
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-
-#include "ags/shared/ac/cdaudio.h"
-#include "ags/shared/ac/display.h"
-#include "ags/shared/ac/dynamicsprite.h"
-#include "ags/shared/ac/event.h"
-#include "ags/shared/ac/game.h"
-#include "ags/shared/ac/global_audio.h"
-#include "ags/shared/ac/global_button.h"
-#include "ags/shared/ac/global_character.h"
-#include "ags/shared/ac/global_datetime.h"
-#include "ags/shared/ac/global_debug.h"
-#include "ags/shared/ac/global_dialog.h"
-#include "ags/shared/ac/global_display.h"
-#include "ags/shared/ac/global_drawingsurface.h"
-#include "ags/shared/ac/global_dynamicsprite.h"
-#include "ags/shared/ac/global_file.h"
-#include "ags/shared/ac/global_game.h"
-#include "ags/shared/ac/global_gui.h"
-#include "ags/shared/ac/global_hotspot.h"
-#include "ags/shared/ac/global_inventoryitem.h"
-#include "ags/shared/ac/global_invwindow.h"
-#include "ags/shared/ac/global_label.h"
-#include "ags/shared/ac/global_listbox.h"
-#include "ags/shared/ac/global_mouse.h"
-#include "ags/shared/ac/global_object.h"
-#include "ags/shared/ac/global_overlay.h"
-#include "ags/shared/ac/global_palette.h"
-#include "ags/shared/ac/global_parser.h"
-#include "ags/shared/ac/global_record.h"
-#include "ags/shared/ac/global_region.h"
-#include "ags/shared/ac/global_room.h"
-#include "ags/shared/ac/global_slider.h"
-#include "ags/shared/ac/global_screen.h"
-#include "ags/shared/ac/global_string.h"
-#include "ags/shared/ac/global_textbox.h"
-#include "ags/shared/ac/global_timer.h"
-#include "ags/shared/ac/global_translation.h"
-#include "ags/shared/ac/global_video.h"
-#include "ags/shared/ac/global_viewframe.h"
-#include "ags/shared/ac/global_viewport.h"
-#include "ags/shared/ac/global_walkablearea.h"
-#include "ags/shared/ac/global_walkbehind.h"
-#include "ags/shared/ac/math.h"
-#include "ags/shared/ac/mouse.h"
-#include "ags/shared/ac/parser.h"
-#include "ags/shared/ac/string.h"
-#include "ags/shared/ac/room.h"
-#include "ags/shared/media/video/video.h"
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
+
+#include "ags/engine/ac/cdaudio.h"
+#include "ags/engine/ac/display.h"
+#include "ags/engine/ac/dynamicsprite.h"
+#include "ags/engine/ac/event.h"
+#include "ags/engine/ac/game.h"
+#include "ags/engine/ac/global_audio.h"
+#include "ags/engine/ac/global_button.h"
+#include "ags/engine/ac/global_character.h"
+#include "ags/engine/ac/global_datetime.h"
+#include "ags/engine/ac/global_debug.h"
+#include "ags/engine/ac/global_dialog.h"
+#include "ags/engine/ac/global_display.h"
+#include "ags/engine/ac/global_drawingsurface.h"
+#include "ags/engine/ac/global_dynamicsprite.h"
+#include "ags/engine/ac/global_file.h"
+#include "ags/engine/ac/global_game.h"
+#include "ags/engine/ac/global_gui.h"
+#include "ags/engine/ac/global_hotspot.h"
+#include "ags/engine/ac/global_inventoryitem.h"
+#include "ags/engine/ac/global_invwindow.h"
+#include "ags/engine/ac/global_label.h"
+#include "ags/engine/ac/global_listbox.h"
+#include "ags/engine/ac/global_mouse.h"
+#include "ags/engine/ac/global_object.h"
+#include "ags/engine/ac/global_overlay.h"
+#include "ags/engine/ac/global_palette.h"
+#include "ags/engine/ac/global_parser.h"
+#include "ags/engine/ac/global_record.h"
+#include "ags/engine/ac/global_region.h"
+#include "ags/engine/ac/global_room.h"
+#include "ags/engine/ac/global_slider.h"
+#include "ags/engine/ac/global_screen.h"
+#include "ags/engine/ac/global_string.h"
+#include "ags/engine/ac/global_textbox.h"
+#include "ags/engine/ac/global_timer.h"
+#include "ags/engine/ac/global_translation.h"
+#include "ags/engine/ac/global_video.h"
+#include "ags/engine/ac/global_viewframe.h"
+#include "ags/engine/ac/global_viewport.h"
+#include "ags/engine/ac/global_walkablearea.h"
+#include "ags/engine/ac/global_walkbehind.h"
+#include "ags/engine/ac/math.h"
+#include "ags/engine/ac/mouse.h"
+#include "ags/engine/ac/parser.h"
+#include "ags/engine/ac/string.h"
+#include "ags/engine/ac/room.h"
+#include "ags/engine/media/video/video.h"
 #include "ags/shared/util/string_compat.h"
-#include "ags/shared/media/audio/audio_system.h"
+#include "ags/engine/media/audio/audio_system.h"
 
-#include "ags/shared/ac/dynobj/scriptstring.h"
+#include "ags/engine/ac/dynobj/scriptstring.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_audio.cpp b/engines/ags/engine/ac/global_audio.cpp
index 10ae491f76..1cf2aaf71e 100644
--- a/engines/ags/engine/ac/global_audio.cpp
+++ b/engines/ags/engine/ac/global_audio.cpp
@@ -21,19 +21,19 @@
  */
 
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/game.h"
-#include "ags/shared/ac/gamesetup.h"
+#include "ags/engine/ac/game.h"
+#include "ags/engine/ac/gamesetup.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_audio.h"
-#include "ags/shared/ac/lipsync.h"
-#include "ags/shared/ac/path_helper.h"
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/debug/debugger.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_audio.h"
+#include "ags/engine/ac/lipsync.h"
+#include "ags/engine/ac/path_helper.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/debugging/debugger.h"
 #include "ags/shared/game/roomstruct.h"
-#include "ags/shared/main/engine.h"
-#include "ags/shared/media/audio/audio_system.h"
-#include "ags/shared/ac/timer.h"
+#include "ags/engine/main/engine.h"
+#include "ags/engine/media/audio/audio_system.h"
+#include "ags/engine/ac/timer.h"
 #include "ags/shared/util/string_compat.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/ac/global_button.cpp b/engines/ags/engine/ac/global_button.cpp
index 3b6124ed11..77508d1f5e 100644
--- a/engines/ags/engine/ac/global_button.cpp
+++ b/engines/ags/engine/ac/global_button.cpp
@@ -20,11 +20,11 @@
  *
  */
 
-#include "ags/shared/ac/global_button.h"
+#include "ags/engine/ac/global_button.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/button.h"
+#include "ags/engine/ac/button.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/string.h"
+#include "ags/engine/ac/string.h"
 #include "ags/shared/gui/guimain.h"
 #include "ags/shared/gui/guibutton.h"
 
diff --git a/engines/ags/engine/ac/global_character.cpp b/engines/ags/engine/ac/global_character.cpp
index e1ea227556..99e40fd043 100644
--- a/engines/ags/engine/ac/global_character.cpp
+++ b/engines/ags/engine/ac/global_character.cpp
@@ -26,26 +26,26 @@
 //
 //=============================================================================
 
-#include "ags/shared/ac/global_character.h"
+#include "ags/engine/ac/global_character.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/view.h"
-#include "ags/shared/ac/character.h"
-#include "ags/shared/ac/display.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/event.h"
+#include "ags/engine/ac/character.h"
+#include "ags/engine/ac/display.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/event.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_overlay.h"
-#include "ags/shared/ac/global_translation.h"
-#include "ags/shared/ac/object.h"
-#include "ags/shared/ac/overlay.h"
-#include "ags/shared/ac/properties.h"
-#include "ags/shared/ac/screenoverlay.h"
-#include "ags/shared/ac/string.h"
-#include "ags/shared/debug/debug_log.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_overlay.h"
+#include "ags/engine/ac/global_translation.h"
+#include "ags/engine/ac/object.h"
+#include "ags/engine/ac/overlay.h"
+#include "ags/engine/ac/properties.h"
+#include "ags/engine/ac/screenoverlay.h"
+#include "ags/engine/ac/string.h"
+#include "ags/engine/debugging/debug_log.h"
 #include "ags/shared/game/roomstruct.h"
-#include "ags/shared/main/game_run.h"
-#include "ags/shared/script/script.h"
+#include "ags/engine/main/game_run.h"
+#include "ags/engine/script/script.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_datetime.cpp b/engines/ags/engine/ac/global_datetime.cpp
index 2151e00cc7..6e45f02f0e 100644
--- a/engines/ags/engine/ac/global_datetime.cpp
+++ b/engines/ags/engine/ac/global_datetime.cpp
@@ -21,9 +21,10 @@
  */
 
 //include <time.h>
-#include "ags/shared/ac/global_datetime.h"
-#include "ags/shared/ac/datetime.h"
+#include "ags/engine/ac/global_datetime.h"
+#include "ags/engine/ac/datetime.h"
 #include "ags/shared/ac/common.h"
+#include "common/system.h"
 
 namespace AGS3 {
 
@@ -45,8 +46,7 @@ int sc_GetTime(int whatti) {
 }
 
 int GetRawTime() {
-	// TODO: we might need to modify script API to support larger time type
-	return static_cast<int>(time(nullptr));
+	return g_system->getMillis();
 }
 
 } // namespace AGS3
diff --git a/engines/ags/engine/ac/global_datetime.h b/engines/ags/engine/ac/global_datetime.h
index 6edcbe2307..4fdfce993a 100644
--- a/engines/ags/engine/ac/global_datetime.h
+++ b/engines/ags/engine/ac/global_datetime.h
@@ -25,8 +25,8 @@
 
 namespace AGS3 {
 
-int sc_GetTime(int whatti);
-int GetRawTime();
+extern int sc_GetTime(int whatti);
+extern int GetRawTime();
 
 } // namespace AGS3
 
diff --git a/engines/ags/engine/ac/global_debug.cpp b/engines/ags/engine/ac/global_debug.cpp
index 1472384150..e1a4aefece 100644
--- a/engines/ags/engine/ac/global_debug.cpp
+++ b/engines/ags/engine/ac/global_debug.cpp
@@ -20,32 +20,32 @@
  *
  */
 
-#include "ags/shared/ac/global_debug.h"
+#include "ags/engine/ac/global_debug.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/characterinfo.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/game.h"
-#include "ags/shared/ac/gamesetup.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/game.h"
+#include "ags/engine/ac/gamesetup.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_character.h"
-#include "ags/shared/ac/global_display.h"
-#include "ags/shared/ac/global_room.h"
-#include "ags/shared/ac/movelist.h"
-#include "ags/shared/ac/properties.h"
-#include "ags/shared/ac/sys_events.h"
-#include "ags/shared/ac/tree_map.h"
-#include "ags/shared/ac/walkablearea.h"
-#include "ags/shared/gfx/gfxfilter.h"
-#include "ags/shared/gui/guidialog.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_character.h"
+#include "ags/engine/ac/global_display.h"
+#include "ags/engine/ac/global_room.h"
+#include "ags/engine/ac/movelist.h"
+#include "ags/engine/ac/properties.h"
+#include "ags/engine/ac/sys_events.h"
+#include "ags/engine/ac/tree_map.h"
+#include "ags/engine/ac/walkablearea.h"
+#include "ags/engine/gfx/gfxfilter.h"
+#include "ags/engine/gui/guidialog.h"
 #include "ags/shared/script/cc_options.h"
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/debug/debugger.h"
-#include "ags/shared/main/main.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/debugging/debugger.h"
+#include "ags/engine/main/main.h"
 #include "ags/shared/ac/spritecache.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/gfx/graphicsdriver.h"
-#include "ags/shared/main/graphics_mode.h"
+#include "ags/engine/gfx/graphicsdriver.h"
+#include "ags/engine/main/graphics_mode.h"
 
 namespace AGS3 {
 
@@ -120,7 +120,7 @@ void script_debug(int cmdd, int dataa) {
 		const Rect &camera = play.GetRoomCamera(camera_index)->GetRect();
 		Bitmap *view_bmp = BitmapHelper::CreateBitmap(viewport.GetWidth(), viewport.GetHeight());
 		Rect mask_src = Rect(camera.Left / thisroom.MaskResolution, camera.Top / thisroom.MaskResolution, camera.Right / thisroom.MaskResolution, camera.Bottom / thisroom.MaskResolution);
-		view_bmp->StretchBlt(tempw, mask_src, RectWH(0, 0, viewport.GetWidth(), viewport.GetHeight()), Common::kBitmap_Transparency);
+		view_bmp->StretchBlt(tempw, mask_src, RectWH(0, 0, viewport.GetWidth(), viewport.GetHeight()), Shared::kBitmap_Transparency);
 
 		IDriverDependantBitmap *ddb = gfxDriver->CreateDDBFromBitmap(view_bmp, false, true);
 		render_graphics(ddb, viewport.Left, viewport.Top);
@@ -174,7 +174,7 @@ void script_debug(int cmdd, int dataa) {
 		const Rect &camera = play.GetRoomCamera(camera_index)->GetRect();
 		Bitmap *view_bmp = BitmapHelper::CreateBitmap(viewport.GetWidth(), viewport.GetHeight());
 		Rect mask_src = Rect(camera.Left / thisroom.MaskResolution, camera.Top / thisroom.MaskResolution, camera.Right / thisroom.MaskResolution, camera.Bottom / thisroom.MaskResolution);
-		view_bmp->StretchBlt(tempw, mask_src, RectWH(0, 0, viewport.GetWidth(), viewport.GetHeight()), Common::kBitmap_Transparency);
+		view_bmp->StretchBlt(tempw, mask_src, RectWH(0, 0, viewport.GetWidth(), viewport.GetHeight()), Shared::kBitmap_Transparency);
 
 		IDriverDependantBitmap *ddb = gfxDriver->CreateDDBFromBitmap(view_bmp, false, true);
 		render_graphics(ddb, viewport.Left, viewport.Top);
diff --git a/engines/ags/engine/ac/global_dialog.cpp b/engines/ags/engine/ac/global_dialog.cpp
index d5faa90097..82f46aa948 100644
--- a/engines/ags/engine/ac/global_dialog.cpp
+++ b/engines/ags/engine/ac/global_dialog.cpp
@@ -20,16 +20,16 @@
  *
  */
 
-#include "ags/shared/ac/global_dialog.h"
+#include "ags/engine/ac/global_dialog.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/dialog.h"
+#include "ags/engine/ac/dialog.h"
 #include "ags/shared/ac/dialogtopic.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/debug/debugger.h"
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/debugging/debugger.h"
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_display.cpp b/engines/ags/engine/ac/global_display.cpp
index 18658b6740..4cbacc467f 100644
--- a/engines/ags/engine/ac/global_display.cpp
+++ b/engines/ags/engine/ac/global_display.cpp
@@ -23,23 +23,23 @@
 //include <cstdio>
 //include <stdarg.h>
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/character.h"
-#include "ags/shared/ac/display.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/game.h"
+#include "ags/engine/ac/character.h"
+#include "ags/engine/ac/display.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/game.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_character.h"
-#include "ags/shared/ac/global_display.h"
-#include "ags/shared/ac/global_screen.h"
-#include "ags/shared/ac/global_translation.h"
-#include "ags/shared/ac/runtime_defines.h"
-#include "ags/shared/ac/speech.h"
-#include "ags/shared/ac/string.h"
-#include "ags/shared/ac/topbarsettings.h"
-#include "ags/shared/debug/debug_log.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_character.h"
+#include "ags/engine/ac/global_display.h"
+#include "ags/engine/ac/global_screen.h"
+#include "ags/engine/ac/global_translation.h"
+#include "ags/engine/ac/runtime_defines.h"
+#include "ags/engine/ac/speech.h"
+#include "ags/engine/ac/string.h"
+#include "ags/engine/ac/topbarsettings.h"
+#include "ags/engine/debugging/debug_log.h"
 #include "ags/shared/game/roomstruct.h"
-#include "ags/shared/main/game_run.h"
+#include "ags/engine/main/game_run.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_drawingsurface.cpp b/engines/ags/engine/ac/global_drawingsurface.cpp
index acee470f8f..d513678e1d 100644
--- a/engines/ags/engine/ac/global_drawingsurface.cpp
+++ b/engines/ags/engine/ac/global_drawingsurface.cpp
@@ -21,21 +21,21 @@
  */
 
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/display.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/game.h"
+#include "ags/engine/ac/display.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/game.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_drawingsurface.h"
-#include "ags/shared/ac/global_translation.h"
-#include "ags/shared/ac/string.h"
-#include "ags/shared/debug/debug_log.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_drawingsurface.h"
+#include "ags/engine/ac/global_translation.h"
+#include "ags/engine/ac/string.h"
+#include "ags/engine/debugging/debug_log.h"
 #include "ags/shared/font/fonts.h"
 #include "ags/shared/game/roomstruct.h"
 #include "ags/shared/gui/guidefines.h"
 #include "ags/shared/ac/spritecache.h"
 #include "ags/shared/gfx/gfx_def.h"
-#include "ags/shared/gfx/gfx_util.h"
+#include "ags/engine/gfx/gfx_util.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_dynamicsprite.cpp b/engines/ags/engine/ac/global_dynamicsprite.cpp
index e9cb5979f4..59a7eb951d 100644
--- a/engines/ags/engine/ac/global_dynamicsprite.cpp
+++ b/engines/ags/engine/ac/global_dynamicsprite.cpp
@@ -20,14 +20,14 @@
  *
  */
 
-#include "ags/shared/ac/global_dynamicsprite.h"
+#include "ags/engine/ac/global_dynamicsprite.h"
 #include "ags/shared/util/wgt2allg.h" // Allegro RGB, PALETTE
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/dynamicsprite.h"
-#include "ags/shared/ac/path_helper.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/dynamicsprite.h"
+#include "ags/engine/ac/path_helper.h"
 #include "ags/shared/ac/spritecache.h"
-#include "ags/shared/ac/runtime_defines.h" //MAX_PATH
-#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/engine/ac/runtime_defines.h" //MAX_PATH
+#include "ags/engine/gfx/graphicsdriver.h"
 #include "ags/shared/gfx/bitmap.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/ac/global_file.cpp b/engines/ags/engine/ac/global_file.cpp
index 0f3708b03f..66fb05648e 100644
--- a/engines/ags/engine/ac/global_file.cpp
+++ b/engines/ags/engine/ac/global_file.cpp
@@ -21,13 +21,13 @@
  */
 
 //include <string.h>
-#include "ags/shared/ac/global_file.h"
+#include "ags/engine/ac/global_file.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/file.h"
-#include "ags/shared/ac/path_helper.h"
-#include "ags/shared/ac/runtime_defines.h"
-#include "ags/shared/ac/string.h"
-#include "ags/shared/debug/debug_log.h"
+#include "ags/engine/ac/file.h"
+#include "ags/engine/ac/path_helper.h"
+#include "ags/engine/ac/runtime_defines.h"
+#include "ags/engine/ac/string.h"
+#include "ags/engine/debugging/debug_log.h"
 #include "ags/shared/util/directory.h"
 #include "ags/shared/util/path.h"
 #include "ags/shared/util/stream.h"
@@ -37,14 +37,14 @@ namespace AGS3 {
 using namespace AGS::Shared;
 
 int32_t FileOpenCMode(const char *fnmm, const char *cmode) {
-	Common::FileOpenMode open_mode;
-	Common::FileWorkMode work_mode;
+	Shared::FileOpenMode open_mode;
+	Shared::FileWorkMode work_mode;
 	// NOTE: here we ignore the text-mode flag. AGS 2.62 did not let
 	// game devs to open files in text mode. The file reading and
 	// writing logic in AGS makes extra control characters added for
 	// security reasons, and FileWriteRawLine adds CR/LF to the end
 	// of string on its own.
-	if (!Common::File::GetFileModesFromCMode(cmode, open_mode, work_mode)) {
+	if (!Shared::File::GetFileModesFromCMode(cmode, open_mode, work_mode)) {
 		return 0;
 	}
 	return FileOpen(fnmm, open_mode, work_mode);
@@ -66,7 +66,7 @@ int32_t FindFreeFileSlot() {
 	return useindx;
 }
 
-int32_t FileOpen(const char *fnmm, Common::FileOpenMode open_mode, Common::FileWorkMode work_mode) {
+int32_t FileOpen(const char *fnmm, Shared::FileOpenMode open_mode, Shared::FileWorkMode work_mode) {
 	int32_t useindx = FindFreeFileSlot();
 	if (useindx < 0)
 		return 0;
diff --git a/engines/ags/engine/ac/global_game.cpp b/engines/ags/engine/ac/global_game.cpp
index b13d206904..1148456630 100644
--- a/engines/ags/engine/ac/global_game.cpp
+++ b/engines/ags/engine/ac/global_game.cpp
@@ -24,50 +24,51 @@
 
 #include "ags/shared/core/platform.h"
 #include "ags/shared/ac/audiocliptype.h"
-#include "ags/shared/ac/global_game.h"
+#include "ags/shared/util/path.h"
+#include "ags/engine/ac/global_game.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/view.h"
-#include "ags/shared/ac/character.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/dynamicsprite.h"
-#include "ags/shared/ac/event.h"
-#include "ags/shared/ac/game.h"
-#include "ags/shared/ac/gamesetup.h"
+#include "ags/engine/ac/character.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/dynamicsprite.h"
+#include "ags/engine/ac/event.h"
+#include "ags/engine/ac/game.h"
+#include "ags/engine/ac/gamesetup.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_character.h"
-#include "ags/shared/ac/global_gui.h"
-#include "ags/shared/ac/global_hotspot.h"
-#include "ags/shared/ac/global_inventoryitem.h"
-#include "ags/shared/ac/global_translation.h"
-#include "ags/shared/ac/gui.h"
-#include "ags/shared/ac/hotspot.h"
-#include "ags/shared/ac/keycode.h"
-#include "ags/shared/ac/mouse.h"
-#include "ags/shared/ac/object.h"
-#include "ags/shared/ac/path_helper.h"
-#include "ags/shared/ac/sys_events.h"
-#include "ags/shared/ac/room.h"
-#include "ags/shared/ac/roomstatus.h"
-#include "ags/shared/ac/string.h"
-#include "ags/shared/ac/system.h"
-#include "ags/shared/debug/debugger.h"
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/gui/guidialog.h"
-#include "ags/shared/main/engine.h"
-#include "ags/shared/main/game_start.h"
-#include "ags/shared/main/game_run.h"
-#include "ags/shared/main/graphics_mode.h"
-#include "ags/shared/script/script.h"
-#include "ags/shared/script/script_runtime.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_character.h"
+#include "ags/engine/ac/global_gui.h"
+#include "ags/engine/ac/global_hotspot.h"
+#include "ags/engine/ac/global_inventoryitem.h"
+#include "ags/engine/ac/global_translation.h"
+#include "ags/engine/ac/gui.h"
+#include "ags/engine/ac/hotspot.h"
+#include "ags/engine/ac/keycode.h"
+#include "ags/engine/ac/mouse.h"
+#include "ags/engine/ac/object.h"
+#include "ags/engine/ac/path_helper.h"
+#include "ags/engine/ac/sys_events.h"
+#include "ags/engine/ac/room.h"
+#include "ags/engine/ac/roomstatus.h"
+#include "ags/engine/ac/string.h"
+#include "ags/engine/ac/system.h"
+#include "ags/engine/debugging/debugger.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/gui/guidialog.h"
+#include "ags/engine/main/engine.h"
+#include "ags/engine/main/game_start.h"
+#include "ags/engine/main/game_run.h"
+#include "ags/engine/main/graphics_mode.h"
+#include "ags/engine/script/script.h"
+#include "ags/engine/script/script_runtime.h"
 #include "ags/shared/ac/spritecache.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/engine/gfx/graphicsdriver.h"
 #include "ags/shared/core/assetmanager.h"
-#include "ags/shared/main/config.h"
-#include "ags/shared/main/game_file.h"
+#include "ags/engine/main/config.h"
+#include "ags/engine/main/game_file.h"
 #include "ags/shared/util/string_utils.h"
-#include "ags/shared/media/audio/audio_system.h"
+#include "ags/engine/media/audio/audio_system.h"
 
 namespace AGS3 {
 
@@ -136,7 +137,7 @@ void DeleteSaveSlot(int slnum) {
 		String thisname;
 		for (int i = MAXSAVEGAMES; i > slnum; i--) {
 			thisname = get_save_game_path(i);
-			if (Common::File::TestReadFile(thisname)) {
+			if (Shared::File::TestReadFile(thisname)) {
 				// Rename the highest save game to fill in the gap
 				rename(thisname, nametouse);
 				break;
@@ -252,7 +253,7 @@ int RunAGSGame(const char *newgame, unsigned int mode, int data) {
 		// need to copy, since the script gets destroyed
 		get_install_dir_path(gamefilenamebuf, newgame);
 		ResPaths.GamePak.Path = gamefilenamebuf;
-		ResPaths.GamePak.Name = get_filename(gamefilenamebuf);
+		ResPaths.GamePak.Name = Shared::Path::get_filename(gamefilenamebuf);
 		play.takeover_data = data;
 		load_new_game_restore = -1;
 
@@ -276,7 +277,7 @@ int RunAGSGame(const char *newgame, unsigned int mode, int data) {
 	// Adjust config (NOTE: normally, RunAGSGame would need a redesign to allow separate config etc per each game)
 	usetup.translation = ""; // reset to default, prevent from trying translation file of game A in game B
 
-	if (Common::AssetManager::SetDataFile(ResPaths.GamePak.Path) != Common::kAssetNoError)
+	if (Shared::AssetManager::SetDataFile(ResPaths.GamePak.Path) != Shared::kAssetNoError)
 		quitprintf("!RunAGSGame: unable to load new game file '%s'", ResPaths.GamePak.Path.GetCStr());
 
 	show_preload();
@@ -1113,7 +1114,7 @@ int WaitImpl(int skip_type, int nloops) {
 
 	if (game.options[OPT_BASESCRIPTAPI] < kScriptAPI_v351) {
 		// < 3.5.1 return 1 is skipped by user input, otherwise 0
-		return (play.wait_skipped_by & (SKIP_KEYPRESS | SKIP_MOUSECLICK) != 0) ? 1 : 0;
+		return (play.wait_skipped_by & (SKIP_KEYPRESS | SKIP_MOUSECLICK)) != 0 ? 1 : 0;
 	}
 	// >= 3.5.1 return positive keycode, negative mouse button code, or 0 as time-out
 	switch (play.wait_skipped_by) {
diff --git a/engines/ags/engine/ac/global_gui.cpp b/engines/ags/engine/ac/global_gui.cpp
index fcd7223b27..6ffeacfdd6 100644
--- a/engines/ags/engine/ac/global_gui.cpp
+++ b/engines/ags/engine/ac/global_gui.cpp
@@ -21,19 +21,19 @@
  */
 
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/display.h"
-#include "ags/shared/ac/draw.h"
+#include "ags/engine/ac/display.h"
+#include "ags/engine/ac/draw.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/global_game.h"
-#include "ags/shared/ac/global_gui.h"
-#include "ags/shared/ac/gui.h"
-#include "ags/shared/ac/guicontrol.h"
-#include "ags/shared/ac/mouse.h"
-#include "ags/shared/ac/string.h"
-#include "ags/shared/debug/debug_log.h"
+#include "ags/engine/ac/global_game.h"
+#include "ags/engine/ac/global_gui.h"
+#include "ags/engine/ac/gui.h"
+#include "ags/engine/ac/guicontrol.h"
+#include "ags/engine/ac/mouse.h"
+#include "ags/engine/ac/string.h"
+#include "ags/engine/debugging/debug_log.h"
 #include "ags/shared/font/fonts.h"
 #include "ags/shared/gui/guimain.h"
-#include "ags/shared/script/runtimescriptvalue.h"
+#include "ags/engine/script/runtimescriptvalue.h"
 #include "ags/shared/util/string_compat.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/ac/global_hotspot.cpp b/engines/ags/engine/ac/global_hotspot.cpp
index b6021c650a..6998213c1e 100644
--- a/engines/ags/engine/ac/global_hotspot.cpp
+++ b/engines/ags/engine/ac/global_hotspot.cpp
@@ -20,22 +20,22 @@
  *
  */
 
-#include "ags/shared/ac/global_hotspot.h"
+#include "ags/engine/ac/global_hotspot.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/common_defines.h"
 #include "ags/shared/ac/characterinfo.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/event.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/event.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/global_character.h"
-#include "ags/shared/ac/global_translation.h"
-#include "ags/shared/ac/hotspot.h"
-#include "ags/shared/ac/properties.h"
-#include "ags/shared/ac/roomstatus.h"
-#include "ags/shared/ac/string.h"
-#include "ags/shared/debug/debug_log.h"
+#include "ags/engine/ac/global_character.h"
+#include "ags/engine/ac/global_translation.h"
+#include "ags/engine/ac/hotspot.h"
+#include "ags/engine/ac/properties.h"
+#include "ags/engine/ac/roomstatus.h"
+#include "ags/engine/ac/string.h"
+#include "ags/engine/debugging/debug_log.h"
 #include "ags/shared/game/roomstruct.h"
-#include "ags/shared/script/script.h"
+#include "ags/engine/script/script.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_inventoryitem.cpp b/engines/ags/engine/ac/global_inventoryitem.cpp
index 7d2f7885d8..4bd15c1eee 100644
--- a/engines/ags/engine/ac/global_inventoryitem.cpp
+++ b/engines/ags/engine/ac/global_inventoryitem.cpp
@@ -22,17 +22,17 @@
 
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/global_gui.h"
-#include "ags/shared/ac/global_inventoryitem.h"
-#include "ags/shared/ac/global_translation.h"
-#include "ags/shared/ac/inventoryitem.h"
-#include "ags/shared/ac/invwindow.h"
-#include "ags/shared/ac/properties.h"
-#include "ags/shared/ac/string.h"
+#include "ags/engine/ac/global_gui.h"
+#include "ags/engine/ac/global_inventoryitem.h"
+#include "ags/engine/ac/global_translation.h"
+#include "ags/engine/ac/inventoryitem.h"
+#include "ags/engine/ac/invwindow.h"
+#include "ags/engine/ac/properties.h"
+#include "ags/engine/ac/string.h"
 #include "ags/shared/gui/guimain.h"
 #include "ags/shared/gui/guiinv.h"
-#include "ags/shared/ac/event.h"
-#include "ags/shared/ac/gamestate.h"
+#include "ags/engine/ac/event.h"
+#include "ags/engine/ac/gamestate.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_invwindow.cpp b/engines/ags/engine/ac/global_invwindow.cpp
index cb3ef9ef1e..ac2a68a8ea 100644
--- a/engines/ags/engine/ac/global_invwindow.cpp
+++ b/engines/ags/engine/ac/global_invwindow.cpp
@@ -20,12 +20,12 @@
  *
  */
 
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_invwindow.h"
-#include "ags/shared/ac/global_translation.h"
-#include "ags/shared/ac/properties.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_invwindow.h"
+#include "ags/engine/ac/global_translation.h"
+#include "ags/engine/ac/properties.h"
 #include "ags/shared/gui/guiinv.h"
-#include "ags/shared/script/executingscript.h"
+#include "ags/engine/script/executingscript.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_label.cpp b/engines/ags/engine/ac/global_label.cpp
index 8c1b404bd4..a60e6f23d6 100644
--- a/engines/ags/engine/ac/global_label.cpp
+++ b/engines/ags/engine/ac/global_label.cpp
@@ -20,11 +20,11 @@
  *
  */
 
-#include "ags/shared/ac/global_label.h"
+#include "ags/engine/ac/global_label.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/label.h"
-#include "ags/shared/ac/string.h"
+#include "ags/engine/ac/label.h"
+#include "ags/engine/ac/string.h"
 #include "ags/shared/gui/guimain.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/ac/global_listbox.cpp b/engines/ags/engine/ac/global_listbox.cpp
index ef607a52f7..be748096bc 100644
--- a/engines/ags/engine/ac/global_listbox.cpp
+++ b/engines/ags/engine/ac/global_listbox.cpp
@@ -20,10 +20,10 @@
  *
  */
 
-#include "ags/shared/ac/global_listbox.h"
+#include "ags/engine/ac/global_listbox.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/listbox.h"
-#include "ags/shared/ac/string.h"
+#include "ags/engine/ac/listbox.h"
+#include "ags/engine/ac/string.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_mouse.cpp b/engines/ags/engine/ac/global_mouse.cpp
index 6310da0da3..7c9471b501 100644
--- a/engines/ags/engine/ac/global_mouse.cpp
+++ b/engines/ags/engine/ac/global_mouse.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ags/shared/ac/global_mouse.h"
-#include "ags/shared/ac/gamestate.h"
+#include "ags/engine/ac/global_mouse.h"
+#include "ags/engine/ac/gamestate.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_object.cpp b/engines/ags/engine/ac/global_object.cpp
index 3be568fa04..a2b552eba3 100644
--- a/engines/ags/engine/ac/global_object.cpp
+++ b/engines/ags/engine/ac/global_object.cpp
@@ -20,28 +20,28 @@
  *
  */
 
-#include "ags/shared/ac/global_object.h"
+#include "ags/engine/ac/global_object.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/object.h"
+#include "ags/engine/ac/object.h"
 #include "ags/shared/ac/view.h"
-#include "ags/shared/ac/character.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/event.h"
+#include "ags/engine/ac/character.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/event.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/global_character.h"
-#include "ags/shared/ac/global_translation.h"
-#include "ags/shared/ac/object.h"
-#include "ags/shared/ac/objectcache.h"
-#include "ags/shared/ac/properties.h"
-#include "ags/shared/ac/roomobject.h"
-#include "ags/shared/ac/roomstatus.h"
-#include "ags/shared/ac/string.h"
-#include "ags/shared/ac/viewframe.h"
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/main/game_run.h"
-#include "ags/shared/script/script.h"
+#include "ags/engine/ac/global_character.h"
+#include "ags/engine/ac/global_translation.h"
+#include "ags/engine/ac/object.h"
+#include "ags/engine/ac/objectcache.h"
+#include "ags/engine/ac/properties.h"
+#include "ags/engine/ac/roomobject.h"
+#include "ags/engine/ac/roomstatus.h"
+#include "ags/engine/ac/string.h"
+#include "ags/engine/ac/viewframe.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/main/game_run.h"
+#include "ags/engine/script/script.h"
 #include "ags/shared/ac/spritecache.h"
-#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/engine/gfx/graphicsdriver.h"
 #include "ags/shared/gfx/bitmap.h"
 #include "ags/shared/gfx/gfx_def.h"
 
diff --git a/engines/ags/engine/ac/global_overlay.cpp b/engines/ags/engine/ac/global_overlay.cpp
index 3f1c82ec10..9fe39315a1 100644
--- a/engines/ags/engine/ac/global_overlay.cpp
+++ b/engines/ags/engine/ac/global_overlay.cpp
@@ -20,19 +20,19 @@
  *
  */
 
-#include "ags/shared/ac/global_overlay.h"
+#include "ags/engine/ac/global_overlay.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/display.h"
-#include "ags/shared/ac/draw.h"
+#include "ags/engine/ac/display.h"
+#include "ags/engine/ac/draw.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_translation.h"
-#include "ags/shared/ac/overlay.h"
-#include "ags/shared/ac/runtime_defines.h"
-#include "ags/shared/ac/screenoverlay.h"
-#include "ags/shared/ac/string.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_translation.h"
+#include "ags/engine/ac/overlay.h"
+#include "ags/engine/ac/runtime_defines.h"
+#include "ags/engine/ac/screenoverlay.h"
+#include "ags/engine/ac/string.h"
 #include "ags/shared/ac/spritecache.h"
-#include "ags/shared/ac/system.h"
+#include "ags/engine/ac/system.h"
 #include "ags/shared/gfx/bitmap.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/ac/global_palette.cpp b/engines/ags/engine/ac/global_palette.cpp
index 0d8bc049fb..17961ad2f5 100644
--- a/engines/ags/engine/ac/global_palette.cpp
+++ b/engines/ags/engine/ac/global_palette.cpp
@@ -21,10 +21,10 @@
  */
 
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/draw.h"
+#include "ags/engine/ac/draw.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_palette.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_palette.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_parser.cpp b/engines/ags/engine/ac/global_parser.cpp
index 68635efc58..6776619898 100644
--- a/engines/ags/engine/ac/global_parser.cpp
+++ b/engines/ags/engine/ac/global_parser.cpp
@@ -20,11 +20,10 @@
  *
  */
 
-//include <cstring> //strcpy()
-#include "ags/shared/ac/global_parser.h"
+#include "ags/engine/ac/global_parser.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/string.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/string.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_record.cpp b/engines/ags/engine/ac/global_record.cpp
index 6e6e0c92f8..40c14ecc9e 100644
--- a/engines/ags/engine/ac/global_record.cpp
+++ b/engines/ags/engine/ac/global_record.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/shared/ac/global_record.h"
+#include "ags/engine/ac/global_record.h"
 #include "ags/shared/ac/common.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/ac/global_region.cpp b/engines/ags/engine/ac/global_region.cpp
index e1307d3941..5ef84c06a9 100644
--- a/engines/ags/engine/ac/global_region.cpp
+++ b/engines/ags/engine/ac/global_region.cpp
@@ -20,16 +20,16 @@
  *
  */
 
-#include "ags/shared/ac/global_region.h"
+#include "ags/engine/ac/global_region.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/game_version.h"
-#include "ags/shared/ac/region.h"
-#include "ags/shared/ac/room.h"
-#include "ags/shared/ac/roomstatus.h"
-#include "ags/shared/debug/debug_log.h"
+#include "ags/engine/ac/region.h"
+#include "ags/engine/ac/room.h"
+#include "ags/engine/ac/roomstatus.h"
+#include "ags/engine/debugging/debug_log.h"
 #include "ags/shared/game/roomstruct.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/script/script.h"
+#include "ags/engine/script/script.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_room.cpp b/engines/ags/engine/ac/global_room.cpp
index ff23f92d91..43ec2bae8d 100644
--- a/engines/ags/engine/ac/global_room.cpp
+++ b/engines/ags/engine/ac/global_room.cpp
@@ -20,23 +20,23 @@
  *
  */
 
-#include "ags/shared/ac/global_room.h"
+#include "ags/engine/ac/global_room.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/character.h"
+#include "ags/engine/ac/character.h"
 #include "ags/shared/ac/characterinfo.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/event.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/event.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_character.h"
-#include "ags/shared/ac/global_game.h"
-#include "ags/shared/ac/movelist.h"
-#include "ags/shared/ac/properties.h"
-#include "ags/shared/ac/room.h"
-#include "ags/shared/ac/roomstatus.h"
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/debug/debugger.h"
-#include "ags/shared/script/script.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_character.h"
+#include "ags/engine/ac/global_game.h"
+#include "ags/engine/ac/movelist.h"
+#include "ags/engine/ac/properties.h"
+#include "ags/engine/ac/room.h"
+#include "ags/engine/ac/roomstatus.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/debugging/debugger.h"
+#include "ags/engine/script/script.h"
 #include "ags/shared/util/math.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/ac/global_screen.cpp b/engines/ags/engine/ac/global_screen.cpp
index 8014024203..52a0c628ad 100644
--- a/engines/ags/engine/ac/global_screen.cpp
+++ b/engines/ags/engine/ac/global_screen.cpp
@@ -21,18 +21,18 @@
  */
 
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/gamesetup.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/gamesetup.h"
+#include "ags/engine/ac/gamesetup.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/gamesetup.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_game.h"
-#include "ags/shared/ac/global_screen.h"
-#include "ags/shared/ac/runtime_defines.h"
-#include "ags/shared/ac/screen.h"
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/platform/base/agsplatformdriver.h"
-#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_game.h"
+#include "ags/engine/ac/global_screen.h"
+#include "ags/engine/ac/runtime_defines.h"
+#include "ags/engine/ac/screen.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
+#include "ags/engine/gfx/graphicsdriver.h"
 #include "ags/shared/gfx/bitmap.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/ac/global_slider.cpp b/engines/ags/engine/ac/global_slider.cpp
index f91e88660d..36845f9440 100644
--- a/engines/ags/engine/ac/global_slider.cpp
+++ b/engines/ags/engine/ac/global_slider.cpp
@@ -20,10 +20,10 @@
  *
  */
 
-#include "ags/shared/ac/global_slider.h"
+#include "ags/engine/ac/global_slider.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/slider.h"
+#include "ags/engine/ac/slider.h"
 #include "ags/shared/gui/guimain.h"
 #include "ags/shared/gui/guislider.h"
 
diff --git a/engines/ags/engine/ac/global_string.cpp b/engines/ags/engine/ac/global_string.cpp
index d64a4fae91..38f74bdb93 100644
--- a/engines/ags/engine/ac/global_string.cpp
+++ b/engines/ags/engine/ac/global_string.cpp
@@ -22,10 +22,10 @@
 
 //include <string.h>
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/global_string.h"
-#include "ags/shared/ac/global_translation.h"
-#include "ags/shared/ac/runtime_defines.h"
-#include "ags/shared/ac/string.h"
+#include "ags/engine/ac/global_string.h"
+#include "ags/engine/ac/global_translation.h"
+#include "ags/engine/ac/runtime_defines.h"
+#include "ags/engine/ac/string.h"
 #include "ags/shared/util/string_compat.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/ac/global_textbox.cpp b/engines/ags/engine/ac/global_textbox.cpp
index aa78c0632c..34a4d1d04a 100644
--- a/engines/ags/engine/ac/global_textbox.cpp
+++ b/engines/ags/engine/ac/global_textbox.cpp
@@ -20,11 +20,11 @@
  *
  */
 
-#include "ags/shared/ac/global_textbox.h"
+#include "ags/engine/ac/global_textbox.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/string.h"
-#include "ags/shared/ac/textbox.h"
+#include "ags/engine/ac/string.h"
+#include "ags/engine/ac/textbox.h"
 #include "ags/shared/gui/guimain.h"
 #include "ags/shared/gui/guitextbox.h"
 
diff --git a/engines/ags/engine/ac/global_timer.cpp b/engines/ags/engine/ac/global_timer.cpp
index d65d2befdf..e06a37eb11 100644
--- a/engines/ags/engine/ac/global_timer.cpp
+++ b/engines/ags/engine/ac/global_timer.cpp
@@ -20,10 +20,10 @@
  *
  */
 
-#include "ags/shared/ac/global_timer.h"
-#include "ags/shared/ac/runtime_defines.h"
+#include "ags/engine/ac/global_timer.h"
+#include "ags/engine/ac/runtime_defines.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/gamestate.h"
+#include "ags/engine/ac/gamestate.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_translation.cpp b/engines/ags/engine/ac/global_translation.cpp
index 822ee3a735..07c2771752 100644
--- a/engines/ags/engine/ac/global_translation.cpp
+++ b/engines/ags/engine/ac/global_translation.cpp
@@ -22,14 +22,14 @@
 
 //include <string.h>
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/display.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_translation.h"
-#include "ags/shared/ac/string.h"
-#include "ags/shared/ac/tree_map.h"
-#include "ags/shared/platform/base/agsplatformdriver.h"
-#include "ags/shared/plugin/agsplugin.h"
-#include "ags/shared/plugin/plugin_engine.h"
+#include "ags/engine/ac/display.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_translation.h"
+#include "ags/engine/ac/string.h"
+#include "ags/engine/ac/tree_map.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
+#include "ags/engine/plugin/agsplugin.h"
+#include "ags/engine/plugin/plugin_engine.h"
 #include "ags/shared/util/memory.h"
 #include "ags/shared/core/types.h"
 
diff --git a/engines/ags/engine/ac/global_video.cpp b/engines/ags/engine/ac/global_video.cpp
index a676765874..e8183a3ec9 100644
--- a/engines/ags/engine/ac/global_video.cpp
+++ b/engines/ags/engine/ac/global_video.cpp
@@ -21,16 +21,16 @@
  */
 
 #include "ags/lib/allegro.h"
-#include "ags/shared/ac/gamesetup.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_audio.h"
-#include "ags/shared/ac/global_game.h"
-#include "ags/shared/ac/global_video.h"
-#include "ags/shared/ac/path_helper.h"
-#include "ags/shared/debug/debugger.h"
-#include "ags/shared/media/video/video.h"
-#include "ags/shared/media/audio/audio_system.h"
-#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/engine/ac/gamesetup.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_audio.h"
+#include "ags/engine/ac/global_game.h"
+#include "ags/engine/ac/global_video.h"
+#include "ags/engine/ac/path_helper.h"
+#include "ags/engine/debugging/debugger.h"
+#include "ags/engine/media/video/video.h"
+#include "ags/engine/media/audio/audio_system.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
 #include "ags/shared/util/string_compat.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/ac/global_viewframe.cpp b/engines/ags/engine/ac/global_viewframe.cpp
index e57afccfb7..8ede616427 100644
--- a/engines/ags/engine/ac/global_viewframe.cpp
+++ b/engines/ags/engine/ac/global_viewframe.cpp
@@ -20,12 +20,12 @@
  *
  */
 
-#include "ags/shared/ac/global_viewframe.h"
+#include "ags/engine/ac/global_viewframe.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/view.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/media/audio/audio_system.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/media/audio/audio_system.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_viewport.cpp b/engines/ags/engine/ac/global_viewport.cpp
index a76a4443fc..776272d2fd 100644
--- a/engines/ags/engine/ac/global_viewport.cpp
+++ b/engines/ags/engine/ac/global_viewport.cpp
@@ -20,9 +20,9 @@
  *
  */
 
-#include "ags/shared/ac/global_viewport.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/debug/debug_log.h"
+#include "ags/engine/ac/global_viewport.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/debugging/debug_log.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/global_walkablearea.cpp b/engines/ags/engine/ac/global_walkablearea.cpp
index 8bf3df756a..3a62a1627d 100644
--- a/engines/ags/engine/ac/global_walkablearea.cpp
+++ b/engines/ags/engine/ac/global_walkablearea.cpp
@@ -20,12 +20,12 @@
  *
  */
 
-#include "ags/shared/ac/global_walkablearea.h"
+#include "ags/engine/ac/global_walkablearea.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/common_defines.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/walkablearea.h"
-#include "ags/shared/debug/debug_log.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/walkablearea.h"
+#include "ags/engine/debugging/debug_log.h"
 #include "ags/shared/game/roomstruct.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/ac/global_walkbehind.cpp b/engines/ags/engine/ac/global_walkbehind.cpp
index 315c3ac4d9..ae1f7cc67f 100644
--- a/engines/ags/engine/ac/global_walkbehind.cpp
+++ b/engines/ags/engine/ac/global_walkbehind.cpp
@@ -20,13 +20,13 @@
  *
  */
 
-#include "ags/shared/ac/global_walkbehind.h"
+#include "ags/engine/ac/global_walkbehind.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/common_defines.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/roomstatus.h"
-#include "ags/shared/ac/walkbehind.h"
-#include "ags/shared/debug/debug_log.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/roomstatus.h"
+#include "ags/engine/ac/walkbehind.h"
+#include "ags/engine/debugging/debug_log.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/gui.cpp b/engines/ags/engine/ac/gui.cpp
index fa00a425ff..d52d7cbc82 100644
--- a/engines/ags/engine/ac/gui.cpp
+++ b/engines/ags/engine/ac/gui.cpp
@@ -21,40 +21,44 @@
  */
 
 //include <cstdio>
-#include "ags/shared/ac/gui.h"
+#include "ags/engine/ac/gui.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/event.h"
-#include "ags/shared/ac/gamesetup.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/event.h"
+#include "ags/engine/ac/gamesetup.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/global_character.h"
-#include "ags/shared/ac/global_game.h"
-#include "ags/shared/ac/global_gui.h"
-#include "ags/shared/ac/global_inventoryitem.h"
-#include "ags/shared/ac/global_screen.h"
-#include "ags/shared/ac/guicontrol.h"
+#include "ags/engine/ac/global_character.h"
+#include "ags/engine/ac/global_game.h"
+#include "ags/engine/ac/global_gui.h"
+#include "ags/engine/ac/global_inventoryitem.h"
+#include "ags/engine/ac/global_screen.h"
+#include "ags/engine/ac/guicontrol.h"
 #include "ags/shared/ac/interfacebutton.h"
-#include "ags/shared/ac/invwindow.h"
-#include "ags/shared/ac/mouse.h"
-#include "ags/shared/ac/runtime_defines.h"
-#include "ags/shared/ac/system.h"
-#include "ags/shared/ac/dynobj/cc_guiobject.h"
-#include "ags/shared/ac/dynobj/scriptgui.h"
-#include "ags/shared/script/cc_instance.h"
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/device/mousew32.h"
-#include "ags/shared/gfx/gfxfilter.h"
+#include "ags/engine/ac/invwindow.h"
+#include "ags/engine/ac/mouse.h"
+#include "ags/engine/ac/runtime_defines.h"
+#include "ags/engine/ac/system.h"
+#include "ags/engine/ac/dynobj/cc_guiobject.h"
+#include "ags/engine/ac/dynobj/scriptgui.h"
+#include "ags/engine/script/cc_instance.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/device/mousew32.h"
+#include "ags/engine/gfx/gfxfilter.h"
 #include "ags/shared/gui/guibutton.h"
 #include "ags/shared/gui/guimain.h"
-#include "ags/shared/script/script.h"
-#include "ags/shared/script/script_runtime.h"
-#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/engine/script/script.h"
+#include "ags/engine/script/script_runtime.h"
+#include "ags/engine/gfx/graphicsdriver.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/ac/dynobj/cc_gui.h"
-#include "ags/shared/ac/dynobj/cc_guiobject.h"
-#include "ags/shared/script/runtimescriptvalue.h"
+#include "ags/engine/ac/dynobj/cc_gui.h"
+#include "ags/engine/ac/dynobj/cc_guiobject.h"
+#include "ags/engine/script/runtimescriptvalue.h"
 #include "ags/shared/util/string_compat.h"
 
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
+
 namespace AGS3 {
 
 using namespace AGS::Shared;
@@ -341,7 +345,7 @@ void process_interface_click(int ifce, int btn, int mbut) {
 	}
 
 	int btype = guis[ifce].GetControlType(btn);
-	int rtype = kGUIAction_None, rdata;
+	int rtype = kGUIAction_None, rdata = 0;
 	if (btype == kGUIButton) {
 		GUIButton *gbuto = (GUIButton *)guis[ifce].GetControl(btn);
 		rtype = gbuto->ClickAction[kMouseLeft];
@@ -685,10 +689,6 @@ void gui_on_mouse_down(const int guin, const int mbut) {
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-
 // void GUI_Centre(ScriptGUI *sgui)
 RuntimeScriptValue Sc_GUI_Centre(void *self, const RuntimeScriptValue *params, int32_t param_count) {
 	API_OBJCALL_VOID(ScriptGUI, GUI_Centre);
diff --git a/engines/ags/engine/ac/guicontrol.cpp b/engines/ags/engine/ac/guicontrol.cpp
index 90907e7748..eb089b3de4 100644
--- a/engines/ags/engine/ac/guicontrol.cpp
+++ b/engines/ags/engine/ac/guicontrol.cpp
@@ -21,9 +21,9 @@
  */
 
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/guicontrol.h"
-#include "ags/shared/ac/global_gui.h"
-#include "ags/shared/debug/debug_log.h"
+#include "ags/engine/ac/guicontrol.h"
+#include "ags/engine/ac/global_gui.h"
+#include "ags/engine/debugging/debug_log.h"
 #include "ags/shared/gui/guibutton.h"
 #include "ags/shared/gui/guiinv.h"
 #include "ags/shared/gui/guilabel.h"
@@ -31,9 +31,13 @@
 #include "ags/shared/gui/guimain.h"
 #include "ags/shared/gui/guislider.h"
 #include "ags/shared/gui/guitextbox.h"
-#include "ags/shared/script/runtimescriptvalue.h"
-#include "ags/shared/ac/dynobj/cc_gui.h"
-#include "ags/shared/ac/dynobj/cc_guiobject.h"
+#include "ags/engine/script/runtimescriptvalue.h"
+#include "ags/engine/ac/dynobj/cc_gui.h"
+#include "ags/engine/ac/dynobj/cc_guiobject.h"
+
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
 
 namespace AGS3 {
 
@@ -237,10 +241,6 @@ void GUIControl_BringToFront(GUIObject *guio) {
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-
 // void (GUIObject *guio)
 RuntimeScriptValue Sc_GUIControl_BringToFront(void *self, const RuntimeScriptValue *params, int32_t param_count) {
 	API_OBJCALL_VOID(GUIObject, GUIControl_BringToFront);
diff --git a/engines/ags/engine/ac/guiinv.cpp b/engines/ags/engine/ac/guiinv.cpp
index 18a08c034c..b7a2767e45 100644
--- a/engines/ags/engine/ac/guiinv.cpp
+++ b/engines/ags/engine/ac/guiinv.cpp
@@ -22,10 +22,10 @@
 
 #include "ags/shared/gui/guiinv.h"
 #include "ags/shared/gui/guimain.h"
-#include "ags/shared/ac/draw.h"
+#include "ags/engine/ac/draw.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/characterextras.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/characterextras.h"
 #include "ags/shared/ac/spritecache.h"
 #include "ags/shared/gfx/bitmap.h"
 
diff --git a/engines/ags/engine/ac/hotspot.cpp b/engines/ags/engine/ac/hotspot.cpp
index ddaee7ce85..09e4948d33 100644
--- a/engines/ags/engine/ac/hotspot.cpp
+++ b/engines/ags/engine/ac/hotspot.cpp
@@ -20,18 +20,23 @@
  *
  */
 
-#include "ags/shared/ac/dynobj/cc_hotspot.h"
-#include "ags/shared/ac/hotspot.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_hotspot.h"
-#include "ags/shared/ac/global_translation.h"
-#include "ags/shared/ac/properties.h"
-#include "ags/shared/ac/room.h"
-#include "ags/shared/ac/roomstatus.h"
-#include "ags/shared/ac/string.h"
+#include "ags/engine/ac/dynobj/cc_hotspot.h"
+#include "ags/engine/ac/hotspot.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_hotspot.h"
+#include "ags/engine/ac/global_translation.h"
+#include "ags/engine/ac/properties.h"
+#include "ags/engine/ac/room.h"
+#include "ags/engine/ac/roomstatus.h"
+#include "ags/engine/ac/string.h"
 #include "ags/shared/game/roomstruct.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/script/runtimescriptvalue.h"
+#include "ags/engine/script/runtimescriptvalue.h"
+
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
+#include "ags/engine/ac/dynobj/scriptstring.h"
 
 namespace AGS3 {
 
@@ -128,11 +133,6 @@ int get_hotspot_at(int xpp, int ypp) {
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-#include "ags/shared/ac/dynobj/scriptstring.h"
-
 extern ScriptString myScriptStringImpl;
 
 RuntimeScriptValue Sc_GetHotspotAtRoom(const RuntimeScriptValue *params, int32_t param_count) {
diff --git a/engines/ags/engine/ac/interfaceelement.cpp b/engines/ags/engine/ac/interfaceelement.cpp
index ea8f5d483c..8f3dc5b529 100644
--- a/engines/ags/engine/ac/interfaceelement.cpp
+++ b/engines/ags/engine/ac/interfaceelement.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-//include <string.h>
 #include "ags/shared/ac/interfaceelement.h"
+#include "common/str.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/inventoryitem.cpp b/engines/ags/engine/ac/inventoryitem.cpp
index c04585e3af..a9b45c23e6 100644
--- a/engines/ags/engine/ac/inventoryitem.cpp
+++ b/engines/ags/engine/ac/inventoryitem.cpp
@@ -20,18 +20,23 @@
  *
  */
 
-#include "ags/shared/ac/inventoryitem.h"
+#include "ags/engine/ac/inventoryitem.h"
 #include "ags/shared/ac/characterinfo.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_inventoryitem.h"
-#include "ags/shared/ac/global_translation.h"
-#include "ags/shared/ac/mouse.h"
-#include "ags/shared/ac/properties.h"
-#include "ags/shared/ac/runtime_defines.h"
-#include "ags/shared/ac/string.h"
-#include "ags/shared/script/runtimescriptvalue.h"
-#include "ags/shared/ac/dynobj/cc_inventory.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_inventoryitem.h"
+#include "ags/engine/ac/global_translation.h"
+#include "ags/engine/ac/mouse.h"
+#include "ags/engine/ac/properties.h"
+#include "ags/engine/ac/runtime_defines.h"
+#include "ags/engine/ac/string.h"
+#include "ags/engine/script/runtimescriptvalue.h"
+#include "ags/engine/ac/dynobj/cc_inventory.h"
+
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
+#include "ags/engine/ac/dynobj/scriptstring.h"
 
 namespace AGS3 {
 
@@ -126,11 +131,6 @@ void set_inv_item_cursorpic(int invItemId, int piccy) {
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-#include "ags/shared/ac/dynobj/scriptstring.h"
-
 extern ScriptString myScriptStringImpl;
 
 // ScriptInvItem *(int xx, int yy)
diff --git a/engines/ags/engine/ac/invwindow.cpp b/engines/ags/engine/ac/invwindow.cpp
index 87b10255e7..208666888d 100644
--- a/engines/ags/engine/ac/invwindow.cpp
+++ b/engines/ags/engine/ac/invwindow.cpp
@@ -20,30 +20,34 @@
  *
  */
 
-#include "ags/shared/ac/invwindow.h"
+#include "ags/engine/ac/invwindow.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/characterextras.h"
+#include "ags/engine/ac/characterextras.h"
 #include "ags/shared/ac/characterinfo.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/event.h"
-#include "ags/shared/ac/gamestate.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/event.h"
+#include "ags/engine/ac/gamestate.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/global_character.h"
-#include "ags/shared/ac/global_display.h"
-#include "ags/shared/ac/global_room.h"
-#include "ags/shared/ac/mouse.h"
-#include "ags/shared/ac/sys_events.h"
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/gui/guidialog.h"
-#include "ags/shared/main/game_run.h"
-#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/engine/ac/global_character.h"
+#include "ags/engine/ac/global_display.h"
+#include "ags/engine/ac/global_room.h"
+#include "ags/engine/ac/mouse.h"
+#include "ags/engine/ac/sys_events.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/gui/guidialog.h"
+#include "ags/engine/main/game_run.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
 #include "ags/shared/ac/spritecache.h"
-#include "ags/shared/script/runtimescriptvalue.h"
-#include "ags/shared/ac/dynobj/cc_character.h"
-#include "ags/shared/ac/dynobj/cc_inventory.h"
+#include "ags/engine/script/runtimescriptvalue.h"
+#include "ags/engine/ac/dynobj/cc_character.h"
+#include "ags/engine/ac/dynobj/cc_inventory.h"
 #include "ags/shared/util/math.h"
-#include "ags/shared/media/audio/audio_system.h"
-#include "ags/shared/ac/timer.h"
+#include "ags/engine/media/audio/audio_system.h"
+#include "ags/engine/ac/timer.h"
+
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
 
 namespace AGS3 {
 
@@ -333,7 +337,7 @@ void InventoryScreen::Draw(Bitmap *ds) {
 	if (top_item > 0)
 		wputblock(ds, windowwid - ARROWBUTTONWID, buttonyp + get_fixed_pixel_size(2), arrowblock, 1);
 	if (top_item + num_visible_items < numitems)
-		arrowblock->FlipBlt(arrowblock, windowwid - ARROWBUTTONWID, buttonyp + get_fixed_pixel_size(4) + ARROWBUTTONWID, Common::kBitmap_VFlip);
+		arrowblock->FlipBlt(arrowblock, windowwid - ARROWBUTTONWID, buttonyp + get_fixed_pixel_size(4) + ARROWBUTTONWID, Shared::kBitmap_VFlip);
 	delete arrowblock;
 }
 
@@ -362,11 +366,11 @@ bool InventoryScreen::Run() {
 	refresh_gui_screen();
 
 	// NOTE: this is because old code was working with full game screen
-	const int mousex = ::mousex - windowxp;
-	const int mousey = ::mousey - windowyp;
+	const int mouseX = AGS3::mousex - windowxp;
+	const int mouseY = AGS3::mousey - windowyp;
 
-	int isonitem = ((mousey - bartop) / highest) * ICONSPERLINE + (mousex - barxp) / widest;
-	if (mousey <= bartop) isonitem = -1;
+	int isonitem = ((mouseY - bartop) / highest) * ICONSPERLINE + (mouseX - barxp) / widest;
+	if (mouseY <= bartop) isonitem = -1;
 	else if (isonitem >= 0) isonitem += top_item;
 	if ((isonitem < 0) | (isonitem >= numitems) | (isonitem >= top_item + num_visible_items))
 		isonitem = -1;
@@ -377,9 +381,9 @@ bool InventoryScreen::Run() {
 	}
 
 	if (mclick == LEFT) {
-		if ((mousey < 0) | (mousey > windowhit) | (mousex < 0) | (mousex > windowwid))
+		if ((mouseY < 0) | (mouseY > windowhit) | (mouseX < 0) | (mouseX > windowwid))
 			return true; // continue inventory screen loop
-		if (mousey < buttonyp) {
+		if (mouseY < buttonyp) {
 			int clickedon = isonitem;
 			if (clickedon < 0) return true; // continue inventory screen loop
 			evblocknum = dii[clickedon].num;
@@ -430,8 +434,8 @@ bool InventoryScreen::Run() {
 			//        break;
 			return true; // continue inventory screen loop
 		} else {
-			if (mousex >= windowwid - ARROWBUTTONWID) {
-				if (mousey < buttonyp + get_fixed_pixel_size(2) + ARROWBUTTONWID) {
+			if (mouseX >= windowwid - ARROWBUTTONWID) {
+				if (mouseY < buttonyp + get_fixed_pixel_size(2) + ARROWBUTTONWID) {
 					if (top_item > 0) {
 						top_item -= ICONSPERLINE;
 						//ags_domouse(DOMOUSE_DISABLE);
@@ -439,7 +443,7 @@ bool InventoryScreen::Run() {
 						break_code = Redraw();
 						return break_code == 0;
 					}
-				} else if ((mousey < buttonyp + get_fixed_pixel_size(4) + ARROWBUTTONWID * 2) && (top_item + num_visible_items < numitems)) {
+				} else if ((mouseY < buttonyp + get_fixed_pixel_size(4) + ARROWBUTTONWID * 2) && (top_item + num_visible_items < numitems)) {
 					top_item += ICONSPERLINE;
 					//ags_domouse(DOMOUSE_DISABLE);
 
@@ -449,7 +453,7 @@ bool InventoryScreen::Run() {
 				return true; // continue inventory screen loop
 			}
 
-			int buton = mousex - 2;
+			int buton = mouseX - 2;
 			if (buton < 0) return true; // continue inventory screen loop
 			buton /= BUTTONWID;
 			if (buton >= 3) return true; // continue inventory screen loop
@@ -526,10 +530,6 @@ int invscreen() {
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-
 // void (GUIInvWindow *guii)
 RuntimeScriptValue Sc_InvWindow_ScrollDown(void *self, const RuntimeScriptValue *params, int32_t param_count) {
 	API_OBJCALL_VOID(GUIInvWindow, InvWindow_ScrollDown);
diff --git a/engines/ags/engine/ac/keycode.cpp b/engines/ags/engine/ac/keycode.cpp
index c3a790e9cf..b2c1521dff 100644
--- a/engines/ags/engine/ac/keycode.cpp
+++ b/engines/ags/engine/ac/keycode.cpp
@@ -20,8 +20,7 @@
  *
  */
 
-#include "ags/shared/ac/keycode.h"
-
+#include "ags/engine/ac/keycode.h"
 #include "ags/lib/allegro.h"
 
 namespace AGS3 {
@@ -31,10 +30,10 @@ int GetKeyForKeyPressCb(int keycode) {
 	return (keycode >= 'a' && keycode <= 'z') ? keycode - 32 : keycode;
 }
 
-int PlatformKeyFromAgsKey(int key) {
+int PlatformKeyFromAgsKey(int key_) {
 	int platformKey = -1;
 
-	switch (key) {
+	switch (key_) {
 		// ctrl-[A-Z] keys are numbered 1-26 for A-Z
 	case eAGSKeyCodeCtrlA:
 		platformKey = 1;
diff --git a/engines/ags/engine/ac/label.cpp b/engines/ags/engine/ac/label.cpp
index de5c06fa84..29249cef09 100644
--- a/engines/ags/engine/ac/label.cpp
+++ b/engines/ags/engine/ac/label.cpp
@@ -21,11 +21,16 @@
  */
 
 //include <string.h>
-#include "ags/shared/ac/label.h"
+#include "ags/engine/ac/label.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/global_translation.h"
-#include "ags/shared/ac/string.h"
+#include "ags/engine/ac/global_translation.h"
+#include "ags/engine/ac/string.h"
+
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
+#include "ags/engine/ac/dynobj/scriptstring.h"
 
 namespace AGS3 {
 
@@ -92,11 +97,6 @@ void Label_SetFont(GUILabel *guil, int fontnum) {
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-#include "ags/shared/ac/dynobj/scriptstring.h"
-
 extern ScriptString myScriptStringImpl;
 
 // void (GUILabel *labl, char *buffer)
diff --git a/engines/ags/engine/ac/listbox.cpp b/engines/ags/engine/ac/listbox.cpp
index 4753e933c3..081cc25e27 100644
--- a/engines/ags/engine/ac/listbox.cpp
+++ b/engines/ags/engine/ac/listbox.cpp
@@ -20,17 +20,25 @@
  *
  */
 
-//include <set>
-#include "ags/shared/ac/listbox.h"
+#include "ags/std/set.h"
+#include "ags/engine/ac/listbox.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/game.h"
+#include "ags/engine/ac/game.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_game.h"
-#include "ags/shared/ac/path_helper.h"
-#include "ags/shared/ac/string.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_game.h"
+#include "ags/engine/ac/path_helper.h"
+#include "ags/engine/ac/string.h"
 #include "ags/shared/gui/guimain.h"
-#include "ags/shared/debug/debug_log.h"
+#include "ags/engine/debugging/debug_log.h"
+
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
+#include "ags/engine/ac/dynobj/scriptstring.h"
+#include "common/fs.h"
+#include "common/savefile.h"
+#include "ags/ags.h"
 
 namespace AGS3 {
 
@@ -63,13 +71,12 @@ void ListBox_Clear(GUIListBox *listbox) {
 }
 
 void FillDirList(std::set<String> &files, const String &path) {
-	al_ffblk dfb;
-	int dun = al_findfirst(path, &dfb, FA_SEARCH);
-	while (!dun) {
-		files.insert(dfb.name);
-		dun = al_findnext(&dfb);
-	}
-	al_findclose(&dfb);
+	Common::FSNode folder(path);
+	Common::FSList fsList;
+	folder.getChildren(fsList, Common::FSNode::kListAll);
+
+	for (uint idx = 0; idx < fsList.size(); ++idx)
+		files.insert(fsList[idx].getName());
 }
 
 void ListBox_FillDirList(GUIListBox *listbox, const char *filemask) {
@@ -101,34 +108,22 @@ int ListBox_FillSaveGameList(GUIListBox *listbox) {
 	listbox->Clear();
 
 	int numsaves = 0;
-	int bufix = 0;
-	al_ffblk ffb;
 	long filedates[MAXSAVEGAMES];
-	char buff[200];
 
-	String svg_dir = get_save_game_directory();
-	String searchPath = String::FromFormat("%s""agssave.*", svg_dir.GetCStr());
+	SaveStateList saveList = ::AGS::g_vm->listSaves();
 
-	int don = al_findfirst(searchPath, &ffb, FA_SEARCH);
-	while (!don) {
-		bufix = 0;
+	for (uint idx = 0; idx < saveList.size(); ++idx) {
 		if (numsaves >= MAXSAVEGAMES)
 			break;
-		// only list games .000 to .099 (to allow higher slots for other perposes)
-		if (strstr(ffb.name, ".0") == nullptr) {
-			don = al_findnext(&ffb);
-			continue;
-		}
-		const char *numberExtension = strstr(ffb.name, ".0") + 1;
-		int saveGameSlot = atoi(numberExtension);
-		GetSaveSlotDescription(saveGameSlot, buff);
-		listbox->AddItem(buff);
+
+		int saveGameSlot = saveList[idx].getSaveSlot();
+		Common::String desc = saveList[idx].getDescription();
+
+		listbox->AddItem(desc);
 		listbox->SavedGameIndex[numsaves] = saveGameSlot;
-		filedates[numsaves] = (long int)ffb.time;
+		filedates[numsaves] = 0;
 		numsaves++;
-		don = al_findnext(&ffb);
 	}
-	al_findclose(&ffb);
 
 	int nn;
 	for (nn = 0; nn < numsaves - 1; nn++) {
@@ -384,11 +379,6 @@ GUIListBox *is_valid_listbox(int guin, int objn) {
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-#include "ags/shared/ac/dynobj/scriptstring.h"
-
 extern ScriptString myScriptStringImpl;
 
 // int (GUIListBox *lbb, const char *text)
diff --git a/engines/ags/engine/ac/math.cpp b/engines/ags/engine/ac/math.cpp
index 431e6bddb4..2709b632cd 100644
--- a/engines/ags/engine/ac/math.cpp
+++ b/engines/ags/engine/ac/math.cpp
@@ -21,10 +21,15 @@
  */
 
 //include <cmath>
-#include "ags/shared/ac/math.h"
+#include "ags/engine/ac/math.h"
 #include "ags/shared/ac/common.h" // quit
 #include "ags/shared/util/math.h"
 
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
+#include "ags/ags.h"
+
 namespace AGS3 {
 
 int FloatToInt(float value, int roundDirection) {
@@ -137,8 +142,8 @@ float Math_Sqrt(float value) {
 int __Rand(int upto) {
 	upto++;
 	if (upto < 1)
-		quit("!Random: invalid parameter passed -- must be at least 0.");
-	return rand() % upto;
+		quit("!Random: invalid parameter passed -- must be at least 1.");
+	return ::AGS::g_vm->getRandomNumber(upto - 1);
 }
 
 
@@ -148,10 +153,6 @@ int __Rand(int upto) {
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-
 // float (float value)
 RuntimeScriptValue Sc_Math_ArcCos(const RuntimeScriptValue *params, int32_t param_count) {
 	API_SCALL_FLOAT_PFLOAT(Math_ArcCos);
diff --git a/engines/ags/engine/ac/mouse.cpp b/engines/ags/engine/ac/mouse.cpp
index fbfa84fa89..c6780c73d3 100644
--- a/engines/ags/engine/ac/mouse.cpp
+++ b/engines/ags/engine/ac/mouse.cpp
@@ -20,27 +20,32 @@
  *
  */
 
-#include "ags/shared/ac/mouse.h"
+#include "ags/engine/ac/mouse.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/characterinfo.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/dynobj/scriptmouse.h"
-#include "ags/shared/ac/dynobj/scriptsystem.h"
-#include "ags/shared/ac/gamesetup.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/dynobj/scriptmouse.h"
+#include "ags/engine/ac/dynobj/scriptsystem.h"
+#include "ags/engine/ac/gamesetup.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_mouse.h"
-#include "ags/shared/ac/global_plugin.h"
-#include "ags/shared/ac/global_screen.h"
-#include "ags/shared/ac/system.h"
-#include "ags/shared/ac/viewframe.h"
-#include "ags/shared/debug/debug_log.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_mouse.h"
+#include "ags/engine/ac/global_plugin.h"
+#include "ags/engine/ac/global_screen.h"
+#include "ags/engine/ac/system.h"
+#include "ags/engine/ac/viewframe.h"
+#include "ags/engine/debugging/debug_log.h"
 #include "ags/shared/gui/guibutton.h"
 #include "ags/shared/gui/guimain.h"
-#include "ags/shared/device/mousew32.h"
+#include "ags/engine/device/mousew32.h"
 #include "ags/shared/ac/spritecache.h"
-#include "ags/shared/gfx/graphicsdriver.h"
-#include "ags/shared/gfx/gfxfilter.h"
+#include "ags/engine/gfx/graphicsdriver.h"
+#include "ags/engine/gfx/gfxfilter.h"
+
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
+#include "ags/engine/ac/global_game.h"
 
 namespace AGS3 {
 
@@ -455,11 +460,6 @@ int find_previous_enabled_cursor(int startwith) {
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-#include "ags/shared/ac/global_game.h"
-
 // void  (int curs, int newslot)
 RuntimeScriptValue Sc_ChangeCursorGraphic(const RuntimeScriptValue *params, int32_t param_count) {
 	API_SCALL_VOID_PINT2(ChangeCursorGraphic);
diff --git a/engines/ags/engine/ac/movelist.cpp b/engines/ags/engine/ac/movelist.cpp
index 5b6154fc15..4393bfafbb 100644
--- a/engines/ags/engine/ac/movelist.cpp
+++ b/engines/ags/engine/ac/movelist.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/shared/ac/movelist.h"
+#include "ags/engine/ac/movelist.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/util/stream.h"
 
diff --git a/engines/ags/engine/ac/object.cpp b/engines/ags/engine/ac/object.cpp
index bc982e325f..58b52be1a1 100644
--- a/engines/ags/engine/ac/object.cpp
+++ b/engines/ags/engine/ac/object.cpp
@@ -20,31 +20,36 @@
  *
  */
 
-#include "ags/shared/ac/object.h"
+#include "ags/engine/ac/object.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/character.h"
-#include "ags/shared/ac/global_object.h"
-#include "ags/shared/ac/global_translation.h"
-#include "ags/shared/ac/objectcache.h"
-#include "ags/shared/ac/properties.h"
-#include "ags/shared/ac/room.h"
-#include "ags/shared/ac/roomstatus.h"
-#include "ags/shared/ac/runtime_defines.h"
-#include "ags/shared/ac/string.h"
-#include "ags/shared/ac/system.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/character.h"
+#include "ags/engine/ac/global_object.h"
+#include "ags/engine/ac/global_translation.h"
+#include "ags/engine/ac/objectcache.h"
+#include "ags/engine/ac/properties.h"
+#include "ags/engine/ac/room.h"
+#include "ags/engine/ac/roomstatus.h"
+#include "ags/engine/ac/runtime_defines.h"
+#include "ags/engine/ac/string.h"
+#include "ags/engine/ac/system.h"
 #include "ags/shared/ac/view.h"
-#include "ags/shared/ac/walkablearea.h"
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/main/game_run.h"
-#include "ags/shared/ac/route_finder.h"
-#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/engine/ac/walkablearea.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/main/game_run.h"
+#include "ags/engine/ac/route_finder.h"
+#include "ags/engine/gfx/graphicsdriver.h"
 #include "ags/shared/gfx/bitmap.h"
 #include "ags/shared/gfx/gfx_def.h"
-#include "ags/shared/script/runtimescriptvalue.h"
-#include "ags/shared/ac/dynobj/cc_object.h"
-#include "ags/shared/ac/movelist.h"
+#include "ags/engine/script/runtimescriptvalue.h"
+#include "ags/engine/ac/dynobj/cc_object.h"
+#include "ags/engine/ac/movelist.h"
+
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
+#include "ags/engine/ac/dynobj/scriptstring.h"
 
 namespace AGS3 {
 
@@ -558,11 +563,6 @@ int check_click_on_object(int roomx, int roomy, int mood) {
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-#include "ags/shared/ac/dynobj/scriptstring.h"
-
 extern ScriptString myScriptStringImpl;
 
 // void (ScriptObject *objj, int loop, int delay, int repeat, int blocking, int direction)
diff --git a/engines/ags/engine/ac/overlay.cpp b/engines/ags/engine/ac/overlay.cpp
index 5edd4a2554..269bb5dc74 100644
--- a/engines/ags/engine/ac/overlay.cpp
+++ b/engines/ags/engine/ac/overlay.cpp
@@ -20,23 +20,27 @@
  *
  */
 
-#include "ags/shared/ac/overlay.h"
+#include "ags/engine/ac/overlay.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/view.h"
-#include "ags/shared/ac/character.h"
-#include "ags/shared/ac/characterextras.h"
-#include "ags/shared/ac/display.h"
-#include "ags/shared/ac/draw.h"
+#include "ags/engine/ac/character.h"
+#include "ags/engine/ac/characterextras.h"
+#include "ags/engine/ac/display.h"
+#include "ags/engine/ac/draw.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_overlay.h"
-#include "ags/shared/ac/global_translation.h"
-#include "ags/shared/ac/runtime_defines.h"
-#include "ags/shared/ac/screenoverlay.h"
-#include "ags/shared/ac/string.h"
-#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_overlay.h"
+#include "ags/engine/ac/global_translation.h"
+#include "ags/engine/ac/runtime_defines.h"
+#include "ags/engine/ac/screenoverlay.h"
+#include "ags/engine/ac/string.h"
+#include "ags/engine/gfx/graphicsdriver.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/script/runtimescriptvalue.h"
+#include "ags/engine/script/runtimescriptvalue.h"
+
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
 
 namespace AGS3 {
 
@@ -202,7 +206,7 @@ size_t add_screen_overlay(int x, int y, int type, Shared::Bitmap *piccy, int pic
 	if (type == OVER_TEXTMSG) is_text_overlay++;
 	if (type == OVER_CUSTOM) {
 		// find an unused custom ID; TODO: find a better approach!
-		for (int id = OVER_CUSTOM + 1; id < screenover.size() + OVER_CUSTOM + 1; ++id) {
+		for (int id = OVER_CUSTOM + 1; id < (int)screenover.size() + OVER_CUSTOM + 1; ++id) {
 			if (find_overlay_of_type(id) == -1) {
 				type = id;
 				break;
@@ -287,10 +291,6 @@ void recreate_overlay_ddbs() {
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-
 // ScriptOverlay* (int x, int y, int slot, int transparent)
 RuntimeScriptValue Sc_Overlay_CreateGraphical(const RuntimeScriptValue *params, int32_t param_count) {
 	API_SCALL_OBJAUTO_PINT4(ScriptOverlay, Overlay_CreateGraphical);
diff --git a/engines/ags/engine/ac/parser.cpp b/engines/ags/engine/ac/parser.cpp
index bddd826e70..43a3ddc63f 100644
--- a/engines/ags/engine/ac/parser.cpp
+++ b/engines/ags/engine/ac/parser.cpp
@@ -24,14 +24,19 @@
 //include <cstdio>
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/parser.h"
-#include "ags/shared/ac/string.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/parser.h"
+#include "ags/engine/ac/string.h"
 #include "ags/shared/ac/wordsdictionary.h"
-#include "ags/shared/debug/debug_log.h"
+#include "ags/engine/debugging/debug_log.h"
 #include "ags/shared/util/string.h"
 #include "ags/shared/util/string_compat.h"
 
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
+#include "ags/engine/ac/dynobj/scriptstring.h"
+
 namespace AGS3 {
 
 using namespace AGS::Shared;
@@ -89,7 +94,7 @@ int find_word_in_dictionary(const char *lookfor) {
 }
 
 int is_valid_word_char(char theChar) {
-	if ((isalnum((unsigned char)theChar)) || (theChar == '\'') || (theChar == '-')) {
+	if ((Common::isAlnum((unsigned char)theChar)) || (theChar == '\'') || (theChar == '-')) {
 		return 1;
 	}
 	return 0;
@@ -239,7 +244,7 @@ int parse_sentence(const char *src_text, int *numwords, short *wordarray, short
 
 						const char *textStart = &text[1];
 
-						while ((text[0] == ',') || (isalnum((unsigned char)text[0]) != 0))
+						while ((text[0] == ',') || (Common::isAlnum((unsigned char)text[0]) != 0))
 							text++;
 
 						continueSearching = 0;
@@ -301,11 +306,6 @@ int parse_sentence(const char *src_text, int *numwords, short *wordarray, short
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-#include "ags/shared/ac/dynobj/scriptstring.h"
-
 extern ScriptString myScriptStringImpl;
 
 // int (const char *wordToFind)
diff --git a/engines/ags/engine/ac/properties.cpp b/engines/ags/engine/ac/properties.cpp
index 9e1f221546..04988a487e 100644
--- a/engines/ags/engine/ac/properties.cpp
+++ b/engines/ags/engine/ac/properties.cpp
@@ -22,10 +22,10 @@
 
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/properties.h"
-#include "ags/shared/ac/string.h"
-#include "ags/shared/ac/dynobj/scriptstring.h"
-#include "ags/shared/script/runtimescriptvalue.h"
+#include "ags/engine/ac/properties.h"
+#include "ags/engine/ac/string.h"
+#include "ags/engine/ac/dynobj/scriptstring.h"
+#include "ags/engine/script/runtimescriptvalue.h"
 #include "ags/shared/util/string_utils.h"
 
 namespace AGS3 {
@@ -42,7 +42,7 @@ bool get_property_desc(PropertyDesc &desc, const char *property, PropertyType wa
 	if (sch_it == game.propSchema.end())
 		quit("!GetProperty: no such property found in schema. Make sure you are using the property's name, and not its description, when calling this command.");
 
-	desc = sch_it->second;
+	desc = sch_it->_value;
 	if (want_type == kPropertyString && desc.Type != kPropertyString)
 		quit("!GetTextProperty: need to use GetProperty for a non-text property");
 	else if (want_type != kPropertyString && desc.Type == kPropertyString)
@@ -55,10 +55,10 @@ String get_property_value(const StringIMap &st_prop, const StringIMap &rt_prop,
 	// if no matching entry was found, use default schema value
 	StringIMap::const_iterator it = rt_prop.find(property);
 	if (it != rt_prop.end())
-		return it->second;
+		return it->_value;
 	it = st_prop.find(property);
 	if (it != st_prop.end())
-		return it->second;
+		return it->_value;
 	return def_val;
 }
 
diff --git a/engines/ags/engine/ac/properties.h b/engines/ags/engine/ac/properties.h
index ac40ab5b2a..b9873d3c8d 100644
--- a/engines/ags/engine/ac/properties.h
+++ b/engines/ags/engine/ac/properties.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_PROPERTIES_H
 #define AGS_ENGINE_AC_PROPERTIES_H
 
-#include "ags/engine/game/customproperties.h"
+#include "ags/shared/game/customproperties.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/region.cpp b/engines/ags/engine/ac/region.cpp
index 0716dd7d5c..22d628828e 100644
--- a/engines/ags/engine/ac/region.cpp
+++ b/engines/ags/engine/ac/region.cpp
@@ -20,17 +20,21 @@
  *
  */
 
-#include "ags/shared/ac/region.h"
+#include "ags/engine/ac/region.h"
 #include "ags/shared/ac/common_defines.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_region.h"
-#include "ags/shared/ac/room.h"
-#include "ags/shared/ac/roomstatus.h"
-#include "ags/shared/ac/dynobj/cc_region.h"
-#include "ags/shared/ac/dynobj/scriptdrawingsurface.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_region.h"
+#include "ags/engine/ac/room.h"
+#include "ags/engine/ac/roomstatus.h"
+#include "ags/engine/ac/dynobj/cc_region.h"
+#include "ags/engine/ac/dynobj/scriptdrawingsurface.h"
 #include "ags/shared/game/roomstruct.h"
-#include "ags/shared/script/runtimescriptvalue.h"
+#include "ags/engine/script/runtimescriptvalue.h"
+
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
 
 namespace AGS3 {
 
@@ -136,10 +140,6 @@ void generate_light_table() {
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-
 // ScriptRegion *(int xx, int yy)
 RuntimeScriptValue Sc_GetRegionAtRoom(const RuntimeScriptValue *params, int32_t param_count) {
 	API_SCALL_OBJ_PINT2(ScriptRegion, ccDynamicRegion, GetRegionAtRoom);
diff --git a/engines/ags/engine/ac/richgamemedia.cpp b/engines/ags/engine/ac/richgamemedia.cpp
index 4409f1b855..1c09739ddd 100644
--- a/engines/ags/engine/ac/richgamemedia.cpp
+++ b/engines/ags/engine/ac/richgamemedia.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/shared/ac/richgamemedia.h"
+#include "ags/engine/ac/richgamemedia.h"
 #include "ags/shared/util/stream.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/ac/room.cpp b/engines/ags/engine/ac/room.cpp
index 12ce1ec851..1cf81d7c5d 100644
--- a/engines/ags/engine/ac/room.cpp
+++ b/engines/ags/engine/ac/room.cpp
@@ -25,57 +25,62 @@
 #include "ags/shared/core/platform.h"
 #include "ags/shared/util/string_utils.h" //strlwr()
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/charactercache.h"
-#include "ags/shared/ac/characterextras.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/event.h"
-#include "ags/shared/ac/game.h"
-#include "ags/shared/ac/gamesetup.h"
+#include "ags/engine/ac/charactercache.h"
+#include "ags/engine/ac/characterextras.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/event.h"
+#include "ags/engine/ac/game.h"
+#include "ags/engine/ac/gamesetup.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_audio.h"
-#include "ags/shared/ac/global_character.h"
-#include "ags/shared/ac/global_game.h"
-#include "ags/shared/ac/global_object.h"
-#include "ags/shared/ac/global_translation.h"
-#include "ags/shared/ac/movelist.h"
-#include "ags/shared/ac/mouse.h"
-#include "ags/shared/ac/objectcache.h"
-#include "ags/shared/ac/overlay.h"
-#include "ags/shared/ac/properties.h"
-#include "ags/shared/ac/region.h"
-#include "ags/shared/ac/sys_events.h"
-#include "ags/shared/ac/room.h"
-#include "ags/shared/ac/roomobject.h"
-#include "ags/shared/ac/roomstatus.h"
-#include "ags/shared/ac/screen.h"
-#include "ags/shared/ac/string.h"
-#include "ags/shared/ac/system.h"
-#include "ags/shared/ac/walkablearea.h"
-#include "ags/shared/ac/walkbehind.h"
-#include "ags/shared/ac/dynobj/scriptobject.h"
-#include "ags/shared/ac/dynobj/scripthotspot.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_audio.h"
+#include "ags/engine/ac/global_character.h"
+#include "ags/engine/ac/global_game.h"
+#include "ags/engine/ac/global_object.h"
+#include "ags/engine/ac/global_translation.h"
+#include "ags/engine/ac/movelist.h"
+#include "ags/engine/ac/mouse.h"
+#include "ags/engine/ac/objectcache.h"
+#include "ags/engine/ac/overlay.h"
+#include "ags/engine/ac/properties.h"
+#include "ags/engine/ac/region.h"
+#include "ags/engine/ac/sys_events.h"
+#include "ags/engine/ac/room.h"
+#include "ags/engine/ac/roomobject.h"
+#include "ags/engine/ac/roomstatus.h"
+#include "ags/engine/ac/screen.h"
+#include "ags/engine/ac/string.h"
+#include "ags/engine/ac/system.h"
+#include "ags/engine/ac/walkablearea.h"
+#include "ags/engine/ac/walkbehind.h"
+#include "ags/engine/ac/dynobj/scriptobject.h"
+#include "ags/engine/ac/dynobj/scripthotspot.h"
 #include "ags/shared/gui/guidefines.h"
-#include "ags/shared/script/cc_instance.h"
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/debug/debugger.h"
-#include "ags/shared/debug/out.h"
+#include "ags/engine/script/cc_instance.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/debugging/debugger.h"
+#include "ags/shared/debugging/out.h"
 #include "ags/shared/game/room_version.h"
-#include "ags/shared/platform/base/agsplatformdriver.h"
-#include "ags/shared/plugin/agsplugin.h"
-#include "ags/shared/plugin/plugin_engine.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
+#include "ags/engine/plugin/agsplugin.h"
+#include "ags/engine/plugin/plugin_engine.h"
 #include "ags/shared/script/cc_error.h"
-#include "ags/shared/script/script.h"
-#include "ags/shared/script/script_runtime.h"
+#include "ags/engine/script/script.h"
+#include "ags/engine/script/script_runtime.h"
 #include "ags/shared/ac/spritecache.h"
 #include "ags/shared/util/stream.h"
-#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/engine/gfx/graphicsdriver.h"
 #include "ags/shared/core/assetmanager.h"
-#include "ags/shared/ac/dynobj/all_dynamicclasses.h"
+#include "ags/engine/ac/dynobj/all_dynamicclasses.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/gfx/gfxfilter.h"
+#include "ags/engine/gfx/gfxfilter.h"
 #include "ags/shared/util/math.h"
-#include "ags/shared/media/audio/audio_system.h"
+#include "ags/engine/media/audio/audio_system.h"
+
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
+#include "ags/engine/ac/dynobj/scriptstring.h"
 
 namespace AGS3 {
 
@@ -462,8 +467,8 @@ void load_new_room(int newnum, CharacterInfo *forchar) {
 	if (newnum == 0) {
 		// support both room0.crm and intro.crm
 		// 2.70: Renamed intro.crm to room0.crm, to stop it causing confusion
-		if ((loaded_game_file_version < kGameVersion_270 && Common::AssetManager::DoesAssetExist("intro.crm")) ||
-		        (loaded_game_file_version >= kGameVersion_270 && !Common::AssetManager::DoesAssetExist(room_filename))) {
+		if ((loaded_game_file_version < kGameVersion_270 && Shared::AssetManager::DoesAssetExist("intro.crm")) ||
+		        (loaded_game_file_version >= kGameVersion_270 && !Shared::AssetManager::DoesAssetExist(room_filename))) {
 			room_filename = "intro.crm";
 		}
 	}
@@ -1102,11 +1107,6 @@ void convert_move_path_to_room_resolution(MoveList *ml) {
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-#include "ags/shared/ac/dynobj/scriptstring.h"
-
 extern ScriptString myScriptStringImpl;
 
 // ScriptDrawingSurface* (int backgroundNumber)
diff --git a/engines/ags/engine/ac/roomobject.cpp b/engines/ags/engine/ac/roomobject.cpp
index 06ae948f4c..8064201197 100644
--- a/engines/ags/engine/ac/roomobject.cpp
+++ b/engines/ags/engine/ac/roomobject.cpp
@@ -20,14 +20,14 @@
  *
  */
 
-#include "ags/shared/ac/roomobject.h"
+#include "ags/engine/ac/roomobject.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/common_defines.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/runtime_defines.h"
-#include "ags/shared/ac/viewframe.h"
-#include "ags/shared/main/update.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/runtime_defines.h"
+#include "ags/engine/ac/viewframe.h"
+#include "ags/engine/main/update.h"
 #include "ags/shared/util/stream.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/ac/roomstatus.cpp b/engines/ags/engine/ac/roomstatus.cpp
index d523a8d006..d24aff1fa8 100644
--- a/engines/ags/engine/ac/roomstatus.cpp
+++ b/engines/ags/engine/ac/roomstatus.cpp
@@ -24,9 +24,9 @@
 //include <stdlib.h> // free
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/game_version.h"
-#include "ags/shared/ac/roomstatus.h"
+#include "ags/engine/ac/roomstatus.h"
 #include "ags/shared/game/customproperties.h"
-#include "ags/shared/game/savegame_components.h"
+#include "ags/engine/game/savegame_components.h"
 #include "ags/shared/util/alignedstream.h"
 
 namespace AGS3 {
@@ -103,7 +103,7 @@ void RoomStatus::ReadFromFile_v321(Stream *in) {
 }
 
 void RoomStatus::ReadRoomObjects_Aligned(Shared::Stream *in) {
-	AlignedStream align_s(in, Common::kAligned_Read);
+	AlignedStream align_s(in, Shared::kAligned_Read);
 	for (int i = 0; i < MAX_ROOM_OBJECTS; ++i) {
 		obj[i].ReadFromFile(&align_s);
 		align_s.Reset();
diff --git a/engines/ags/engine/ac/route_finder.cpp b/engines/ags/engine/ac/route_finder.cpp
index 2daaff186f..b5722d3b10 100644
--- a/engines/ags/engine/ac/route_finder.cpp
+++ b/engines/ags/engine/ac/route_finder.cpp
@@ -20,12 +20,12 @@
  *
  */
 
-#include "ags/shared/ac/route_finder.h"
+#include "ags/engine/ac/route_finder.h"
 
-#include "ags/shared/ac/route_finder_impl.h"
-#include "ags/shared/ac/route_finder_impl_legacy.h"
+#include "ags/engine/ac/route_finder_impl.h"
+#include "ags/engine/ac/route_finder_impl_legacy.h"
 
-#include "ags/shared/debug/out.h"
+#include "ags/shared/debugging/out.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/route_finder_impl.cpp b/engines/ags/engine/ac/route_finder_impl.cpp
index b62bd5cfb8..13ea1c667a 100644
--- a/engines/ags/engine/ac/route_finder_impl.cpp
+++ b/engines/ags/engine/ac/route_finder_impl.cpp
@@ -26,18 +26,18 @@
 //
 //=============================================================================
 
-#include "ags/shared/ac/route_finder_impl.h"
+#include "ags/engine/ac/route_finder_impl.h"
 
 //include <string.h>
 //include <math.h>
 
 #include "ags/shared/ac/common.h"   // quit()
-#include "ags/shared/ac/movelist.h"     // MoveList
+#include "ags/engine/ac/movelist.h"     // MoveList
 #include "ags/shared/ac/common_defines.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/debug/out.h"
+#include "ags/shared/debugging/out.h"
 
-#include "ags/shared/route_finder_jps.inl"
+#include "ags/engine/ac/route_finder_jps.inl"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/route_finder_impl_legacy.cpp b/engines/ags/engine/ac/route_finder_impl_legacy.cpp
index 88c30f5fd8..067900745e 100644
--- a/engines/ags/engine/ac/route_finder_impl_legacy.cpp
+++ b/engines/ags/engine/ac/route_finder_impl_legacy.cpp
@@ -27,7 +27,7 @@
 //
 //=============================================================================
 
-#include "ags/shared/ac/route_finder_impl_legacy.h"
+#include "ags/engine/ac/route_finder_impl_legacy.h"
 
 //include <string.h>
 //include <math.h>
@@ -35,9 +35,9 @@
 #include "ags/shared/ac/common.h"   // quit()
 #include "ags/shared/ac/common_defines.h"
 #include "ags/shared/game/roomstruct.h"
-#include "ags/shared/ac/movelist.h"     // MoveList
+#include "ags/engine/ac/movelist.h"     // MoveList
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/debug/out.h"
+#include "ags/shared/debugging/out.h"
 
 namespace AGS3 {
 
@@ -123,7 +123,7 @@ void get_lastcpos(int &lastcx_, int &lastcy_) {
 int find_nearest_walkable_area(Bitmap *tempw, int fromX, int fromY, int toX, int toY, int destX, int destY, int granularity) {
 	assert(tempw != nullptr);
 
-	int ex, ey, nearest = 99999, thisis, nearx, neary;
+	int ex, ey, nearest = 99999, thisis, nearx = 0, neary = 0;
 	if (fromX < 0) fromX = 0;
 	if (fromY < 0) fromY = 0;
 	if (toX >= tempw->GetWidth()) toX = tempw->GetWidth() - 1;
diff --git a/engines/ags/engine/ac/route_finder_jps.inl b/engines/ags/engine/ac/route_finder_jps.inl
index 5172e59538..0f21f05c75 100644
--- a/engines/ags/engine/ac/route_finder_jps.inl
+++ b/engines/ags/engine/ac/route_finder_jps.inl
@@ -1,15 +1,25 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
+/* 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.
+ *
+ */
+
 //=============================================================================
 //
 // jump point search grid navigation with navpoint refinement
@@ -17,28 +27,29 @@
 //
 //=============================================================================
 
-//include <queue>
+#include "ags/std/queue.h"
 #include "ags/std/vector.h"
-//include <algorithm>
-//include <functional>
+#include "ags/std/algorithm.h"
+#include "ags/std/functional.h"
+#include "ags/std/xutility.h"
 //include <assert.h>
 //include <stddef.h>
 //include <math.h>
 
+namespace AGS3 {
+
 // TODO: this could be cleaned up/simplified ...
 
 // further optimizations possible:
 //    - forward refinement should use binary search
 
-class Navigation
-{
+class Navigation {
 public:
 	Navigation();
 
 	void Resize(int width, int height);
 
-	enum NavResult
-	{
+	enum NavResult {
 		// unreachable
 		NAV_UNREACHABLE,
 		// straight line exists
@@ -57,15 +68,16 @@ public:
 	bool TraceLine(int srcx, int srcy, int targx, int targy, int &lastValidX, int &lastValidY) const;
 	bool TraceLine(int srcx, int srcy, int targx, int targy, std::vector<int> *rpath = nullptr) const;
 
-	inline void SetMapRow(int y, const unsigned char *row) {map[y] = row;}
+	inline void SetMapRow(int y, const unsigned char *row) {
+		map[y] = row;
+	}
 
 	inline static int PackSquare(int x, int y);
 	inline static void UnpackSquare(int sq, int &x, int &y);
 
 private:
 	// priority queue entry
-	struct Entry
-	{
+	struct Entry {
 		float cost;
 		int index;
 
@@ -73,17 +85,14 @@ private:
 
 		inline Entry(float ncost, int nindex)
 			: cost(ncost)
-			, index(nindex)
-		{
+			, index(nindex) {
 		}
 
-		inline bool operator <(const Entry &b) const
-		{
+		inline bool operator <(const Entry &b) const {
 			return cost < b.cost;
 		}
 
-		inline bool operator >(const Entry &b) const
-		{
+		inline bool operator >(const Entry &b) const {
 			return cost > b.cost;
 		}
 	};
@@ -95,8 +104,7 @@ private:
 	typedef unsigned short tFrameId;
 	typedef int tPrev;
 
-	struct NodeInfo
-	{
+	struct NodeInfo {
 		// quantized min distance from origin
 		unsigned short dist;
 		// frame id (counter to detect new search)
@@ -107,8 +115,7 @@ private:
 		inline NodeInfo()
 			: dist(0)
 			, frameId(0)
-			, prev(-1)
-		{
+			, prev(-1) {
 		}
 	};
 
@@ -118,7 +125,7 @@ private:
 	std::vector<NodeInfo> mapNodes;
 	tFrameId frameId;
 
-	std::priority_queue<Entry, std::vector<Entry>, std::greater<Entry> > pq;
+	std::priority_queue<Entry, std::vector<Entry>, Common::Greater<Entry> > pq;
 
 	// temporary buffers:
 	mutable std::vector<int> fpath;
@@ -151,24 +158,20 @@ private:
 	// neighbor reachable (nodiag only)
 	bool Reachable(int x0, int y0, int x1, int y1) const;
 
-	static inline int sign(int n)
-	{
+	static inline int sign(int n) {
 		return n < 0 ? -1 : (n > 0 ? 1 : 0);
 	}
 
-	static inline int iabs(int n)
-	{
+	static inline int iabs(int n) {
 		return n < 0 ? -n : n;
 	}
 
-	static inline int iclamp(int v, int min, int max)
-	{
+	static inline int iclamp(int v, int min, int max) {
 		return v < min ? min : (v > max ? max : v);
 	}
 
-	static inline int ClosestDist(int dx, int dy)
-	{
-		return dx*dx + dy*dy;
+	static inline int ClosestDist(int dx, int dy) {
+		return dx * dx + dy * dy;
 		// Manhattan?
 		//return iabs(dx) + iabs(dy);
 	}
@@ -189,63 +192,53 @@ Navigation::Navigation()
 	, closest(0)
 	// no diagonal route - this should correspond to what AGS does
 	, nodiag(true)
-	, navLock(false)
-{
+	, navLock(false) {
 }
 
-void Navigation::Resize(int width, int height)
-{
+void Navigation::Resize(int width, int height) {
 	mapWidth = width;
 	mapHeight = height;
 
-	int size = mapWidth*mapHeight;
+	int size = mapWidth * mapHeight;
 
 	map.resize(mapHeight);
 	mapNodes.resize(size);
 }
 
-void Navigation::IncFrameId()
-{
-	if (++frameId == 0)
-	{
-		for (int i=0; i<(int)mapNodes.size(); i++)
+void Navigation::IncFrameId() {
+	if (++frameId == 0) {
+		for (int i = 0; i < (int)mapNodes.size(); i++)
 			mapNodes[i].frameId = 0;
 
 		frameId = 1;
 	}
 }
 
-inline int Navigation::PackSquare(int x, int y)
-{
+inline int Navigation::PackSquare(int x, int y) {
 	return (y << 16) + x;
 }
 
-inline void Navigation::UnpackSquare(int sq, int &x, int &y)
-{
+inline void Navigation::UnpackSquare(int sq, int &x, int &y) {
 	y = sq >> 16;
-	x = sq & ((1 << 16)-1);
+	x = sq & ((1 << 16) - 1);
 }
 
-inline bool Navigation::Outside(int x, int y) const
-{
+inline bool Navigation::Outside(int x, int y) const {
 	return
 		(unsigned)x >= (unsigned)mapWidth ||
 		(unsigned)y >= (unsigned)mapHeight;
 }
 
-inline bool Navigation::Walkable(int x, int y) const
-{
+inline bool Navigation::Walkable(int x, int y) const {
 	// invert condition because of AGS
 	return map[y][x] != 0;
 }
 
-bool Navigation::Passable(int x, int y) const
-{
+bool Navigation::Passable(int x, int y) const {
 	return !Outside(x, y) && Walkable(x, y);
 }
 
-bool Navigation::Reachable(int x0, int y0, int x1, int y1) const
-{
+bool Navigation::Reachable(int x0, int y0, int x1, int y1) const {
 	assert(nodiag);
 
 	return Passable(x1, y1) &&
@@ -254,26 +247,22 @@ bool Navigation::Reachable(int x0, int y0, int x1, int y1) const
 
 // A* using jump point search (JPS)
 // reference: http://users.cecs.anu.edu.au/~dharabor/data/papers/harabor-grastien-aaai11.pdf
-void Navigation::AddPruned(int *buf, int &bcount, int x, int y) const
-{
+void Navigation::AddPruned(int *buf, int &bcount, int x, int y) const {
 	assert(buf && bcount < 8);
 
 	if (Passable(x, y))
 		buf[bcount++] = PackSquare(x, y);
 }
 
-bool Navigation::HasForcedNeighbor(int x, int y, int dx, int dy) const
-{
-	if (!dy)
-	{
-		return  (!Passable(x, y-1) && Passable(x+dx, y-1)) ||
-				(!Passable(x, y+1) && Passable(x+dx, y+1));
+bool Navigation::HasForcedNeighbor(int x, int y, int dx, int dy) const {
+	if (!dy) {
+		return  (!Passable(x, y - 1) && Passable(x + dx, y - 1)) ||
+			(!Passable(x, y + 1) && Passable(x + dx, y + 1));
 	}
 
-	if (!dx)
-	{
-		return  (!Passable(x-1, y) && Passable(x-1, y+dy)) ||
-				(!Passable(x+1, y) && Passable(x+1, y+dy));
+	if (!dx) {
+		return  (!Passable(x - 1, y) && Passable(x - 1, y + dy)) ||
+			(!Passable(x + 1, y) && Passable(x + 1, y + dy));
 	}
 
 	return
@@ -281,12 +270,10 @@ bool Navigation::HasForcedNeighbor(int x, int y, int dx, int dy) const
 		(!Passable(x, y - dy) && Passable(x + dx, y - dy));
 }
 
-int Navigation::FindOrthoJump(int x, int y, int dx, int dy, int ex, int ey)
-{
+int Navigation::FindOrthoJump(int x, int y, int dx, int dy, int ex, int ey) {
 	assert((!dx || !dy) && (dx || dy));
 
-	for (;;)
-	{
+	for (;;) {
 		x += dx;
 		y += dy;
 
@@ -297,8 +284,7 @@ int Navigation::FindOrthoJump(int x, int y, int dx, int dy, int ex, int ey)
 		int edy = y - ey;
 		int edist = ClosestDist(edx, edy);
 
-		if (edist < closest)
-		{
+		if (edist < closest) {
 			closest = edist;
 			cnode = PackSquare(x, y);
 		}
@@ -310,12 +296,11 @@ int Navigation::FindOrthoJump(int x, int y, int dx, int dy, int ex, int ey)
 	return -1;
 }
 
-int Navigation::FindJump(int x, int y, int dx, int dy, int ex, int ey)
-{
+int Navigation::FindJump(int x, int y, int dx, int dy, int ex, int ey) {
 	if (!(dx && dy))
 		return FindOrthoJump(x, y, dx, dy, ex, ey);
 
-	if (nodiag && !Reachable(x, y, x+dx, y+dy))
+	if (nodiag && !Reachable(x, y, x + dx, y + dy))
 		return -1;
 
 	x += dx;
@@ -328,8 +313,7 @@ int Navigation::FindJump(int x, int y, int dx, int dy, int ex, int ey)
 	int edy = y - ey;
 	int edist = ClosestDist(edx, edy);
 
-	if (edist < closest)
-	{
+	if (edist < closest) {
 		closest = edist;
 		cnode = PackSquare(x, y);
 	}
@@ -337,8 +321,7 @@ int Navigation::FindJump(int x, int y, int dx, int dy, int ex, int ey)
 	if ((x == ex && y == ey) || HasForcedNeighbor(x, y, dx, dy))
 		return PackSquare(x, y);
 
-	if (dx && dy)
-	{
+	if (dx && dy) {
 		if (FindOrthoJump(x, y, dx, 0, ex, ey) ||
 			FindOrthoJump(x, y, 0, dy, ex, ey))
 			return PackSquare(x, y);
@@ -347,12 +330,10 @@ int Navigation::FindJump(int x, int y, int dx, int dy, int ex, int ey)
 	return nodiag ? -1 : FindJump(x, y, dx, dy, ex, ey);
 }
 
-Navigation::NavResult Navigation::Navigate(int sx, int sy, int ex, int ey, std::vector<int> &opath)
-{
+Navigation::NavResult Navigation::Navigate(int sx, int sy, int ex, int ey, std::vector<int> &opath) {
 	IncFrameId();
 
-	if (!Passable(sx, sy))
-	{
+	if (!Passable(sx, sy)) {
 		opath.clear();
 		return NAV_UNREACHABLE;
 	}
@@ -361,7 +342,7 @@ Navigation::NavResult Navigation::Navigate(int sx, int sy, int ex, int ey, std::
 	if (!TraceLine(sx, sy, ex, ey, &opath))
 		return NAV_STRAIGHT;
 
-	NodeInfo &ni = mapNodes[sy*mapWidth+sx];
+	NodeInfo &ni = mapNodes[sy * mapWidth + sx];
 	ni.dist = 0;
 	ni.frameId = frameId;
 	ni.prev = -1;
@@ -371,12 +352,11 @@ Navigation::NavResult Navigation::Navigate(int sx, int sy, int ex, int ey, std::
 
 	// no clear for priority queue, like, really?!
 	while (!pq.empty())
-			pq.pop();
+		pq.pop();
 
 	pq.push(Entry(0.0, cnode));
 
-	while (!pq.empty())
-	{
+	while (!pq.empty()) {
 		Entry e = pq.top();
 		pq.pop();
 
@@ -387,19 +367,17 @@ Navigation::NavResult Navigation::Navigate(int sx, int sy, int ex, int ey, std::
 		int dy = y - ey;
 		int edist = ClosestDist(dx, dy);
 
-		if (edist < closest)
-		{
+		if (edist < closest) {
 			closest = edist;
 			cnode = e.index;
 		}
 
-		if (x == ex && y == ey)
-		{
+		if (x == ex && y == ey) {
 			// done
 			break;
 		}
 
-		const NodeInfo &node = mapNodes[y*mapWidth+x];
+		const NodeInfo &node = mapNodes[y * mapWidth + x];
 
 		float dist = node.dist * DIST_SCALE_UNPACK;
 
@@ -408,15 +386,12 @@ Navigation::NavResult Navigation::Navigate(int sx, int sy, int ex, int ey, std::
 
 		int prev = node.prev;
 
-		if (prev < 0)
-		{
-			for (int ny = y-1; ny <= y+1; ny++)
-			{
+		if (prev < 0) {
+			for (int ny = y - 1; ny <= y + 1; ny++) {
 				if ((unsigned)ny >= (unsigned)mapHeight)
 					continue;
 
-				for (int nx = x-1; nx <= x+1; nx++)
-				{
+				for (int nx = x - 1; nx <= x + 1; nx++) {
 					if (nx == x && ny == y)
 						continue;
 
@@ -432,93 +407,82 @@ Navigation::NavResult Navigation::Navigate(int sx, int sy, int ex, int ey, std::
 					pneig[ncount++] = PackSquare(nx, ny);
 				}
 			}
-		}
-		else
-		{
+		} else {
 			// filter
 			int px, py;
 			UnpackSquare(prev, px, py);
-			int dx = sign(x - px);
-			int dy = sign(y - py);
-			assert(dx || dy);
+			int dX = sign(x - px);
+			int dY = sign(y - py);
+			assert(dX || dY);
 
-			if (!dy)
-			{
-				AddPruned(pneig, ncount, x+dx, y);
+			if (!dY) {
+				AddPruned(pneig, ncount, x + dX, y);
 
 				// add corners
-				if (!nodiag || Passable(x+dx, y))
-				{
-					if (!Passable(x, y+1))
-						AddPruned(pneig, ncount, x+dx, y+1);
+				if (!nodiag || Passable(x + dX, y)) {
+					if (!Passable(x, y + 1))
+						AddPruned(pneig, ncount, x + dX, y + 1);
 
-					if (!Passable(x, y-1))
-						AddPruned(pneig, ncount, x+dx, y-1);
+					if (!Passable(x, y - 1))
+						AddPruned(pneig, ncount, x + dX, y - 1);
 				}
-			}
-			else if (!dx)
-			{
+			} else if (!dX) {
 				// same as above but transposed
-				AddPruned(pneig, ncount, x, y+dy);
+				AddPruned(pneig, ncount, x, y + dY);
 
 				// add corners
-				if (!nodiag || Passable(x, y+dy))
-				{
-					if (!Passable(x+1, y))
-						AddPruned(pneig, ncount, x+1, y+dy);
+				if (!nodiag || Passable(x, y + dY)) {
+					if (!Passable(x + 1, y))
+						AddPruned(pneig, ncount, x + 1, y + dY);
 
-					if (!Passable(x-1, y))
-						AddPruned(pneig, ncount, x-1, y+dy);
+					if (!Passable(x - 1, y))
+						AddPruned(pneig, ncount, x - 1, y + dY);
 				}
-			}
-			else
-			{
+			} else {
 				// diagonal case
-				AddPruned(pneig, ncount, x, y+dy);
-				AddPruned(pneig, ncount, x+dx, y);
+				AddPruned(pneig, ncount, x, y + dY);
+				AddPruned(pneig, ncount, x + dX, y);
 
-				if (!nodiag || Reachable(x, y, x+dx, y+dy))
-					AddPruned(pneig, ncount, x+dx, y+dy);
+				if (!nodiag || Reachable(x, y, x + dX, y + dY))
+					AddPruned(pneig, ncount, x + dX, y + dY);
 
-				if (!Passable(x - dx, y) &&
-					(nodiag || Reachable(x, y, x-dx, y+dy)))
-					AddPruned(pneig, ncount, x-dx, y+dy);
+				if (!Passable(x - dX, y) &&
+					(nodiag || Reachable(x, y, x - dX, y + dY)))
+					AddPruned(pneig, ncount, x - dX, y + dY);
 
-				if (!Passable(x, y-dy) &&
-					(nodiag || Reachable(x, y, x+dx, y-dy)))
-					AddPruned(pneig, ncount, x+dx, y-dy);
+				if (!Passable(x, y - dY) &&
+					(nodiag || Reachable(x, y, x + dX, y - dY)))
+					AddPruned(pneig, ncount, x + dX, y - dY);
 			}
 		}
 
 		// sort by heuristics
 		Entry sort[8];
 
-		for (int ni = 0; ni < ncount; ni++)
-		{
+		for (int idx = 0; idx < ncount; idx++) {
 			int nx, ny;
-			UnpackSquare(pneig[ni], nx, ny);
+			UnpackSquare(pneig[idx], nx, ny);
 			float edx = (float)(nx - ex);
 			float edy = (float)(ny - ey);
-			sort[ni].cost = sqrt(edx*edx + edy*edy);
-			sort[ni].index = pneig[ni];
+			sort[idx].cost = sqrt(edx * edx + edy * edy);
+			sort[idx].index = pneig[idx];
 		}
 
-		std::sort(sort, sort+ncount);
+		std::sort(sort, sort + ncount, Common::Less<Entry>());
 
 		int succ[8];
 		int nsucc = 0;
 
-		for (int ni=0; ni<ncount; ni++)
-			pneig[ni] = sort[ni].index;
+		for (int idx = 0; idx < ncount; idx++)
+			pneig[idx] = sort[idx].index;
 
-		for (int ni = 0; ni < ncount; ni ++)
-		{
+		for (int idx = 0; idx < ncount; idx++) {
 			int nx, ny;
-			UnpackSquare(pneig[ni], nx, ny);
+			UnpackSquare(pneig[idx], nx, ny);
 
-			int dx = nx - x;
-			int dy = ny - y;
-			int j = FindJump(x, y, dx, dy, ex, ey);
+			int dX = nx - x;
+			int dY = ny - y;
+			int j = FindJump(x, y, dX, dY, ex, ey);
 
 			if (j < 0)
 				continue;
@@ -526,28 +490,26 @@ Navigation::NavResult Navigation::Navigate(int sx, int sy, int ex, int ey, std::
 			succ[nsucc++] = j;
 		}
 
-		for (int ni = 0; ni < nsucc; ni ++)
-		{
+		for (int idx = 0; idx < nsucc; idx++) {
 			int nx, ny;
-			UnpackSquare(succ[ni], nx, ny);
+			UnpackSquare(succ[idx], nx, ny);
 			assert(Walkable(nx, ny));
 
-			NodeInfo &node = mapNodes[ny*mapWidth+nx];
+			NodeInfo &nodeInfo = mapNodes[ny * mapWidth + nx];
 
-			float ndist = node.frameId != frameId ? INFINITY : node.dist * DIST_SCALE_UNPACK;
+			float ndist = nodeInfo.frameId != frameId ? INFINITY : nodeInfo.dist * DIST_SCALE_UNPACK;
 
-			float dx = (float)(nx - x);
-			float dy = (float)(ny - y);
+			float dX = (float)(nx - x);
+			float dY = (float)(ny - y);
 			// FIXME: can do better here
-			float cost = sqrt(dx*dx + dy*dy);
+			float cost = sqrt(dX * dX + dY * dY);
 			float ecost = dist + cost;
 
 			float edx = (float)(nx - ex);
 			float edy = (float)(ny - ey);
-			float heur = sqrt(edx*edx + edy*edy);
+			float heur = sqrt(edx * edx + edy * edy);
 
-			if (ecost < ndist)
-			{
+			if (ecost < ndist) {
 				ecost *= DIST_SCALE_PACK;
 
 				// assert because we use 16-bit quantized min distance from start to save memory
@@ -556,9 +518,9 @@ Navigation::NavResult Navigation::Navigate(int sx, int sy, int ex, int ey, std::
 				if (ecost > 65535.0f)
 					continue;
 
-				node.dist = (unsigned short)(ecost + 0.5f);
-				node.frameId = frameId;
-				node.prev = PackSquare(x, y);
+				nodeInfo.dist = (unsigned short)(ecost + 0.5f);
+				nodeInfo.frameId = frameId;
+				nodeInfo.prev = PackSquare(x, y);
 				pq.push(Entry(ecost + heur, PackSquare(nx, ny)));
 			}
 		}
@@ -573,8 +535,7 @@ Navigation::NavResult Navigation::Navigate(int sx, int sy, int ex, int ey, std::
 	int nex, ney;
 	UnpackSquare(cnode, nex, ney);
 
-	if ((nex != sx || ney != sy) && (nex != ex || ney != ey))
-	{
+	if ((nex != sx || ney != sy) && (nex != ex || ney != ey)) {
 		// target not directly reachable => move closer to target
 		TraceLine(nex, ney, ex, ey, &opath);
 		UnpackSquare(opath.back(), nex, ney);
@@ -585,8 +546,7 @@ Navigation::NavResult Navigation::Navigate(int sx, int sy, int ex, int ey, std::
 		// infinite recursion should never happen but... better safe than sorry
 		assert(!navLock);
 
-		if (!navLock)
-		{
+		if (!navLock) {
 			// and re-route
 			opath.clear();
 
@@ -601,17 +561,15 @@ Navigation::NavResult Navigation::Navigate(int sx, int sy, int ex, int ey, std::
 		int best = 0x7fffffff;
 		int bestSize = (int)opath.size();
 
-		for (int i=0; i<(int)opath.size(); i++)
-		{
+		for (int i = 0; i < (int)opath.size(); i++) {
 			int x, y;
 			UnpackSquare(opath[i], x, y);
-			int dx = x-ex, dy = y-ey;
+			int dx = x - ex, dy = y - ey;
 			int cost = ClosestDist(dx, dy);
 
-			if (cost < best)
-			{
+			if (cost < best) {
 				best = cost;
-				bestSize = i+1;
+				bestSize = i + 1;
 			}
 		}
 
@@ -621,8 +579,7 @@ Navigation::NavResult Navigation::Navigate(int sx, int sy, int ex, int ey, std::
 	}
 
 	if (ex < 0 || ex >= mapWidth || ey < 0 || ey >= mapHeight ||
-		mapNodes[ey*mapWidth+ex].frameId != frameId)
-	{
+		mapNodes[ey * mapWidth + ex].frameId != frameId) {
 		// path not found
 		return NAV_UNREACHABLE;
 	}
@@ -632,9 +589,8 @@ Navigation::NavResult Navigation::Navigate(int sx, int sy, int ex, int ey, std::
 	// add end
 	opath.push_back(PackSquare(tx, ty));
 
-	for (;;)
-	{
-		int prev = mapNodes[ty*mapWidth+tx].prev;
+	for (;;) {
+		int prev = mapNodes[ty * mapWidth + tx].prev;
 
 		if (prev < 0)
 			break;
@@ -645,8 +601,7 @@ Navigation::NavResult Navigation::Navigate(int sx, int sy, int ex, int ey, std::
 		int dx = sign(px - tx);
 		int dy = sign(py - ty);
 
-		while (tx != px || ty != py)
-		{
+		while (tx != px || ty != py) {
 			tx += dx;
 			ty += dy;
 			opath.push_back(PackSquare(tx, ty));
@@ -658,16 +613,13 @@ Navigation::NavResult Navigation::Navigate(int sx, int sy, int ex, int ey, std::
 }
 
 Navigation::NavResult Navigation::NavigateRefined(int sx, int sy, int ex, int ey,
-	std::vector<int> &opath, std::vector<int> &ncpath)
-{
+	std::vector<int> &opath, std::vector<int> &ncpath) {
 	ncpath.clear();
 
 	NavResult res = Navigate(sx, sy, ex, ey, opath);
 
-	if (res != NAV_PATH)
-	{
-		if (res == NAV_STRAIGHT)
-		{
+	if (res != NAV_PATH) {
+		if (res == NAV_STRAIGHT) {
 			ncpath.push_back(opath[0]);
 			ncpath.push_back(opath.back());
 		}
@@ -692,16 +644,14 @@ Navigation::NavResult Navigation::NavigateRefined(int sx, int sy, int ex, int ey
 	rayPath.reserve(opath.size());
 	orayPath.reserve(opath.size());
 
-	for (int i=1; i<(int)opath.size(); i++)
-	{
+	for (int i = 1; i < (int)opath.size(); i++) {
 		// trying to optimize path
 		int tx, ty;
 		UnpackSquare(opath[i], tx, ty);
 
-		bool last = i == (int)opath.size()-1;
+		bool last = i == (int)opath.size() - 1;
 
-		if (!TraceLine(fx, fy, tx, ty, &rayPath))
-		{
+		if (!TraceLine(fx, fy, tx, ty, &rayPath)) {
 			assert(rayPath.back() == opath[i]);
 			std::swap(rayPath, orayPath);
 
@@ -710,17 +660,15 @@ Navigation::NavResult Navigation::NavigateRefined(int sx, int sy, int ex, int ey
 		}
 
 		// copy orayPath
-		for (int j=1; j<(int)orayPath.size(); j++)
+		for (int j = 1; j < (int)orayPath.size(); j++)
 			fpath.push_back(orayPath[j]);
 
-		if (!orayPath.empty())
-		{
+		if (!orayPath.empty()) {
 			assert(ncpath.back() == orayPath[0]);
 			ncpath.push_back(orayPath.back());
-			ncpathIndex.push_back((int)fpath.size()-1);
+			ncpathIndex.push_back((int)fpath.size() - 1);
 
-			if (!last)
-			{
+			if (!last) {
 				UnpackSquare(orayPath.back(), fx, fy);
 				orayPath.clear();
 				i--;
@@ -731,10 +679,9 @@ Navigation::NavResult Navigation::NavigateRefined(int sx, int sy, int ex, int ey
 		if (fpath.back() != opath[i])
 			fpath.push_back(opath[i]);
 
-		if (ncpath.back() != opath[i])
-		{
+		if (ncpath.back() != opath[i]) {
 			ncpath.push_back(opath[i]);
-			ncpathIndex.push_back((int)fpath.size()-1);
+			ncpathIndex.push_back((int)fpath.size() - 1);
 		}
 
 		fx = tx;
@@ -744,11 +691,10 @@ Navigation::NavResult Navigation::NavigateRefined(int sx, int sy, int ex, int ey
 	std::swap(opath, fpath);
 
 	// validate cpath
-	for (int i=0; i<(int)ncpath.size()-1; i++)
-	{
+	for (int i = 0; i < (int)ncpath.size() - 1; i++) {
 		int tx, ty;
 		UnpackSquare(ncpath[i], fx, fy);
-		UnpackSquare(ncpath[i+1], tx, ty);
+		UnpackSquare(ncpath[i + 1], tx, ty);
 		assert(!TraceLine(fx, fy, tx, ty, &rayPath));
 	}
 
@@ -761,19 +707,17 @@ Navigation::NavResult Navigation::NavigateRefined(int sx, int sy, int ex, int ey
 
 	bool adjusted = false;
 
-	for (int i=(int)ncpath.size()-2; i>0; i--)
-	{
+	for (int i = (int)ncpath.size() - 2; i > 0; i--) {
 		int px, py;
 		int nx, ny;
 
-		int pidx = ncpathIndex[i-1];
+		int pidx = ncpathIndex[i - 1];
 		int idx = ncpathIndex[i];
 
-		UnpackSquare(ncpath[i-1], px, py);
-		UnpackSquare(ncpath[i+1], nx, ny);
+		UnpackSquare(ncpath[i - 1], px, py);
+		UnpackSquare(ncpath[i + 1], nx, ny);
 
-		for (int j=idx-1; j >= pidx; j--)
-		{
+		for (int j = idx - 1; j >= pidx; j--) {
 			int x, y;
 			UnpackSquare(opath[j], x, y);
 
@@ -790,12 +734,11 @@ Navigation::NavResult Navigation::NavigateRefined(int sx, int sy, int ex, int ey
 			adjusted = true;
 		}
 
-		if (ncpath[i] == ncpath[i-1])
-		{
+		if (ncpath[i] == ncpath[i - 1]) {
 			// if we get here, we need to remove ncpath[i]
 			// because we reached the previous node
-			ncpath.erase(ncpath.begin()+i);
-			ncpathIndex.erase(ncpathIndex.begin()+i);
+			ncpath.erase(ncpath.begin() + i);
+			ncpathIndex.erase(ncpathIndex.begin() + i);
 			adjusted = true;
 		}
 	}
@@ -808,25 +751,23 @@ Navigation::NavResult Navigation::NavigateRefined(int sx, int sy, int ex, int ey
 	opath.clear();
 	opath.push_back(ncpath[0]);
 
-	for (int i=1; i<(int)ncpath.size(); i++)
-	{
-		int fx, fy;
+	for (int i = 1; i < (int)ncpath.size(); i++) {
+//		int fx, fy;
 		int tx, ty;
 
-		UnpackSquare(ncpath[i-1], fx, fy);
+		UnpackSquare(ncpath[i - 1], fx, fy);
 		UnpackSquare(ncpath[i], tx, ty);
 
 		TraceLine(fx, fy, tx, ty, &rayPath);
 
-		for (int j=1; j<(int)rayPath.size(); j++)
+		for (int j = 1; j < (int)rayPath.size(); j++)
 			opath.push_back(rayPath[j]);
 	}
 
 	return NAV_PATH;
 }
 
-bool Navigation::TraceLine(int srcx, int srcy, int targx, int targy, int &lastValidX, int &lastValidY) const
-{
+bool Navigation::TraceLine(int srcx, int srcy, int targx, int targy, int &lastValidX, int &lastValidY) const {
 	lastValidX = srcx;
 	lastValidY = srcy;
 
@@ -838,8 +779,7 @@ bool Navigation::TraceLine(int srcx, int srcy, int targx, int targy, int &lastVa
 	return res;
 }
 
-bool Navigation::TraceLine(int srcx, int srcy, int targx, int targy, std::vector<int> *rpath) const
-{
+bool Navigation::TraceLine(int srcx, int srcy, int targx, int targy, std::vector<int> *rpath) const {
 	if (rpath)
 		rpath->clear();
 
@@ -852,8 +792,7 @@ bool Navigation::TraceLine(int srcx, int srcy, int targx, int targy, std::vector
 	int dx = x1 - x0;
 	int dy = y1 - y0;
 
-	if (!dx && !dy)
-	{
+	if (!dx && !dy) {
 		if (!Passable(srcx, srcy))
 			return true;
 
@@ -865,14 +804,11 @@ bool Navigation::TraceLine(int srcx, int srcy, int targx, int targy, std::vector
 
 	int xinc, yinc;
 
-	if (iabs(dx) >= iabs(dy))
-	{
+	if (iabs(dx) >= iabs(dy)) {
 		// step along x
 		xinc = sign(dx) * 65536;
 		yinc = (int)((double)dy * 65536 / iabs(dx));
-	}
-	else
-	{
+	} else {
 		// step along y
 		yinc = sign(dy) * 65536;
 		xinc = (int)((double)dx * 65536 / iabs(dy));
@@ -885,8 +821,7 @@ bool Navigation::TraceLine(int srcx, int srcy, int targx, int targy, std::vector
 	int ex = x1 >> 16;
 	int ey = y1 >> 16;
 
-	while (x != ex || y != ey)
-	{
+	while (x != ex || y != ey) {
 		if (!Passable(x, y))
 			return true;
 
@@ -919,3 +854,5 @@ bool Navigation::TraceLine(int srcx, int srcy, int targx, int targy, std::vector
 
 	return false;
 }
+
+} // namespace AGS3
diff --git a/engines/ags/engine/ac/screen.cpp b/engines/ags/engine/ac/screen.cpp
index 15ddac6f35..9306c4ac88 100644
--- a/engines/ags/engine/ac/screen.cpp
+++ b/engines/ags/engine/ac/screen.cpp
@@ -21,20 +21,20 @@
  */
 
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/draw.h"
+#include "ags/engine/ac/draw.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_game.h"
-#include "ags/shared/ac/global_screen.h"
-#include "ags/shared/ac/screen.h"
-#include "ags/shared/ac/dynobj/scriptviewport.h"
-#include "ags/shared/ac/dynobj/scriptuserobject.h"
-#include "ags/shared/script/script_runtime.h"
-#include "ags/shared/platform/base/agsplatformdriver.h"
-#include "ags/shared/plugin/agsplugin.h"
-#include "ags/shared/plugin/plugin_engine.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_game.h"
+#include "ags/engine/ac/global_screen.h"
+#include "ags/engine/ac/screen.h"
+#include "ags/engine/ac/dynobj/scriptviewport.h"
+#include "ags/engine/ac/dynobj/scriptuserobject.h"
+#include "ags/engine/script/script_runtime.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
+#include "ags/engine/plugin/agsplugin.h"
+#include "ags/engine/plugin/plugin_engine.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/engine/gfx/graphicsdriver.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/screenoverlay.cpp b/engines/ags/engine/ac/screenoverlay.cpp
index fadd6e6c2e..c4c133e67f 100644
--- a/engines/ags/engine/ac/screenoverlay.cpp
+++ b/engines/ags/engine/ac/screenoverlay.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/shared/screenoverlay.h"
+#include "ags/engine/ac/screenoverlay.h"
 #include "ags/shared/util/stream.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/ac/scriptcontainers.cpp b/engines/ags/engine/ac/scriptcontainers.cpp
index 148832bda5..e67e3a1ed3 100644
--- a/engines/ags/engine/ac/scriptcontainers.cpp
+++ b/engines/ags/engine/ac/scriptcontainers.cpp
@@ -27,14 +27,14 @@
 //=============================================================================
 
 #include "ags/shared/ac/common.h" // quit
-#include "ags/shared/ac/string.h"
-#include "ags/shared/ac/dynobj/cc_dynamicarray.h"
-#include "ags/shared/ac/dynobj/cc_dynamicobject.h"
-#include "ags/shared/ac/dynobj/scriptdict.h"
-#include "ags/shared/ac/dynobj/scriptset.h"
-#include "ags/shared/ac/dynobj/scriptstring.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
+#include "ags/engine/ac/string.h"
+#include "ags/engine/ac/dynobj/cc_dynamicarray.h"
+#include "ags/engine/ac/dynobj/cc_dynamicobject.h"
+#include "ags/engine/ac/dynobj/scriptdict.h"
+#include "ags/engine/ac/dynobj/scriptset.h"
+#include "ags/engine/ac/dynobj/scriptstring.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
 #include "ags/shared/util/bbop.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/ac/slider.cpp b/engines/ags/engine/ac/slider.cpp
index 89589b80e3..005570b2e3 100644
--- a/engines/ags/engine/ac/slider.cpp
+++ b/engines/ags/engine/ac/slider.cpp
@@ -20,9 +20,13 @@
  *
  */
 
-#include "ags/shared/ac/slider.h"
+#include "ags/engine/ac/slider.h"
 #include "ags/shared/ac/common.h"
 
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
+
 namespace AGS3 {
 
 // *** SLIDER FUNCTIONS
@@ -118,10 +122,6 @@ void Slider_SetHandleOffset(GUISlider *guisl, int newOffset) {
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-
 // int (GUISlider *guisl)
 RuntimeScriptValue Sc_Slider_GetBackgroundGraphic(void *self, const RuntimeScriptValue *params, int32_t param_count) {
 	API_OBJCALL_INT(GUISlider, Slider_GetBackgroundGraphic);
diff --git a/engines/ags/engine/ac/speech.cpp b/engines/ags/engine/ac/speech.cpp
index 08b2584ebc..8164c12362 100644
--- a/engines/ags/engine/ac/speech.cpp
+++ b/engines/ags/engine/ac/speech.cpp
@@ -21,9 +21,17 @@
  */
 
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/runtime_defines.h"
-#include "ags/shared/ac/speech.h"
-#include "ags/shared/debug/debug_log.h"
+#include "ags/engine/ac/runtime_defines.h"
+#include "ags/engine/ac/speech.h"
+#include "ags/engine/debugging/debug_log.h"
+
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_audio.h"
+#include "ags/engine/ac/global_display.h"
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
 
 namespace AGS3 {
 
@@ -78,14 +86,6 @@ SkipSpeechStyle internal_skip_speech_to_user(int internal_val) {
 //
 //=============================================================================
 
-#include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_audio.h"
-#include "ags/shared/ac/global_display.h"
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-
 extern GameSetupStruct game;
 extern GameState play;
 
diff --git a/engines/ags/engine/ac/sprite.cpp b/engines/ags/engine/ac/sprite.cpp
index 4220305ce9..e8e1f2eeee 100644
--- a/engines/ags/engine/ac/sprite.cpp
+++ b/engines/ags/engine/ac/sprite.cpp
@@ -21,16 +21,16 @@
  */
 
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/draw.h"
+#include "ags/engine/ac/draw.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/sprite.h"
-#include "ags/shared/ac/system.h"
-#include "ags/shared/platform/base/agsplatformdriver.h"
-#include "ags/shared/plugin/agsplugin.h"
-#include "ags/shared/plugin/plugin_engine.h"
+#include "ags/engine/ac/sprite.h"
+#include "ags/engine/ac/system.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
+#include "ags/engine/plugin/agsplugin.h"
+#include "ags/engine/plugin/plugin_engine.h"
 #include "ags/shared/ac/spritecache.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/engine/gfx/graphicsdriver.h"
 
 namespace AGS3 {
 
@@ -158,7 +158,7 @@ void initialize_sprite(int ee) {
 				quit("Not enough memory to load sprite graphics");
 			tmpdbl->Acquire();
 			curspr->Acquire();
-			tmpdbl->StretchBlt(curspr, RectWH(0, 0, tmpdbl->GetWidth(), tmpdbl->GetHeight()), Common::kBitmap_Transparency);
+			tmpdbl->StretchBlt(curspr, RectWH(0, 0, tmpdbl->GetWidth(), tmpdbl->GetHeight()), Shared::kBitmap_Transparency);
 			curspr->Release();
 			tmpdbl->Release();
 			delete curspr;
diff --git a/engines/ags/engine/ac/string.cpp b/engines/ags/engine/ac/string.cpp
index 60a963a50a..283be7111f 100644
--- a/engines/ags/engine/ac/string.cpp
+++ b/engines/ags/engine/ac/string.cpp
@@ -30,10 +30,15 @@
 #include "ags/shared/ac/runtime_defines.h"
 #include "ags/shared/ac/dynobj/scriptstring.h"
 #include "ags/shared/font/fonts.h"
-#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/debugging/debug_log.h"
 #include "ags/shared/script/runtimescriptvalue.h"
 #include "ags/shared/util/string_compat.h"
 
+#include "ags/shared/debugging/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
+#include "ags/shared/ac/math.h"
+
 namespace AGS3 {
 
 extern GameSetupStruct game;
@@ -298,11 +303,6 @@ void my_strncpy(char *dest, const char *src, int len) {
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-#include "ags/shared/ac/math.h"
-
 // int (const char *thisString)
 RuntimeScriptValue Sc_String_IsNullOrEmpty(const RuntimeScriptValue *params, int32_t param_count) {
 	API_SCALL_INT_POBJ(String_IsNullOrEmpty, const char);
diff --git a/engines/ags/engine/ac/sys_events.cpp b/engines/ags/engine/ac/sys_events.cpp
index 467e80a13d..7142cb7792 100644
--- a/engines/ags/engine/ac/sys_events.cpp
+++ b/engines/ags/engine/ac/sys_events.cpp
@@ -23,13 +23,13 @@
 #include "ags/shared/core/platform.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/keycode.h"
-#include "ags/shared/ac/mouse.h"
-#include "ags/shared/ac/sys_events.h"
-#include "ags/shared/device/mousew32.h"
-#include "ags/shared/platform/base/agsplatformdriver.h"
-#include "ags/shared/ac/timer.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/keycode.h"
+#include "ags/engine/ac/mouse.h"
+#include "ags/engine/ac/sys_events.h"
+#include "ags/engine/device/mousew32.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
+#include "ags/engine/ac/timer.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/system.cpp b/engines/ags/engine/ac/system.cpp
index 873b11ee98..6c52eb2b51 100644
--- a/engines/ags/engine/ac/system.cpp
+++ b/engines/ags/engine/ac/system.cpp
@@ -29,8 +29,8 @@
 #include "ags/shared/ac/string.h"
 #include "ags/shared/ac/system.h"
 #include "ags/shared/ac/dynobj/scriptsystem.h"
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/debug/out.h"
+#include "ags/shared/debugging/debug_log.h"
+#include "ags/shared/debugging/out.h"
 #include "ags/shared/main/engine.h"
 #include "ags/shared/main/main.h"
 #include "ags/shared/gfx/graphicsdriver.h"
@@ -41,6 +41,11 @@
 #include "ags/shared/media/audio/audio_system.h"
 #include "ags/shared/util/string_compat.h"
 
+#include "ags/shared/debugging/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
+#include "ags/shared/ac/dynobj/scriptstring.h"
+
 namespace AGS3 {
 
 using namespace AGS::Shared;
@@ -227,11 +232,6 @@ void System_SetRenderAtScreenResolution(int enable) {
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-#include "ags/shared/ac/dynobj/scriptstring.h"
-
 extern ScriptString myScriptStringImpl;
 
 // int ()
diff --git a/engines/ags/engine/ac/textbox.cpp b/engines/ags/engine/ac/textbox.cpp
index f4dfa5809b..9a926db00c 100644
--- a/engines/ags/engine/ac/textbox.cpp
+++ b/engines/ags/engine/ac/textbox.cpp
@@ -26,6 +26,11 @@
 #include "ags/shared/ac/gamesetupstruct.h"
 #include "ags/shared/ac/string.h"
 
+#include "ags/shared/debugging/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
+#include "ags/shared/ac/dynobj/scriptstring.h"
+
 namespace AGS3 {
 
 extern GameSetupStruct game;
@@ -90,11 +95,6 @@ void TextBox_SetShowBorder(GUITextBox *guit, bool on) {
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-#include "ags/shared/ac/dynobj/scriptstring.h"
-
 extern ScriptString myScriptStringImpl;
 
 // void (GUITextBox *texbox, char *buffer)
diff --git a/engines/ags/engine/ac/translation.cpp b/engines/ags/engine/ac/translation.cpp
index 3c2892b583..64c065b308 100644
--- a/engines/ags/engine/ac/translation.cpp
+++ b/engines/ags/engine/ac/translation.cpp
@@ -31,7 +31,7 @@
 #include "ags/shared/ac/translation.h"
 #include "ags/shared/ac/tree_map.h"
 #include "ags/shared/ac/wordsdictionary.h"
-#include "ags/shared/debug/out.h"
+#include "ags/shared/debugging/out.h"
 #include "ags/shared/util/misc.h"
 #include "ags/shared/util/stream.h"
 #include "ags/shared/core/assetmanager.h"
diff --git a/engines/ags/engine/ac/viewframe.cpp b/engines/ags/engine/ac/viewframe.cpp
index 41ab83b027..5461f4b1f9 100644
--- a/engines/ags/engine/ac/viewframe.cpp
+++ b/engines/ags/engine/ac/viewframe.cpp
@@ -22,7 +22,7 @@
 
 #include "ags/shared/ac/gamesetupstruct.h"
 #include "ags/shared/ac/viewframe.h"
-#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/debugging/debug_log.h"
 #include "ags/shared/ac/spritecache.h"
 #include "ags/shared/gfx/bitmap.h"
 #include "ags/shared/script/runtimescriptvalue.h"
@@ -31,6 +31,10 @@
 #include "ags/shared/ac/game_version.h"
 #include "ags/shared/media/audio/audio_system.h"
 
+#include "ags/shared/debugging/out.h"
+#include "ags/shared/script/script_api.h"
+#include "ags/shared/script/script_runtime.h"
+
 } // namespace AGS3
 
 using AGS::Shared::Bitmap;
@@ -159,16 +163,16 @@ void DrawViewFrame(Bitmap *ds, const ViewFrame *vframe, int x, int y, bool alpha
 		Bitmap *src = vf_bmp;
 		if (vframe->flags & VFLG_FLIPSPRITE) {
 			src = new Bitmap(vf_bmp->GetWidth(), vf_bmp->GetHeight(), vf_bmp->GetColorDepth());
-			src->FlipBlt(vf_bmp, 0, 0, Common::kBitmap_HFlip);
+			src->FlipBlt(vf_bmp, 0, 0, Shared::kBitmap_HFlip);
 		}
 		draw_sprite_support_alpha(ds, true, x, y, src, (game.SpriteInfos[vframe->pic].Flags & SPF_ALPHACHANNEL) != 0);
 		if (src != vf_bmp)
 			delete src;
 	} else {
 		if (vframe->flags & VFLG_FLIPSPRITE)
-			ds->FlipBlt(spriteset[vframe->pic], x, y, Common::kBitmap_HFlip);
+			ds->FlipBlt(spriteset[vframe->pic], x, y, Shared::kBitmap_HFlip);
 		else
-			ds->Blit(spriteset[vframe->pic], x, y, Common::kBitmap_Transparency);
+			ds->Blit(spriteset[vframe->pic], x, y, Shared::kBitmap_Transparency);
 	}
 }
 
@@ -178,10 +182,6 @@ void DrawViewFrame(Bitmap *ds, const ViewFrame *vframe, int x, int y, bool alpha
 //
 //=============================================================================
 
-#include "ags/shared/debug/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-
 // int (ScriptViewFrame *svf)
 RuntimeScriptValue Sc_ViewFrame_GetFlipped(void *self, const RuntimeScriptValue *params, int32_t param_count) {
 	API_OBJCALL_INT(ScriptViewFrame, ViewFrame_GetFlipped);
diff --git a/engines/ags/engine/ac/viewport_script.cpp b/engines/ags/engine/ac/viewport_script.cpp
index e145c78d96..5d0c2672d8 100644
--- a/engines/ags/engine/ac/viewport_script.cpp
+++ b/engines/ags/engine/ac/viewport_script.cpp
@@ -31,7 +31,7 @@
 #include "ags/shared/ac/dynobj/scriptuserobject.h"
 #include "ags/shared/ac/draw.h"
 #include "ags/shared/ac/gamestate.h"
-#include "ags/shared/debug/debug_log.h"
+#include "ags/shared/debugging/debug_log.h"
 #include "ags/shared/script/script_api.h"
 #include "ags/shared/script/script_runtime.h"
 
diff --git a/engines/ags/engine/debugging/dummyagsdebugger.h b/engines/ags/engine/debugging/dummyagsdebugger.h
index cc1158755a..efbdb3a295 100644
--- a/engines/ags/engine/debugging/dummyagsdebugger.h
+++ b/engines/ags/engine/debugging/dummyagsdebugger.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_DEBUGGING_DUMMYAGSDEBUGGER_H
 #define AGS_ENGINE_DEBUGGING_DUMMYAGSDEBUGGER_H
 
-#include "ags/shared/debug/debugger.h"
+#include "ags/engine/debugging/debugger.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/main/main.cpp b/engines/ags/engine/main/main.cpp
index a70fb04f86..de0b2b72ea 100644
--- a/engines/ags/engine/main/main.cpp
+++ b/engines/ags/engine/main/main.cpp
@@ -38,9 +38,9 @@
 #include "ags/shared/ac/gamesetup.h"
 #include "ags/shared/ac/gamestate.h"
 #include "ags/shared/core/def_version.h"
-#include "ags/shared/debug/debugger.h"
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/debug/out.h"
+#include "ags/shared/debugging/debugger.h"
+#include "ags/shared/debugging/debug_log.h"
+#include "ags/shared/debugging/out.h"
 #include "ags/shared/main/config.h"
 #include "ags/shared/main/engine.h"
 #include "ags/shared/main/mainheader.h"
diff --git a/engines/ags/engine/media/audio/audio.cpp b/engines/ags/engine/media/audio/audio.cpp
index f7db003f40..414db622ae 100644
--- a/engines/ags/engine/media/audio/audio.cpp
+++ b/engines/ags/engine/media/audio/audio.cpp
@@ -36,8 +36,8 @@
 #include "ags/shared/ac/gamesetup.h"
 #include "ags/shared/ac/path_helper.h"
 #include "ags/shared/media/audio/sound.h"
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/debug/debugger.h"
+#include "ags/shared/debugging/debug_log.h"
+#include "ags/shared/debugging/debugger.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/file.h"
 #include "ags/shared/ac/global_audio.h"
diff --git a/engines/ags/engine/media/audio/soundcache.cpp b/engines/ags/engine/media/audio/soundcache.cpp
index 0ca7dde4a5..dcf4136ac3 100644
--- a/engines/ags/engine/media/audio/soundcache.cpp
+++ b/engines/ags/engine/media/audio/soundcache.cpp
@@ -29,7 +29,7 @@
 #include "ags/shared/util/mutex.h"
 #include "ags/shared/util/mutex_lock.h"
 #include "ags/shared/util/string.h"
-#include "ags/shared/debug/out.h"
+#include "ags/shared/debugging/out.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/media/video/video.cpp b/engines/ags/engine/media/video/video.cpp
index 930a5bc797..9372858dfb 100644
--- a/engines/ags/engine/media/video/video.cpp
+++ b/engines/ags/engine/media/video/video.cpp
@@ -29,8 +29,8 @@
 #define AGS_FLI_FROM_PACK_FILE ((ALLEGRO_DATE >= 20190303) || \
                                 AGS_PLATFORM_OS_WINDOWS || AGS_PLATFORM_OS_ANDROID || AGS_PLATFORM_OS_MACOS)
 
-#include "ags/shared/debug/debug_log.h"
-#include "ags/shared/debug/out.h"
+#include "ags/shared/debugging/debug_log.h"
+#include "ags/shared/debugging/out.h"
 #include "ags/shared/ac/asset_helper.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/draw.h"
diff --git a/engines/ags/engine/platform/linux/acpllnx.cpp b/engines/ags/engine/platform/linux/acpllnx.cpp
index 4c44c0afcf..f0279b6602 100644
--- a/engines/ags/engine/platform/linux/acpllnx.cpp
+++ b/engines/ags/engine/platform/linux/acpllnx.cpp
@@ -100,10 +100,10 @@ size_t BuildXDGPath(char *destPath, size_t destSize) {
 		// No evironment variable, so we fall back to home dir in /etc/passwd
 		struct passwd *p = getpwuid(getuid());
 		l = snprintf(destPath, destSize, "%s/.local", p->pw_dir);
-		if (mkdir(destPath, 0755) != 0 && errno != EEXIST)
+		if (mkdir(destPath, 0755) != 0 && errnum != EEXIST)
 			return 0;
 		l += snprintf(destPath + l, destSize - l, "/share");
-		if (mkdir(destPath, 0755) != 0 && errno != EEXIST)
+		if (mkdir(destPath, 0755) != 0 && errnum != EEXIST)
 			return 0;
 	}
 	return l;
diff --git a/engines/ags/engine/platform/windows/acplwin.cpp b/engines/ags/engine/platform/windows/acplwin.cpp
index 9f300fb1e1..eda5ca2d98 100644
--- a/engines/ags/engine/platform/windows/acplwin.cpp
+++ b/engines/ags/engine/platform/windows/acplwin.cpp
@@ -36,7 +36,7 @@
 #include "ags/shared/ac/global_display.h"
 #include "ags/shared/ac/runtime_defines.h"
 #include "ags/shared/ac/string.h"
-#include "ags/shared/debug/out.h"
+#include "ags/shared/debugging/out.h"
 #include "ags/shared/gfx/graphicsdriver.h"
 #include "ags/shared/gfx/bitmap.h"
 #include "ags/shared/main/engine.h"
@@ -618,7 +618,7 @@ void DetermineAppOutputDirectory() {
 	if (win32SavedGamesDirectory[0]) {
 		win32OutputDirectory = win32SavedGamesDirectory;
 		win32OutputDirectory.Append("\\.ags");
-		log_to_saves_dir = mkdir(win32OutputDirectory) == 0 || errno == EEXIST;
+		log_to_saves_dir = mkdir(win32OutputDirectory) == 0 || errnum == EEXIST;
 	}
 
 	if (!log_to_saves_dir) {
diff --git a/engines/ags/engine/platform/windows/debugging/namedpipesagsdebugger.h b/engines/ags/engine/platform/windows/debugging/namedpipesagsdebugger.h
index 6e7b86d43f..879f95faa2 100644
--- a/engines/ags/engine/platform/windows/debugging/namedpipesagsdebugger.h
+++ b/engines/ags/engine/platform/windows/debugging/namedpipesagsdebugger.h
@@ -25,7 +25,7 @@
 
 //include <windows.h>
 //include <io.h>
-#include "ags/shared/debug/agseditordebugger.h"
+#include "ags/shared/debugging/agseditordebugger.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp b/engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
index 3a28afb3ba..269c5b0507 100644
--- a/engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
+++ b/engines/ags/engine/platform/windows/gfx/ali3dd3d.cpp
@@ -35,8 +35,8 @@
 #include "ags/lib/allegro.h"
 //include <allegro/platform/aintwin.h>
 #include "ags/shared/ac/timer.h"
-#include "ags/shared/debug/assert.h"
-#include "ags/shared/debug/out.h"
+#include "ags/shared/debugging/assert.h"
+#include "ags/shared/debugging/out.h"
 #include "ags/shared/gfx/ali3dexception.h"
 #include "ags/shared/gfx/gfxfilter_d3d.h"
 #include "ags/shared/gfx/gfxfilter_aad3d.h"
diff --git a/engines/ags/engine/platform/windows/win_ex_handling.cpp b/engines/ags/engine/platform/windows/win_ex_handling.cpp
index aeffbc23c9..de3fcd9150 100644
--- a/engines/ags/engine/platform/windows/win_ex_handling.cpp
+++ b/engines/ags/engine/platform/windows/win_ex_handling.cpp
@@ -28,8 +28,8 @@
 //include <winalleg.h>
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/common_defines.h"
-#include "ags/shared/debug/debugger.h"
-#include "ags/shared/debug/out.h"
+#include "ags/shared/debugging/debugger.h"
+#include "ags/shared/debugging/out.h"
 #include "ags/shared/main/main.h"
 #include "ags/shared/util/ini_util.h"
 
diff --git a/engines/ags/engine/util/library_psp.h b/engines/ags/engine/util/library_psp.h
index 64bbdf1d1d..10b95d2431 100644
--- a/engines/ags/engine/util/library_psp.h
+++ b/engines/ags/engine/util/library_psp.h
@@ -25,7 +25,7 @@
 
 //include <pspsdk.h>
 #include "ags/shared/util/string.h"
-#include "ags/shared/debug/out.h"
+#include "ags/shared/debugging/out.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/util/library_windows.h b/engines/ags/engine/util/library_windows.h
index 4ce9b74e41..8f7c2ab881 100644
--- a/engines/ags/engine/util/library_windows.h
+++ b/engines/ags/engine/util/library_windows.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_UTIL_LIBRARY_WINDOWS_H
 #define AGS_ENGINE_UTIL_LIBRARY_WINDOWS_H
 
-#include "ags/shared/debug/out.h"
+#include "ags/shared/debugging/out.h"
 #include "ags/shared/platform/windows/winapi_exclusive.h"
 #include "ags/shared/util/string.h"
 
diff --git a/engines/ags/lib/aldumb.h b/engines/ags/lib/aldumb.h
new file mode 100644
index 0000000000..b72dc823d8
--- /dev/null
+++ b/engines/ags/lib/aldumb.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.
+ *
+ */
+
+/*  _______         ____    __         ___    ___
+ * \    _  \       \    /  \  /       \   \  /   /       '   '  '
+ *  |  | \  \       |  |    ||         |   \/   |         .      .
+ *  |  |  |  |      |  |    ||         ||\  /|  |
+ *  |  |  |  |      |  |    ||         || \/ |  |         '  '  '
+ *  |  |  |  |      |  |    ||         ||    |  |         .      .
+ *  |  |_/  /        \  \__//          ||    |  |
+ * /_______/ynamic    \____/niversal  /__\  /____\usic   /|  .  . ibliotheque
+ *                                                      /  \
+ *                                                     / .  \
+ * aldumb.h - The user header file for DUMB with      / / \  \
+ *            Allegro.                               | <  /   \_
+ *                                                   |  \/ /\   /
+ * Include this file if you wish to use DUMB          \_  /  > /
+ * with Allegro. It will include dumb.h for you,        | \ / /
+ * and provide extra functionality such as audio        |  ' /
+ * stream and datafile integration.                      \__/
+ */
+
+#ifndef AGS_LIB_ALDUMB_H
+#define AGS_LIB_ALDUMB_H
+
+#include "ags/lib/allegro.h"
+#include "ags/lib/dumb.h"
+
+namespace AGS3 {
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Packfile Support */
+
+void dumb_register_packfiles(void);
+
+DUMBFILE *dumbfile_open_packfile(PACKFILE *p);
+DUMBFILE *dumbfile_from_packfile(PACKFILE *p);
+
+
+/* Datafile Registration Functions */
+
+#define DUMB_DAT_DUH DAT_ID('D','U','H',' ')
+#define DUMB_DAT_IT  DAT_ID('I','T',' ',' ')
+#define DUMB_DAT_XM  DAT_ID('X','M',' ',' ')
+#define DUMB_DAT_S3M DAT_ID('S','3','M',' ')
+#define DUMB_DAT_MOD DAT_ID('M','O','D',' ')
+
+void dumb_register_dat_duh(long type);
+void dumb_register_dat_it(long type);
+void dumb_register_dat_xm(long type);
+void dumb_register_dat_s3m(long type);
+void dumb_register_dat_mod(long type);
+void dumb_register_dat_it_quick(long type);
+void dumb_register_dat_xm_quick(long type);
+void dumb_register_dat_s3m_quick(long type);
+void dumb_register_dat_mod_quick(long type);
+
+
+/* DUH Playing Functions */
+
+typedef struct AL_DUH_PLAYER AL_DUH_PLAYER;
+
+AL_DUH_PLAYER *al_start_duh(DUH *duh, int n_channels, long pos, float volume, long bufsize, int freq);
+void al_stop_duh(AL_DUH_PLAYER *dp);
+void al_pause_duh(AL_DUH_PLAYER *dp);
+void al_resume_duh(AL_DUH_PLAYER *dp);
+void al_duh_set_priority(AL_DUH_PLAYER *dp, int priority);
+void al_duh_set_volume(AL_DUH_PLAYER *dp, float volume);
+float al_duh_get_volume(AL_DUH_PLAYER *dp);
+int al_poll_duh(AL_DUH_PLAYER *dp);
+long al_duh_get_position(AL_DUH_PLAYER *dp);
+
+AL_DUH_PLAYER *al_duh_encapsulate_sigrenderer(DUH_SIGRENDERER *sigrenderer, float volume, long bufsize, int freq);
+DUH_SIGRENDERER *al_duh_get_sigrenderer(AL_DUH_PLAYER *dp);
+
+/* IMPORTANT: This function will return NULL if the music has ended. */
+DUH_SIGRENDERER *al_duh_decompose_to_sigrenderer(AL_DUH_PLAYER *dp);
+
+#ifdef DUMB_DECLARE_DEPRECATED
+
+	AL_DUH_PLAYER *al_duh_encapsulate_renderer(DUH_SIGRENDERER *dr, float volume, long bufsize, int freq) DUMB_DEPRECATED;
+	DUH_SIGRENDERER *al_duh_get_renderer(AL_DUH_PLAYER *dp) DUMB_DEPRECATED;
+	DUH_SIGRENDERER *al_duh_decompose_to_renderer(AL_DUH_PLAYER *dp) DUMB_DEPRECATED;
+	/* Replace 'renderer' with 'sigrenderer' in each case where you called one of
+	 * these functions.
+	 */
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/lib/allegro.h b/engines/ags/lib/allegro.h
index 4667540d0f..9ecceb509e 100644
--- a/engines/ags/lib/allegro.h
+++ b/engines/ags/lib/allegro.h
@@ -30,9 +30,11 @@
 #include "ags/lib/allegro/color.h"
 #include "ags/lib/allegro/config.h"
 #include "ags/lib/allegro/digi.h"
+#include "ags/lib/allegro/draw.h"
 #include "ags/lib/allegro/error.h"
 #include "ags/lib/allegro/file.h"
 #include "ags/lib/allegro/fixed.h"
+#include "ags/lib/allegro/fmaths.h"
 #include "ags/lib/allegro/gfx.h"
 #include "ags/lib/allegro/keyboard.h"
 #include "ags/lib/allegro/midi.h"
diff --git a/engines/ags/lib/allegro/draw.cpp b/engines/ags/lib/allegro/draw.cpp
new file mode 100644
index 0000000000..e6b467557d
--- /dev/null
+++ b/engines/ags/lib/allegro/draw.cpp
@@ -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.
+ *
+ */
+
+#include "ags/lib/allegro/draw.h"
+
+namespace AGS3 {
+
+void do_line(BITMAP *bmp, int x1, int y_1, int x2, int y2, int d, DrawMethod proc) {
+	warning("TODO: do_line");
+}
+
+} // namespace AGS3
diff --git a/engines/ags/lib/allegro/draw.h b/engines/ags/lib/allegro/draw.h
new file mode 100644
index 0000000000..3e16ff8f2e
--- /dev/null
+++ b/engines/ags/lib/allegro/draw.h
@@ -0,0 +1,37 @@
+/* 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 "ags/lib/allegro/base.h"
+#include "ags/lib/allegro/gfx.h"
+
+#ifndef AGS_LIB_ALLEGRO_DRAW_H
+#define AGS_LIB_ALLEGRO_DRAW_H
+
+namespace AGS3 {
+
+typedef void (*DrawMethod)(BITMAP *, int, int, int);
+
+AL_FUNC(void, do_line, (BITMAP *bmp, int x1, int y_1, int x2, int y2, int d, DrawMethod proc));
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/lib/allegro/file.cpp b/engines/ags/lib/allegro/file.cpp
index 8ac3f05793..1ab7ebacad 100644
--- a/engines/ags/lib/allegro/file.cpp
+++ b/engines/ags/lib/allegro/file.cpp
@@ -22,6 +22,7 @@
 
 #include "ags/lib/allegro/file.h"
 #include "common/str.h"
+#include "common/textconsole.h"
 
 namespace AGS3 {
 
@@ -54,4 +55,104 @@ int is_relative_filename(const char *filename) {
 	return !fname.contains('/') && !fname.contains('\\') ? 0 : -1;
 }
 
+void packfile_password(AL_CONST char *password) {
+	error("TODO: packfile_password");
+}
+
+PACKFILE *pack_fopen(AL_CONST char *filename, AL_CONST char *mode) {
+	error("TODO: pack_fopen");
+}
+
+PACKFILE *pack_fopen_vtable(AL_CONST PACKFILE_VTABLE *vtable, void *userdata) {
+	error("TODO: pack_fopen_vtable");
+}
+
+int pack_fclose(PACKFILE *f) {
+	error("TODO: xxx");
+}
+
+int pack_fseek(PACKFILE *f, int offset) {
+	error("TODO: xxx");
+}
+
+PACKFILE *pack_fopen_chunk(PACKFILE *f, int pack) {
+	error("TODO: xxx");
+}
+
+PACKFILE *pack_fclose_chunk(PACKFILE *f) {
+	error("TODO: xxx");
+}
+
+int pack_getc(PACKFILE *f) {
+	error("TODO: xxx");
+}
+
+int pack_putc(int c, PACKFILE *f) {
+	error("TODO: xxx");
+}
+
+int pack_feof(PACKFILE *f) {
+	error("TODO: xxx");
+}
+
+int pack_ferror(PACKFILE *f) {
+	error("TODO: xxx");
+}
+
+int pack_igetw(PACKFILE *f) {
+	error("TODO: xxx");
+}
+
+long pack_igetl(PACKFILE *f) {
+	error("TODO: xxx");
+}
+
+int pack_iputw(int w, PACKFILE *f) {
+	error("TODO: xxx");
+}
+
+long pack_iputl(long l, PACKFILE *f) {
+	error("TODO: xxx");
+}
+
+int pack_mgetw(PACKFILE *f) {
+	error("TODO: xxx");
+}
+
+long pack_mgetl(PACKFILE *f) {
+	error("TODO: xxx");
+}
+
+int pack_mputw(int w, PACKFILE *f) {
+	error("TODO: xxx");
+}
+
+long pack_mputl(long l, PACKFILE *f) {
+	error("TODO: xxx");
+}
+
+long pack_fread(void *p, long n, PACKFILE *f) {
+	error("TODO: xxx");
+}
+
+long pack_fwrite(AL_CONST void *p, long n, PACKFILE *f) {
+	error("TODO: xxx");
+}
+
+int pack_ungetc(int c, PACKFILE *f) {
+	error("TODO: xxx");
+}
+
+char *pack_fgets(char *p, int max, PACKFILE *f) {
+	error("TODO: xxx");
+}
+
+int pack_fputs(AL_CONST char *p, PACKFILE *f) {
+	error("TODO: xxx");
+}
+
+void *pack_get_userdata(PACKFILE *f) {
+	error("TODO: xxx");
+}
+
 } // namespace AGS3
diff --git a/engines/ags/lib/allegro/file.h b/engines/ags/lib/allegro/file.h
index 0e2a490032..abf82d97d5 100644
--- a/engines/ags/lib/allegro/file.h
+++ b/engines/ags/lib/allegro/file.h
@@ -23,11 +23,62 @@
 #ifndef AGS_LIB_ALLEGRO_FILE_H
 #define AGS_LIB_ALLEGRO_FILE_H
 
+#include "ags/lib/allegro/alconfig.h"
+
 namespace AGS3 {
 
+#define F_READ          "r"
+#define F_WRITE         "w"
+#define F_READ_PACKED   "rp"
+#define F_WRITE_PACKED  "wp"
+#define F_WRITE_NOPACK  "w!"
+
+#define F_BUF_SIZE      4096           /* 4K buffer for caching data */
+#define F_PACK_MAGIC    0x736C6821L    /* magic number for packed files */
+#define F_NOPACK_MAGIC  0x736C682EL    /* magic number for autodetect */
+#define F_EXE_MAGIC     0x736C682BL    /* magic number for appended data */
+
+struct _al_normal_packfile_details {
+	int hndl;                           /* DOS file handle */
+	int flags;                          /* PACKFILE_FLAG_* constants */
+	unsigned char *buf_pos;             /* position in buffer */
+	int buf_size;                       /* number of bytes in the buffer */
+	long todo;                          /* number of bytes still on the disk */
+	struct PACKFILE *parent;            /* nested, parent file */
+	struct LZSS_PACK_DATA *pack_data;   /* for LZSS compression */
+	struct LZSS_UNPACK_DATA *unpack_data; /* for LZSS decompression */
+	char *filename;                     /* name of the file */
+	char *passdata;                     /* encryption key data */
+	char *passpos;                      /* current key position */
+	unsigned char buf[F_BUF_SIZE];      /* the actual data buffer */
+};
+
+struct PACKFILE_VTABLE {
+	AL_METHOD(int, pf_fclose, (void *userdata));
+	AL_METHOD(int, pf_getc, (void *userdata));
+	AL_METHOD(int, pf_ungetc, (int c, void *userdata));
+	AL_METHOD(long, pf_fread, (void *p, long n, void *userdata));
+	AL_METHOD(int, pf_putc, (int c, void *userdata));
+	AL_METHOD(long, pf_fwrite, (AL_CONST void *p, long n, void *userdata));
+	AL_METHOD(int, pf_fseek, (void *userdata, int offset));
+	AL_METHOD(int, pf_feof, (void *userdata));
+	AL_METHOD(int, pf_ferror, (void *userdata));
+};
+
+/**
+ * Allegro file class
+ */
 struct PACKFILE {
-	// TODO: PACKFILE handling
-	int dummy;
+	AL_CONST PACKFILE_VTABLE *vtable;
+	void *userdata;
+	int is_normal_packfile;
+
+	/* The following is only to be used for the "normal" PACKFILE vtable,
+	 * i.e. what is implemented by Allegro itself. If is_normal_packfile is
+	 * false then the following is not even allocated. This must be the last
+	 * member in the structure.
+	 */
+	struct _al_normal_packfile_details normal;
 };
 
 extern char *fix_filename_case(char *path);
@@ -37,6 +88,32 @@ extern char *canonicalize_filename(char *dest, const char *filename, int size);
 extern char *make_relative_filename(char *dest, const char *path, const char *filename, int size);
 extern int is_relative_filename(const char *filename);
 
+AL_FUNC(void, packfile_password, (AL_CONST char *password));
+AL_FUNC(PACKFILE *, pack_fopen, (AL_CONST char *filename, AL_CONST char *mode));
+AL_FUNC(PACKFILE *, pack_fopen_vtable, (AL_CONST PACKFILE_VTABLE *vtable, void *userdata));
+AL_FUNC(int, pack_fclose, (PACKFILE *f));
+AL_FUNC(int, pack_fseek, (PACKFILE *f, int offset));
+AL_FUNC(PACKFILE *, pack_fopen_chunk, (PACKFILE *f, int pack));
+AL_FUNC(PACKFILE *, pack_fclose_chunk, (PACKFILE *f));
+AL_FUNC(int, pack_getc, (PACKFILE *f));
+AL_FUNC(int, pack_putc, (int c, PACKFILE *f));
+AL_FUNC(int, pack_feof, (PACKFILE *f));
+AL_FUNC(int, pack_ferror, (PACKFILE *f));
+AL_FUNC(int, pack_igetw, (PACKFILE *f));
+AL_FUNC(long, pack_igetl, (PACKFILE *f));
+AL_FUNC(int, pack_iputw, (int w, PACKFILE *f));
+AL_FUNC(long, pack_iputl, (long l, PACKFILE *f));
+AL_FUNC(int, pack_mgetw, (PACKFILE *f));
+AL_FUNC(long, pack_mgetl, (PACKFILE *f));
+AL_FUNC(int, pack_mputw, (int w, PACKFILE *f));
+AL_FUNC(long, pack_mputl, (long l, PACKFILE *f));
+AL_FUNC(long, pack_fread, (void *p, long n, PACKFILE *f));
+AL_FUNC(long, pack_fwrite, (AL_CONST void *p, long n, PACKFILE *f));
+AL_FUNC(int, pack_ungetc, (int c, PACKFILE *f));
+AL_FUNC(char *, pack_fgets, (char *p, int max, PACKFILE *f));
+AL_FUNC(int, pack_fputs, (AL_CONST char *p, PACKFILE *f));
+AL_FUNC(void *, pack_get_userdata, (PACKFILE *f));
+
 } // namespace AGS3
 
 #endif
diff --git a/engines/ags/lib/allegro/fixed.h b/engines/ags/lib/allegro/fixed.h
index f8692ee9cf..da0a7a5d85 100644
--- a/engines/ags/lib/allegro/fixed.h
+++ b/engines/ags/lib/allegro/fixed.h
@@ -27,7 +27,7 @@
 
 namespace AGS3 {
 
-typedef long fixed;
+typedef int32 fixed;
 
 extern fixed fixtorad_r;
 extern fixed radtofix_r;
@@ -51,13 +51,6 @@ extern fixed fixtan(fixed x);
 extern fixed fixacos(fixed x);
 extern fixed fixasin(fixed x);
 
-#if 0
-extern fixed fixsqrt(fixed x);
-extern fixed fixhypot(fixed x, fixed y);
-extern fixed fixatan(fixed x);
-extern fixed fixatan2(fixed y, fixed x);
-#endif
-
 } // namespace AGS3
 
 #endif
diff --git a/engines/ags/lib/allegro/fmaths.cpp b/engines/ags/lib/allegro/fmaths.cpp
new file mode 100644
index 0000000000..fa44612677
--- /dev/null
+++ b/engines/ags/lib/allegro/fmaths.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.
+ *
+ */
+
+#include "ags/lib/allegro/fmaths.h"
+
+namespace AGS3 {
+
+fixed fixsqrt(fixed x) {
+	if (x > 0)
+		return ftofix(sqrt(fixtof(x)));
+
+	if (x < 0)
+		*allegro_errno = EDOM;
+
+	return 0;
+}
+
+fixed fixhypot(fixed x, fixed y) {
+	return ftofix(hypot(fixtof(x), fixtof(y)));
+}
+
+fixed fixatan(fixed x) {
+	int a, b, c;            /* for binary search */
+	fixed d;                /* difference value for search */
+
+	if (x >= 0) {           /* search the first part of tan table */
+		a = 0;
+		b = 127;
+	} else {                  /* search the second half instead */
+		a = 128;
+		b = 255;
+	}
+
+	do {
+		c = (a + b) >> 1;
+		d = x - _tan_tbl[c];
+
+		if (d > 0)
+			a = c + 1;
+		else
+			if (d < 0)
+				b = c - 1;
+
+	} while ((a <= b) && (d));
+
+	if (x >= 0)
+		return ((long)c) << 15;
+
+	return (-0x00800000L + (((long)c) << 15));
+}
+
+fixed fixatan2(fixed y, fixed x) {
+	fixed r;
+
+	if (x == 0) {
+		if (y == 0) {
+			*allegro_errno = EDOM;
+			return 0L;
+		} else
+			return ((y < 0) ? -0x00400000L : 0x00400000L);
+	}
+
+	*allegro_errno = 0;
+	r = fixdiv(y, x);
+
+	if (*allegro_errno) {
+		*allegro_errno = 0;
+		return ((y < 0) ? -0x00400000L : 0x00400000L);
+	}
+
+	r = fixatan(r);
+
+	if (x >= 0)
+		return r;
+
+	if (y >= 0)
+		return 0x00800000L + r;
+
+	return r - 0x00800000L;
+}
+
+} // namespace AGS3
diff --git a/engines/ags/lib/allegro/fmaths.h b/engines/ags/lib/allegro/fmaths.h
new file mode 100644
index 0000000000..0aad8c5a1c
--- /dev/null
+++ b/engines/ags/lib/allegro/fmaths.h
@@ -0,0 +1,41 @@
+/* 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 AGS_LIB_ALLEGRO_FMATHS_H
+#define AGS_LIB_ALLEGRO_FMATHS_H
+
+#include "ags/lib/allegro/fixed.h"
+
+namespace AGS3 {
+
+AL_FUNC(fixed, fixsqrt, (fixed x));
+AL_FUNC(fixed, fixhypot, (fixed x, fixed y));
+AL_FUNC(fixed, fixatan, (fixed x));
+AL_FUNC(fixed, fixatan2, (fixed y, fixed x));
+
+AL_ARRAY(fixed, _cos_tbl);
+AL_ARRAY(fixed, _tan_tbl);
+AL_ARRAY(fixed, _acos_tbl);
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/lib/allegro/gfx.cpp b/engines/ags/lib/allegro/gfx.cpp
index 153a00be72..a14bf1dda8 100644
--- a/engines/ags/lib/allegro/gfx.cpp
+++ b/engines/ags/lib/allegro/gfx.cpp
@@ -38,6 +38,19 @@ BITMAP::BITMAP(Graphics::ManagedSurface *owner) : _owner(owner),
 		line[y] = (byte *)_owner->getBasePtr(0, y);
 }
 
+int BITMAP::getpixel(int x, int y) const {
+	if (x < 0 || y < 0 || x >= w || y >= h)
+		return -1;
+
+	const byte *pixel = (const byte *)getBasePtr(x, y);
+	if (format.bytesPerPixel == 1)
+		return *pixel;
+	else if (format.bytesPerPixel == 2)
+		return *(const uint16 *)pixel;
+	else
+		return *(const uint32 *)pixel;
+}
+
 /*-------------------------------------------------------------------*/
 
 /**
diff --git a/engines/ags/lib/allegro/gfx.h b/engines/ags/lib/allegro/gfx.h
index 95cd8104c8..66dbdc3be3 100644
--- a/engines/ags/lib/allegro/gfx.h
+++ b/engines/ags/lib/allegro/gfx.h
@@ -37,6 +37,13 @@ namespace AGS3 {
 #define GFX_SAFE                       AL_ID('S','A','F','E')
 #define GFX_NONE                       AL_ID('N','O','N','E')
 
+/* Bitfield for relaying graphics driver type information */
+#define GFX_TYPE_UNKNOWN     0
+#define GFX_TYPE_WINDOWED    1
+#define GFX_TYPE_FULLSCREEN  2
+#define GFX_TYPE_DEFINITE    4
+#define GFX_TYPE_MAGIC       8
+
 /* drawing modes for draw_sprite_ex() */
 #define DRAW_SPRITE_NORMAL 0
 #define DRAW_SPRITE_LIT 1
@@ -194,6 +201,8 @@ public:
 	uint getTransparentColor() const {
 		return _owner->getTransparentColor();
 	}
+
+	int getpixel(int x, int y) const;
 };
 
 AL_FUNC(void, set_color_conversion, (int mode));
diff --git a/engines/ags/lib/allegro/keyboard.cpp b/engines/ags/lib/allegro/keyboard.cpp
index 9e0a0f638a..38516df5a6 100644
--- a/engines/ags/lib/allegro/keyboard.cpp
+++ b/engines/ags/lib/allegro/keyboard.cpp
@@ -23,6 +23,9 @@
 #include "ags/lib/allegro/keyboard.h"
 #include "common/algorithm.h"
 #include "common/textconsole.h"
+#include "common/system.h"
+#include "common/events.h"
+#include "common/textconsole.h"
 
 namespace AGS3 {
 
@@ -36,4 +39,41 @@ int install_keyboard() {
 void remove_keyboard() {
 }
 
+bool keyboard_needs_poll() {
+	// TODO: Check if it's okay to be hardcoded for events, since I'm not sure
+	// how to check with ScummVM event manager for pending events
+	return true;
+}
+
+int poll_keyboard() {
+	warning("TODO: poll_keyboard");
+	return false;
+}
+
+void simulate_keypress(int keycode) {
+	simulate_ukeypress(keycode, keycode);
+}
+
+void simulate_ukeypress(int keycode, int scancode) {
+	Common::Event event;
+
+	event.type = Common::EVENT_KEYDOWN;
+	event.kbd.ascii = scancode;
+	event.kbd.keycode = (Common::KeyCode)keycode;
+	g_system->getEventManager()->pushEvent(event);
+
+	event.type = Common::EVENT_KEYUP;
+	g_system->getEventManager()->pushEvent(event);
+}
+
+bool keypressed() {
+	warning("TODO: keypressed");
+	return true;
+}
+
+int readkey(void) {
+	warning("TODO: readkey");
+	return 0;
+}
+
 } // namespace AGS3
diff --git a/engines/ags/lib/allegro/keyboard.h b/engines/ags/lib/allegro/keyboard.h
index 0634eec0ab..15a1ce5512 100644
--- a/engines/ags/lib/allegro/keyboard.h
+++ b/engines/ags/lib/allegro/keyboard.h
@@ -23,10 +23,13 @@
 #ifndef AGS_LIB_ALLEGRO_KEYBOARD_H
 #define AGS_LIB_ALLEGRO_KEYBOARD_H
 
+#include "ags/lib/allegro/alconfig.h"
 #include "common/keyboard.h"
 
 namespace AGS3 {
 
+#define __allegro_KEY_MAX Common::KEYCODE_LAST
+
 #define KB_SHIFT_FLAG Common::KBD_SHIFT
 #define KB_CTRL_FLAG Common::KBD_CTRL
 #define KB_ALT_FLAG Common::KBD_ALT
@@ -100,10 +103,83 @@ namespace AGS3 {
 #define __allegro_KEY_NUMLOCK Common::KEYCODE_NUMLOCK
 #define __allegro_KEY_CAPSLOCK Common::KEYCODE_CAPSLOCK
 
+#define __allegro_KEY_0 Common::KEYCODE_0
+#define __allegro_KEY_1 Common::KEYCODE_1
+#define __allegro_KEY_2 Common::KEYCODE_2
+#define __allegro_KEY_3 Common::KEYCODE_3
+#define __allegro_KEY_4 Common::KEYCODE_4
+#define __allegro_KEY_5 Common::KEYCODE_5
+#define __allegro_KEY_6 Common::KEYCODE_6
+#define __allegro_KEY_7 Common::KEYCODE_7
+#define __allegro_KEY_8 Common::KEYCODE_8
+#define __allegro_KEY_9 Common::KEYCODE_9
+
+#define __allegro_KEY_A Common::KEYCODE_a
+#define __allegro_KEY_B Common::KEYCODE_b
+#define __allegro_KEY_C Common::KEYCODE_c
+#define __allegro_KEY_D Common::KEYCODE_d
+#define __allegro_KEY_E Common::KEYCODE_e
+#define __allegro_KEY_F Common::KEYCODE_f
+#define __allegro_KEY_G Common::KEYCODE_g
+#define __allegro_KEY_H Common::KEYCODE_h
+#define __allegro_KEY_I Common::KEYCODE_i
+#define __allegro_KEY_J Common::KEYCODE_j
+#define __allegro_KEY_K Common::KEYCODE_k
+#define __allegro_KEY_L Common::KEYCODE_l
+#define __allegro_KEY_M Common::KEYCODE_m
+#define __allegro_KEY_N Common::KEYCODE_n
+#define __allegro_KEY_O Common::KEYCODE_o
+#define __allegro_KEY_P Common::KEYCODE_p
+#define __allegro_KEY_Q Common::KEYCODE_q
+#define __allegro_KEY_R Common::KEYCODE_r
+#define __allegro_KEY_S Common::KEYCODE_s
+#define __allegro_KEY_T Common::KEYCODE_t
+#define __allegro_KEY_U Common::KEYCODE_u
+#define __allegro_KEY_V Common::KEYCODE_v
+#define __allegro_KEY_W Common::KEYCODE_w
+#define __allegro_KEY_X Common::KEYCODE_x
+#define __allegro_KEY_Y Common::KEYCODE_y
+#define __allegro_KEY_Z Common::KEYCODE_z
+
+
+#define __allegro_KEY_BACKSPACE Common::KEYCODE_BACKSPACE
+#define __allegro_KEY_TAB Common::KEYCODE_TAB
+#define __allegro_KEY_ENTER Common::KEYCODE_RETURN
+#define __allegro_KEY_ENTER_PAD Common::KEYCODE_KP_ENTER
+#define __allegro_KEY_ESC Common::KEYCODE_ESCAPE
+#define __allegro_KEY_SPACE Common::KEYCODE_SPACE
+#define __allegro_KEY_QUOTE Common::KEYCODE_QUOTE
+#define __allegro_KEY_COMMA Common::KEYCODE_COMMA
+#define __allegro_KEY_STOP 0
+#define __allegro_KEY_SLASH Common::KEYCODE_SLASH
+#define __allegro_KEY_SLASH_PAD Common::KEYCODE_KP_DIVIDE
+#define __allegro_KEY_BACKSLASH Common::KEYCODE_BACKSLASH
+#define __allegro_KEY_BACKSLASH2 Common::KEYCODE_BACKSLASH
+#define __allegro_KEY_SEMICOLON Common::KEYCODE_SEMICOLON
+#define __allegro_KEY_EQUALS Common::KEYCODE_EQUALS
+#define __allegro_KEY_EQUALS_PAD Common::KEYCODE_KP_EQUALS
+#define __allegro_KEY_OPENBRACE 123
+#define __allegro_KEY_CLOSEBRACE 125
+#define __allegro_KEY_PLUS_PAD Common::KEYCODE_KP_PLUS
+#define __allegro_KEY_MINUS Common::KEYCODE_MINUS
+#define __allegro_KEY_MINUS_PAD Common::KEYCODE_KP_MINUS
+#define __allegro_KEY_COLON Common::KEYCODE_COLON
+#define __allegro_KEY_COLON2 Common::KEYCODE_COLON
+#define __allegro_KEY_ASTERISK Common::KEYCODE_ASTERISK
+#define __allegro_KEY_AT Common::KEYCODE_AT
+
 extern bool key[Common::KEYCODE_LAST];
 
+AL_FUNC(bool, keyboard_needs_poll, (void));
+AL_FUNC(int, poll_keyboard, (void));
+
 extern int install_keyboard();
 extern void remove_keyboard();
+AL_FUNC(void, simulate_keypress, (int keycode));
+AL_FUNC(void, simulate_ukeypress, (int keycode, int scancode));
+
+AL_FUNC(bool, keypressed, (void));
+AL_FUNC(int, readkey, (void));
 
 } // namespace AGS3
 
diff --git a/engines/ags/lib/allegro/system.h b/engines/ags/lib/allegro/system.h
index be5759b02f..c44eedd84d 100644
--- a/engines/ags/lib/allegro/system.h
+++ b/engines/ags/lib/allegro/system.h
@@ -36,6 +36,14 @@ namespace AGS3 {
 #define SYSTEM_AUTODETECT  0
 #define SYSTEM_NONE        AL_ID('N','O','N','E')
 
+#define SWITCH_NONE           0
+#define SWITCH_PAUSE          1
+#define SWITCH_AMNESIA        2
+#define SWITCH_BACKGROUND     3
+#define SWITCH_BACKAMNESIA    4
+
+#define SWITCH_IN             0
+#define SWITCH_OUT            1
 
 struct GFX_MODE {
 	int width, height, bpp;
@@ -140,6 +148,8 @@ extern GFX_MODE_LIST *get_gfx_mode_list(int card);
 extern void destroy_gfx_mode_list(GFX_MODE_LIST *list);
 
 inline void vsync() {}
+inline int set_display_switch_callback(int dir, AL_METHOD(void, cb, (void))) { return 0; }
+inline int set_display_switch_mode(int v) { return -1; }
 
 } // namespace AGS3
 
diff --git a/engines/ags/lib/dumb.h b/engines/ags/lib/dumb.h
new file mode 100644
index 0000000000..a74ffdf0ba
--- /dev/null
+++ b/engines/ags/lib/dumb.h
@@ -0,0 +1,581 @@
+/* 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.
+ *
+ */
+
+/*  _______         ____    __         ___    ___
+ * \    _  \       \    /  \  /       \   \  /   /       '   '  '
+ *  |  | \  \       |  |    ||         |   \/   |         .      .
+ *  |  |  |  |      |  |    ||         ||\  /|  |
+ *  |  |  |  |      |  |    ||         || \/ |  |         '  '  '
+ *  |  |  |  |      |  |    ||         ||    |  |         .      .
+ *  |  |_/  /        \  \__//          ||    |  |
+ * /_______/ynamic    \____/niversal  /__\  /____\usic   /|  .  . ibliotheque
+ *                                                      /  \
+ *                                                     / .  \
+ * dumb.h - The user header file for DUMB.            / / \  \
+ *                                                   | <  /   \_
+ * Include this file in any of your files in         |  \/ /\   /
+ * which you wish to use the DUMB functions           \_  /  > /
+ * and variables.                                       | \ / /
+ *                                                      |  ' /
+ *                                                       \__/
+ */
+
+#ifndef AGS_LIB_DUMB_H
+#define AGS_LIB_DUMB_H
+
+#include "common/stream.h"
+
+namespace AGS3 {
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+#define DUMB_MAJOR_VERSION    0
+#define DUMB_MINOR_VERSION    9
+#define DUMB_REVISION_VERSION 2
+
+#define DUMB_VERSION (DUMB_MAJOR_VERSION*10000 + DUMB_MINOR_VERSION*100 + DUMB_REVISION_VERSION)
+
+#define DUMB_VERSION_STR "0.9.2"
+
+#define DUMB_NAME "DUMB v" DUMB_VERSION_STR
+
+#define DUMB_YEAR  2003
+#define DUMB_MONTH 4
+#define DUMB_DAY   2
+
+#define DUMB_YEAR_STR2  "03"
+#define DUMB_YEAR_STR4  "2003"
+#define DUMB_MONTH_STR1 "4"
+#define DUMB_DAY_STR1   "2"
+
+#if DUMB_MONTH < 10
+#define DUMB_MONTH_STR2 "0" DUMB_MONTH_STR1
+#else
+#define DUMB_MONTH_STR2 DUMB_MONTH_STR1
+#endif
+
+#if DUMB_DAY < 10
+#define DUMB_DAY_STR2 "0" DUMB_DAY_STR1
+#else
+#define DUMB_DAY_STR2 DUMB_DAY_STR1
+#endif
+
+
+	/* WARNING: The month and day were inadvertently swapped in the v0.8 release.
+	 *          Please do not compare this constant against any date in 2002. In
+	 *          any case, DUMB_VERSION is probably more useful for this purpose.
+	 */
+#define DUMB_DATE (DUMB_YEAR*10000 + DUMB_MONTH*100 + DUMB_DAY)
+
+#define DUMB_DATE_STR DUMB_DAY_STR1 "." DUMB_MONTH_STR1 "." DUMB_YEAR_STR4
+
+
+#undef MIN
+#undef MAX
+#undef MID
+
+#define MIN(x,y)   (((x) < (y)) ? (x) : (y))
+#define MAX(x,y)   (((x) > (y)) ? (x) : (y))
+#define MID(x,y,z) MAX((x), MIN((y), (z)))
+
+#undef ABS
+#define ABS(x) (((x) >= 0) ? (x) : (-(x)))
+
+
+#ifdef DEBUGMODE
+
+#ifndef ASSERT
+#include <assert.h>
+#define ASSERT(n) assert(n)
+#endif
+#ifndef TRACE
+	 // it would be nice if this did actually trace ...
+#define TRACE 1 ? (void)0 : (void)printf
+#endif
+
+#else
+
+#ifndef ASSERT
+#define ASSERT(n)
+#endif
+#ifndef TRACE
+#define TRACE 1 ? (void)0 : (void)printf
+#endif
+
+#endif
+
+
+#define DUMB_ID(a,b,c,d) (((unsigned int)(a) << 24) | \
+                          ((unsigned int)(b) << 16) | \
+                          ((unsigned int)(c) <<  8) | \
+                          ((unsigned int)(d)      ))
+
+
+
+#ifndef LONG_LONG
+#ifdef __GNUC__
+#define LONG_LONG long long
+#elif defined _MSC_VER
+#define LONG_LONG __int64
+#else
+#error 64-bit integer type unknown
+#endif
+#endif
+
+#if __GNUC__ * 100 + __GNUC_MINOR__ >= 301 /* GCC 3.1+ */
+#ifndef DUMB_DECLARE_DEPRECATED
+#define DUMB_DECLARE_DEPRECATED
+#endif
+#define DUMB_DEPRECATED __attribute__((__deprecated__))
+#else
+#define DUMB_DEPRECATED
+#endif
+
+
+	 /* Basic Sample Type. Normal range is -0x800000 to 0x7FFFFF. */
+
+	typedef int sample_t;
+
+
+	/* Library Clean-up Management */
+
+	int dumb_atexit(void (*proc)(void));
+
+	void dumb_exit(void);
+
+
+	/* File Input Functions */
+
+	typedef struct DUMBFILE_SYSTEM {
+		void *(*open)(const char *filename);
+		int (*skip)(void *f, long n);
+		int (*getc)(void *f);
+		long (*getnc)(char *ptr, long n, void *f);
+		void (*close)(void *f);
+	}
+	DUMBFILE_SYSTEM;
+
+	typedef struct DUMBFILE DUMBFILE;
+
+	void register_dumbfile_system(DUMBFILE_SYSTEM *dfs);
+
+	DUMBFILE *dumbfile_open(const char *filename);
+	DUMBFILE *dumbfile_open_ex(void *file, DUMBFILE_SYSTEM *dfs);
+
+	long dumbfile_pos(DUMBFILE *f);
+	int dumbfile_skip(DUMBFILE *f, long n);
+
+	int dumbfile_getc(DUMBFILE *f);
+
+	int dumbfile_igetw(DUMBFILE *f);
+	int dumbfile_mgetw(DUMBFILE *f);
+
+	long dumbfile_igetl(DUMBFILE *f);
+	long dumbfile_mgetl(DUMBFILE *f);
+
+	unsigned long dumbfile_cgetul(DUMBFILE *f);
+	signed long dumbfile_cgetsl(DUMBFILE *f);
+
+	long dumbfile_getnc(char *ptr, long n, DUMBFILE *f);
+
+	int dumbfile_error(DUMBFILE *f);
+	int dumbfile_close(DUMBFILE *f);
+
+
+	/* stdio File Input Module */
+
+	void dumb_register_stdfiles(void);
+
+	DUMBFILE *dumbfile_open_stdfile(Common::ReadStream *p);
+
+
+	/* Memory File Input Module */
+
+	DUMBFILE *dumbfile_open_memory(const char *data, long size);
+
+
+	/* DUH Management */
+
+	typedef struct DUH DUH;
+
+#define DUH_SIGNATURE DUMB_ID('D','U','H','!')
+
+	void unload_duh(DUH *duh);
+
+	DUH *load_duh(const char *filename);
+	DUH *read_duh(DUMBFILE *f);
+
+	long duh_get_length(DUH *duh);
+
+
+	/* Signal Rendering Functions */
+
+	typedef struct DUH_SIGRENDERER DUH_SIGRENDERER;
+
+	DUH_SIGRENDERER *duh_start_sigrenderer(DUH *duh, int sig, int n_channels, long pos);
+
+#ifdef DUMB_DECLARE_DEPRECATED
+	typedef void (*DUH_SIGRENDERER_CALLBACK)(void *data, sample_t **samples, int n_channels, long length);
+	/* This is deprecated, but is not marked as such because GCC tends to
+	 * complain spuriously when the typedef is used later. See comments below.
+	 */
+
+	void duh_sigrenderer_set_callback(
+		DUH_SIGRENDERER *sigrenderer,
+		DUH_SIGRENDERER_CALLBACK callback, void *data
+	) DUMB_DEPRECATED;
+	/* The 'callback' argument's type has changed for const-correctness. See the
+	 * DUH_SIGRENDERER_CALLBACK definition just above. Also note that the samples
+	 * in the buffer are now 256 times as large; the normal range is -0x800000 to
+	 * 0x7FFFFF. The function has been renamed partly because its functionality
+	 * has changed slightly and partly so that its name is more meaningful. The
+	 * new one is duh_sigrenderer_set_analyser_callback(), and the typedef for
+	 * the function pointer has also changed, from DUH_SIGRENDERER_CALLBACK to
+	 * DUH_SIGRENDERER_ANALYSER_CALLBACK. (If you wanted to use this callback to
+	 * apply a DSP effect, don't worry; there is a better way of doing this. It
+	 * is undocumented, so contact me and I shall try to help. Contact details
+	 * are in readme.txt.)
+	 */
+#endif
+
+	typedef void (*DUH_SIGRENDERER_ANALYSER_CALLBACK)(void *data, const sample_t *const *samples, int n_channels, long length);
+
+	void duh_sigrenderer_set_analyser_callback(
+		DUH_SIGRENDERER *sigrenderer,
+		DUH_SIGRENDERER_ANALYSER_CALLBACK callback, void *data
+	);
+
+	int duh_sigrenderer_get_n_channels(DUH_SIGRENDERER *sigrenderer);
+	long duh_sigrenderer_get_position(DUH_SIGRENDERER *sigrenderer);
+
+	void duh_sigrenderer_set_sigparam(DUH_SIGRENDERER *sigrenderer, unsigned char id, long value);
+
+	long duh_sigrenderer_get_samples(
+		DUH_SIGRENDERER *sigrenderer,
+		float volume, float delta,
+		long size, sample_t **samples
+	);
+
+	void duh_sigrenderer_get_current_sample(DUH_SIGRENDERER *sigrenderer, float volume, sample_t *samples);
+
+	void duh_end_sigrenderer(DUH_SIGRENDERER *sigrenderer);
+
+
+	/* DUH Rendering Functions */
+
+	long duh_render(
+		DUH_SIGRENDERER *sigrenderer,
+		int bits, int unsign,
+		float volume, float delta,
+		long size, void *sptr
+	);
+
+#ifdef DUMB_DECLARE_DEPRECATED
+
+	long duh_render_signal(
+		DUH_SIGRENDERER *sigrenderer,
+		float volume, float delta,
+		long size, sample_t **samples
+	) DUMB_DEPRECATED;
+	/* Please use duh_sigrenderer_get_samples(). Arguments and functionality are
+	 * identical.
+	 */
+
+	typedef DUH_SIGRENDERER DUH_RENDERER DUMB_DEPRECATED;
+	/* Please use DUH_SIGRENDERER instead of DUH_RENDERER. */
+
+	DUH_SIGRENDERER *duh_start_renderer(DUH *duh, int n_channels, long pos) DUMB_DEPRECATED;
+	/* Please use duh_start_sigrenderer() instead. Pass 0 for 'sig'. */
+
+	int duh_renderer_get_n_channels(DUH_SIGRENDERER *dr) DUMB_DEPRECATED;
+	long duh_renderer_get_position(DUH_SIGRENDERER *dr) DUMB_DEPRECATED;
+	/* Please use the duh_sigrenderer_*() equivalents of these two functions. */
+
+	void duh_end_renderer(DUH_SIGRENDERER *dr) DUMB_DEPRECATED;
+	/* Please use duh_end_sigrenderer() instead. */
+
+	DUH_SIGRENDERER *duh_renderer_encapsulate_sigrenderer(DUH_SIGRENDERER *sigrenderer) DUMB_DEPRECATED;
+	DUH_SIGRENDERER *duh_renderer_get_sigrenderer(DUH_SIGRENDERER *dr) DUMB_DEPRECATED;
+	DUH_SIGRENDERER *duh_renderer_decompose_to_sigrenderer(DUH_SIGRENDERER *dr) DUMB_DEPRECATED;
+	/* These functions have become no-ops that just return the parameter.
+	 * So, for instance, replace
+	 *   duh_renderer_encapsulate_sigrenderer(my_sigrenderer)
+	 * with
+	 *   my_sigrenderer
+	 */
+
+#endif
+
+
+	 /* Impulse Tracker Support */
+
+	extern int dumb_it_max_to_mix;
+
+	typedef struct DUMB_IT_SIGDATA DUMB_IT_SIGDATA;
+	typedef struct DUMB_IT_SIGRENDERER DUMB_IT_SIGRENDERER;
+
+	DUMB_IT_SIGDATA *duh_get_it_sigdata(DUH *duh);
+	DUH_SIGRENDERER *duh_encapsulate_it_sigrenderer(DUMB_IT_SIGRENDERER *it_sigrenderer, int n_channels, long pos);
+	DUMB_IT_SIGRENDERER *duh_get_it_sigrenderer(DUH_SIGRENDERER *sigrenderer);
+
+	DUH_SIGRENDERER *dumb_it_start_at_order(DUH *duh, int n_channels, int startorder);
+
+	void dumb_it_set_loop_callback(DUMB_IT_SIGRENDERER *sigrenderer, int (*callback)(void *data), void *data);
+	void dumb_it_set_xm_speed_zero_callback(DUMB_IT_SIGRENDERER *sigrenderer, int (*callback)(void *data), void *data);
+	void dumb_it_set_midi_callback(DUMB_IT_SIGRENDERER *sigrenderer, int (*callback)(void *data, int channel, unsigned char byte), void *data);
+
+	int dumb_it_callback_terminate(void *data);
+	int dumb_it_callback_midi_block(void *data, int channel, unsigned char byte);
+
+	DUH *dumb_load_it(const char *filename);
+	DUH *dumb_load_xm(const char *filename);
+	DUH *dumb_load_s3m(const char *filename);
+	DUH *dumb_load_mod(const char *filename);
+
+	DUH *dumb_read_it(DUMBFILE *f);
+	DUH *dumb_read_xm(DUMBFILE *f);
+	DUH *dumb_read_s3m(DUMBFILE *f);
+	DUH *dumb_read_mod(DUMBFILE *f);
+
+	int dumb_it_sd_get_n_orders(DUMB_IT_SIGDATA *sd);
+
+	int dumb_it_sd_get_initial_global_volume(DUMB_IT_SIGDATA *sd);
+	void dumb_it_sd_set_initial_global_volume(DUMB_IT_SIGDATA *sd, int gv);
+
+	int dumb_it_sd_get_mixing_volume(DUMB_IT_SIGDATA *sd);
+	void dumb_it_sd_set_mixing_volume(DUMB_IT_SIGDATA *sd, int mv);
+
+	int dumb_it_sd_get_initial_speed(DUMB_IT_SIGDATA *sd);
+	void dumb_it_sd_set_initial_speed(DUMB_IT_SIGDATA *sd, int speed);
+
+	int dumb_it_sd_get_initial_tempo(DUMB_IT_SIGDATA *sd);
+	void dumb_it_sd_set_initial_tempo(DUMB_IT_SIGDATA *sd, int tempo);
+
+	int dumb_it_sd_get_initial_channel_volume(DUMB_IT_SIGDATA *sd, int channel);
+	void dumb_it_sd_set_initial_channel_volume(DUMB_IT_SIGDATA *sd, int channel, int volume);
+
+	int dumb_it_sr_get_current_order(DUMB_IT_SIGRENDERER *sr);
+	int dumb_it_sr_get_current_row(DUMB_IT_SIGRENDERER *sr);
+
+	int dumb_it_sr_get_global_volume(DUMB_IT_SIGRENDERER *sr);
+	void dumb_it_sr_set_global_volume(DUMB_IT_SIGRENDERER *sr, int gv);
+
+	int dumb_it_sr_get_tempo(DUMB_IT_SIGRENDERER *sr);
+	void dumb_it_sr_set_tempo(DUMB_IT_SIGRENDERER *sr, int tempo);
+
+	int dumb_it_sr_get_speed(DUMB_IT_SIGRENDERER *sr);
+	void dumb_it_sr_set_speed(DUMB_IT_SIGRENDERER *sr, int speed);
+
+#define DUMB_IT_N_CHANNELS 64
+#define DUMB_IT_N_NNA_CHANNELS 192
+#define DUMB_IT_TOTAL_CHANNELS (DUMB_IT_N_CHANNELS + DUMB_IT_N_NNA_CHANNELS)
+
+	/* Channels passed to any of these functions are 0-based */
+	int dumb_it_sr_get_channel_volume(DUMB_IT_SIGRENDERER *sr, int channel);
+	void dumb_it_sr_set_channel_volume(DUMB_IT_SIGRENDERER *sr, int channel, int volume);
+
+	typedef struct DUMB_IT_CHANNEL_STATE DUMB_IT_CHANNEL_STATE;
+
+	struct DUMB_IT_CHANNEL_STATE {
+		int channel; /* 0-based; meaningful for NNA channels */
+		int sample; /* 1-based; 0 if nothing playing, then other fields undef */
+		int freq; /* in Hz */
+		float volume; /* 1.0 maximum; affected by ALL factors, inc. mixing vol */
+		unsigned char pan; /* 0-64, 100 for surround */
+		signed char subpan; /* use (pan + subpan/256.0f) or ((pan<<8)+subpan) */
+		unsigned char filter_cutoff;    /* 0-127    cutoff=127 AND resonance=0 */
+		unsigned char filter_subcutoff; /* 0-255      -> no filters (subcutoff */
+		unsigned char filter_resonance; /* 0-127        always 0 in this case) */
+		/* subcutoff only changes from zero if filter envelopes are in use. The
+		 * calculation (filter_cutoff + filter_subcutoff/256.0f) gives a more
+		 * accurate filter cutoff measurement as a float. It would often be more
+		 * useful to use a scaled int such as ((cutoff<<8) + subcutoff).
+		 */
+	};
+
+	/* Values of 64 or more will access NNA channels here. */
+	void dumb_it_sr_get_channel_state(DUMB_IT_SIGRENDERER *sr, int channel, DUMB_IT_CHANNEL_STATE *state);
+
+
+	/* Signal Design Helper Values */
+
+	/* Use pow(DUMB_SEMITONE_BASE, n) to get the 'delta' value to transpose up by
+	 * n semitones. To transpose down, use negative n.
+	 */
+#define DUMB_SEMITONE_BASE 1.059463094359295309843105314939748495817
+
+	 /* Use pow(DUMB_QUARTERTONE_BASE, n) to get the 'delta' value to transpose up
+	  * by n quartertones. To transpose down, use negative n.
+	  */
+#define DUMB_QUARTERTONE_BASE 1.029302236643492074463779317738953977823
+
+	  /* Use pow(DUMB_PITCH_BASE, n) to get the 'delta' value to transpose up by n
+	   * units. In this case, 256 units represent one semitone; 3072 units
+	   * represent one octave. These units are used by the sequence signal (SEQU).
+	   */
+#define DUMB_PITCH_BASE 1.000225659305069791926712241547647863626
+
+
+	   /* Signal Design Function Types */
+
+	typedef void sigdata_t;
+	typedef void sigrenderer_t;
+
+	typedef sigdata_t *(*DUH_LOAD_SIGDATA)(DUH *duh, DUMBFILE *file);
+
+	typedef sigrenderer_t *(*DUH_START_SIGRENDERER)(
+		DUH *duh,
+		sigdata_t *sigdata,
+		int n_channels,
+		long pos
+		);
+
+	typedef void (*DUH_SIGRENDERER_SET_SIGPARAM)(
+		sigrenderer_t *sigrenderer,
+		unsigned char id, long value
+		);
+
+	typedef long (*DUH_SIGRENDERER_GET_SAMPLES)(
+		sigrenderer_t *sigrenderer,
+		float volume, float delta,
+		long size, sample_t **samples
+		);
+
+	typedef void (*DUH_SIGRENDERER_GET_CURRENT_SAMPLE)(
+		sigrenderer_t *sigrenderer,
+		float volume,
+		sample_t *samples
+		);
+
+	typedef void (*DUH_END_SIGRENDERER)(sigrenderer_t *sigrenderer);
+
+	typedef void (*DUH_UNLOAD_SIGDATA)(sigdata_t *sigdata);
+
+
+	/* Signal Design Function Registration */
+
+	typedef struct DUH_SIGTYPE_DESC {
+		long type;
+		DUH_LOAD_SIGDATA                   load_sigdata;
+		DUH_START_SIGRENDERER              start_sigrenderer;
+		DUH_SIGRENDERER_SET_SIGPARAM       sigrenderer_set_sigparam;
+		DUH_SIGRENDERER_GET_SAMPLES        sigrenderer_get_samples;
+		DUH_SIGRENDERER_GET_CURRENT_SAMPLE sigrenderer_get_current_sample;
+		DUH_END_SIGRENDERER                end_sigrenderer;
+		DUH_UNLOAD_SIGDATA                 unload_sigdata;
+	}
+	DUH_SIGTYPE_DESC;
+
+	void dumb_register_sigtype(DUH_SIGTYPE_DESC *desc);
+
+
+	// Decide where to put these functions; new heading?
+
+	sigdata_t *duh_get_raw_sigdata(DUH *duh, int sig, long type);
+
+	DUH_SIGRENDERER *duh_encapsulate_raw_sigrenderer(sigrenderer_t *vsigrenderer, DUH_SIGTYPE_DESC *desc, int n_channels, long pos);
+	sigrenderer_t *duh_get_raw_sigrenderer(DUH_SIGRENDERER *sigrenderer, long type);
+
+
+	/* Sample Buffer Allocation Helpers */
+
+	sample_t **create_sample_buffer(int n_channels, long length);
+	void destroy_sample_buffer(sample_t **samples);
+
+
+	/* Silencing Helper */
+
+	void dumb_silence(sample_t *samples, long length);
+
+
+	/* Click Removal Helpers */
+
+	typedef struct DUMB_CLICK_REMOVER DUMB_CLICK_REMOVER;
+
+	DUMB_CLICK_REMOVER *dumb_create_click_remover(void);
+	void dumb_record_click(DUMB_CLICK_REMOVER *cr, long pos, sample_t step);
+	void dumb_remove_clicks(DUMB_CLICK_REMOVER *cr, sample_t *samples, long length, float halflife);
+	sample_t dumb_click_remover_get_offset(DUMB_CLICK_REMOVER *cr);
+	void dumb_destroy_click_remover(DUMB_CLICK_REMOVER *cr);
+
+	DUMB_CLICK_REMOVER **dumb_create_click_remover_array(int n);
+	void dumb_record_click_array(int n, DUMB_CLICK_REMOVER **cr, long pos, sample_t *step);
+	void dumb_record_click_negative_array(int n, DUMB_CLICK_REMOVER **cr, long pos, sample_t *step);
+	void dumb_remove_clicks_array(int n, DUMB_CLICK_REMOVER **cr, sample_t **samples, long length, float halflife);
+	void dumb_click_remover_get_offset_array(int n, DUMB_CLICK_REMOVER **cr, sample_t *offset);
+	void dumb_destroy_click_remover_array(int n, DUMB_CLICK_REMOVER **cr);
+
+
+	/* Resampling Helpers */
+
+#define DUMB_RQ_ALIASING 0
+#define DUMB_RQ_LINEAR   1
+#define DUMB_RQ_CUBIC    2
+#define DUMB_RQ_N_LEVELS 3
+	extern int dumb_resampling_quality;
+
+	typedef struct DUMB_RESAMPLER DUMB_RESAMPLER;
+
+	typedef void (*DUMB_RESAMPLE_PICKUP)(DUMB_RESAMPLER *resampler, void *data);
+
+	struct DUMB_RESAMPLER {
+		sample_t *src;
+		long pos;
+		int subpos;
+		long start, end;
+		int dir;
+		DUMB_RESAMPLE_PICKUP pickup;
+		void *pickup_data;
+		int min_quality;
+		int max_quality;
+		/* Everything below this point is internal: do not use. */
+		sample_t x[3];
+		int overshot;
+	};
+
+	void dumb_reset_resampler(DUMB_RESAMPLER *resampler, sample_t *src, long pos, long start, long end);
+	DUMB_RESAMPLER *dumb_start_resampler(sample_t *src, long pos, long start, long end);
+	long dumb_resample(DUMB_RESAMPLER *resampler, sample_t *dst, long dst_size, float volume, float delta);
+	sample_t dumb_resample_get_current_sample(DUMB_RESAMPLER *resampler, float volume);
+	void dumb_end_resampler(DUMB_RESAMPLER *resampler);
+
+
+	/* DUH Construction */
+
+	DUH *make_duh(
+		long length,
+		int n_signals,
+		DUH_SIGTYPE_DESC *desc[],
+		sigdata_t *sigdata[]
+	);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index b455f9916d..4806c7b00a 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -10,6 +10,7 @@ MODULE_OBJS = \
 	lib/allegro/color.o \
 	lib/allegro/config.o \
 	lib/allegro/digi.o \
+	lib/allegro/draw.o \
 	lib/allegro/error.o \
 	lib/allegro/file.o \
 	lib/allegro/fixed.o \
@@ -109,6 +110,97 @@ MODULE_OBJS = \
 	engine/ac/dynobj/scriptset.o \
 	engine/ac/statobj/agsstaticobject.o \
     engine/ac/statobj/staticarray.o \
+    engine/ac/audiochannel.o \
+    engine/ac/audioclip.o \
+    engine/ac/button.o \
+    engine/ac/cdaudio.o \
+    engine/ac/character.o \
+    engine/ac/characterextras.o \
+    engine/ac/characterinfo_engine.o \
+    engine/ac/datetime.o \
+    engine/ac/dialog.o \
+    engine/ac/dialogoptionsrendering.o \
+    engine/ac/display.o \
+    engine/ac/draw.o \
+    engine/ac/drawingsurface.o \
+    engine/ac/draw_software.o \
+    engine/ac/dynamicsprite.o \
+    engine/ac/event.o \
+    engine/ac/file.o \
+    engine/ac/game.o \
+    engine/ac/gamesetup.o \
+    engine/ac/gamestate.o \
+    engine/ac/global_api.o \
+    engine/ac/global_audio.o \
+    engine/ac/global_button.o \
+    engine/ac/global_character.o \
+    engine/ac/global_datetime.o \
+    engine/ac/global_debug.o \
+    engine/ac/global_dialog.o \
+    engine/ac/global_display.o \
+    engine/ac/global_drawingsurface.o \
+    engine/ac/global_dynamicsprite.o \
+    engine/ac/global_file.o \
+    engine/ac/global_game.o \
+    engine/ac/global_gui.o \
+    engine/ac/global_hotspot.o \
+    engine/ac/global_inventoryitem.o \
+    engine/ac/global_invwindow.o \
+    engine/ac/global_label.o \
+    engine/ac/global_listbox.o \
+    engine/ac/global_mouse.o \
+    engine/ac/global_object.o \
+    engine/ac/global_overlay.o \
+    engine/ac/global_palette.o \
+    engine/ac/global_parser.o \
+    engine/ac/global_record.o \
+    engine/ac/global_region.o \
+    engine/ac/global_room.o \
+    engine/ac/global_screen.o \
+    engine/ac/global_slider.o \
+    engine/ac/global_string.o \
+    engine/ac/global_textbox.o \
+    engine/ac/global_timer.o \
+    engine/ac/global_translation.o \
+    engine/ac/global_video.o \
+    engine/ac/global_viewframe.o \
+    engine/ac/global_viewport.o \
+    engine/ac/global_walkablearea.o \
+    engine/ac/global_walkbehind.o \
+    engine/ac/gui.o \
+    engine/ac/guicontrol.o \
+    engine/ac/guiinv.o \
+    engine/ac/hotspot.o \
+    engine/ac/interfacebutton.o \
+    engine/ac/interfaceelement.o \
+    engine/ac/inventoryitem.o \
+    engine/ac/invwindow.o \
+    engine/ac/keycode.o \
+    engine/ac/label.o \
+    engine/ac/listbox.o \
+    engine/ac/math.o \
+    engine/ac/mouse.o \
+    engine/ac/movelist.o \
+    engine/ac/object.o \
+    engine/ac/overlay.o \
+    engine/ac/parser.o \
+    engine/ac/properties.o \
+    engine/ac/route_finder_impl.o \
+    engine/ac/route_finder_impl_legacy.o \
+    engine/ac/scriptcontainers.o \
+    engine/ac/sys_events.o \
+    engine/ac/region.o \
+    engine/ac/richgamemedia.o \
+    engine/ac/room.o \
+    engine/ac/roomobject.o \
+    engine/ac/roomstatus.o \
+    engine/ac/route_finder.o \
+    engine/ac/screen.o \
+    engine/ac/screenoverlay.o \
+    engine/ac/slider.o \
+    engine/ac/speech.o \
+    engine/ac/sprite.o \
+    engine/ac/spritecache_engine.o \
 	engine/debugging/consoleoutputtarget.o \
 	engine/debugging/debug.o \
 	engine/debugging/filebasedagsdebugger.o \
diff --git a/engines/ags/shared/core/types.h b/engines/ags/shared/core/types.h
index f1e3dd1b54..b4209972a6 100644
--- a/engines/ags/shared/core/types.h
+++ b/engines/ags/shared/core/types.h
@@ -74,12 +74,14 @@ typedef int64 intptr_t;
 #define fixed_t int32_t
 #define color_t int
 
+#undef INT16_MAX
 #undef INT32_MIN
 #undef INT32_MAX
 #undef INT_MIN
 #undef INT_MAX
 #undef UINT_MAX
 #undef SIZE_MAX
+#define INT16_MAX     0x7fff
 #define INT32_MIN     (-2147483647 - 1)
 #define INT32_MAX       2147483647
 #define INT_MIN     (-2147483647 - 1)
diff --git a/engines/ags/std/algorithm.h b/engines/ags/std/algorithm.h
index 8599dc0878..6e02eed2c3 100644
--- a/engines/ags/std/algorithm.h
+++ b/engines/ags/std/algorithm.h
@@ -43,7 +43,17 @@ In fill(In first, In last, const Value &val) {
 
 template<typename T, class StrictWeakOrdering>
 void sort(T first, T last, StrictWeakOrdering comp) {
-	Common::sort<T, StrictWeakOrdering>(first, last, comp);
+	Common::sort(first, last, comp);
+}
+
+template<typename T>
+void sort(T *first, T *last) {
+	Common::sort(first, last, Common::Less<T>());
+}
+
+template<class T>
+void sort(T first, T last) {
+	Common::sort(first, last);
 }
 
 } // namespace std
diff --git a/engines/ags/std/map.h b/engines/ags/std/map.h
index 34a27bb7d1..70156b9cb2 100644
--- a/engines/ags/std/map.h
+++ b/engines/ags/std/map.h
@@ -35,8 +35,9 @@ class map : public Common::HashMap<Key, Val, HashFunc, EqualFunc> {
 public:
 	using iterator = typename Common::HashMap<Key, Val, HashFunc, EqualFunc>::iterator;
 
-	void insert(pair<Key, Val> elem) {
+	pair<Key, Val> insert(pair<Key, Val> elem) {
 		this->operator[](elem.first) = elem.second;
+		return elem;
 	}
 
 	// FUNCTION TEMPLATE lower_bound
@@ -55,8 +56,9 @@ template<class Key, class Val, class HashFunc = Common::Hash<Key>,
          class EqualFunc = Common::EqualTo<Key> >
 class unordered_map : public Common::HashMap<Key, Val, HashFunc, EqualFunc> {
 public:
-	void insert(pair<Key, Val> elem) {
+	pair<Key, Val> insert(pair<Key, Val> elem) {
 		this->operator[](elem.first) = elem.second;
+		return elem;
 	}
 
 	void reserve(size_t size) {
diff --git a/engines/ags/std/math.h b/engines/ags/std/math.h
new file mode 100644
index 0000000000..8fa5814ed6
--- /dev/null
+++ b/engines/ags/std/math.h
@@ -0,0 +1,42 @@
+/* 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 AGS_STD_MATH_H
+#define AGS_STD_MATH_H
+
+#include "common/hashmap.h"
+#include "ags/std/utility.h"
+
+namespace AGS3 {
+namespace std {
+
+#ifndef NAN
+#define NAN        ((float)(INFINITY * 0.0F))
+#endif
+
+template<class T>
+inline bool isnan(T val) { return val == NAN; }
+
+} // namespace std
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/std/queue.h b/engines/ags/std/queue.h
index 41c0653464..52761ec45d 100644
--- a/engines/ags/std/queue.h
+++ b/engines/ags/std/queue.h
@@ -23,6 +23,8 @@
 #ifndef AGS_STD_QUEUE_H
 #define AGS_STD_QUEUE_H
 
+#include "ags/std/algorithm.h"
+#include "ags/std/vector.h"
 #include "common/queue.h"
 
 namespace AGS3 {
@@ -31,6 +33,26 @@ namespace std {
 template<class T>
 using queue = Common::Queue<T>;
 
+template<class T, class Container = vector<T>, class Comparitor = typename Common::Less<T> >
+class priority_queue {
+private:
+	Container _container;
+	Comparitor _comparitor;
+public:
+	priority_queue();
+
+	bool empty() const { return _container.empty(); }
+
+	const T &top() const { return _container.front(); }
+
+	void push(const T &item) {
+		_container.push_back(item);
+		Common::sort(_container.begin(), _container.end(), _comparitor);
+	}
+
+	void pop() { _container.remove_at(0); }
+};
+
 } // namespace std
 } // namespace AGS3
 
diff --git a/engines/ags/std/set.h b/engines/ags/std/set.h
index f50a8f87e0..7815a40ed4 100644
--- a/engines/ags/std/set.h
+++ b/engines/ags/std/set.h
@@ -35,9 +35,16 @@ template<class T, class Comparitor = Common::Less<T> >
 class set : public Common::SortedArray<T, const T &> {
 private:
 	static int ComparatorFn(const T &a, const T &b) {
-		return Comparitor()(a, b) ? -1 : 0;
+		return Comparitor().operator()(a, b) ? -1 : 0;
 	}
 public:
+	struct Entry {
+		const T &_value;
+		Entry(const T &item) : _value(item) {
+		}
+	};
+public:
+	using iterator = typename Common::SortedArray<T, const T &>::iterator;
 	using const_iterator = typename Common::SortedArray<T, const T &>::const_iterator;
 
 	/**
@@ -45,6 +52,25 @@ public:
 	 */
 	set() : Common::SortedArray<T, const T &>(ComparatorFn) {}
 
+	/**
+	 * Locate an item in the set
+	 */
+	iterator find(const T &item) {
+		iterator it;
+		for (it = this->begin(); it != this->end() && *it != item; ++it) {
+		}
+
+		return it;
+	}
+
+	/**
+	 * Insert an element at the sorted position.
+	 */
+	Entry insert(const T &item) {
+		Common::SortedArray<T, const T &>::insert(item);
+		return Entry(item);
+	}
+
 	/**
 	 * Returns the number of keys that match the specified key
 	 */
@@ -53,7 +79,7 @@ public:
 		for (const_iterator it = this->begin(); it != this->end(); ++it) {
 			if (*it == item)
 				++total;
-			else if (!ComparatorFn(item, *it))
+			else if (!ComparatorFn (item, *it))
 				// Passed beyond possibility of matches
 				break;
 		}
diff --git a/engines/ags/std/unordered_set.h b/engines/ags/std/unordered_set.h
index 9ef12dd3e5..c9db4ffbde 100644
--- a/engines/ags/std/unordered_set.h
+++ b/engines/ags/std/unordered_set.h
@@ -29,15 +29,60 @@
 namespace AGS3 {
 namespace std {
 
-template <class Key, class Hash = Common::Hash<Key>, class Pred = Common::EqualTo<Key> >
-class unordered_set {
+/**
+ * Unordered set
+ * TODO: If needed, implement containers of items by unique hash of key
+ */
+template <class T, class Hash = Common::Hash<T>, class Pred = Common::EqualTo<T> >
+class unordered_set : public Common::Array<T> {
 private:
 	Hash _hash;
 	Pred _comparitor;
 public:
+	struct Entry {
+		const T &_value;
+		Entry(const T &item) : _value(item) {}
+	};
+public:
+	using iterator = typename Common::Array<T>::iterator;
+	using const_iterator = typename Common::Array<T>::const_iterator;
+
 	unordered_set() {}
 
-	// TODO: Implement whatever unordered_set methods are needed
+	/**
+	 * Locate an item in the set
+	 */
+	iterator find(const T &item) {
+		iterator it;
+		for (it = this->begin(); it != this->end() && *it != item; ++it) {
+		}
+
+		return it;
+	}
+
+	/**
+	 * Adds an item
+	 */
+	Entry insert(const T &item) {
+		this->push_back(item);
+		return Entry(item);
+	}
+
+	/**
+	 * Returns the number of keys that match the specified key
+	 */
+	size_t count(const T item) const {
+		size_t total = 0;
+		for (const_iterator it = this->begin(); it != this->end(); ++it) {
+			if (*it == item)
+				++total;
+			else if (!_comparitor(item, *it))
+				// Passed beyond possibility of matches
+				break;
+		}
+
+		return total;
+	}
 };
 
 } // namespace std
diff --git a/engines/ags/std/vector.h b/engines/ags/std/vector.h
index 84a1915d49..dffff2aa28 100644
--- a/engines/ags/std/vector.h
+++ b/engines/ags/std/vector.h
@@ -84,6 +84,9 @@ public:
 			return !operator==(rhs);
 		}
 	};
+
+	using iterator = typename Common::Array<T>::iterator;
+	using const_iterator = typename Common::Array<T>::const_iterator;
 public:
 	typedef T reference;
 	typedef const T const_reference;
@@ -97,12 +100,12 @@ public:
 		resize(newSize, elem);
 	}
 
-	typename Common::Array<T>::iterator erase(typename Common::Array<T>::iterator pos) {
+	iterator erase(iterator pos) {
 		return Common::Array<T>::erase(pos);
 	}
 
-	typename Common::Array<T>::iterator erase(typename Common::Array<T>::iterator first,
-	        typename Common::Array<T>::iterator last) {
+	iterator erase(iterator first,
+	        iterator last) {
 		Common::copy(last, this->_storage + this->_size, first);
 
 		int count = (last - first);
@@ -125,7 +128,7 @@ public:
 	 * Rotates the array so that the item pointed to by the iterator becomes
 	 * the first item, and the predeceding item becomes the last one
 	 */
-	void rotate(typename Common::Array<T>::iterator it) {
+	void rotate(iterator it) {
 		if (it != Common::Array<T>::end()) {
 			size_t count = it - Common::Array<T>::begin();
 			for (size_t ctr = 0; ctr < count; ++ctr) {
@@ -165,6 +168,30 @@ public:
 	T at(size_t index) const {
 		return (*this)[index];
 	}
+
+	/**
+	 * Adds an item to the array
+	 */
+	void insert(const T &element) {
+		Common::Array<T>::push_back(element);
+	}
+
+	/**
+	 * Adds an item to the array at a specified index
+	 */
+	void insert(iterator pos, const T &element) {
+		Common::Array<T>::insert(pos, element);
+	}
+
+	/**
+	 * Adds a range of items at the specified position in the array
+	 */
+	void insert(iterator position, const_iterator first, const_iterator last) {
+		int destIndex = position - this->begin();
+		for (; first != last; ++first) {
+			this->insert_at(destIndex++, *first);
+		}
+	}
 };
 
 } // namespace std
diff --git a/engines/ags/std/xutility.h b/engines/ags/std/xutility.h
index ac5627fbdb..e207d7fc66 100644
--- a/engines/ags/std/xutility.h
+++ b/engines/ags/std/xutility.h
@@ -24,10 +24,18 @@
 #define AGS_STD_XUTILITY_H
 
 #include "common/algorithm.h"
+#include "common/util.h"
 
 namespace AGS3 {
 namespace std {
 
+template <class T>
+void reverse(T *First, T *Last) {
+	for (; First < Last; ++First, --Last) {
+		SWAP(*First, *Last);
+	}
+}
+
 } // namespace std
 } // namespace AGS3
 


Commit: 14b1344aa06f9233411c29cf4d2e414c9bbbfe56
    https://github.com/scummvm/scummvm/commit/14b1344aa06f9233411c29cf4d2e414c9bbbfe56
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Warning fixes

Changed paths:
    engines/ags/engine/ac/character.cpp
    engines/ags/engine/ac/dialog.cpp
    engines/ags/engine/ac/display.cpp
    engines/ags/engine/ac/draw.cpp
    engines/ags/engine/ac/dynamicsprite.cpp
    engines/ags/engine/ac/dynobj/cc_guiobject.cpp
    engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp
    engines/ags/engine/ac/game.cpp
    engines/ags/engine/ac/gamestate.cpp
    engines/ags/engine/ac/roomobject.cpp
    engines/ags/engine/main/update.cpp
    engines/ags/lib/opengl/opengl.h
    engines/ags/shared/gfx/allegrobitmap.h


diff --git a/engines/ags/engine/ac/character.cpp b/engines/ags/engine/ac/character.cpp
index 4d0dc7434c..cfee01f260 100644
--- a/engines/ags/engine/ac/character.cpp
+++ b/engines/ags/engine/ac/character.cpp
@@ -750,7 +750,7 @@ void Character_SayAt(CharacterInfo *chaa, int x, int y, int width, const char *t
 
 ScriptOverlay *Character_SayBackground(CharacterInfo *chaa, const char *texx) {
 
-	int ovltype = DisplaySpeechBackground(chaa->index_id, (char *)texx);
+	int ovltype = DisplaySpeechBackground(chaa->index_id, (const char *)texx);
 	int ovri = find_overlay_of_type(ovltype);
 	if (ovri < 0)
 		quit("!SayBackground internal error: no overlay");
@@ -2291,7 +2291,7 @@ void _DisplayThoughtCore(int chid, const char *displbuf) {
 		ypp = -1;
 	}
 
-	_displayspeech((char *)displbuf, chid, xpp, ypp, width, 1);
+	_displayspeech((const char *)displbuf, chid, xpp, ypp, width, 1);
 }
 
 void _displayspeech(const char *texx, int aschar, int xx, int yy, int widd, int isThought) {
@@ -2448,7 +2448,7 @@ void _displayspeech(const char *texx, int aschar, int xx, int yy, int widd, int
 
 		if (tdyp < 0) {
 			int sppic = views[speakingChar->view].loops[speakingChar->loop].frames[0].pic;
-			int height = (charextra[aschar].height < 1) ? game.SpriteInfos[sppic].Height : height = charextra[aschar].height;
+			int height = (charextra[aschar].height < 1) ? game.SpriteInfos[sppic].Height : charextra[aschar].height;
 			tdyp = view->RoomToScreen(0, data_to_game_coord(game.chars[aschar].get_effective_y()) - height).first.Y
 			       - get_fixed_pixel_size(5);
 			if (isThought) // if it's a thought, lift it a bit further up
diff --git a/engines/ags/engine/ac/dialog.cpp b/engines/ags/engine/ac/dialog.cpp
index 4ccb896ed4..6c7d6d9f1a 100644
--- a/engines/ags/engine/ac/dialog.cpp
+++ b/engines/ags/engine/ac/dialog.cpp
@@ -337,7 +337,7 @@ int write_dialog_options(Bitmap *ds, bool ds_has_alpha, int dlgxp, int curyp, in
 	color_t text_color;
 	for (ww = 0; ww < numdisp; ww++) {
 
-		if ((dtop->optionflags[disporder[ww]] & DFLG_HASBEENCHOSEN) &&
+		if ((dtop->optionflags[(int)disporder[ww]] & DFLG_HASBEENCHOSEN) &&
 		        (play.read_dialog_option_colour >= 0)) {
 			// 'read' colour
 			text_color = ds->GetCompatibleColor(play.read_dialog_option_colour);
@@ -352,7 +352,7 @@ int write_dialog_options(Bitmap *ds, bool ds_has_alpha, int dlgxp, int curyp, in
 			else text_color = ds->GetCompatibleColor(utextcol);
 		}
 
-		break_up_text_into_lines(get_translation(dtop->optionnames[disporder[ww]]), Lines, areawid - (2 * padding + 2 + bullet_wid), usingfont);
+		break_up_text_into_lines(get_translation(dtop->optionnames[(int)disporder[ww]]), Lines, areawid - (2 * padding + 2 + bullet_wid), usingfont);
 		dispyp[ww] = curyp;
 		if (game.dialog_bullet > 0) {
 			draw_gui_sprite_v330(ds, game.dialog_bullet, dlgxp, curyp, ds_has_alpha);
@@ -381,7 +381,7 @@ int write_dialog_options(Bitmap *ds, bool ds_has_alpha, int dlgxp, int curyp, in
 #define GET_OPTIONS_HEIGHT {\
 		needheight = 0;\
 		for (int i = 0; i < numdisp; ++i) {\
-			break_up_text_into_lines(get_translation(dtop->optionnames[disporder[i]]), Lines, areawid-(2*padding+2+bullet_wid), usingfont);\
+			break_up_text_into_lines(get_translation(dtop->optionnames[(int)disporder[i]]), Lines, areawid-(2*padding+2+bullet_wid), usingfont);\
 			needheight += getheightoflines(usingfont, Lines.Count()) + data_to_game_coord(game.options[OPT_DIALOGGAP]);\
 		}\
 		if (parserInput) needheight += parserInput->Height + data_to_game_coord(game.options[OPT_DIALOGGAP]);\
@@ -664,7 +664,7 @@ void DialogOptions::Redraw() {
 		int biggest = 0;
 		padding = guis[game.options[OPT_DIALOGIFACE]].Padding;
 		for (int i = 0; i < numdisp; ++i) {
-			break_up_text_into_lines(get_translation(dtop->optionnames[disporder[i]]), Lines, areawid - ((2 * padding + 2) + bullet_wid), usingfont);
+			break_up_text_into_lines(get_translation(dtop->optionnames[(int)disporder[i]]), Lines, areawid - ((2 * padding + 2) + bullet_wid), usingfont);
 			if (longestline > biggest)
 				biggest = longestline;
 		}
diff --git a/engines/ags/engine/ac/display.cpp b/engines/ags/engine/ac/display.cpp
index 7f4574138a..9a21e70eae 100644
--- a/engines/ags/engine/ac/display.cpp
+++ b/engines/ags/engine/ac/display.cpp
@@ -553,7 +553,7 @@ void wouttext_aligned(Bitmap *ds, int usexp, int yy, int oriwid, int usingfont,
 	else if (align & kMAlignRight)
 		usexp = usexp + (oriwid - wgettextwidth_compensate(text, usingfont));
 
-	wouttext_outline(ds, usexp, yy, usingfont, text_color, (char *)text);
+	wouttext_outline(ds, usexp, yy, usingfont, text_color, (const char *)text);
 }
 
 // Get outline's thickness addition to the font's width or height
@@ -633,7 +633,7 @@ void draw_button_background(Bitmap *ds, int xx1, int yy1, int xx2, int yy2, GUIM
 			if ((loaded_game_file_version <= kGameVersion_272) // 2.xx
 				&& (spriteset[iep->BgImage]->GetWidth() == 1)
 				&& (spriteset[iep->BgImage]->GetHeight() == 1)
-				&& (*((unsigned int *)spriteset[iep->BgImage]->GetData()) == 0x00FF00FF)) {
+				&& (*((const unsigned int *)spriteset[iep->BgImage]->GetData()) == 0x00FF00FF)) {
 				// Don't draw fully transparent dummy GUI backgrounds
 			} else {
 				// offset the background image and clip it so that it is drawn
diff --git a/engines/ags/engine/ac/draw.cpp b/engines/ags/engine/ac/draw.cpp
index 6e451c414d..8f824f35c7 100644
--- a/engines/ags/engine/ac/draw.cpp
+++ b/engines/ags/engine/ac/draw.cpp
@@ -255,7 +255,7 @@ Bitmap *convert_32_to_32bgr(Bitmap *tempbl) {
 //
 Bitmap *AdjustBitmapForUseWithDisplayMode(Bitmap *bitmap, bool has_alpha) {
 	const int bmp_col_depth = bitmap->GetColorDepth();
-	const int sys_col_depth = System_GetColorDepth();
+	//const int sys_col_depth = System_GetColorDepth();
 	const int game_col_depth = game.GetColorDepth();
 	Bitmap *new_bitmap = bitmap;
 
@@ -661,7 +661,7 @@ void mark_current_background_dirty() {
 
 
 void draw_and_invalidate_text(Bitmap *ds, int x1, int y1, int font, color_t text_color, const char *text) {
-	wouttext_outline(ds, x1, y1, font, text_color, (char *)text);
+	wouttext_outline(ds, x1, y1, font, text_color, (const char *)text);
 	invalidate_rect(x1, y1, x1 + wgettextwidth_compensate(text, font), y1 + getfontheight_outlined(font) + get_fixed_pixel_size(1), false);
 }
 
diff --git a/engines/ags/engine/ac/dynamicsprite.cpp b/engines/ags/engine/ac/dynamicsprite.cpp
index 2d78b61869..1cafa99166 100644
--- a/engines/ags/engine/ac/dynamicsprite.cpp
+++ b/engines/ags/engine/ac/dynamicsprite.cpp
@@ -276,7 +276,7 @@ int DynamicSprite_SaveToFile(ScriptDynamicSprite *sds, const char *namm) {
 		quit("!DynamicSprite.SaveToFile: sprite has been deleted");
 
 	auto filename = String(namm);
-	if (filename.FindChar('.') == -1)
+	if (filename.FindChar('.') == String::npos)
 		filename.Append(".bmp");
 
 	ResolvedPath rp;
diff --git a/engines/ags/engine/ac/dynobj/cc_guiobject.cpp b/engines/ags/engine/ac/dynobj/cc_guiobject.cpp
index e8c0e35091..0f0a9a5abc 100644
--- a/engines/ags/engine/ac/dynobj/cc_guiobject.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_guiobject.cpp
@@ -37,7 +37,7 @@ const char *CCGUIObject::GetType() {
 // serialize the object into BUFFER (which is BUFSIZE bytes)
 // return number of bytes used
 int CCGUIObject::Serialize(const char *address, char *buffer, int bufsize) {
-	GUIObject *guio = (GUIObject *)address;
+	const GUIObject *guio = (const GUIObject *)address;
 	StartSerialize(buffer);
 	SerializeInt(guio->ParentId);
 	SerializeInt(guio->Id);
diff --git a/engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp b/engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp
index 041a9f7aad..4c19c95c67 100644
--- a/engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptdrawingsurface.cpp
@@ -84,7 +84,7 @@ const char *ScriptDrawingSurface::GetType() {
 
 int ScriptDrawingSurface::Serialize(const char *address, char *buffer, int bufsize) {
 	StartSerialize(buffer);
-	SerializeInt(roomBackgroundNumber & 0xFFFF | (roomMaskType << 16));
+	SerializeInt((roomBackgroundNumber & 0xFFFF) | (roomMaskType << 16));
 	SerializeInt(dynamicSpriteNumber);
 	SerializeInt(dynamicSurfaceNumber);
 	SerializeInt(currentColour);
diff --git a/engines/ags/engine/ac/game.cpp b/engines/ags/engine/ac/game.cpp
index 4b988ef1c3..b1f40dc1aa 100644
--- a/engines/ags/engine/ac/game.cpp
+++ b/engines/ags/engine/ac/game.cpp
@@ -931,7 +931,7 @@ void convert_guid_from_text_to_binary(const char *guidText, unsigned char *buffe
 		tempString[1] = guidText[1];
 		tempString[2] = 0;
 		int thisByte = 0;
-		sscanf(tempString, "%X", &thisByte);
+		sscanf(tempString, "%X", (unsigned int *)&thisByte);
 
 		buffer[bytesDone] = thisByte;
 		guidText += 2;
@@ -1392,7 +1392,7 @@ HSaveError restore_game_audioclips_and_crossfade(Stream *in, RestoredData &r_dat
 		chan_info.Pos = 0;
 		chan_info.ClipID = in->ReadInt32();
 		if (chan_info.ClipID >= 0) {
-			if ((size_t)chan_info.ClipID >= (int)game.audioClips.size()) {
+			if (chan_info.ClipID >= (int)game.audioClips.size()) {
 				return new SavegameError(kSvgErr_GameObjectInitFailed, "Invalid audio clip index.");
 			}
 
@@ -1500,7 +1500,7 @@ HSaveError restore_game_data(Stream *in, SavegameVersion svg_version, const Pres
 	if (!err)
 		return err;
 
-	if (in->ReadInt32() != MAGICNUMBER + 1) {
+	if (in->ReadInt32() != (int32)(MAGICNUMBER + 1)) {
 		return new SavegameError(kSvgErr_InconsistentFormat, "MAGICNUMBER not found before Audio Clips.");
 	}
 
@@ -1512,7 +1512,7 @@ HSaveError restore_game_data(Stream *in, SavegameVersion svg_version, const Pres
 	pl_set_file_handle(pluginFileHandle, in);
 	pl_run_plugin_hooks(AGSE_RESTOREGAME, pluginFileHandle);
 	pl_clear_file_handle();
-	if (in->ReadInt32() != (unsigned)MAGICNUMBER)
+	if (in->ReadInt32() != (int32)MAGICNUMBER)
 		return new SavegameError(kSvgErr_InconsistentPlugin);
 
 	// save the new room music vol for later use
diff --git a/engines/ags/engine/ac/gamestate.cpp b/engines/ags/engine/ac/gamestate.cpp
index 889c3a5d45..125f211b53 100644
--- a/engines/ags/engine/ac/gamestate.cpp
+++ b/engines/ags/engine/ac/gamestate.cpp
@@ -139,7 +139,7 @@ void GameState::UpdateViewports() {
 			vp->ClearChangedFlags();
 		}
 	}
-	if (vp_changed != -1)
+	if (vp_changed != (size_t)-1)
 		detect_roomviewport_overlaps(vp_changed);
 	for (auto cam : _roomCameras) {
 		if (cam->HasChangedSize() || cam->HasChangedPosition()) {
diff --git a/engines/ags/engine/ac/roomobject.cpp b/engines/ags/engine/ac/roomobject.cpp
index 8064201197..858ab3737d 100644
--- a/engines/ags/engine/ac/roomobject.cpp
+++ b/engines/ags/engine/ac/roomobject.cpp
@@ -162,7 +162,7 @@ void RoomObject::ReadFromFile(Stream *in) {
 void RoomObject::WriteToFile(Stream *out) const {
 	out->WriteArrayOfInt32(&x, 3);
 	out->WriteArrayOfInt16(&tint_r, 15);
-	out->WriteArrayOfInt8((int8_t *)&cycling, 4);
+	out->WriteArrayOfInt8((const int8_t *)&cycling, 4);
 	out->WriteArrayOfInt16(&blocking_width, 2);
 }
 
diff --git a/engines/ags/engine/main/update.cpp b/engines/ags/engine/main/update.cpp
index 9ace25d198..4f8298bc8f 100644
--- a/engines/ags/engine/main/update.cpp
+++ b/engines/ags/engine/main/update.cpp
@@ -96,21 +96,21 @@ int do_movelist_move(short *mlnum, int *xx, int *yy) {
 
 		int adjAmnt = 3;
 		// 2.70: if the X permove is also <=1, don't do the skipping
-		if (((xpermove & 0xffff0000) == 0xffff0000) ||
-			((xpermove & 0xffff0000) == 0x00000000))
+		if ((((uint32)xpermove & 0xffff0000) == 0xffff0000) ||
+			(((uint32)xpermove & 0xffff0000) == 0x00000000))
 			adjAmnt = 2;
 
 		// 2.61 RC1: correct this to work with > -1 as well as < 1
 		if (ypermove == 0) {
 		}
 		// Y per move is < 1, so finish the move
-		else if ((ypermove & 0xffff0000) == 0)
+		else if (((uint32)ypermove & 0xffff0000) == 0)
 			targety -= adjAmnt;
 		// Y per move is -1 exactly, don't snap to finish
-		else if (ypermove == 0xffff0000) {
+		else if ((uint32)ypermove == 0xffff0000) {
 		}
 		// Y per move is > -1, so finish the move
-		else if ((ypermove & 0xffff0000) == 0xffff0000)
+		else if (((uint32)ypermove & 0xffff0000) == 0xffff0000)
 			targety += adjAmnt;
 	} else xps = cmls->fromx + (int)(fixtof(xpermove) * (float)cmls->onpart);
 
@@ -120,20 +120,20 @@ int do_movelist_move(short *mlnum, int *xx, int *yy) {
 		int adjAmnt = 3;
 
 		// if the Y permove is also <=1, don't skip as far
-		if (((ypermove & 0xffff0000) == 0xffff0000) ||
+		if ((((uint32)ypermove & 0xffff0000) == 0xffff0000) ||
 			((ypermove & 0xffff0000) == 0x00000000))
 			adjAmnt = 2;
 
 		if (xpermove == 0) {
 		}
 		// Y per move is < 1, so finish the move
-		else if ((xpermove & 0xffff0000) == 0)
+		else if (((uint32)xpermove & 0xffff0000) == 0)
 			targetx -= adjAmnt;
 		// X per move is -1 exactly, don't snap to finish
-		else if (xpermove == 0xffff0000) {
+		else if ((uint32)xpermove == 0xffff0000) {
 		}
 		// X per move is > -1, so finish the move
-		else if ((xpermove & 0xffff0000) == 0xffff0000)
+		else if (((uint32)xpermove & 0xffff0000) == 0xffff0000)
 			targetx += adjAmnt;
 
 		/*    int xpmm=(xpermove >> 16) & 0x0000ffff;
diff --git a/engines/ags/lib/opengl/opengl.h b/engines/ags/lib/opengl/opengl.h
index 3e6ecd89cf..2525645547 100644
--- a/engines/ags/lib/opengl/opengl.h
+++ b/engines/ags/lib/opengl/opengl.h
@@ -122,7 +122,7 @@ inline void glViewport(GLint x, GLint y, GLsizei width, GLsizei height) {}
 inline void glMatrixMode(GLenum mode) {}
 inline void glLoadIdentity() {}
 inline void glOrtho(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top,
-	GLdouble nearVal, GLdouble farVal);
+	GLdouble nearVal, GLdouble farVal) {}
 inline void glEnableClientState(GLenum arr) {}
 inline void glDisableClientState(GLenum arr) {}
 inline void glUseProgram(GLuint program) {}
@@ -131,10 +131,10 @@ inline void glUniform3f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2) {}
 inline void glUniform1i(GLint location, GLint v0) {}
 inline void glTranslatef(GLfloat x, GLfloat y, GLfloat z) {}
 inline void glMultMatrixf(const GLfloat *m) {}
-inline void glRotatef(GLfloat angle, GLfloat x, GLfloat y, GLfloat z);
-inline void glScalef(GLfloat x, GLfloat y, GLfloat z);
+inline void glRotatef(GLfloat angle, GLfloat x, GLfloat y, GLfloat z) {}
+inline void glScalef(GLfloat x, GLfloat y, GLfloat z) {}
 inline void glBindTexture(GLenum target, GLuint texture) {}
-inline void glTexCoordPointer(GLint size, GLenum type, GLsizei stride, const void *pointer);
+inline void glTexCoordPointer(GLint size, GLenum type, GLsizei stride, const void *pointer) {}
 inline void glVertexPointer(GLint size, GLenum type, GLsizei stride, const void *pointer) {}
 inline void glBindFramebufferEXT(GLenum v1, uint v2) {}
 inline void glDeleteFramebuffersEXT(int v1, uint *v2) {}
diff --git a/engines/ags/shared/gfx/allegrobitmap.h b/engines/ags/shared/gfx/allegrobitmap.h
index 37ba3fcd97..3b04c369eb 100644
--- a/engines/ags/shared/gfx/allegrobitmap.h
+++ b/engines/ags/shared/gfx/allegrobitmap.h
@@ -132,6 +132,9 @@ public:
 	inline const unsigned char *GetScanLine(int index) const {
 		return (index >= 0 && index < GetHeight()) ? _alBitmap->getBasePtr(0, index) : nullptr;
 	}
+	inline unsigned char *GetScanLine(int index) {
+		return (index >= 0 && index < GetHeight()) ? (unsigned char *)_alBitmap->getBasePtr(0, index) : nullptr;
+	}
 
 	void    SetMaskColor(color_t color);
 	inline color_t GetMaskColor() const {


Commit: 12dc2c220fd93202f96e2205477332ba662b3590
    https://github.com/scummvm/scummvm/commit/12dc2c220fd93202f96e2205477332ba662b3590
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added shared/font/ folder

Changed paths:
  A engines/ags/lib/alfont/alfont.cpp
  A engines/ags/lib/alfont/alfont.h
    engines/ags/engine/font/fonts_engine.cpp
    engines/ags/lib/allegro/gfx.h
    engines/ags/module.mk
    engines/ags/shared/font/fonts.cpp
    engines/ags/shared/font/ttffontrenderer.cpp
    engines/ags/shared/font/ttffontrenderer.h
    engines/ags/shared/font/wfnfont.cpp
    engines/ags/shared/font/wfnfontrenderer.h
    engines/ags/std/algorithm.h


diff --git a/engines/ags/engine/font/fonts_engine.cpp b/engines/ags/engine/font/fonts_engine.cpp
index b52947b26c..cd608b7a97 100644
--- a/engines/ags/engine/font/fonts_engine.cpp
+++ b/engines/ags/engine/font/fonts_engine.cpp
@@ -26,7 +26,7 @@
 //
 //=============================================================================
 
-//include <alfont.h>
+#include "ags/lib/alfont/alfont.h"
 #include "ags/shared/ac/gamesetupstruct.h"
 
 namespace AGS3 {
diff --git a/engines/ags/lib/alfont/alfont.cpp b/engines/ags/lib/alfont/alfont.cpp
new file mode 100644
index 0000000000..3a69e8e7b4
--- /dev/null
+++ b/engines/ags/lib/alfont/alfont.cpp
@@ -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.
+ *
+ */
+
+#include "ags/lib/alfont/alfont.h"
+#include "common/file.h"
+#include "graphics/fonts/ttf.h"
+
+namespace AGS3 {
+
+Graphics::Font *ALFONT_FONT::getFont() {
+	if (!_fonts.contains(_size)) {
+		Common::File f;
+		if (!f.open(_filename))
+			error("Could not read font - %s", _filename.c_str());
+		_fonts[_size] = Graphics::loadTTFFont(f, f.size());
+		f.close();
+
+		assert(_fonts[_size]);
+	}
+
+	return _fonts[_size];
+}
+
+/*------------------------------------------------------------------*/
+
+ALFONT_FONT *alfont_loadFont(const Common::String &filename) {
+	ALFONT_FONT *result = new ALFONT_FONT();
+	result->_filename = filename;
+
+	return result;
+}
+
+void alfont_destroy_font(ALFONT_FONT *font) {
+	delete font;
+}
+
+size_t alfont_text_length(ALFONT_FONT *font, const char *text) {
+	return font->getFont()->getStringWidth(text);
+}
+
+size_t alfont_text_height(ALFONT_FONT *font) {
+	return font->getFont()->getFontHeight();
+}
+
+void alfont_textout(BITMAP *bmp, ALFONT_FONT *font, const char *text, int x, int y, uint32 color) {
+	Graphics::ManagedSurface &surf = **bmp;
+	font->getFont()->drawString(&surf, Common::U32String(text), x, y, bmp->w - x, color);
+}
+
+void alfont_textout_aa(BITMAP *bmp, ALFONT_FONT *font, const char *text, int x, int y, uint32 color) {
+	alfont_textout(bmp, font, text, x, y, color);
+}
+
+void alfont_set_font_size(ALFONT_FONT *font, int size) {
+	font->_size = size;
+}
+
+const char *alfont_get_name(ALFONT_FONT *font) {
+	// TODO: Return ttf font name
+	return "Unsupported";
+}
+
+} // namespace AGS3
diff --git a/engines/ags/lib/alfont/alfont.h b/engines/ags/lib/alfont/alfont.h
new file mode 100644
index 0000000000..d3f92e2451
--- /dev/null
+++ b/engines/ags/lib/alfont/alfont.h
@@ -0,0 +1,65 @@
+/* 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 AGS_LIB_ALFONT_H
+#define AGS_LIB_ALFONT_H
+
+#include "common/hashmap.h"
+#include "graphics/font.h"
+#include "ags/lib/allegro/gfx.h"
+
+namespace AGS3 {
+
+struct ALFONT_FONT {
+	Common::String _filename;
+	int _size;
+	Common::HashMap<int, Graphics::Font *> _fonts;
+
+	ALFONT_FONT() : _size(-1) {}
+	ALFONT_FONT(const Common::String &filename) : _filename(filename), _size(-1) {}
+
+	~ALFONT_FONT() {
+		for (Common::HashMap<int, Graphics::Font *>::iterator it = _fonts.begin();
+			it != _fonts.end(); ++it)
+			delete (*it)._value;
+	}
+
+	Graphics::Font *getFont();
+};
+
+inline void alfont_init() {}
+inline void alfont_exit() {}
+inline void alfont_text_mode(int val) {}
+extern ALFONT_FONT *alfont_loadFont(const Common::String &filename);
+extern void alfont_destroy_font(ALFONT_FONT *font);
+
+extern size_t alfont_text_length(ALFONT_FONT *font, const char *text);
+extern size_t alfont_text_height(ALFONT_FONT *font);
+extern void alfont_textout(BITMAP *bmp, ALFONT_FONT *font, const char *text, int x, int y, uint32 color);
+extern void alfont_textout_aa(BITMAP *bmp, ALFONT_FONT *font, const char *text, int x, int y, uint32 color);
+extern const char *alfont_get_name(ALFONT_FONT *font);
+extern void alfont_set_font_size(ALFONT_FONT *font, int size);
+
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/lib/allegro/gfx.h b/engines/ags/lib/allegro/gfx.h
index 66dbdc3be3..11a1c07a16 100644
--- a/engines/ags/lib/allegro/gfx.h
+++ b/engines/ags/lib/allegro/gfx.h
@@ -225,7 +225,6 @@ AL_FUNC(void, release_bitmap, (BITMAP *bitmap));
 AL_FUNC(void, draw_sprite, (BITMAP *bmp, const BITMAP *sprite, int x, int y));
 AL_FUNC(void, stretch_sprite, (BITMAP *bmp, const BITMAP *sprite, int x, int y, int w, int h));
 
-
 extern void clear_to_color(BITMAP *bitmap, int color);
 extern int bitmap_color_depth(BITMAP *bmp);
 extern int bitmap_mask_color(BITMAP *bmp);
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 4806c7b00a..f1e905fb1a 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -6,6 +6,7 @@ MODULE_OBJS = \
 	lib/aastr-0.1.1/aarot.o \
 	lib/aastr-0.1.1/aastr.o \
 	lib/aastr-0.1.1/aautil.o \
+	lib/alfont/alfont.o \
 	lib/allegro.o \
 	lib/allegro/color.o \
 	lib/allegro/config.o \
@@ -38,6 +39,10 @@ MODULE_OBJS = \
 	shared/core/asset.o \
 	shared/core/assetmanager.o \
 	shared/debugging/debugmanager.o \
+	shared/font/fonts.o \
+	shared/font/ttffontrenderer.o \
+	shared/font/wfnfont.o \
+	shared/font/wfnfontrenderer.o \
 	shared/game/customproperties.o \
 	shared/game/interactions.o \
 	shared/game/room_file.o \
diff --git a/engines/ags/shared/font/fonts.cpp b/engines/ags/shared/font/fonts.cpp
index 0bc9c8505c..ad4c4c5ab2 100644
--- a/engines/ags/shared/font/fonts.cpp
+++ b/engines/ags/shared/font/fonts.cpp
@@ -20,9 +20,8 @@
  *
  */
 
-//include <cstdio>
 #include "ags/std/vector.h"
-//include <alfont.h>
+#include "ags/lib/alfont/alfont.h"
 #include "ags/shared/ac/common.h" // set_our_eip
 #include "ags/shared/ac/gamestructdefines.h"
 #include "ags/shared/font/fonts.h"
@@ -241,7 +240,7 @@ size_t split_lines(const char *todis, SplitLines &lines, int wii, int fonnt, siz
 	size_t splitAt;
 	char nextCharWas;
 	while (1) {
-		splitAt = -1;
+		splitAt = (size_t)-1;
 
 		if (theline[i] == 0) {
 			// end of the text, add the last line if necessary
@@ -294,7 +293,7 @@ size_t split_lines(const char *todis, SplitLines &lines, int wii, int fonnt, siz
 			// skip the space or new line that caused the line break
 			if ((theline[0] == ' ') || (theline[0] == '\n'))
 				theline++;
-			i = -1;
+			i = (size_t)-1;
 		}
 
 		i++;
@@ -302,7 +301,7 @@ size_t split_lines(const char *todis, SplitLines &lines, int wii, int fonnt, siz
 	return lines.Count();
 }
 
-void wouttextxy(Common::Bitmap *ds, int xxx, int yyy, size_t fontNumber, color_t text_color, const char *texx) {
+void wouttextxy(Shared::Bitmap *ds, int xxx, int yyy, size_t fontNumber, color_t text_color, const char *texx) {
 	if (fontNumber >= fonts.size())
 		return;
 	yyy += fonts[fontNumber].Info.YOffset;
@@ -343,7 +342,7 @@ bool wloadfont_size(size_t fontNumber, const FontInfo &font_info) {
 	return false;
 }
 
-void wgtprintf(Common::Bitmap *ds, int xxx, int yyy, size_t fontNumber, color_t text_color, char *fmt, ...) {
+void wgtprintf(Shared::Bitmap *ds, int xxx, int yyy, size_t fontNumber, color_t text_color, char *fmt, ...) {
 	if (fontNumber >= fonts.size())
 		return;
 
diff --git a/engines/ags/shared/font/ttffontrenderer.cpp b/engines/ags/shared/font/ttffontrenderer.cpp
index dfbf669d21..34a5489fa9 100644
--- a/engines/ags/shared/font/ttffontrenderer.cpp
+++ b/engines/ags/shared/font/ttffontrenderer.cpp
@@ -20,7 +20,8 @@
  *
  */
 
-//include <alfont.h>
+#include "ags/lib/alfont/alfont.h"
+#include "ags/lib/allegro/gfx.h"
 #include "ags/shared/core/platform.h"
 
 #define AGS_OUTLINE_FONT_FIX (!AGS_PLATFORM_OS_WINDOWS)
@@ -91,21 +92,8 @@ bool TTFFontRenderer::IsBitmapFont() {
 
 bool TTFFontRenderer::LoadFromDiskEx(int fontNumber, int fontSize, const FontRenderParams *params) {
 	String file_name = String::FromFormat("agsfnt%d.ttf", fontNumber);
-	Stream *reader = AssetManager::OpenAsset(file_name);
-	char *membuffer;
-
-	if (reader == nullptr)
-		return false;
-
-	long lenof = AssetManager::GetLastAssetSize();
-
-	membuffer = (char *)malloc(lenof);
-	reader->ReadArray(membuffer, lenof, 1);
-	delete reader;
-
-	ALFONT_FONT *alfptr = alfont_load_font_from_mem(membuffer, lenof);
-	free(membuffer);
 
+	ALFONT_FONT *alfptr = alfont_loadFont(file_name);
 	if (alfptr == nullptr)
 		return false;
 
diff --git a/engines/ags/shared/font/ttffontrenderer.h b/engines/ags/shared/font/ttffontrenderer.h
index 38e1fab00f..368dac016e 100644
--- a/engines/ags/shared/font/ttffontrenderer.h
+++ b/engines/ags/shared/font/ttffontrenderer.h
@@ -23,13 +23,12 @@
 #ifndef AGS_SHARED_FONT_TTFFONTRENDERER_H
 #define AGS_SHARED_FONT_TTFFONTRENDERER_H
 
-//include <map>
+#include "ags/std/map.h"
+#include "ags/lib/alfont/alfont.h"
 #include "ags/shared/font/agsfontrenderer.h"
 
 namespace AGS3 {
 
-struct ALFONT_FONT;
-
 class TTFFontRenderer : public IAGSFontRenderer, public IAGSFontRenderer2 {
 public:
 	// IAGSFontRenderer implementation
diff --git a/engines/ags/shared/font/wfnfont.cpp b/engines/ags/shared/font/wfnfont.cpp
index ce76cda9e3..c98d5e3d1c 100644
--- a/engines/ags/shared/font/wfnfont.cpp
+++ b/engines/ags/shared/font/wfnfont.cpp
@@ -109,7 +109,12 @@ WFNError WFNFont::ReadFromFile(Stream *in, const soff_t data_size) {
 	}
 	// sort offsets vector and remove any duplicates
 	std::sort(offs.begin(), offs.end());
+#if AGS_PLATFORM_SCUMMVM
+	// TODO: See if this works correctly
+	std::unique(offs.begin(), offs.end());
+#else
 	std::vector<uint16_t>(offs.begin(), std::unique(offs.begin(), offs.end())).swap(offs);
+#endif
 
 	// Now that we know number of valid character items, parse and store character data
 	WFNChar init_ch;
@@ -155,7 +160,7 @@ WFNError WFNFont::ReadFromFile(Stream *in, const soff_t data_size) {
 		_items[i].RestrictToBytes(src_size);
 
 		assert(pixel_it + pixel_data_size <= _pixelData.end()); // should not normally fail
-		std::copy(raw_data + raw_off, raw_data + raw_off + src_size, pixel_it);
+		Common::copy(raw_data + raw_off, raw_data + raw_off + src_size, pixel_it);
 		_items[i].Data = &(*pixel_it);
 		pixel_it += pixel_data_size;
 	}
diff --git a/engines/ags/shared/font/wfnfontrenderer.h b/engines/ags/shared/font/wfnfontrenderer.h
index 25fe6930d4..76d57efe9b 100644
--- a/engines/ags/shared/font/wfnfontrenderer.h
+++ b/engines/ags/shared/font/wfnfontrenderer.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_FONT_WFNFONTRENDERER_H
 #define AGS_SHARED_FONT_WFNFONTRENDERER_H
 
-//include <map>
+#include "ags/std/map.h"
 #include "ags/shared/font/agsfontrenderer.h"
 
 namespace AGS3 {
diff --git a/engines/ags/std/algorithm.h b/engines/ags/std/algorithm.h
index 6e02eed2c3..f95335f351 100644
--- a/engines/ags/std/algorithm.h
+++ b/engines/ags/std/algorithm.h
@@ -56,6 +56,37 @@ void sort(T first, T last) {
 	Common::sort(first, last);
 }
 
+template<class T>
+T unique(T first, T last) {
+	T pos;
+	for (pos = first + 1; pos < last; ++pos) {
+		// Check for duplicate
+		for (T existingPos = first; existingPos < last; ++existingPos) {
+			if (*pos == *existingPos) {
+				// Found a match, so shift values over the duplicate
+				while (pos < (last - 1)) {
+					*pos++ = *(pos + 1);
+				}
+
+				--last;
+				break;
+			}
+		}
+	}
+
+	return pos;
+}
+
+template<class ForwardIt, class T>
+ForwardIt lower_bound(ForwardIt first, ForwardIt last, const T &value) {
+	for (ForwardIt it = first; it < last; ++it) {
+		if (*it >= value)
+			return it;
+	}
+
+	return last;
+}
+
 } // namespace std
 } // namespace AGS3
 


Commit: 77cdd07d6f972e6b2c58d7a735848dc9d8df9e07
    https://github.com/scummvm/scummvm/commit/77cdd07d6f972e6b2c58d7a735848dc9d8df9e07
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added engine/media/audio/ folder

Changed paths:
  A engines/ags/lib/audio/digi.cpp
  A engines/ags/lib/audio/digi.h
  A engines/ags/lib/audio/midi.cpp
  A engines/ags/lib/audio/midi.h
  A engines/ags/lib/audio/mod.cpp
  A engines/ags/lib/audio/mod.h
  A engines/ags/lib/audio/mp3.cpp
  A engines/ags/lib/audio/mp3.h
  A engines/ags/lib/audio/ogg.cpp
  A engines/ags/lib/audio/ogg.h
  A engines/ags/lib/audio/sound.cpp
  A engines/ags/lib/audio/sound.h
  A engines/ags/lib/audio/wav.cpp
  A engines/ags/lib/audio/wav.h
  R engines/ags/lib/allegro/digi.cpp
  R engines/ags/lib/allegro/digi.h
  R engines/ags/lib/allegro/midi.cpp
  R engines/ags/lib/allegro/midi.h
  R engines/ags/lib/allegro/sound.h
    engines/ags/configure.engine
    engines/ags/engine/media/audio/ambientsound.cpp
    engines/ags/engine/media/audio/audio.cpp
    engines/ags/engine/media/audio/clip_mydumbmod.cpp
    engines/ags/engine/media/audio/clip_mydumbmod.h
    engines/ags/engine/media/audio/clip_myjgmod.cpp
    engines/ags/engine/media/audio/clip_myjgmod.h
    engines/ags/engine/media/audio/clip_mymidi.cpp
    engines/ags/engine/media/audio/clip_mymidi.h
    engines/ags/engine/media/audio/clip_mymp3.cpp
    engines/ags/engine/media/audio/clip_mymp3.h
    engines/ags/engine/media/audio/clip_myogg.cpp
    engines/ags/engine/media/audio/clip_myogg.h
    engines/ags/engine/media/audio/clip_mystaticmp3.cpp
    engines/ags/engine/media/audio/clip_mystaticmp3.h
    engines/ags/engine/media/audio/clip_mystaticogg.cpp
    engines/ags/engine/media/audio/clip_mystaticogg.h
    engines/ags/engine/media/audio/clip_mywave.cpp
    engines/ags/engine/media/audio/clip_mywave.h
    engines/ags/engine/media/audio/queuedaudioitem.cpp
    engines/ags/engine/media/audio/sound.cpp
    engines/ags/engine/media/audio/soundcache.cpp
    engines/ags/engine/media/audio/soundclip.cpp
    engines/ags/lib/allegro.h
    engines/ags/lib/allegro/sound.cpp
    engines/ags/module.mk


diff --git a/engines/ags/configure.engine b/engines/ags/configure.engine
index 55cba93bb4..6149895b71 100644
--- a/engines/ags/configure.engine
+++ b/engines/ags/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 ags "Adventure Game Studio" no "" "" "cxx11"
+add_engine ags "Adventure Game Studio" no "" "" "cxx11 mp3 ogg"
diff --git a/engines/ags/engine/media/audio/ambientsound.cpp b/engines/ags/engine/media/audio/ambientsound.cpp
index 94e1e0cbb6..4010abc0dd 100644
--- a/engines/ags/engine/media/audio/ambientsound.cpp
+++ b/engines/ags/engine/media/audio/ambientsound.cpp
@@ -20,9 +20,9 @@
  *
  */
 
-#include "ags/shared/media/audio/ambientsound.h"
-#include "ags/shared/media/audio/audio.h"
-#include "ags/shared/media/audio/soundclip.h"
+#include "ags/engine/media/audio/ambientsound.h"
+#include "ags/engine/media/audio/audio.h"
+#include "ags/engine/media/audio/soundclip.h"
 #include "ags/shared/util/stream.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/media/audio/audio.cpp b/engines/ags/engine/media/audio/audio.cpp
index 414db622ae..0d4ca41d3b 100644
--- a/engines/ags/engine/media/audio/audio.cpp
+++ b/engines/ags/engine/media/audio/audio.cpp
@@ -20,32 +20,30 @@
  *
  */
 
-//include <math.h>
-
 #include "ags/shared/core/platform.h"
 #include "ags/shared/util/wgt2allg.h"
-#include "ags/shared/media/audio/audio.h"
+#include "ags/engine/media/audio/audio.h"
 #include "ags/shared/ac/audiocliptype.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/dynobj/cc_audioclip.h"
-#include "ags/shared/ac/dynobj/cc_audiochannel.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/script/script_runtime.h"
-#include "ags/shared/ac/audiochannel.h"
-#include "ags/shared/ac/audioclip.h"
-#include "ags/shared/ac/gamesetup.h"
-#include "ags/shared/ac/path_helper.h"
-#include "ags/shared/media/audio/sound.h"
-#include "ags/shared/debugging/debug_log.h"
-#include "ags/shared/debugging/debugger.h"
+#include "ags/engine/ac/dynobj/cc_audioclip.h"
+#include "ags/engine/ac/dynobj/cc_audiochannel.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/script/script_runtime.h"
+#include "ags/engine/ac/audiochannel.h"
+#include "ags/engine/ac/audioclip.h"
+#include "ags/engine/ac/gamesetup.h"
+#include "ags/engine/ac/path_helper.h"
+#include "ags/engine/media/audio/sound.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/debugging/debugger.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/file.h"
-#include "ags/shared/ac/global_audio.h"
-//include <math.h>
+#include "ags/engine/ac/file.h"
+#include "ags/engine/ac/global_audio.h"
 #include "ags/shared/util/stream.h"
 #include "ags/shared/core/assetmanager.h"
-#include "ags/shared/ac/timer.h"
-#include "ags/shared/main/game_run.h"
+#include "ags/engine/ac/timer.h"
+#include "ags/engine/main/game_run.h"
+#include "ags/lib/audio/sound.h"
 
 namespace AGS3 {
 
@@ -55,7 +53,7 @@ using namespace AGS::Engine;
 //-----------------------
 //sound channel management; all access goes through here, which can't be done without a lock
 
-static std::array < SOUNDCLIP *, MAX_SOUND_CHANNELS + 1 > _channels;
+static std::array<SOUNDCLIP *> _channels(MAX_SOUND_CHANNELS + 1);
 AGS::Engine::Mutex AudioChannelsLock::s_mutex;
 
 SOUNDCLIP *AudioChannelsLock::GetChannel(int index) {
@@ -546,7 +544,7 @@ void force_audiostream_include() {
 }
 
 // TODO: double check that ambient sounds array actually needs +1
-std::array < AmbientSound, MAX_SOUND_CHANNELS + 1 > ambient;
+std::array<AmbientSound> ambient(MAX_SOUND_CHANNELS + 1);
 
 int get_volume_adjusted_for_distance(int volume, int sndX, int sndY, int sndMaxDist) {
 	int distx = playerchar->x - sndX;
@@ -682,9 +680,9 @@ static int play_sound_priority(int val1, int priority) {
 			if (usechan >= 0) {
 				// channel will hold a different clip here
 				assert(usechan == i);
-				auto *ch = lock.GetChannel(usechan);
-				if (ch)
-					ch->priority = priority;
+				auto *chan = lock.GetChannel(usechan);
+				if (chan)
+					chan->priority = priority;
 			}
 			return usechan;
 		} else if (ch->priority < lowest_pri) {
diff --git a/engines/ags/engine/media/audio/clip_mydumbmod.cpp b/engines/ags/engine/media/audio/clip_mydumbmod.cpp
index d863bce0dc..d5c2262379 100644
--- a/engines/ags/engine/media/audio/clip_mydumbmod.cpp
+++ b/engines/ags/engine/media/audio/clip_mydumbmod.cpp
@@ -20,12 +20,12 @@
  *
  */
 
-#include "ags/shared/media/audio/audiodefines.h"
+#include "ags/engine/media/audio/audiodefines.h"
 
 #ifdef DUMB_MOD_PLAYER
 
-#include "ags/shared/media/audio/clip_mydumbmod.h"
-#include "ags/shared/media/audio/audiointernaldefs.h"
+#include "ags/engine/media/audio/clip_mydumbmod.h"
+#include "ags/engine/media/audio/audiointernaldefs.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/media/audio/clip_mydumbmod.h b/engines/ags/engine/media/audio/clip_mydumbmod.h
index fcd2f6cb74..927eee6f89 100644
--- a/engines/ags/engine/media/audio/clip_mydumbmod.h
+++ b/engines/ags/engine/media/audio/clip_mydumbmod.h
@@ -23,8 +23,8 @@
 #ifndef AGS_ENGINE_MEDIA_AUDIO_CLIP_MYDUMBMOD_H
 #define AGS_ENGINE_MEDIA_AUDIO_CLIP_MYDUMBMOD_H
 
-#include "ags/shared/aldumb.h"
-#include "ags/shared/media/audio/soundclip.h"
+#include "ags/lib/aldumb.h"
+#include "ags/engine/media/audio/soundclip.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/media/audio/clip_myjgmod.cpp b/engines/ags/engine/media/audio/clip_myjgmod.cpp
index 6f1fed0492..73fd0004de 100644
--- a/engines/ags/engine/media/audio/clip_myjgmod.cpp
+++ b/engines/ags/engine/media/audio/clip_myjgmod.cpp
@@ -20,12 +20,12 @@
  *
  */
 
-#include "ags/shared/media/audio/audiodefines.h"
+#include "ags/engine/media/audio/audiodefines.h"
 
 #ifdef JGMOD_MOD_PLAYER
 
-#include "ags/shared/media/audio/clip_myjgmod.h"
-#include "ags/shared/media/audio/audiointernaldefs.h"
+#include "ags/engine/media/audio/clip_myjgmod.h"
+#include "ags/engine/media/audio/audiointernaldefs.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/media/audio/clip_myjgmod.h b/engines/ags/engine/media/audio/clip_myjgmod.h
index 1649492823..ad5058e8d4 100644
--- a/engines/ags/engine/media/audio/clip_myjgmod.h
+++ b/engines/ags/engine/media/audio/clip_myjgmod.h
@@ -23,8 +23,8 @@
 #ifndef AGS_ENGINE_MEDIA_AUDIO_CLIP_MYJGMOD_H
 #define AGS_ENGINE_MEDIA_AUDIO_CLIP_MYJGMOD_H
 
-#include "ags/shared/jgmod.h"
-#include "ags/shared/media/audio/soundclip.h"
+#include "ags/lib/audio/mod.h"
+#include "ags/engine/media/audio/soundclip.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/media/audio/clip_mymidi.cpp b/engines/ags/engine/media/audio/clip_mymidi.cpp
index ed60c2f25c..2dfbb72041 100644
--- a/engines/ags/engine/media/audio/clip_mymidi.cpp
+++ b/engines/ags/engine/media/audio/clip_mymidi.cpp
@@ -20,10 +20,10 @@
  *
  */
 
-#include "ags/shared/media/audio/audiodefines.h"
+#include "ags/engine/media/audio/audiodefines.h"
 #include "ags/shared/util/wgt2allg.h"
-#include "ags/shared/media/audio/clip_mymidi.h"
-#include "ags/shared/media/audio/audiointernaldefs.h"
+#include "ags/engine/media/audio/clip_mymidi.h"
+#include "ags/engine/media/audio/audiointernaldefs.h"
 
 namespace AGS3 {
 
@@ -40,7 +40,7 @@ void MYMIDI::adjust_volume() {
 	if (!is_playing()) {
 		return;
 	}
-	::set_volume(-1, get_final_volume());
+	AGS3::set_volume(-1, get_final_volume());
 }
 
 void MYMIDI::set_volume(int newvol) {
@@ -112,7 +112,7 @@ int MYMIDI::play() {
 	}
 
 	lengthInSeconds = get_midi_length(tune);
-	if (::play_midi(tune, repeat)) {
+	if (AGS3::play_midi(tune, repeat)) {
 		return 0;
 	}
 
diff --git a/engines/ags/engine/media/audio/clip_mymidi.h b/engines/ags/engine/media/audio/clip_mymidi.h
index 8a802867b3..87e21d7704 100644
--- a/engines/ags/engine/media/audio/clip_mymidi.h
+++ b/engines/ags/engine/media/audio/clip_mymidi.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_MEDIA_AUDIO_CLIP_MYMIDI_H
 #define AGS_ENGINE_MEDIA_AUDIO_CLIP_MYMIDI_H
 
-#include "ags/shared/media/audio/soundclip.h"
+#include "ags/engine/media/audio/soundclip.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/media/audio/clip_mymp3.cpp b/engines/ags/engine/media/audio/clip_mymp3.cpp
index 0519eb413d..66e9674d3d 100644
--- a/engines/ags/engine/media/audio/clip_mymp3.cpp
+++ b/engines/ags/engine/media/audio/clip_mymp3.cpp
@@ -20,17 +20,17 @@
  *
  */
 
-#include "ags/shared/media/audio/audiodefines.h"
+#include "ags/engine/media/audio/audiodefines.h"
 
 #ifndef NO_MP3_PLAYER
 
-#include "ags/shared/media/audio/clip_mymp3.h"
-#include "ags/shared/media/audio/audiointernaldefs.h"
+#include "ags/engine/media/audio/clip_mymp3.h"
+#include "ags/engine/media/audio/audiointernaldefs.h"
 #include "ags/shared/ac/common.h"               // quit()
-#include "ags/shared/ac/asset_helper.h"
-#include "ags/shared/util/mutex_lock.h"
+#include "ags/engine/ac/asset_helper.h"
+#include "ags/engine/util/mutex_lock.h"
 
-#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
 
 namespace AGS3 {
 
@@ -38,7 +38,7 @@ void MYMP3::poll() {
 	if (state_ != SoundClipPlaying) {
 		return;
 	}
-
+#if !AGS_PLATFORM_SCUMMVM
 	// update the buffer
 	char *tempbuf = nullptr;
 	{
@@ -60,7 +60,7 @@ void MYMP3::poll() {
 			almp3_free_mp3stream_buffer(stream, free_val);
 		}
 	}
-
+#endif
 	{
 		AGS::Engine::MutexLock _lockMp3(_mp3_mutex);
 		if (almp3_poll_mp3stream(stream) == ALMP3_POLL_PLAYJUSTFINISHED) {
diff --git a/engines/ags/engine/media/audio/clip_mymp3.h b/engines/ags/engine/media/audio/clip_mymp3.h
index cdd034b9bb..787bd5a3f3 100644
--- a/engines/ags/engine/media/audio/clip_mymp3.h
+++ b/engines/ags/engine/media/audio/clip_mymp3.h
@@ -23,8 +23,9 @@
 #ifndef AGS_ENGINE_MEDIA_AUDIO_CLIP_MYMP3_H
 #define AGS_ENGINE_MEDIA_AUDIO_CLIP_MYMP3_H
 
-#include "ags/shared/almp3.h"
-#include "ags/shared/media/audio/soundclip.h"
+#include "ags/lib/audio/mp3.h"
+#include "ags/lib/allegro/file.h"
+#include "ags/engine/media/audio/soundclip.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/media/audio/clip_myogg.cpp b/engines/ags/engine/media/audio/clip_myogg.cpp
index 6c5539d1bf..c2c16a770d 100644
--- a/engines/ags/engine/media/audio/clip_myogg.cpp
+++ b/engines/ags/engine/media/audio/clip_myogg.cpp
@@ -20,29 +20,23 @@
  *
  */
 
-#include "ags/shared/media/audio/audiodefines.h"
-#include "ags/shared/media/audio/clip_myogg.h"
-#include "ags/shared/media/audio/audiointernaldefs.h"
+#include "ags/lib/audio/digi.h"
+#include "ags/engine/media/audio/audiodefines.h"
+#include "ags/engine/media/audio/clip_myogg.h"
+#include "ags/engine/media/audio/audiointernaldefs.h"
 #include "ags/shared/ac/common.h"               // quit()
-#include "ags/shared/ac/asset_helper.h"
-#include "ags/shared/util/mutex_lock.h"
+#include "ags/engine/ac/asset_helper.h"
+#include "ags/engine/util/mutex_lock.h"
 
-#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
 
 namespace AGS3 {
 
-extern "C" {
-	extern int alogg_is_end_of_oggstream(ALOGG_OGGSTREAM *ogg);
-	extern int alogg_is_end_of_ogg(ALOGG_OGG *ogg);
-	extern int alogg_get_ogg_freq(ALOGG_OGG *ogg);
-	extern int alogg_get_ogg_stereo(ALOGG_OGG *ogg);
-}
-
 void MYOGG::poll() {
 	if (state_ != SoundClipPlaying) {
 		return;
 	}
-
+#if !AGS_PLATFORM_SCUMMVM
 	AGS_PACKFILE_OBJ *obj = (AGS_PACKFILE_OBJ *)in->userdata;
 	if (obj->remains > 0) {
 		// update the buffer
@@ -57,7 +51,7 @@ void MYOGG::poll() {
 			alogg_free_oggstream_buffer(stream, free_val);
 		}
 	}
-
+#endif
 	int ret = alogg_poll_oggstream(stream);
 	if (ret == ALOGG_OK || ret == ALOGG_POLL_BUFFERUNDERRUN)
 		get_pos_ms();  // call this to keep the last_but_one stuff up to date
diff --git a/engines/ags/engine/media/audio/clip_myogg.h b/engines/ags/engine/media/audio/clip_myogg.h
index 0341caec08..951ae336b3 100644
--- a/engines/ags/engine/media/audio/clip_myogg.h
+++ b/engines/ags/engine/media/audio/clip_myogg.h
@@ -23,8 +23,9 @@
 #ifndef AGS_ENGINE_MEDIA_AUDIO_CLIP_MYOGG_H
 #define AGS_ENGINE_MEDIA_AUDIO_CLIP_MYOGG_H
 
-#include "ags/shared/alogg.h"
-#include "ags/shared/media/audio/soundclip.h"
+#include "ags/lib/audio/ogg.h"
+#include "ags/lib/allegro/file.h"
+#include "ags/engine/media/audio/soundclip.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/media/audio/clip_mystaticmp3.cpp b/engines/ags/engine/media/audio/clip_mystaticmp3.cpp
index f653f3d1b1..9f27f55461 100644
--- a/engines/ags/engine/media/audio/clip_mystaticmp3.cpp
+++ b/engines/ags/engine/media/audio/clip_mystaticmp3.cpp
@@ -20,16 +20,16 @@
  *
  */
 
-#include "ags/shared/media/audio/audiodefines.h"
+#include "ags/engine/media/audio/audiodefines.h"
 
 #ifndef NO_MP3_PLAYER
 
-#include "ags/shared/media/audio/clip_mystaticmp3.h"
-#include "ags/shared/media/audio/audiointernaldefs.h"
-#include "ags/shared/media/audio/soundcache.h"
-#include "ags/shared/util/mutex_lock.h"
+#include "ags/engine/media/audio/clip_mystaticmp3.h"
+#include "ags/engine/media/audio/audiointernaldefs.h"
+#include "ags/engine/media/audio/soundcache.h"
+#include "ags/engine/util/mutex_lock.h"
 
-#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/media/audio/clip_mystaticmp3.h b/engines/ags/engine/media/audio/clip_mystaticmp3.h
index 7f1313d137..c849a1803b 100644
--- a/engines/ags/engine/media/audio/clip_mystaticmp3.h
+++ b/engines/ags/engine/media/audio/clip_mystaticmp3.h
@@ -23,8 +23,8 @@
 #ifndef AGS_ENGINE_MEDIA_AUDIO_CLIP_MYSTATICMP3_H
 #define AGS_ENGINE_MEDIA_AUDIO_CLIP_MYSTATICMP3_H
 
-#include "ags/shared/almp3.h"
-#include "ags/shared/media/audio/soundclip.h"
+#include "ags/lib/audio/mp3.h"
+#include "ags/engine/media/audio/soundclip.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/media/audio/clip_mystaticogg.cpp b/engines/ags/engine/media/audio/clip_mystaticogg.cpp
index 5cbbb79a6f..84654620ce 100644
--- a/engines/ags/engine/media/audio/clip_mystaticogg.cpp
+++ b/engines/ags/engine/media/audio/clip_mystaticogg.cpp
@@ -20,23 +20,18 @@
  *
  */
 
-#include "ags/shared/media/audio/audiodefines.h"
-#include "ags/shared/media/audio/clip_mystaticogg.h"
-#include "ags/shared/media/audio/audiointernaldefs.h"
-#include "ags/shared/media/audio/soundcache.h"
-#include "ags/shared/util/mutex_lock.h"
+#include "ags/engine/media/audio/audiodefines.h"
+#include "ags/engine/media/audio/clip_mystaticogg.h"
+#include "ags/engine/media/audio/audiointernaldefs.h"
+#include "ags/engine/media/audio/soundcache.h"
+#include "ags/engine/util/mutex_lock.h"
 
-#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
+#include "ags/lib/audio/digi.h"
+#include "ags/lib/audio/ogg.h"
 
 namespace AGS3 {
 
-extern "C" {
-	extern int alogg_is_end_of_oggstream(ALOGG_OGGSTREAM *ogg);
-	extern int alogg_is_end_of_ogg(ALOGG_OGG *ogg);
-	extern int alogg_get_ogg_freq(ALOGG_OGG *ogg);
-	extern int alogg_get_ogg_stereo(ALOGG_OGG *ogg);
-}
-
 extern int use_extra_sound_offset;  // defined in ac.cpp
 
 void MYSTATICOGG::poll() {
diff --git a/engines/ags/engine/media/audio/clip_mystaticogg.h b/engines/ags/engine/media/audio/clip_mystaticogg.h
index 4663560961..cffe990090 100644
--- a/engines/ags/engine/media/audio/clip_mystaticogg.h
+++ b/engines/ags/engine/media/audio/clip_mystaticogg.h
@@ -23,8 +23,8 @@
 #ifndef AGS_ENGINE_MEDIA_AUDIO_CLIP_MYSTATICOGG_H
 #define AGS_ENGINE_MEDIA_AUDIO_CLIP_MYSTATICOGG_H
 
-#include "ags/shared/alogg.h"
-#include "ags/shared/media/audio/soundclip.h"
+#include "ags/lib/audio/ogg.h"
+#include "ags/engine/media/audio/soundclip.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/media/audio/clip_mywave.cpp b/engines/ags/engine/media/audio/clip_mywave.cpp
index 875bd3363b..f11f1b22dd 100644
--- a/engines/ags/engine/media/audio/clip_mywave.cpp
+++ b/engines/ags/engine/media/audio/clip_mywave.cpp
@@ -20,14 +20,15 @@
  *
  */
 
+#include "ags/lib/audio/digi.h"
 #include "ags/shared/util/wgt2allg.h"
-#include "ags/shared/media/audio/audiodefines.h"
-#include "ags/shared/media/audio/clip_mywave.h"
-#include "ags/shared/media/audio/audiointernaldefs.h"
-#include "ags/shared/media/audio/soundcache.h"
-#include "ags/shared/util/mutex_lock.h"
+#include "ags/engine/media/audio/audiodefines.h"
+#include "ags/engine/media/audio/clip_mywave.h"
+#include "ags/engine/media/audio/audiointernaldefs.h"
+#include "ags/engine/media/audio/soundcache.h"
+#include "ags/engine/util/mutex_lock.h"
 
-#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/media/audio/clip_mywave.h b/engines/ags/engine/media/audio/clip_mywave.h
index 24b119a7eb..a9f75b8319 100644
--- a/engines/ags/engine/media/audio/clip_mywave.h
+++ b/engines/ags/engine/media/audio/clip_mywave.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_MEDIA_AUDIO_CLIP_MYWAVE_H
 #define AGS_ENGINE_MEDIA_AUDIO_CLIP_MYWAVE_H
 
-#include "ags/shared/media/audio/soundclip.h"
+#include "ags/engine/media/audio/soundclip.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/media/audio/queuedaudioitem.cpp b/engines/ags/engine/media/audio/queuedaudioitem.cpp
index 744e6db89f..80dbadfe43 100644
--- a/engines/ags/engine/media/audio/queuedaudioitem.cpp
+++ b/engines/ags/engine/media/audio/queuedaudioitem.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/shared/media/audio/queuedaudioitem.h"
+#include "ags/engine/media/audio/queuedaudioitem.h"
 #include "ags/shared/ac/common_defines.h"
 #include "ags/shared/util/stream.h"
 
diff --git a/engines/ags/engine/media/audio/sound.cpp b/engines/ags/engine/media/audio/sound.cpp
index 057a498b98..5c3a72424f 100644
--- a/engines/ags/engine/media/audio/sound.cpp
+++ b/engines/ags/engine/media/audio/sound.cpp
@@ -30,26 +30,26 @@
 
 #include "ags/shared/core/platform.h"
 #include "ags/shared/util/wgt2allg.h"
-#include "ags/shared/ac/file.h"
-#include "ags/shared/media/audio/audiodefines.h"
-#include "ags/shared/media/audio/sound.h"
-#include "ags/shared/media/audio/audiointernaldefs.h"
-#include "ags/shared/media/audio/clip_mywave.h"
+#include "ags/engine/ac/file.h"
+#include "ags/engine/media/audio/audiodefines.h"
+#include "ags/engine/media/audio/sound.h"
+#include "ags/engine/media/audio/audiointernaldefs.h"
+#include "ags/engine/media/audio/clip_mywave.h"
 #ifndef NO_MP3_PLAYER
-#include "ags/shared/media/audio/clip_mymp3.h"
-#include "ags/shared/media/audio/clip_mystaticmp3.h"
+#include "ags/engine/media/audio/clip_mymp3.h"
+#include "ags/engine/media/audio/clip_mystaticmp3.h"
 #endif
-#include "ags/shared/media/audio/clip_myogg.h"
-#include "ags/shared/media/audio/clip_mystaticogg.h"
-#include "ags/shared/media/audio/clip_mymidi.h"
+#include "ags/engine/media/audio/clip_myogg.h"
+#include "ags/engine/media/audio/clip_mystaticogg.h"
+#include "ags/engine/media/audio/clip_mymidi.h"
 #ifdef JGMOD_MOD_PLAYER
-#include "ags/shared/media/audio/clip_myjgmod.h"
+#include "ags/engine/media/audio/clip_myjgmod.h"
 #endif
 #ifdef DUMB_MOD_PLAYER
-#include "ags/shared/media/audio/clip_mydumbmod.h"
+#include "ags/engine/media/audio/clip_mydumbmod.h"
 #endif
-#include "ags/shared/media/audio/soundcache.h"
-#include "ags/shared/util/mutex_lock.h"
+#include "ags/engine/media/audio/soundcache.h"
+#include "ags/engine/util/mutex_lock.h"
 
 namespace AGS3 {
 
@@ -94,6 +94,7 @@ PACKFILE *mp3in;
 #ifndef NO_MP3_PLAYER
 
 MYMP3 *thistune;
+
 SOUNDCLIP *my_load_mp3(const AssetPath &asset_name, int voll) {
 	size_t asset_size;
 	mp3in = PackfileFromAsset(asset_name, asset_size);
@@ -111,7 +112,7 @@ SOUNDCLIP *my_load_mp3(const AssetPath &asset_name, int voll) {
 	thistune->filesize = asset_size;
 	thistune->vol = voll;
 
-	if (thistune->chunksize > thistune->filesize)
+	if (thistune->chunksize > (int)thistune->filesize)
 		thistune->chunksize = thistune->filesize;
 
 	pack_fread(tmpbuffer, thistune->chunksize, mp3in);
@@ -230,7 +231,7 @@ SOUNDCLIP *my_load_ogg(const AssetPath &asset_name, int voll) {
 	thisogg->last_ms_offs = 0;
 	thisogg->last_but_one_but_one = 0;
 
-	if (thisogg->chunksize > asset_size)
+	if (thisogg->chunksize > (int)asset_size)
 		thisogg->chunksize = asset_size;
 
 	pack_fread(tmpbuffer, thisogg->chunksize, mp3in);
diff --git a/engines/ags/engine/media/audio/soundcache.cpp b/engines/ags/engine/media/audio/soundcache.cpp
index dcf4136ac3..81eb9737a7 100644
--- a/engines/ags/engine/media/audio/soundcache.cpp
+++ b/engines/ags/engine/media/audio/soundcache.cpp
@@ -22,12 +22,12 @@
 
 //include <stdlib.h>
 //include <string.h>
-#include "ags/shared/ac/file.h"
+#include "ags/engine/ac/file.h"
 #include "ags/shared/util/wgt2allg.h"
-#include "ags/shared/media/audio/soundcache.h"
-#include "ags/shared/media/audio/audiointernaldefs.h"
-#include "ags/shared/util/mutex.h"
-#include "ags/shared/util/mutex_lock.h"
+#include "ags/engine/media/audio/soundcache.h"
+#include "ags/engine/media/audio/audiointernaldefs.h"
+#include "ags/engine/util/mutex.h"
+#include "ags/engine/util/mutex_lock.h"
 #include "ags/shared/util/string.h"
 #include "ags/shared/debugging/out.h"
 
diff --git a/engines/ags/engine/media/audio/soundclip.cpp b/engines/ags/engine/media/audio/soundclip.cpp
index 68fc57ceec..c7b54cc83a 100644
--- a/engines/ags/engine/media/audio/soundclip.cpp
+++ b/engines/ags/engine/media/audio/soundclip.cpp
@@ -21,10 +21,10 @@
  */
 
 #include "ags/shared/util/wgt2allg.h"
-#include "ags/shared/media/audio/audio.h"
-#include "ags/shared/media/audio/audiodefines.h"
-#include "ags/shared/media/audio/soundclip.h"
-#include "ags/shared/media/audio/audiointernaldefs.h"
+#include "ags/engine/media/audio/audio.h"
+#include "ags/engine/media/audio/audiodefines.h"
+#include "ags/engine/media/audio/soundclip.h"
+#include "ags/engine/media/audio/audiointernaldefs.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/lib/allegro.h b/engines/ags/lib/allegro.h
index 9ecceb509e..9952637ada 100644
--- a/engines/ags/lib/allegro.h
+++ b/engines/ags/lib/allegro.h
@@ -29,7 +29,6 @@
 #include "ags/lib/allegro/base.h"
 #include "ags/lib/allegro/color.h"
 #include "ags/lib/allegro/config.h"
-#include "ags/lib/allegro/digi.h"
 #include "ags/lib/allegro/draw.h"
 #include "ags/lib/allegro/error.h"
 #include "ags/lib/allegro/file.h"
@@ -37,12 +36,14 @@
 #include "ags/lib/allegro/fmaths.h"
 #include "ags/lib/allegro/gfx.h"
 #include "ags/lib/allegro/keyboard.h"
-#include "ags/lib/allegro/midi.h"
 #include "ags/lib/allegro/mouse.h"
-#include "ags/lib/allegro/sound.h"
 #include "ags/lib/allegro/system.h"
 #include "ags/lib/allegro/unicode.h"
 
+#include "ags/lib/audio/sound.h"
+#include "ags/lib/audio/digi.h"
+#include "ags/lib/audio/midi.h"
+
 namespace AGS3 {
 
 extern int install_allegro();
diff --git a/engines/ags/lib/allegro/sound.cpp b/engines/ags/lib/allegro/sound.cpp
index a4acc0565f..46b9d1b909 100644
--- a/engines/ags/lib/allegro/sound.cpp
+++ b/engines/ags/lib/allegro/sound.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/lib/allegro/sound.h"
+#include "ags/lib/audio/sound.h"
 #include "common/textconsole.h"
 
 namespace AGS3 {
@@ -69,7 +69,7 @@ void get_volume(int *digi_volume, int *midi_volume) {
 }
 
 void get_hardware_volume(int *digi_volume, int *midi_volume) {
-	error("get_hardware_volume");
+	error("get_hardware_volume"); 
 }
 
 void set_mixer_quality(int quality) {
@@ -100,4 +100,12 @@ int get_mixer_buffer_length() {
 	error("get_mixer_buffer_length");
 }
 
+
+void stop_audio_stream(AUDIOSTREAM *stream) {
+	warning("TODO: stop_audio_stream");
+}
+
+void set_volume(int channel, int vol) {
+	warning("TODO: set_volume(%d, %d)", channel, vol);
+}
 } // namespace AGS3
diff --git a/engines/ags/lib/audio/digi.cpp b/engines/ags/lib/audio/digi.cpp
new file mode 100644
index 0000000000..6e34e036e9
--- /dev/null
+++ b/engines/ags/lib/audio/digi.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 "ags/lib/audio/digi.h"
+#include "common/textconsole.h"
+
+namespace AGS3 {
+
+DIGI_DRIVER *digi_driver;
+
+DIGI_DRIVER *digi_input_driver;
+
+int digi_card;
+
+int digi_input_card;
+
+
+int detect_digi_driver(int driver_id) {
+	return 0;
+}
+
+SAMPLE *load_wav_pf(PACKFILE *f) {
+	warning("TODO: load_wav_pf");
+	return nullptr;
+}
+
+void destroy_sample(SAMPLE *spl) {
+	delete spl;
+}
+
+int play_sample(SAMPLE *spl, int vol, int pan, int freq, int loop) {
+	warning("TODO: play_sample");
+	return 0;
+}
+
+void stop_sample(SAMPLE *spl) {
+	warning("TODO: stop_sample");
+}
+
+
+void voice_start(int voice) {
+	warning("TODO: voice_start");
+}
+
+void voice_stop(int voice) {
+	warning("TODO: voice_stop");
+}
+
+int voice_get_position(int voice) {
+	warning("TODO: voice_get_position");
+	return 0;
+}
+
+void voice_set_position(int voice, int position) {
+	warning("TODO: voice_set_position");
+}
+
+void voice_set_volume(int voice, int volume) {
+	warning("TODO: voice_set_volume");
+}
+
+int voice_get_frequency(int voice) {
+	warning("TODO: voice_get_frequency");
+	return 0;
+}
+
+void voice_set_pan(int voice, int pan) {
+	warning("TODO: voice_set_pan");
+}
+
+} // namespace AGS3
diff --git a/engines/ags/lib/allegro/digi.h b/engines/ags/lib/audio/digi.h
similarity index 89%
rename from engines/ags/lib/allegro/digi.h
rename to engines/ags/lib/audio/digi.h
index 1ffe0bdc24..904c40fb3f 100644
--- a/engines/ags/lib/allegro/digi.h
+++ b/engines/ags/lib/audio/digi.h
@@ -20,12 +20,13 @@
  *
  */
 
-#ifndef AGS_LIB_ALLEGRO_DIGI_H
-#define AGS_LIB_ALLEGRO_DIGI_H
+#ifndef AGS_LIB_AUDIO_DIGI_H
+#define AGS_LIB_AUDIO_DIGI_H
 
 #include "common/scummsys.h"
 #include "ags/lib/allegro/base.h"
 #include "ags/lib/allegro/alconfig.h"
+#include "ags/lib/allegro/file.h"
 
 namespace AGS3 {
 
@@ -140,6 +141,20 @@ AL_VAR(int, digi_input_card);
 
 AL_FUNC(int, detect_digi_driver, (int driver_id));
 
+
+extern SAMPLE *load_wav_pf(PACKFILE *f);
+extern void destroy_sample(SAMPLE *spl);
+extern int play_sample(SAMPLE *spl, int vol, int pan, int freq, int loop);
+extern void stop_sample(SAMPLE *spl);
+
+extern void voice_start(int voice);
+extern void voice_stop(int voice);
+extern int voice_get_position(int voice);
+extern void voice_set_position(int voice, int position);
+extern void voice_set_volume(int voice, int volume);
+extern int voice_get_frequency(int voice);
+extern void voice_set_pan(int voice, int pan);
+
 } // namespace AGS3
 
 #endif
diff --git a/engines/ags/lib/allegro/midi.cpp b/engines/ags/lib/audio/midi.cpp
similarity index 71%
rename from engines/ags/lib/allegro/midi.cpp
rename to engines/ags/lib/audio/midi.cpp
index 7b058574ba..96ed12eb10 100644
--- a/engines/ags/lib/allegro/midi.cpp
+++ b/engines/ags/lib/audio/midi.cpp
@@ -20,7 +20,8 @@
  *
  */
 
-#include "ags/lib/allegro/midi.h"
+#include "ags/lib/audio/midi.h"
+#include "common/textconsole.h"
 
 namespace AGS3 {
 
@@ -43,4 +44,40 @@ int detect_midi_driver(int driver_id) {
 	return 0;
 }
 
+
+void stop_midi() {
+	warning("TODO: stop_midi");
+}
+
+void destroy_midi(MIDI *midi) {
+	delete midi;
+}
+
+int play_midi(MIDI *tune, bool repeat) {
+	warning("TODO: play_midi");
+	return 0;
+}
+
+size_t get_midi_length(MIDI *tune) {
+	warning("TODO: get_midi_length");
+	return 0;
+}
+
+void midi_seek(int target) {
+	warning("TODO: midi_seek");
+}
+
+void midi_pause() {
+	warning("TODO: midi_pause");
+}
+
+void midi_resume() {
+	warning("TODO: midi_resume");
+}
+
+int load_midi_patches() {
+	warning("TODO: load_midi_patches");
+	return 0;
+}
+
 } // namespace AGS3
diff --git a/engines/ags/lib/allegro/midi.h b/engines/ags/lib/audio/midi.h
similarity index 92%
rename from engines/ags/lib/allegro/midi.h
rename to engines/ags/lib/audio/midi.h
index 8f474995e1..a96048191d 100644
--- a/engines/ags/lib/allegro/midi.h
+++ b/engines/ags/lib/audio/midi.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef AGS_LIB_ALLEGRO_MIDI_H
-#define AGS_LIB_ALLEGRO_MIDI_H
+#ifndef AGS_LIB_AUDIO_MIDI_H
+#define AGS_LIB_AUDIO_MIDI_H
 
 #include "common/scummsys.h"
 #include "ags/lib/allegro/base.h"
@@ -118,6 +118,15 @@ AL_VAR(long, midi_loop_end);           /* loop when we hit this position */
 
 AL_FUNC(int, detect_midi_driver, (int driver_id));
 
+extern void stop_midi();
+extern void destroy_midi(MIDI *tune);
+extern int play_midi(MIDI *tune, bool repeat);
+extern size_t get_midi_length(MIDI *tune);
+extern void midi_seek(int target);
+extern void midi_pause();
+extern void midi_resume();
+extern int load_midi_patches();
+
 } // namespace AGS3
 
 #endif
diff --git a/engines/ags/lib/audio/mod.cpp b/engines/ags/lib/audio/mod.cpp
new file mode 100644
index 0000000000..29c9acadb7
--- /dev/null
+++ b/engines/ags/lib/audio/mod.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 "ags/lib/audio/ogg.h"
+#include "common/textconsole.h"
+#include "ags/ags.h"
+
+namespace AGS3 {
+
+int alogg_poll_ogg(ALOGG_OGG *ogg) {
+	return ::AGS::g_vm->_mixer->isSoundHandleActive(ogg->_handle) ? 0 : ALOGG_POLL_PLAYJUSTFINISHED;
+}
+
+
+} // namespace AGS3
diff --git a/engines/ags/lib/allegro/digi.cpp b/engines/ags/lib/audio/mod.h
similarity index 84%
rename from engines/ags/lib/allegro/digi.cpp
rename to engines/ags/lib/audio/mod.h
index c3dbacf4ba..5fcf46c3fa 100644
--- a/engines/ags/lib/allegro/digi.cpp
+++ b/engines/ags/lib/audio/mod.h
@@ -20,21 +20,15 @@
  *
  */
 
-#include "ags/lib/allegro/digi.h"
+#ifndef AGS_LIB_AUDIO_MOD_H
+#define AGS_LIB_AUDIO_MOD_H
 
-namespace AGS3 {
-
-DIGI_DRIVER *digi_driver;
-
-DIGI_DRIVER *digi_input_driver;
-
-int digi_card;
-
-int digi_input_card;
+#include "audio/audiostream.h"
+#include "audio/mixer.h"
 
+namespace AGS3 {
 
-int detect_digi_driver(int driver_id) {
-	return 0;
-}
 
 } // namespace AGS3
+
+#endif
diff --git a/engines/ags/lib/audio/mp3.cpp b/engines/ags/lib/audio/mp3.cpp
new file mode 100644
index 0000000000..b948acdbf7
--- /dev/null
+++ b/engines/ags/lib/audio/mp3.cpp
@@ -0,0 +1,117 @@
+/* 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 "ags/lib/audio/mp3.h"
+#include "common/textconsole.h"
+#include "ags/ags.h"
+
+namespace AGS3 {
+
+ALMP3_MP3 *almp3_create_mp3(void *data, int data_len) {
+	warning("TODO: almp3_create_mp3");
+	return nullptr;
+}
+
+int almp3_play_mp3(ALMP3_MP3 *mp3, int buffer_len, int vol, int pan) {
+	warning("TODO: almp3_play_mp3");
+	return 0;
+}
+
+int almp3_play_ex_mp3(ALMP3_MP3 *mp3, int buffer_len, int vol, int pan, int speed, int loop) {
+	warning("TODO: almp3_play_ex_mp3");
+	return 0;
+}
+
+void almp3_stop_mp3(ALMP3_MP3 *mp3) {
+	::AGS::g_vm->_mixer->stopHandle(mp3->_handle);
+}
+
+void almp3_destroy_mp3(ALMP3_MP3 *mp3) {
+	delete mp3;
+}
+
+int almp3_poll_mp3(ALMP3_MP3 *mp3) {
+	return ::AGS::g_vm->_mixer->isSoundHandleActive(mp3->_handle) ? 0 : ALMP3_POLL_PLAYJUSTFINISHED;
+}
+
+void almp3_adjust_mp3(ALMP3_MP3 *mp3, int volume, int panning, int speed, bool repeat) {
+	warning("TODO: almp3_adjust_mp3");
+}
+
+void almp3_seek_abs_msecs_mp3(ALMP3_MP3 *mp3, int pos) {
+	warning("TODO: almp3_seek_abs_msecs_mp3");
+}
+
+int almp3_get_pos_msecs_mp3(ALMP3_MP3 *mp3) {
+	warning("TODO: almp3_get_pos_msecs_mp3");
+	return 0;
+}
+
+AUDIOSTREAM *almp3_get_audiostream_mp3(ALMP3_MP3 *mp3) {
+	warning("TODO: almp3_get_audiostream_mp3");
+	return nullptr;
+}
+
+int almp3_get_length_msecs_mp3(ALMP3_MP3 *mp3) {
+	warning("TODO: almp3_get_length_msecs_mp3");
+	return 0;
+}
+
+
+ALMP3_MP3STREAM *almp3_create_mp3stream(void *first_data_buffer, int data_buffer_len, int last_block) {
+	warning("TODO: almp3_create_mp3stream");
+	return nullptr;
+}
+
+int almp3_play_mp3stream(ALMP3_MP3STREAM *mp3, int buffer_len, int vol, int pan) {
+	warning("TODO: almp3_play_mp3stream");
+	return -1;
+}
+
+int almp3_poll_mp3stream(ALMP3_MP3STREAM *mp3) {
+	warning("TODO: almp3_poll_mp3stream");
+	return 0;
+}
+
+void almp3_adjust_mp3stream(ALMP3_MP3STREAM *mp3, int volume, int panning, int speed) {
+	warning("TODO: almp3_adjust_mp3stream");
+}
+
+void almp3_stop_mp3stream(ALMP3_MP3STREAM *mp3) {
+	warning("TODO: almp3_stop_mp3stream");
+}
+
+void almp3_destroy_mp3stream(ALMP3_MP3STREAM *mp3) {
+	warning("TODO: almp3_destroy_mp3stream");
+}
+
+int almp3_get_pos_msecs_mp3stream(ALMP3_MP3STREAM *mp3) {
+	warning("TODO: almp3_get_pos_msecs_mp3stream");
+	return 0;
+}
+
+AUDIOSTREAM *almp3_get_audiostream_mp3stream(ALMP3_MP3STREAM *mp3) {
+	warning("TODO: almp3_get_audiostream_mp3stream");
+	return nullptr;
+}
+
+} // namespace AGS3
diff --git a/engines/ags/lib/audio/mp3.h b/engines/ags/lib/audio/mp3.h
new file mode 100644
index 0000000000..2ac411aa75
--- /dev/null
+++ b/engines/ags/lib/audio/mp3.h
@@ -0,0 +1,64 @@
+/* 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 AGS_LIB_AUDIO_MP3_H
+#define AGS_LIB_AUDIO_MP3_H
+
+#include "ags/lib/audio/sound.h"
+#include "audio/mixer.h"
+
+namespace AGS3 {
+
+#define ALMP3_OK 0
+#define ALMP3_POLL_PLAYJUSTFINISHED 1
+
+typedef Audio::AudioStream ALMP3_MP3STREAM;
+struct ALMP3_MP3 {
+	ALMP3_MP3STREAM *_stream;
+	Audio::SoundHandle _handle;
+};
+
+extern ALMP3_MP3 *almp3_create_mp3(void *data, int data_len);
+extern void almp3_destroy_mp3(ALMP3_MP3 *mp3);
+extern int almp3_play_mp3(ALMP3_MP3 *mp3, int buffer_len, int vol, int pan);
+extern int almp3_play_ex_mp3(ALMP3_MP3 *mp3, int buffer_len, int vol, int pan, int speed, int loop);
+extern void almp3_stop_mp3(ALMP3_MP3 *mp3);
+extern int almp3_poll_mp3(ALMP3_MP3 *mp3);
+extern void almp3_adjust_mp3(ALMP3_MP3 *mp3, int volume, int panning, int speed, bool repeat);
+extern void almp3_seek_abs_msecs_mp3(ALMP3_MP3 *mp3, int pos);
+extern int almp3_get_pos_msecs_mp3(ALMP3_MP3 *mp3);
+extern AUDIOSTREAM *almp3_get_audiostream_mp3(ALMP3_MP3 *mp3);
+extern int almp3_get_length_msecs_mp3(ALMP3_MP3 *mp3);
+
+extern ALMP3_MP3STREAM *almp3_create_mp3stream(void *first_data_buffer, int data_buffer_len, int last_block);
+extern int almp3_play_mp3stream(ALMP3_MP3STREAM *mp3, int buffer_len, int vol, int pan);
+extern int almp3_poll_mp3stream(ALMP3_MP3STREAM *mp3);
+extern void almp3_adjust_mp3stream(ALMP3_MP3STREAM *mp3, int volume, int panning, int speed);
+extern void almp3_stop_mp3stream(ALMP3_MP3STREAM *mp3);
+extern void almp3_destroy_mp3stream(ALMP3_MP3STREAM *mp3);
+extern int almp3_get_pos_msecs_mp3stream(ALMP3_MP3STREAM *mp3);
+extern AUDIOSTREAM *almp3_get_audiostream_mp3stream(ALMP3_MP3STREAM *mp3);
+extern int almp3_get_length_msecs_mp3stream(ALMP3_MP3STREAM *mp3, int total_size);
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/lib/audio/ogg.cpp b/engines/ags/lib/audio/ogg.cpp
new file mode 100644
index 0000000000..60860b3df9
--- /dev/null
+++ b/engines/ags/lib/audio/ogg.cpp
@@ -0,0 +1,146 @@
+/* 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 "ags/lib/audio/ogg.h"
+#include "common/textconsole.h"
+#include "ags/ags.h"
+
+namespace AGS3 {
+
+ALOGG_OGG *alogg_create_ogg_from_buffer(void *data, int data_len) {
+	warning("TODO: alogg_create_ogg_from_buffer");
+	return nullptr;
+}
+
+void alogg_destroy_ogg(ALOGG_OGG *ogg) {
+	delete ogg;
+}
+
+int alogg_play_ogg(ALOGG_OGG *ogg, int buffer_len, int vol, int pan) {
+	warning("TODO: alogg_play_ogg");
+	return 0;
+}
+
+int alogg_play_ex_ogg(ALOGG_OGG *ogg, int buffer_len, int vol, int pan, int speed, int loop) {
+	warning("TODO: alogg_play_ex_ogg");
+	return 0;
+}
+
+void alogg_stop_ogg(ALOGG_OGG *ogg) {
+	warning("TODO: alogg_stop_ogg");
+}
+
+int alogg_poll_ogg(ALOGG_OGG *ogg) {
+	return ::AGS::g_vm->_mixer->isSoundHandleActive(ogg->_handle) ? 0 : ALOGG_POLL_PLAYJUSTFINISHED;
+}
+
+bool alogg_is_playing_ogg(ALOGG_OGG *ogg) {
+	warning("TODO: alogg_is_playing_ogg");
+	return false;
+}
+
+void alogg_adjust_ogg(ALOGG_OGG *ogg, int volume, int panning, int speed, bool repeat) {
+	warning("TODO: alogg_adjust_oggstream");
+}
+
+AUDIOSTREAM *alogg_get_audiostream_ogg(ALOGG_OGG *ogg) {
+	return ogg->_stream;
+}
+
+int alogg_get_pos_msecs_ogg(ALOGG_OGG *ogg) {
+	warning("TODO: alogg_get_pos_msecs_ogg");
+	return 0;
+}
+
+bool alogg_get_wave_is_stereo_ogg(ALOGG_OGG *ogg) {
+	warning("TODO: alogg_get_wave_is_stereo_ogg");
+	return true;
+}
+
+int alogg_get_length_msecs_ogg(ALOGG_OGG *ogg) {
+	warning("TODO: alogg_get_length_msecs_ogg");
+	return 0;
+}
+
+void alogg_seek_abs_msecs_ogg(ALOGG_OGG *ogg, int msecs) {
+	warning("TODO: alogg_seek_abs_msecs_ogg");
+}
+
+int alogg_get_wave_freq_ogg(ALOGG_OGG *ogg) {
+	warning("TODO: alogg_get_wave_freq_ogg");
+	return 0;
+}
+
+int alogg_is_end_of_ogg(ALOGG_OGG *ogg) {
+	warning("TODO: alogg_is_end_of_oggstream");
+	return 0;
+}
+
+
+ALOGG_OGGSTREAM *alogg_create_oggstream(void *first_data_buffer, int data_buffer_len, int last_block) {
+	warning("TODO: alogg_create_oggstream");
+	return nullptr;
+}
+
+void alogg_destroy_oggstream(ALOGG_OGGSTREAM *ogg) {
+	warning("TODO: alogg_destroy_oggstream");
+}
+
+int alogg_play_oggstream(ALOGG_OGGSTREAM *ogg, int buffer_len, int vol, int pan) {
+	warning("TODO: alogg_play_oggstream");
+	return 0;
+}
+
+void alogg_stop_oggstream(ALOGG_OGGSTREAM *ogg) {
+	warning("TODO: alogg_stop_oggstream");
+}
+
+int alogg_poll_oggstream(ALOGG_OGGSTREAM *ogg) {
+	warning("TODO: alogg_poll_oggstream");
+	return 0;
+}
+
+void alogg_adjust_oggstream(ALOGG_OGGSTREAM *ogg, int volume, int panning, int speed) {
+	warning("TODO: alogg_adjust_oggstream");
+}
+
+bool alogg_is_playing_oggstream(ALOGG_OGGSTREAM *ogg) {
+	warning("TODO: alogg_is_playing_oggstream");
+	return false;
+}
+
+int alogg_is_end_of_oggstream(ALOGG_OGGSTREAM *ogg) {
+	warning("TODO: alogg_is_end_of_oggstream");
+	return 0;
+}
+
+AUDIOSTREAM *alogg_get_audiostream_oggstream(ALOGG_OGGSTREAM *ogg) {
+	warning("TODO: alogg_get_audiostream_oggstream");
+	return nullptr;
+}
+
+int alogg_get_pos_msecs_oggstream(ALOGG_OGGSTREAM *ogg) {
+	warning("TODO: alogg_get_pos_msecs_oggstream");
+	return 0;
+}
+
+} // namespace AGS3
diff --git a/engines/ags/lib/audio/ogg.h b/engines/ags/lib/audio/ogg.h
new file mode 100644
index 0000000000..b967cb53f9
--- /dev/null
+++ b/engines/ags/lib/audio/ogg.h
@@ -0,0 +1,76 @@
+/* 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 AGS_LIB_AUDIO_OGG_H
+#define AGS_LIB_AUDIO_OGG_H
+
+#include "ags/lib/audio/sound.h"
+#include "audio/mixer.h"
+
+namespace AGS3 {
+
+#define ALOGG_OK 0
+
+#define ALOGG_PLAY_BUFFERTOOSMALL    -1
+
+#define ALOGG_POLL_PLAYJUSTFINISHED  1
+#define ALOGG_POLL_NOTPLAYING        -1
+#define ALOGG_POLL_FRAMECORRUPT      -2
+#define ALOGG_POLL_BUFFERUNDERRUN    -3
+#define ALOGG_POLL_INTERNALERROR     -4
+
+typedef AUDIOSTREAM ALOGG_OGGSTREAM;
+struct ALOGG_OGG {
+	ALOGG_OGGSTREAM *_stream;
+	Audio::SoundHandle _handle;
+};
+
+extern ALOGG_OGG *alogg_create_ogg_from_buffer(void *data, int data_len);
+extern void alogg_destroy_ogg(ALOGG_OGG *ogg);
+extern int alogg_play_ogg(ALOGG_OGG *ogg, int buffer_len, int vol, int pan);
+extern int alogg_play_ex_ogg(ALOGG_OGG *ogg, int buffer_len, int vol, int pan, int speed, int loop);
+extern void alogg_stop_ogg(ALOGG_OGG *ogg);
+extern int alogg_poll_ogg(ALOGG_OGG *ogg);
+extern bool alogg_is_playing_ogg(ALOGG_OGG *ogg);
+extern void alogg_adjust_ogg(ALOGG_OGG *ogg, int volume, int panning, int speed, bool repeat);
+extern AUDIOSTREAM *alogg_get_audiostream_ogg(ALOGG_OGG *ogg);
+extern int alogg_get_pos_msecs_ogg(ALOGG_OGG *ogg);
+extern bool alogg_get_wave_is_stereo_ogg(ALOGG_OGG *ogg);
+extern int alogg_get_length_msecs_ogg(ALOGG_OGG *ogg);
+extern void alogg_seek_abs_msecs_ogg(ALOGG_OGG *ogg, int msecs);
+extern int alogg_get_wave_freq_ogg(ALOGG_OGG *ogg);
+extern int alogg_is_end_of_ogg(ALOGG_OGG *ogg);
+
+ALOGG_OGGSTREAM *alogg_create_oggstream(void *first_data_buffer, int data_buffer_len, int last_block);
+extern int alogg_play_oggstream(ALOGG_OGGSTREAM *ogg, int buffer_len, int vol, int pan);
+extern void alogg_stop_oggstream(ALOGG_OGGSTREAM *ogg);
+extern void alogg_destroy_oggstream(ALOGG_OGGSTREAM *ogg);
+extern int alogg_poll_oggstream(ALOGG_OGGSTREAM *ogg);
+extern void alogg_adjust_oggstream(ALOGG_OGGSTREAM *ogg, int volume, int panning, int speed);
+extern bool alogg_is_playing_oggstream(ALOGG_OGGSTREAM *ogg);
+extern int alogg_is_end_of_oggstream(ALOGG_OGGSTREAM *ogg);
+extern AUDIOSTREAM *alogg_get_audiostream_oggstream(ALOGG_OGGSTREAM *ogg);
+extern int alogg_get_pos_msecs_oggstream(ALOGG_OGGSTREAM *ogg);
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/lib/audio/sound.cpp b/engines/ags/lib/audio/sound.cpp
new file mode 100644
index 0000000000..e8d197b660
--- /dev/null
+++ b/engines/ags/lib/audio/sound.cpp
@@ -0,0 +1,108 @@
+/* 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 "ags/lib/audio/sound.h"
+#include "common/textconsole.h"
+
+namespace AGS3 {
+
+_DRIVER_INFO _digi_driver_list[] = {
+	{ 0, nullptr, 0     }
+};
+
+
+int install_sound(int digi, int midi, const char *cfg_path) {
+	// TODO: install_sound
+	return 0;
+}
+
+void remove_sound() {
+	// TODO: remove_sound
+}
+
+void reserve_voices(int digi_voices, int midi_voices) {
+	error("reserve_voices");
+}
+
+void set_volume_per_voice(int scale) {
+	error("set_volume_per_voice");
+
+}
+
+int install_sound_input(int digi, int midi) {
+	error("install_sound_input");
+}
+
+void remove_sound_input() {
+	error("remove_sound_input");
+}
+
+void set_volume(int digi_volume, int midi_volume) {
+	error("set_volume");
+}
+
+void set_hardware_volume(int digi_volume, int midi_volume) {
+	error("set_hardware_volume");
+}
+
+void get_volume(int *digi_volume, int *midi_volume) {
+	error("get_volume");
+}
+
+void get_hardware_volume(int *digi_volume, int *midi_volume) {
+	error("get_hardware_volume"); 
+}
+
+void set_mixer_quality(int quality) {
+	error("set_mixer_quality");
+}
+
+int get_mixer_quality() {
+	error("get_mixer_quality");
+}
+
+int get_mixer_frequency() {
+	error("get_mixer_frequency");
+}
+
+int get_mixer_bits() {
+	error("get_mixer_bits");
+}
+
+int get_mixer_channels() {
+	error("get_mixer_channels");
+}
+
+int get_mixer_voices() {
+	error("get_mixer_voices");
+}
+
+int get_mixer_buffer_length() {
+	error("get_mixer_buffer_length");
+}
+
+
+void stop_audio_stream(AUDIOSTREAM *stream) {
+	warning("TODO: stop_audio_stream");
+}
+
+} // namespace AGS3
diff --git a/engines/ags/lib/allegro/sound.h b/engines/ags/lib/audio/sound.h
similarity index 90%
rename from engines/ags/lib/allegro/sound.h
rename to engines/ags/lib/audio/sound.h
index bc4790c9ac..d8c046de25 100644
--- a/engines/ags/lib/allegro/sound.h
+++ b/engines/ags/lib/audio/sound.h
@@ -29,6 +29,15 @@
 
 namespace AGS3 {
 
+struct SAMPLE;
+
+struct AUDIOSTREAM {
+	int voice = -1;
+	SAMPLE *samp = nullptr;
+	bool active = false;
+	void *locked = nullptr;
+};
+
 AL_FUNC(void, reserve_voices, (int digi_voices, int midi_voices));
 AL_FUNC(void, set_volume_per_voice, (int scale));
 
@@ -52,6 +61,10 @@ AL_FUNC(int, get_mixer_channels, (void));
 AL_FUNC(int, get_mixer_voices, (void));
 AL_FUNC(int, get_mixer_buffer_length, (void));
 
+
+extern void stop_audio_stream(AUDIOSTREAM *stream);
+extern void set_volume(int channel, int vol);
+
 } // namespace AGS3
 
 #endif
diff --git a/engines/ags/lib/audio/wav.cpp b/engines/ags/lib/audio/wav.cpp
new file mode 100644
index 0000000000..851877df46
--- /dev/null
+++ b/engines/ags/lib/audio/wav.cpp
@@ -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.
+ *
+ */
+
+#include "ags/lib/audio/wav.h"
+#include "common/textconsole.h"
+#include "ags/ags.h"
+
+namespace AGS3 {
+
+
+
+} // namespace AGS3
diff --git a/engines/ags/lib/audio/wav.h b/engines/ags/lib/audio/wav.h
new file mode 100644
index 0000000000..d550c03312
--- /dev/null
+++ b/engines/ags/lib/audio/wav.h
@@ -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.
+ *
+ */
+
+#ifndef AGS_LIB_AUDIO_WAV_H
+#define AGS_LIB_AUDIO_WAV_H
+
+#include "audio/audiostream.h"
+#include "audio/mixer.h"
+
+namespace AGS3 {
+
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index f1e905fb1a..90af620cbf 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -10,18 +10,22 @@ MODULE_OBJS = \
 	lib/allegro.o \
 	lib/allegro/color.o \
 	lib/allegro/config.o \
-	lib/allegro/digi.o \
 	lib/allegro/draw.o \
 	lib/allegro/error.o \
 	lib/allegro/file.o \
 	lib/allegro/fixed.o \
 	lib/allegro/gfx.o \
 	lib/allegro/keyboard.o \
-	lib/allegro/midi.o \
 	lib/allegro/mouse.o \
-	lib/allegro/sound.o \
 	lib/allegro/system.o \
 	lib/allegro/unicode.o \
+	lib/audio/audio.o \
+	lib/audio/digi.o \
+	lib/audio/midi.o \
+	lib/audio/mp3.o \
+	lib/audio/ogg.o \
+	lib/audio/sound.o \
+	lib/audio/wav.o \
 	lib/opengl/opengl.o \
 	lib/system/datetime.o \
 	shared/ac/dynobj/scriptaudioclip.o \
@@ -248,6 +252,20 @@ MODULE_OBJS = \
 	engine/main/graphics_mode.o \
 	engine/main/quit.o \
 	engine/main/update.o \
+    engine/media/audio/ambientsound.o \
+    engine/media/audio/audio.o \
+    engine/media/audio/clip_mydumbmod.o \
+    engine/media/audio/clip_myjgmod.o \
+    engine/media/audio/clip_mymidi.o \
+    engine/media/audio/clip_mymp3.o \
+    engine/media/audio/clip_myogg.o \
+    engine/media/audio/clip_mystaticmp3.o \
+    engine/media/audio/clip_mystaticogg.o \
+    engine/media/audio/clip_mywave.o \
+    engine/media/audio/queuedaudioitem.o \
+    engine/media/audio/sound.o \
+    engine/media/audio/soundcache.o \
+    engine/media/audio/soundclip.o \
 	engine/platform/base/agsplatformdriver.o \
 	engine/platform/windows/acplwin.o \
 	engine/platform/windows/minidump.o \


Commit: a4fd46ecc842f4d261c58a532c022d03854a2e64
    https://github.com/scummvm/scummvm/commit/a4fd46ecc842f4d261c58a532c022d03854a2e64
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added engine/media/video/ folder

Changed paths:
  A engines/ags/engine/media/video/vmr9_graph.h
  R engines/ags/engine/media/video/VMR9Graph.h
    engines/ags/engine/media/video/video.cpp
    engines/ags/engine/platform/windows/media/video/acwavi3d.cpp
    engines/ags/module.mk


diff --git a/engines/ags/engine/media/video/video.cpp b/engines/ags/engine/media/video/video.cpp
index 9372858dfb..d5a14bc821 100644
--- a/engines/ags/engine/media/video/video.cpp
+++ b/engines/ags/engine/media/video/video.cpp
@@ -20,38 +20,41 @@
  *
  */
 
-#include "ags/shared/media/video/video.h"
+#include "ags/engine/media/video/video.h"
 
-#ifndef AGS_NO_VIDEO_PLAYER
-
-#include "ags/shared/apeg.h"
+//include "apeg.h"
 #include "ags/shared/core/platform.h"
 #define AGS_FLI_FROM_PACK_FILE ((ALLEGRO_DATE >= 20190303) || \
-                                AGS_PLATFORM_OS_WINDOWS || AGS_PLATFORM_OS_ANDROID || AGS_PLATFORM_OS_MACOS)
+	AGS_PLATFORM_OS_WINDOWS || AGS_PLATFORM_OS_ANDROID || AGS_PLATFORM_OS_MACOS)
 
-#include "ags/shared/debugging/debug_log.h"
+#include "ags/engine/debugging/debug_log.h"
 #include "ags/shared/debugging/out.h"
-#include "ags/shared/ac/asset_helper.h"
+#include "ags/engine/ac/asset_helper.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/draw.h"
+#include "ags/engine/ac/draw.h"
 #include "ags/shared/ac/game_version.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_display.h"
-#include "ags/shared/ac/mouse.h"
-#include "ags/shared/ac/sys_events.h"
-#include "ags/shared/ac/runtime_defines.h"
-#include "ags/shared/ac/system.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_display.h"
+#include "ags/engine/ac/mouse.h"
+#include "ags/engine/ac/sys_events.h"
+#include "ags/engine/ac/runtime_defines.h"
+#include "ags/engine/ac/system.h"
 #include "ags/shared/core/assetmanager.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/gfx/ddb.h"
-#include "ags/shared/gfx/graphicsdriver.h"
-#include "ags/shared/main/game_run.h"
+#include "ags/engine/gfx/ddb.h"
+#include "ags/engine/gfx/graphicsdriver.h"
+#include "ags/engine/main/game_run.h"
 #include "ags/shared/util/stream.h"
-#include "ags/shared/media/audio/audio_system.h"
+#include "ags/engine/media/audio/audio_system.h"
 
 namespace AGS3 {
 
+// TODO: Enable video playback
+#define AGS_NO_VIDEO_PLAYER
+
+#ifndef AGS_NO_VIDEO_PLAYER
+
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
@@ -397,10 +400,14 @@ void video_on_gfxmode_changed() {
 #else
 
 void play_theora_video(const char *name, int skip, int flags) {
+	warning("TODO: play_theora_video");
 }
 void play_flc_file(int numb, int playflags) {
+	warning("TODO: play_flc_file");
 }
+
 void video_on_gfxmode_changed() {
+	warning("TODO: video_on_gfxmode_changed");
 }
 
 #endif
diff --git a/engines/ags/engine/media/video/VMR9Graph.h b/engines/ags/engine/media/video/vmr9_graph.h
similarity index 94%
rename from engines/ags/engine/media/video/VMR9Graph.h
rename to engines/ags/engine/media/video/vmr9_graph.h
index 837d3a5896..d3488fbd9b 100644
--- a/engines/ags/engine/media/video/VMR9Graph.h
+++ b/engines/ags/engine/media/video/vmr9_graph.h
@@ -22,16 +22,12 @@
 
 //=============================================================================
 //
-// VMR9Graph.h: interface for the CVMR9Graph class.
+// vmr9_graph.h: interface for the CVMR9Graph class.
 //
 //=============================================================================
 
-#if !defined(AFX_VMR9GRAPH_H__449FDB5B_6719_4134_B5A7_B651C08D109E__INCLUDED_)
-#define AFX_VMR9GRAPH_H__449FDB5B_6719_4134_B5A7_B651C08D109E__INCLUDED_
-
-#if _MSC_VER > 1000
-#pragma once
-#endif
+#ifndef AGS_ENGINE_MEDIA_VIDEO_VMR9_GRAPH_H
+#define AGS_ENGINE_MEDIA_VIDEO_VMR9_GRAPH_H
 
 //include <dshow.h>
 //include <Vmr9.h>
diff --git a/engines/ags/engine/platform/windows/media/video/acwavi3d.cpp b/engines/ags/engine/platform/windows/media/video/acwavi3d.cpp
index 11b24ecb2b..0b70185d65 100644
--- a/engines/ags/engine/platform/windows/media/video/acwavi3d.cpp
+++ b/engines/ags/engine/platform/windows/media/video/acwavi3d.cpp
@@ -45,7 +45,7 @@
 typedef float D3DVALUE, *LPD3DVALUE;
 #include "ags/shared/ac/common.h"
 #include "ags/shared/main/game_run.h"
-#include "ags/shared/media/video/VMR9Graph.h"
+#include "ags/shared/media/video/vmr9_graph.h"
 #include "ags/shared/platform/base/agsplatformdriver.h"
 ////include <atlbase.h>
 #include "ags/shared/media/audio/audio_system.h"
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 90af620cbf..fd1677c059 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -266,6 +266,7 @@ MODULE_OBJS = \
     engine/media/audio/sound.o \
     engine/media/audio/soundcache.o \
     engine/media/audio/soundclip.o \
+	engine/media/video/video.o \
 	engine/platform/base/agsplatformdriver.o \
 	engine/platform/windows/acplwin.o \
 	engine/platform/windows/minidump.o \


Commit: 69b6cfab2942a5b8766753f1bffbca22983d3fe7
    https://github.com/scummvm/scummvm/commit/69b6cfab2942a5b8766753f1bffbca22983d3fe7
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Move std/ folder into lib/

Changed paths:
  A engines/ags/lib/std/algorithm.h
  A engines/ags/lib/std/array.h
  A engines/ags/lib/std/chrono.h
  A engines/ags/lib/std/functional.h
  A engines/ags/lib/std/initializer_list.h
  A engines/ags/lib/std/limits.h
  A engines/ags/lib/std/list.h
  A engines/ags/lib/std/map.h
  A engines/ags/lib/std/math.h
  A engines/ags/lib/std/memory.h
  A engines/ags/lib/std/mutex.h
  A engines/ags/lib/std/queue.h
  A engines/ags/lib/std/set.h
  A engines/ags/lib/std/std.cpp
  A engines/ags/lib/std/thread.h
  A engines/ags/lib/std/type_traits.h
  A engines/ags/lib/std/unordered_set.h
  A engines/ags/lib/std/utility.h
  A engines/ags/lib/std/vector.h
  A engines/ags/lib/std/xtr1common.h
  A engines/ags/lib/std/xutility.h
  R engines/ags/std/algorithm.h
  R engines/ags/std/array.h
  R engines/ags/std/chrono.h
  R engines/ags/std/functional.h
  R engines/ags/std/initializer_list.h
  R engines/ags/std/limits.h
  R engines/ags/std/list.h
  R engines/ags/std/map.h
  R engines/ags/std/math.h
  R engines/ags/std/memory.h
  R engines/ags/std/mutex.h
  R engines/ags/std/queue.h
  R engines/ags/std/set.h
  R engines/ags/std/thread.h
  R engines/ags/std/type_traits.h
  R engines/ags/std/unordered_set.h
  R engines/ags/std/utility.h
  R engines/ags/std/vector.h
  R engines/ags/std/xtr1common.h
  R engines/ags/std/xutility.h
    engines/ags/engine/ac/asset_helper.h
    engines/ags/engine/ac/dialog.h
    engines/ags/engine/ac/draw.cpp
    engines/ags/engine/ac/draw.h
    engines/ags/engine/ac/draw_software.cpp
    engines/ags/engine/ac/dynobj/cc_dynamicarray.h
    engines/ags/engine/ac/dynobj/cc_dynamicobject.h
    engines/ags/engine/ac/dynobj/managedobjectpool.cpp
    engines/ags/engine/ac/dynobj/managedobjectpool.h
    engines/ags/engine/ac/dynobj/scriptdict.h
    engines/ags/engine/ac/dynobj/scriptset.h
    engines/ags/engine/ac/dynobj/scriptuserobject.cpp
    engines/ags/engine/ac/gamestate.cpp
    engines/ags/engine/ac/gamestate.h
    engines/ags/engine/ac/listbox.cpp
    engines/ags/engine/ac/overlay.h
    engines/ags/engine/ac/route_finder_jps.inl
    engines/ags/engine/ac/timer.h
    engines/ags/engine/debugging/debug.cpp
    engines/ags/engine/debugging/logfile.h
    engines/ags/engine/debugging/messagebuffer.h
    engines/ags/engine/game/savegame.h
    engines/ags/engine/game/savegame_internal.h
    engines/ags/engine/game/viewport.h
    engines/ags/engine/gfx/ali3dogl.cpp
    engines/ags/engine/gfx/ali3dogl.h
    engines/ags/engine/gfx/ali3dsw.cpp
    engines/ags/engine/gfx/ali3dsw.h
    engines/ags/engine/gfx/gfxdriverbase.h
    engines/ags/engine/gfx/gfxdriverfactory.h
    engines/ags/engine/gfx/gfxdriverfactorybase.h
    engines/ags/engine/gfx/gfxfilter.h
    engines/ags/engine/gfx/graphicsdriver.h
    engines/ags/engine/main/game_run.cpp
    engines/ags/engine/media/audio/audio.h
    engines/ags/engine/platform/base/agsplatformdriver.cpp
    engines/ags/engine/platform/base/agsplatformdriver.h
    engines/ags/engine/platform/windows/gfx/ali3dd3d.h
    engines/ags/engine/platform/windows/setup/winsetup.cpp
    engines/ags/engine/plugin/agsplugin.cpp
    engines/ags/engine/plugin/plugin_engine.h
    engines/ags/engine/script/cc_instance.h
    engines/ags/engine/script/nonblockingscriptfunction.h
    engines/ags/engine/script/script.h
    engines/ags/engine/script/systemimports.h
    engines/ags/engine/util/mutex_std.h
    engines/ags/engine/util/thread_std.h
    engines/ags/module.mk
    engines/ags/shared/ac/gamesetupstruct.h
    engines/ags/shared/ac/spritecache.h
    engines/ags/shared/ac/view.h
    engines/ags/shared/ac/wordsdictionary.cpp
    engines/ags/shared/core/asset.h
    engines/ags/shared/debugging/debugmanager.h
    engines/ags/shared/font/fonts.cpp
    engines/ags/shared/font/fonts.h
    engines/ags/shared/font/ttffontrenderer.h
    engines/ags/shared/font/wfnfont.cpp
    engines/ags/shared/font/wfnfont.h
    engines/ags/shared/font/wfnfontrenderer.h
    engines/ags/shared/game/customproperties.h
    engines/ags/shared/game/interactions.h
    engines/ags/shared/game/main_game_file.h
    engines/ags/shared/game/plugininfo.h
    engines/ags/shared/game/room_file.h
    engines/ags/shared/game/roomstruct.h
    engines/ags/shared/gui/guibutton.h
    engines/ags/shared/gui/guiinv.h
    engines/ags/shared/gui/guilabel.h
    engines/ags/shared/gui/guilistbox.h
    engines/ags/shared/gui/guimain.cpp
    engines/ags/shared/gui/guimain.h
    engines/ags/shared/gui/guislider.h
    engines/ags/shared/gui/guitextbox.h
    engines/ags/shared/script/cc_error.cpp
    engines/ags/shared/script/cc_script.h
    engines/ags/shared/util/bufferedstream.cpp
    engines/ags/shared/util/bufferedstream.h
    engines/ags/shared/util/error.h
    engines/ags/shared/util/geometry.cpp
    engines/ags/shared/util/ini_util.cpp
    engines/ags/shared/util/ini_util.h
    engines/ags/shared/util/inifile.h
    engines/ags/shared/util/string.cpp
    engines/ags/shared/util/string.h
    engines/ags/shared/util/string_types.h


diff --git a/engines/ags/engine/ac/asset_helper.h b/engines/ags/engine/ac/asset_helper.h
index 7c6160af7b..4ce099cc9b 100644
--- a/engines/ags/engine/ac/asset_helper.h
+++ b/engines/ags/engine/ac/asset_helper.h
@@ -29,8 +29,8 @@
 #ifndef AGS_ENGINE_AC_ASSETHELPER_H
 #define AGS_ENGINE_AC_ASSETHELPER_H
 
-#include "ags/std/memory.h"
-#include "ags/std/utility.h"
+#include "ags/lib/std/memory.h"
+#include "ags/lib/std/utility.h"
 #include "ags/shared/util/string.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/ac/dialog.h b/engines/ags/engine/ac/dialog.h
index 696c195b5e..6621259050 100644
--- a/engines/ags/engine/ac/dialog.h
+++ b/engines/ags/engine/ac/dialog.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DIALOG_H
 #define AGS_ENGINE_AC_DIALOG_H
 
-#include "ags/std/vector.h"
+#include "ags/lib/std/vector.h"
 #include "ags/engine/ac/dynobj/scriptdialog.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/ac/draw.cpp b/engines/ags/engine/ac/draw.cpp
index 8f824f35c7..d74095bdee 100644
--- a/engines/ags/engine/ac/draw.cpp
+++ b/engines/ags/engine/ac/draw.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ags/std/algorithm.h"
-#include "ags/std/math.h"
+#include "ags/lib/std/algorithm.h"
+#include "ags/lib/std/math.h"
 #include "ags/lib/aastr-0.1.1/aastr.h"
 #include "ags/shared/core/platform.h"
 #include "ags/shared/ac/common.h"
diff --git a/engines/ags/engine/ac/draw.h b/engines/ags/engine/ac/draw.h
index 03901e7884..481a502700 100644
--- a/engines/ags/engine/ac/draw.h
+++ b/engines/ags/engine/ac/draw.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DRAW_H
 #define AGS_ENGINE_AC_DRAW_H
 
-#include "ags/std/memory.h"
+#include "ags/lib/std/memory.h"
 #include "ags/shared/core/types.h"
 #include "ags/shared/ac/common_defines.h"
 #include "ags/shared/gfx/gfx_def.h"
diff --git a/engines/ags/engine/ac/draw_software.cpp b/engines/ags/engine/ac/draw_software.cpp
index 999d9b4a7b..e6af2262bc 100644
--- a/engines/ags/engine/ac/draw_software.cpp
+++ b/engines/ags/engine/ac/draw_software.cpp
@@ -46,8 +46,8 @@
 //
 //=============================================================================
 
-#include "ags/std/utility.h"
-#include "ags/std/vector.h"
+#include "ags/lib/std/utility.h"
+#include "ags/lib/std/vector.h"
 #include "ags/engine/ac/draw_software.h"
 #include "ags/shared/gfx/bitmap.h"
 #include "ags/engine/util/scaling.h"
diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicarray.h b/engines/ags/engine/ac/dynobj/cc_dynamicarray.h
index aea7d06935..d68244e64c 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicarray.h
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicarray.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_CCDYNAMICARRAY_H
 #define AGS_ENGINE_AC_DYNOBJ_CCDYNAMICARRAY_H
 
-#include "ags/std/vector.h"
+#include "ags/lib/std/vector.h"
 #include "ags/engine/ac/dynobj/cc_dynamicobject.h"   // ICCDynamicObject
 
 namespace AGS3 {
diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicobject.h b/engines/ags/engine/ac/dynobj/cc_dynamicobject.h
index 93bc659351..88e4aa1d5a 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicobject.h
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicobject.h
@@ -29,7 +29,7 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_CCDYNAMICOBJECT_H
 #define AGS_ENGINE_AC_DYNOBJ_CCDYNAMICOBJECT_H
 
-#include "ags/std/utility.h"
+#include "ags/lib/std/utility.h"
 #include "ags/shared/core/types.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/ac/dynobj/managedobjectpool.cpp b/engines/ags/engine/ac/dynobj/managedobjectpool.cpp
index d7b30f4ef9..f89fe38698 100644
--- a/engines/ags/engine/ac/dynobj/managedobjectpool.cpp
+++ b/engines/ags/engine/ac/dynobj/managedobjectpool.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/std/vector.h"
+#include "ags/lib/std/vector.h"
 //include <string.h>
 #include "ags/engine/ac/dynobj/managedobjectpool.h"
 #include "ags/engine/ac/dynobj/cc_dynamicarray.h" // globalDynamicArray, constants
diff --git a/engines/ags/engine/ac/dynobj/managedobjectpool.h b/engines/ags/engine/ac/dynobj/managedobjectpool.h
index a66f23c869..1dee09a0da 100644
--- a/engines/ags/engine/ac/dynobj/managedobjectpool.h
+++ b/engines/ags/engine/ac/dynobj/managedobjectpool.h
@@ -23,9 +23,9 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_MANAGEDOBJECTPOOL_H
 #define AGS_ENGINE_AC_DYNOBJ_MANAGEDOBJECTPOOL_H
 
-#include "ags/std/vector.h"
-#include "ags/std/queue.h"
-#include "ags/std/map.h"
+#include "ags/lib/std/vector.h"
+#include "ags/lib/std/queue.h"
+#include "ags/lib/std/map.h"
 #include "ags/engine/script/runtimescriptvalue.h"
 #include "ags/engine/ac/dynobj/cc_dynamicobject.h"   // ICCDynamicObject
 #include "ags/shared/util/string_types.h"
diff --git a/engines/ags/engine/ac/dynobj/scriptdict.h b/engines/ags/engine/ac/dynobj/scriptdict.h
index e560fccf9e..8d6210da27 100644
--- a/engines/ags/engine/ac/dynobj/scriptdict.h
+++ b/engines/ags/engine/ac/dynobj/scriptdict.h
@@ -37,7 +37,7 @@
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTDICT_H
 
 //include <string.h>
-#include "ags/std/map.h"
+#include "ags/lib/std/map.h"
 #include "ags/engine/ac/dynobj/cc_agsdynamicobject.h"
 #include "ags/shared/util/string.h"
 #include "ags/shared/util/string_types.h"
diff --git a/engines/ags/engine/ac/dynobj/scriptset.h b/engines/ags/engine/ac/dynobj/scriptset.h
index 10a00757ac..073390d0dd 100644
--- a/engines/ags/engine/ac/dynobj/scriptset.h
+++ b/engines/ags/engine/ac/dynobj/scriptset.h
@@ -35,9 +35,9 @@
 #ifndef AGS_ENGINE_AC_DYNOBJ_SCRIPTSET_H
 #define AGS_ENGINE_AC_DYNOBJ_SCRIPTSET_H
 
-#include "ags/std/set.h"
-#include "ags/std/unordered_set.h"
-#include "ags/std/map.h"
+#include "ags/lib/std/set.h"
+#include "ags/lib/std/unordered_set.h"
+#include "ags/lib/std/map.h"
 #include "ags/engine/ac/dynobj/cc_agsdynamicobject.h"
 #include "ags/shared/util/string.h"
 #include "ags/shared/util/string_types.h"
diff --git a/engines/ags/engine/ac/dynobj/scriptuserobject.cpp b/engines/ags/engine/ac/dynobj/scriptuserobject.cpp
index ae02f3cb91..81a7095405 100644
--- a/engines/ags/engine/ac/dynobj/scriptuserobject.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptuserobject.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/std/memory.h"
+#include "ags/lib/std/memory.h"
 #include "ags/engine/ac/dynobj/scriptuserobject.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/ac/gamestate.cpp b/engines/ags/engine/ac/gamestate.cpp
index 125f211b53..347899db76 100644
--- a/engines/ags/engine/ac/gamestate.cpp
+++ b/engines/ags/engine/ac/gamestate.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/std/algorithm.h"
+#include "ags/lib/std/algorithm.h"
 #include "ags/engine/ac/draw.h"
 #include "ags/shared/ac/game_version.h"
 #include "ags/engine/ac/gamestate.h"
diff --git a/engines/ags/engine/ac/gamestate.h b/engines/ags/engine/ac/gamestate.h
index cf6102581f..0285962a5e 100644
--- a/engines/ags/engine/ac/gamestate.h
+++ b/engines/ags/engine/ac/gamestate.h
@@ -23,8 +23,8 @@
 #ifndef AGS_ENGINE_AC_GAMESTATE_H
 #define AGS_ENGINE_AC_GAMESTATE_H
 
-#include "ags/std/memory.h"
-#include "ags/std/vector.h"
+#include "ags/lib/std/memory.h"
+#include "ags/lib/std/vector.h"
 #include "ags/shared/ac/characterinfo.h"
 #include "ags/engine/ac/runtime_defines.h"
 #include "ags/shared/game/roomstruct.h"
diff --git a/engines/ags/engine/ac/listbox.cpp b/engines/ags/engine/ac/listbox.cpp
index 081cc25e27..baeeab7222 100644
--- a/engines/ags/engine/ac/listbox.cpp
+++ b/engines/ags/engine/ac/listbox.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/std/set.h"
+#include "ags/lib/std/set.h"
 #include "ags/engine/ac/listbox.h"
 #include "ags/shared/ac/common.h"
 #include "ags/engine/ac/game.h"
diff --git a/engines/ags/engine/ac/overlay.h b/engines/ags/engine/ac/overlay.h
index 8300596c6f..429da7ace8 100644
--- a/engines/ags/engine/ac/overlay.h
+++ b/engines/ags/engine/ac/overlay.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_AC_OVERLAY_H
 #define AGS_ENGINE_AC_OVERLAY_H
 
-#include "ags/std/vector.h"
+#include "ags/lib/std/vector.h"
 #include "ags/engine/ac/screenoverlay.h"
 #include "ags/engine/ac/dynobj/scriptoverlay.h"
 
diff --git a/engines/ags/engine/ac/route_finder_jps.inl b/engines/ags/engine/ac/route_finder_jps.inl
index 0f21f05c75..c977b48f57 100644
--- a/engines/ags/engine/ac/route_finder_jps.inl
+++ b/engines/ags/engine/ac/route_finder_jps.inl
@@ -27,11 +27,11 @@
 //
 //=============================================================================
 
-#include "ags/std/queue.h"
-#include "ags/std/vector.h"
-#include "ags/std/algorithm.h"
-#include "ags/std/functional.h"
-#include "ags/std/xutility.h"
+#include "ags/lib/std/queue.h"
+#include "ags/lib/std/vector.h"
+#include "ags/lib/std/algorithm.h"
+#include "ags/lib/std/functional.h"
+#include "ags/lib/std/xutility.h"
 //include <assert.h>
 //include <stddef.h>
 //include <math.h>
diff --git a/engines/ags/engine/ac/timer.h b/engines/ags/engine/ac/timer.h
index b737923aee..6470e7ff7b 100644
--- a/engines/ags/engine/ac/timer.h
+++ b/engines/ags/engine/ac/timer.h
@@ -23,9 +23,9 @@
 #ifndef AGS_ENGINE_AC_TIMER_H
 #define AGS_ENGINE_AC_TIMER_H
 
-#include "ags/std/type_traits.h"
-#include "ags/std/chrono.h"
-#include "ags/std/xtr1common.h"
+#include "ags/lib/std/type_traits.h"
+#include "ags/lib/std/chrono.h"
+#include "ags/lib/std/xtr1common.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/debugging/debug.cpp b/engines/ags/engine/debugging/debug.cpp
index 903787665d..921108c4b2 100644
--- a/engines/ags/engine/debugging/debug.cpp
+++ b/engines/ags/engine/debugging/debug.cpp
@@ -20,9 +20,9 @@
  *
  */
 
-#include "ags/std/initializer_list.h"
-#include "ags/std/limits.h"
-#include "ags/std/memory.h"
+#include "ags/lib/std/initializer_list.h"
+#include "ags/lib/std/limits.h"
+#include "ags/lib/std/memory.h"
 #include "ags/shared/core/platform.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/gamesetupstruct.h"
diff --git a/engines/ags/engine/debugging/logfile.h b/engines/ags/engine/debugging/logfile.h
index 18a4356342..1f93d64999 100644
--- a/engines/ags/engine/debugging/logfile.h
+++ b/engines/ags/engine/debugging/logfile.h
@@ -35,7 +35,7 @@
 #ifndef AGS_ENGINE_DEBUGGING_LOGFILE_H
 #define AGS_ENGINE_DEBUGGING_LOGFILE_H
 
-#include "ags/std/memory.h"
+#include "ags/lib/std/memory.h"
 #include "ags/shared/debugging/outputhandler.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/debugging/messagebuffer.h b/engines/ags/engine/debugging/messagebuffer.h
index 57016fe611..34956e8e47 100644
--- a/engines/ags/engine/debugging/messagebuffer.h
+++ b/engines/ags/engine/debugging/messagebuffer.h
@@ -31,7 +31,7 @@
 #ifndef AGS_ENGINE_DEBUGGING_MESSAGEBUFFER_H
 #define AGS_ENGINE_DEBUGGING_MESSAGEBUFFER_H
 
-#include "ags/std/vector.h"
+#include "ags/lib/std/vector.h"
 #include "ags/shared/debugging/outputhandler.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/game/savegame.h b/engines/ags/engine/game/savegame.h
index 53b7d355d2..ff0804025d 100644
--- a/engines/ags/engine/game/savegame.h
+++ b/engines/ags/engine/game/savegame.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_GAME_SAVEGAME_H
 #define AGS_ENGINE_GAME_SAVEGAME_H
 
-#include "ags/std/memory.h"
+#include "ags/lib/std/memory.h"
 #include "ags/shared/ac/game_version.h"
 #include "ags/shared/util/error.h"
 #include "ags/shared/util/version.h"
diff --git a/engines/ags/engine/game/savegame_internal.h b/engines/ags/engine/game/savegame_internal.h
index 5db638911e..29661bdc7c 100644
--- a/engines/ags/engine/game/savegame_internal.h
+++ b/engines/ags/engine/game/savegame_internal.h
@@ -23,8 +23,8 @@
 #ifndef AGS_ENGINE_GAME_SAVEGAMEINTERNAL_H
 #define AGS_ENGINE_GAME_SAVEGAMEINTERNAL_H
 
-#include "ags/std/memory.h"
-#include "ags/std/vector.h"
+#include "ags/lib/std/memory.h"
+#include "ags/lib/std/vector.h"
 #include "ags/shared/ac/common_defines.h"
 #include "ags/shared/gfx/bitmap.h"
 #include "ags/engine/media/audio/audiodefines.h"
diff --git a/engines/ags/engine/game/viewport.h b/engines/ags/engine/game/viewport.h
index 3834dd9e0a..3d7964300a 100644
--- a/engines/ags/engine/game/viewport.h
+++ b/engines/ags/engine/game/viewport.h
@@ -29,8 +29,8 @@
 #ifndef AGS_ENGINE_GAME_VIEWPORT_H
 #define AGS_ENGINE_GAME_VIEWPORT_H
 
-#include "ags/std/memory.h"
-#include "ags/std/vector.h"
+#include "ags/lib/std/memory.h"
+#include "ags/lib/std/vector.h"
 #include "ags/shared/util/geometry.h"
 #include "ags/engine/util/scaling.h"
 
diff --git a/engines/ags/engine/gfx/ali3dogl.cpp b/engines/ags/engine/gfx/ali3dogl.cpp
index ec1b2825c1..6d621b1c02 100644
--- a/engines/ags/engine/gfx/ali3dogl.cpp
+++ b/engines/ags/engine/gfx/ali3dogl.cpp
@@ -24,7 +24,7 @@
 
 #if AGS_PLATFORM_OS_WINDOWS || AGS_PLATFORM_OS_ANDROID || AGS_PLATFORM_OS_IOS || AGS_PLATFORM_OS_LINUX
 
-#include "ags/std/algorithm.h"
+#include "ags/lib/std/algorithm.h"
 #include "ags/engine/gfx/ali3dexception.h"
 #include "ags/engine/gfx/ali3dogl.h"
 #include "ags/engine/gfx/gfxfilter_ogl.h"
diff --git a/engines/ags/engine/gfx/ali3dogl.h b/engines/ags/engine/gfx/ali3dogl.h
index c3f944d358..e6dd2e35e8 100644
--- a/engines/ags/engine/gfx/ali3dogl.h
+++ b/engines/ags/engine/gfx/ali3dogl.h
@@ -29,7 +29,7 @@
 #ifndef AGS_ENGINE_GFX_ALI3DOGL_H
 #define AGS_ENGINE_GFX_ALI3DOGL_H
 
-#include "ags/std/memory.h"
+#include "ags/lib/std/memory.h"
 #include "ags/shared/gfx/bitmap.h"
 #include "ags/engine/gfx/ddb.h"
 #include "ags/engine/gfx/gfxdriverfactorybase.h"
diff --git a/engines/ags/engine/gfx/ali3dsw.cpp b/engines/ags/engine/gfx/ali3dsw.cpp
index 9d82d3cb42..3e67d37602 100644
--- a/engines/ags/engine/gfx/ali3dsw.cpp
+++ b/engines/ags/engine/gfx/ali3dsw.cpp
@@ -37,7 +37,7 @@
 #include "ags/engine/ac/timer.h"
 #include "ags/lib/allegro/color.h"
 #include "ags/lib/opengl/opengl.h"
-#include "ags/std/algorithm.h"
+#include "ags/lib/std/algorithm.h"
 #include "ags/ags.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/gfx/ali3dsw.h b/engines/ags/engine/gfx/ali3dsw.h
index a9e2a4fb29..c168667c50 100644
--- a/engines/ags/engine/gfx/ali3dsw.h
+++ b/engines/ags/engine/gfx/ali3dsw.h
@@ -29,7 +29,7 @@
 #ifndef AGS_ENGINE_GFX_ALI3DSW_H
 #define AGS_ENGINE_GFX_ALI3DSW_H
 
-#include "ags/std/memory.h"
+#include "ags/lib/std/memory.h"
 
 #include "ags/shared/core/platform.h"
 #define AGS_DDRAW_GAMMA_CONTROL (AGS_PLATFORM_OS_WINDOWS)
diff --git a/engines/ags/engine/gfx/gfxdriverbase.h b/engines/ags/engine/gfx/gfxdriverbase.h
index 88f83fa6b0..5241a76d36 100644
--- a/engines/ags/engine/gfx/gfxdriverbase.h
+++ b/engines/ags/engine/gfx/gfxdriverbase.h
@@ -29,7 +29,7 @@
 #ifndef AGS_ENGINE_GFX_GFXDRIVERBASE_H
 #define AGS_ENGINE_GFX_GFXDRIVERBASE_H
 
-#include "ags/std/vector.h"
+#include "ags/lib/std/vector.h"
 #include "ags/engine/gfx/ddb.h"
 #include "ags/engine/gfx/graphicsdriver.h"
 #include "ags/engine/util/scaling.h"
diff --git a/engines/ags/engine/gfx/gfxdriverfactory.h b/engines/ags/engine/gfx/gfxdriverfactory.h
index b28560d765..2873b345c0 100644
--- a/engines/ags/engine/gfx/gfxdriverfactory.h
+++ b/engines/ags/engine/gfx/gfxdriverfactory.h
@@ -33,7 +33,7 @@
 #ifndef AGS_ENGINE_GFX_GFXDRIVERFACTORY_H
 #define AGS_ENGINE_GFX_GFXDRIVERFACTORY_H
 
-#include "ags/std/memory.h"
+#include "ags/lib/std/memory.h"
 #include "ags/shared/util/string.h"
 #include "ags/shared/util/string_types.h"
 
diff --git a/engines/ags/engine/gfx/gfxdriverfactorybase.h b/engines/ags/engine/gfx/gfxdriverfactorybase.h
index 8a1d66d567..911f718d83 100644
--- a/engines/ags/engine/gfx/gfxdriverfactorybase.h
+++ b/engines/ags/engine/gfx/gfxdriverfactorybase.h
@@ -33,7 +33,7 @@
 #ifndef AGS_ENGINE_GFX_GFXDRIVERFACTORYBASE_H
 #define AGS_ENGINE_GFX_GFXDRIVERFACTORYBASE_H
 
-#include "ags/std/vector.h"
+#include "ags/lib/std/vector.h"
 #include "ags/engine/gfx/gfxdriverfactory.h"
 #include "ags/engine/gfx/gfxfilter.h"
 
diff --git a/engines/ags/engine/gfx/gfxfilter.h b/engines/ags/engine/gfx/gfxfilter.h
index 7b0f636215..1e03c77190 100644
--- a/engines/ags/engine/gfx/gfxfilter.h
+++ b/engines/ags/engine/gfx/gfxfilter.h
@@ -29,7 +29,7 @@
 #ifndef AGS_ENGINE_GFX_GFXFILTER_H
 #define AGS_ENGINE_GFX_GFXFILTER_H
 
-#include "ags/std/memory.h"
+#include "ags/lib/std/memory.h"
 #include "ags/shared/util/geometry.h"
 #include "ags/shared/util/string.h"
 
diff --git a/engines/ags/engine/gfx/graphicsdriver.h b/engines/ags/engine/gfx/graphicsdriver.h
index 1024addc12..9ff9a77c9c 100644
--- a/engines/ags/engine/gfx/graphicsdriver.h
+++ b/engines/ags/engine/gfx/graphicsdriver.h
@@ -29,7 +29,7 @@
 #ifndef AGS_ENGINE_GFX_GRAPHICSDRIVER_H
 #define AGS_ENGINE_GFX_GRAPHICSDRIVER_H
 
-#include "ags/std/memory.h"
+#include "ags/lib/std/memory.h"
 #include "ags/engine/gfx/gfxdefines.h"
 #include "ags/engine/gfx/gfxmodelist.h"
 #include "ags/shared/util/geometry.h"
diff --git a/engines/ags/engine/main/game_run.cpp b/engines/ags/engine/main/game_run.cpp
index 541b1ab719..a695db97ac 100644
--- a/engines/ags/engine/main/game_run.cpp
+++ b/engines/ags/engine/main/game_run.cpp
@@ -24,8 +24,8 @@
 // Game loop
 //
 
-#include "ags/std/limits.h"
-#include "ags/std/chrono.h"
+#include "ags/lib/std/limits.h"
+#include "ags/lib/std/chrono.h"
 #include "ags/shared/ac/common.h"
 #include "ags/engine/ac/characterextras.h"
 #include "ags/shared/ac/characterinfo.h"
diff --git a/engines/ags/engine/media/audio/audio.h b/engines/ags/engine/media/audio/audio.h
index 42471bfd76..192de3246e 100644
--- a/engines/ags/engine/media/audio/audio.h
+++ b/engines/ags/engine/media/audio/audio.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_MEDIA_AUDIO_AUDIO_H
 #define AGS_ENGINE_MEDIA_AUDIO_AUDIO_H
 
-#include "ags/std/array.h"
+#include "ags/lib/std/array.h"
 #include "ags/engine/media/audio/audiodefines.h"
 #include "ags/shared/ac/dynobj/scriptaudioclip.h"
 #include "ags/engine/ac/dynobj/scriptaudiochannel.h"
diff --git a/engines/ags/engine/platform/base/agsplatformdriver.cpp b/engines/ags/engine/platform/base/agsplatformdriver.cpp
index 11d4e585eb..ea977eb504 100644
--- a/engines/ags/engine/platform/base/agsplatformdriver.cpp
+++ b/engines/ags/engine/platform/base/agsplatformdriver.cpp
@@ -37,7 +37,7 @@
 #include "ags/engine/ac/timer.h"
 #include "ags/engine/media/audio/audio_system.h"
 #include "ags/lib/system/datetime.h"
-#include "ags/std/algorithm.h"
+#include "ags/lib/std/algorithm.h"
 
 #if defined (AGS_HAS_CD_AUDIO)
 #include "libcda.h"
diff --git a/engines/ags/engine/platform/base/agsplatformdriver.h b/engines/ags/engine/platform/base/agsplatformdriver.h
index 1975d94353..95c7c68b3d 100644
--- a/engines/ags/engine/platform/base/agsplatformdriver.h
+++ b/engines/ags/engine/platform/base/agsplatformdriver.h
@@ -29,7 +29,7 @@
 #ifndef AGS_ENGINE_PLATFORM_BASE_AGSPLATFORMDRIVER_H
 #define AGS_ENGINE_PLATFORM_BASE_AGSPLATFORMDRIVER_H
 
-#include "ags/std/vector.h"
+#include "ags/lib/std/vector.h"
 #include "ags/engine/ac/datetime.h"
 #include "ags/shared/debugging/outputhandler.h"
 #include "ags/shared/util/ini_util.h"
diff --git a/engines/ags/engine/platform/windows/gfx/ali3dd3d.h b/engines/ags/engine/platform/windows/gfx/ali3dd3d.h
index deb25f9d97..62558e34c6 100644
--- a/engines/ags/engine/platform/windows/gfx/ali3dd3d.h
+++ b/engines/ags/engine/platform/windows/gfx/ali3dd3d.h
@@ -35,7 +35,7 @@
 #error This file should only be included on the Windows build
 #endif
 
-#include "ags/std/memory.h"
+#include "ags/lib/std/memory.h"
 #include "ags/lib/allegro.h"
 //include <winalleg.h>
 //include <d3d9.h>
diff --git a/engines/ags/engine/platform/windows/setup/winsetup.cpp b/engines/ags/engine/platform/windows/setup/winsetup.cpp
index 3a3e824f10..3ee704f376 100644
--- a/engines/ags/engine/platform/windows/setup/winsetup.cpp
+++ b/engines/ags/engine/platform/windows/setup/winsetup.cpp
@@ -29,10 +29,10 @@
 //include <crtdbg.h>
 //include <shlobj.h>
 //include <shlwapi.h>
-#include "ags/std/memory.h"
+#include "ags/lib/std/memory.h"
 //include <algorithm>
 //include <set>
-#include "ags/std/vector.h"
+#include "ags/lib/std/vector.h"
 #include "ags/shared/ac/gamestructdefines.h"
 #undef RGB
 #undef PALETTE
diff --git a/engines/ags/engine/plugin/agsplugin.cpp b/engines/ags/engine/plugin/agsplugin.cpp
index 5307263fd9..f128e0c599 100644
--- a/engines/ags/engine/plugin/agsplugin.cpp
+++ b/engines/ags/engine/plugin/agsplugin.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/std/vector.h"
+#include "ags/lib/std/vector.h"
 #include "ags/shared/core/platform.h"
 #if AGS_PLATFORM_OS_WINDOWS
 #include "ags/shared/platform/windows/winapi_exclusive.h"
diff --git a/engines/ags/engine/plugin/plugin_engine.h b/engines/ags/engine/plugin/plugin_engine.h
index 736f5d5950..430d3c5d7e 100644
--- a/engines/ags/engine/plugin/plugin_engine.h
+++ b/engines/ags/engine/plugin/plugin_engine.h
@@ -29,7 +29,7 @@
 #ifndef AGS_ENGINE_PLUGIN_PLUGIN_ENGINE_H
 #define AGS_ENGINE_PLUGIN_PLUGIN_ENGINE_H
 
-#include "ags/std/vector.h"
+#include "ags/lib/std/vector.h"
 #include "ags/engine/game/game_init.h"
 #include "ags/shared/game/plugininfo.h"
 
diff --git a/engines/ags/engine/script/cc_instance.h b/engines/ags/engine/script/cc_instance.h
index 7b0dd97c2c..efa176d30f 100644
--- a/engines/ags/engine/script/cc_instance.h
+++ b/engines/ags/engine/script/cc_instance.h
@@ -29,8 +29,8 @@
 #ifndef AGS_ENGINE_SCRIPT_CCINSTANCE_H
 #define AGS_ENGINE_SCRIPT_CCINSTANCE_H
 
-#include "ags/std/map.h"
-#include "ags/std/memory.h"
+#include "ags/lib/std/map.h"
+#include "ags/lib/std/memory.h"
 #include "ags/shared/script/script_common.h"
 #include "ags/shared/script/cc_script.h"  // ccScript
 #include "ags/engine/script/nonblockingscriptfunction.h"
diff --git a/engines/ags/engine/script/nonblockingscriptfunction.h b/engines/ags/engine/script/nonblockingscriptfunction.h
index a7e982a1cd..b4439ff3a8 100644
--- a/engines/ags/engine/script/nonblockingscriptfunction.h
+++ b/engines/ags/engine/script/nonblockingscriptfunction.h
@@ -26,7 +26,7 @@
 #include "ags/engine/ac/runtime_defines.h"
 #include "ags/engine/script/runtimescriptvalue.h"
 
-#include "ags/std/vector.h"
+#include "ags/lib/std/vector.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/script/script.h b/engines/ags/engine/script/script.h
index 8c797038cd..abc5eea914 100644
--- a/engines/ags/engine/script/script.h
+++ b/engines/ags/engine/script/script.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_SCRIPT_SCRIPT_H
 #define AGS_ENGINE_SCRIPT_SCRIPT_H
 
-#include "ags/std/vector.h"
+#include "ags/lib/std/vector.h"
 
 #include "ags/shared/game/roomstruct.h" // MAX_ROOM_OBJECTS
 #include "ags/engine/script/cc_instance.h"
diff --git a/engines/ags/engine/script/systemimports.h b/engines/ags/engine/script/systemimports.h
index 4bf2238dd9..1332252b06 100644
--- a/engines/ags/engine/script/systemimports.h
+++ b/engines/ags/engine/script/systemimports.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_SCRIPT_SYSTEMIMPORTS_H
 #define AGS_ENGINE_SCRIPT_SYSTEMIMPORTS_H
 
-#include "ags/std/map.h"
+#include "ags/lib/std/map.h"
 #include "ags/engine/script/cc_instance.h"    // ccInstance
 #include "ags/shared/util/string_types.h"
 
diff --git a/engines/ags/engine/util/mutex_std.h b/engines/ags/engine/util/mutex_std.h
index 41ab31ea26..47c6209184 100644
--- a/engines/ags/engine/util/mutex_std.h
+++ b/engines/ags/engine/util/mutex_std.h
@@ -24,7 +24,7 @@
 #define AGS_ENGINE_UTIL_MUTEX_STD_H
 
 #include "ags/engine/util/mutex.h"
-#include "ags/std/mutex.h"
+#include "ags/lib/std/mutex.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/util/thread_std.h b/engines/ags/engine/util/thread_std.h
index 88d6543f61..1ad4477838 100644
--- a/engines/ags/engine/util/thread_std.h
+++ b/engines/ags/engine/util/thread_std.h
@@ -25,7 +25,7 @@
 
 //include <system_error>
 #include "ags/engine/util/thread.h"
-#include "ags/std/thread.h"
+#include "ags/lib/std/thread.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/std/algorithm.h b/engines/ags/lib/std/algorithm.h
similarity index 100%
rename from engines/ags/std/algorithm.h
rename to engines/ags/lib/std/algorithm.h
diff --git a/engines/ags/std/array.h b/engines/ags/lib/std/array.h
similarity index 100%
rename from engines/ags/std/array.h
rename to engines/ags/lib/std/array.h
diff --git a/engines/ags/std/chrono.h b/engines/ags/lib/std/chrono.h
similarity index 100%
rename from engines/ags/std/chrono.h
rename to engines/ags/lib/std/chrono.h
diff --git a/engines/ags/std/functional.h b/engines/ags/lib/std/functional.h
similarity index 100%
rename from engines/ags/std/functional.h
rename to engines/ags/lib/std/functional.h
diff --git a/engines/ags/std/initializer_list.h b/engines/ags/lib/std/initializer_list.h
similarity index 100%
rename from engines/ags/std/initializer_list.h
rename to engines/ags/lib/std/initializer_list.h
diff --git a/engines/ags/std/limits.h b/engines/ags/lib/std/limits.h
similarity index 100%
rename from engines/ags/std/limits.h
rename to engines/ags/lib/std/limits.h
diff --git a/engines/ags/std/list.h b/engines/ags/lib/std/list.h
similarity index 100%
rename from engines/ags/std/list.h
rename to engines/ags/lib/std/list.h
diff --git a/engines/ags/std/map.h b/engines/ags/lib/std/map.h
similarity index 98%
rename from engines/ags/std/map.h
rename to engines/ags/lib/std/map.h
index 70156b9cb2..3d596dc0c7 100644
--- a/engines/ags/std/map.h
+++ b/engines/ags/lib/std/map.h
@@ -24,7 +24,7 @@
 #define AGS_STD_MAP_H
 
 #include "common/hashmap.h"
-#include "ags/std/utility.h"
+#include "ags/lib/std/utility.h"
 
 namespace AGS3 {
 namespace std {
diff --git a/engines/ags/std/math.h b/engines/ags/lib/std/math.h
similarity index 97%
rename from engines/ags/std/math.h
rename to engines/ags/lib/std/math.h
index 8fa5814ed6..14cc226822 100644
--- a/engines/ags/std/math.h
+++ b/engines/ags/lib/std/math.h
@@ -24,7 +24,7 @@
 #define AGS_STD_MATH_H
 
 #include "common/hashmap.h"
-#include "ags/std/utility.h"
+#include "ags/lib/std/utility.h"
 
 namespace AGS3 {
 namespace std {
diff --git a/engines/ags/std/memory.h b/engines/ags/lib/std/memory.h
similarity index 100%
rename from engines/ags/std/memory.h
rename to engines/ags/lib/std/memory.h
diff --git a/engines/ags/std/mutex.h b/engines/ags/lib/std/mutex.h
similarity index 100%
rename from engines/ags/std/mutex.h
rename to engines/ags/lib/std/mutex.h
diff --git a/engines/ags/std/queue.h b/engines/ags/lib/std/queue.h
similarity index 96%
rename from engines/ags/std/queue.h
rename to engines/ags/lib/std/queue.h
index 52761ec45d..b8846fd8c4 100644
--- a/engines/ags/std/queue.h
+++ b/engines/ags/lib/std/queue.h
@@ -23,8 +23,8 @@
 #ifndef AGS_STD_QUEUE_H
 #define AGS_STD_QUEUE_H
 
-#include "ags/std/algorithm.h"
-#include "ags/std/vector.h"
+#include "ags/lib/std/algorithm.h"
+#include "ags/lib/std/vector.h"
 #include "common/queue.h"
 
 namespace AGS3 {
diff --git a/engines/ags/std/set.h b/engines/ags/lib/std/set.h
similarity index 100%
rename from engines/ags/std/set.h
rename to engines/ags/lib/std/set.h
diff --git a/engines/ags/lib/std/std.cpp b/engines/ags/lib/std/std.cpp
new file mode 100644
index 0000000000..4a737d3cbe
--- /dev/null
+++ b/engines/ags/lib/std/std.cpp
@@ -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.
+ *
+ */
+
+// Dummy include of STD mockup headers so they'll appear in the Visual Studio project
+
+#include "ags/lib/std/algorithm.h"
+#include "ags/lib/std/array.h"
+#include "ags/lib/std/chrono.h"
+#include "ags/lib/std/functional.h"
+#include "ags/lib/std/initializer_list.h"
+#include "ags/lib/std/limits.h"
+#include "ags/lib/std/list.h"
+#include "ags/lib/std/map.h"
+#include "ags/lib/std/math.h"
+#include "ags/lib/std/memory.h"
+#include "ags/lib/std/mutex.h"
+#include "ags/lib/std/queue.h"
+#include "ags/lib/std/set.h"
+#include "ags/lib/std/thread.h"
+#include "ags/lib/std/type_traits.h"
+#include "ags/lib/std/unordered_set.h"
+#include "ags/lib/std/utility.h"
+#include "ags/lib/std/vector.h"
+#include "ags/lib/std/xtr1common.h"
+#include "ags/lib/std/xutility.h"
diff --git a/engines/ags/std/thread.h b/engines/ags/lib/std/thread.h
similarity index 98%
rename from engines/ags/std/thread.h
rename to engines/ags/lib/std/thread.h
index 53455e9dd0..bdd43e6cf7 100644
--- a/engines/ags/std/thread.h
+++ b/engines/ags/lib/std/thread.h
@@ -23,7 +23,7 @@
 #ifndef AGS_STD_THREAD_H
 #define AGS_STD_THREAD_H
 
-#include "ags/std/chrono.h"
+#include "ags/lib/std/chrono.h"
 #include "common/textconsole.h"
 
 namespace AGS3 {
diff --git a/engines/ags/std/type_traits.h b/engines/ags/lib/std/type_traits.h
similarity index 100%
rename from engines/ags/std/type_traits.h
rename to engines/ags/lib/std/type_traits.h
diff --git a/engines/ags/std/unordered_set.h b/engines/ags/lib/std/unordered_set.h
similarity index 100%
rename from engines/ags/std/unordered_set.h
rename to engines/ags/lib/std/unordered_set.h
diff --git a/engines/ags/std/utility.h b/engines/ags/lib/std/utility.h
similarity index 100%
rename from engines/ags/std/utility.h
rename to engines/ags/lib/std/utility.h
diff --git a/engines/ags/std/vector.h b/engines/ags/lib/std/vector.h
similarity index 100%
rename from engines/ags/std/vector.h
rename to engines/ags/lib/std/vector.h
diff --git a/engines/ags/std/xtr1common.h b/engines/ags/lib/std/xtr1common.h
similarity index 100%
rename from engines/ags/std/xtr1common.h
rename to engines/ags/lib/std/xtr1common.h
diff --git a/engines/ags/std/xutility.h b/engines/ags/lib/std/xutility.h
similarity index 100%
rename from engines/ags/std/xutility.h
rename to engines/ags/lib/std/xutility.h
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index fd1677c059..59e28d33b6 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -27,6 +27,7 @@ MODULE_OBJS = \
 	lib/audio/sound.o \
 	lib/audio/wav.o \
 	lib/opengl/opengl.o \
+	lib/std/std.o \
 	lib/system/datetime.o \
 	shared/ac/dynobj/scriptaudioclip.o \
 	shared/ac/audiocliptype.o \
diff --git a/engines/ags/shared/ac/gamesetupstruct.h b/engines/ags/shared/ac/gamesetupstruct.h
index 3d47eea279..7dc8660f03 100644
--- a/engines/ags/shared/ac/gamesetupstruct.h
+++ b/engines/ags/shared/ac/gamesetupstruct.h
@@ -23,8 +23,8 @@
 #ifndef AGS_SHARED_AC_GAMESETUPSTRUCT_H
 #define AGS_SHARED_AC_GAMESETUPSTRUCT_H
 
-#include "ags/std/vector.h"
-#include "ags/std/memory.h"
+#include "ags/lib/std/vector.h"
+#include "ags/lib/std/memory.h"
 #include "ags/shared/ac/audiocliptype.h"
 #include "ags/shared/ac/characterinfo.h" // TODO: constants to separate header
 #include "ags/shared/ac/gamesetupstructbase.h"
diff --git a/engines/ags/shared/ac/spritecache.h b/engines/ags/shared/ac/spritecache.h
index 4ee33e4f61..712985ef24 100644
--- a/engines/ags/shared/ac/spritecache.h
+++ b/engines/ags/shared/ac/spritecache.h
@@ -45,8 +45,8 @@
 #ifndef AGS_SHARED_AC_SPRITECACHE_H
 #define AGS_SHARED_AC_SPRITECACHE_H
 
-#include "ags/std/memory.h"
-#include "ags/std/vector.h"
+#include "ags/lib/std/memory.h"
+#include "ags/lib/std/vector.h"
 #include "ags/shared/core/platform.h"
 #include "ags/shared/util/error.h"
 
diff --git a/engines/ags/shared/ac/view.h b/engines/ags/shared/ac/view.h
index b30b406e58..e05863aea3 100644
--- a/engines/ags/shared/ac/view.h
+++ b/engines/ags/shared/ac/view.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_AC_VIEW_H
 #define AGS_SHARED_AC_VIEW_H
 
-#include "ags/std/vector.h"
+#include "ags/lib/std/vector.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/ac/wordsdictionary.cpp b/engines/ags/shared/ac/wordsdictionary.cpp
index 6ec5cfe571..a73f247a93 100644
--- a/engines/ags/shared/ac/wordsdictionary.cpp
+++ b/engines/ags/shared/ac/wordsdictionary.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/std/algorithm.h"
+#include "ags/lib/std/algorithm.h"
 //include <string.h>
 #include "ags/shared/ac/wordsdictionary.h"
 #include "ags/shared/util/stream.h"
diff --git a/engines/ags/shared/core/asset.h b/engines/ags/shared/core/asset.h
index bcbed3a231..71081a8716 100644
--- a/engines/ags/shared/core/asset.h
+++ b/engines/ags/shared/core/asset.h
@@ -29,7 +29,7 @@
 #ifndef AGS_SHARED_CORE_ASSET_H
 #define AGS_SHARED_CORE_ASSET_H
 
-#include "ags/std/vector.h"
+#include "ags/lib/std/vector.h"
 #include "ags/shared/util/string.h"
 
 namespace AGS3 {
diff --git a/engines/ags/shared/debugging/debugmanager.h b/engines/ags/shared/debugging/debugmanager.h
index eefa9aac01..a8b92fc527 100644
--- a/engines/ags/shared/debugging/debugmanager.h
+++ b/engines/ags/shared/debugging/debugmanager.h
@@ -47,8 +47,8 @@
 #ifndef AGS_SHARED_DEBUGGING_DEBUGMANAGER_H
 #define AGS_SHARED_DEBUGGING_DEBUGMANAGER_H
 
-#include "ags/std/memory.h"
-#include "ags/std/map.h"
+#include "ags/lib/std/memory.h"
+#include "ags/lib/std/map.h"
 #include "ags/shared/debugging/out.h"
 #include "ags/shared/debugging/outputhandler.h"
 #include "ags/shared/util/string.h"
diff --git a/engines/ags/shared/font/fonts.cpp b/engines/ags/shared/font/fonts.cpp
index ad4c4c5ab2..5ffaf7788f 100644
--- a/engines/ags/shared/font/fonts.cpp
+++ b/engines/ags/shared/font/fonts.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/std/vector.h"
+#include "ags/lib/std/vector.h"
 #include "ags/lib/alfont/alfont.h"
 #include "ags/shared/ac/common.h" // set_our_eip
 #include "ags/shared/ac/gamestructdefines.h"
diff --git a/engines/ags/shared/font/fonts.h b/engines/ags/shared/font/fonts.h
index 56dcb7d3c0..b9374f49d6 100644
--- a/engines/ags/shared/font/fonts.h
+++ b/engines/ags/shared/font/fonts.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_FONT_FONTS_H
 #define AGS_SHARED_FONT_FONTS_H
 
-#include "ags/std/vector.h"
+#include "ags/lib/std/vector.h"
 #include "ags/shared/core/types.h"
 #include "ags/shared/util/string.h"
 
diff --git a/engines/ags/shared/font/ttffontrenderer.h b/engines/ags/shared/font/ttffontrenderer.h
index 368dac016e..033425cdc6 100644
--- a/engines/ags/shared/font/ttffontrenderer.h
+++ b/engines/ags/shared/font/ttffontrenderer.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_FONT_TTFFONTRENDERER_H
 #define AGS_SHARED_FONT_TTFFONTRENDERER_H
 
-#include "ags/std/map.h"
+#include "ags/lib/std/map.h"
 #include "ags/lib/alfont/alfont.h"
 #include "ags/shared/font/agsfontrenderer.h"
 
diff --git a/engines/ags/shared/font/wfnfont.cpp b/engines/ags/shared/font/wfnfont.cpp
index c98d5e3d1c..2e07a5955c 100644
--- a/engines/ags/shared/font/wfnfont.cpp
+++ b/engines/ags/shared/font/wfnfont.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/std/algorithm.h"
+#include "ags/lib/std/algorithm.h"
 #include "ags/shared/font/wfnfont.h"
 #include "ags/shared/debugging/out.h"
 #include "ags/shared/util/memory.h"
diff --git a/engines/ags/shared/font/wfnfont.h b/engines/ags/shared/font/wfnfont.h
index 583d304598..c5e23e3956 100644
--- a/engines/ags/shared/font/wfnfont.h
+++ b/engines/ags/shared/font/wfnfont.h
@@ -46,7 +46,7 @@
 #ifndef AGS_SHARED_FONT_WFNFONT_H
 #define AGS_SHARED_FONT_WFNFONT_H
 
-#include "ags/std/vector.h"
+#include "ags/lib/std/vector.h"
 #include "ags/shared/core/types.h"
 
 namespace AGS3 {
diff --git a/engines/ags/shared/font/wfnfontrenderer.h b/engines/ags/shared/font/wfnfontrenderer.h
index 76d57efe9b..47341efe48 100644
--- a/engines/ags/shared/font/wfnfontrenderer.h
+++ b/engines/ags/shared/font/wfnfontrenderer.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_FONT_WFNFONTRENDERER_H
 #define AGS_SHARED_FONT_WFNFONTRENDERER_H
 
-#include "ags/std/map.h"
+#include "ags/lib/std/map.h"
 #include "ags/shared/font/agsfontrenderer.h"
 
 namespace AGS3 {
diff --git a/engines/ags/shared/game/customproperties.h b/engines/ags/shared/game/customproperties.h
index 7b956e9d79..14bcd2eba3 100644
--- a/engines/ags/shared/game/customproperties.h
+++ b/engines/ags/shared/game/customproperties.h
@@ -36,7 +36,7 @@
 #ifndef AGS_SHARED_GAME_CUSTOMPROPERTIES_H
 #define AGS_SHARED_GAME_CUSTOMPROPERTIES_H
 
-#include "ags/std/map.h"
+#include "ags/lib/std/map.h"
 #include "ags/shared/util/string.h"
 #include "ags/shared/util/string_types.h"
 
diff --git a/engines/ags/shared/game/interactions.h b/engines/ags/shared/game/interactions.h
index ead5ec7a48..dba759886f 100644
--- a/engines/ags/shared/game/interactions.h
+++ b/engines/ags/shared/game/interactions.h
@@ -50,7 +50,7 @@
 #define AGS_SHARED_GAME_INTEREACTIONS_H
 
 #include "ags/shared/util/string_types.h"
-#include "ags/std/memory.h"
+#include "ags/lib/std/memory.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/game/main_game_file.h b/engines/ags/shared/game/main_game_file.h
index 3fb86a794c..0a30f115e0 100644
--- a/engines/ags/shared/game/main_game_file.h
+++ b/engines/ags/shared/game/main_game_file.h
@@ -31,9 +31,9 @@
 #ifndef AGS_SHARED_GAME_MAINGAMEFILE_H
 #define AGS_SHARED_GAME_MAINGAMEFILE_H
 
-#include "ags/std/memory.h"
-#include "ags/std/set.h"
-#include "ags/std/vector.h"
+#include "ags/lib/std/memory.h"
+#include "ags/lib/std/set.h"
+#include "ags/lib/std/vector.h"
 #include "ags/shared/ac/game_version.h"
 #include "ags/shared/game/plugininfo.h"
 #include "ags/shared/script/cc_script.h"
diff --git a/engines/ags/shared/game/plugininfo.h b/engines/ags/shared/game/plugininfo.h
index 025ccd8ce6..1ce6f27c13 100644
--- a/engines/ags/shared/game/plugininfo.h
+++ b/engines/ags/shared/game/plugininfo.h
@@ -29,7 +29,7 @@
 #ifndef AGS_SHARED_GAME_PLUGININFO_H
 #define AGS_SHARED_GAME_PLUGININFO_H
 
-#include "ags/std/memory.h"
+#include "ags/lib/std/memory.h"
 #include "ags/shared/util/string.h"
 
 namespace AGS3 {
diff --git a/engines/ags/shared/game/room_file.h b/engines/ags/shared/game/room_file.h
index 1de92c364b..1874dbeebf 100644
--- a/engines/ags/shared/game/room_file.h
+++ b/engines/ags/shared/game/room_file.h
@@ -31,8 +31,8 @@
 #ifndef AGS_SHARED_GAME_ROOMFILE_H
 #define AGS_SHARED_GAME_ROOMFILE_H
 
-#include "ags/std/memory.h"
-#include "ags/std/vector.h"
+#include "ags/lib/std/memory.h"
+#include "ags/lib/std/vector.h"
 #include "ags/shared/game/room_version.h"
 #include "ags/shared/util/error.h"
 #include "ags/shared/util/stream.h"
diff --git a/engines/ags/shared/game/roomstruct.h b/engines/ags/shared/game/roomstruct.h
index 40bd7dd461..45fe84740a 100644
--- a/engines/ags/shared/game/roomstruct.h
+++ b/engines/ags/shared/game/roomstruct.h
@@ -52,7 +52,7 @@
 #include "ags/shared/game/interactions.h"
 #include "ags/shared/util/geometry.h"
 #include "ags/shared/util/wgt2allg.h" // color (allegro RGB)
-#include "ags/std/memory.h"
+#include "ags/lib/std/memory.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/gui/guibutton.h b/engines/ags/shared/gui/guibutton.h
index ab03e4fd23..1176faacf4 100644
--- a/engines/ags/shared/gui/guibutton.h
+++ b/engines/ags/shared/gui/guibutton.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_GUI_GUIBUTTON_H
 #define AGS_SHARED_GUI_GUIBUTTON_H
 
-#include "ags/std/vector.h"
+#include "ags/lib/std/vector.h"
 #include "ags/shared/gui/guiobject.h"
 #include "ags/shared/util/string.h"
 
diff --git a/engines/ags/shared/gui/guiinv.h b/engines/ags/shared/gui/guiinv.h
index 7ab166063e..5e585ded79 100644
--- a/engines/ags/shared/gui/guiinv.h
+++ b/engines/ags/shared/gui/guiinv.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_GUI_GUIINV_H
 #define AGS_SHARED_GUI_GUIINV_H
 
-#include "ags/std/vector.h"
+#include "ags/lib/std/vector.h"
 #include "ags/shared/gui/guiobject.h"
 
 namespace AGS3 {
diff --git a/engines/ags/shared/gui/guilabel.h b/engines/ags/shared/gui/guilabel.h
index 82d7b7538d..22a690b45f 100644
--- a/engines/ags/shared/gui/guilabel.h
+++ b/engines/ags/shared/gui/guilabel.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_GUI_GUILABEL_H
 #define AGS_SHARED_GUI_GUILABEL_H
 
-#include "ags/std/vector.h"
+#include "ags/lib/std/vector.h"
 #include "ags/shared/gui/guiobject.h"
 #include "ags/shared/util/string.h"
 
diff --git a/engines/ags/shared/gui/guilistbox.h b/engines/ags/shared/gui/guilistbox.h
index 52193b6af4..b754decaab 100644
--- a/engines/ags/shared/gui/guilistbox.h
+++ b/engines/ags/shared/gui/guilistbox.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_GUI_GUILISTBOX_H
 #define AGS_SHARED_GUI_GUILISTBOX_H
 
-#include "ags/std/vector.h"
+#include "ags/lib/std/vector.h"
 #include "ags/shared/gui/guiobject.h"
 #include "ags/shared/util/string.h"
 
diff --git a/engines/ags/shared/gui/guimain.cpp b/engines/ags/shared/gui/guimain.cpp
index 1fb82b5175..889bf289f7 100644
--- a/engines/ags/shared/gui/guimain.cpp
+++ b/engines/ags/shared/gui/guimain.cpp
@@ -33,7 +33,7 @@
 #include "ags/shared/gui/guitextbox.h"
 #include "ags/shared/util/stream.h"
 #include "ags/shared/util/string_utils.h"
-#include "ags/std/algorithm.h"
+#include "ags/lib/std/algorithm.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/gui/guimain.h b/engines/ags/shared/gui/guimain.h
index 4c42a25e59..3e72bbae29 100644
--- a/engines/ags/shared/gui/guimain.h
+++ b/engines/ags/shared/gui/guimain.h
@@ -29,8 +29,8 @@
 #include "ags/shared/util/error.h"
 #include "ags/shared/util/geometry.h"
 #include "ags/shared/util/string.h"
-#include "ags/std/utility.h"
-#include "ags/std/vector.h"
+#include "ags/lib/std/utility.h"
+#include "ags/lib/std/vector.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/gui/guislider.h b/engines/ags/shared/gui/guislider.h
index 5cbb4fc00d..b2ac2663d7 100644
--- a/engines/ags/shared/gui/guislider.h
+++ b/engines/ags/shared/gui/guislider.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_GUI_GUISLIDER_H
 #define AGS_SHARED_GUI_GUISLIDER_H
 
-#include "ags/std/vector.h"
+#include "ags/lib/std/vector.h"
 #include "ags/shared/gui/guiobject.h"
 
 namespace AGS3 {
diff --git a/engines/ags/shared/gui/guitextbox.h b/engines/ags/shared/gui/guitextbox.h
index 53b830590a..840f3f6e27 100644
--- a/engines/ags/shared/gui/guitextbox.h
+++ b/engines/ags/shared/gui/guitextbox.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_GUI_GUITEXTBOX_H
 #define AGS_SHARED_GUI_GUITEXTBOX_H
 
-#include "ags/std/vector.h"
+#include "ags/lib/std/vector.h"
 #include "ags/shared/gui/guiobject.h"
 #include "ags/shared/util/string.h"
 
diff --git a/engines/ags/shared/script/cc_error.cpp b/engines/ags/shared/script/cc_error.cpp
index 9e5736bb81..f404788f6c 100644
--- a/engines/ags/shared/script/cc_error.cpp
+++ b/engines/ags/shared/script/cc_error.cpp
@@ -22,7 +22,7 @@
 
 #include "ags/shared/script/script_common.h"  // current_line
 #include "ags/shared/util/string.h"
-#include "ags/std/utility.h"
+#include "ags/lib/std/utility.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/script/cc_script.h b/engines/ags/shared/script/cc_script.h
index a0852f5851..ad9e440cc6 100644
--- a/engines/ags/shared/script/cc_script.h
+++ b/engines/ags/shared/script/cc_script.h
@@ -30,7 +30,7 @@
 #define AGS_SHARED_SCRIPT_CC_SCRIPT_H
 
 #include "ags/shared/core/types.h"
-#include "ags/std/memory.h"
+#include "ags/lib/std/memory.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/util/bufferedstream.cpp b/engines/ags/shared/util/bufferedstream.cpp
index 69e81b5cbc..63f2bc0990 100644
--- a/engines/ags/shared/util/bufferedstream.cpp
+++ b/engines/ags/shared/util/bufferedstream.cpp
@@ -20,8 +20,8 @@
  *
  */
 
-#include "ags/std/algorithm.h"
-#include "ags/std/memory.h"
+#include "ags/lib/std/algorithm.h"
+#include "ags/lib/std/memory.h"
 #include "ags/shared/util/bufferedstream.h"
 #include "ags/shared/util/stdio_compat.h"
 #include "ags/shared/util/string.h"
diff --git a/engines/ags/shared/util/bufferedstream.h b/engines/ags/shared/util/bufferedstream.h
index ffc16c2de4..debae2eaab 100644
--- a/engines/ags/shared/util/bufferedstream.h
+++ b/engines/ags/shared/util/bufferedstream.h
@@ -23,7 +23,7 @@
 #ifndef AGS_SHARED_UTIL_BUFFEREDSTREAM_H
 #define AGS_SHARED_UTIL_BUFFEREDSTREAM_H
 
-#include "ags/std/vector.h"
+#include "ags/lib/std/vector.h"
 #include "ags/shared/util/filestream.h"
 #include "ags/shared/util/file.h" // TODO: extract filestream mode constants
 
diff --git a/engines/ags/shared/util/error.h b/engines/ags/shared/util/error.h
index 4a983dfea4..370a1a6c28 100644
--- a/engines/ags/shared/util/error.h
+++ b/engines/ags/shared/util/error.h
@@ -30,7 +30,7 @@
 #ifndef AGS_SHARED_UTIL_ERROR_H
 #define AGS_SHARED_UTIL_ERROR_H
 
-#include "ags/std/memory.h"
+#include "ags/lib/std/memory.h"
 #include "ags/shared/util/string.h"
 
 namespace AGS3 {
diff --git a/engines/ags/shared/util/geometry.cpp b/engines/ags/shared/util/geometry.cpp
index 5da09aabd1..8059f9f5bd 100644
--- a/engines/ags/shared/util/geometry.cpp
+++ b/engines/ags/shared/util/geometry.cpp
@@ -21,8 +21,8 @@
  */
 
 #include "ags/shared/util/geometry.h"
-#include "ags/std/algorithm.h"
-#include "ags/std/algorithm.h"
+#include "ags/lib/std/algorithm.h"
+#include "ags/lib/std/algorithm.h"
 //include <cmath>
 
 namespace AGS3 {
diff --git a/engines/ags/shared/util/ini_util.cpp b/engines/ags/shared/util/ini_util.cpp
index e4849740d2..d39d7830c9 100644
--- a/engines/ags/shared/util/ini_util.cpp
+++ b/engines/ags/shared/util/ini_util.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/std/memory.h"
+#include "ags/lib/std/memory.h"
 #include "ags/shared/util/file.h"
 #include "ags/shared/util/ini_util.h"
 #include "ags/shared/util/inifile.h"
diff --git a/engines/ags/shared/util/ini_util.h b/engines/ags/shared/util/ini_util.h
index c3fd2276db..a5e36e859a 100644
--- a/engines/ags/shared/util/ini_util.h
+++ b/engines/ags/shared/util/ini_util.h
@@ -30,7 +30,7 @@
 #ifndef AGS_SHARED_UTIL_INIUTIL_H
 #define AGS_SHARED_UTIL_INIUTIL_H
 
-#include "ags/std/map.h"
+#include "ags/lib/std/map.h"
 #include "ags/shared/util/string.h"
 #include "ags/shared/util/string_types.h"
 
diff --git a/engines/ags/shared/util/inifile.h b/engines/ags/shared/util/inifile.h
index 0008f7b13d..b4f7afa6aa 100644
--- a/engines/ags/shared/util/inifile.h
+++ b/engines/ags/shared/util/inifile.h
@@ -34,8 +34,8 @@
 #define AGS_SHARED_UTIL_INIFILE_H
 
 #include "ags/shared/util/string.h"
-#include "ags/std/utility.h"
-#include "ags/std/list.h"
+#include "ags/lib/std/utility.h"
+#include "ags/lib/std/list.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/util/string.cpp b/engines/ags/shared/util/string.cpp
index 49c5fad5ac..4fa6ea1f69 100644
--- a/engines/ags/shared/util/string.cpp
+++ b/engines/ags/shared/util/string.cpp
@@ -24,7 +24,7 @@
 #include "ags/shared/util/stream.h"
 #include "ags/shared/util/string.h"
 #include "ags/shared/util/string_compat.h"
-#include "ags/std/algorithm.h"
+#include "ags/lib/std/algorithm.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/shared/util/string.h b/engines/ags/shared/util/string.h
index ae9063c1a3..c492112d00 100644
--- a/engines/ags/shared/util/string.h
+++ b/engines/ags/shared/util/string.h
@@ -47,7 +47,7 @@
 #define AGS_SHARED_UTIL_STRING_H
 
 //include <stdarg.h>
-#include "ags/std/vector.h"
+#include "ags/lib/std/vector.h"
 #include "ags/shared/core/platform.h"
 #include "ags/shared/core/types.h"
 #include "ags/shared/debugging/assert.h"
diff --git a/engines/ags/shared/util/string_types.h b/engines/ags/shared/util/string_types.h
index 0e65ce084e..bde5fd750e 100644
--- a/engines/ags/shared/util/string_types.h
+++ b/engines/ags/shared/util/string_types.h
@@ -23,8 +23,8 @@
 #ifndef AGS_SHARED_UTIL_STRINGTYPES_H
 #define AGS_SHARED_UTIL_STRINGTYPES_H
 
-#include "ags/std/map.h"
-#include "ags/std/vector.h"
+#include "ags/lib/std/map.h"
+#include "ags/lib/std/vector.h"
 #include "ags/shared/util/string.h"
 #include "common/hash-str.h"
 


Commit: cb88fc7a924ca9dd6c30d99bbd62051a23926609
    https://github.com/scummvm/scummvm/commit/cb88fc7a924ca9dd6c30d99bbd62051a23926609
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added platform driver

Changed paths:
    engines/ags/engine/platform/linux/acpllnx.cpp
    engines/ags/lib/opengl/opengl.h
    engines/ags/module.mk


diff --git a/engines/ags/engine/platform/linux/acpllnx.cpp b/engines/ags/engine/platform/linux/acpllnx.cpp
index f0279b6602..415dd3dc72 100644
--- a/engines/ags/engine/platform/linux/acpllnx.cpp
+++ b/engines/ags/engine/platform/linux/acpllnx.cpp
@@ -27,17 +27,17 @@
 // ********* LINUX PLACEHOLDER DRIVER *********
 
 //include <stdio.h>
-#include "ags/lib/allegro.h"
 //include <xalleg.h>
-#include "ags/shared/ac/runtime_defines.h"
-#include "ags/shared/gfx/gfxdefines.h"
-#include "ags/shared/platform/base/agsplatformdriver.h"
-#include "ags/shared/plugin/agsplugin.h"
-#include "ags/shared/util/string.h"
 //include <libcda.h>
-
 //include <pwd.h>
 //include <sys/stat.h>
+#include "ags/lib/allegro.h"
+#include "ags/lib/opengl/opengl.h"
+#include "ags/engine/ac/runtime_defines.h"
+#include "ags/engine/gfx/gfxdefines.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
+#include "ags/engine/plugin/agsplugin.h"
+#include "ags/shared/util/string.h"
 
 namespace AGS3 {
 
@@ -46,8 +46,8 @@ using AGS::Shared::String;
 
 // Replace the default Allegro icon. The original defintion is in the
 // Allegro 4.4 source under "src/x/xwin.c".
-#include "ags/shared/icon.xpm"
-void *allegro_icon = icon_xpm;
+//include "ags/shared/icon.xpm"
+//void *allegro_icon = icon_xpm;
 String CommonDataDirectory;
 String UserDataDirectory;
 
@@ -75,7 +75,9 @@ struct AGSLinux : AGSPlatformDriver {
 
 
 int AGSLinux::CDPlayerCommand(int cmdd, int datt) {
-	return cd_player_control(cmdd, datt);
+	warning("CDPlayerCommand(%d,%d)", cmdd, datt);
+	//return cd_player_control(cmdd, datt);
+	return 0;
 }
 
 void AGSLinux::DisplayAlert(const char *text, ...) {
@@ -85,12 +87,13 @@ void AGSLinux::DisplayAlert(const char *text, ...) {
 	vsprintf(displbuf, text, ap);
 	va_end(ap);
 	if (_logToStdErr)
-		fprintf(stderr, "%s\n", displbuf);
+		debug("ERROR: %s\n", displbuf);
 	else
-		fprintf(stdout, "%s\n", displbuf);
+		debug("ERROR: %s\n", displbuf);
 }
 
 size_t BuildXDGPath(char *destPath, size_t destSize) {
+#ifdef TODO
 	// Check to see if XDG_DATA_HOME is set in the enviroment
 	const char *home_dir = getenv("XDG_DATA_HOME");
 	size_t l = 0;
@@ -107,9 +110,12 @@ size_t BuildXDGPath(char *destPath, size_t destSize) {
 			return 0;
 	}
 	return l;
+#endif
+	return 0;
 }
 
 void DetermineDataDirectories() {
+#ifdef TODO
 	if (!UserDataDirectory.IsEmpty())
 		return;
 	char xdg_path[256];
@@ -119,6 +125,7 @@ void DetermineDataDirectories() {
 	mkdir(UserDataDirectory.GetCStr(), 0755);
 	CommonDataDirectory.Format("%s/ags-common", xdg_path);
 	mkdir(CommonDataDirectory.GetCStr(), 0755);
+#endif
 }
 
 const char *AGSLinux::GetAllUsersDataDirectory() {
@@ -162,7 +169,8 @@ eScriptSystemOSID AGSLinux::GetSystemOSID() {
 }
 
 int AGSLinux::InitializeCDPlayer() {
-	return cd_player_init();
+	//return cd_player_init();
+	return 0;
 }
 
 void AGSLinux::PostAllegroExit() {
@@ -174,7 +182,7 @@ void AGSLinux::SetGameWindowIcon() {
 }
 
 void AGSLinux::ShutdownCDPlayer() {
-	cd_exit();
+	//cd_exit();
 }
 
 AGSPlatformDriver *AGSPlatformDriver::GetDriver() {
@@ -184,13 +192,19 @@ AGSPlatformDriver *AGSPlatformDriver::GetDriver() {
 }
 
 bool AGSLinux::LockMouseToWindow() {
+#if 0
 	return XGrabPointer(_xwin.display, _xwin.window, False,
 	                    PointerMotionMask | ButtonPressMask | ButtonReleaseMask,
 	                    GrabModeAsync, GrabModeAsync, _xwin.window, None, CurrentTime) == GrabSuccess;
+#else
+	return false;
+#endif
 }
 
 void AGSLinux::UnlockMouse() {
+#if 0
 	XUngrabPointer(_xwin.display, CurrentTime);
+#endif
 }
 
 void AGSLinux::GetSystemDisplayModes(std::vector<Engine::DisplayMode> &dms) {
diff --git a/engines/ags/lib/opengl/opengl.h b/engines/ags/lib/opengl/opengl.h
index 2525645547..92fb19034f 100644
--- a/engines/ags/lib/opengl/opengl.h
+++ b/engines/ags/lib/opengl/opengl.h
@@ -24,6 +24,7 @@
 #define AGS_LIB_OPENGL_OPENGL_H
 
 #include "common/scummsys.h"
+#include "common/endian.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 59e28d33b6..7a4fbd1a0c 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -269,9 +269,7 @@ MODULE_OBJS = \
     engine/media/audio/soundclip.o \
 	engine/media/video/video.o \
 	engine/platform/base/agsplatformdriver.o \
-	engine/platform/windows/acplwin.o \
-	engine/platform/windows/minidump.o \
-	engine/platform/windows/win_ex_handling.o \
+	engine/platform/linux/acpllnx.o \
 	engine/plugin/agsplugin.o \
 	engine/plugin/pluginobjectreader.o \
 	engine/script/cc_instance.o \


Commit: 2a2f3585ef0a7889c0425251519993d95ff66780
    https://github.com/scummvm/scummvm/commit/2a2f3585ef0a7889c0425251519993d95ff66780
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added lib/hq2x/ folder

Changed paths:
  A engines/ags/lib/hq2x/hq2x3x.cpp
  A engines/ags/lib/hq2x/hq2x3x.h
    engines/ags/module.mk


diff --git a/engines/ags/lib/hq2x/hq2x3x.cpp b/engines/ags/lib/hq2x/hq2x3x.cpp
new file mode 100644
index 0000000000..0129ff67ea
--- /dev/null
+++ b/engines/ags/lib/hq2x/hq2x3x.cpp
@@ -0,0 +1,5278 @@
+/* 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 "ags/shared/core/types.h"
+
+namespace AGS3 {
+
+static int   LUT16to32[65536];
+static int   RGBtoYUV[65536];
+static int   YUV1, YUV2;
+const  int   Ymask = 0x00FF0000;
+const  int   Umask = 0x0000FF00;
+const  int   Vmask = 0x000000FF;
+const  int   trY   = 0x00300000;
+const  int   trU   = 0x00000700;
+const  int   trV   = 0x00000006;
+
+inline void Interp1(unsigned char *pc, int c1, int c2) {
+	*((int *)pc) = (c1 * 3 + c2) >> 2;
+}
+
+inline void Interp2(unsigned char *pc, int c1, int c2, int c3) {
+	*((int *)pc) = (c1 * 2 + c2 + c3) >> 2;
+}
+
+inline void Interp3(unsigned char *pc, int c1, int c2) {
+	//*((int*)pc) = (c1*7+c2)/8;
+
+	*((int *)pc) = ((((c1 & 0x00FF00) * 7 + (c2 & 0x00FF00)) & 0x0007F800) +
+	                (((c1 & 0xFF00FF) * 7 + (c2 & 0xFF00FF)) & 0x07F807F8)) >> 3;
+}
+
+inline void Interp4(unsigned char *pc, int c1, int c2, int c3) {
+	//*((int*)pc) = (c1*2+(c2+c3)*7)/16;
+
+	*((int *)pc) = ((((c1 & 0x00FF00) * 2 + ((c2 & 0x00FF00) + (c3 & 0x00FF00)) * 7) & 0x000FF000) +
+	                (((c1 & 0xFF00FF) * 2 + ((c2 & 0xFF00FF) + (c3 & 0xFF00FF)) * 7) & 0x0FF00FF0)) >> 4;
+}
+
+inline void Interp5(unsigned char *pc, int c1, int c2) {
+	*((int *)pc) = (c1 + c2) >> 1;
+}
+
+inline void Interp6(unsigned char *pc, int c1, int c2, int c3) {
+	//*((int*)pc) = (c1*5+c2*2+c3)/8;
+
+	*((int *)pc) = ((((c1 & 0x00FF00) * 5 + (c2 & 0x00FF00) * 2 + (c3 & 0x00FF00)) & 0x0007F800) +
+	                (((c1 & 0xFF00FF) * 5 + (c2 & 0xFF00FF) * 2 + (c3 & 0xFF00FF)) & 0x07F807F8)) >> 3;
+}
+
+inline void Interp7(unsigned char *pc, int c1, int c2, int c3) {
+	//*((int*)pc) = (c1*6+c2+c3)/8;
+
+	*((int *)pc) = ((((c1 & 0x00FF00) * 6 + (c2 & 0x00FF00) + (c3 & 0x00FF00)) & 0x0007F800) +
+	                (((c1 & 0xFF00FF) * 6 + (c2 & 0xFF00FF) + (c3 & 0xFF00FF)) & 0x07F807F8)) >> 3;
+}
+
+inline void Interp9(unsigned char *pc, int c1, int c2, int c3) {
+	//*((int*)pc) = (c1*2+(c2+c3)*3)/8;
+
+	*((int *)pc) = ((((c1 & 0x00FF00) * 2 + ((c2 & 0x00FF00) + (c3 & 0x00FF00)) * 3) & 0x0007F800) +
+	                (((c1 & 0xFF00FF) * 2 + ((c2 & 0xFF00FF) + (c3 & 0xFF00FF)) * 3) & 0x07F807F8)) >> 3;
+}
+
+inline void Interp10(unsigned char *pc, int c1, int c2, int c3) {
+	//*((int*)pc) = (c1*14+c2+c3)/16;
+
+	*((int *)pc) = ((((c1 & 0x00FF00) * 14 + (c2 & 0x00FF00) + (c3 & 0x00FF00)) & 0x000FF000) +
+	                (((c1 & 0xFF00FF) * 14 + (c2 & 0xFF00FF) + (c3 & 0xFF00FF)) & 0x0FF00FF0)) >> 4;
+}
+
+
+#define PIXEL00_0     *((int*)(pOut)) = c[5];
+#define PIXEL00_10    Interp1(pOut, c[5], c[1]);
+#define PIXEL00_11    Interp1(pOut, c[5], c[4]);
+#define PIXEL00_12    Interp1(pOut, c[5], c[2]);
+#define PIXEL00_20    Interp2(pOut, c[5], c[4], c[2]);
+#define PIXEL00_21    Interp2(pOut, c[5], c[1], c[2]);
+#define PIXEL00_22    Interp2(pOut, c[5], c[1], c[4]);
+#define PIXEL00_60    Interp6(pOut, c[5], c[2], c[4]);
+#define PIXEL00_61    Interp6(pOut, c[5], c[4], c[2]);
+#define PIXEL00_70    Interp7(pOut, c[5], c[4], c[2]);
+#define PIXEL00_90    Interp9(pOut, c[5], c[4], c[2]);
+#define PIXEL00_100   Interp10(pOut, c[5], c[4], c[2]);
+#define PIXEL01_0     *((int*)(pOut+4)) = c[5];
+#define PIXEL01_10    Interp1(pOut+4, c[5], c[3]);
+#define PIXEL01_11    Interp1(pOut+4, c[5], c[2]);
+#define PIXEL01_12    Interp1(pOut+4, c[5], c[6]);
+#define PIXEL01_20    Interp2(pOut+4, c[5], c[2], c[6]);
+#define PIXEL01_21    Interp2(pOut+4, c[5], c[3], c[6]);
+#define PIXEL01_22    Interp2(pOut+4, c[5], c[3], c[2]);
+#define PIXEL01_60    Interp6(pOut+4, c[5], c[6], c[2]);
+#define PIXEL01_61    Interp6(pOut+4, c[5], c[2], c[6]);
+#define PIXEL01_70    Interp7(pOut+4, c[5], c[2], c[6]);
+#define PIXEL01_90    Interp9(pOut+4, c[5], c[2], c[6]);
+#define PIXEL01_100   Interp10(pOut+4, c[5], c[2], c[6]);
+#define PIXEL10_0     *((int*)(pOut+BpL)) = c[5];
+#define PIXEL10_10    Interp1(pOut+BpL, c[5], c[7]);
+#define PIXEL10_11    Interp1(pOut+BpL, c[5], c[8]);
+#define PIXEL10_12    Interp1(pOut+BpL, c[5], c[4]);
+#define PIXEL10_20    Interp2(pOut+BpL, c[5], c[8], c[4]);
+#define PIXEL10_21    Interp2(pOut+BpL, c[5], c[7], c[4]);
+#define PIXEL10_22    Interp2(pOut+BpL, c[5], c[7], c[8]);
+#define PIXEL10_60    Interp6(pOut+BpL, c[5], c[4], c[8]);
+#define PIXEL10_61    Interp6(pOut+BpL, c[5], c[8], c[4]);
+#define PIXEL10_70    Interp7(pOut+BpL, c[5], c[8], c[4]);
+#define PIXEL10_90    Interp9(pOut+BpL, c[5], c[8], c[4]);
+#define PIXEL10_100   Interp10(pOut+BpL, c[5], c[8], c[4]);
+#define PIXEL11_0     *((int*)(pOut+BpL+4)) = c[5];
+#define PIXEL11_10    Interp1(pOut+BpL+4, c[5], c[9]);
+#define PIXEL11_11    Interp1(pOut+BpL+4, c[5], c[6]);
+#define PIXEL11_12    Interp1(pOut+BpL+4, c[5], c[8]);
+#define PIXEL11_20    Interp2(pOut+BpL+4, c[5], c[6], c[8]);
+#define PIXEL11_21    Interp2(pOut+BpL+4, c[5], c[9], c[8]);
+#define PIXEL11_22    Interp2(pOut+BpL+4, c[5], c[9], c[6]);
+#define PIXEL11_60    Interp6(pOut+BpL+4, c[5], c[8], c[6]);
+#define PIXEL11_61    Interp6(pOut+BpL+4, c[5], c[6], c[8]);
+#define PIXEL11_70    Interp7(pOut+BpL+4, c[5], c[6], c[8]);
+#define PIXEL11_90    Interp9(pOut+BpL+4, c[5], c[6], c[8]);
+#define PIXEL11_100   Interp10(pOut+BpL+4, c[5], c[6], c[8]);
+
+
+
+inline bool Diff(unsigned int w1, unsigned int w2) {
+	YUV1 = RGBtoYUV[w1];
+	YUV2 = RGBtoYUV[w2];
+	return ((abs((YUV1 & Ymask) - (YUV2 & Ymask)) > trY) ||
+	        (abs((YUV1 & Umask) - (YUV2 & Umask)) > trU) ||
+	        (abs((YUV1 & Vmask) - (YUV2 & Vmask)) > trV));
+}
+
+#define INPUT_IMAGE_PIXEL_SIZE uint32_t
+#define INPUT_IMAGE_PIXEL_SIZE_IN_BYTES sizeof(INPUT_IMAGE_PIXEL_SIZE)
+
+void hq2x_32(unsigned char *pIn, unsigned char *pOut, int Xres, int Yres, int BpL) {
+	int  i, j, k;
+	int  prevline, nextline;
+	int  w[10];
+	int  c[10];
+
+	//   +----+----+----+
+	//   |    |    |    |
+	//   | w1 | w2 | w3 |
+	//   +----+----+----+
+	//   |    |    |    |
+	//   | w4 | w5 | w6 |
+	//   +----+----+----+
+	//   |    |    |    |
+	//   | w7 | w8 | w9 |
+	//   +----+----+----+
+
+	for (j = 0; j < Yres; j++) {
+		if (j > 0)      prevline = -Xres * 4;
+		else prevline = 0;
+		if (j < Yres - 1) nextline =  Xres * 4;
+		else nextline = 0;
+
+		for (i = 0; i < Xres; i++) {
+			w[2] = *((INPUT_IMAGE_PIXEL_SIZE *)(pIn + prevline));
+			w[5] = *((INPUT_IMAGE_PIXEL_SIZE *)pIn);
+			w[8] = *((INPUT_IMAGE_PIXEL_SIZE *)(pIn + nextline));
+
+			if (i > 0) {
+				w[1] = *((INPUT_IMAGE_PIXEL_SIZE *)(pIn + prevline - INPUT_IMAGE_PIXEL_SIZE_IN_BYTES));
+				w[4] = *((INPUT_IMAGE_PIXEL_SIZE *)(pIn - INPUT_IMAGE_PIXEL_SIZE_IN_BYTES));
+				w[7] = *((INPUT_IMAGE_PIXEL_SIZE *)(pIn + nextline - INPUT_IMAGE_PIXEL_SIZE_IN_BYTES));
+			} else {
+				w[1] = w[2];
+				w[4] = w[5];
+				w[7] = w[8];
+			}
+
+			if (i < Xres - 1) {
+				w[3] = *((INPUT_IMAGE_PIXEL_SIZE *)(pIn + prevline + INPUT_IMAGE_PIXEL_SIZE_IN_BYTES));
+				w[6] = *((INPUT_IMAGE_PIXEL_SIZE *)(pIn + INPUT_IMAGE_PIXEL_SIZE_IN_BYTES));
+				w[9] = *((INPUT_IMAGE_PIXEL_SIZE *)(pIn + nextline + INPUT_IMAGE_PIXEL_SIZE_IN_BYTES));
+			} else {
+				w[3] = w[2];
+				w[6] = w[5];
+				w[9] = w[8];
+			}
+
+			// convert down to 16-bit
+			for (k = 1; k <= 9; k++) {
+				w[k] = (((((w[k] >> 16) & 0x00ff) / 8) << 11) +
+				        ((((w[k] >> 8) & 0x00ff) / 4) << 5) +
+				        ((w[k]  & 0x00ff) / 8)) & 0x000ffff;
+			}
+
+			int pattern = 0;
+			int flag = 1;
+
+			YUV1 = RGBtoYUV[w[5]];
+
+			for (k = 1; k <= 9; k++) {
+				if (k == 5) continue;
+
+				if (w[k] != w[5]) {
+					YUV2 = RGBtoYUV[w[k]];
+					if ((abs((YUV1 & Ymask) - (YUV2 & Ymask)) > trY) ||
+					        (abs((YUV1 & Umask) - (YUV2 & Umask)) > trU) ||
+					        (abs((YUV1 & Vmask) - (YUV2 & Vmask)) > trV))
+						pattern |= flag;
+				}
+				flag <<= 1;
+			}
+
+			for (k = 1; k <= 9; k++)
+				c[k] = LUT16to32[w[k]];
+
+			switch (pattern) {
+			case 0:
+			case 1:
+			case 4:
+			case 32:
+			case 128:
+			case 5:
+			case 132:
+			case 160:
+			case 33:
+			case 129:
+			case 36:
+			case 133:
+			case 164:
+			case 161:
+			case 37:
+			case 165: {
+				PIXEL00_20
+				PIXEL01_20
+				PIXEL10_20
+				PIXEL11_20
+				break;
+			}
+			case 2:
+			case 34:
+			case 130:
+			case 162: {
+				PIXEL00_22
+				PIXEL01_21
+				PIXEL10_20
+				PIXEL11_20
+				break;
+			}
+			case 16:
+			case 17:
+			case 48:
+			case 49: {
+				PIXEL00_20
+				PIXEL01_22
+				PIXEL10_20
+				PIXEL11_21
+				break;
+			}
+			case 64:
+			case 65:
+			case 68:
+			case 69: {
+				PIXEL00_20
+				PIXEL01_20
+				PIXEL10_21
+				PIXEL11_22
+				break;
+			}
+			case 8:
+			case 12:
+			case 136:
+			case 140: {
+				PIXEL00_21
+				PIXEL01_20
+				PIXEL10_22
+				PIXEL11_20
+				break;
+			}
+			case 3:
+			case 35:
+			case 131:
+			case 163: {
+				PIXEL00_11
+				PIXEL01_21
+				PIXEL10_20
+				PIXEL11_20
+				break;
+			}
+			case 6:
+			case 38:
+			case 134:
+			case 166: {
+				PIXEL00_22
+				PIXEL01_12
+				PIXEL10_20
+				PIXEL11_20
+				break;
+			}
+			case 20:
+			case 21:
+			case 52:
+			case 53: {
+				PIXEL00_20
+				PIXEL01_11
+				PIXEL10_20
+				PIXEL11_21
+				break;
+			}
+			case 144:
+			case 145:
+			case 176:
+			case 177: {
+				PIXEL00_20
+				PIXEL01_22
+				PIXEL10_20
+				PIXEL11_12
+				break;
+			}
+			case 192:
+			case 193:
+			case 196:
+			case 197: {
+				PIXEL00_20
+				PIXEL01_20
+				PIXEL10_21
+				PIXEL11_11
+				break;
+			}
+			case 96:
+			case 97:
+			case 100:
+			case 101: {
+				PIXEL00_20
+				PIXEL01_20
+				PIXEL10_12
+				PIXEL11_22
+				break;
+			}
+			case 40:
+			case 44:
+			case 168:
+			case 172: {
+				PIXEL00_21
+				PIXEL01_20
+				PIXEL10_11
+				PIXEL11_20
+				break;
+			}
+			case 9:
+			case 13:
+			case 137:
+			case 141: {
+				PIXEL00_12
+				PIXEL01_20
+				PIXEL10_22
+				PIXEL11_20
+				break;
+			}
+			case 18:
+			case 50: {
+				PIXEL00_22
+				if (Diff(w[2], w[6])) {
+					PIXEL01_10
+				} else {
+					PIXEL01_20
+				}
+				PIXEL10_20
+				PIXEL11_21
+				break;
+			}
+			case 80:
+			case 81: {
+				PIXEL00_20
+				PIXEL01_22
+				PIXEL10_21
+				if (Diff(w[6], w[8])) {
+					PIXEL11_10
+				} else {
+					PIXEL11_20
+				}
+				break;
+			}
+			case 72:
+			case 76: {
+				PIXEL00_21
+				PIXEL01_20
+				if (Diff(w[8], w[4])) {
+					PIXEL10_10
+				} else {
+					PIXEL10_20
+				}
+				PIXEL11_22
+				break;
+			}
+			case 10:
+			case 138: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_10
+				} else {
+					PIXEL00_20
+				}
+				PIXEL01_21
+				PIXEL10_22
+				PIXEL11_20
+				break;
+			}
+			case 66: {
+				PIXEL00_22
+				PIXEL01_21
+				PIXEL10_21
+				PIXEL11_22
+				break;
+			}
+			case 24: {
+				PIXEL00_21
+				PIXEL01_22
+				PIXEL10_22
+				PIXEL11_21
+				break;
+			}
+			case 7:
+			case 39:
+			case 135: {
+				PIXEL00_11
+				PIXEL01_12
+				PIXEL10_20
+				PIXEL11_20
+				break;
+			}
+			case 148:
+			case 149:
+			case 180: {
+				PIXEL00_20
+				PIXEL01_11
+				PIXEL10_20
+				PIXEL11_12
+				break;
+			}
+			case 224:
+			case 228:
+			case 225: {
+				PIXEL00_20
+				PIXEL01_20
+				PIXEL10_12
+				PIXEL11_11
+				break;
+			}
+			case 41:
+			case 169:
+			case 45: {
+				PIXEL00_12
+				PIXEL01_20
+				PIXEL10_11
+				PIXEL11_20
+				break;
+			}
+			case 22:
+			case 54: {
+				PIXEL00_22
+				if (Diff(w[2], w[6])) {
+					PIXEL01_0
+				} else {
+					PIXEL01_20
+				}
+				PIXEL10_20
+				PIXEL11_21
+				break;
+			}
+			case 208:
+			case 209: {
+				PIXEL00_20
+				PIXEL01_22
+				PIXEL10_21
+				if (Diff(w[6], w[8])) {
+					PIXEL11_0
+				} else {
+					PIXEL11_20
+				}
+				break;
+			}
+			case 104:
+			case 108: {
+				PIXEL00_21
+				PIXEL01_20
+				if (Diff(w[8], w[4])) {
+					PIXEL10_0
+				} else {
+					PIXEL10_20
+				}
+				PIXEL11_22
+				break;
+			}
+			case 11:
+			case 139: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+				} else {
+					PIXEL00_20
+				}
+				PIXEL01_21
+				PIXEL10_22
+				PIXEL11_20
+				break;
+			}
+			case 19:
+			case 51: {
+				if (Diff(w[2], w[6])) {
+					PIXEL00_11
+					PIXEL01_10
+				} else {
+					PIXEL00_60
+					PIXEL01_90
+				}
+				PIXEL10_20
+				PIXEL11_21
+				break;
+			}
+			case 146:
+			case 178: {
+				PIXEL00_22
+				if (Diff(w[2], w[6])) {
+					PIXEL01_10
+					PIXEL11_12
+				} else {
+					PIXEL01_90
+					PIXEL11_61
+				}
+				PIXEL10_20
+				break;
+			}
+			case 84:
+			case 85: {
+				PIXEL00_20
+				if (Diff(w[6], w[8])) {
+					PIXEL01_11
+					PIXEL11_10
+				} else {
+					PIXEL01_60
+					PIXEL11_90
+				}
+				PIXEL10_21
+				break;
+			}
+			case 112:
+			case 113: {
+				PIXEL00_20
+				PIXEL01_22
+				if (Diff(w[6], w[8])) {
+					PIXEL10_12
+					PIXEL11_10
+				} else {
+					PIXEL10_61
+					PIXEL11_90
+				}
+				break;
+			}
+			case 200:
+			case 204: {
+				PIXEL00_21
+				PIXEL01_20
+				if (Diff(w[8], w[4])) {
+					PIXEL10_10
+					PIXEL11_11
+				} else {
+					PIXEL10_90
+					PIXEL11_60
+				}
+				break;
+			}
+			case 73:
+			case 77: {
+				if (Diff(w[8], w[4])) {
+					PIXEL00_12
+					PIXEL10_10
+				} else {
+					PIXEL00_61
+					PIXEL10_90
+				}
+				PIXEL01_20
+				PIXEL11_22
+				break;
+			}
+			case 42:
+			case 170: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_10
+					PIXEL10_11
+				} else {
+					PIXEL00_90
+					PIXEL10_60
+				}
+				PIXEL01_21
+				PIXEL11_20
+				break;
+			}
+			case 14:
+			case 142: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_10
+					PIXEL01_12
+				} else {
+					PIXEL00_90
+					PIXEL01_61
+				}
+				PIXEL10_22
+				PIXEL11_20
+				break;
+			}
+			case 67: {
+				PIXEL00_11
+				PIXEL01_21
+				PIXEL10_21
+				PIXEL11_22
+				break;
+			}
+			case 70: {
+				PIXEL00_22
+				PIXEL01_12
+				PIXEL10_21
+				PIXEL11_22
+				break;
+			}
+			case 28: {
+				PIXEL00_21
+				PIXEL01_11
+				PIXEL10_22
+				PIXEL11_21
+				break;
+			}
+			case 152: {
+				PIXEL00_21
+				PIXEL01_22
+				PIXEL10_22
+				PIXEL11_12
+				break;
+			}
+			case 194: {
+				PIXEL00_22
+				PIXEL01_21
+				PIXEL10_21
+				PIXEL11_11
+				break;
+			}
+			case 98: {
+				PIXEL00_22
+				PIXEL01_21
+				PIXEL10_12
+				PIXEL11_22
+				break;
+			}
+			case 56: {
+				PIXEL00_21
+				PIXEL01_22
+				PIXEL10_11
+				PIXEL11_21
+				break;
+			}
+			case 25: {
+				PIXEL00_12
+				PIXEL01_22
+				PIXEL10_22
+				PIXEL11_21
+				break;
+			}
+			case 26:
+			case 31: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+				} else {
+					PIXEL00_20
+				}
+				if (Diff(w[2], w[6])) {
+					PIXEL01_0
+				} else {
+					PIXEL01_20
+				}
+				PIXEL10_22
+				PIXEL11_21
+				break;
+			}
+			case 82:
+			case 214: {
+				PIXEL00_22
+				if (Diff(w[2], w[6])) {
+					PIXEL01_0
+				} else {
+					PIXEL01_20
+				}
+				PIXEL10_21
+				if (Diff(w[6], w[8])) {
+					PIXEL11_0
+				} else {
+					PIXEL11_20
+				}
+				break;
+			}
+			case 88:
+			case 248: {
+				PIXEL00_21
+				PIXEL01_22
+				if (Diff(w[8], w[4])) {
+					PIXEL10_0
+				} else {
+					PIXEL10_20
+				}
+				if (Diff(w[6], w[8])) {
+					PIXEL11_0
+				} else {
+					PIXEL11_20
+				}
+				break;
+			}
+			case 74:
+			case 107: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+				} else {
+					PIXEL00_20
+				}
+				PIXEL01_21
+				if (Diff(w[8], w[4])) {
+					PIXEL10_0
+				} else {
+					PIXEL10_20
+				}
+				PIXEL11_22
+				break;
+			}
+			case 27: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+				} else {
+					PIXEL00_20
+				}
+				PIXEL01_10
+				PIXEL10_22
+				PIXEL11_21
+				break;
+			}
+			case 86: {
+				PIXEL00_22
+				if (Diff(w[2], w[6])) {
+					PIXEL01_0
+				} else {
+					PIXEL01_20
+				}
+				PIXEL10_21
+				PIXEL11_10
+				break;
+			}
+			case 216: {
+				PIXEL00_21
+				PIXEL01_22
+				PIXEL10_10
+				if (Diff(w[6], w[8])) {
+					PIXEL11_0
+				} else {
+					PIXEL11_20
+				}
+				break;
+			}
+			case 106: {
+				PIXEL00_10
+				PIXEL01_21
+				if (Diff(w[8], w[4])) {
+					PIXEL10_0
+				} else {
+					PIXEL10_20
+				}
+				PIXEL11_22
+				break;
+			}
+			case 30: {
+				PIXEL00_10
+				if (Diff(w[2], w[6])) {
+					PIXEL01_0
+				} else {
+					PIXEL01_20
+				}
+				PIXEL10_22
+				PIXEL11_21
+				break;
+			}
+			case 210: {
+				PIXEL00_22
+				PIXEL01_10
+				PIXEL10_21
+				if (Diff(w[6], w[8])) {
+					PIXEL11_0
+				} else {
+					PIXEL11_20
+				}
+				break;
+			}
+			case 120: {
+				PIXEL00_21
+				PIXEL01_22
+				if (Diff(w[8], w[4])) {
+					PIXEL10_0
+				} else {
+					PIXEL10_20
+				}
+				PIXEL11_10
+				break;
+			}
+			case 75: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+				} else {
+					PIXEL00_20
+				}
+				PIXEL01_21
+				PIXEL10_10
+				PIXEL11_22
+				break;
+			}
+			case 29: {
+				PIXEL00_12
+				PIXEL01_11
+				PIXEL10_22
+				PIXEL11_21
+				break;
+			}
+			case 198: {
+				PIXEL00_22
+				PIXEL01_12
+				PIXEL10_21
+				PIXEL11_11
+				break;
+			}
+			case 184: {
+				PIXEL00_21
+				PIXEL01_22
+				PIXEL10_11
+				PIXEL11_12
+				break;
+			}
+			case 99: {
+				PIXEL00_11
+				PIXEL01_21
+				PIXEL10_12
+				PIXEL11_22
+				break;
+			}
+			case 57: {
+				PIXEL00_12
+				PIXEL01_22
+				PIXEL10_11
+				PIXEL11_21
+				break;
+			}
+			case 71: {
+				PIXEL00_11
+				PIXEL01_12
+				PIXEL10_21
+				PIXEL11_22
+				break;
+			}
+			case 156: {
+				PIXEL00_21
+				PIXEL01_11
+				PIXEL10_22
+				PIXEL11_12
+				break;
+			}
+			case 226: {
+				PIXEL00_22
+				PIXEL01_21
+				PIXEL10_12
+				PIXEL11_11
+				break;
+			}
+			case 60: {
+				PIXEL00_21
+				PIXEL01_11
+				PIXEL10_11
+				PIXEL11_21
+				break;
+			}
+			case 195: {
+				PIXEL00_11
+				PIXEL01_21
+				PIXEL10_21
+				PIXEL11_11
+				break;
+			}
+			case 102: {
+				PIXEL00_22
+				PIXEL01_12
+				PIXEL10_12
+				PIXEL11_22
+				break;
+			}
+			case 153: {
+				PIXEL00_12
+				PIXEL01_22
+				PIXEL10_22
+				PIXEL11_12
+				break;
+			}
+			case 58: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_10
+				} else {
+					PIXEL00_70
+				}
+				if (Diff(w[2], w[6])) {
+					PIXEL01_10
+				} else {
+					PIXEL01_70
+				}
+				PIXEL10_11
+				PIXEL11_21
+				break;
+			}
+			case 83: {
+				PIXEL00_11
+				if (Diff(w[2], w[6])) {
+					PIXEL01_10
+				} else {
+					PIXEL01_70
+				}
+				PIXEL10_21
+				if (Diff(w[6], w[8])) {
+					PIXEL11_10
+				} else {
+					PIXEL11_70
+				}
+				break;
+			}
+			case 92: {
+				PIXEL00_21
+				PIXEL01_11
+				if (Diff(w[8], w[4])) {
+					PIXEL10_10
+				} else {
+					PIXEL10_70
+				}
+				if (Diff(w[6], w[8])) {
+					PIXEL11_10
+				} else {
+					PIXEL11_70
+				}
+				break;
+			}
+			case 202: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_10
+				} else {
+					PIXEL00_70
+				}
+				PIXEL01_21
+				if (Diff(w[8], w[4])) {
+					PIXEL10_10
+				} else {
+					PIXEL10_70
+				}
+				PIXEL11_11
+				break;
+			}
+			case 78: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_10
+				} else {
+					PIXEL00_70
+				}
+				PIXEL01_12
+				if (Diff(w[8], w[4])) {
+					PIXEL10_10
+				} else {
+					PIXEL10_70
+				}
+				PIXEL11_22
+				break;
+			}
+			case 154: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_10
+				} else {
+					PIXEL00_70
+				}
+				if (Diff(w[2], w[6])) {
+					PIXEL01_10
+				} else {
+					PIXEL01_70
+				}
+				PIXEL10_22
+				PIXEL11_12
+				break;
+			}
+			case 114: {
+				PIXEL00_22
+				if (Diff(w[2], w[6])) {
+					PIXEL01_10
+				} else {
+					PIXEL01_70
+				}
+				PIXEL10_12
+				if (Diff(w[6], w[8])) {
+					PIXEL11_10
+				} else {
+					PIXEL11_70
+				}
+				break;
+			}
+			case 89: {
+				PIXEL00_12
+				PIXEL01_22
+				if (Diff(w[8], w[4])) {
+					PIXEL10_10
+				} else {
+					PIXEL10_70
+				}
+				if (Diff(w[6], w[8])) {
+					PIXEL11_10
+				} else {
+					PIXEL11_70
+				}
+				break;
+			}
+			case 90: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_10
+				} else {
+					PIXEL00_70
+				}
+				if (Diff(w[2], w[6])) {
+					PIXEL01_10
+				} else {
+					PIXEL01_70
+				}
+				if (Diff(w[8], w[4])) {
+					PIXEL10_10
+				} else {
+					PIXEL10_70
+				}
+				if (Diff(w[6], w[8])) {
+					PIXEL11_10
+				} else {
+					PIXEL11_70
+				}
+				break;
+			}
+			case 55:
+			case 23: {
+				if (Diff(w[2], w[6])) {
+					PIXEL00_11
+					PIXEL01_0
+				} else {
+					PIXEL00_60
+					PIXEL01_90
+				}
+				PIXEL10_20
+				PIXEL11_21
+				break;
+			}
+			case 182:
+			case 150: {
+				PIXEL00_22
+				if (Diff(w[2], w[6])) {
+					PIXEL01_0
+					PIXEL11_12
+				} else {
+					PIXEL01_90
+					PIXEL11_61
+				}
+				PIXEL10_20
+				break;
+			}
+			case 213:
+			case 212: {
+				PIXEL00_20
+				if (Diff(w[6], w[8])) {
+					PIXEL01_11
+					PIXEL11_0
+				} else {
+					PIXEL01_60
+					PIXEL11_90
+				}
+				PIXEL10_21
+				break;
+			}
+			case 241:
+			case 240: {
+				PIXEL00_20
+				PIXEL01_22
+				if (Diff(w[6], w[8])) {
+					PIXEL10_12
+					PIXEL11_0
+				} else {
+					PIXEL10_61
+					PIXEL11_90
+				}
+				break;
+			}
+			case 236:
+			case 232: {
+				PIXEL00_21
+				PIXEL01_20
+				if (Diff(w[8], w[4])) {
+					PIXEL10_0
+					PIXEL11_11
+				} else {
+					PIXEL10_90
+					PIXEL11_60
+				}
+				break;
+			}
+			case 109:
+			case 105: {
+				if (Diff(w[8], w[4])) {
+					PIXEL00_12
+					PIXEL10_0
+				} else {
+					PIXEL00_61
+					PIXEL10_90
+				}
+				PIXEL01_20
+				PIXEL11_22
+				break;
+			}
+			case 171:
+			case 43: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+					PIXEL10_11
+				} else {
+					PIXEL00_90
+					PIXEL10_60
+				}
+				PIXEL01_21
+				PIXEL11_20
+				break;
+			}
+			case 143:
+			case 15: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+					PIXEL01_12
+				} else {
+					PIXEL00_90
+					PIXEL01_61
+				}
+				PIXEL10_22
+				PIXEL11_20
+				break;
+			}
+			case 124: {
+				PIXEL00_21
+				PIXEL01_11
+				if (Diff(w[8], w[4])) {
+					PIXEL10_0
+				} else {
+					PIXEL10_20
+				}
+				PIXEL11_10
+				break;
+			}
+			case 203: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+				} else {
+					PIXEL00_20
+				}
+				PIXEL01_21
+				PIXEL10_10
+				PIXEL11_11
+				break;
+			}
+			case 62: {
+				PIXEL00_10
+				if (Diff(w[2], w[6])) {
+					PIXEL01_0
+				} else {
+					PIXEL01_20
+				}
+				PIXEL10_11
+				PIXEL11_21
+				break;
+			}
+			case 211: {
+				PIXEL00_11
+				PIXEL01_10
+				PIXEL10_21
+				if (Diff(w[6], w[8])) {
+					PIXEL11_0
+				} else {
+					PIXEL11_20
+				}
+				break;
+			}
+			case 118: {
+				PIXEL00_22
+				if (Diff(w[2], w[6])) {
+					PIXEL01_0
+				} else {
+					PIXEL01_20
+				}
+				PIXEL10_12
+				PIXEL11_10
+				break;
+			}
+			case 217: {
+				PIXEL00_12
+				PIXEL01_22
+				PIXEL10_10
+				if (Diff(w[6], w[8])) {
+					PIXEL11_0
+				} else {
+					PIXEL11_20
+				}
+				break;
+			}
+			case 110: {
+				PIXEL00_10
+				PIXEL01_12
+				if (Diff(w[8], w[4])) {
+					PIXEL10_0
+				} else {
+					PIXEL10_20
+				}
+				PIXEL11_22
+				break;
+			}
+			case 155: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+				} else {
+					PIXEL00_20
+				}
+				PIXEL01_10
+				PIXEL10_22
+				PIXEL11_12
+				break;
+			}
+			case 188: {
+				PIXEL00_21
+				PIXEL01_11
+				PIXEL10_11
+				PIXEL11_12
+				break;
+			}
+			case 185: {
+				PIXEL00_12
+				PIXEL01_22
+				PIXEL10_11
+				PIXEL11_12
+				break;
+			}
+			case 61: {
+				PIXEL00_12
+				PIXEL01_11
+				PIXEL10_11
+				PIXEL11_21
+				break;
+			}
+			case 157: {
+				PIXEL00_12
+				PIXEL01_11
+				PIXEL10_22
+				PIXEL11_12
+				break;
+			}
+			case 103: {
+				PIXEL00_11
+				PIXEL01_12
+				PIXEL10_12
+				PIXEL11_22
+				break;
+			}
+			case 227: {
+				PIXEL00_11
+				PIXEL01_21
+				PIXEL10_12
+				PIXEL11_11
+				break;
+			}
+			case 230: {
+				PIXEL00_22
+				PIXEL01_12
+				PIXEL10_12
+				PIXEL11_11
+				break;
+			}
+			case 199: {
+				PIXEL00_11
+				PIXEL01_12
+				PIXEL10_21
+				PIXEL11_11
+				break;
+			}
+			case 220: {
+				PIXEL00_21
+				PIXEL01_11
+				if (Diff(w[8], w[4])) {
+					PIXEL10_10
+				} else {
+					PIXEL10_70
+				}
+				if (Diff(w[6], w[8])) {
+					PIXEL11_0
+				} else {
+					PIXEL11_20
+				}
+				break;
+			}
+			case 158: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_10
+				} else {
+					PIXEL00_70
+				}
+				if (Diff(w[2], w[6])) {
+					PIXEL01_0
+				} else {
+					PIXEL01_20
+				}
+				PIXEL10_22
+				PIXEL11_12
+				break;
+			}
+			case 234: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_10
+				} else {
+					PIXEL00_70
+				}
+				PIXEL01_21
+				if (Diff(w[8], w[4])) {
+					PIXEL10_0
+				} else {
+					PIXEL10_20
+				}
+				PIXEL11_11
+				break;
+			}
+			case 242: {
+				PIXEL00_22
+				if (Diff(w[2], w[6])) {
+					PIXEL01_10
+				} else {
+					PIXEL01_70
+				}
+				PIXEL10_12
+				if (Diff(w[6], w[8])) {
+					PIXEL11_0
+				} else {
+					PIXEL11_20
+				}
+				break;
+			}
+			case 59: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+				} else {
+					PIXEL00_20
+				}
+				if (Diff(w[2], w[6])) {
+					PIXEL01_10
+				} else {
+					PIXEL01_70
+				}
+				PIXEL10_11
+				PIXEL11_21
+				break;
+			}
+			case 121: {
+				PIXEL00_12
+				PIXEL01_22
+				if (Diff(w[8], w[4])) {
+					PIXEL10_0
+				} else {
+					PIXEL10_20
+				}
+				if (Diff(w[6], w[8])) {
+					PIXEL11_10
+				} else {
+					PIXEL11_70
+				}
+				break;
+			}
+			case 87: {
+				PIXEL00_11
+				if (Diff(w[2], w[6])) {
+					PIXEL01_0
+				} else {
+					PIXEL01_20
+				}
+				PIXEL10_21
+				if (Diff(w[6], w[8])) {
+					PIXEL11_10
+				} else {
+					PIXEL11_70
+				}
+				break;
+			}
+			case 79: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+				} else {
+					PIXEL00_20
+				}
+				PIXEL01_12
+				if (Diff(w[8], w[4])) {
+					PIXEL10_10
+				} else {
+					PIXEL10_70
+				}
+				PIXEL11_22
+				break;
+			}
+			case 122: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_10
+				} else {
+					PIXEL00_70
+				}
+				if (Diff(w[2], w[6])) {
+					PIXEL01_10
+				} else {
+					PIXEL01_70
+				}
+				if (Diff(w[8], w[4])) {
+					PIXEL10_0
+				} else {
+					PIXEL10_20
+				}
+				if (Diff(w[6], w[8])) {
+					PIXEL11_10
+				} else {
+					PIXEL11_70
+				}
+				break;
+			}
+			case 94: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_10
+				} else {
+					PIXEL00_70
+				}
+				if (Diff(w[2], w[6])) {
+					PIXEL01_0
+				} else {
+					PIXEL01_20
+				}
+				if (Diff(w[8], w[4])) {
+					PIXEL10_10
+				} else {
+					PIXEL10_70
+				}
+				if (Diff(w[6], w[8])) {
+					PIXEL11_10
+				} else {
+					PIXEL11_70
+				}
+				break;
+			}
+			case 218: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_10
+				} else {
+					PIXEL00_70
+				}
+				if (Diff(w[2], w[6])) {
+					PIXEL01_10
+				} else {
+					PIXEL01_70
+				}
+				if (Diff(w[8], w[4])) {
+					PIXEL10_10
+				} else {
+					PIXEL10_70
+				}
+				if (Diff(w[6], w[8])) {
+					PIXEL11_0
+				} else {
+					PIXEL11_20
+				}
+				break;
+			}
+			case 91: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+				} else {
+					PIXEL00_20
+				}
+				if (Diff(w[2], w[6])) {
+					PIXEL01_10
+				} else {
+					PIXEL01_70
+				}
+				if (Diff(w[8], w[4])) {
+					PIXEL10_10
+				} else {
+					PIXEL10_70
+				}
+				if (Diff(w[6], w[8])) {
+					PIXEL11_10
+				} else {
+					PIXEL11_70
+				}
+				break;
+			}
+			case 229: {
+				PIXEL00_20
+				PIXEL01_20
+				PIXEL10_12
+				PIXEL11_11
+				break;
+			}
+			case 167: {
+				PIXEL00_11
+				PIXEL01_12
+				PIXEL10_20
+				PIXEL11_20
+				break;
+			}
+			case 173: {
+				PIXEL00_12
+				PIXEL01_20
+				PIXEL10_11
+				PIXEL11_20
+				break;
+			}
+			case 181: {
+				PIXEL00_20
+				PIXEL01_11
+				PIXEL10_20
+				PIXEL11_12
+				break;
+			}
+			case 186: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_10
+				} else {
+					PIXEL00_70
+				}
+				if (Diff(w[2], w[6])) {
+					PIXEL01_10
+				} else {
+					PIXEL01_70
+				}
+				PIXEL10_11
+				PIXEL11_12
+				break;
+			}
+			case 115: {
+				PIXEL00_11
+				if (Diff(w[2], w[6])) {
+					PIXEL01_10
+				} else {
+					PIXEL01_70
+				}
+				PIXEL10_12
+				if (Diff(w[6], w[8])) {
+					PIXEL11_10
+				} else {
+					PIXEL11_70
+				}
+				break;
+			}
+			case 93: {
+				PIXEL00_12
+				PIXEL01_11
+				if (Diff(w[8], w[4])) {
+					PIXEL10_10
+				} else {
+					PIXEL10_70
+				}
+				if (Diff(w[6], w[8])) {
+					PIXEL11_10
+				} else {
+					PIXEL11_70
+				}
+				break;
+			}
+			case 206: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_10
+				} else {
+					PIXEL00_70
+				}
+				PIXEL01_12
+				if (Diff(w[8], w[4])) {
+					PIXEL10_10
+				} else {
+					PIXEL10_70
+				}
+				PIXEL11_11
+				break;
+			}
+			case 205:
+			case 201: {
+				PIXEL00_12
+				PIXEL01_20
+				if (Diff(w[8], w[4])) {
+					PIXEL10_10
+				} else {
+					PIXEL10_70
+				}
+				PIXEL11_11
+				break;
+			}
+			case 174:
+			case 46: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_10
+				} else {
+					PIXEL00_70
+				}
+				PIXEL01_12
+				PIXEL10_11
+				PIXEL11_20
+				break;
+			}
+			case 179:
+			case 147: {
+				PIXEL00_11
+				if (Diff(w[2], w[6])) {
+					PIXEL01_10
+				} else {
+					PIXEL01_70
+				}
+				PIXEL10_20
+				PIXEL11_12
+				break;
+			}
+			case 117:
+			case 116: {
+				PIXEL00_20
+				PIXEL01_11
+				PIXEL10_12
+				if (Diff(w[6], w[8])) {
+					PIXEL11_10
+				} else {
+					PIXEL11_70
+				}
+				break;
+			}
+			case 189: {
+				PIXEL00_12
+				PIXEL01_11
+				PIXEL10_11
+				PIXEL11_12
+				break;
+			}
+			case 231: {
+				PIXEL00_11
+				PIXEL01_12
+				PIXEL10_12
+				PIXEL11_11
+				break;
+			}
+			case 126: {
+				PIXEL00_10
+				if (Diff(w[2], w[6])) {
+					PIXEL01_0
+				} else {
+					PIXEL01_20
+				}
+				if (Diff(w[8], w[4])) {
+					PIXEL10_0
+				} else {
+					PIXEL10_20
+				}
+				PIXEL11_10
+				break;
+			}
+			case 219: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+				} else {
+					PIXEL00_20
+				}
+				PIXEL01_10
+				PIXEL10_10
+				if (Diff(w[6], w[8])) {
+					PIXEL11_0
+				} else {
+					PIXEL11_20
+				}
+				break;
+			}
+			case 125: {
+				if (Diff(w[8], w[4])) {
+					PIXEL00_12
+					PIXEL10_0
+				} else {
+					PIXEL00_61
+					PIXEL10_90
+				}
+				PIXEL01_11
+				PIXEL11_10
+				break;
+			}
+			case 221: {
+				PIXEL00_12
+				if (Diff(w[6], w[8])) {
+					PIXEL01_11
+					PIXEL11_0
+				} else {
+					PIXEL01_60
+					PIXEL11_90
+				}
+				PIXEL10_10
+				break;
+			}
+			case 207: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+					PIXEL01_12
+				} else {
+					PIXEL00_90
+					PIXEL01_61
+				}
+				PIXEL10_10
+				PIXEL11_11
+				break;
+			}
+			case 238: {
+				PIXEL00_10
+				PIXEL01_12
+				if (Diff(w[8], w[4])) {
+					PIXEL10_0
+					PIXEL11_11
+				} else {
+					PIXEL10_90
+					PIXEL11_60
+				}
+				break;
+			}
+			case 190: {
+				PIXEL00_10
+				if (Diff(w[2], w[6])) {
+					PIXEL01_0
+					PIXEL11_12
+				} else {
+					PIXEL01_90
+					PIXEL11_61
+				}
+				PIXEL10_11
+				break;
+			}
+			case 187: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+					PIXEL10_11
+				} else {
+					PIXEL00_90
+					PIXEL10_60
+				}
+				PIXEL01_10
+				PIXEL11_12
+				break;
+			}
+			case 243: {
+				PIXEL00_11
+				PIXEL01_10
+				if (Diff(w[6], w[8])) {
+					PIXEL10_12
+					PIXEL11_0
+				} else {
+					PIXEL10_61
+					PIXEL11_90
+				}
+				break;
+			}
+			case 119: {
+				if (Diff(w[2], w[6])) {
+					PIXEL00_11
+					PIXEL01_0
+				} else {
+					PIXEL00_60
+					PIXEL01_90
+				}
+				PIXEL10_12
+				PIXEL11_10
+				break;
+			}
+			case 237:
+			case 233: {
+				PIXEL00_12
+				PIXEL01_20
+				if (Diff(w[8], w[4])) {
+					PIXEL10_0
+				} else {
+					PIXEL10_100
+				}
+				PIXEL11_11
+				break;
+			}
+			case 175:
+			case 47: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+				} else {
+					PIXEL00_100
+				}
+				PIXEL01_12
+				PIXEL10_11
+				PIXEL11_20
+				break;
+			}
+			case 183:
+			case 151: {
+				PIXEL00_11
+				if (Diff(w[2], w[6])) {
+					PIXEL01_0
+				} else {
+					PIXEL01_100
+				}
+				PIXEL10_20
+				PIXEL11_12
+				break;
+			}
+			case 245:
+			case 244: {
+				PIXEL00_20
+				PIXEL01_11
+				PIXEL10_12
+				if (Diff(w[6], w[8])) {
+					PIXEL11_0
+				} else {
+					PIXEL11_100
+				}
+				break;
+			}
+			case 250: {
+				PIXEL00_10
+				PIXEL01_10
+				if (Diff(w[8], w[4])) {
+					PIXEL10_0
+				} else {
+					PIXEL10_20
+				}
+				if (Diff(w[6], w[8])) {
+					PIXEL11_0
+				} else {
+					PIXEL11_20
+				}
+				break;
+			}
+			case 123: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+				} else {
+					PIXEL00_20
+				}
+				PIXEL01_10
+				if (Diff(w[8], w[4])) {
+					PIXEL10_0
+				} else {
+					PIXEL10_20
+				}
+				PIXEL11_10
+				break;
+			}
+			case 95: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+				} else {
+					PIXEL00_20
+				}
+				if (Diff(w[2], w[6])) {
+					PIXEL01_0
+				} else {
+					PIXEL01_20
+				}
+				PIXEL10_10
+				PIXEL11_10
+				break;
+			}
+			case 222: {
+				PIXEL00_10
+				if (Diff(w[2], w[6])) {
+					PIXEL01_0
+				} else {
+					PIXEL01_20
+				}
+				PIXEL10_10
+				if (Diff(w[6], w[8])) {
+					PIXEL11_0
+				} else {
+					PIXEL11_20
+				}
+				break;
+			}
+			case 252: {
+				PIXEL00_21
+				PIXEL01_11
+				if (Diff(w[8], w[4])) {
+					PIXEL10_0
+				} else {
+					PIXEL10_20
+				}
+				if (Diff(w[6], w[8])) {
+					PIXEL11_0
+				} else {
+					PIXEL11_100
+				}
+				break;
+			}
+			case 249: {
+				PIXEL00_12
+				PIXEL01_22
+				if (Diff(w[8], w[4])) {
+					PIXEL10_0
+				} else {
+					PIXEL10_100
+				}
+				if (Diff(w[6], w[8])) {
+					PIXEL11_0
+				} else {
+					PIXEL11_20
+				}
+				break;
+			}
+			case 235: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+				} else {
+					PIXEL00_20
+				}
+				PIXEL01_21
+				if (Diff(w[8], w[4])) {
+					PIXEL10_0
+				} else {
+					PIXEL10_100
+				}
+				PIXEL11_11
+				break;
+			}
+			case 111: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+				} else {
+					PIXEL00_100
+				}
+				PIXEL01_12
+				if (Diff(w[8], w[4])) {
+					PIXEL10_0
+				} else {
+					PIXEL10_20
+				}
+				PIXEL11_22
+				break;
+			}
+			case 63: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+				} else {
+					PIXEL00_100
+				}
+				if (Diff(w[2], w[6])) {
+					PIXEL01_0
+				} else {
+					PIXEL01_20
+				}
+				PIXEL10_11
+				PIXEL11_21
+				break;
+			}
+			case 159: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+				} else {
+					PIXEL00_20
+				}
+				if (Diff(w[2], w[6])) {
+					PIXEL01_0
+				} else {
+					PIXEL01_100
+				}
+				PIXEL10_22
+				PIXEL11_12
+				break;
+			}
+			case 215: {
+				PIXEL00_11
+				if (Diff(w[2], w[6])) {
+					PIXEL01_0
+				} else {
+					PIXEL01_100
+				}
+				PIXEL10_21
+				if (Diff(w[6], w[8])) {
+					PIXEL11_0
+				} else {
+					PIXEL11_20
+				}
+				break;
+			}
+			case 246: {
+				PIXEL00_22
+				if (Diff(w[2], w[6])) {
+					PIXEL01_0
+				} else {
+					PIXEL01_20
+				}
+				PIXEL10_12
+				if (Diff(w[6], w[8])) {
+					PIXEL11_0
+				} else {
+					PIXEL11_100
+				}
+				break;
+			}
+			case 254: {
+				PIXEL00_10
+				if (Diff(w[2], w[6])) {
+					PIXEL01_0
+				} else {
+					PIXEL01_20
+				}
+				if (Diff(w[8], w[4])) {
+					PIXEL10_0
+				} else {
+					PIXEL10_20
+				}
+				if (Diff(w[6], w[8])) {
+					PIXEL11_0
+				} else {
+					PIXEL11_100
+				}
+				break;
+			}
+			case 253: {
+				PIXEL00_12
+				PIXEL01_11
+				if (Diff(w[8], w[4])) {
+					PIXEL10_0
+				} else {
+					PIXEL10_100
+				}
+				if (Diff(w[6], w[8])) {
+					PIXEL11_0
+				} else {
+					PIXEL11_100
+				}
+				break;
+			}
+			case 251: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+				} else {
+					PIXEL00_20
+				}
+				PIXEL01_10
+				if (Diff(w[8], w[4])) {
+					PIXEL10_0
+				} else {
+					PIXEL10_100
+				}
+				if (Diff(w[6], w[8])) {
+					PIXEL11_0
+				} else {
+					PIXEL11_20
+				}
+				break;
+			}
+			case 239: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+				} else {
+					PIXEL00_100
+				}
+				PIXEL01_12
+				if (Diff(w[8], w[4])) {
+					PIXEL10_0
+				} else {
+					PIXEL10_100
+				}
+				PIXEL11_11
+				break;
+			}
+			case 127: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+				} else {
+					PIXEL00_100
+				}
+				if (Diff(w[2], w[6])) {
+					PIXEL01_0
+				} else {
+					PIXEL01_20
+				}
+				if (Diff(w[8], w[4])) {
+					PIXEL10_0
+				} else {
+					PIXEL10_20
+				}
+				PIXEL11_10
+				break;
+			}
+			case 191: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+				} else {
+					PIXEL00_100
+				}
+				if (Diff(w[2], w[6])) {
+					PIXEL01_0
+				} else {
+					PIXEL01_100
+				}
+				PIXEL10_11
+				PIXEL11_12
+				break;
+			}
+			case 223: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+				} else {
+					PIXEL00_20
+				}
+				if (Diff(w[2], w[6])) {
+					PIXEL01_0
+				} else {
+					PIXEL01_100
+				}
+				PIXEL10_10
+				if (Diff(w[6], w[8])) {
+					PIXEL11_0
+				} else {
+					PIXEL11_20
+				}
+				break;
+			}
+			case 247: {
+				PIXEL00_11
+				if (Diff(w[2], w[6])) {
+					PIXEL01_0
+				} else {
+					PIXEL01_100
+				}
+				PIXEL10_12
+				if (Diff(w[6], w[8])) {
+					PIXEL11_0
+				} else {
+					PIXEL11_100
+				}
+				break;
+			}
+			case 255: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_0
+				} else {
+					PIXEL00_100
+				}
+				if (Diff(w[2], w[6])) {
+					PIXEL01_0
+				} else {
+					PIXEL01_100
+				}
+				if (Diff(w[8], w[4])) {
+					PIXEL10_0
+				} else {
+					PIXEL10_100
+				}
+				if (Diff(w[6], w[8])) {
+					PIXEL11_0
+				} else {
+					PIXEL11_100
+				}
+				break;
+			}
+			}
+			pIn += INPUT_IMAGE_PIXEL_SIZE_IN_BYTES;
+			pOut += 8;
+		}
+		pOut += BpL + (BpL - Xres * 8);
+	}
+}
+
+void InitLUTs(void) {
+	int i, j, k, r, g, b, Y, u, v;
+
+	for (i = 0; i < 65536; i++)
+		LUT16to32[i] = ((i & 0xF800) << 8) + ((i & 0x07E0) << 5) + ((i & 0x001F) << 3);
+
+	for (i = 0; i < 32; i++)
+		for (j = 0; j < 64; j++)
+			for (k = 0; k < 32; k++) {
+				r = i << 3;
+				g = j << 2;
+				b = k << 3;
+				Y = (r + g + b) >> 2;
+				u = 128 + ((r - b) >> 2);
+				v = 128 + ((-r + 2 * g - b) >> 3);
+				RGBtoYUV[(i << 11) + (j << 5) + k ] = (Y << 16) + (u << 8) + v;
+			}
+}
+
+
+
+//// **** HQ3X BELOW **** /////
+
+
+#define PIXEL00_1M  Interp1(pOut, c[5], c[1]);
+#define PIXEL00_1U  Interp1(pOut, c[5], c[2]);
+#define PIXEL00_1L  Interp1(pOut, c[5], c[4]);
+#define PIXEL00_2   Interp2(pOut, c[5], c[4], c[2]);
+#define PIXEL00_4   Interp4(pOut, c[5], c[4], c[2]);
+#define PIXEL00_5   Interp5(pOut, c[4], c[2]);
+#define PIXEL00_C   *((int*)(pOut))   = c[5];
+
+#define PIXEL01_1   Interp1(pOut+4, c[5], c[2]);
+#define PIXEL01_3   Interp3(pOut+4, c[5], c[2]);
+#define PIXEL01_6   Interp1(pOut+4, c[2], c[5]);
+#define PIXEL01_C   *((int*)(pOut+4)) = c[5];
+
+#define PIXEL02_1M  Interp1(pOut+8, c[5], c[3]);
+#define PIXEL02_1U  Interp1(pOut+8, c[5], c[2]);
+#define PIXEL02_1R  Interp1(pOut+8, c[5], c[6]);
+#define PIXEL02_2   Interp2(pOut+8, c[5], c[2], c[6]);
+#define PIXEL02_4   Interp4(pOut+8, c[5], c[2], c[6]);
+#define PIXEL02_5   Interp5(pOut+8, c[2], c[6]);
+#define PIXEL02_C   *((int*)(pOut+8)) = c[5];
+
+#define PIXEL10_1   Interp1(pOut+BpL, c[5], c[4]);
+#define PIXEL10_3   Interp3(pOut+BpL, c[5], c[4]);
+#define PIXEL10_6   Interp1(pOut+BpL, c[4], c[5]);
+#define PIXEL10_C   *((int*)(pOut+BpL)) = c[5];
+
+#define PIXEL11     *((int*)(pOut+BpL+4)) = c[5];
+
+#define PIXEL12_1   Interp1(pOut+BpL+8, c[5], c[6]);
+#define PIXEL12_3   Interp3(pOut+BpL+8, c[5], c[6]);
+#define PIXEL12_6   Interp1(pOut+BpL+8, c[6], c[5]);
+#define PIXEL12_C   *((int*)(pOut+BpL+8)) = c[5];
+
+#define PIXEL20_1M  Interp1(pOut+BpL+BpL, c[5], c[7]);
+#define PIXEL20_1D  Interp1(pOut+BpL+BpL, c[5], c[8]);
+#define PIXEL20_1L  Interp1(pOut+BpL+BpL, c[5], c[4]);
+#define PIXEL20_2   Interp2(pOut+BpL+BpL, c[5], c[8], c[4]);
+#define PIXEL20_4   Interp4(pOut+BpL+BpL, c[5], c[8], c[4]);
+#define PIXEL20_5   Interp5(pOut+BpL+BpL, c[8], c[4]);
+#define PIXEL20_C   *((int*)(pOut+BpL+BpL)) = c[5];
+
+#define PIXEL21_1   Interp1(pOut+BpL+BpL+4, c[5], c[8]);
+#define PIXEL21_3   Interp3(pOut+BpL+BpL+4, c[5], c[8]);
+#define PIXEL21_6   Interp1(pOut+BpL+BpL+4, c[8], c[5]);
+#define PIXEL21_C   *((int*)(pOut+BpL+BpL+4)) = c[5];
+
+#define PIXEL22_1M  Interp1(pOut+BpL+BpL+8, c[5], c[9]);
+#define PIXEL22_1D  Interp1(pOut+BpL+BpL+8, c[5], c[8]);
+#define PIXEL22_1R  Interp1(pOut+BpL+BpL+8, c[5], c[6]);
+#define PIXEL22_2   Interp2(pOut+BpL+BpL+8, c[5], c[6], c[8]);
+#define PIXEL22_4   Interp4(pOut+BpL+BpL+8, c[5], c[6], c[8]);
+#define PIXEL22_5   Interp5(pOut+BpL+BpL+8, c[6], c[8]);
+#define PIXEL22_C   *((int*)(pOut+BpL+BpL+8)) = c[5];
+
+
+
+void hq3x_32(unsigned char *pIn, unsigned char *pOut, int Xres, int Yres, int BpL) {
+	int  i, j, k;
+	int  prevline, nextline;
+	int  w[10];
+	int  c[10];
+
+	//   +----+----+----+
+	//   |    |    |    |
+	//   | w1 | w2 | w3 |
+	//   +----+----+----+
+	//   |    |    |    |
+	//   | w4 | w5 | w6 |
+	//   +----+----+----+
+	//   |    |    |    |
+	//   | w7 | w8 | w9 |
+	//   +----+----+----+
+
+	for (j = 0; j < Yres; j++) {
+		if (j > 0)      prevline = -Xres * 4;
+		else prevline = 0;
+		if (j < Yres - 1) nextline =  Xres * 4;
+		else nextline = 0;
+
+		for (i = 0; i < Xres; i++) {
+			w[2] = *((INPUT_IMAGE_PIXEL_SIZE *)(pIn + prevline));
+			w[5] = *((INPUT_IMAGE_PIXEL_SIZE *)pIn);
+			w[8] = *((INPUT_IMAGE_PIXEL_SIZE *)(pIn + nextline));
+
+			if (i > 0) {
+				w[1] = *((INPUT_IMAGE_PIXEL_SIZE *)(pIn + prevline - INPUT_IMAGE_PIXEL_SIZE_IN_BYTES));
+				w[4] = *((INPUT_IMAGE_PIXEL_SIZE *)(pIn - INPUT_IMAGE_PIXEL_SIZE_IN_BYTES));
+				w[7] = *((INPUT_IMAGE_PIXEL_SIZE *)(pIn + nextline - INPUT_IMAGE_PIXEL_SIZE_IN_BYTES));
+			} else {
+				w[1] = w[2];
+				w[4] = w[5];
+				w[7] = w[8];
+			}
+
+			if (i < Xres - 1) {
+				w[3] = *((INPUT_IMAGE_PIXEL_SIZE *)(pIn + prevline + INPUT_IMAGE_PIXEL_SIZE_IN_BYTES));
+				w[6] = *((INPUT_IMAGE_PIXEL_SIZE *)(pIn + INPUT_IMAGE_PIXEL_SIZE_IN_BYTES));
+				w[9] = *((INPUT_IMAGE_PIXEL_SIZE *)(pIn + nextline + INPUT_IMAGE_PIXEL_SIZE_IN_BYTES));
+			} else {
+				w[3] = w[2];
+				w[6] = w[5];
+				w[9] = w[8];
+			}
+
+			// convert down to 16-bit
+			for (k = 1; k <= 9; k++) {
+				w[k] = (((((w[k] >> 16) & 0x00ff) / 8) << 11) +
+				        ((((w[k] >> 8) & 0x00ff) / 4) << 5) +
+				        ((w[k]  & 0x00ff) / 8)) & 0x000ffff;
+			}
+
+			int pattern = 0;
+			int flag = 1;
+
+			YUV1 = RGBtoYUV[w[5]];
+
+			for (k = 1; k <= 9; k++) {
+				if (k == 5) continue;
+
+				if (w[k] != w[5]) {
+					YUV2 = RGBtoYUV[w[k]];
+					if ((abs((YUV1 & Ymask) - (YUV2 & Ymask)) > trY) ||
+					        (abs((YUV1 & Umask) - (YUV2 & Umask)) > trU) ||
+					        (abs((YUV1 & Vmask) - (YUV2 & Vmask)) > trV))
+						pattern |= flag;
+				}
+				flag <<= 1;
+			}
+
+			for (k = 1; k <= 9; k++)
+				c[k] = LUT16to32[w[k]];
+
+			switch (pattern) {
+			case 0:
+			case 1:
+			case 4:
+			case 32:
+			case 128:
+			case 5:
+			case 132:
+			case 160:
+			case 33:
+			case 129:
+			case 36:
+			case 133:
+			case 164:
+			case 161:
+			case 37:
+			case 165: {
+				PIXEL00_2
+				PIXEL01_1
+				PIXEL02_2
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_2
+				PIXEL21_1
+				PIXEL22_2
+				break;
+			}
+			case 2:
+			case 34:
+			case 130:
+			case 162: {
+				PIXEL00_1M
+				PIXEL01_C
+				PIXEL02_1M
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_2
+				PIXEL21_1
+				PIXEL22_2
+				break;
+			}
+			case 16:
+			case 17:
+			case 48:
+			case 49: {
+				PIXEL00_2
+				PIXEL01_1
+				PIXEL02_1M
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_2
+				PIXEL21_1
+				PIXEL22_1M
+				break;
+			}
+			case 64:
+			case 65:
+			case 68:
+			case 69: {
+				PIXEL00_2
+				PIXEL01_1
+				PIXEL02_2
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1M
+				PIXEL21_C
+				PIXEL22_1M
+				break;
+			}
+			case 8:
+			case 12:
+			case 136:
+			case 140: {
+				PIXEL00_1M
+				PIXEL01_1
+				PIXEL02_2
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1M
+				PIXEL21_1
+				PIXEL22_2
+				break;
+			}
+			case 3:
+			case 35:
+			case 131:
+			case 163: {
+				PIXEL00_1L
+				PIXEL01_C
+				PIXEL02_1M
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_2
+				PIXEL21_1
+				PIXEL22_2
+				break;
+			}
+			case 6:
+			case 38:
+			case 134:
+			case 166: {
+				PIXEL00_1M
+				PIXEL01_C
+				PIXEL02_1R
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_2
+				PIXEL21_1
+				PIXEL22_2
+				break;
+			}
+			case 20:
+			case 21:
+			case 52:
+			case 53: {
+				PIXEL00_2
+				PIXEL01_1
+				PIXEL02_1U
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_2
+				PIXEL21_1
+				PIXEL22_1M
+				break;
+			}
+			case 144:
+			case 145:
+			case 176:
+			case 177: {
+				PIXEL00_2
+				PIXEL01_1
+				PIXEL02_1M
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_2
+				PIXEL21_1
+				PIXEL22_1D
+				break;
+			}
+			case 192:
+			case 193:
+			case 196:
+			case 197: {
+				PIXEL00_2
+				PIXEL01_1
+				PIXEL02_2
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1M
+				PIXEL21_C
+				PIXEL22_1R
+				break;
+			}
+			case 96:
+			case 97:
+			case 100:
+			case 101: {
+				PIXEL00_2
+				PIXEL01_1
+				PIXEL02_2
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1L
+				PIXEL21_C
+				PIXEL22_1M
+				break;
+			}
+			case 40:
+			case 44:
+			case 168:
+			case 172: {
+				PIXEL00_1M
+				PIXEL01_1
+				PIXEL02_2
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1D
+				PIXEL21_1
+				PIXEL22_2
+				break;
+			}
+			case 9:
+			case 13:
+			case 137:
+			case 141: {
+				PIXEL00_1U
+				PIXEL01_1
+				PIXEL02_2
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1M
+				PIXEL21_1
+				PIXEL22_2
+				break;
+			}
+			case 18:
+			case 50: {
+				PIXEL00_1M
+				if (Diff(w[2], w[6])) {
+					PIXEL01_C
+					PIXEL02_1M
+					PIXEL12_C
+				} else {
+					PIXEL01_3
+					PIXEL02_4
+					PIXEL12_3
+				}
+				PIXEL10_1
+				PIXEL11
+				PIXEL20_2
+				PIXEL21_1
+				PIXEL22_1M
+				break;
+			}
+			case 80:
+			case 81: {
+				PIXEL00_2
+				PIXEL01_1
+				PIXEL02_1M
+				PIXEL10_1
+				PIXEL11
+				PIXEL20_1M
+				if (Diff(w[6], w[8])) {
+					PIXEL12_C
+					PIXEL21_C
+					PIXEL22_1M
+				} else {
+					PIXEL12_3
+					PIXEL21_3
+					PIXEL22_4
+				}
+				break;
+			}
+			case 72:
+			case 76: {
+				PIXEL00_1M
+				PIXEL01_1
+				PIXEL02_2
+				PIXEL11
+				PIXEL12_1
+				if (Diff(w[8], w[4])) {
+					PIXEL10_C
+					PIXEL20_1M
+					PIXEL21_C
+				} else {
+					PIXEL10_3
+					PIXEL20_4
+					PIXEL21_3
+				}
+				PIXEL22_1M
+				break;
+			}
+			case 10:
+			case 138: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_1M
+					PIXEL01_C
+					PIXEL10_C
+				} else {
+					PIXEL00_4
+					PIXEL01_3
+					PIXEL10_3
+				}
+				PIXEL02_1M
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1M
+				PIXEL21_1
+				PIXEL22_2
+				break;
+			}
+			case 66: {
+				PIXEL00_1M
+				PIXEL01_C
+				PIXEL02_1M
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1M
+				PIXEL21_C
+				PIXEL22_1M
+				break;
+			}
+			case 24: {
+				PIXEL00_1M
+				PIXEL01_1
+				PIXEL02_1M
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1M
+				PIXEL21_1
+				PIXEL22_1M
+				break;
+			}
+			case 7:
+			case 39:
+			case 135: {
+				PIXEL00_1L
+				PIXEL01_C
+				PIXEL02_1R
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_2
+				PIXEL21_1
+				PIXEL22_2
+				break;
+			}
+			case 148:
+			case 149:
+			case 180: {
+				PIXEL00_2
+				PIXEL01_1
+				PIXEL02_1U
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_2
+				PIXEL21_1
+				PIXEL22_1D
+				break;
+			}
+			case 224:
+			case 228:
+			case 225: {
+				PIXEL00_2
+				PIXEL01_1
+				PIXEL02_2
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1L
+				PIXEL21_C
+				PIXEL22_1R
+				break;
+			}
+			case 41:
+			case 169:
+			case 45: {
+				PIXEL00_1U
+				PIXEL01_1
+				PIXEL02_2
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1D
+				PIXEL21_1
+				PIXEL22_2
+				break;
+			}
+			case 22:
+			case 54: {
+				PIXEL00_1M
+				if (Diff(w[2], w[6])) {
+					PIXEL01_C
+					PIXEL02_C
+					PIXEL12_C
+				} else {
+					PIXEL01_3
+					PIXEL02_4
+					PIXEL12_3
+				}
+				PIXEL10_1
+				PIXEL11
+				PIXEL20_2
+				PIXEL21_1
+				PIXEL22_1M
+				break;
+			}
+			case 208:
+			case 209: {
+				PIXEL00_2
+				PIXEL01_1
+				PIXEL02_1M
+				PIXEL10_1
+				PIXEL11
+				PIXEL20_1M
+				if (Diff(w[6], w[8])) {
+					PIXEL12_C
+					PIXEL21_C
+					PIXEL22_C
+				} else {
+					PIXEL12_3
+					PIXEL21_3
+					PIXEL22_4
+				}
+				break;
+			}
+			case 104:
+			case 108: {
+				PIXEL00_1M
+				PIXEL01_1
+				PIXEL02_2
+				PIXEL11
+				PIXEL12_1
+				if (Diff(w[8], w[4])) {
+					PIXEL10_C
+					PIXEL20_C
+					PIXEL21_C
+				} else {
+					PIXEL10_3
+					PIXEL20_4
+					PIXEL21_3
+				}
+				PIXEL22_1M
+				break;
+			}
+			case 11:
+			case 139: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+					PIXEL01_C
+					PIXEL10_C
+				} else {
+					PIXEL00_4
+					PIXEL01_3
+					PIXEL10_3
+				}
+				PIXEL02_1M
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1M
+				PIXEL21_1
+				PIXEL22_2
+				break;
+			}
+			case 19:
+			case 51: {
+				if (Diff(w[2], w[6])) {
+					PIXEL00_1L
+					PIXEL01_C
+					PIXEL02_1M
+					PIXEL12_C
+				} else {
+					PIXEL00_2
+					PIXEL01_6
+					PIXEL02_5
+					PIXEL12_1
+				}
+				PIXEL10_1
+				PIXEL11
+				PIXEL20_2
+				PIXEL21_1
+				PIXEL22_1M
+				break;
+			}
+			case 146:
+			case 178: {
+				if (Diff(w[2], w[6])) {
+					PIXEL01_C
+					PIXEL02_1M
+					PIXEL12_C
+					PIXEL22_1D
+				} else {
+					PIXEL01_1
+					PIXEL02_5
+					PIXEL12_6
+					PIXEL22_2
+				}
+				PIXEL00_1M
+				PIXEL10_1
+				PIXEL11
+				PIXEL20_2
+				PIXEL21_1
+				break;
+			}
+			case 84:
+			case 85: {
+				if (Diff(w[6], w[8])) {
+					PIXEL02_1U
+					PIXEL12_C
+					PIXEL21_C
+					PIXEL22_1M
+				} else {
+					PIXEL02_2
+					PIXEL12_6
+					PIXEL21_1
+					PIXEL22_5
+				}
+				PIXEL00_2
+				PIXEL01_1
+				PIXEL10_1
+				PIXEL11
+				PIXEL20_1M
+				break;
+			}
+			case 112:
+			case 113: {
+				if (Diff(w[6], w[8])) {
+					PIXEL12_C
+					PIXEL20_1L
+					PIXEL21_C
+					PIXEL22_1M
+				} else {
+					PIXEL12_1
+					PIXEL20_2
+					PIXEL21_6
+					PIXEL22_5
+				}
+				PIXEL00_2
+				PIXEL01_1
+				PIXEL02_1M
+				PIXEL10_1
+				PIXEL11
+				break;
+			}
+			case 200:
+			case 204: {
+				if (Diff(w[8], w[4])) {
+					PIXEL10_C
+					PIXEL20_1M
+					PIXEL21_C
+					PIXEL22_1R
+				} else {
+					PIXEL10_1
+					PIXEL20_5
+					PIXEL21_6
+					PIXEL22_2
+				}
+				PIXEL00_1M
+				PIXEL01_1
+				PIXEL02_2
+				PIXEL11
+				PIXEL12_1
+				break;
+			}
+			case 73:
+			case 77: {
+				if (Diff(w[8], w[4])) {
+					PIXEL00_1U
+					PIXEL10_C
+					PIXEL20_1M
+					PIXEL21_C
+				} else {
+					PIXEL00_2
+					PIXEL10_6
+					PIXEL20_5
+					PIXEL21_1
+				}
+				PIXEL01_1
+				PIXEL02_2
+				PIXEL11
+				PIXEL12_1
+				PIXEL22_1M
+				break;
+			}
+			case 42:
+			case 170: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_1M
+					PIXEL01_C
+					PIXEL10_C
+					PIXEL20_1D
+				} else {
+					PIXEL00_5
+					PIXEL01_1
+					PIXEL10_6
+					PIXEL20_2
+				}
+				PIXEL02_1M
+				PIXEL11
+				PIXEL12_1
+				PIXEL21_1
+				PIXEL22_2
+				break;
+			}
+			case 14:
+			case 142: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_1M
+					PIXEL01_C
+					PIXEL02_1R
+					PIXEL10_C
+				} else {
+					PIXEL00_5
+					PIXEL01_6
+					PIXEL02_2
+					PIXEL10_1
+				}
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1M
+				PIXEL21_1
+				PIXEL22_2
+				break;
+			}
+			case 67: {
+				PIXEL00_1L
+				PIXEL01_C
+				PIXEL02_1M
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1M
+				PIXEL21_C
+				PIXEL22_1M
+				break;
+			}
+			case 70: {
+				PIXEL00_1M
+				PIXEL01_C
+				PIXEL02_1R
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1M
+				PIXEL21_C
+				PIXEL22_1M
+				break;
+			}
+			case 28: {
+				PIXEL00_1M
+				PIXEL01_1
+				PIXEL02_1U
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1M
+				PIXEL21_1
+				PIXEL22_1M
+				break;
+			}
+			case 152: {
+				PIXEL00_1M
+				PIXEL01_1
+				PIXEL02_1M
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1M
+				PIXEL21_1
+				PIXEL22_1D
+				break;
+			}
+			case 194: {
+				PIXEL00_1M
+				PIXEL01_C
+				PIXEL02_1M
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1M
+				PIXEL21_C
+				PIXEL22_1R
+				break;
+			}
+			case 98: {
+				PIXEL00_1M
+				PIXEL01_C
+				PIXEL02_1M
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1L
+				PIXEL21_C
+				PIXEL22_1M
+				break;
+			}
+			case 56: {
+				PIXEL00_1M
+				PIXEL01_1
+				PIXEL02_1M
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1D
+				PIXEL21_1
+				PIXEL22_1M
+				break;
+			}
+			case 25: {
+				PIXEL00_1U
+				PIXEL01_1
+				PIXEL02_1M
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1M
+				PIXEL21_1
+				PIXEL22_1M
+				break;
+			}
+			case 26:
+			case 31: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+					PIXEL10_C
+				} else {
+					PIXEL00_4
+					PIXEL10_3
+				}
+				PIXEL01_C
+				if (Diff(w[2], w[6])) {
+					PIXEL02_C
+					PIXEL12_C
+				} else {
+					PIXEL02_4
+					PIXEL12_3
+				}
+				PIXEL11
+				PIXEL20_1M
+				PIXEL21_1
+				PIXEL22_1M
+				break;
+			}
+			case 82:
+			case 214: {
+				PIXEL00_1M
+				if (Diff(w[2], w[6])) {
+					PIXEL01_C
+					PIXEL02_C
+				} else {
+					PIXEL01_3
+					PIXEL02_4
+				}
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1M
+				if (Diff(w[6], w[8])) {
+					PIXEL21_C
+					PIXEL22_C
+				} else {
+					PIXEL21_3
+					PIXEL22_4
+				}
+				break;
+			}
+			case 88:
+			case 248: {
+				PIXEL00_1M
+				PIXEL01_1
+				PIXEL02_1M
+				PIXEL11
+				if (Diff(w[8], w[4])) {
+					PIXEL10_C
+					PIXEL20_C
+				} else {
+					PIXEL10_3
+					PIXEL20_4
+				}
+				PIXEL21_C
+				if (Diff(w[6], w[8])) {
+					PIXEL12_C
+					PIXEL22_C
+				} else {
+					PIXEL12_3
+					PIXEL22_4
+				}
+				break;
+			}
+			case 74:
+			case 107: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+					PIXEL01_C
+				} else {
+					PIXEL00_4
+					PIXEL01_3
+				}
+				PIXEL02_1M
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_1
+				if (Diff(w[8], w[4])) {
+					PIXEL20_C
+					PIXEL21_C
+				} else {
+					PIXEL20_4
+					PIXEL21_3
+				}
+				PIXEL22_1M
+				break;
+			}
+			case 27: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+					PIXEL01_C
+					PIXEL10_C
+				} else {
+					PIXEL00_4
+					PIXEL01_3
+					PIXEL10_3
+				}
+				PIXEL02_1M
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1M
+				PIXEL21_1
+				PIXEL22_1M
+				break;
+			}
+			case 86: {
+				PIXEL00_1M
+				if (Diff(w[2], w[6])) {
+					PIXEL01_C
+					PIXEL02_C
+					PIXEL12_C
+				} else {
+					PIXEL01_3
+					PIXEL02_4
+					PIXEL12_3
+				}
+				PIXEL10_1
+				PIXEL11
+				PIXEL20_1M
+				PIXEL21_C
+				PIXEL22_1M
+				break;
+			}
+			case 216: {
+				PIXEL00_1M
+				PIXEL01_1
+				PIXEL02_1M
+				PIXEL10_C
+				PIXEL11
+				PIXEL20_1M
+				if (Diff(w[6], w[8])) {
+					PIXEL12_C
+					PIXEL21_C
+					PIXEL22_C
+				} else {
+					PIXEL12_3
+					PIXEL21_3
+					PIXEL22_4
+				}
+				break;
+			}
+			case 106: {
+				PIXEL00_1M
+				PIXEL01_C
+				PIXEL02_1M
+				PIXEL11
+				PIXEL12_1
+				if (Diff(w[8], w[4])) {
+					PIXEL10_C
+					PIXEL20_C
+					PIXEL21_C
+				} else {
+					PIXEL10_3
+					PIXEL20_4
+					PIXEL21_3
+				}
+				PIXEL22_1M
+				break;
+			}
+			case 30: {
+				PIXEL00_1M
+				if (Diff(w[2], w[6])) {
+					PIXEL01_C
+					PIXEL02_C
+					PIXEL12_C
+				} else {
+					PIXEL01_3
+					PIXEL02_4
+					PIXEL12_3
+				}
+				PIXEL10_C
+				PIXEL11
+				PIXEL20_1M
+				PIXEL21_1
+				PIXEL22_1M
+				break;
+			}
+			case 210: {
+				PIXEL00_1M
+				PIXEL01_C
+				PIXEL02_1M
+				PIXEL10_1
+				PIXEL11
+				PIXEL20_1M
+				if (Diff(w[6], w[8])) {
+					PIXEL12_C
+					PIXEL21_C
+					PIXEL22_C
+				} else {
+					PIXEL12_3
+					PIXEL21_3
+					PIXEL22_4
+				}
+				break;
+			}
+			case 120: {
+				PIXEL00_1M
+				PIXEL01_1
+				PIXEL02_1M
+				PIXEL11
+				PIXEL12_C
+				if (Diff(w[8], w[4])) {
+					PIXEL10_C
+					PIXEL20_C
+					PIXEL21_C
+				} else {
+					PIXEL10_3
+					PIXEL20_4
+					PIXEL21_3
+				}
+				PIXEL22_1M
+				break;
+			}
+			case 75: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+					PIXEL01_C
+					PIXEL10_C
+				} else {
+					PIXEL00_4
+					PIXEL01_3
+					PIXEL10_3
+				}
+				PIXEL02_1M
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1M
+				PIXEL21_C
+				PIXEL22_1M
+				break;
+			}
+			case 29: {
+				PIXEL00_1U
+				PIXEL01_1
+				PIXEL02_1U
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1M
+				PIXEL21_1
+				PIXEL22_1M
+				break;
+			}
+			case 198: {
+				PIXEL00_1M
+				PIXEL01_C
+				PIXEL02_1R
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1M
+				PIXEL21_C
+				PIXEL22_1R
+				break;
+			}
+			case 184: {
+				PIXEL00_1M
+				PIXEL01_1
+				PIXEL02_1M
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1D
+				PIXEL21_1
+				PIXEL22_1D
+				break;
+			}
+			case 99: {
+				PIXEL00_1L
+				PIXEL01_C
+				PIXEL02_1M
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1L
+				PIXEL21_C
+				PIXEL22_1M
+				break;
+			}
+			case 57: {
+				PIXEL00_1U
+				PIXEL01_1
+				PIXEL02_1M
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1D
+				PIXEL21_1
+				PIXEL22_1M
+				break;
+			}
+			case 71: {
+				PIXEL00_1L
+				PIXEL01_C
+				PIXEL02_1R
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1M
+				PIXEL21_C
+				PIXEL22_1M
+				break;
+			}
+			case 156: {
+				PIXEL00_1M
+				PIXEL01_1
+				PIXEL02_1U
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1M
+				PIXEL21_1
+				PIXEL22_1D
+				break;
+			}
+			case 226: {
+				PIXEL00_1M
+				PIXEL01_C
+				PIXEL02_1M
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1L
+				PIXEL21_C
+				PIXEL22_1R
+				break;
+			}
+			case 60: {
+				PIXEL00_1M
+				PIXEL01_1
+				PIXEL02_1U
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1D
+				PIXEL21_1
+				PIXEL22_1M
+				break;
+			}
+			case 195: {
+				PIXEL00_1L
+				PIXEL01_C
+				PIXEL02_1M
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1M
+				PIXEL21_C
+				PIXEL22_1R
+				break;
+			}
+			case 102: {
+				PIXEL00_1M
+				PIXEL01_C
+				PIXEL02_1R
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1L
+				PIXEL21_C
+				PIXEL22_1M
+				break;
+			}
+			case 153: {
+				PIXEL00_1U
+				PIXEL01_1
+				PIXEL02_1M
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1M
+				PIXEL21_1
+				PIXEL22_1D
+				break;
+			}
+			case 58: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_1M
+				} else {
+					PIXEL00_2
+				}
+				PIXEL01_C
+				if (Diff(w[2], w[6])) {
+					PIXEL02_1M
+				} else {
+					PIXEL02_2
+				}
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1D
+				PIXEL21_1
+				PIXEL22_1M
+				break;
+			}
+			case 83: {
+				PIXEL00_1L
+				PIXEL01_C
+				if (Diff(w[2], w[6])) {
+					PIXEL02_1M
+				} else {
+					PIXEL02_2
+				}
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1M
+				PIXEL21_C
+				if (Diff(w[6], w[8])) {
+					PIXEL22_1M
+				} else {
+					PIXEL22_2
+				}
+				break;
+			}
+			case 92: {
+				PIXEL00_1M
+				PIXEL01_1
+				PIXEL02_1U
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				if (Diff(w[8], w[4])) {
+					PIXEL20_1M
+				} else {
+					PIXEL20_2
+				}
+				PIXEL21_C
+				if (Diff(w[6], w[8])) {
+					PIXEL22_1M
+				} else {
+					PIXEL22_2
+				}
+				break;
+			}
+			case 202: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_1M
+				} else {
+					PIXEL00_2
+				}
+				PIXEL01_C
+				PIXEL02_1M
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_1
+				if (Diff(w[8], w[4])) {
+					PIXEL20_1M
+				} else {
+					PIXEL20_2
+				}
+				PIXEL21_C
+				PIXEL22_1R
+				break;
+			}
+			case 78: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_1M
+				} else {
+					PIXEL00_2
+				}
+				PIXEL01_C
+				PIXEL02_1R
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_1
+				if (Diff(w[8], w[4])) {
+					PIXEL20_1M
+				} else {
+					PIXEL20_2
+				}
+				PIXEL21_C
+				PIXEL22_1M
+				break;
+			}
+			case 154: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_1M
+				} else {
+					PIXEL00_2
+				}
+				PIXEL01_C
+				if (Diff(w[2], w[6])) {
+					PIXEL02_1M
+				} else {
+					PIXEL02_2
+				}
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1M
+				PIXEL21_1
+				PIXEL22_1D
+				break;
+			}
+			case 114: {
+				PIXEL00_1M
+				PIXEL01_C
+				if (Diff(w[2], w[6])) {
+					PIXEL02_1M
+				} else {
+					PIXEL02_2
+				}
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1L
+				PIXEL21_C
+				if (Diff(w[6], w[8])) {
+					PIXEL22_1M
+				} else {
+					PIXEL22_2
+				}
+				break;
+			}
+			case 89: {
+				PIXEL00_1U
+				PIXEL01_1
+				PIXEL02_1M
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				if (Diff(w[8], w[4])) {
+					PIXEL20_1M
+				} else {
+					PIXEL20_2
+				}
+				PIXEL21_C
+				if (Diff(w[6], w[8])) {
+					PIXEL22_1M
+				} else {
+					PIXEL22_2
+				}
+				break;
+			}
+			case 90: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_1M
+				} else {
+					PIXEL00_2
+				}
+				PIXEL01_C
+				if (Diff(w[2], w[6])) {
+					PIXEL02_1M
+				} else {
+					PIXEL02_2
+				}
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				if (Diff(w[8], w[4])) {
+					PIXEL20_1M
+				} else {
+					PIXEL20_2
+				}
+				PIXEL21_C
+				if (Diff(w[6], w[8])) {
+					PIXEL22_1M
+				} else {
+					PIXEL22_2
+				}
+				break;
+			}
+			case 55:
+			case 23: {
+				if (Diff(w[2], w[6])) {
+					PIXEL00_1L
+					PIXEL01_C
+					PIXEL02_C
+					PIXEL12_C
+				} else {
+					PIXEL00_2
+					PIXEL01_6
+					PIXEL02_5
+					PIXEL12_1
+				}
+				PIXEL10_1
+				PIXEL11
+				PIXEL20_2
+				PIXEL21_1
+				PIXEL22_1M
+				break;
+			}
+			case 182:
+			case 150: {
+				if (Diff(w[2], w[6])) {
+					PIXEL01_C
+					PIXEL02_C
+					PIXEL12_C
+					PIXEL22_1D
+				} else {
+					PIXEL01_1
+					PIXEL02_5
+					PIXEL12_6
+					PIXEL22_2
+				}
+				PIXEL00_1M
+				PIXEL10_1
+				PIXEL11
+				PIXEL20_2
+				PIXEL21_1
+				break;
+			}
+			case 213:
+			case 212: {
+				if (Diff(w[6], w[8])) {
+					PIXEL02_1U
+					PIXEL12_C
+					PIXEL21_C
+					PIXEL22_C
+				} else {
+					PIXEL02_2
+					PIXEL12_6
+					PIXEL21_1
+					PIXEL22_5
+				}
+				PIXEL00_2
+				PIXEL01_1
+				PIXEL10_1
+				PIXEL11
+				PIXEL20_1M
+				break;
+			}
+			case 241:
+			case 240: {
+				if (Diff(w[6], w[8])) {
+					PIXEL12_C
+					PIXEL20_1L
+					PIXEL21_C
+					PIXEL22_C
+				} else {
+					PIXEL12_1
+					PIXEL20_2
+					PIXEL21_6
+					PIXEL22_5
+				}
+				PIXEL00_2
+				PIXEL01_1
+				PIXEL02_1M
+				PIXEL10_1
+				PIXEL11
+				break;
+			}
+			case 236:
+			case 232: {
+				if (Diff(w[8], w[4])) {
+					PIXEL10_C
+					PIXEL20_C
+					PIXEL21_C
+					PIXEL22_1R
+				} else {
+					PIXEL10_1
+					PIXEL20_5
+					PIXEL21_6
+					PIXEL22_2
+				}
+				PIXEL00_1M
+				PIXEL01_1
+				PIXEL02_2
+				PIXEL11
+				PIXEL12_1
+				break;
+			}
+			case 109:
+			case 105: {
+				if (Diff(w[8], w[4])) {
+					PIXEL00_1U
+					PIXEL10_C
+					PIXEL20_C
+					PIXEL21_C
+				} else {
+					PIXEL00_2
+					PIXEL10_6
+					PIXEL20_5
+					PIXEL21_1
+				}
+				PIXEL01_1
+				PIXEL02_2
+				PIXEL11
+				PIXEL12_1
+				PIXEL22_1M
+				break;
+			}
+			case 171:
+			case 43: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+					PIXEL01_C
+					PIXEL10_C
+					PIXEL20_1D
+				} else {
+					PIXEL00_5
+					PIXEL01_1
+					PIXEL10_6
+					PIXEL20_2
+				}
+				PIXEL02_1M
+				PIXEL11
+				PIXEL12_1
+				PIXEL21_1
+				PIXEL22_2
+				break;
+			}
+			case 143:
+			case 15: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+					PIXEL01_C
+					PIXEL02_1R
+					PIXEL10_C
+				} else {
+					PIXEL00_5
+					PIXEL01_6
+					PIXEL02_2
+					PIXEL10_1
+				}
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1M
+				PIXEL21_1
+				PIXEL22_2
+				break;
+			}
+			case 124: {
+				PIXEL00_1M
+				PIXEL01_1
+				PIXEL02_1U
+				PIXEL11
+				PIXEL12_C
+				if (Diff(w[8], w[4])) {
+					PIXEL10_C
+					PIXEL20_C
+					PIXEL21_C
+				} else {
+					PIXEL10_3
+					PIXEL20_4
+					PIXEL21_3
+				}
+				PIXEL22_1M
+				break;
+			}
+			case 203: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+					PIXEL01_C
+					PIXEL10_C
+				} else {
+					PIXEL00_4
+					PIXEL01_3
+					PIXEL10_3
+				}
+				PIXEL02_1M
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1M
+				PIXEL21_C
+				PIXEL22_1R
+				break;
+			}
+			case 62: {
+				PIXEL00_1M
+				if (Diff(w[2], w[6])) {
+					PIXEL01_C
+					PIXEL02_C
+					PIXEL12_C
+				} else {
+					PIXEL01_3
+					PIXEL02_4
+					PIXEL12_3
+				}
+				PIXEL10_C
+				PIXEL11
+				PIXEL20_1D
+				PIXEL21_1
+				PIXEL22_1M
+				break;
+			}
+			case 211: {
+				PIXEL00_1L
+				PIXEL01_C
+				PIXEL02_1M
+				PIXEL10_1
+				PIXEL11
+				PIXEL20_1M
+				if (Diff(w[6], w[8])) {
+					PIXEL12_C
+					PIXEL21_C
+					PIXEL22_C
+				} else {
+					PIXEL12_3
+					PIXEL21_3
+					PIXEL22_4
+				}
+				break;
+			}
+			case 118: {
+				PIXEL00_1M
+				if (Diff(w[2], w[6])) {
+					PIXEL01_C
+					PIXEL02_C
+					PIXEL12_C
+				} else {
+					PIXEL01_3
+					PIXEL02_4
+					PIXEL12_3
+				}
+				PIXEL10_1
+				PIXEL11
+				PIXEL20_1L
+				PIXEL21_C
+				PIXEL22_1M
+				break;
+			}
+			case 217: {
+				PIXEL00_1U
+				PIXEL01_1
+				PIXEL02_1M
+				PIXEL10_C
+				PIXEL11
+				PIXEL20_1M
+				if (Diff(w[6], w[8])) {
+					PIXEL12_C
+					PIXEL21_C
+					PIXEL22_C
+				} else {
+					PIXEL12_3
+					PIXEL21_3
+					PIXEL22_4
+				}
+				break;
+			}
+			case 110: {
+				PIXEL00_1M
+				PIXEL01_C
+				PIXEL02_1R
+				PIXEL11
+				PIXEL12_1
+				if (Diff(w[8], w[4])) {
+					PIXEL10_C
+					PIXEL20_C
+					PIXEL21_C
+				} else {
+					PIXEL10_3
+					PIXEL20_4
+					PIXEL21_3
+				}
+				PIXEL22_1M
+				break;
+			}
+			case 155: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+					PIXEL01_C
+					PIXEL10_C
+				} else {
+					PIXEL00_4
+					PIXEL01_3
+					PIXEL10_3
+				}
+				PIXEL02_1M
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1M
+				PIXEL21_1
+				PIXEL22_1D
+				break;
+			}
+			case 188: {
+				PIXEL00_1M
+				PIXEL01_1
+				PIXEL02_1U
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1D
+				PIXEL21_1
+				PIXEL22_1D
+				break;
+			}
+			case 185: {
+				PIXEL00_1U
+				PIXEL01_1
+				PIXEL02_1M
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1D
+				PIXEL21_1
+				PIXEL22_1D
+				break;
+			}
+			case 61: {
+				PIXEL00_1U
+				PIXEL01_1
+				PIXEL02_1U
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1D
+				PIXEL21_1
+				PIXEL22_1M
+				break;
+			}
+			case 157: {
+				PIXEL00_1U
+				PIXEL01_1
+				PIXEL02_1U
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1M
+				PIXEL21_1
+				PIXEL22_1D
+				break;
+			}
+			case 103: {
+				PIXEL00_1L
+				PIXEL01_C
+				PIXEL02_1R
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1L
+				PIXEL21_C
+				PIXEL22_1M
+				break;
+			}
+			case 227: {
+				PIXEL00_1L
+				PIXEL01_C
+				PIXEL02_1M
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1L
+				PIXEL21_C
+				PIXEL22_1R
+				break;
+			}
+			case 230: {
+				PIXEL00_1M
+				PIXEL01_C
+				PIXEL02_1R
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1L
+				PIXEL21_C
+				PIXEL22_1R
+				break;
+			}
+			case 199: {
+				PIXEL00_1L
+				PIXEL01_C
+				PIXEL02_1R
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1M
+				PIXEL21_C
+				PIXEL22_1R
+				break;
+			}
+			case 220: {
+				PIXEL00_1M
+				PIXEL01_1
+				PIXEL02_1U
+				PIXEL10_C
+				PIXEL11
+				if (Diff(w[8], w[4])) {
+					PIXEL20_1M
+				} else {
+					PIXEL20_2
+				}
+				if (Diff(w[6], w[8])) {
+					PIXEL12_C
+					PIXEL21_C
+					PIXEL22_C
+				} else {
+					PIXEL12_3
+					PIXEL21_3
+					PIXEL22_4
+				}
+				break;
+			}
+			case 158: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_1M
+				} else {
+					PIXEL00_2
+				}
+				if (Diff(w[2], w[6])) {
+					PIXEL01_C
+					PIXEL02_C
+					PIXEL12_C
+				} else {
+					PIXEL01_3
+					PIXEL02_4
+					PIXEL12_3
+				}
+				PIXEL10_C
+				PIXEL11
+				PIXEL20_1M
+				PIXEL21_1
+				PIXEL22_1D
+				break;
+			}
+			case 234: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_1M
+				} else {
+					PIXEL00_2
+				}
+				PIXEL01_C
+				PIXEL02_1M
+				PIXEL11
+				PIXEL12_1
+				if (Diff(w[8], w[4])) {
+					PIXEL10_C
+					PIXEL20_C
+					PIXEL21_C
+				} else {
+					PIXEL10_3
+					PIXEL20_4
+					PIXEL21_3
+				}
+				PIXEL22_1R
+				break;
+			}
+			case 242: {
+				PIXEL00_1M
+				PIXEL01_C
+				if (Diff(w[2], w[6])) {
+					PIXEL02_1M
+				} else {
+					PIXEL02_2
+				}
+				PIXEL10_1
+				PIXEL11
+				PIXEL20_1L
+				if (Diff(w[6], w[8])) {
+					PIXEL12_C
+					PIXEL21_C
+					PIXEL22_C
+				} else {
+					PIXEL12_3
+					PIXEL21_3
+					PIXEL22_4
+				}
+				break;
+			}
+			case 59: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+					PIXEL01_C
+					PIXEL10_C
+				} else {
+					PIXEL00_4
+					PIXEL01_3
+					PIXEL10_3
+				}
+				if (Diff(w[2], w[6])) {
+					PIXEL02_1M
+				} else {
+					PIXEL02_2
+				}
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1D
+				PIXEL21_1
+				PIXEL22_1M
+				break;
+			}
+			case 121: {
+				PIXEL00_1U
+				PIXEL01_1
+				PIXEL02_1M
+				PIXEL11
+				PIXEL12_C
+				if (Diff(w[8], w[4])) {
+					PIXEL10_C
+					PIXEL20_C
+					PIXEL21_C
+				} else {
+					PIXEL10_3
+					PIXEL20_4
+					PIXEL21_3
+				}
+				if (Diff(w[6], w[8])) {
+					PIXEL22_1M
+				} else {
+					PIXEL22_2
+				}
+				break;
+			}
+			case 87: {
+				PIXEL00_1L
+				if (Diff(w[2], w[6])) {
+					PIXEL01_C
+					PIXEL02_C
+					PIXEL12_C
+				} else {
+					PIXEL01_3
+					PIXEL02_4
+					PIXEL12_3
+				}
+				PIXEL10_1
+				PIXEL11
+				PIXEL20_1M
+				PIXEL21_C
+				if (Diff(w[6], w[8])) {
+					PIXEL22_1M
+				} else {
+					PIXEL22_2
+				}
+				break;
+			}
+			case 79: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+					PIXEL01_C
+					PIXEL10_C
+				} else {
+					PIXEL00_4
+					PIXEL01_3
+					PIXEL10_3
+				}
+				PIXEL02_1R
+				PIXEL11
+				PIXEL12_1
+				if (Diff(w[8], w[4])) {
+					PIXEL20_1M
+				} else {
+					PIXEL20_2
+				}
+				PIXEL21_C
+				PIXEL22_1M
+				break;
+			}
+			case 122: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_1M
+				} else {
+					PIXEL00_2
+				}
+				PIXEL01_C
+				if (Diff(w[2], w[6])) {
+					PIXEL02_1M
+				} else {
+					PIXEL02_2
+				}
+				PIXEL11
+				PIXEL12_C
+				if (Diff(w[8], w[4])) {
+					PIXEL10_C
+					PIXEL20_C
+					PIXEL21_C
+				} else {
+					PIXEL10_3
+					PIXEL20_4
+					PIXEL21_3
+				}
+				if (Diff(w[6], w[8])) {
+					PIXEL22_1M
+				} else {
+					PIXEL22_2
+				}
+				break;
+			}
+			case 94: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_1M
+				} else {
+					PIXEL00_2
+				}
+				if (Diff(w[2], w[6])) {
+					PIXEL01_C
+					PIXEL02_C
+					PIXEL12_C
+				} else {
+					PIXEL01_3
+					PIXEL02_4
+					PIXEL12_3
+				}
+				PIXEL10_C
+				PIXEL11
+				if (Diff(w[8], w[4])) {
+					PIXEL20_1M
+				} else {
+					PIXEL20_2
+				}
+				PIXEL21_C
+				if (Diff(w[6], w[8])) {
+					PIXEL22_1M
+				} else {
+					PIXEL22_2
+				}
+				break;
+			}
+			case 218: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_1M
+				} else {
+					PIXEL00_2
+				}
+				PIXEL01_C
+				if (Diff(w[2], w[6])) {
+					PIXEL02_1M
+				} else {
+					PIXEL02_2
+				}
+				PIXEL10_C
+				PIXEL11
+				if (Diff(w[8], w[4])) {
+					PIXEL20_1M
+				} else {
+					PIXEL20_2
+				}
+				if (Diff(w[6], w[8])) {
+					PIXEL12_C
+					PIXEL21_C
+					PIXEL22_C
+				} else {
+					PIXEL12_3
+					PIXEL21_3
+					PIXEL22_4
+				}
+				break;
+			}
+			case 91: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+					PIXEL01_C
+					PIXEL10_C
+				} else {
+					PIXEL00_4
+					PIXEL01_3
+					PIXEL10_3
+				}
+				if (Diff(w[2], w[6])) {
+					PIXEL02_1M
+				} else {
+					PIXEL02_2
+				}
+				PIXEL11
+				PIXEL12_C
+				if (Diff(w[8], w[4])) {
+					PIXEL20_1M
+				} else {
+					PIXEL20_2
+				}
+				PIXEL21_C
+				if (Diff(w[6], w[8])) {
+					PIXEL22_1M
+				} else {
+					PIXEL22_2
+				}
+				break;
+			}
+			case 229: {
+				PIXEL00_2
+				PIXEL01_1
+				PIXEL02_2
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1L
+				PIXEL21_C
+				PIXEL22_1R
+				break;
+			}
+			case 167: {
+				PIXEL00_1L
+				PIXEL01_C
+				PIXEL02_1R
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_2
+				PIXEL21_1
+				PIXEL22_2
+				break;
+			}
+			case 173: {
+				PIXEL00_1U
+				PIXEL01_1
+				PIXEL02_2
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1D
+				PIXEL21_1
+				PIXEL22_2
+				break;
+			}
+			case 181: {
+				PIXEL00_2
+				PIXEL01_1
+				PIXEL02_1U
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_2
+				PIXEL21_1
+				PIXEL22_1D
+				break;
+			}
+			case 186: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_1M
+				} else {
+					PIXEL00_2
+				}
+				PIXEL01_C
+				if (Diff(w[2], w[6])) {
+					PIXEL02_1M
+				} else {
+					PIXEL02_2
+				}
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1D
+				PIXEL21_1
+				PIXEL22_1D
+				break;
+			}
+			case 115: {
+				PIXEL00_1L
+				PIXEL01_C
+				if (Diff(w[2], w[6])) {
+					PIXEL02_1M
+				} else {
+					PIXEL02_2
+				}
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1L
+				PIXEL21_C
+				if (Diff(w[6], w[8])) {
+					PIXEL22_1M
+				} else {
+					PIXEL22_2
+				}
+				break;
+			}
+			case 93: {
+				PIXEL00_1U
+				PIXEL01_1
+				PIXEL02_1U
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				if (Diff(w[8], w[4])) {
+					PIXEL20_1M
+				} else {
+					PIXEL20_2
+				}
+				PIXEL21_C
+				if (Diff(w[6], w[8])) {
+					PIXEL22_1M
+				} else {
+					PIXEL22_2
+				}
+				break;
+			}
+			case 206: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_1M
+				} else {
+					PIXEL00_2
+				}
+				PIXEL01_C
+				PIXEL02_1R
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_1
+				if (Diff(w[8], w[4])) {
+					PIXEL20_1M
+				} else {
+					PIXEL20_2
+				}
+				PIXEL21_C
+				PIXEL22_1R
+				break;
+			}
+			case 205:
+			case 201: {
+				PIXEL00_1U
+				PIXEL01_1
+				PIXEL02_2
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_1
+				if (Diff(w[8], w[4])) {
+					PIXEL20_1M
+				} else {
+					PIXEL20_2
+				}
+				PIXEL21_C
+				PIXEL22_1R
+				break;
+			}
+			case 174:
+			case 46: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_1M
+				} else {
+					PIXEL00_2
+				}
+				PIXEL01_C
+				PIXEL02_1R
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1D
+				PIXEL21_1
+				PIXEL22_2
+				break;
+			}
+			case 179:
+			case 147: {
+				PIXEL00_1L
+				PIXEL01_C
+				if (Diff(w[2], w[6])) {
+					PIXEL02_1M
+				} else {
+					PIXEL02_2
+				}
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_2
+				PIXEL21_1
+				PIXEL22_1D
+				break;
+			}
+			case 117:
+			case 116: {
+				PIXEL00_2
+				PIXEL01_1
+				PIXEL02_1U
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1L
+				PIXEL21_C
+				if (Diff(w[6], w[8])) {
+					PIXEL22_1M
+				} else {
+					PIXEL22_2
+				}
+				break;
+			}
+			case 189: {
+				PIXEL00_1U
+				PIXEL01_1
+				PIXEL02_1U
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1D
+				PIXEL21_1
+				PIXEL22_1D
+				break;
+			}
+			case 231: {
+				PIXEL00_1L
+				PIXEL01_C
+				PIXEL02_1R
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1L
+				PIXEL21_C
+				PIXEL22_1R
+				break;
+			}
+			case 126: {
+				PIXEL00_1M
+				if (Diff(w[2], w[6])) {
+					PIXEL01_C
+					PIXEL02_C
+					PIXEL12_C
+				} else {
+					PIXEL01_3
+					PIXEL02_4
+					PIXEL12_3
+				}
+				PIXEL11
+				if (Diff(w[8], w[4])) {
+					PIXEL10_C
+					PIXEL20_C
+					PIXEL21_C
+				} else {
+					PIXEL10_3
+					PIXEL20_4
+					PIXEL21_3
+				}
+				PIXEL22_1M
+				break;
+			}
+			case 219: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+					PIXEL01_C
+					PIXEL10_C
+				} else {
+					PIXEL00_4
+					PIXEL01_3
+					PIXEL10_3
+				}
+				PIXEL02_1M
+				PIXEL11
+				PIXEL20_1M
+				if (Diff(w[6], w[8])) {
+					PIXEL12_C
+					PIXEL21_C
+					PIXEL22_C
+				} else {
+					PIXEL12_3
+					PIXEL21_3
+					PIXEL22_4
+				}
+				break;
+			}
+			case 125: {
+				if (Diff(w[8], w[4])) {
+					PIXEL00_1U
+					PIXEL10_C
+					PIXEL20_C
+					PIXEL21_C
+				} else {
+					PIXEL00_2
+					PIXEL10_6
+					PIXEL20_5
+					PIXEL21_1
+				}
+				PIXEL01_1
+				PIXEL02_1U
+				PIXEL11
+				PIXEL12_C
+				PIXEL22_1M
+				break;
+			}
+			case 221: {
+				if (Diff(w[6], w[8])) {
+					PIXEL02_1U
+					PIXEL12_C
+					PIXEL21_C
+					PIXEL22_C
+				} else {
+					PIXEL02_2
+					PIXEL12_6
+					PIXEL21_1
+					PIXEL22_5
+				}
+				PIXEL00_1U
+				PIXEL01_1
+				PIXEL10_C
+				PIXEL11
+				PIXEL20_1M
+				break;
+			}
+			case 207: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+					PIXEL01_C
+					PIXEL02_1R
+					PIXEL10_C
+				} else {
+					PIXEL00_5
+					PIXEL01_6
+					PIXEL02_2
+					PIXEL10_1
+				}
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1M
+				PIXEL21_C
+				PIXEL22_1R
+				break;
+			}
+			case 238: {
+				if (Diff(w[8], w[4])) {
+					PIXEL10_C
+					PIXEL20_C
+					PIXEL21_C
+					PIXEL22_1R
+				} else {
+					PIXEL10_1
+					PIXEL20_5
+					PIXEL21_6
+					PIXEL22_2
+				}
+				PIXEL00_1M
+				PIXEL01_C
+				PIXEL02_1R
+				PIXEL11
+				PIXEL12_1
+				break;
+			}
+			case 190: {
+				if (Diff(w[2], w[6])) {
+					PIXEL01_C
+					PIXEL02_C
+					PIXEL12_C
+					PIXEL22_1D
+				} else {
+					PIXEL01_1
+					PIXEL02_5
+					PIXEL12_6
+					PIXEL22_2
+				}
+				PIXEL00_1M
+				PIXEL10_C
+				PIXEL11
+				PIXEL20_1D
+				PIXEL21_1
+				break;
+			}
+			case 187: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+					PIXEL01_C
+					PIXEL10_C
+					PIXEL20_1D
+				} else {
+					PIXEL00_5
+					PIXEL01_1
+					PIXEL10_6
+					PIXEL20_2
+				}
+				PIXEL02_1M
+				PIXEL11
+				PIXEL12_C
+				PIXEL21_1
+				PIXEL22_1D
+				break;
+			}
+			case 243: {
+				if (Diff(w[6], w[8])) {
+					PIXEL12_C
+					PIXEL20_1L
+					PIXEL21_C
+					PIXEL22_C
+				} else {
+					PIXEL12_1
+					PIXEL20_2
+					PIXEL21_6
+					PIXEL22_5
+				}
+				PIXEL00_1L
+				PIXEL01_C
+				PIXEL02_1M
+				PIXEL10_1
+				PIXEL11
+				break;
+			}
+			case 119: {
+				if (Diff(w[2], w[6])) {
+					PIXEL00_1L
+					PIXEL01_C
+					PIXEL02_C
+					PIXEL12_C
+				} else {
+					PIXEL00_2
+					PIXEL01_6
+					PIXEL02_5
+					PIXEL12_1
+				}
+				PIXEL10_1
+				PIXEL11
+				PIXEL20_1L
+				PIXEL21_C
+				PIXEL22_1M
+				break;
+			}
+			case 237:
+			case 233: {
+				PIXEL00_1U
+				PIXEL01_1
+				PIXEL02_2
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_1
+				if (Diff(w[8], w[4])) {
+					PIXEL20_C
+				} else {
+					PIXEL20_2
+				}
+				PIXEL21_C
+				PIXEL22_1R
+				break;
+			}
+			case 175:
+			case 47: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+				} else {
+					PIXEL00_2
+				}
+				PIXEL01_C
+				PIXEL02_1R
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_1
+				PIXEL20_1D
+				PIXEL21_1
+				PIXEL22_2
+				break;
+			}
+			case 183:
+			case 151: {
+				PIXEL00_1L
+				PIXEL01_C
+				if (Diff(w[2], w[6])) {
+					PIXEL02_C
+				} else {
+					PIXEL02_2
+				}
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_2
+				PIXEL21_1
+				PIXEL22_1D
+				break;
+			}
+			case 245:
+			case 244: {
+				PIXEL00_2
+				PIXEL01_1
+				PIXEL02_1U
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1L
+				PIXEL21_C
+				if (Diff(w[6], w[8])) {
+					PIXEL22_C
+				} else {
+					PIXEL22_2
+				}
+				break;
+			}
+			case 250: {
+				PIXEL00_1M
+				PIXEL01_C
+				PIXEL02_1M
+				PIXEL11
+				if (Diff(w[8], w[4])) {
+					PIXEL10_C
+					PIXEL20_C
+				} else {
+					PIXEL10_3
+					PIXEL20_4
+				}
+				PIXEL21_C
+				if (Diff(w[6], w[8])) {
+					PIXEL12_C
+					PIXEL22_C
+				} else {
+					PIXEL12_3
+					PIXEL22_4
+				}
+				break;
+			}
+			case 123: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+					PIXEL01_C
+				} else {
+					PIXEL00_4
+					PIXEL01_3
+				}
+				PIXEL02_1M
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				if (Diff(w[8], w[4])) {
+					PIXEL20_C
+					PIXEL21_C
+				} else {
+					PIXEL20_4
+					PIXEL21_3
+				}
+				PIXEL22_1M
+				break;
+			}
+			case 95: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+					PIXEL10_C
+				} else {
+					PIXEL00_4
+					PIXEL10_3
+				}
+				PIXEL01_C
+				if (Diff(w[2], w[6])) {
+					PIXEL02_C
+					PIXEL12_C
+				} else {
+					PIXEL02_4
+					PIXEL12_3
+				}
+				PIXEL11
+				PIXEL20_1M
+				PIXEL21_C
+				PIXEL22_1M
+				break;
+			}
+			case 222: {
+				PIXEL00_1M
+				if (Diff(w[2], w[6])) {
+					PIXEL01_C
+					PIXEL02_C
+				} else {
+					PIXEL01_3
+					PIXEL02_4
+				}
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1M
+				if (Diff(w[6], w[8])) {
+					PIXEL21_C
+					PIXEL22_C
+				} else {
+					PIXEL21_3
+					PIXEL22_4
+				}
+				break;
+			}
+			case 252: {
+				PIXEL00_1M
+				PIXEL01_1
+				PIXEL02_1U
+				PIXEL11
+				PIXEL12_C
+				if (Diff(w[8], w[4])) {
+					PIXEL10_C
+					PIXEL20_C
+				} else {
+					PIXEL10_3
+					PIXEL20_4
+				}
+				PIXEL21_C
+				if (Diff(w[6], w[8])) {
+					PIXEL22_C
+				} else {
+					PIXEL22_2
+				}
+				break;
+			}
+			case 249: {
+				PIXEL00_1U
+				PIXEL01_1
+				PIXEL02_1M
+				PIXEL10_C
+				PIXEL11
+				if (Diff(w[8], w[4])) {
+					PIXEL20_C
+				} else {
+					PIXEL20_2
+				}
+				PIXEL21_C
+				if (Diff(w[6], w[8])) {
+					PIXEL12_C
+					PIXEL22_C
+				} else {
+					PIXEL12_3
+					PIXEL22_4
+				}
+				break;
+			}
+			case 235: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+					PIXEL01_C
+				} else {
+					PIXEL00_4
+					PIXEL01_3
+				}
+				PIXEL02_1M
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_1
+				if (Diff(w[8], w[4])) {
+					PIXEL20_C
+				} else {
+					PIXEL20_2
+				}
+				PIXEL21_C
+				PIXEL22_1R
+				break;
+			}
+			case 111: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+				} else {
+					PIXEL00_2
+				}
+				PIXEL01_C
+				PIXEL02_1R
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_1
+				if (Diff(w[8], w[4])) {
+					PIXEL20_C
+					PIXEL21_C
+				} else {
+					PIXEL20_4
+					PIXEL21_3
+				}
+				PIXEL22_1M
+				break;
+			}
+			case 63: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+				} else {
+					PIXEL00_2
+				}
+				PIXEL01_C
+				if (Diff(w[2], w[6])) {
+					PIXEL02_C
+					PIXEL12_C
+				} else {
+					PIXEL02_4
+					PIXEL12_3
+				}
+				PIXEL10_C
+				PIXEL11
+				PIXEL20_1D
+				PIXEL21_1
+				PIXEL22_1M
+				break;
+			}
+			case 159: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+					PIXEL10_C
+				} else {
+					PIXEL00_4
+					PIXEL10_3
+				}
+				PIXEL01_C
+				if (Diff(w[2], w[6])) {
+					PIXEL02_C
+				} else {
+					PIXEL02_2
+				}
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1M
+				PIXEL21_1
+				PIXEL22_1D
+				break;
+			}
+			case 215: {
+				PIXEL00_1L
+				PIXEL01_C
+				if (Diff(w[2], w[6])) {
+					PIXEL02_C
+				} else {
+					PIXEL02_2
+				}
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1M
+				if (Diff(w[6], w[8])) {
+					PIXEL21_C
+					PIXEL22_C
+				} else {
+					PIXEL21_3
+					PIXEL22_4
+				}
+				break;
+			}
+			case 246: {
+				PIXEL00_1M
+				if (Diff(w[2], w[6])) {
+					PIXEL01_C
+					PIXEL02_C
+				} else {
+					PIXEL01_3
+					PIXEL02_4
+				}
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1L
+				PIXEL21_C
+				if (Diff(w[6], w[8])) {
+					PIXEL22_C
+				} else {
+					PIXEL22_2
+				}
+				break;
+			}
+			case 254: {
+				PIXEL00_1M
+				if (Diff(w[2], w[6])) {
+					PIXEL01_C
+					PIXEL02_C
+				} else {
+					PIXEL01_3
+					PIXEL02_4
+				}
+				PIXEL11
+				if (Diff(w[8], w[4])) {
+					PIXEL10_C
+					PIXEL20_C
+				} else {
+					PIXEL10_3
+					PIXEL20_4
+				}
+				if (Diff(w[6], w[8])) {
+					PIXEL12_C
+					PIXEL21_C
+					PIXEL22_C
+				} else {
+					PIXEL12_3
+					PIXEL21_3
+					PIXEL22_2
+				}
+				break;
+			}
+			case 253: {
+				PIXEL00_1U
+				PIXEL01_1
+				PIXEL02_1U
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				if (Diff(w[8], w[4])) {
+					PIXEL20_C
+				} else {
+					PIXEL20_2
+				}
+				PIXEL21_C
+				if (Diff(w[6], w[8])) {
+					PIXEL22_C
+				} else {
+					PIXEL22_2
+				}
+				break;
+			}
+			case 251: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+					PIXEL01_C
+				} else {
+					PIXEL00_4
+					PIXEL01_3
+				}
+				PIXEL02_1M
+				PIXEL11
+				if (Diff(w[8], w[4])) {
+					PIXEL10_C
+					PIXEL20_C
+					PIXEL21_C
+				} else {
+					PIXEL10_3
+					PIXEL20_2
+					PIXEL21_3
+				}
+				if (Diff(w[6], w[8])) {
+					PIXEL12_C
+					PIXEL22_C
+				} else {
+					PIXEL12_3
+					PIXEL22_4
+				}
+				break;
+			}
+			case 239: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+				} else {
+					PIXEL00_2
+				}
+				PIXEL01_C
+				PIXEL02_1R
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_1
+				if (Diff(w[8], w[4])) {
+					PIXEL20_C
+				} else {
+					PIXEL20_2
+				}
+				PIXEL21_C
+				PIXEL22_1R
+				break;
+			}
+			case 127: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+					PIXEL01_C
+					PIXEL10_C
+				} else {
+					PIXEL00_2
+					PIXEL01_3
+					PIXEL10_3
+				}
+				if (Diff(w[2], w[6])) {
+					PIXEL02_C
+					PIXEL12_C
+				} else {
+					PIXEL02_4
+					PIXEL12_3
+				}
+				PIXEL11
+				if (Diff(w[8], w[4])) {
+					PIXEL20_C
+					PIXEL21_C
+				} else {
+					PIXEL20_4
+					PIXEL21_3
+				}
+				PIXEL22_1M
+				break;
+			}
+			case 191: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+				} else {
+					PIXEL00_2
+				}
+				PIXEL01_C
+				if (Diff(w[2], w[6])) {
+					PIXEL02_C
+				} else {
+					PIXEL02_2
+				}
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1D
+				PIXEL21_1
+				PIXEL22_1D
+				break;
+			}
+			case 223: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+					PIXEL10_C
+				} else {
+					PIXEL00_4
+					PIXEL10_3
+				}
+				if (Diff(w[2], w[6])) {
+					PIXEL01_C
+					PIXEL02_C
+					PIXEL12_C
+				} else {
+					PIXEL01_3
+					PIXEL02_2
+					PIXEL12_3
+				}
+				PIXEL11
+				PIXEL20_1M
+				if (Diff(w[6], w[8])) {
+					PIXEL21_C
+					PIXEL22_C
+				} else {
+					PIXEL21_3
+					PIXEL22_4
+				}
+				break;
+			}
+			case 247: {
+				PIXEL00_1L
+				PIXEL01_C
+				if (Diff(w[2], w[6])) {
+					PIXEL02_C
+				} else {
+					PIXEL02_2
+				}
+				PIXEL10_1
+				PIXEL11
+				PIXEL12_C
+				PIXEL20_1L
+				PIXEL21_C
+				if (Diff(w[6], w[8])) {
+					PIXEL22_C
+				} else {
+					PIXEL22_2
+				}
+				break;
+			}
+			case 255: {
+				if (Diff(w[4], w[2])) {
+					PIXEL00_C
+				} else {
+					PIXEL00_2
+				}
+				PIXEL01_C
+				if (Diff(w[2], w[6])) {
+					PIXEL02_C
+				} else {
+					PIXEL02_2
+				}
+				PIXEL10_C
+				PIXEL11
+				PIXEL12_C
+				if (Diff(w[8], w[4])) {
+					PIXEL20_C
+				} else {
+					PIXEL20_2
+				}
+				PIXEL21_C
+				if (Diff(w[6], w[8])) {
+					PIXEL22_C
+				} else {
+					PIXEL22_2
+				}
+				break;
+			}
+			}
+			pIn += INPUT_IMAGE_PIXEL_SIZE_IN_BYTES;
+			pOut += 12;
+		}
+		pOut += BpL + (BpL - Xres * 12);
+		pOut += BpL;
+	}
+}
+
+} // namespace AGS3
diff --git a/engines/ags/lib/hq2x/hq2x3x.h b/engines/ags/lib/hq2x/hq2x3x.h
new file mode 100644
index 0000000000..e3202f7380
--- /dev/null
+++ b/engines/ags/lib/hq2x/hq2x3x.h
@@ -0,0 +1,45 @@
+/* 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 AGS_LIB_HQ2X_HQ2X3X_H
+#define AGS_LIB_HQ2X_HQ2X3X_H
+
+#include "ags/shared/core/platform.h"
+
+namespace AGS3 {
+
+#if AGS_PLATFORM_OS_ANDROID
+void InitLUTs() {
+}
+void hq2x_32(unsigned char *pIn, unsigned char *pOut, int Xres, int Yres, int BpL) {
+}
+void hq3x_32(unsigned char *pIn, unsigned char *pOut, int Xres, int Yres, int BpL) {
+}
+#else
+void InitLUTs();
+void hq2x_32(unsigned char *pIn, unsigned char *pOut, int Xres, int Yres, int BpL);
+void hq3x_32(unsigned char *pIn, unsigned char *pOut, int Xres, int Yres, int BpL);
+#endif
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 7a4fbd1a0c..355c530133 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -26,6 +26,7 @@ MODULE_OBJS = \
 	lib/audio/ogg.o \
 	lib/audio/sound.o \
 	lib/audio/wav.o \
+	lib/hq2x/hq2x3x.o \
 	lib/opengl/opengl.o \
 	lib/std/std.o \
 	lib/system/datetime.o \


Commit: c51cc1dd762986d294cd09c59122a9b6cc736371
    https://github.com/scummvm/scummvm/commit/c51cc1dd762986d294cd09c59122a9b6cc736371
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Add missing files from engine/ac/ to project

Changed paths:
    engines/ags/engine/ac/string.cpp
    engines/ags/engine/ac/system.cpp
    engines/ags/engine/ac/textbox.cpp
    engines/ags/engine/ac/timer.cpp
    engines/ags/engine/ac/translation.cpp
    engines/ags/engine/ac/tree_map.cpp
    engines/ags/engine/ac/viewframe.cpp
    engines/ags/engine/ac/viewport_script.cpp
    engines/ags/engine/ac/walkablearea.cpp
    engines/ags/engine/ac/walkbehind.cpp
    engines/ags/lib/allegro/keyboard.cpp
    engines/ags/lib/allegro/keyboard.h
    engines/ags/lib/std/chrono.h
    engines/ags/module.mk


diff --git a/engines/ags/engine/ac/string.cpp b/engines/ags/engine/ac/string.cpp
index 283be7111f..b1ac38d05c 100644
--- a/engines/ags/engine/ac/string.cpp
+++ b/engines/ags/engine/ac/string.cpp
@@ -21,23 +21,23 @@
  */
 
 //include <cstdio>
-#include "ags/shared/ac/string.h"
+#include "ags/engine/ac/string.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/display.h"
+#include "ags/engine/ac/display.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_translation.h"
-#include "ags/shared/ac/runtime_defines.h"
-#include "ags/shared/ac/dynobj/scriptstring.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_translation.h"
+#include "ags/engine/ac/runtime_defines.h"
+#include "ags/engine/ac/dynobj/scriptstring.h"
 #include "ags/shared/font/fonts.h"
-#include "ags/shared/debugging/debug_log.h"
-#include "ags/shared/script/runtimescriptvalue.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/script/runtimescriptvalue.h"
 #include "ags/shared/util/string_compat.h"
 
 #include "ags/shared/debugging/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-#include "ags/shared/ac/math.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
+#include "ags/engine/ac/math.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/system.cpp b/engines/ags/engine/ac/system.cpp
index 6c52eb2b51..954d8ff9cd 100644
--- a/engines/ags/engine/ac/system.cpp
+++ b/engines/ags/engine/ac/system.cpp
@@ -21,30 +21,30 @@
  */
 
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/gamesetup.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/gamesetup.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/mouse.h"
-#include "ags/shared/ac/string.h"
-#include "ags/shared/ac/system.h"
-#include "ags/shared/ac/dynobj/scriptsystem.h"
-#include "ags/shared/debugging/debug_log.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/mouse.h"
+#include "ags/engine/ac/string.h"
+#include "ags/engine/ac/system.h"
+#include "ags/engine/ac/dynobj/scriptsystem.h"
+#include "ags/engine/debugging/debug_log.h"
 #include "ags/shared/debugging/out.h"
-#include "ags/shared/main/engine.h"
-#include "ags/shared/main/main.h"
-#include "ags/shared/gfx/graphicsdriver.h"
-#include "ags/shared/ac/dynobj/cc_audiochannel.h"
-#include "ags/shared/main/graphics_mode.h"
-#include "ags/shared/ac/global_debug.h"
-#include "ags/shared/ac/global_translation.h"
-#include "ags/shared/media/audio/audio_system.h"
+#include "ags/engine/main/engine.h"
+#include "ags/engine/main/main.h"
+#include "ags/engine/gfx/graphicsdriver.h"
+#include "ags/engine/ac/dynobj/cc_audiochannel.h"
+#include "ags/engine/main/graphics_mode.h"
+#include "ags/engine/ac/global_debug.h"
+#include "ags/engine/ac/global_translation.h"
+#include "ags/engine/media/audio/audio_system.h"
 #include "ags/shared/util/string_compat.h"
 
 #include "ags/shared/debugging/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-#include "ags/shared/ac/dynobj/scriptstring.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
+#include "ags/engine/ac/dynobj/scriptstring.h"
 
 namespace AGS3 {
 
@@ -130,12 +130,7 @@ int System_GetScrollLock() {
 }
 
 void System_SetNumLock(int newValue) {
-	// doesn't work ... maybe allegro doesn't implement this on windows
-	int ledState = key_shifts & (KB_SCROLOCK_FLAG | KB_CAPSLOCK_FLAG);
-	if (newValue) {
-		ledState |= KB_NUMLOCK_FLAG;
-	}
-	set_leds(ledState);
+	// No implementation
 }
 
 int System_GetVsync() {
diff --git a/engines/ags/engine/ac/textbox.cpp b/engines/ags/engine/ac/textbox.cpp
index 9a926db00c..31b35d74cb 100644
--- a/engines/ags/engine/ac/textbox.cpp
+++ b/engines/ags/engine/ac/textbox.cpp
@@ -21,15 +21,15 @@
  */
 
 //include <string.h>
-#include "ags/shared/ac/textbox.h"
+#include "ags/engine/ac/textbox.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/string.h"
+#include "ags/engine/ac/string.h"
 
 #include "ags/shared/debugging/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
-#include "ags/shared/ac/dynobj/scriptstring.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
+#include "ags/engine/ac/dynobj/scriptstring.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/timer.cpp b/engines/ags/engine/ac/timer.cpp
index 08f475228f..5eb0e31c3f 100644
--- a/engines/ags/engine/ac/timer.cpp
+++ b/engines/ags/engine/ac/timer.cpp
@@ -20,16 +20,16 @@
  *
  */
 
-#include "ags/shared/ac/timer.h"
-
+#include "ags/engine/ac/timer.h"
 #include "ags/shared/core/platform.h"
+#include "ags/lib/std/chrono.h"
+#include "ags/lib/std/thread.h"
 #if AGS_PLATFORM_DEBUG && defined (__GNUC__)
 //include <stdio.h>
 //include <execinfo.h>
 //include <unistd.h>
 #endif
-//include <thread>
-#include "ags/shared/platform/base/agsplatformdriver.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/translation.cpp b/engines/ags/engine/ac/translation.cpp
index 64c065b308..7f4612b776 100644
--- a/engines/ags/engine/ac/translation.cpp
+++ b/engines/ags/engine/ac/translation.cpp
@@ -21,15 +21,15 @@
  */
 
 //include <cstdio>
-#include "ags/shared/ac/asset_helper.h"
+#include "ags/engine/ac/asset_helper.h"
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/gamesetup.h"
+#include "ags/engine/ac/gamesetup.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/ac/global_game.h"
-#include "ags/shared/ac/runtime_defines.h"
-#include "ags/shared/ac/translation.h"
-#include "ags/shared/ac/tree_map.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/global_game.h"
+#include "ags/engine/ac/runtime_defines.h"
+#include "ags/engine/ac/translation.h"
+#include "ags/engine/ac/tree_map.h"
 #include "ags/shared/ac/wordsdictionary.h"
 #include "ags/shared/debugging/out.h"
 #include "ags/shared/util/misc.h"
diff --git a/engines/ags/engine/ac/tree_map.cpp b/engines/ags/engine/ac/tree_map.cpp
index d81be33d3b..008796689c 100644
--- a/engines/ags/engine/ac/tree_map.cpp
+++ b/engines/ags/engine/ac/tree_map.cpp
@@ -20,10 +20,9 @@
  *
  */
 
-//include <string.h>
-//include <stdlib.h>
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/tree_map.h"
+#include "ags/engine/ac/tree_map.h"
+#include "common/str.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/viewframe.cpp b/engines/ags/engine/ac/viewframe.cpp
index 5461f4b1f9..6faa57becc 100644
--- a/engines/ags/engine/ac/viewframe.cpp
+++ b/engines/ags/engine/ac/viewframe.cpp
@@ -21,21 +21,21 @@
  */
 
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/viewframe.h"
-#include "ags/shared/debugging/debug_log.h"
+#include "ags/engine/ac/viewframe.h"
+#include "ags/engine/debugging/debug_log.h"
 #include "ags/shared/ac/spritecache.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/shared/script/runtimescriptvalue.h"
-#include "ags/shared/ac/dynobj/cc_audioclip.h"
-#include "ags/shared/ac/draw.h"
+#include "ags/engine/script/runtimescriptvalue.h"
+#include "ags/engine/ac/dynobj/cc_audioclip.h"
+#include "ags/engine/ac/draw.h"
 #include "ags/shared/ac/game_version.h"
-#include "ags/shared/media/audio/audio_system.h"
+#include "ags/engine/media/audio/audio_system.h"
 
 #include "ags/shared/debugging/out.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
 
-} // namespace AGS3
+namespace AGS3 {
 
 using AGS::Shared::Bitmap;
 using AGS::Shared::Graphics;
diff --git a/engines/ags/engine/ac/viewport_script.cpp b/engines/ags/engine/ac/viewport_script.cpp
index 5d0c2672d8..23edbfa232 100644
--- a/engines/ags/engine/ac/viewport_script.cpp
+++ b/engines/ags/engine/ac/viewport_script.cpp
@@ -26,14 +26,14 @@
 //
 //=============================================================================
 
-#include "ags/shared/ac/dynobj/scriptcamera.h"
-#include "ags/shared/ac/dynobj/scriptviewport.h"
-#include "ags/shared/ac/dynobj/scriptuserobject.h"
-#include "ags/shared/ac/draw.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/debugging/debug_log.h"
-#include "ags/shared/script/script_api.h"
-#include "ags/shared/script/script_runtime.h"
+#include "ags/engine/ac/dynobj/scriptcamera.h"
+#include "ags/engine/ac/dynobj/scriptviewport.h"
+#include "ags/engine/ac/dynobj/scriptuserobject.h"
+#include "ags/engine/ac/draw.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/script_runtime.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/walkablearea.cpp b/engines/ags/engine/ac/walkablearea.cpp
index 8d9a62caf2..f8a585a9bc 100644
--- a/engines/ags/engine/ac/walkablearea.cpp
+++ b/engines/ags/engine/ac/walkablearea.cpp
@@ -21,15 +21,15 @@
  */
 
 #include "ags/shared/ac/common.h"
-#include "ags/shared/ac/object.h"
-#include "ags/shared/ac/character.h"
-#include "ags/shared/ac/gamestate.h"
+#include "ags/engine/ac/object.h"
+#include "ags/engine/ac/character.h"
+#include "ags/engine/ac/gamestate.h"
 #include "ags/shared/ac/gamesetupstruct.h"
-#include "ags/shared/ac/object.h"
-#include "ags/shared/ac/room.h"
-#include "ags/shared/ac/roomobject.h"
-#include "ags/shared/ac/roomstatus.h"
-#include "ags/shared/ac/walkablearea.h"
+#include "ags/engine/ac/object.h"
+#include "ags/engine/ac/room.h"
+#include "ags/engine/ac/roomobject.h"
+#include "ags/engine/ac/roomstatus.h"
+#include "ags/engine/ac/walkablearea.h"
 #include "ags/shared/game/roomstruct.h"
 #include "ags/shared/gfx/bitmap.h"
 
diff --git a/engines/ags/engine/ac/walkbehind.cpp b/engines/ags/engine/ac/walkbehind.cpp
index 27b36e1ec4..2c53228b0d 100644
--- a/engines/ags/engine/ac/walkbehind.cpp
+++ b/engines/ags/engine/ac/walkbehind.cpp
@@ -20,11 +20,11 @@
  *
  */
 
-#include "ags/shared/ac/walkbehind.h"
+#include "ags/engine/ac/walkbehind.h"
 #include "ags/shared/ac/common.h"
 #include "ags/shared/ac/common_defines.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/gfx/graphicsdriver.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/engine/gfx/graphicsdriver.h"
 #include "ags/shared/gfx/bitmap.h"
 
 namespace AGS3 {
diff --git a/engines/ags/lib/allegro/keyboard.cpp b/engines/ags/lib/allegro/keyboard.cpp
index 38516df5a6..652e73815e 100644
--- a/engines/ags/lib/allegro/keyboard.cpp
+++ b/engines/ags/lib/allegro/keyboard.cpp
@@ -30,9 +30,11 @@
 namespace AGS3 {
 
 bool key[Common::KEYCODE_LAST];
+uint key_shifts;
 
 int install_keyboard() {
 	Common::fill(&key[0], &key[Common::KEYCODE_LAST], false);
+	key_shifts = 0;
 	return 0;
 }
 
diff --git a/engines/ags/lib/allegro/keyboard.h b/engines/ags/lib/allegro/keyboard.h
index 15a1ce5512..01a85e338b 100644
--- a/engines/ags/lib/allegro/keyboard.h
+++ b/engines/ags/lib/allegro/keyboard.h
@@ -33,6 +33,9 @@ namespace AGS3 {
 #define KB_SHIFT_FLAG Common::KBD_SHIFT
 #define KB_CTRL_FLAG Common::KBD_CTRL
 #define KB_ALT_FLAG Common::KBD_ALT
+#define KB_NUMLOCK_FLAG Common::KBD_NUM
+#define KB_CAPSLOCK_FLAG Common::KBD_CAPS
+#define KB_SCROLOCK_FLAG Common::KBD_SCRL
 
 #define KEY_LSHIFT Common::KEYCODE_LSHIFT
 #define KEY_RSHIFT Common::KEYCODE_RSHIFT
@@ -169,6 +172,7 @@ namespace AGS3 {
 #define __allegro_KEY_AT Common::KEYCODE_AT
 
 extern bool key[Common::KEYCODE_LAST];
+extern uint key_shifts;
 
 AL_FUNC(bool, keyboard_needs_poll, (void));
 AL_FUNC(int, poll_keyboard, (void));
diff --git a/engines/ags/lib/std/chrono.h b/engines/ags/lib/std/chrono.h
index 5bbb2b03fd..a5728bd8da 100644
--- a/engines/ags/lib/std/chrono.h
+++ b/engines/ags/lib/std/chrono.h
@@ -30,7 +30,43 @@ namespace std {
 
 namespace chrono {
 
-typedef uint32 milliseconds;
+class duration {
+private:
+	uint32 _value;
+public:
+	duration() : _value(0) {
+	}
+	duration(uint32 value) : _value(value) {
+	}
+
+	size_t count() const {
+		// durations for ScummVM are hardcoded to be in milliseconds
+		return 1000;
+	}
+
+	operator uint32() const {
+		return _value;
+	}
+
+	inline bool operator>=(const duration &rhs) const {
+		return _value >= rhs._value;
+	}
+};
+
+class milliseconds : public duration {
+public:
+	milliseconds() : duration(0) {}
+	milliseconds(uint32 val) : duration(val) {}
+
+	static milliseconds zero() { return milliseconds(); }
+};
+
+class microseconds : public duration {
+public:
+	microseconds() : duration(0) {}
+	microseconds(long val) : duration(val / 1000) {}
+};
+
 
 struct system_clock {
 };
@@ -50,30 +86,11 @@ struct steady_clock { // wraps QueryPerformanceCounter
 
 using high_resolution_clock = steady_clock;
 
-class duration {
-private:
-	uint32 _value;
-public:
-	duration() : _value(0) {
-	}
-	duration(uint32 value) : _value(value) {
-	}
-
-	size_t count() const {
-		// durations for ScummVM are hardcoded to be in milliseconds
-		return 1000;
-	}
-
-	operator milliseconds() const {
-		return _value;
-	}
-};
-
 template<class T>
 duration duration_cast(T param);
 
-template<milliseconds>
-duration duration_cast(milliseconds param) {
+template<class T>
+duration duration_cast(T param) {
 	return duration(param);
 }
 
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 355c530133..a5fd0e803f 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -212,6 +212,17 @@ MODULE_OBJS = \
     engine/ac/speech.o \
     engine/ac/sprite.o \
     engine/ac/spritecache_engine.o \
+	engine/ac/string.o \
+	engine/ac/sys_events.o \
+	engine/ac/system.o \
+	engine/ac/textbox.o \
+	engine/ac/timer.o \
+	engine/ac/translation.o \
+	engine/ac/tree_map.o \
+	engine/ac/viewframe.o \
+	engine/ac/viewport_script.o \
+	engine/ac/walkablearea.o \
+	engine/ac/walkbehind.o \
 	engine/debugging/consoleoutputtarget.o \
 	engine/debugging/debug.o \
 	engine/debugging/filebasedagsdebugger.o \


Commit: 94a4ef6e7f26efc7689282c37ad9e0583cf891c4
    https://github.com/scummvm/scummvm/commit/94a4ef6e7f26efc7689282c37ad9e0583cf891c4
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added shared/game/main_game_file.cpp to project

Changed paths:
    engines/ags/module.mk
    engines/ags/shared/game/main_game_file.cpp
    engines/ags/shared/game/main_game_file.h


diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index a5fd0e803f..1bca0736cd 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -51,6 +51,7 @@ MODULE_OBJS = \
 	shared/font/wfnfontrenderer.o \
 	shared/game/customproperties.o \
 	shared/game/interactions.o \
+	shared/game/main_game_file.o \
 	shared/game/room_file.o \
 	shared/game/room_file_deprecated.o \
 	shared/game/roomstruct.o \
diff --git a/engines/ags/shared/game/main_game_file.cpp b/engines/ags/shared/game/main_game_file.cpp
index 276aceb53c..48edb9ab8b 100644
--- a/engines/ags/shared/game/main_game_file.cpp
+++ b/engines/ags/shared/game/main_game_file.cpp
@@ -633,8 +633,10 @@ HGameFileError ReadSpriteFlags(LoadedGameEntities &ents, Stream *in, GameDataVer
 			sprcount, (uint32_t)SpriteCache::MAX_SPRITE_INDEX + 1));
 
 	ents.SpriteCount = sprcount;
-	ents.SpriteFlags.reset(new char[sprcount]);
-	in->Read(ents.SpriteFlags.get(), sprcount);
+	ents.SpriteFlags.clear();
+	ents.SpriteFlags.resize(sprcount);
+
+	in->Read(&ents.SpriteFlags[0], sprcount);
 	return HGameFileError::None();
 }
 
diff --git a/engines/ags/shared/game/main_game_file.h b/engines/ags/shared/game/main_game_file.h
index 0a30f115e0..108abf51b1 100644
--- a/engines/ags/shared/game/main_game_file.h
+++ b/engines/ags/shared/game/main_game_file.h
@@ -119,7 +119,7 @@ struct LoadedGameEntities {
 
 	// Original sprite data (when it was read into const-sized arrays)
 	size_t                  SpriteCount;
-	std::unique_ptr<char[]> SpriteFlags;
+	Common::Array<byte>     SpriteFlags;
 
 	// Old dialog support
 	// legacy compiled dialog script of its own format,


Commit: fcce2aa02dc99be14c644ed210375d8eb18e2146
    https://github.com/scummvm/scummvm/commit/fcce2aa02dc99be14c644ed210375d8eb18e2146
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added shared/util/stdio_compat.cpp to project

Changed paths:
    engines/ags/module.mk
    engines/ags/shared/util/stdio_compat.cpp
    engines/ags/shared/util/stdio_compat.h


diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 1bca0736cd..02d2539fda 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -84,6 +84,7 @@ MODULE_OBJS = \
 	shared/util/mutifilelib.o \
 	shared/util/path.o \
 	shared/util/proxystream.o \
+	shared/util/stdio_compat.o \
 	shared/util/stream.o \
 	shared/util/string.o \
 	shared/util/string_compat.o \
diff --git a/engines/ags/shared/util/stdio_compat.cpp b/engines/ags/shared/util/stdio_compat.cpp
index 8a0048364d..e5fe999338 100644
--- a/engines/ags/shared/util/stdio_compat.cpp
+++ b/engines/ags/shared/util/stdio_compat.cpp
@@ -28,7 +28,7 @@
 
 namespace AGS3 {
 
-int	 ags_fseek(Common::Stream *stream, file_off_t offset, int whence) {
+int ags_fseek(Common::Stream *stream, file_off_t offset, int whence) {
 	Common::SeekableReadStream *rs = dynamic_cast<Common::SeekableReadStream *>(stream);
 	Common::SeekableWriteStream *ws = dynamic_cast<Common::SeekableWriteStream *>(stream);
 
@@ -40,8 +40,10 @@ int	 ags_fseek(Common::Stream *stream, file_off_t offset, int whence) {
 		error("Seek on null stream");
 }
 
-file_off_t ags_ftell(FILE *stream) {
-	return stream->pos();
+file_off_t ags_ftell(Common::Stream *stream) {
+	Common::SeekableReadStream *rs = dynamic_cast<Common::SeekableReadStream *>(stream);
+	assert(rs);
+	return rs->pos();
 }
 
 int  ags_file_exists(const char *path) {
diff --git a/engines/ags/shared/util/stdio_compat.h b/engines/ags/shared/util/stdio_compat.h
index c930546b03..f3bfc73999 100644
--- a/engines/ags/shared/util/stdio_compat.h
+++ b/engines/ags/shared/util/stdio_compat.h
@@ -29,10 +29,6 @@ namespace AGS3 {
 
 typedef int64 file_off_t;
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 int  ags_fseek(Common::Stream *stream, file_off_t offset, int whence);
 file_off_t ags_ftell(Common::Stream *stream);
 
@@ -41,10 +37,6 @@ int ags_directory_exists(const char *path);
 int ags_path_exists(const char *path);
 file_off_t ags_file_size(const char *path);
 
-#ifdef __cplusplus
-}
-#endif
-
 } // namespace AGS3
 
 #endif


Commit: cc8bbe896e3757c94cde2704ae1aa212b957ee0e
    https://github.com/scummvm/scummvm/commit/cc8bbe896e3757c94cde2704ae1aa212b957ee0e
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Add in missing code to project

Changed paths:
    engines/ags/engine/plugin/agsplugin.cpp
    engines/ags/engine/plugin/agsplugin.h


diff --git a/engines/ags/engine/plugin/agsplugin.cpp b/engines/ags/engine/plugin/agsplugin.cpp
index f128e0c599..637330b9df 100644
--- a/engines/ags/engine/plugin/agsplugin.cpp
+++ b/engines/ags/engine/plugin/agsplugin.cpp
@@ -156,9 +156,27 @@ std::vector<InbuiltPluginDetails> _registered_builtin_plugins;
 void IAGSEngine::AbortGame(const char *reason) {
 	quit((const char *)reason);
 }
+
 const char *IAGSEngine::GetEngineVersion() {
 	return get_engine_version();
 }
+
+#ifdef WINDOWS_VERSION
+
+HWND IAGSEngine::GetWindowHandle() {
+	return (HWND)0;
+}
+
+LPDIRECTDRAW2 IAGSEngine::GetDirectDraw2() {
+	return nullptr;
+}
+
+LPDIRECTDRAWSURFACE2 IAGSEngine::GetBitmapSurface(BITMAP *) {
+	return nullptr;
+}
+
+#endif
+
 void IAGSEngine::RegisterScriptFunction(const char *name, void *addy) {
 	ccAddExternalPluginFunction(name, addy);
 }
diff --git a/engines/ags/engine/plugin/agsplugin.h b/engines/ags/engine/plugin/agsplugin.h
index 6b40b888a4..f38aca8c99 100644
--- a/engines/ags/engine/plugin/agsplugin.h
+++ b/engines/ags/engine/plugin/agsplugin.h
@@ -59,7 +59,7 @@ typedef int HWND;
 
 // This file is distributed as part of the Plugin API docs, so
 // ensure that WINDOWS_VERSION is defined (if applicable)
-#if defined(_WIN32)
+#if AGS_PLATFORM_OS_WINDOWS
 #undef WINDOWS_VERSION
 #define WINDOWS_VERSION
 #endif


Commit: f07fc5d7b8e55c1bea7d60cb9a2e4bf83d139a9e
    https://github.com/scummvm/scummvm/commit/f07fc5d7b8e55c1bea7d60cb9a2e4bf83d139a9e
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added stubs for DUH player

Changed paths:
  A engines/ags/lib/audio/aldumb.cpp
  A engines/ags/lib/audio/aldumb.h
  A engines/ags/lib/audio/dumb.h
  R engines/ags/lib/aldumb.h
  R engines/ags/lib/dumb.h
    engines/ags/engine/ac/file.cpp
    engines/ags/engine/media/audio/clip_mydumbmod.h
    engines/ags/module.mk


diff --git a/engines/ags/engine/ac/file.cpp b/engines/ags/engine/ac/file.cpp
index cfee54d31c..ae826d9489 100644
--- a/engines/ags/engine/ac/file.cpp
+++ b/engines/ags/engine/ac/file.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/lib/aldumb.h"
+#include "ags/lib/audio/aldumb.h"
 #include "ags/engine/ac/asset_helper.h"
 #include "ags/shared/ac/audiocliptype.h"
 #include "ags/engine/ac/file.h"
diff --git a/engines/ags/engine/media/audio/clip_mydumbmod.h b/engines/ags/engine/media/audio/clip_mydumbmod.h
index 927eee6f89..75c0a0433b 100644
--- a/engines/ags/engine/media/audio/clip_mydumbmod.h
+++ b/engines/ags/engine/media/audio/clip_mydumbmod.h
@@ -23,7 +23,7 @@
 #ifndef AGS_ENGINE_MEDIA_AUDIO_CLIP_MYDUMBMOD_H
 #define AGS_ENGINE_MEDIA_AUDIO_CLIP_MYDUMBMOD_H
 
-#include "ags/lib/aldumb.h"
+#include "ags/lib/audio/aldumb.h"
 #include "ags/engine/media/audio/soundclip.h"
 
 namespace AGS3 {
diff --git a/engines/ags/lib/audio/aldumb.cpp b/engines/ags/lib/audio/aldumb.cpp
new file mode 100644
index 0000000000..b1eeba1b14
--- /dev/null
+++ b/engines/ags/lib/audio/aldumb.cpp
@@ -0,0 +1,133 @@
+/* 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 "ags/lib/audio/aldumb.h"
+
+namespace AGS3 {
+
+void dumb_register_packfiles() {
+}
+
+DUMBFILE *dumbfile_open_packfile(PACKFILE *p) {
+	warning("TODO: dumbfile_open_packfile");
+	return nullptr;
+}
+
+DUMBFILE *dumbfile_from_packfile(PACKFILE *p) {
+	warning("TODO: dumbfile_from_packfile");
+	return nullptr;
+}
+
+void dumb_register_dat_duh(long type) {
+	warning("TODO: dumb_register_dat_duh");
+}
+
+void dumb_register_dat_it(long type) {
+	warning("TODO: dumb_register_dat_it");
+}
+
+void dumb_register_dat_xm(long type) {
+	warning("TODO: dumb_register_dat_xm");
+}
+
+void dumb_register_dat_s3m(long type) {
+	warning("TODO: dumb_register_dat_s3m");
+}
+
+void dumb_register_dat_mod(long type) {
+	warning("TODO: dumb_register_dat_mod");
+}
+
+void dumb_register_dat_it_quick(long type) {
+	warning("TODO: dumb_register_dat_it_quick");
+}
+
+void dumb_register_dat_xm_quick(long type) {
+	warning("TODO: dumb_register_dat_xm_quick");
+}
+
+void dumb_register_dat_s3m_quick(long type) {
+	warning("TODO: dumb_register_dat_s3m_quick");
+}
+
+void dumb_register_dat_mod_quick(long type) {
+	warning("TODO: dumb_register_dat_mod_quick");
+}
+
+/* DUH Playing Functions */
+
+AL_DUH_PLAYER *al_start_duh(DUH *duh, int n_channels, long pos, float volume, long bufsize, int freq) {
+	warning("TODO: al_start_duh");
+	return nullptr;
+}
+
+void al_stop_duh(AL_DUH_PLAYER *dp) {
+	warning("TODO: al_stop_duh");
+}
+
+void al_pause_duh(AL_DUH_PLAYER *dp) {
+	warning("TODO: al_pause_duh");
+}
+
+void al_resume_duh(AL_DUH_PLAYER *dp) {
+	warning("TODO: al_resume_duh");
+}
+
+void al_duh_set_priority(AL_DUH_PLAYER *dp, int priority) {
+	warning("TODO: al_duh_set_priority");
+}
+
+void al_duh_set_volume(AL_DUH_PLAYER *dp, float volume) {
+	warning("TODO: al_duh_set_volume");
+}
+
+float al_duh_get_volume(AL_DUH_PLAYER *dp) {
+	warning("TODO: al_duh_get_volume");
+	return 0;
+}
+
+int al_poll_duh(AL_DUH_PLAYER *dp) {
+	warning("TODO: al_poll_duh");
+	return 0;
+}
+
+long al_duh_get_position(AL_DUH_PLAYER *dp) {
+	warning("TODO: al_duh_get_position");
+	return 0;
+}
+
+AL_DUH_PLAYER *al_duh_encapsulate_sigrenderer(DUH_SIGRENDERER *sigrenderer, float volume, long bufsize, int freq) {
+	warning("TODO: al_duh_encapsulate_sigrenderer");
+	return nullptr;
+}
+
+DUH_SIGRENDERER *al_duh_get_sigrenderer(AL_DUH_PLAYER *dp) {
+	warning("TODO: al_duh_get_sigrenderer");
+	return nullptr;
+}
+
+DUH_SIGRENDERER *al_duh_decompose_to_sigrenderer(AL_DUH_PLAYER *dp) {
+	warning("TODO: al_duh_decompose_to_sigrenderer");
+	return nullptr;
+}
+
+} // namespace AGS3
diff --git a/engines/ags/lib/aldumb.h b/engines/ags/lib/audio/aldumb.h
similarity index 97%
rename from engines/ags/lib/aldumb.h
rename to engines/ags/lib/audio/aldumb.h
index b72dc823d8..478760e1bc 100644
--- a/engines/ags/lib/aldumb.h
+++ b/engines/ags/lib/audio/aldumb.h
@@ -43,14 +43,10 @@
 #define AGS_LIB_ALDUMB_H
 
 #include "ags/lib/allegro.h"
-#include "ags/lib/dumb.h"
+#include "ags/lib/audio/dumb.h"
 
 namespace AGS3 {
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 /* Packfile Support */
 
 void dumb_register_packfiles(void);
@@ -109,10 +105,6 @@ DUH_SIGRENDERER *al_duh_decompose_to_sigrenderer(AL_DUH_PLAYER *dp);
 
 #endif
 
-#ifdef __cplusplus
-}
-#endif
-
 } // namespace AGS3
 
 #endif
diff --git a/engines/ags/lib/dumb.h b/engines/ags/lib/audio/dumb.h
similarity index 100%
rename from engines/ags/lib/dumb.h
rename to engines/ags/lib/audio/dumb.h
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 02d2539fda..d5a605bc36 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -19,7 +19,7 @@ MODULE_OBJS = \
 	lib/allegro/mouse.o \
 	lib/allegro/system.o \
 	lib/allegro/unicode.o \
-	lib/audio/audio.o \
+	lib/audio/aldumb.o \
 	lib/audio/digi.o \
 	lib/audio/midi.o \
 	lib/audio/mp3.o \


Commit: 712ef7ed064255f8f98b499dacdc13e24ad67d69
    https://github.com/scummvm/scummvm/commit/712ef7ed064255f8f98b499dacdc13e24ad67d69
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Adding DUMBFILE methods to project

Changed paths:
  A engines/ags/lib/dumb-0.9.2/dumbfile.cpp
  A engines/ags/lib/dumb-0.9.2/dumbfile.h
  R engines/ags/lib/audio/dumb.h
    engines/ags/lib/audio/aldumb.h
    engines/ags/module.mk


diff --git a/engines/ags/lib/audio/aldumb.h b/engines/ags/lib/audio/aldumb.h
index 478760e1bc..61ede22bd8 100644
--- a/engines/ags/lib/audio/aldumb.h
+++ b/engines/ags/lib/audio/aldumb.h
@@ -43,7 +43,7 @@
 #define AGS_LIB_ALDUMB_H
 
 #include "ags/lib/allegro.h"
-#include "ags/lib/audio/dumb.h"
+#include "ags/lib/dumb-0.9.2/dumbfile.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/lib/dumb-0.9.2/dumbfile.cpp b/engines/ags/lib/dumb-0.9.2/dumbfile.cpp
new file mode 100644
index 0000000000..60d82b5801
--- /dev/null
+++ b/engines/ags/lib/dumb-0.9.2/dumbfile.cpp
@@ -0,0 +1,409 @@
+/* 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.
+ *
+ */
+
+/*  _______         ____    __         ___    ___
+ * \    _  \       \    /  \  /       \   \  /   /       '   '  '
+ *  |  | \  \       |  |    ||         |   \/   |         .      .
+ *  |  |  |  |      |  |    ||         ||\  /|  |
+ *  |  |  |  |      |  |    ||         || \/ |  |         '  '  '
+ *  |  |  |  |      |  |    ||         ||    |  |         .      .
+ *  |  |_/  /        \  \__//          ||    |  |
+ * /_______/ynamic    \____/niversal  /__\  /____\usic   /|  .  . ibliotheque
+ *                                                      /  \
+ *                                                     / .  \
+ * dumbfile.c - Hookable, strictly sequential         / / \  \
+ *              file input functions.                | <  /   \_
+ *                                                   |  \/ /\   /
+ * By entheh.                                         \_  /  > /
+ *                                                      | \ / /
+ *                                                      |  ' /
+ *                                                       \__/
+ */
+
+//include <stdlib.h>
+
+#include "ags/lib/dumb-0.9.2/dumbfile.h"
+
+namespace AGS3 {
+
+static DUMBFILE_SYSTEM *the_dfs = NULL;
+
+
+
+void register_dumbfile_system(DUMBFILE_SYSTEM *dfs) {
+	ASSERT(dfs);
+	ASSERT(dfs->open);
+	ASSERT(dfs->getc);
+	ASSERT(dfs->close);
+	the_dfs = dfs;
+}
+
+
+
+struct DUMBFILE {
+	DUMBFILE_SYSTEM *dfs;
+	void *file;
+	long pos;
+};
+
+
+
+DUMBFILE *dumbfile_open(const char *filename) {
+	DUMBFILE *f;
+
+	ASSERT(the_dfs);
+
+	f = (DUMBFILE *)malloc(sizeof(DUMBFILE));
+
+	if (!f)
+		return NULL;
+
+	f->dfs = the_dfs;
+
+	f->file = (*the_dfs->open)(filename);
+
+	if (!f->file) {
+		free(f);
+		return NULL;
+	}
+
+	f->pos = 0;
+
+	return f;
+}
+
+
+
+DUMBFILE *dumbfile_open_ex(void *file, DUMBFILE_SYSTEM *dfs) {
+	DUMBFILE *f;
+
+	ASSERT(dfs);
+	ASSERT(dfs->getc);
+	ASSERT(file);
+
+	f = (DUMBFILE *)malloc(sizeof(DUMBFILE));
+
+	if (!f) {
+		if (dfs->close)
+			(*dfs->close)(file);
+		return NULL;
+	}
+
+	f->dfs = dfs;
+	f->file = file;
+
+	f->pos = 0;
+
+	return f;
+}
+
+
+
+long dumbfile_pos(DUMBFILE *f) {
+	ASSERT(f);
+
+	return f->pos;
+}
+
+
+
+int dumbfile_skip(DUMBFILE *f, long n) {
+	int rv;
+
+	ASSERT(f);
+	ASSERT(n >= 0);
+
+	if (f->pos < 0)
+		return -1;
+
+	f->pos += n;
+
+	if (f->dfs->skip) {
+		rv = (*f->dfs->skip)(f->file, n);
+		if (rv) {
+			f->pos = -1;
+			return rv;
+		}
+	} else {
+		while (n) {
+			rv = (*f->dfs->getc)(f->file);
+			if (rv < 0) {
+				f->pos = -1;
+				return rv;
+			}
+			n--;
+		}
+	}
+
+	return 0;
+}
+
+
+
+int dumbfile_getc(DUMBFILE *f) {
+	int rv;
+
+	ASSERT(f);
+
+	if (f->pos < 0)
+		return -1;
+
+	rv = (*f->dfs->getc)(f->file);
+
+	if (rv < 0) {
+		f->pos = -1;
+		return rv;
+	}
+
+	f->pos++;
+
+	return rv;
+}
+
+
+
+int dumbfile_igetw(DUMBFILE *f) {
+	int l, h;
+
+	ASSERT(f);
+
+	if (f->pos < 0)
+		return -1;
+
+	l = (*f->dfs->getc)(f->file);
+	if (l < 0) {
+		f->pos = -1;
+		return l;
+	}
+
+	h = (*f->dfs->getc)(f->file);
+	if (h < 0) {
+		f->pos = -1;
+		return h;
+	}
+
+	f->pos += 2;
+
+	return l | (h << 8);
+}
+
+
+
+int dumbfile_mgetw(DUMBFILE *f) {
+	int l, h;
+
+	ASSERT(f);
+
+	if (f->pos < 0)
+		return -1;
+
+	h = (*f->dfs->getc)(f->file);
+	if (h < 0) {
+		f->pos = -1;
+		return h;
+	}
+
+	l = (*f->dfs->getc)(f->file);
+	if (l < 0) {
+		f->pos = -1;
+		return l;
+	}
+
+	f->pos += 2;
+
+	return l | (h << 8);
+}
+
+
+
+long dumbfile_igetl(DUMBFILE *f) {
+	unsigned long rv, b;
+
+	ASSERT(f);
+
+	if (f->pos < 0)
+		return -1;
+
+	rv = (*f->dfs->getc)(f->file);
+	if ((signed long)rv < 0) {
+		f->pos = -1;
+		return rv;
+	}
+
+	b = (*f->dfs->getc)(f->file);
+	if ((signed long)b < 0) {
+		f->pos = -1;
+		return b;
+	}
+	rv |= b << 8;
+
+	b = (*f->dfs->getc)(f->file);
+	if ((signed long)b < 0) {
+		f->pos = -1;
+		return b;
+	}
+	rv |= b << 16;
+
+	b = (*f->dfs->getc)(f->file);
+	if ((signed long)b < 0) {
+		f->pos = -1;
+		return b;
+	}
+	rv |= b << 24;
+
+	f->pos += 4;
+
+	return rv;
+}
+
+
+
+long dumbfile_mgetl(DUMBFILE *f) {
+	unsigned long rv, b;
+
+	ASSERT(f);
+
+	if (f->pos < 0)
+		return -1;
+
+	rv = (*f->dfs->getc)(f->file);
+	if ((signed long)rv < 0) {
+		f->pos = -1;
+		return rv;
+	}
+	rv <<= 24;
+
+	b = (*f->dfs->getc)(f->file);
+	if ((signed long)b < 0) {
+		f->pos = -1;
+		return b;
+	}
+	rv |= b << 16;
+
+	b = (*f->dfs->getc)(f->file);
+	if ((signed long)b < 0) {
+		f->pos = -1;
+		return b;
+	}
+	rv |= b << 8;
+
+	b = (*f->dfs->getc)(f->file);
+	if ((signed long)b < 0) {
+		f->pos = -1;
+		return b;
+	}
+	rv |= b;
+
+	f->pos += 4;
+
+	return rv;
+}
+
+
+
+unsigned long dumbfile_cgetul(DUMBFILE *f) {
+	unsigned long rv = 0;
+	int v;
+
+	do {
+		v = dumbfile_getc(f);
+
+		if (v < 0)
+			return v;
+
+		rv <<= 7;
+		rv |= v & 0x7F;
+	} while (v & 0x80);
+
+	return rv;
+}
+
+
+
+signed long dumbfile_cgetsl(DUMBFILE *f) {
+	unsigned long rv = dumbfile_cgetul(f);
+
+	if (f->pos < 0)
+		return rv;
+
+	return (rv >> 1) | (rv << 31);
+}
+
+
+
+long dumbfile_getnc(char *ptr, long n, DUMBFILE *f) {
+	long rv;
+
+	ASSERT(f);
+	ASSERT(n >= 0);
+
+	if (f->pos < 0)
+		return -1;
+
+	if (f->dfs->getnc) {
+		rv = (*f->dfs->getnc)(ptr, n, f->file);
+		if (rv < n) {
+			f->pos = -1;
+			return MAX(rv, 0);
+		}
+	} else {
+		for (rv = 0; rv < n; rv++) {
+			int c = (*f->dfs->getc)(f->file);
+			if (c < 0) {
+				f->pos = -1;
+				return rv;
+			}
+			*ptr++ = c;
+		}
+	}
+
+	f->pos += rv;
+
+	return rv;
+}
+
+
+
+int dumbfile_error(DUMBFILE *f) {
+	ASSERT(f);
+
+	return f->pos < 0;
+}
+
+
+
+int dumbfile_close(DUMBFILE *f) {
+	int rv;
+
+	ASSERT(f);
+
+	rv = f->pos < 0;
+
+	if (f->dfs->close)
+		(*f->dfs->close)(f->file);
+
+	free(f);
+
+	return rv;
+}
+
+} // namespace AGS3
diff --git a/engines/ags/lib/audio/dumb.h b/engines/ags/lib/dumb-0.9.2/dumbfile.h
similarity index 99%
rename from engines/ags/lib/audio/dumb.h
rename to engines/ags/lib/dumb-0.9.2/dumbfile.h
index a74ffdf0ba..2099c27b48 100644
--- a/engines/ags/lib/audio/dumb.h
+++ b/engines/ags/lib/dumb-0.9.2/dumbfile.h
@@ -39,8 +39,8 @@
  *                                                       \__/
  */
 
-#ifndef AGS_LIB_DUMB_H
-#define AGS_LIB_DUMB_H
+#ifndef AGS_LIB_DUMB_DUMBFILE_H
+#define AGS_LIB_DUMB_DUMBFILE_H
 
 #include "common/stream.h"
 
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index d5a605bc36..dd57d91c4c 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -26,6 +26,7 @@ MODULE_OBJS = \
 	lib/audio/ogg.o \
 	lib/audio/sound.o \
 	lib/audio/wav.o \
+	lib/dumb-0.9.2/dumbfile.o \
 	lib/hq2x/hq2x3x.o \
 	lib/opengl/opengl.o \
 	lib/std/std.o \


Commit: b5ce4bc97aaba60e1e13a089e72c49ab92d36b77
    https://github.com/scummvm/scummvm/commit/b5ce4bc97aaba60e1e13a089e72c49ab92d36b77
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Add missing dll stub methods to project

Changed paths:
    engines/ags/module.mk


diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index dd57d91c4c..0e97a279be 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -286,6 +286,7 @@ MODULE_OBJS = \
 	engine/platform/base/agsplatformdriver.o \
 	engine/platform/linux/acpllnx.o \
 	engine/plugin/agsplugin.o \
+	engine/plugin/library.o \
 	engine/plugin/pluginobjectreader.o \
 	engine/script/cc_instance.o \
 	engine/script/executingscript.o \


Commit: 37148c0f1961ae2f366bf8b6f0e83b7a3c8aba77
    https://github.com/scummvm/scummvm/commit/37148c0f1961ae2f366bf8b6f0e83b7a3c8aba77
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added color blending methods

Changed paths:
  A engines/ags/lib/allegro/colblend.cpp
  A engines/ags/lib/allegro/colblend.h
    engines/ags/engine/gfx/blender.cpp
    engines/ags/lib/allegro.h


diff --git a/engines/ags/engine/gfx/blender.cpp b/engines/ags/engine/gfx/blender.cpp
index 549c74f53c..b800d9bb51 100644
--- a/engines/ags/engine/gfx/blender.cpp
+++ b/engines/ags/engine/gfx/blender.cpp
@@ -24,21 +24,10 @@
 #include "ags/engine/gfx/blender.h"
 #include "ags/shared/util/wgt2allg.h"
 #include "ags/lib/allegro/color.h"
+#include "ags/lib/allegro/colblend.h"
 
 namespace AGS3 {
 
-extern "C" {
-	// Fallback routine for when we don't have anything better to do.
-	unsigned long _blender_black(unsigned long x, unsigned long y, unsigned long n);
-	// Standard Allegro 4 trans blenders for 16 and 15-bit color modes
-	unsigned long _blender_trans15(unsigned long x, unsigned long y, unsigned long n);
-	unsigned long _blender_trans16(unsigned long x, unsigned long y, unsigned long n);
-	// Standard Allegro 4 alpha blenders for 16 and 15-bit color modes
-	unsigned long _blender_alpha15(unsigned long x, unsigned long y, unsigned long n);
-	unsigned long _blender_alpha16(unsigned long x, unsigned long y, unsigned long n);
-	unsigned long _blender_alpha24(unsigned long x, unsigned long y, unsigned long n);
-}
-
 // the allegro "inline" ones are not actually inline, so #define
 // over them to speed it up
 #define getr32(xx) ((xx >> _rgb_r_shift_32) & 0xFF)
diff --git a/engines/ags/lib/allegro.h b/engines/ags/lib/allegro.h
index 9952637ada..879029da10 100644
--- a/engines/ags/lib/allegro.h
+++ b/engines/ags/lib/allegro.h
@@ -27,6 +27,7 @@
 
 #include "ags/lib/allegro/alconfig.h"
 #include "ags/lib/allegro/base.h"
+#include "ags/lib/allegro/colblend.h"
 #include "ags/lib/allegro/color.h"
 #include "ags/lib/allegro/config.h"
 #include "ags/lib/allegro/draw.h"
diff --git a/engines/ags/lib/allegro/colblend.cpp b/engines/ags/lib/allegro/colblend.cpp
new file mode 100644
index 0000000000..4b623a190d
--- /dev/null
+++ b/engines/ags/lib/allegro/colblend.cpp
@@ -0,0 +1,115 @@
+/* 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 "ags/lib/allegro/colblend.h"
+
+namespace AGS3 {
+
+unsigned long _blender_black(unsigned long x, unsigned long y, unsigned long n) {
+	return 0;
+}
+
+unsigned long _blender_trans15(unsigned long x, unsigned long y, unsigned long n) {
+	unsigned long result;
+
+	if (n)
+		n = (n + 1) / 8;
+
+	x = ((x & 0xFFFF) | (x << 16)) & 0x3E07C1F;
+	y = ((y & 0xFFFF) | (y << 16)) & 0x3E07C1F;
+
+	result = ((x - y) * n / 32 + y) & 0x3E07C1F;
+
+	return ((result & 0xFFFF) | (result >> 16));
+}
+
+unsigned long _blender_trans16(unsigned long x, unsigned long y, unsigned long n) {
+	unsigned long result;
+
+	if (n)
+		n = (n + 1) / 8;
+
+	x = ((x & 0xFFFF) | (x << 16)) & 0x7E0F81F;
+	y = ((y & 0xFFFF) | (y << 16)) & 0x7E0F81F;
+
+	result = ((x - y) * n / 32 + y) & 0x7E0F81F;
+
+	return ((result & 0xFFFF) | (result >> 16));
+}
+
+unsigned long _blender_alpha15(unsigned long x, unsigned long y, unsigned long n) {
+	unsigned long result;
+
+	n = geta32(x);
+
+	if (n)
+		n = (n + 1) / 8;
+
+	x = makecol15(getr32(x), getg32(x), getb32(x));
+
+	x = (x | (x << 16)) & 0x3E07C1F;
+	y = ((y & 0xFFFF) | (y << 16)) & 0x3E07C1F;
+
+	result = ((x - y) * n / 32 + y) & 0x3E07C1F;
+
+	return ((result & 0xFFFF) | (result >> 16));
+}
+
+unsigned long _blender_alpha16(unsigned long x, unsigned long y, unsigned long n) {
+	unsigned long result;
+
+	n = geta32(x);
+
+	if (n)
+		n = (n + 1) / 8;
+
+	x = makecol16(getr32(x), getg32(x), getb32(x));
+
+	x = (x | (x << 16)) & 0x7E0F81F;
+	y = ((y & 0xFFFF) | (y << 16)) & 0x7E0F81F;
+
+	result = ((x - y) * n / 32 + y) & 0x7E0F81F;
+
+	return ((result & 0xFFFF) | (result >> 16));
+}
+
+unsigned long _blender_alpha24(unsigned long x, unsigned long y, unsigned long n) {
+	unsigned long xx = makecol24(getr32(x), getg32(x), getb32(x));
+	unsigned long res, g;
+
+	n = geta32(x);
+
+	if (n)
+		n++;
+
+	res = ((xx & 0xFF00FF) - (y & 0xFF00FF)) * n / 256 + y;
+	y &= 0xFF00;
+	xx &= 0xFF00;
+	g = (xx - y) * n / 256 + y;
+
+	res &= 0xFF00FF;
+	g &= 0xFF00;
+
+	return res | g;
+}
+
+} // namespace AGS3
diff --git a/engines/ags/lib/allegro/colblend.h b/engines/ags/lib/allegro/colblend.h
new file mode 100644
index 0000000000..60eaea8e32
--- /dev/null
+++ b/engines/ags/lib/allegro/colblend.h
@@ -0,0 +1,41 @@
+/* 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 AGS_LIB_ALLEGRO_COLBLEND_H
+#define AGS_LIB_ALLEGRO_COLBLEND_H
+
+#include "ags/lib/allegro/alconfig.h"
+
+namespace AGS3 {
+
+extern unsigned long _blender_black(unsigned long x, unsigned long y, unsigned long n);
+
+extern unsigned long _blender_trans15(unsigned long x, unsigned long y, unsigned long n);
+extern unsigned long _blender_trans16(unsigned long x, unsigned long y, unsigned long n);
+
+extern unsigned long _blender_alpha15(unsigned long x, unsigned long y, unsigned long n);
+extern unsigned long _blender_alpha16(unsigned long x, unsigned long y, unsigned long n);
+extern unsigned long _blender_alpha24(unsigned long x, unsigned long y, unsigned long n);
+
+} // namespace AGS3
+
+#endif


Commit: ceaae27126c9639566c8e3965bccfa364efe6f53
    https://github.com/scummvm/scummvm/commit/ceaae27126c9639566c8e3965bccfa364efe6f53
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Adding missing methods

Changed paths:
  A engines/ags/lib/allegro/math.cpp
  A engines/ags/lib/dumb-0.9.2/it.h
  A engines/ags/lib/dumb-0.9.2/readxm.cpp
    engines/ags/engine/gfx/gfxfilter_aaogl.cpp


diff --git a/engines/ags/engine/gfx/gfxfilter_aaogl.cpp b/engines/ags/engine/gfx/gfxfilter_aaogl.cpp
index 0bec89329c..ac26f29557 100644
--- a/engines/ags/engine/gfx/gfxfilter_aaogl.cpp
+++ b/engines/ags/engine/gfx/gfxfilter_aaogl.cpp
@@ -22,7 +22,7 @@
 
 #include "ags/shared/core/platform.h"
 
-#if AGS_PLATFORM_OS_WINDOWS || AGS_PLATFORM_OS_ANDROID || AGS_PLATFORM_OS_IOS || AGS_PLATFORM_OS_LINUX
+#if 1
 
 #include "ags/shared/gfx/gfxfilter_aaogl.h"
 #include "ags/shared/ogl_headers.h"
diff --git a/engines/ags/lib/allegro/math.cpp b/engines/ags/lib/allegro/math.cpp
new file mode 100644
index 0000000000..88c1a5eafa
--- /dev/null
+++ b/engines/ags/lib/allegro/math.cpp
@@ -0,0 +1,286 @@
+/* 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 AGS_LIB_ALLEGRO_MATH_H
+#define AGS_LIB_ALLEGRO_MATH_H
+
+#include "ags/lib/allegro/fixed.h"
+
+namespace AGS3 {
+
+
+fixed _cos_tbl[512] =
+{
+	/* precalculated fixed point (16.16) cosines for a full circle (0-255) */
+
+	65536L,  65531L,  65516L,  65492L,  65457L,  65413L,  65358L,  65294L,
+	65220L,  65137L,  65043L,  64940L,  64827L,  64704L,  64571L,  64429L,
+	64277L,  64115L,  63944L,  63763L,  63572L,  63372L,  63162L,  62943L,
+	62714L,  62476L,  62228L,  61971L,  61705L,  61429L,  61145L,  60851L,
+	60547L,  60235L,  59914L,  59583L,  59244L,  58896L,  58538L,  58172L,
+	57798L,  57414L,  57022L,  56621L,  56212L,  55794L,  55368L,  54934L,
+	54491L,  54040L,  53581L,  53114L,  52639L,  52156L,  51665L,  51166L,
+	50660L,  50146L,  49624L,  49095L,  48559L,  48015L,  47464L,  46906L,
+	46341L,  45769L,  45190L,  44604L,  44011L,  43412L,  42806L,  42194L,
+	41576L,  40951L,  40320L,  39683L,  39040L,  38391L,  37736L,  37076L,
+	36410L,  35738L,  35062L,  34380L,  33692L,  33000L,  32303L,  31600L,
+	30893L,  30182L,  29466L,  28745L,  28020L,  27291L,  26558L,  25821L,
+	25080L,  24335L,  23586L,  22834L,  22078L,  21320L,  20557L,  19792L,
+	19024L,  18253L,  17479L,  16703L,  15924L,  15143L,  14359L,  13573L,
+	12785L,  11996L,  11204L,  10411L,  9616L,   8820L,   8022L,   7224L,
+	6424L,   5623L,   4821L,   4019L,   3216L,   2412L,   1608L,   804L,
+	0L,      -804L,   -1608L,  -2412L,  -3216L,  -4019L,  -4821L,  -5623L,
+	-6424L,  -7224L,  -8022L,  -8820L,  -9616L,  -10411L, -11204L, -11996L,
+	-12785L, -13573L, -14359L, -15143L, -15924L, -16703L, -17479L, -18253L,
+	-19024L, -19792L, -20557L, -21320L, -22078L, -22834L, -23586L, -24335L,
+	-25080L, -25821L, -26558L, -27291L, -28020L, -28745L, -29466L, -30182L,
+	-30893L, -31600L, -32303L, -33000L, -33692L, -34380L, -35062L, -35738L,
+	-36410L, -37076L, -37736L, -38391L, -39040L, -39683L, -40320L, -40951L,
+	-41576L, -42194L, -42806L, -43412L, -44011L, -44604L, -45190L, -45769L,
+	-46341L, -46906L, -47464L, -48015L, -48559L, -49095L, -49624L, -50146L,
+	-50660L, -51166L, -51665L, -52156L, -52639L, -53114L, -53581L, -54040L,
+	-54491L, -54934L, -55368L, -55794L, -56212L, -56621L, -57022L, -57414L,
+	-57798L, -58172L, -58538L, -58896L, -59244L, -59583L, -59914L, -60235L,
+	-60547L, -60851L, -61145L, -61429L, -61705L, -61971L, -62228L, -62476L,
+	-62714L, -62943L, -63162L, -63372L, -63572L, -63763L, -63944L, -64115L,
+	-64277L, -64429L, -64571L, -64704L, -64827L, -64940L, -65043L, -65137L,
+	-65220L, -65294L, -65358L, -65413L, -65457L, -65492L, -65516L, -65531L,
+	-65536L, -65531L, -65516L, -65492L, -65457L, -65413L, -65358L, -65294L,
+	-65220L, -65137L, -65043L, -64940L, -64827L, -64704L, -64571L, -64429L,
+	-64277L, -64115L, -63944L, -63763L, -63572L, -63372L, -63162L, -62943L,
+	-62714L, -62476L, -62228L, -61971L, -61705L, -61429L, -61145L, -60851L,
+	-60547L, -60235L, -59914L, -59583L, -59244L, -58896L, -58538L, -58172L,
+	-57798L, -57414L, -57022L, -56621L, -56212L, -55794L, -55368L, -54934L,
+	-54491L, -54040L, -53581L, -53114L, -52639L, -52156L, -51665L, -51166L,
+	-50660L, -50146L, -49624L, -49095L, -48559L, -48015L, -47464L, -46906L,
+	-46341L, -45769L, -45190L, -44604L, -44011L, -43412L, -42806L, -42194L,
+	-41576L, -40951L, -40320L, -39683L, -39040L, -38391L, -37736L, -37076L,
+	-36410L, -35738L, -35062L, -34380L, -33692L, -33000L, -32303L, -31600L,
+	-30893L, -30182L, -29466L, -28745L, -28020L, -27291L, -26558L, -25821L,
+	-25080L, -24335L, -23586L, -22834L, -22078L, -21320L, -20557L, -19792L,
+	-19024L, -18253L, -17479L, -16703L, -15924L, -15143L, -14359L, -13573L,
+	-12785L, -11996L, -11204L, -10411L, -9616L,  -8820L,  -8022L,  -7224L,
+	-6424L,  -5623L,  -4821L,  -4019L,  -3216L,  -2412L,  -1608L,  -804L,
+	0L,      804L,    1608L,   2412L,   3216L,   4019L,   4821L,   5623L,
+	6424L,   7224L,   8022L,   8820L,   9616L,   10411L,  11204L,  11996L,
+	12785L,  13573L,  14359L,  15143L,  15924L,  16703L,  17479L,  18253L,
+	19024L,  19792L,  20557L,  21320L,  22078L,  22834L,  23586L,  24335L,
+	25080L,  25821L,  26558L,  27291L,  28020L,  28745L,  29466L,  30182L,
+	30893L,  31600L,  32303L,  33000L,  33692L,  34380L,  35062L,  35738L,
+	36410L,  37076L,  37736L,  38391L,  39040L,  39683L,  40320L,  40951L,
+	41576L,  42194L,  42806L,  43412L,  44011L,  44604L,  45190L,  45769L,
+	46341L,  46906L,  47464L,  48015L,  48559L,  49095L,  49624L,  50146L,
+	50660L,  51166L,  51665L,  52156L,  52639L,  53114L,  53581L,  54040L,
+	54491L,  54934L,  55368L,  55794L,  56212L,  56621L,  57022L,  57414L,
+	57798L,  58172L,  58538L,  58896L,  59244L,  59583L,  59914L,  60235L,
+	60547L,  60851L,  61145L,  61429L,  61705L,  61971L,  62228L,  62476L,
+	62714L,  62943L,  63162L,  63372L,  63572L,  63763L,  63944L,  64115L,
+	64277L,  64429L,  64571L,  64704L,  64827L,  64940L,  65043L,  65137L,
+	65220L,  65294L,  65358L,  65413L,  65457L,  65492L,  65516L,  65531L
+};
+
+
+
+fixed _tan_tbl[256] =
+{
+	/* precalculated fixed point (16.16) tangents for a half circle (0-127) */
+
+	0L,      804L,    1609L,   2414L,   3220L,   4026L,   4834L,   5644L,
+	6455L,   7268L,   8083L,   8901L,   9721L,   10545L,  11372L,  12202L,
+	13036L,  13874L,  14717L,  15564L,  16416L,  17273L,  18136L,  19005L,
+	19880L,  20762L,  21650L,  22546L,  23449L,  24360L,  25280L,  26208L,
+	27146L,  28093L,  29050L,  30018L,  30996L,  31986L,  32988L,  34002L,
+	35030L,  36071L,  37126L,  38196L,  39281L,  40382L,  41500L,  42636L,
+	43790L,  44963L,  46156L,  47369L,  48605L,  49863L,  51145L,  52451L,
+	53784L,  55144L,  56532L,  57950L,  59398L,  60880L,  62395L,  63947L,
+	65536L,  67165L,  68835L,  70548L,  72308L,  74116L,  75974L,  77887L,
+	79856L,  81885L,  83977L,  86135L,  88365L,  90670L,  93054L,  95523L,
+	98082L,  100736L, 103493L, 106358L, 109340L, 112447L, 115687L, 119071L,
+	122609L, 126314L, 130198L, 134276L, 138564L, 143081L, 147847L, 152884L,
+	158218L, 163878L, 169896L, 176309L, 183161L, 190499L, 198380L, 206870L,
+	216043L, 225990L, 236817L, 248648L, 261634L, 275959L, 291845L, 309568L,
+	329472L, 351993L, 377693L, 407305L, 441808L, 482534L, 531352L, 590958L,
+	665398L, 761030L, 888450L, 1066730L,1334016L,1779314L,2669641L,5340086L,
+	-2147483647L,-5340086L,-2669641L,-1779314L,-1334016L,-1066730L,-888450L,-761030L,
+	-665398L,-590958L,-531352L,-482534L,-441808L,-407305L,-377693L,-351993L,
+	-329472L,-309568L,-291845L,-275959L,-261634L,-248648L,-236817L,-225990L,
+	-216043L,-206870L,-198380L,-190499L,-183161L,-176309L,-169896L,-163878L,
+	-158218L,-152884L,-147847L,-143081L,-138564L,-134276L,-130198L,-126314L,
+	-122609L,-119071L,-115687L,-112447L,-109340L,-106358L,-103493L,-100736L,
+	-98082L, -95523L, -93054L, -90670L, -88365L, -86135L, -83977L, -81885L,
+	-79856L, -77887L, -75974L, -74116L, -72308L, -70548L, -68835L, -67165L,
+	-65536L, -63947L, -62395L, -60880L, -59398L, -57950L, -56532L, -55144L,
+	-53784L, -52451L, -51145L, -49863L, -48605L, -47369L, -46156L, -44963L,
+	-43790L, -42636L, -41500L, -40382L, -39281L, -38196L, -37126L, -36071L,
+	-35030L, -34002L, -32988L, -31986L, -30996L, -30018L, -29050L, -28093L,
+	-27146L, -26208L, -25280L, -24360L, -23449L, -22546L, -21650L, -20762L,
+	-19880L, -19005L, -18136L, -17273L, -16416L, -15564L, -14717L, -13874L,
+	-13036L, -12202L, -11372L, -10545L, -9721L,  -8901L,  -8083L,  -7268L,
+	-6455L,  -5644L,  -4834L,  -4026L,  -3220L,  -2414L,  -1609L,  -804L
+};
+
+
+
+fixed _acos_tbl[513] =
+{
+	/* precalculated fixed point (16.16) inverse cosines (-1 to 1) */
+
+	0x800000L,  0x7C65C7L,  0x7AE75AL,  0x79C19EL,  0x78C9BEL,  0x77EF25L,  0x772953L,  0x76733AL,
+	0x75C991L,  0x752A10L,  0x74930CL,  0x740345L,  0x7379C1L,  0x72F5BAL,  0x72768FL,  0x71FBBCL,
+	0x7184D3L,  0x711174L,  0x70A152L,  0x703426L,  0x6FC9B5L,  0x6F61C9L,  0x6EFC36L,  0x6E98D1L,
+	0x6E3777L,  0x6DD805L,  0x6D7A5EL,  0x6D1E68L,  0x6CC40BL,  0x6C6B2FL,  0x6C13C1L,  0x6BBDAFL,
+	0x6B68E6L,  0x6B1558L,  0x6AC2F5L,  0x6A71B1L,  0x6A217EL,  0x69D251L,  0x698420L,  0x6936DFL,
+	0x68EA85L,  0x689F0AL,  0x685465L,  0x680A8DL,  0x67C17DL,  0x67792CL,  0x673194L,  0x66EAAFL,
+	0x66A476L,  0x665EE5L,  0x6619F5L,  0x65D5A2L,  0x6591E7L,  0x654EBFL,  0x650C26L,  0x64CA18L,
+	0x648890L,  0x64478CL,  0x640706L,  0x63C6FCL,  0x63876BL,  0x63484FL,  0x6309A5L,  0x62CB6AL,
+	0x628D9CL,  0x625037L,  0x621339L,  0x61D69FL,  0x619A68L,  0x615E90L,  0x612316L,  0x60E7F7L,
+	0x60AD31L,  0x6072C3L,  0x6038A9L,  0x5FFEE3L,  0x5FC56EL,  0x5F8C49L,  0x5F5372L,  0x5F1AE7L,
+	0x5EE2A7L,  0x5EAAB0L,  0x5E7301L,  0x5E3B98L,  0x5E0473L,  0x5DCD92L,  0x5D96F3L,  0x5D6095L,
+	0x5D2A76L,  0x5CF496L,  0x5CBEF2L,  0x5C898BL,  0x5C545EL,  0x5C1F6BL,  0x5BEAB0L,  0x5BB62DL,
+	0x5B81E1L,  0x5B4DCAL,  0x5B19E7L,  0x5AE638L,  0x5AB2BCL,  0x5A7F72L,  0x5A4C59L,  0x5A1970L,
+	0x59E6B6L,  0x59B42AL,  0x5981CCL,  0x594F9BL,  0x591D96L,  0x58EBBDL,  0x58BA0EL,  0x588889L,
+	0x58572DL,  0x5825FAL,  0x57F4EEL,  0x57C40AL,  0x57934DL,  0x5762B5L,  0x573243L,  0x5701F5L,
+	0x56D1CCL,  0x56A1C6L,  0x5671E4L,  0x564224L,  0x561285L,  0x55E309L,  0x55B3ADL,  0x558471L,
+	0x555555L,  0x552659L,  0x54F77BL,  0x54C8BCL,  0x549A1BL,  0x546B98L,  0x543D31L,  0x540EE7L,
+	0x53E0B9L,  0x53B2A7L,  0x5384B0L,  0x5356D4L,  0x532912L,  0x52FB6BL,  0x52CDDDL,  0x52A068L,
+	0x52730CL,  0x5245C9L,  0x52189EL,  0x51EB8BL,  0x51BE8FL,  0x5191AAL,  0x5164DCL,  0x513825L,
+	0x510B83L,  0x50DEF7L,  0x50B280L,  0x50861FL,  0x5059D2L,  0x502D99L,  0x500175L,  0x4FD564L,
+	0x4FA967L,  0x4F7D7DL,  0x4F51A6L,  0x4F25E2L,  0x4EFA30L,  0x4ECE90L,  0x4EA301L,  0x4E7784L,
+	0x4E4C19L,  0x4E20BEL,  0x4DF574L,  0x4DCA3AL,  0x4D9F10L,  0x4D73F6L,  0x4D48ECL,  0x4D1DF1L,
+	0x4CF305L,  0x4CC829L,  0x4C9D5AL,  0x4C729AL,  0x4C47E9L,  0x4C1D45L,  0x4BF2AEL,  0x4BC826L,
+	0x4B9DAAL,  0x4B733BL,  0x4B48D9L,  0x4B1E84L,  0x4AF43BL,  0x4AC9FEL,  0x4A9FCDL,  0x4A75A7L,
+	0x4A4B8DL,  0x4A217EL,  0x49F77AL,  0x49CD81L,  0x49A393L,  0x4979AFL,  0x494FD5L,  0x492605L,
+	0x48FC3FL,  0x48D282L,  0x48A8CFL,  0x487F25L,  0x485584L,  0x482BECL,  0x48025DL,  0x47D8D6L,
+	0x47AF57L,  0x4785E0L,  0x475C72L,  0x47330AL,  0x4709ABL,  0x46E052L,  0x46B701L,  0x468DB7L,
+	0x466474L,  0x463B37L,  0x461201L,  0x45E8D0L,  0x45BFA6L,  0x459682L,  0x456D64L,  0x45444BL,
+	0x451B37L,  0x44F229L,  0x44C920L,  0x44A01CL,  0x44771CL,  0x444E21L,  0x44252AL,  0x43FC38L,
+	0x43D349L,  0x43AA5FL,  0x438178L,  0x435894L,  0x432FB4L,  0x4306D8L,  0x42DDFEL,  0x42B527L,
+	0x428C53L,  0x426381L,  0x423AB2L,  0x4211E5L,  0x41E91AL,  0x41C051L,  0x41978AL,  0x416EC5L,
+	0x414601L,  0x411D3EL,  0x40F47CL,  0x40CBBBL,  0x40A2FBL,  0x407A3CL,  0x40517DL,  0x4028BEL,
+	0x400000L,  0x3FD742L,  0x3FAE83L,  0x3F85C4L,  0x3F5D05L,  0x3F3445L,  0x3F0B84L,  0x3EE2C2L,
+	0x3EB9FFL,  0x3E913BL,  0x3E6876L,  0x3E3FAFL,  0x3E16E6L,  0x3DEE1BL,  0x3DC54EL,  0x3D9C7FL,
+	0x3D73ADL,  0x3D4AD9L,  0x3D2202L,  0x3CF928L,  0x3CD04CL,  0x3CA76CL,  0x3C7E88L,  0x3C55A1L,
+	0x3C2CB7L,  0x3C03C8L,  0x3BDAD6L,  0x3BB1DFL,  0x3B88E4L,  0x3B5FE4L,  0x3B36E0L,  0x3B0DD7L,
+	0x3AE4C9L,  0x3ABBB5L,  0x3A929CL,  0x3A697EL,  0x3A405AL,  0x3A1730L,  0x39EDFFL,  0x39C4C9L,
+	0x399B8CL,  0x397249L,  0x3948FFL,  0x391FAEL,  0x38F655L,  0x38CCF6L,  0x38A38EL,  0x387A20L,
+	0x3850A9L,  0x38272AL,  0x37FDA3L,  0x37D414L,  0x37AA7CL,  0x3780DBL,  0x375731L,  0x372D7EL,
+	0x3703C1L,  0x36D9FBL,  0x36B02BL,  0x368651L,  0x365C6DL,  0x36327FL,  0x360886L,  0x35DE82L,
+	0x35B473L,  0x358A59L,  0x356033L,  0x353602L,  0x350BC5L,  0x34E17CL,  0x34B727L,  0x348CC5L,
+	0x346256L,  0x3437DAL,  0x340D52L,  0x33E2BBL,  0x33B817L,  0x338D66L,  0x3362A6L,  0x3337D7L,
+	0x330CFBL,  0x32E20FL,  0x32B714L,  0x328C0AL,  0x3260F0L,  0x3235C6L,  0x320A8CL,  0x31DF42L,
+	0x31B3E7L,  0x31887CL,  0x315CFFL,  0x313170L,  0x3105D0L,  0x30DA1EL,  0x30AE5AL,  0x308283L,
+	0x305699L,  0x302A9CL,  0x2FFE8BL,  0x2FD267L,  0x2FA62EL,  0x2F79E1L,  0x2F4D80L,  0x2F2109L,
+	0x2EF47DL,  0x2EC7DBL,  0x2E9B24L,  0x2E6E56L,  0x2E4171L,  0x2E1475L,  0x2DE762L,  0x2DBA37L,
+	0x2D8CF4L,  0x2D5F98L,  0x2D3223L,  0x2D0495L,  0x2CD6EEL,  0x2CA92CL,  0x2C7B50L,  0x2C4D59L,
+	0x2C1F47L,  0x2BF119L,  0x2BC2CFL,  0x2B9468L,  0x2B65E5L,  0x2B3744L,  0x2B0885L,  0x2AD9A7L,
+	0x2AAAABL,  0x2A7B8FL,  0x2A4C53L,  0x2A1CF7L,  0x29ED7BL,  0x29BDDCL,  0x298E1CL,  0x295E3AL,
+	0x292E34L,  0x28FE0BL,  0x28CDBDL,  0x289D4BL,  0x286CB3L,  0x283BF6L,  0x280B12L,  0x27DA06L,
+	0x27A8D3L,  0x277777L,  0x2745F2L,  0x271443L,  0x26E26AL,  0x26B065L,  0x267E34L,  0x264BD6L,
+	0x26194AL,  0x25E690L,  0x25B3A7L,  0x25808EL,  0x254D44L,  0x2519C8L,  0x24E619L,  0x24B236L,
+	0x247E1FL,  0x2449D3L,  0x241550L,  0x23E095L,  0x23ABA2L,  0x237675L,  0x23410EL,  0x230B6AL,
+	0x22D58AL,  0x229F6BL,  0x22690DL,  0x22326EL,  0x21FB8DL,  0x21C468L,  0x218CFFL,  0x215550L,
+	0x211D59L,  0x20E519L,  0x20AC8EL,  0x2073B7L,  0x203A92L,  0x20011DL,  0x1FC757L,  0x1F8D3DL,
+	0x1F52CFL,  0x1F1809L,  0x1EDCEAL,  0x1EA170L,  0x1E6598L,  0x1E2961L,  0x1DECC7L,  0x1DAFC9L,
+	0x1D7264L,  0x1D3496L,  0x1CF65BL,  0x1CB7B1L,  0x1C7895L,  0x1C3904L,  0x1BF8FAL,  0x1BB874L,
+	0x1B7770L,  0x1B35E8L,  0x1AF3DAL,  0x1AB141L,  0x1A6E19L,  0x1A2A5EL,  0x19E60BL,  0x19A11BL,
+	0x195B8AL,  0x191551L,  0x18CE6CL,  0x1886D4L,  0x183E83L,  0x17F573L,  0x17AB9BL,  0x1760F6L,
+	0x17157BL,  0x16C921L,  0x167BE0L,  0x162DAFL,  0x15DE82L,  0x158E4FL,  0x153D0BL,  0x14EAA8L,
+	0x14971AL,  0x144251L,  0x13EC3FL,  0x1394D1L,  0x133BF5L,  0x12E198L,  0x1285A2L,  0x1227FBL,
+	0x11C889L,  0x11672FL,  0x1103CAL,  0x109E37L,  0x10364BL,  0xFCBDAL,   0xF5EAEL,   0xEEE8CL,
+	0xE7B2DL,   0xE0444L,   0xD8971L,   0xD0A46L,   0xC863FL,   0xBFCBBL,   0xB6CF4L,   0xAD5F0L,
+	0xA366FL,   0x98CC6L,   0x8D6ADL,   0x810DBL,   0x73642L,   0x63E62L,   0x518A6L,   0x39A39L,
+	0x0L
+};
+
+
+
+/* fixatan:
+ *  Fixed point inverse tangent. Does a binary search on the tan table.
+ */
+fixed fixatan(fixed x) {
+	int a, b, c;            /* for binary search */
+	fixed d;                /* difference value for search */
+
+	if (x >= 0) {           /* search the first part of tan table */
+		a = 0;
+		b = 127;
+	} else {                  /* search the second half instead */
+		a = 128;
+		b = 255;
+	}
+
+	do {
+		c = (a + b) >> 1;
+		d = x - _tan_tbl[c];
+
+		if (d > 0)
+			a = c + 1;
+		else
+			if (d < 0)
+				b = c - 1;
+
+	} while ((a <= b) && (d));
+
+	if (x >= 0)
+		return ((long)c) << 15;
+
+	return (-0x00800000L + (((long)c) << 15));
+}
+
+
+
+/* fixatan2:
+ *  Like the libc atan2, but for fixed point numbers.
+ */
+fixed fixatan2(fixed y, fixed x) {
+	fixed r;
+
+	if (x == 0) {
+		if (y == 0) {
+			*allegro_errno = EDOM;
+			return 0L;
+		} else
+			return ((y < 0) ? -0x00400000L : 0x00400000L);
+	}
+
+	*allegro_errno = 0;
+	r = fixdiv(y, x);
+
+	if (*allegro_errno) {
+		*allegro_errno = 0;
+		return ((y < 0) ? -0x00400000L : 0x00400000L);
+	}
+
+	r = fixatan(r);
+
+	if (x >= 0)
+		return r;
+
+	if (y >= 0)
+		return 0x00800000L + r;
+
+	return r - 0x00800000L;
+}
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/lib/dumb-0.9.2/it.h b/engines/ags/lib/dumb-0.9.2/it.h
new file mode 100644
index 0000000000..40678b9502
--- /dev/null
+++ b/engines/ags/lib/dumb-0.9.2/it.h
@@ -0,0 +1,716 @@
+/* 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.
+ *
+ */
+
+/*  _______         ____    __         ___    ___
+ * \    _  \       \    /  \  /       \   \  /   /       '   '  '
+ *  |  | \  \       |  |    ||         |   \/   |         .      .
+ *  |  |  |  |      |  |    ||         ||\  /|  |
+ *  |  |  |  |      |  |    ||         || \/ |  |         '  '  '
+ *  |  |  |  |      |  |    ||         ||    |  |         .      .
+ *  |  |_/  /        \  \__//          ||    |  |
+ * /_______/ynamic    \____/niversal  /__\  /____\usic   /|  .  . ibliotheque
+ *                                                      /  \
+ *                                                     / .  \
+ * internal/it.h - Internal stuff for IT playback     / / \  \
+ *                 and MOD/XM/S3M conversion.        | <  /   \_
+ *                                                   |  \/ /\   /
+ *                                                    \_  /  > /
+ *                                                      | \ / /
+ *                                                      |  ' /
+ *                                                       \__/
+ */
+
+#ifndef INTERNAL_IT_H
+#define INTERNAL_IT_H
+
+#include "common/scummsys.h"
+
+namespace AGS3 {
+
+/** TO DO: THINK ABOUT THE FOLLOWING:
+
+sigdata->flags & IT_COMPATIBLE_GXX
+
+				Bit 5: On = Link Effect G's memory with Effect E/F. Also
+							Gxx with an instrument present will cause the
+							envelopes to be retriggered. If you change a
+							sample on a row with Gxx, it'll adjust the
+							frequency of the current note according to:
+
+							  NewFrequency = OldFrequency * NewC5 / OldC5;
+*/
+
+
+
+/* These #defines are TEMPORARY. They are used to write alternative code to
+ * handle ambiguities in the format specification. The correct code in each
+ * case will be determined most likely by experimentation.
+ */
+#define STEREO_SAMPLES_COUNT_AS_TWO
+#define INVALID_ORDERS_END_SONG
+#define INVALID_NOTES_CAUSE_NOTE_CUT
+#define SUSTAIN_LOOP_OVERRIDES_NORMAL_LOOP
+#define VOLUME_OUT_OF_RANGE_SETS_MAXIMUM
+
+
+
+#define SIGTYPE_IT DUMB_ID('I', 'T', ' ', ' ')
+
+#define IT_SIGNATURE            DUMB_ID('I', 'M', 'P', 'M')
+#define IT_INSTRUMENT_SIGNATURE DUMB_ID('I', 'M', 'P', 'I')
+#define IT_SAMPLE_SIGNATURE     DUMB_ID('I', 'M', 'P', 'S')
+
+
+
+ /* 1 minute per 4 rows, each row 6 ticks; this is divided by the tempo to get
+  * the interval between ticks.
+  */
+#define TICK_TIME_DIVIDEND ((65536 * 60) / (4 * 6))
+
+
+
+  /* I'm not going to try to explain this, because I didn't derive it very
+   * formally ;)
+   */
+   /* #define AMIGA_DIVISOR ((float)(4.0 * 14317056.0)) */
+   /* I believe the following one to be more accurate. */
+#define AMIGA_DIVISOR ((float)(8.0 * 7159090.5))
+
+
+
+typedef struct IT_MIDI IT_MIDI;
+typedef struct IT_FILTER_STATE IT_FILTER_STATE;
+typedef struct IT_ENVELOPE IT_ENVELOPE;
+typedef struct IT_INSTRUMENT IT_INSTRUMENT;
+typedef struct IT_SAMPLE IT_SAMPLE;
+typedef struct IT_ENTRY IT_ENTRY;
+typedef struct IT_PATTERN IT_PATTERN;
+typedef struct IT_PLAYING_ENVELOPE IT_PLAYING_ENVELOPE;
+typedef struct IT_PLAYING IT_PLAYING;
+typedef struct IT_CHANNEL IT_CHANNEL;
+typedef struct IT_CHECKPOINT IT_CHECKPOINT;
+typedef struct IT_CALLBACKS IT_CALLBACKS;
+
+
+
+struct IT_MIDI {
+	unsigned char SFmacro[16][16]; // read these from 0x120
+	unsigned char SFmacrolen[16];
+	unsigned short SFmacroz[16]; /* Bitfield; bit 0 set = z in first position */
+	unsigned char Zmacro[128][16]; // read these from 0x320
+	unsigned char Zmacrolen[128];
+};
+
+
+
+struct IT_FILTER_STATE {
+	float currsample, prevsample;
+};
+
+
+
+#define IT_ENVELOPE_ON                1
+#define IT_ENVELOPE_LOOP_ON           2
+#define IT_ENVELOPE_SUSTAIN_LOOP      4
+#define IT_ENVELOPE_PITCH_IS_FILTER 128
+
+struct IT_ENVELOPE {
+	unsigned char flags;
+	unsigned char n_nodes;
+	unsigned char loop_start;
+	unsigned char loop_end;
+	unsigned char sus_loop_start;
+	unsigned char sus_loop_end;
+	signed char node_y[25];
+	unsigned short node_t[25];
+};
+
+
+
+#define NNA_NOTE_CUT      0
+#define NNA_NOTE_CONTINUE 1
+#define NNA_NOTE_OFF      2
+#define NNA_NOTE_FADE     3
+
+#define DCT_OFF        0
+#define DCT_NOTE       1
+#define DCT_SAMPLE     2
+#define DCT_INSTRUMENT 3
+
+#define DCA_NOTE_CUT  0
+#define DCA_NOTE_OFF  1
+#define DCA_NOTE_FADE 2
+
+struct IT_INSTRUMENT {
+	int fadeout;
+
+	IT_ENVELOPE volume_envelope;
+	IT_ENVELOPE pan_envelope;
+	IT_ENVELOPE pitch_envelope;
+
+	unsigned char new_note_action;
+	unsigned char dup_check_type;
+	unsigned char dup_check_action;
+	unsigned char pp_separation;
+	unsigned char pp_centre;
+	unsigned char global_volume;
+	unsigned char default_pan;
+	unsigned char random_volume;
+	unsigned char random_pan;
+
+	unsigned char filter_cutoff;
+	unsigned char filter_resonance;
+
+	unsigned char map_note[120];
+	unsigned short map_sample[120];
+};
+
+
+
+#define IT_SAMPLE_EXISTS              1
+#define IT_SAMPLE_16BIT               2
+#define IT_SAMPLE_STEREO              4
+#define IT_SAMPLE_LOOP               16
+#define IT_SAMPLE_SUS_LOOP           32
+#define IT_SAMPLE_PINGPONG_LOOP      64
+#define IT_SAMPLE_PINGPONG_SUS_LOOP 128
+
+#define IT_VIBRATO_SINE     0
+#define IT_VIBRATO_SAWTOOTH 1 /* Ramp down */
+#define IT_VIBRATO_SQUARE   2
+#define IT_VIBRATO_RANDOM   3
+
+struct IT_SAMPLE {
+	unsigned char flags;
+	unsigned char global_volume;
+	unsigned char default_volume;
+	unsigned char default_pan;
+
+	long length;
+	long loop_start;
+	long loop_end;
+	long C5_speed;
+	long sus_loop_start;
+	long sus_loop_end;
+
+	unsigned char vibrato_speed;
+	unsigned char vibrato_depth;
+	unsigned char vibrato_rate;
+	unsigned char vibrato_waveform;
+
+	sample_t *left;
+	sample_t *right;
+};
+
+
+
+#define IT_ENTRY_NOTE       1
+#define IT_ENTRY_INSTRUMENT 2
+#define IT_ENTRY_VOLPAN     4
+#define IT_ENTRY_EFFECT     8
+
+#define IT_SET_END_ROW(entry) ((entry)->channel = 255)
+#define IT_IS_END_ROW(entry) ((entry)->channel >= DUMB_IT_N_CHANNELS)
+
+#define IT_NOTE_OFF 255
+#define IT_NOTE_CUT 254
+
+#define IT_ENVELOPE_SHIFT 8
+
+#define IT_SURROUND 100
+#define IT_IS_SURROUND(pan) ((pan) > 64)
+#define IT_IS_SURROUND_SHIFTED(pan) ((pan) > 64 << IT_ENVELOPE_SHIFT)
+
+#define IT_SET_SPEED              1
+#define IT_JUMP_TO_ORDER          2
+#define IT_BREAK_TO_ROW           3
+#define IT_VOLUME_SLIDE           4
+#define IT_PORTAMENTO_DOWN        5
+#define IT_PORTAMENTO_UP          6
+#define IT_TONE_PORTAMENTO        7
+#define IT_VIBRATO                8
+#define IT_TREMOR                 9
+#define IT_ARPEGGIO              10
+#define IT_VOLSLIDE_VIBRATO      11
+#define IT_VOLSLIDE_TONEPORTA    12
+#define IT_SET_CHANNEL_VOLUME    13
+#define IT_CHANNEL_VOLUME_SLIDE  14
+#define IT_SET_SAMPLE_OFFSET     15
+#define IT_PANNING_SLIDE         16
+#define IT_RETRIGGER_NOTE        17
+#define IT_TREMOLO               18
+#define IT_S                     19
+#define IT_SET_SONG_TEMPO        20
+#define IT_FINE_VIBRATO          21
+#define IT_SET_GLOBAL_VOLUME     22
+#define IT_GLOBAL_VOLUME_SLIDE   23
+#define IT_SET_PANNING           24
+#define IT_PANBRELLO             25
+#define IT_MIDI_MACRO            26 //see MIDI.TXT
+
+/* Some effects needed for XM compatibility */
+#define IT_XM_PORTAMENTO_DOWN    27
+#define IT_XM_PORTAMENTO_UP      28
+#define IT_XM_FINE_VOLSLIDE_DOWN 29
+#define IT_XM_FINE_VOLSLIDE_UP   30
+#define IT_XM_RETRIGGER_NOTE     31
+
+#define IT_N_EFFECTS             32
+
+/* These represent the top nibble of the command value. */
+#define IT_S_SET_FILTER              0 /* Greyed out in IT... */
+#define IT_S_SET_GLISSANDO_CONTROL   1 /* Greyed out in IT... */
+#define IT_S_FINETUNE                2 /* Greyed out in IT... */
+#define IT_S_SET_VIBRATO_WAVEFORM    3
+#define IT_S_SET_TREMOLO_WAVEFORM    4
+#define IT_S_SET_PANBRELLO_WAVEFORM  5
+#define IT_S_FINE_PATTERN_DELAY      6
+#define IT_S7                        7
+#define IT_S_SET_PAN                 8
+#define IT_S_SET_SURROUND_SOUND      9
+#define IT_S_SET_HIGH_OFFSET        10
+#define IT_S_PATTERN_LOOP           11
+#define IT_S_DELAYED_NOTE_CUT       12
+#define IT_S_NOTE_DELAY             13
+#define IT_S_PATTERN_DELAY          14
+#define IT_S_SET_MIDI_MACRO         15
+
+/*
+S0x Set filter
+S1x Set glissando control
+S2x Set finetune
+
+
+S3x Set vibrato waveform to type x
+S4x Set tremelo waveform to type x
+S5x Set panbrello waveform to type x
+  Waveforms for commands S3x, S4x and S5x:
+	0: Sine wave
+	1: Ramp down
+	2: Square wave
+	3: Random wave
+S6x Pattern delay for x ticks
+S70 Past note cut
+S71 Past note off
+S72 Past note fade
+S73 Set NNA to note cut
+S74 Set NNA to continue
+S75 Set NNA to note off
+S76 Set NNA to note fade
+S77 Turn off volume envelope
+S78 Turn on volume envelope
+S79 Turn off panning envelope
+S7A Turn on panning envelope
+S7B Turn off pitch envelope
+S7C Turn on pitch envelope
+S8x Set panning position
+S91 Set surround sound
+SAy Set high value of sample offset yxx00h
+SB0 Set loopback point
+SBx Loop x times to loopback point
+SCx Note cut after x ticks
+SDx Note delay for x ticks
+SEx Pattern delay for x rows
+SFx Set parameterised MIDI Macro
+*/
+
+struct IT_ENTRY {
+	unsigned char channel; /* End of row if channel >= DUMB_IT_N_CHANNELS */
+	unsigned char mask;
+	unsigned char note;
+	unsigned char instrument;
+	unsigned char volpan;
+	unsigned char effect;
+	unsigned char effectvalue;
+};
+
+
+
+struct IT_PATTERN {
+	int n_rows;
+	int n_entries;
+	IT_ENTRY *entry;
+};
+
+
+
+#define IT_STEREO            1
+#define IT_USE_INSTRUMENTS   4
+#define IT_LINEAR_SLIDES     8 /* If not set, use Amiga slides */
+#define IT_OLD_EFFECTS      16
+#define IT_COMPATIBLE_GXX   32
+
+/* Make sure IT_WAS_AN_XM and IT_WAS_A_MOD aren't set accidentally */
+#define IT_REAL_FLAGS       63
+
+#define IT_WAS_AN_XM        64 /* Set for both XMs and MODs */
+#define IT_WAS_A_MOD       128
+
+#define IT_ORDER_END  255
+#define IT_ORDER_SKIP 254
+
+struct DUMB_IT_SIGDATA {
+	int n_orders;
+	int n_instruments;
+	int n_samples;
+	int n_patterns;
+
+	int flags;
+
+	int global_volume;
+	int mixing_volume;
+	int speed;
+	int tempo;
+	int pan_separation;
+
+	unsigned char channel_pan[DUMB_IT_N_CHANNELS];
+	unsigned char channel_volume[DUMB_IT_N_CHANNELS];
+
+	unsigned char *order;
+	unsigned char restart_position; /* for XM compatiblity */
+
+	IT_INSTRUMENT *instrument;
+	IT_SAMPLE *sample;
+	IT_PATTERN *pattern;
+
+	IT_MIDI *midi;
+
+	IT_CHECKPOINT *checkpoint;
+};
+
+
+
+struct IT_PLAYING_ENVELOPE {
+	int next_node;
+	int tick;
+};
+
+
+
+#define IT_PLAYING_BACKGROUND 1
+#define IT_PLAYING_SUSTAINOFF 2
+#define IT_PLAYING_FADING     4
+#define IT_PLAYING_DEAD       8
+
+struct IT_PLAYING {
+	int flags;
+
+	IT_CHANNEL *channel;
+	IT_SAMPLE *sample;
+	IT_INSTRUMENT *instrument;
+	IT_INSTRUMENT *env_instrument;
+
+	unsigned short sampnum;
+	unsigned char instnum;
+
+	unsigned char channel_volume;
+
+	unsigned char volume;
+	unsigned short pan;
+
+	unsigned char note;
+
+	unsigned char filter_cutoff;
+	unsigned char filter_resonance;
+
+	unsigned short true_filter_cutoff;   /* These incorporate the filter envelope, and will not */
+	unsigned char true_filter_resonance; /* be changed if they would be set to 127<<8 and 0.    */
+
+	unsigned char vibrato_speed;
+	unsigned char vibrato_depth;
+	unsigned char vibrato_n; /* May be specified twice: volpan & effect. */
+	unsigned char vibrato_time;
+
+	unsigned char tremolo_speed;
+	unsigned char tremolo_depth;
+	unsigned char tremolo_time;
+
+	unsigned char sample_vibrato_time;
+	int sample_vibrato_depth; /* Starts at rate?0:depth, increases by rate */
+
+	int slide;
+	float delta;
+
+	IT_PLAYING_ENVELOPE volume_envelope;
+	IT_PLAYING_ENVELOPE pan_envelope;
+	IT_PLAYING_ENVELOPE pitch_envelope;
+
+	int fadeoutcount;
+
+	IT_FILTER_STATE filter_state[2]; /* Left and right */
+
+	DUMB_RESAMPLER resampler[2];
+
+	/* time_lost is used to emulate Impulse Tracker's sample looping
+	 * characteristics. When time_lost is added to pos, the result represents
+	 * the position in the theoretical version of the sample where all loops
+	 * have been expanded. If this is stored, the resampling helpers will
+	 * safely convert it for use with new loop boundaries. The situation is
+	 * slightly more complicated if dir == -1 when the change takes place; we
+	 * must reflect pos off the loop end point and set dir to 1 before
+	 * proceeding.
+	 */
+	long time_lost;
+};
+
+
+
+#define IT_CHANNEL_MUTED 1
+
+struct IT_CHANNEL {
+	int flags;
+
+	unsigned char volume;
+	signed char volslide;
+	signed char xm_volslide;
+
+	/* xm_volslide is used for volume slides done in the volume column in an
+	 * XM file, since it seems the volume column slide is applied first,
+	 * followed by clamping, followed by the effects column slide. IT does
+	 * not exhibit this behaviour, so xm_volslide is maintained at zero.
+	 */
+
+	unsigned char pan;
+	unsigned short truepan;
+
+	unsigned char channelvolume;
+	signed char channelvolslide;
+
+	unsigned char instrument;
+	unsigned char note;
+
+	unsigned char SFmacro;
+
+	unsigned char filter_cutoff;
+	unsigned char filter_resonance;
+
+	unsigned char note_cut_count;
+	unsigned char note_delay_count;
+	IT_ENTRY *note_delay_entry;
+
+	int arpeggio;
+	unsigned char retrig;
+	unsigned char xm_retrig;
+	int retrig_tick;
+
+	unsigned char tremor;
+	unsigned char tremor_time; /* Bit 6 set if note on; bit 7 set if tremor active. */
+
+	int portamento;
+	int toneporta;
+	unsigned char destnote;
+
+	/** WARNING - for neatness, should one or both of these be in the IT_PLAYING struct? */
+	unsigned short sample;
+	unsigned char truenote;
+
+	unsigned char midi_state;
+
+	signed char lastvolslide;
+	unsigned char lastDKL;
+	unsigned char lastEF; /* Doubles as last portamento up for XM files */
+	unsigned char lastG;
+	unsigned char lastHspeed;
+	unsigned char lastHdepth;
+	unsigned char lastRspeed;
+	unsigned char lastRdepth;
+	unsigned char lastI;
+	unsigned char lastJ; /* Doubles as last portamento down for XM files */
+	unsigned char lastN;
+	unsigned char lastO;
+	unsigned char high_offset;
+	unsigned char lastQ;
+	unsigned char lastS;
+	unsigned char pat_loop_row;
+	unsigned char pat_loop_count;
+	unsigned char lastW;
+
+	unsigned char xm_lastE1;
+	unsigned char xm_lastE2;
+	unsigned char xm_lastEA;
+	unsigned char xm_lastEB;
+	unsigned char xm_lastX1;
+	unsigned char xm_lastX2;
+
+	IT_PLAYING *playing;
+};
+
+
+
+struct DUMB_IT_SIGRENDERER {
+	DUMB_IT_SIGDATA *sigdata;
+
+	int n_channels;
+
+	unsigned char globalvolume;
+	signed char globalvolslide;
+
+	unsigned char tempo;
+	signed char temposlide;
+
+	IT_CHANNEL channel[DUMB_IT_N_CHANNELS];
+
+	IT_PLAYING *playing[DUMB_IT_N_NNA_CHANNELS];
+
+	int tick;
+	int speed;
+	int rowcount;
+
+	int order; /* Set to -1 if the song is terminated by a callback. */
+	int row;
+	int processorder;
+	int processrow;
+	int breakrow;
+	int pat_loop_row;
+
+	int n_rows;
+
+	IT_ENTRY *entry_start;
+	IT_ENTRY *entry;
+	IT_ENTRY *entry_end;
+
+	long time_left; /* Time before the next tick is processed */
+	int sub_time_left;
+
+	DUMB_CLICK_REMOVER **click_remover;
+
+	IT_CALLBACKS *callbacks;
+};
+
+
+
+struct IT_CHECKPOINT {
+	IT_CHECKPOINT *next;
+	long time;
+	DUMB_IT_SIGRENDERER *sigrenderer;
+};
+
+
+
+struct IT_CALLBACKS {
+	int (*loop)(void *data);
+	void *loop_data;
+	/* Return 1 to prevent looping; the music will terminate abruptly. If you
+	 * want to make the music stop but allow samples to fade (beware, as they
+	 * might not fade at all!), use dumb_it_sr_set_speed() and set the speed
+	 * to 0. Note that xm_speed_zero() will not be called if you set the
+	 * speed manually, and also that this will work for IT and S3M files even
+	 * though the music can't stop in this way by itself.
+	 */
+
+	int (*xm_speed_zero)(void *data);
+	void *xm_speed_zero_data;
+	/* Return 1 to terminate the mod, without letting samples fade. */
+
+	int (*midi)(void *data, int channel, unsigned char byte);
+	void *midi_data;
+	/* Return 1 to prevent DUMB from subsequently interpreting the MIDI bytes
+	 * itself. In other words, return 1 if the Zxx macros in an IT file are
+	 * controlling filters and shouldn't be.
+	 */
+};
+
+
+
+void _dumb_it_end_sigrenderer(sigrenderer_t *sigrenderer);
+void _dumb_it_unload_sigdata(sigdata_t *vsigdata);
+
+extern DUH_SIGTYPE_DESC _dumb_sigtype_it;
+
+
+
+long _dumb_it_build_checkpoints(DUMB_IT_SIGDATA *sigdata);
+
+
+
+#define XM_APPREGIO                0
+#define XM_PORTAMENTO_UP           1
+#define XM_PORTAMENTO_DOWN         2
+#define XM_TONE_PORTAMENTO         3
+#define XM_VIBRATO                 4
+#define XM_VOLSLIDE_TONEPORTA      5
+#define XM_VOLSLIDE_VIBRATO        6
+#define XM_TREMOLO                 7
+#define XM_SET_PANNING             8
+#define XM_SAMPLE_OFFSET           9
+#define XM_VOLUME_SLIDE            10 /* A */
+#define XM_POSITION_JUMP           11 /* B */
+#define XM_SET_CHANNEL_VOLUME      12 /* C */
+#define XM_PATTERN_BREAK           13 /* D */
+#define XM_E                       14 /* E */
+#define XM_SET_TEMPO_BPM           15 /* F */
+#define XM_SET_GLOBAL_VOLUME       16 /* G */
+#define XM_GLOBAL_VOLUME_SLIDE     17 /* H */
+#define XM_KEY_OFF                 20 /* K (undocumented) */
+#define XM_SET_ENVELOPE_POSITION   21 /* L */
+#define XM_PANNING_SLIDE           25 /* P */
+#define XM_MULTI_RETRIG            27 /* R */
+#define XM_TREMOR                  29 /* T */
+#define XM_X                       33 /* X */
+#define XM_N_EFFECTS               (10+26)
+
+#define XM_E_SET_FILTER            0x0
+#define XM_E_FINE_PORTA_UP         0x1
+#define XM_E_FINE_PORTA_DOWN       0x2
+#define XM_E_SET_GLISSANDO_CONTROL 0x3
+#define XM_E_SET_VIBRATO_CONTROL   0x4
+#define XM_E_SET_FINETUNE          0x5
+#define XM_E_SET_LOOP              0x6
+#define XM_E_SET_TREMOLO_CONTROL   0x7
+#define XM_E_RETRIG_NOTE           0x9
+#define XM_E_FINE_VOLSLIDE_UP      0xA
+#define XM_E_FINE_VOLSLIDE_DOWN    0xB
+#define XM_E_NOTE_CUT              0xC
+#define XM_E_NOTE_DELAY            0xD
+#define XM_E_PATTERN_DELAY         0xE
+
+#define XM_X_EXTRAFINE_PORTA_UP    1
+#define XM_X_EXTRAFINE_PORTA_DOWN  2
+
+/* To make my life a bit simpler during conversion, effect E:xy is converted
+ * to effect number EBASE+x:y. The same applies to effect X, and IT's S. That
+ * way, these effects can be manipulated like regular effects.
+ */
+#define EBASE              (XM_N_EFFECTS)
+#define XBASE              (EBASE+16)
+#define SBASE              (IT_N_EFFECTS)
+
+#define EFFECT_VALUE(x, y) (((x)<<4)|(y))
+#define HIGH(v)            ((v)>>4)
+#define LOW(v)             ((v)&0x0F)
+#define SET_HIGH(v, x)     v = (((x)<<4)|((v)&0x0F))
+#define SET_LOW(v, y)      v = (((v)&0xF0)|(y))
+#define BCD_TO_NORMAL(v)   (HIGH(v)*10+LOW(v))
+
+
+
+#if 0
+unsigned char **_dumb_malloc2(int w, int h);
+void _dumb_free2(unsigned char **line);
+#endif
+
+void _dumb_it_xm_convert_effect(int effect, int value, IT_ENTRY *entry);
+int _dumb_it_fix_invalid_orders(DUMB_IT_SIGDATA *sigdata);
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/lib/dumb-0.9.2/readxm.cpp b/engines/ags/lib/dumb-0.9.2/readxm.cpp
new file mode 100644
index 0000000000..775620e8c5
--- /dev/null
+++ b/engines/ags/lib/dumb-0.9.2/readxm.cpp
@@ -0,0 +1,1007 @@
+/* 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.
+ *
+ */
+
+ /*  _______         ____    __         ___    ___
+  * \    _  \       \    /  \  /       \   \  /   /       '   '  '
+  *  |  | \  \       |  |    ||         |   \/   |         .      .
+  *  |  |  |  |      |  |    ||         ||\  /|  |
+  *  |  |  |  |      |  |    ||         || \/ |  |         '  '  '
+  *  |  |  |  |      |  |    ||         ||    |  |         .      .
+  *  |  |_/  /        \  \__//          ||    |  |
+  * /_______/ynamic    \____/niversal  /__\  /____\usic   /|  .  . ibliotheque
+  *                                                      /  \
+  *                                                     / .  \
+  * readxm.c - Code to read a Fast Tracker II          / / \  \
+  *            module from an open file.              | <  /   \_
+  *                                                   |  \/ /\   /
+  * By Julien Cugniere. Some bits of code taken        \_  /  > /
+  * from reads3m.c.                                      | \ / /
+  *                                                      |  ' /
+  *                                                       \__/
+  */
+
+#include "ags/lib/dumb-0.9.2/dumb.h"
+#include "ags/lib/dumb-0.9.2/it.h"
+
+namespace AGS3 {
+
+/** TODO:
+
+ * XM_TREMOLO                        doesn't sound quite right...
+ * XM_E_SET_FINETUNE                 todo.
+ * XM_SET_ENVELOPE_POSITION          todo.
+
+ * VIBRATO conversion needs to be checked (sample/effect/volume). Plus check
+   that effect memory is correct when using XM_VOLSLIDE_VIBRATO.
+   - sample vibrato (instrument vibrato) is now handled correctly. - entheh
+
+ * XM_E_SET_VIBRATO/TREMOLO_CONTROL: effectvalue&4 -> don't retrig wave when
+   a new instrument is played. In retrigger_note()?. Is it worth implementing?
+
+ * Lossy fadeout approximation. 0..31 converted to 0 --> won't fade at all.
+
+ * Replace DUMB's sawtooth by ramp_down/ramp_up. Update XM loader.
+
+ * A lot of things need to be reset when the end of the song is reached.
+
+ * It seems that IT and XM don't behave the same way when dealing with
+   mixed loops. When IT encounters multiple SBx (x>0) commands on the same
+   row, it decrements the loop count for all, but only execute the loop of
+   the last one (highest channel). FT2 only decrements the loop count of the
+   last one. Not that I know of any modules using so convoluted combinations!
+
+ * Maybe we could remove patterns that don't appear in the order table ? Or
+   provide a function to "optimize" a DUMB_IT_SIGDATA ?
+
+*/
+
+
+
+#define XM_LINEAR_FREQUENCY        1 /* otherwise, use amiga slides */
+
+#define XM_ENTRY_PACKED            128
+#define XM_ENTRY_NOTE              1
+#define XM_ENTRY_INSTRUMENT        2
+#define XM_ENTRY_VOLUME            4
+#define XM_ENTRY_EFFECT            8
+#define XM_ENTRY_EFFECTVALUE       16
+
+#define XM_NOTE_OFF                97
+
+#define XM_ENVELOPE_ON             1
+#define XM_ENVELOPE_SUSTAIN        2
+#define XM_ENVELOPE_LOOP           4
+
+#define XM_SAMPLE_NO_LOOP          0
+#define XM_SAMPLE_FORWARD_LOOP     1
+#define XM_SAMPLE_PINGPONG_LOOP    2
+#define XM_SAMPLE_16BIT            16
+#define XM_SAMPLE_STEREO           32
+
+#define XM_VIBRATO_SINE            0
+#define XM_VIBRATO_SQUARE          1
+#define XM_VIBRATO_RAMP_DOWN       2
+#define XM_VIBRATO_RAMP_UP         3
+
+
+
+/* Probably useless :) */
+static const char xm_convert_vibrato[] = {
+	IT_VIBRATO_SINE,
+	IT_VIBRATO_SQUARE,
+	IT_VIBRATO_SAWTOOTH,
+	IT_VIBRATO_SAWTOOTH
+};
+
+
+
+#define XM_MAX_SAMPLES_PER_INSTRUMENT 16
+
+
+
+/* Extra data that doesn't fit inside IT_INSTRUMENT */
+typedef struct XM_INSTRUMENT_EXTRA {
+	int n_samples;
+	int vibrato_type;
+	int vibrato_sweep; /* 0-0xFF */
+	int vibrato_depth; /* 0-0x0F */
+	int vibrato_speed; /* 0-0x3F */
+}
+XM_INSTRUMENT_EXTRA;
+
+
+
+/* Frees the original block if it can't resize it or if size is 0, and acts
+ * as malloc if ptr is NULL.
+ */
+static void *safe_realloc(void *ptr, size_t size) {
+	if (ptr == NULL)
+		return malloc(size);
+
+	if (size == 0) {
+		free(ptr);
+		return NULL;
+	} else {
+		void *new_block = realloc(ptr, size);
+		if (!new_block)
+			free(ptr);
+		return new_block;
+	}
+}
+
+
+
+/* The interpretation of the XM volume column is left to the player. Here, we
+ * just filter bad values.
+ */
+ // This function is so tiny now, should we inline it?
+static void it_xm_convert_volume(int volume, IT_ENTRY *entry) {
+	entry->mask |= IT_ENTRY_VOLPAN;
+	entry->volpan = volume;
+
+	switch (volume >> 4) {
+	case 0xA: /* set vibrato speed */
+	case 0xB: /* vibrato */
+	case 0xF: /* tone porta */
+	case 0x6: /* vol slide up */
+	case 0x7: /* vol slide down */
+	case 0x8: /* fine vol slide up */
+	case 0x9: /* fine vol slide down */
+	case 0xC: /* set panning */
+	case 0xD: /* pan slide left */
+	case 0xE: /* pan slide right */
+	case 0x1: /* set volume */
+	case 0x2: /* set volume */
+	case 0x3: /* set volume */
+	case 0x4: /* set volume */
+		break;
+
+	case 0x5:
+		if (volume == 0x50)
+			break; /* set volume */
+		/* else fall through */
+
+	default:
+		entry->mask &= ~IT_ENTRY_VOLPAN;
+		break;
+	}
+}
+
+
+
+static int it_xm_read_pattern(IT_PATTERN *pattern, DUMBFILE *f, int n_channels, unsigned char *buffer) {
+	int size;
+	int pos;
+	int channel;
+	int row;
+	int effect, effectvalue;
+	IT_ENTRY *entry;
+
+	/* pattern header size */
+	if (dumbfile_igetl(f) != 0x09) {
+		TRACE("XM error: unexpected pattern header size\n");
+		return -1;
+	}
+
+	/* pattern data packing type */
+	if (dumbfile_getc(f) != 0) {
+		TRACE("XM error: unexpected pattern packing type\n");
+		return -1;
+	}
+
+	pattern->n_rows = dumbfile_igetw(f);  /* 1..256 */
+	size = dumbfile_igetw(f);
+	pattern->n_entries = 0;
+
+	if (dumbfile_error(f))
+		return -1;
+
+	if (size == 0)
+		return 0;
+
+	if (size > 1280 * n_channels) {
+		TRACE("XM error: pattern data size > %d bytes\n", 1280 * n_channels);
+		return -1;
+	}
+
+	if (dumbfile_getnc(buffer, size, f) < size)
+		return -1;
+
+	/* compute number of entries */
+	pattern->n_entries = 0;
+	pos = channel = row = 0;
+	while (pos < size) {
+		if (!(buffer[pos] & XM_ENTRY_PACKED) || (buffer[pos] & 31))
+			pattern->n_entries++;
+
+		channel++;
+		if (channel >= n_channels) {
+			channel = 0;
+			row++;
+			pattern->n_entries++;
+		}
+
+		if (buffer[pos] & XM_ENTRY_PACKED) {
+			static const char offset[] = { 0, 1, 1, 2, 1, 2, 2, 3,   1, 2, 2, 3, 2, 3, 3, 4,
+										   1, 2, 2, 3, 2, 3, 3, 4,   2, 3, 3, 4, 3, 4, 4, 5 };
+			pos += 1 + offset[buffer[pos] & 31];
+		} else {
+			pos += 5;
+		}
+	}
+
+	if (row != pattern->n_rows) {
+		TRACE("XM error: wrong number of rows in pattern data\n");
+		return -1;
+	}
+
+	pattern->entry = malloc(pattern->n_entries * sizeof(*pattern->entry));
+	if (!pattern->entry)
+		return -1;
+
+	/* read the entries */
+	entry = pattern->entry;
+	pos = channel = row = 0;
+	while (pos < size) {
+		unsigned char mask;
+
+		if (buffer[pos] & XM_ENTRY_PACKED)
+			mask = buffer[pos++] & 31;
+		else
+			mask = 31;
+
+		if (mask) {
+			ASSERT(entry < pattern->entry + pattern->n_entries);
+
+			entry->channel = channel;
+			entry->mask = 0;
+
+			if (mask & XM_ENTRY_NOTE) {
+				int note = buffer[pos++]; /* 1-96 <=> C0-B7 */
+				entry->note = (note == XM_NOTE_OFF) ? (IT_NOTE_OFF) : (note - 1);
+				entry->mask |= IT_ENTRY_NOTE;
+			}
+
+			if (mask & XM_ENTRY_INSTRUMENT) {
+				entry->instrument = buffer[pos++]; /* 1-128 */
+				entry->mask |= IT_ENTRY_INSTRUMENT;
+			}
+
+			if (mask & XM_ENTRY_VOLUME)
+				it_xm_convert_volume(buffer[pos++], entry);
+
+			effect = effectvalue = 0;
+			if (mask & XM_ENTRY_EFFECT)      effect = buffer[pos++];
+			if (mask & XM_ENTRY_EFFECTVALUE) effectvalue = buffer[pos++];
+			_dumb_it_xm_convert_effect(effect, effectvalue, entry);
+
+			entry++;
+		}
+
+		channel++;
+		if (channel >= n_channels) {
+			channel = 0;
+			row++;
+			IT_SET_END_ROW(entry);
+			entry++;
+		}
+	}
+
+	return 0;
+}
+
+
+
+static int it_xm_make_envelope(IT_ENVELOPE *envelope, const unsigned short *data, int y_offset) {
+	int i, pos;
+
+	if (envelope->n_nodes > 12) {
+		TRACE("XM error: wrong number of envelope nodes (%d)\n", envelope->n_nodes);
+		envelope->n_nodes = 0;
+		return -1;
+	}
+
+	pos = 0;
+	for (i = 0; i < envelope->n_nodes; i++) {
+		envelope->node_t[i] = data[pos++];
+		if (data[pos] > 64) {
+			TRACE("XM error: out-of-range envelope node (node_y[%d]=%d)\n", i, data[pos]);
+			envelope->n_nodes = 0;
+			return -1;
+		}
+		envelope->node_y[i] = (signed char)(data[pos++] + y_offset);
+	}
+
+	return 0;
+}
+
+
+
+static int it_xm_read_instrument(IT_INSTRUMENT *instrument, XM_INSTRUMENT_EXTRA *extra, DUMBFILE *f) {
+	unsigned long size, bytes_read;
+	unsigned short vol_points[24];
+	unsigned short pan_points[24];
+	int i, type;
+
+	/* Header size. Tends to be more than the actual size of the structure.
+	 * So unread bytes must be skipped before reading the first sample
+	 * header.
+	 */
+	size = dumbfile_igetl(f);
+
+	//memset(instrument, 0, sizeof(*instrument));
+	dumbfile_skip(f, 22); /* Instrument name */
+	dumbfile_skip(f, 1);  /* Instrument type. Should be 0, but seems random. */
+	extra->n_samples = dumbfile_igetw(f);
+
+	if (dumbfile_error(f) || (unsigned int)extra->n_samples > XM_MAX_SAMPLES_PER_INSTRUMENT)
+		return -1;
+
+	bytes_read = 4 + 22 + 1 + 2;
+
+	if (extra->n_samples) {
+		/* sample header size */
+		if (dumbfile_igetl(f) != 0x28) {
+			TRACE("XM error: unexpected sample header size\n");
+			return -1;
+		}
+
+		/* sample map */
+		for (i = 0; i < 96; i++) {
+			instrument->map_sample[i] = dumbfile_getc(f) + 1;
+			instrument->map_note[i] = i;
+		}
+
+		if (dumbfile_error(f))
+			return 1;
+
+		/* volume/panning envelopes */
+		for (i = 0; i < 24; i++)
+			vol_points[i] = dumbfile_igetw(f);
+		for (i = 0; i < 24; i++)
+			pan_points[i] = dumbfile_igetw(f);
+
+		instrument->volume_envelope.n_nodes = dumbfile_getc(f);
+		instrument->pan_envelope.n_nodes = dumbfile_getc(f);
+
+		if (dumbfile_error(f))
+			return -1;
+
+		instrument->volume_envelope.sus_loop_start = dumbfile_getc(f);
+		instrument->volume_envelope.loop_start = dumbfile_getc(f);
+		instrument->volume_envelope.loop_end = dumbfile_getc(f);
+
+		instrument->pan_envelope.sus_loop_start = dumbfile_getc(f);
+		instrument->pan_envelope.loop_start = dumbfile_getc(f);
+		instrument->pan_envelope.loop_end = dumbfile_getc(f);
+
+		/* The envelope handler for XM files won't use sus_loop_end. */
+
+		type = dumbfile_getc(f);
+		instrument->volume_envelope.flags = 0;
+		if ((type & XM_ENVELOPE_ON) && instrument->volume_envelope.n_nodes)
+			instrument->volume_envelope.flags |= IT_ENVELOPE_ON;
+		if (type & XM_ENVELOPE_LOOP)    instrument->volume_envelope.flags |= IT_ENVELOPE_LOOP_ON;
+#if 1
+		if (type & XM_ENVELOPE_SUSTAIN) instrument->volume_envelope.flags |= IT_ENVELOPE_SUSTAIN_LOOP;
+#else // This is now handled in itrender.c
+		/* let's avoid fading out when reaching the last envelope node */
+		if (!(type & XM_ENVELOPE_LOOP)) {
+			instrument->volume_envelope.loop_start = instrument->volume_envelope.n_nodes - 1;
+			instrument->volume_envelope.loop_end = instrument->volume_envelope.n_nodes - 1;
+		}
+		instrument->volume_envelope.flags |= IT_ENVELOPE_LOOP_ON;
+#endif
+
+		type = dumbfile_getc(f);
+		instrument->pan_envelope.flags = 0;
+		if ((type & XM_ENVELOPE_ON) && instrument->pan_envelope.n_nodes)
+			instrument->pan_envelope.flags |= IT_ENVELOPE_ON;
+		if (type & XM_ENVELOPE_LOOP)    instrument->pan_envelope.flags |= IT_ENVELOPE_LOOP_ON; // should this be here?
+		if (type & XM_ENVELOPE_SUSTAIN) instrument->pan_envelope.flags |= IT_ENVELOPE_SUSTAIN_LOOP;
+
+		if (it_xm_make_envelope(&instrument->volume_envelope, vol_points, 0) != 0) {
+			TRACE("XM error: volume envelope\n");
+			if (instrument->volume_envelope.flags & IT_ENVELOPE_ON) return -1;
+		}
+
+		if (it_xm_make_envelope(&instrument->pan_envelope, pan_points, -32) != 0) {
+			TRACE("XM error: pan envelope\n");
+			if (instrument->pan_envelope.flags & IT_ENVELOPE_ON) return -1;
+		}
+
+		instrument->pitch_envelope.flags = 0;
+
+		extra->vibrato_type = dumbfile_getc(f);
+		extra->vibrato_sweep = dumbfile_getc(f);
+		extra->vibrato_depth = dumbfile_getc(f);
+		extra->vibrato_speed = dumbfile_getc(f);
+
+		if (dumbfile_error(f) || extra->vibrato_type >= 4)
+			return -1;
+
+		/** WARNING: lossy approximation */
+		instrument->fadeout = (dumbfile_igetw(f) * 128 + 64) / 0xFFF;
+
+		dumbfile_skip(f, 2); /* reserved */
+
+		bytes_read += 4 + 96 + 48 + 48 + 14 * 1 + 2 + 2;
+	}
+
+	if (dumbfile_skip(f, size - bytes_read))
+		return -1;
+
+	instrument->new_note_action = NNA_NOTE_CUT;
+	instrument->dup_check_type = DCT_OFF;
+	instrument->dup_check_action = DCA_NOTE_CUT;
+	instrument->pp_separation = 0;
+	instrument->pp_centre = 60; /* C-5 */
+	instrument->global_volume = 128;
+	instrument->default_pan = 32;
+	instrument->random_volume = 0;
+	instrument->random_pan = 0;
+	instrument->filter_cutoff = 0;
+	instrument->filter_resonance = 0;
+
+	return 0;
+}
+
+
+
+/* I (entheh) have two XM files saved by a very naughty program. After a
+ * 16-bit sample, it saved a rogue byte. The length of the sample was indeed
+ * an odd number, incremented to include the rogue byte.
+ *
+ * In this function we are converting sample lengths and loop points so they
+ * are measured in samples. This means we forget about the extra bytes, and
+ * they don't get skipped. So we fail trying to read the next instrument.
+ *
+ * To get around this, this function returns the number of rogue bytes that
+ * won't be accounted for by reading sample->length samples. It returns a
+ * negative number on failure.
+ */
+static int it_xm_read_sample_header(IT_SAMPLE *sample, DUMBFILE *f) {
+	int type;
+	int relative_note_number; /* relative to C4 */
+	int finetune;
+	int roguebytes;
+	int roguebytesmask;
+
+	sample->length = dumbfile_igetl(f);
+	sample->loop_start = dumbfile_igetl(f);
+	sample->loop_end = sample->loop_start + dumbfile_igetl(f);
+	sample->global_volume = 64;
+	sample->default_volume = dumbfile_getc(f);
+	finetune = (signed char)dumbfile_getc(f); /* -128..127 <=> -1 semitone .. +127/128 of a semitone */
+	type = dumbfile_getc(f);
+	sample->default_pan = (dumbfile_getc(f) * 64) / 255 | 128; /* 0-255 */
+	relative_note_number = (signed char)dumbfile_getc(f);
+
+	dumbfile_skip(f, 1);  /* reserved */
+	dumbfile_skip(f, 22); /* sample name */
+
+	if (dumbfile_error(f))
+		return -1;
+
+	sample->C5_speed = (long)(16726.0 * pow(DUMB_SEMITONE_BASE, relative_note_number) * pow(DUMB_PITCH_BASE, finetune * 2));
+
+	sample->flags = IT_SAMPLE_EXISTS;
+
+	roguebytes = (int)sample->length;
+	roguebytesmask = 3;
+
+	if (type & XM_SAMPLE_16BIT) {
+		sample->flags |= IT_SAMPLE_16BIT;
+		sample->length >>= 1;
+		sample->loop_start >>= 1;
+		sample->loop_end >>= 1;
+	} else
+		roguebytesmask >>= 1;
+
+	if (type & XM_SAMPLE_STEREO) {
+		sample->flags |= IT_SAMPLE_STEREO;
+		sample->length >>= 1;
+		sample->loop_start >>= 1;
+		sample->loop_end >>= 1;
+	} else
+		roguebytesmask >>= 1;
+
+	roguebytes &= roguebytesmask;
+
+	if ((unsigned int)sample->loop_start < (unsigned int)sample->loop_end) {
+		if (type & XM_SAMPLE_FORWARD_LOOP) sample->flags |= IT_SAMPLE_LOOP;
+		if (type & XM_SAMPLE_PINGPONG_LOOP) sample->flags |= IT_SAMPLE_LOOP | IT_SAMPLE_PINGPONG_LOOP;
+	}
+
+	if (sample->length <= 0)
+		sample->flags &= ~IT_SAMPLE_EXISTS;
+	else if ((unsigned int)sample->loop_end > (unsigned int)sample->length)
+		sample->flags &= ~IT_SAMPLE_LOOP;
+	else if ((unsigned int)sample->loop_start >= (unsigned int)sample->loop_end)
+		sample->flags &= ~IT_SAMPLE_LOOP;
+
+	return roguebytes;
+}
+
+
+
+static int it_xm_read_sample_data(IT_SAMPLE *sample, unsigned char roguebytes, DUMBFILE *f) {
+	int old;
+	long i;
+	long truncated_size;
+
+	if (!(sample->flags & IT_SAMPLE_EXISTS))
+		return dumbfile_skip(f, roguebytes);
+
+	/* let's get rid of the sample data coming after the end of the loop */
+	if ((sample->flags & IT_SAMPLE_LOOP) && sample->loop_end < sample->length) {
+		truncated_size = sample->length - sample->loop_end;
+		sample->length = sample->loop_end;
+	} else {
+		truncated_size = 0;
+	}
+
+	sample->left = malloc(sample->length * sizeof(*sample->left));
+	if (!sample->left)
+		return -1;
+
+	if (sample->flags & IT_SAMPLE_STEREO) {
+		sample->right = malloc(sample->length * sizeof(*sample->right));
+		if (!sample->right)
+			return -1;
+	}
+
+	/* sample data is stored as signed delta values */
+	old = 0;
+	if (sample->flags & IT_SAMPLE_16BIT) {
+		for (i = 0; i < sample->length; i++) {
+			old = sample->left[i] = (int)(signed short)(old + dumbfile_igetw(f));
+			sample->left[i] <<= 8;
+		}
+	} else {
+		for (i = 0; i < sample->length; i++) {
+			old = sample->left[i] = (int)(signed char)(old + dumbfile_getc(f));
+			sample->left[i] <<= 16;
+		}
+	}
+
+	/* skip truncated data */
+	dumbfile_skip(f, (sample->flags & IT_SAMPLE_16BIT) ? (2 * truncated_size) : (truncated_size));
+
+	if (sample->flags & IT_SAMPLE_STEREO) {
+		old = 0;
+		if (sample->flags & IT_SAMPLE_16BIT) {
+			for (i = 0; i < sample->length; i++) {
+				old = sample->right[i] = (int)(signed short)(old + dumbfile_igetw(f));
+				sample->right[i] <<= 8;
+			}
+		} else {
+			for (i = 0; i < sample->length; i++) {
+				old = sample->right[i] = (int)(signed char)(old + dumbfile_getc(f));
+				sample->right[i] <<= 16;
+			}
+		}
+		/* skip truncated data */
+		dumbfile_skip(f, (sample->flags & IT_SAMPLE_16BIT) ? (2 * truncated_size) : (truncated_size));
+	}
+
+	dumbfile_skip(f, roguebytes);
+
+	if (dumbfile_error(f))
+		return -1;
+
+	return 0;
+}
+
+
+
+/* "Real programmers don't document. If it was hard to write,
+ *  it should be hard to understand."
+ *
+ * (Never trust the documentation provided with a tracker.
+ *  Real files are the only truth...)
+ */
+static DUMB_IT_SIGDATA *it_xm_load_sigdata(DUMBFILE *f) {
+	DUMB_IT_SIGDATA *sigdata;
+	char id_text[18];
+
+	int flags;
+	int n_channels;
+	int total_samples;
+	int i, j;
+
+	/* check ID text */
+	if (dumbfile_getnc(id_text, 17, f) < 17)
+		return NULL;
+	id_text[17] = 0;
+	if (strcmp(id_text, "Extended Module: ") != 0) {
+		TRACE("XM error: Not an Extended Module\n");
+		return NULL;
+	}
+
+	/* song name */
+	if (dumbfile_skip(f, 20))
+		return NULL;
+
+	if (dumbfile_getc(f) != 0x1A) {
+		TRACE("XM error: 0x1A not found\n");
+		return NULL;
+	}
+
+	/* tracker name */
+	if (dumbfile_skip(f, 20))
+		return NULL;
+
+	/* version number */
+	if (dumbfile_igetw(f) != 0x0104) {
+		TRACE("XM error: wrong format version\n");
+		return NULL;
+	}
+
+	/*
+		------------------
+		---   Header   ---
+		------------------
+	*/
+
+	/* header size */
+	if (dumbfile_igetl(f) != 0x0114) {
+		TRACE("XM error: unexpected header size\n");
+		return NULL;
+	}
+
+	sigdata = malloc(sizeof(*sigdata));
+	if (!sigdata)
+		return NULL;
+
+	sigdata->order = NULL;
+	sigdata->instrument = NULL;
+	sigdata->sample = NULL;
+	sigdata->pattern = NULL;
+	sigdata->midi = NULL;
+	sigdata->checkpoint = NULL;
+
+	sigdata->n_samples = 0;
+	sigdata->n_orders = dumbfile_igetw(f);
+	sigdata->restart_position = dumbfile_igetw(f);
+	n_channels = dumbfile_igetw(f); /* max 32 but we'll be lenient */
+	sigdata->n_patterns = dumbfile_igetw(f);
+	sigdata->n_instruments = dumbfile_igetw(f); /* max 128 */
+	flags = dumbfile_igetw(f);
+	sigdata->speed = dumbfile_igetw(f);
+	sigdata->tempo = dumbfile_igetw(f);
+
+	/* sanity checks */
+	if (dumbfile_error(f) || sigdata->n_orders <= 0 || sigdata->n_orders > 256 || sigdata->n_patterns > 256 || sigdata->n_instruments > 128 || n_channels > DUMB_IT_N_CHANNELS) {
+		_dumb_it_unload_sigdata(sigdata);
+		return NULL;
+	}
+
+	//if (sigdata->restart_position >= sigdata->n_orders)
+		//sigdata->restart_position = 0;
+
+	/* order table */
+	sigdata->order = malloc(sigdata->n_orders * sizeof(*sigdata->order));
+	if (!sigdata->order) {
+		_dumb_it_unload_sigdata(sigdata);
+		return NULL;
+	}
+	dumbfile_getnc(sigdata->order, sigdata->n_orders, f);
+	dumbfile_skip(f, 256 - sigdata->n_orders);
+
+	if (dumbfile_error(f)) {
+		_dumb_it_unload_sigdata(sigdata);
+		return NULL;
+	}
+
+	/*
+		--------------------
+		---   Patterns   ---
+		--------------------
+	*/
+
+	sigdata->pattern = malloc(sigdata->n_patterns * sizeof(*sigdata->pattern));
+	if (!sigdata->pattern) {
+		_dumb_it_unload_sigdata(sigdata);
+		return NULL;
+	}
+	for (i = 0; i < sigdata->n_patterns; i++)
+		sigdata->pattern[i].entry = NULL;
+
+	{
+		unsigned char *buffer = malloc(1280 * n_channels); /* 256 rows * 5 bytes */
+		if (!buffer) {
+			_dumb_it_unload_sigdata(sigdata);
+			return NULL;
+		}
+		for (i = 0; i < sigdata->n_patterns; i++) {
+			if (it_xm_read_pattern(&sigdata->pattern[i], f, n_channels, buffer) != 0) {
+				free(buffer);
+				_dumb_it_unload_sigdata(sigdata);
+				return NULL;
+			}
+		}
+		free(buffer);
+	}
+
+	/*
+		-----------------------------------
+		---   Instruments and Samples   ---
+		-----------------------------------
+	*/
+
+	sigdata->instrument = malloc(sigdata->n_instruments * sizeof(*sigdata->instrument));
+	if (!sigdata->instrument) {
+		_dumb_it_unload_sigdata(sigdata);
+		return NULL;
+	}
+
+	/* With XM, samples are not global, they're part of an instrument. In a
+	 * file, each instrument is stored with its samples. Because of this, I
+	 * don't know how to find how many samples are present in the file. Thus
+	 * I have to do n_instruments reallocation on sigdata->sample.
+	 * Looking at FT2, it doesn't seem possible to have more than 16 samples
+	 * per instrument (even though n_samples is stored as 2 bytes). So maybe
+	 * we could allocate a 128*16 array of samples, and shrink it back to the
+	 * correct size when we know it?
+	 * Alternatively, I could allocate samples by blocks of N (still O(n)),
+	 * or double the number of allocated samples when I need more (O(log n)).
+	 */
+	total_samples = 0;
+	sigdata->sample = NULL;
+
+	for (i = 0; i < sigdata->n_instruments; i++) {
+		XM_INSTRUMENT_EXTRA extra;
+
+		if (it_xm_read_instrument(&sigdata->instrument[i], &extra, f) < 0) {
+			TRACE("XM error: instrument %d\n", i + 1);
+			_dumb_it_unload_sigdata(sigdata);
+			return NULL;
+		}
+
+		if (extra.n_samples) {
+			unsigned char roguebytes[XM_MAX_SAMPLES_PER_INSTRUMENT];
+
+			/* adjust instrument sample map (make indices absolute) */
+			for (j = 0; j < 96; j++)
+				sigdata->instrument[i].map_sample[j] += total_samples;
+
+			sigdata->sample = safe_realloc(sigdata->sample, sizeof(*sigdata->sample) * (total_samples + extra.n_samples));
+			if (!sigdata->sample) {
+				_dumb_it_unload_sigdata(sigdata);
+				return NULL;
+			}
+			for (j = total_samples; j < total_samples + extra.n_samples; j++)
+				sigdata->sample[j].right = sigdata->sample[j].left = NULL;
+
+			/* read instrument's samples */
+			for (j = 0; j < extra.n_samples; j++) {
+				IT_SAMPLE *sample = &sigdata->sample[total_samples + j];
+				int b = it_xm_read_sample_header(sample, f);
+				if (b < 0) {
+					_dumb_it_unload_sigdata(sigdata);
+					return NULL;
+				}
+				roguebytes[j] = b;
+				// Any reason why these can't be set inside it_xm_read_sample_header()?
+				sample->vibrato_speed = extra.vibrato_speed;
+				sample->vibrato_depth = extra.vibrato_depth;
+				sample->vibrato_rate = extra.vibrato_sweep;
+				/* Rate and sweep don't match, but the difference is
+				 * accounted for in itrender.c.
+				 */
+				sample->vibrato_waveform = xm_convert_vibrato[extra.vibrato_type];
+			}
+			for (j = 0; j < extra.n_samples; j++) {
+				if (it_xm_read_sample_data(&sigdata->sample[total_samples + j], roguebytes[j], f) != 0) {
+					_dumb_it_unload_sigdata(sigdata);
+					return NULL;
+				}
+			}
+			total_samples += extra.n_samples;
+		}
+	}
+
+	sigdata->n_samples = total_samples;
+
+	sigdata->flags = IT_WAS_AN_XM | IT_OLD_EFFECTS | IT_COMPATIBLE_GXX | IT_STEREO | IT_USE_INSTRUMENTS;
+	// Are we OK with IT_COMPATIBLE_GXX off?
+	//
+	// When specifying note + instr + tone portamento, and an old note is still playing (even after note off):
+	// - If Compatible Gxx is on, the new note will be triggered only if the instrument _changes_.
+	// - If Compatible Gxx is off, the new note will always be triggered, provided the instrument is specified.
+	// - FT2 seems to do the latter (unconfirmed).
+
+	// Err, wait. XM playback has its own code. The change made to the IT
+	// playbackc code didn't affect XM playback. Forget this then. There's
+	// still a bug in XM playback though, and it'll need some investigation...
+	// tomorrow...
+
+	// UPDATE: IT_COMPATIBLE_GXX is required to be on, so that tone porta has
+	// separate memory from portamento.
+
+	if (flags & XM_LINEAR_FREQUENCY)
+		sigdata->flags |= IT_LINEAR_SLIDES;
+
+	sigdata->global_volume = 128;
+	sigdata->mixing_volume = 48;
+	sigdata->pan_separation = 128;
+
+	memset(sigdata->channel_volume, 64, DUMB_IT_N_CHANNELS);
+	memset(sigdata->channel_pan, 32, DUMB_IT_N_CHANNELS);
+
+	_dumb_it_fix_invalid_orders(sigdata);
+
+	return sigdata;
+}
+
+
+
+#if 0 // no fucking way, dude!
+
+/* The length returned is the time required to play from the beginning of the
+ * file to the last row of the last order (which is when the player will
+ * loop). Depending on the song, the sound might stop sooner.
+ * Due to fixed point roundoffs, I think this is only reliable to the second.
+ * Full precision could be achieved by using a double during the computation,
+ * or maybe a LONG_LONG.
+ */
+long it_compute_length(const DUMB_IT_SIGDATA *sigdata) {
+	IT_PATTERN *pattern;
+	int tempo, speed;
+	int loop_start[IT_N_CHANNELS];
+	char loop_count[IT_N_CHANNELS];
+	int order, entry;
+	int row_first_entry = 0;
+	int jump, jump_dest;
+	int delay, fine_delay;
+	int i;
+	long t;
+
+	if (!sigdata)
+		return 0;
+
+	tempo = sigdata->tempo;
+	speed = sigdata->speed;
+	order = entry = 0;
+	jump = jump_dest = 0;
+	t = 0;
+
+	/* for each PATTERN */
+	for (order = 0; order < sigdata->n_orders; order++) {
+
+		if (sigdata->order[order] == IT_ORDER_END) break;
+		if (sigdata->order[order] == IT_ORDER_SKIP) continue;
+
+		for (i = 0; i < IT_N_CHANNELS; i++)
+			loop_count[i] = -1;
+
+		pattern = &sigdata->pattern[sigdata->order[order]];
+		entry = 0;
+		if (jump == IT_BREAK_TO_ROW) {
+			int row = 0;
+			while (row < jump_dest)
+				if (pattern->entry[entry++].channel >= IT_N_CHANNELS)
+					row++;
+		}
+
+		/* for each ROW */
+		while (entry < pattern->n_entries) {
+			row_first_entry = entry;
+			delay = fine_delay = 0;
+			jump = 0;
+
+			/* for each note NOTE */
+			while (entry < pattern->n_entries && pattern->entry[entry].channel < IT_N_CHANNELS) {
+				int value = pattern->entry[entry].effectvalue;
+				int channel = pattern->entry[entry].channel;
+
+				switch (pattern->entry[entry].effect) {
+
+				case IT_SET_SPEED: speed = value; break;
+
+				case IT_JUMP_TO_ORDER:
+					if (value <= order) /* infinite loop */
+						return 0;
+					jump = IT_JUMP_TO_ORDER;
+					jump_dest = value;
+					break;
+
+				case IT_BREAK_TO_ROW:
+					jump = IT_BREAK_TO_ROW;
+					jump_dest = value;
+					break;
+
+				case IT_S:
+					switch (HIGH(value)) {
+					case IT_S_PATTERN_DELAY:      delay = LOW(value); break;
+					case IT_S_FINE_PATTERN_DELAY: fine_delay = LOW(value); break;
+					case IT_S_PATTERN_LOOP:
+						if (LOW(value) == 0) {
+							loop_start[channel] = row_first_entry;
+						} else {
+							if (loop_count[channel] == -1)
+								loop_count[channel] = LOW(value);
+
+							if (loop_count[channel]) {
+								jump = IT_S_PATTERN_LOOP;
+								jump_dest = loop_start[channel];
+							}
+							loop_count[channel]--;
+						}
+						break;
+					}
+					break;
+
+				case IT_SET_SONG_TEMPO:
+					switch (HIGH(value)) { /* slides happen every non-row frames */
+					case 0:  tempo = tempo - LOW(value) * (speed - 1); break;
+					case 1:  tempo = tempo + LOW(value) * (speed - 1); break;
+					default: tempo = value;
+					}
+					tempo = MID(32, tempo, 255);
+					break;
+				}
+
+				entry++;
+			}
+
+			/* end of ROW */
+			entry++;
+			t += TICK_TIME_DIVIDEND * (speed * (1 + delay) + fine_delay) / tempo;
+
+			if (jump == IT_JUMP_TO_ORDER) {
+				order = jump_dest - 1;
+				break;
+			} else if (jump == IT_BREAK_TO_ROW)
+				break;
+			else if (jump == IT_S_PATTERN_LOOP)
+				entry = jump_dest - 1;
+		}
+
+		/* end of PATTERN */
+	}
+
+	return t;
+}
+
+#endif /* 0 */
+
+
+
+DUH *dumb_read_xm(DUMBFILE *f) {
+	sigdata_t *sigdata;
+	long length;
+
+	DUH_SIGTYPE_DESC *descptr = &_dumb_sigtype_it;
+
+	sigdata = it_xm_load_sigdata(f);
+
+	if (!sigdata)
+		return NULL;
+
+	length = _dumb_it_build_checkpoints(sigdata);
+
+	return make_duh(length, 1, &descptr, &sigdata);
+}
+
+} // namespace AGS3


Commit: 04ed87109853ae912a2bec80f1d4573a0d640992
    https://github.com/scummvm/scummvm/commit/04ed87109853ae912a2bec80f1d4573a0d640992
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added missing allegro gfx methods

Changed paths:
  A engines/ags/lib/allegro/aintern.h
  A engines/ags/lib/allegro/graphics.cpp
    engines/ags/lib/allegro/color.cpp
    engines/ags/lib/allegro/color.h
    engines/ags/lib/allegro/system.cpp
    engines/ags/module.mk


diff --git a/engines/ags/lib/allegro/aintern.h b/engines/ags/lib/allegro/aintern.h
new file mode 100644
index 0000000000..37ac742507
--- /dev/null
+++ b/engines/ags/lib/allegro/aintern.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 AGS_LIB_ALLEGRO_AINTERN_H
+#define AGS_LIB_ALLEGRO_AINTERN_H
+
+#include "ags/lib/allegro/base.h"
+#include "ags/lib/allegro/color.h"
+
+namespace AGS3 {
+
+extern int _color_depth;
+
+/* truecolor blending functions */
+AL_VAR(BLENDER_FUNC, _blender_func15);
+AL_VAR(BLENDER_FUNC, _blender_func16);
+AL_VAR(BLENDER_FUNC, _blender_func24);
+AL_VAR(BLENDER_FUNC, _blender_func32);
+
+AL_VAR(int, _blender_alpha);
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/lib/allegro/color.cpp b/engines/ags/lib/allegro/color.cpp
index 5126e5c62e..41eed40000 100644
--- a/engines/ags/lib/allegro/color.cpp
+++ b/engines/ags/lib/allegro/color.cpp
@@ -21,6 +21,8 @@
  */
 
 #include "ags/lib/allegro/color.h"
+#include "ags/lib/allegro/system.h"
+#include "ags/lib/allegro/aintern.h"
 #include "common/textconsole.h"
 #include "common/system.h"
 #include "graphics/palette.h"
@@ -46,10 +48,6 @@ AL_ARRAY(int, _rgb_scale_6);
 
 PALETTE _current_palette;
 
-int bestfit_color(const PALETTE pal, int r, int g, int b) {
-	error("TODO: bestfit_color");
-}
-
 void set_color(int idx, const RGB *p) {
 	_current_palette[idx] = *p;
 	g_system->getPaletteManager()->setPalette((const byte *)p, idx, 1);
@@ -74,22 +72,6 @@ void set_palette_range(const PALETTE p, int from, int to, int retracesync) {
 	g_system->getPaletteManager()->setPalette(&palette[from], from, to - from + 1);
 }
 
-int makeacol(int r, int g, int b, int a) {
-	error("TODO: makeacol");
-}
-
-int makeacol_depth(int color_depth, int r, int g, int b, int a) {
-	error("TODO: makeacol_depth");
-}
-
-void hsv_to_rgb(float h, float s, float v, int *r, int *g, int *b) {
-	error("TODO: hsv_to_rgb");
-}
-
-void rgb_to_hsv(int r, int g, int b, float *h, float *s, float *v) {
-	error("TODO: rgb_to_hsv");
-}
-
 int makecol15(int r, int g, int b) {
 	return (((r >> 3) << _rgb_r_shift_15) |
 		((g >> 3) << _rgb_g_shift_15) |
@@ -157,6 +139,22 @@ int getb16(int c) {
    return _rgb_scale_5[(c >> _rgb_b_shift_16) & 0x1F];
 }
 
+int getr24(int c) {
+	error("TODO: getr24");
+}
+
+int getg24(int c) {
+	error("TODO: getg24");
+}
+
+int getb24(int c) {
+	error("TODO: getb24");
+}
+
+int geta24(int c) {
+	error("TODO: geta24");
+}
+
 int getr32(int c) {
 	error("TODO: getr32");
 }
@@ -181,20 +179,953 @@ int makecol8(byte r, byte g, byte b) {
 	return (b) | (g << 8) | (r << 16);
 }
 
+void get_color(int idx, RGB *p) {
+	warning("TODO: get_color");
+}
+
+void get_palette(PALETTE p) {
+	warning("TODO: get_palette");
+}
+
+void get_palette_range(PALETTE p, int from, int to) {
+	warning("TODO: get_palette_range");
+}
+
+void fade_interpolate(AL_CONST PALETTE source, AL_CONST PALETTE dest, PALETTE output, int pos, int from, int to) {
+	warning("TODO: fade_interpolate");
+}
+
+void fade_from_range(AL_CONST PALETTE source, AL_CONST PALETTE dest, int speed, int from, int to) {
+	warning("TODO: fade_from_range");
+}
+
+void fade_in_range(AL_CONST PALETTE p, int speed, int from, int to) {
+	warning("TODO: fade_in_range");
+}
+
+void fade_out_range(int speed, int from, int to) {
+	warning("TODO: fade_out_range");
+}
+
+void fade_from(AL_CONST PALETTE source, AL_CONST PALETTE dest, int speed) {
+	warning("TODO: fade_from");
+}
+
+void fade_in(AL_CONST PALETTE p, int speed) {
+	warning("TODO: fade_in");
+}
+
+void fade_out(int speed) {
+	warning("TODO: fade_out");
+}
+
+void select_palette(AL_CONST PALETTE p) {
+	warning("TODO: select_palette");
+}
+
+void unselect_palette(void) {
+	warning("TODO: unselect_palette");
+}
+
+void generate_332_palette(PALETTE pal) {
+	warning("TODO: generate_332_palette");
+}
+
+int generate_optimized_palette(BITMAP *image, PALETTE pal, AL_CONST signed char rsvdcols[256]) {
+	warning("TODO: generate_optimized_palette");
+	return 0;
+}
+
+void set_blender_mode(BLENDER_FUNC b15, BLENDER_FUNC b16, BLENDER_FUNC b24, int r, int g, int b, int a) {
+	warning("TODO: set_blender_mode");
+}
+
+void set_blender_mode_ex(BLENDER_FUNC b15, BLENDER_FUNC b16, BLENDER_FUNC b24, BLENDER_FUNC b32, BLENDER_FUNC b15x, BLENDER_FUNC b16x, BLENDER_FUNC b24x, int r, int g, int b, int a) {
+	warning("TODO: set_blender_mode_ex");
+}
+
+void set_alpha_blender(void) {
+	warning("TODO: set_alpha_blender");
+}
+
+void set_write_alpha_blender(void) {
+	warning("TODO: set_write_alpha_blender");
+}
+
+void set_trans_blender(int r, int g, int b, int a) {
+	warning("TODO: set_trans_blender");
+}
+
+void set_add_blender(int r, int g, int b, int a) {
+	warning("TODO: set_add_blender");
+}
+
+void set_burn_blender(int r, int g, int b, int a) {
+	warning("TODO: set_burn_blender");
+}
+
+void set_color_blender(int r, int g, int b, int a) {
+	warning("TODO: set_color_blender");
+}
+
+void set_difference_blender(int r, int g, int b, int a) {
+	warning("TODO: set_difference_blender");
+}
+
+void set_dissolve_blender(int r, int g, int b, int a) {
+	warning("TODO: set_dissolve_blender");
+}
+
+void set_dodge_blender(int r, int g, int b, int a) {
+	warning("TODO: set_dodge_blender");
+}
+
+void set_hue_blender(int r, int g, int b, int a) {
+	warning("TODO: set_hue_blender");
+}
+
+void set_invert_blender(int r, int g, int b, int a) {
+	warning("TODO: set_invert_blender");
+}
+
+void set_luminance_blender(int r, int g, int b, int a) {
+	warning("TODO: set_luminance_blender");
+}
+
+void set_multiply_blender(int r, int g, int b, int a) {
+	warning("TODO: set_multiply_blender");
+}
+
+void set_saturation_blender(int r, int g, int b, int a) {
+	warning("TODO: set_saturation_blender");
+}
+
+void set_screen_blender(int r, int g, int b, int a) {
+	warning("TODO: set_screen_blender");
+}
+
+
+/* makecol_depth:
+ *  Converts R, G, and B values (ranging 0-255) to whatever pixel format
+ *  is required by the specified color depth.
+ */
+int makecol_depth(int color_depth, int r, int g, int b) {
+	switch (color_depth) {
+
+	case 8:
+		return makecol8(r, g, b);
+
+	case 15:
+		return makecol15(r, g, b);
+
+	case 16:
+		return makecol16(r, g, b);
+
+	case 24:
+		return makecol24(r, g, b);
+
+	case 32:
+		return makecol32(r, g, b);
+	}
+
+	return 0;
+}
+
+
+
+/* makeacol_depth:
+ *  Converts R, G, B, and A values (ranging 0-255) to whatever pixel format
+ *  is required by the specified color depth.
+ */
+int makeacol_depth(int color_depth, int r, int g, int b, int a) {
+	switch (color_depth) {
+
+	case 8:
+		return makecol8(r, g, b);
+
+	case 15:
+		return makecol15(r, g, b);
+
+	case 16:
+		return makecol16(r, g, b);
+
+	case 24:
+		return makecol24(r, g, b);
+
+	case 32:
+		return makeacol32(r, g, b, a);
+	}
+
+	return 0;
+}
+
+
+
+/* makecol:
+ *  Converts R, G, and B values (ranging 0-255) to whatever pixel format
+ *  is required by the current video mode.
+ */
+int makecol(int r, int g, int b) {
+	return makecol_depth(_color_depth, r, g, b);
+}
+
+
+
+/* makeacol:
+ *  Converts R, G, B, and A values (ranging 0-255) to whatever pixel format
+ *  is required by the current video mode.
+ */
+int makeacol(int r, int g, int b, int a) {
+	return makeacol_depth(_color_depth, r, g, b, a);
+}
+
+
+
+/* getr_depth:
+ *  Extracts the red component (ranging 0-255) from a pixel in the format
+ *  being used by the specified color depth.
+ */
 int getr_depth(int color_depth, int c) {
-	error("TOD: getr_depth");
+	switch (color_depth) {
+
+	case 8:
+		return getr8(c);
+
+	case 15:
+		return getr15(c);
+
+	case 16:
+		return getr16(c);
+
+	case 24:
+		return getr24(c);
+
+	case 32:
+		return getr32(c);
+	}
+
+	return 0;
 }
 
+
+
+/* getg_depth:
+ *  Extracts the green component (ranging 0-255) from a pixel in the format
+ *  being used by the specified color depth.
+ */
 int getg_depth(int color_depth, int c) {
-	error("TOD: getg_depth");
+	switch (color_depth) {
+
+	case 8:
+		return getg8(c);
+
+	case 15:
+		return getg15(c);
+
+	case 16:
+		return getg16(c);
+
+	case 24:
+		return getg24(c);
+
+	case 32:
+		return getg32(c);
+	}
+
+	return 0;
 }
 
+
+
+/* getb_depth:
+ *  Extracts the blue component (ranging 0-255) from a pixel in the format
+ *  being used by the specified color depth.
+ */
 int getb_depth(int color_depth, int c) {
-	error("TOD: getb_depth");
+	switch (color_depth) {
+
+	case 8:
+		return getb8(c);
+
+	case 15:
+		return getb15(c);
+
+	case 16:
+		return getb16(c);
+
+	case 24:
+		return getb24(c);
+
+	case 32:
+		return getb32(c);
+	}
+
+	return 0;
 }
 
+
+
+/* geta_depth:
+ *  Extracts the alpha component (ranging 0-255) from a pixel in the format
+ *  being used by the specified color depth.
+ */
 int geta_depth(int color_depth, int c) {
-	error("TOD: geta_depth");
+	if (color_depth == 32)
+		return geta32(c);
+
+	return 0;
+}
+
+
+
+/* getr:
+ *  Extracts the red component (ranging 0-255) from a pixel in the format
+ *  being used by the current video mode.
+ */
+int getr(int c) {
+	return getr_depth(_color_depth, c);
+}
+
+
+
+/* getg:
+ *  Extracts the green component (ranging 0-255) from a pixel in the format
+ *  being used by the current video mode.
+ */
+int getg(int c) {
+	return getg_depth(_color_depth, c);
+}
+
+
+
+/* getb:
+ *  Extracts the blue component (ranging 0-255) from a pixel in the format
+ *  being used by the current video mode.
+ */
+int getb(int c) {
+	return getb_depth(_color_depth, c);
+}
+
+
+
+/* geta:
+ *  Extracts the alpha component (ranging 0-255) from a pixel in the format
+ *  being used by the current video mode.
+ */
+int geta(int c) {
+	return geta_depth(_color_depth, c);
+}
+
+
+
+/* 1.5k lookup table for color matching */
+static unsigned int col_diff[3 * 128];
+
+
+
+/* bestfit_init:
+ *  Color matching is done with weighted squares, which are much faster
+ *  if we pregenerate a little lookup table...
+ */
+static void bestfit_init(void) {
+	int i;
+
+	for (i = 1; i < 64; i++) {
+		int k = i * i;
+		col_diff[0 + i] = col_diff[0 + 128 - i] = k * (59 * 59);
+		col_diff[128 + i] = col_diff[128 + 128 - i] = k * (30 * 30);
+		col_diff[256 + i] = col_diff[256 + 128 - i] = k * (11 * 11);
+	}
+}
+
+
+
+/* bestfit_color:
+ *  Searches a palette for the color closest to the requested R, G, B value.
+ */
+int bestfit_color(AL_CONST PALETTE pal, int r, int g, int b) {
+	int i, coldiff, lowest, bestfit;
+
+	assert(r >= 0 && r <= 63);
+	assert(g >= 0 && g <= 63);
+	assert(b >= 0 && b <= 63);
+
+	if (col_diff[1] == 0)
+		bestfit_init();
+
+	bestfit = 0;
+	lowest = INT_MAX;
+
+	/* only the transparent (pink) color can be mapped to index 0 */
+	if ((r == 63) && (g == 0) && (b == 63))
+		i = 0;
+	else
+		i = 1;
+
+	while (i < PAL_SIZE) {
+		AL_CONST RGB *rgb = &pal[i];
+		coldiff = (col_diff + 0)[(rgb->g - g) & 0x7F];
+		if (coldiff < lowest) {
+			coldiff += (col_diff + 128)[(rgb->r - r) & 0x7F];
+			if (coldiff < lowest) {
+				coldiff += (col_diff + 256)[(rgb->b - b) & 0x7F];
+				if (coldiff < lowest) {
+					bestfit = rgb - pal;    /* faster than `bestfit = i;' */
+					if (coldiff == 0)
+						return bestfit;
+					lowest = coldiff;
+				}
+			}
+		}
+		i++;
+	}
+
+	return bestfit;
+}
+
+
+
+/* makecol8:
+ *  Converts R, G, and B values (ranging 0-255) to an 8 bit paletted color.
+ *  If the global rgb_map table is initialised, it uses that, otherwise
+ *  it searches through the current palette to find the best match.
+ */
+int makecol8(int r, int g, int b) {
+	if (rgb_map)
+		return rgb_map->data[r >> 3][g >> 3][b >> 3];
+	else
+		return bestfit_color(_current_palette, r >> 2, g >> 2, b >> 2);
+}
+
+
+
+/* hsv_to_rgb:
+ *  Converts from HSV colorspace to RGB values.
+ */
+void hsv_to_rgb(float h, float s, float v, int *r, int *g, int *b) {
+	float f, x, y, z;
+	int i;
+
+	assert(s >= 0 && s <= 1);
+	assert(v >= 0 && v <= 1);
+
+	v *= 255.0f;
+
+	if (s == 0.0f) { /* ok since we don't divide by s, and faster */
+		*r = *g = *b = v + 0.5f;
+	} else {
+		h = fmod(h, 360.0f) / 60.0f;
+		if (h < 0.0f)
+			h += 6.0f;
+
+		i = (int)h;
+		f = h - i;
+		x = v * s;
+		y = x * f;
+		v += 0.5f; /* round to the nearest integer below */
+		z = v - x;
+
+		switch (i) {
+
+		case 6:
+		case 0:
+			*r = v;
+			*g = z + y;
+			*b = z;
+			break;
+
+		case 1:
+			*r = v - y;
+			*g = v;
+			*b = z;
+			break;
+
+		case 2:
+			*r = z;
+			*g = v;
+			*b = z + y;
+			break;
+
+		case 3:
+			*r = z;
+			*g = v - y;
+			*b = v;
+			break;
+
+		case 4:
+			*r = z + y;
+			*g = z;
+			*b = v;
+			break;
+
+		case 5:
+			*r = v;
+			*g = z;
+			*b = v - y;
+			break;
+		}
+	}
+}
+
+
+
+/* rgb_to_hsv:
+ *  Converts an RGB value into the HSV colorspace.
+ */
+void rgb_to_hsv(int r, int g, int b, float *h, float *s, float *v) {
+	int delta;
+
+	assert(r >= 0 && r <= 255);
+	assert(g >= 0 && g <= 255);
+	assert(b >= 0 && b <= 255);
+
+	if (r > g) {
+		if (b > r) {
+			/* b>r>g */
+			delta = b - g;
+			*h = 240.0f + ((r - g) * 60) / (float)delta;
+			*s = (float)delta / (float)b;
+			*v = (float)b * (1.0f / 255.0f);
+		} else {
+			/* r>g and r>b */
+			delta = r - MIN(g, b);
+			*h = ((g - b) * 60) / (float)delta;
+			if (*h < 0.0f)
+				*h += 360.0f;
+			*s = (float)delta / (float)r;
+			*v = (float)r * (1.0f / 255.0f);
+		}
+	} else {
+		if (b > g) {
+			/* b>g>=r */
+			delta = b - r;
+			*h = 240.0f + ((r - g) * 60) / (float)delta;
+			*s = (float)delta / (float)b;
+			*v = (float)b * (1.0f / 255.0f);
+		} else {
+			/* g>=b and g>=r */
+			delta = g - MIN(r, b);
+			if (delta == 0) {
+				*h = 0.0f;
+				if (g == 0)
+					*s = *v = 0.0f;
+				else {
+					*s = (float)delta / (float)g;
+					*v = (float)g * (1.0f / 255.0f);
+				}
+			} else {
+				*h = 120.0f + ((b - r) * 60) / (float)delta;
+				*s = (float)delta / (float)g;
+				*v = (float)g * (1.0f / 255.0f);
+			}
+		}
+	}
+}
+
+
+
+/* create_rgb_table:
+ *  Fills an RGB_MAP lookup table with conversion data for the specified
+ *  palette. This is the faster version by Jan Hubicka.
+ *
+ *  Uses alg. similar to floodfill - it adds one seed per every color in
+ *  palette to its best position. Then areas around seed are filled by
+ *  same color because it is best approximation for them, and then areas
+ *  about them etc...
+ *
+ *  It does just about 80000 tests for distances and this is about 100
+ *  times better than normal 256*32000 tests so the calculation time
+ *  is now less than one second at all computers I tested.
+ */
+void create_rgb_table(RGB_MAP *table, AL_CONST PALETTE pal, void (*callback)(int pos)) {
+#define UNUSED 65535
+#define LAST 65532
+
+	/* macro add adds to single linked list */
+#define add(i)    (next[(i)] == UNUSED ? (next[(i)] = LAST, \
+		     (first != LAST ? (next[last] = (i)) : (first = (i))), \
+		     (last = (i))) : 0)
+
+   /* same but w/o checking for first element */
+#define add1(i)   (next[(i)] == UNUSED ? (next[(i)] = LAST, \
+		     next[last] = (i), \
+		     (last = (i))) : 0)
+
+   /* calculates distance between two colors */
+#define dist(a1, a2, a3, b1, b2, b3) \
+		     (col_diff[ ((a2) - (b2)) & 0x7F] + \
+		     (col_diff + 128)[((a1) - (b1)) & 0x7F] + \
+		     (col_diff + 256)[((a3) - (b3)) & 0x7F])
+
+   /* converts r,g,b to position in array and back */
+#define pos(r, g, b) \
+		     (((r) / 2) * 32 * 32 + ((g) / 2) * 32 + ((b) / 2))
+
+#define depos(pal, r, g, b) \
+		     ((b) = ((pal) & 31) * 2, \
+		      (g) = (((pal) >> 5) & 31) * 2, \
+		      (r) = (((pal) >> 10) & 31) * 2)
+
+   /* is current color better than pal1? */
+#define better(r1, g1, b1, pal1) \
+		     (((int)dist((r1), (g1), (b1), \
+				 (pal1).r, (pal1).g, (pal1).b)) > (int)dist2)
+
+   /* checking of position */
+#define dopos(rp, gp, bp, ts) \
+      if ((rp > -1 || r > 0) && (rp < 1 || r < 61) && \
+	  (gp > -1 || g > 0) && (gp < 1 || g < 61) && \
+	  (bp > -1 || b > 0) && (bp < 1 || b < 61)) { \
+	 i = first + rp * 32 * 32 + gp * 32 + bp; \
+         if (!data[i]) { \
+	    data[i] = val; \
+	    add1(i); \
+	 } \
+	 else if ((ts) && (data[i] != val)) { \
+	    dist2 = (rp ? (col_diff+128)[(r+2*rp-pal[val].r) & 0x7F] : r2) + \
+		    (gp ? (col_diff    )[(g+2*gp-pal[val].g) & 0x7F] : g2) + \
+		    (bp ? (col_diff+256)[(b+2*bp-pal[val].b) & 0x7F] : b2); \
+	    if (better((r+2*rp), (g+2*gp), (b+2*bp), pal[data[i]])) { \
+	       data[i] = val; \
+	       add1(i); \
+	    } \
+	 } \
+      }
+
+	int i, curr, r, g, b, val, dist2;
+	unsigned int r2, g2, b2;
+	unsigned short next[32 * 32 * 32];
+	unsigned char *data;
+	int first = LAST;
+	int last = LAST;
+	int count = 0;
+	int cbcount = 0;
+
+#define AVERAGE_COUNT   18000
+
+	if (col_diff[1] == 0)
+		bestfit_init();
+
+	memset(next, 255, sizeof(next));
+	memset(table->data, 0, sizeof(char) * 32 * 32 * 32);
+
+	data = (unsigned char *)table->data;
+
+	/* add starting seeds for floodfill */
+	for (i = 1; i < PAL_SIZE; i++) {
+		curr = pos(pal[i].r, pal[i].g, pal[i].b);
+		if (next[curr] == UNUSED) {
+			data[curr] = i;
+			add(curr);
+		}
+	}
+
+	/* main floodfill: two versions of loop for faster growing in blue axis */
+	while (first != LAST) {
+		depos(first, r, g, b);
+
+		/* calculate distance of current color */
+		val = data[first];
+		r2 = (col_diff + 128)[((pal[val].r) - (r)) & 0x7F];
+		g2 = (col_diff)[((pal[val].g) - (g)) & 0x7F];
+		b2 = (col_diff + 256)[((pal[val].b) - (b)) & 0x7F];
+
+		/* try to grow to all directions */
+		dopos(0, 0, 1, 1);
+		dopos(0, 0, -1, 1);
+		dopos(1, 0, 0, 1);
+		dopos(-1, 0, 0, 1);
+		dopos(0, 1, 0, 1);
+		dopos(0, -1, 0, 1);
+
+		/* faster growing of blue direction */
+		if ((b > 0) && (data[first - 1] == val)) {
+			b -= 2;
+			first--;
+			b2 = (col_diff + 256)[((pal[val].b) - (b)) & 0x7F];
+
+			dopos(-1, 0, 0, 0);
+			dopos(1, 0, 0, 0);
+			dopos(0, -1, 0, 0);
+			dopos(0, 1, 0, 0);
+
+			first++;
+		}
+
+		/* get next from list */
+		i = first;
+		first = next[first];
+		next[i] = UNUSED;
+
+		/* second version of loop */
+		if (first != LAST) {
+			depos(first, r, g, b);
+
+			val = data[first];
+			r2 = (col_diff + 128)[((pal[val].r) - (r)) & 0x7F];
+			g2 = (col_diff)[((pal[val].g) - (g)) & 0x7F];
+			b2 = (col_diff + 256)[((pal[val].b) - (b)) & 0x7F];
+
+			dopos(0, 0, 1, 1);
+			dopos(0, 0, -1, 1);
+			dopos(1, 0, 0, 1);
+			dopos(-1, 0, 0, 1);
+			dopos(0, 1, 0, 1);
+			dopos(0, -1, 0, 1);
+
+			if ((b < 61) && (data[first + 1] == val)) {
+				b += 2;
+				first++;
+				b2 = (col_diff + 256)[((pal[val].b) - (b)) & 0x7f];
+
+				dopos(-1, 0, 0, 0);
+				dopos(1, 0, 0, 0);
+				dopos(0, -1, 0, 0);
+				dopos(0, 1, 0, 0);
+
+				first--;
+			}
+
+			i = first;
+			first = next[first];
+			next[i] = UNUSED;
+		}
+
+		count++;
+		if (count == (cbcount + 1) * AVERAGE_COUNT / 256) {
+			if (cbcount < 256) {
+				if (callback)
+					callback(cbcount);
+				cbcount++;
+			}
+		}
+	}
+
+	/* only the transparent (pink) color can be mapped to index 0 */
+	if ((pal[0].r == 63) && (pal[0].g == 0) && (pal[0].b == 63))
+		table->data[31][0][31] = 0;
+
+	if (callback)
+		while (cbcount < 256)
+			callback(cbcount++);
+}
+
+
+
+/* create_light_table:
+ *  Constructs a lighting color table for the specified palette. At light
+ *  intensity 255 the table will produce the palette colors directly, and
+ *  at level 0 it will produce the specified R, G, B value for all colors
+ *  (this is specified in 0-63 VGA format). If the callback function is
+ *  not NULL, it will be called 256 times during the calculation, allowing
+ *  you to display a progress indicator.
+ */
+void create_light_table(COLOR_MAP *table, AL_CONST PALETTE pal, int r, int g, int b, void (*callback)(int pos)) {
+	int r1, g1, b1, r2, g2, b2, x, y;
+	unsigned int t1, t2;
+
+	assert(table);
+	assert(r >= 0 && r <= 63);
+	assert(g >= 0 && g <= 63);
+	assert(b >= 0 && b <= 63);
+
+	if (rgb_map) {
+		for (x = 0; x < PAL_SIZE - 1; x++) {
+			t1 = x * 0x010101;
+			t2 = 0xFFFFFF - t1;
+
+			r1 = (1 << 24) + r * t2;
+			g1 = (1 << 24) + g * t2;
+			b1 = (1 << 24) + b * t2;
+
+			for (y = 0; y < PAL_SIZE; y++) {
+				r2 = (r1 + pal[y].r * t1) >> 25;
+				g2 = (g1 + pal[y].g * t1) >> 25;
+				b2 = (b1 + pal[y].b * t1) >> 25;
+
+				table->data[x][y] = rgb_map->data[r2][g2][b2];
+			}
+		}
+		if (callback)
+			(*callback)(x);
+	} else {
+		for (x = 0; x < PAL_SIZE - 1; x++) {
+			t1 = x * 0x010101;
+			t2 = 0xFFFFFF - t1;
+
+			r1 = (1 << 23) + r * t2;
+			g1 = (1 << 23) + g * t2;
+			b1 = (1 << 23) + b * t2;
+
+			for (y = 0; y < PAL_SIZE; y++) {
+				r2 = (r1 + pal[y].r * t1) >> 24;
+				g2 = (g1 + pal[y].g * t1) >> 24;
+				b2 = (b1 + pal[y].b * t1) >> 24;
+
+				table->data[x][y] = bestfit_color(pal, r2, g2, b2);
+			}
+		}
+
+		if (callback)
+			(*callback)(x);
+	}
+
+	for (y = 0; y < PAL_SIZE; y++)
+		table->data[255][y] = y;
+}
+
+
+
+/* create_trans_table:
+ *  Constructs a translucency color table for the specified palette. The
+ *  r, g, and b parameters specifiy the solidity of each color component,
+ *  ranging from 0 (totally transparent) to 255 (totally solid). Source
+ *  color #0 is a special case, and is set to leave the destination
+ *  unchanged, so that masked sprites will draw correctly. If the callback
+ *  function is not NULL, it will be called 256 times during the calculation,
+ *  allowing you to display a progress indicator.
+ */
+void create_trans_table(COLOR_MAP *table, AL_CONST PALETTE pal, int r, int g, int b, void (*callback)(int pos)) {
+	int tmp[768], *q;
+	int x, y, i, j, k;
+	unsigned char *p;
+	int tr, tg, tb;
+	int add;
+
+	assert(table);
+	assert(r >= 0 && r <= 255);
+	assert(g >= 0 && g <= 255);
+	assert(b >= 0 && b <= 255);
+
+	/* This is a bit ugly, but accounts for the solidity parameters
+	   being in the range 0-255 rather than 0-256. Given that the
+	   precision of r,g,b components is only 6 bits it shouldn't do any
+	   harm. */
+	if (r > 128)
+		r++;
+	if (g > 128)
+		g++;
+	if (b > 128)
+		b++;
+
+	if (rgb_map)
+		add = 255;
+	else
+		add = 127;
+
+	for (x = 0; x < 256; x++) {
+		tmp[x * 3] = pal[x].r * (256 - r) + add;
+		tmp[x * 3 + 1] = pal[x].g * (256 - g) + add;
+		tmp[x * 3 + 2] = pal[x].b * (256 - b) + add;
+	}
+
+	for (x = 1; x < PAL_SIZE; x++) {
+		i = pal[x].r * r;
+		j = pal[x].g * g;
+		k = pal[x].b * b;
+
+		p = table->data[x];
+		q = tmp;
+
+		if (rgb_map) {
+			for (y = 0; y < PAL_SIZE; y++) {
+				tr = (i + *(q++)) >> 9;
+				tg = (j + *(q++)) >> 9;
+				tb = (k + *(q++)) >> 9;
+				p[y] = rgb_map->data[tr][tg][tb];
+			}
+		} else {
+			for (y = 0; y < PAL_SIZE; y++) {
+				tr = (i + *(q++)) >> 8;
+				tg = (j + *(q++)) >> 8;
+				tb = (k + *(q++)) >> 8;
+				p[y] = bestfit_color(pal, tr, tg, tb);
+			}
+		}
+
+		if (callback)
+			(*callback)(x - 1);
+	}
+
+	for (y = 0; y < PAL_SIZE; y++) {
+		table->data[0][y] = y;
+		table->data[y][y] = y;
+	}
+
+	if (callback)
+		(*callback)(255);
+}
+
+
+
+/* create_color_table:
+ *  Creates a color mapping table, using a user-supplied callback to blend
+ *  each pair of colors. Your blend routine will be passed a pointer to the
+ *  palette and the two colors to be blended (x is the source color, y is
+ *  the destination), and should return the desired output RGB for this
+ *  combination. If the callback function is not NULL, it will be called
+ *  256 times during the calculation, allowing you to display a progress
+ *  indicator.
+ */
+void create_color_table(COLOR_MAP *table, AL_CONST PALETTE pal, void (*blend)(AL_CONST PALETTE pal, int x, int y, RGB *rgb), void (*callback)(int pos)) {
+	int x, y;
+	RGB c;
+
+	for (x = 0; x < PAL_SIZE; x++) {
+		for (y = 0; y < PAL_SIZE; y++) {
+			blend(pal, x, y, &c);
+
+			if (rgb_map)
+				table->data[x][y] = rgb_map->data[c.r >> 1][c.g >> 1][c.b >> 1];
+			else
+				table->data[x][y] = bestfit_color(pal, c.r, c.g, c.b);
+		}
+
+		if (callback)
+			(*callback)(x);
+	}
+}
+
+
+
+/* create_blender_table:
+ *  Fills the specified color mapping table with lookup data for doing a
+ *  paletted equivalent of whatever truecolor blender mode is currently
+ *  selected.
+ */
+void create_blender_table(COLOR_MAP *table, AL_CONST PALETTE pal, void (*callback)(int pos)) {
+	int x, y, c;
+	int r, g, b;
+	int r1, g1, b1;
+	int r2, g2, b2;
+
+	assert(_blender_func24);
+
+	for (x = 0; x < PAL_SIZE; x++) {
+		for (y = 0; y < PAL_SIZE; y++) {
+			r1 = (pal[x].r << 2) | ((pal[x].r & 0x30) >> 4);
+			g1 = (pal[x].g << 2) | ((pal[x].g & 0x30) >> 4);
+			b1 = (pal[x].b << 2) | ((pal[x].b & 0x30) >> 4);
+
+			r2 = (pal[y].r << 2) | ((pal[y].r & 0x30) >> 4);
+			g2 = (pal[y].g << 2) | ((pal[y].g & 0x30) >> 4);
+			b2 = (pal[y].b << 2) | ((pal[y].b & 0x30) >> 4);
+
+			c = _blender_func24(makecol24(r1, g1, b1), makecol24(r2, g2, b2), _blender_alpha);
+
+			r = getr24(c);
+			g = getg24(c);
+			b = getb24(c);
+
+			if (rgb_map)
+				table->data[x][y] = rgb_map->data[r >> 3][g >> 3][b >> 3];
+			else
+				table->data[x][y] = bestfit_color(pal, r >> 2, g >> 2, b >> 2);
+		}
+
+		if (callback)
+			(*callback)(x);
+	}
 }
 
 } // namespace AGS3
diff --git a/engines/ags/lib/allegro/color.h b/engines/ags/lib/allegro/color.h
index c5b92444f4..2ab216255d 100644
--- a/engines/ags/lib/allegro/color.h
+++ b/engines/ags/lib/allegro/color.h
@@ -24,6 +24,7 @@
 #define AGS_LIB_ALLEGRO_COLOR_H
 
 #include "common/scummsys.h"
+#include "ags/lib/allegro/base.h"
 #include "ags/lib/allegro/alconfig.h"
 
 namespace AGS3 {
diff --git a/engines/ags/lib/allegro/graphics.cpp b/engines/ags/lib/allegro/graphics.cpp
new file mode 100644
index 0000000000..cc435162ea
--- /dev/null
+++ b/engines/ags/lib/allegro/graphics.cpp
@@ -0,0 +1,37 @@
+/* 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 "ags/lib/allegro/gfx.h"
+#include "ags/lib/allegro/color.h"
+
+namespace AGS3 {
+
+int _color_depth;
+
+BLENDER_FUNC _blender_func15 = NULL;   /* truecolor pixel blender routines */
+BLENDER_FUNC _blender_func16 = NULL;
+BLENDER_FUNC _blender_func24 = NULL;
+BLENDER_FUNC _blender_func32 = NULL;
+
+int _blender_alpha;
+
+} // namespace AGS3
diff --git a/engines/ags/lib/allegro/system.cpp b/engines/ags/lib/allegro/system.cpp
index b372b7ebdd..a27cb655b3 100644
--- a/engines/ags/lib/allegro/system.cpp
+++ b/engines/ags/lib/allegro/system.cpp
@@ -21,12 +21,11 @@
  */
 
 #include "ags/lib/allegro/system.h"
+#include "ags/lib/allegro/aintern.h"
 #include "common/system.h"
 
 namespace AGS3 {
 
-int color_depth;
-
 SYSTEM_DRIVER system_none;
 SYSTEM_DRIVER *system_driver;
 
@@ -57,11 +56,11 @@ void destroy_gfx_mode_list(GFX_MODE_LIST *list) {
 }
 
 void set_color_depth(int depth) {
-	color_depth = depth;
+	_color_depth = depth;
 }
 
 int get_color_depth() {
-	return color_depth;
+	return _color_depth;
 }
 
 int get_desktop_resolution(int *width, int *height) {
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 0e97a279be..27941c9d82 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -15,6 +15,7 @@ MODULE_OBJS = \
 	lib/allegro/file.o \
 	lib/allegro/fixed.o \
 	lib/allegro/gfx.o \
+	lib/allegro/graphics.o \
 	lib/allegro/keyboard.o \
 	lib/allegro/mouse.o \
 	lib/allegro/system.o \


Commit: cf26917b29ff2fb426735d0dc891fcc642e84277
    https://github.com/scummvm/scummvm/commit/cf26917b29ff2fb426735d0dc891fcc642e84277
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Further adding missing code

Changed paths:
    engines/ags/engine/plugin/global_plugin.cpp
    engines/ags/module.mk


diff --git a/engines/ags/engine/plugin/global_plugin.cpp b/engines/ags/engine/plugin/global_plugin.cpp
index 8ec36dd51d..cc84eca682 100644
--- a/engines/ags/engine/plugin/global_plugin.cpp
+++ b/engines/ags/engine/plugin/global_plugin.cpp
@@ -27,9 +27,10 @@
 //=============================================================================
 
 //include <string.h>
-#include "ags/shared/ac/global_plugin.h"
-#include "ags/shared/ac/mouse.h"
+#include "ags/engine/ac/global_plugin.h"
+#include "ags/engine/ac/mouse.h"
 #include "ags/shared/util/string_compat.h"
+#include "ags/engine/script/script_runtime.h"
 
 namespace AGS3 {
 
@@ -45,8 +46,6 @@ void PluginSimulateMouseClick(int pluginButtonID) {
 //
 //=============================================================================
 
-#include "ags/shared/script/script_runtime.h"
-
 RuntimeScriptValue Sc_PluginStub_Void(const RuntimeScriptValue *params, int32_t param_count) {
 	return RuntimeScriptValue((int32_t)0);
 }
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 27941c9d82..8c278fbe87 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -287,6 +287,7 @@ MODULE_OBJS = \
 	engine/platform/base/agsplatformdriver.o \
 	engine/platform/linux/acpllnx.o \
 	engine/plugin/agsplugin.o \
+	engine/plugin/global_plugin.o \
 	engine/plugin/library.o \
 	engine/plugin/pluginobjectreader.o \
 	engine/script/cc_instance.o \


Commit: 536bb13032e749f2aa1f445aa342c7ed886f8e42
    https://github.com/scummvm/scummvm/commit/536bb13032e749f2aa1f445aa342c7ed886f8e42
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Add further missing lib/ code

Changed paths:
  A engines/ags/lib/dumb-0.9.2/dumb.cpp
  A engines/ags/lib/dumb-0.9.2/dumb.h
  A engines/ags/lib/dumb-0.9.2/helpers/clickrem.cpp
  A engines/ags/lib/dumb-0.9.2/helpers/memfile.c
  A engines/ags/lib/dumb-0.9.2/helpers/resample.c
  A engines/ags/lib/dumb-0.9.2/helpers/sampbuf.c
  A engines/ags/lib/dumb-0.9.2/helpers/silence.c
  A engines/ags/lib/dumb-0.9.2/helpers/stdfile.c
  A engines/ags/lib/dumb-0.9.2/it/it.h
  A engines/ags/lib/dumb-0.9.2/it/itmisc.cpp
  A engines/ags/lib/dumb-0.9.2/it/itrender.cpp
  A engines/ags/lib/dumb-0.9.2/it/itunload.cpp
  R engines/ags/lib/dumb-0.9.2/dumbfile.h
    engines/ags/engine/gfx/gfxfilter_aaogl.cpp
    engines/ags/engine/media/audio/clip_mydumbmod.h
    engines/ags/engine/media/audio/sound.cpp
    engines/ags/lib/allegro.cpp
    engines/ags/lib/allegro/colblend.cpp
    engines/ags/lib/allegro/color.cpp
    engines/ags/lib/allegro/color.h
    engines/ags/lib/allegro/gfx.cpp
    engines/ags/lib/allegro/graphics.cpp
    engines/ags/lib/allegro/math.cpp
    engines/ags/lib/audio/aldumb.h
    engines/ags/lib/audio/midi.cpp
    engines/ags/lib/audio/mp3.cpp
    engines/ags/lib/dumb-0.9.2/dumbfile.cpp
    engines/ags/lib/std/queue.h
    engines/ags/module.mk


diff --git a/engines/ags/engine/gfx/gfxfilter_aaogl.cpp b/engines/ags/engine/gfx/gfxfilter_aaogl.cpp
index ac26f29557..f809d93310 100644
--- a/engines/ags/engine/gfx/gfxfilter_aaogl.cpp
+++ b/engines/ags/engine/gfx/gfxfilter_aaogl.cpp
@@ -22,10 +22,10 @@
 
 #include "ags/shared/core/platform.h"
 
-#if 1
+#if AGS_PLATFORM_OS_WINDOWS || AGS_PLATFORM_OS_ANDROID || AGS_PLATFORM_OS_IOS || AGS_PLATFORM_OS_LINUX
 
-#include "ags/shared/gfx/gfxfilter_aaogl.h"
-#include "ags/shared/ogl_headers.h"
+#include "ags/engine/gfx/gfxfilter_aaogl.h"
+#include "ags/engine/gfx/ogl_headers.h"
 
 namespace AGS3 {
 namespace AGS {
diff --git a/engines/ags/engine/media/audio/clip_mydumbmod.h b/engines/ags/engine/media/audio/clip_mydumbmod.h
index 75c0a0433b..370de3f344 100644
--- a/engines/ags/engine/media/audio/clip_mydumbmod.h
+++ b/engines/ags/engine/media/audio/clip_mydumbmod.h
@@ -30,7 +30,7 @@ namespace AGS3 {
 
 #define VOLUME_TO_DUMB_VOL(vol) ((float)vol) / 256.0
 
-void al_duh_set_loop(AL_DUH_PLAYER *dp, int loop);
+extern void al_duh_set_loop(AL_DUH_PLAYER *dp, int loop);
 
 // MOD/XM (DUMB)
 struct MYMOD : public SOUNDCLIP {
diff --git a/engines/ags/engine/media/audio/sound.cpp b/engines/ags/engine/media/audio/sound.cpp
index 5c3a72424f..f92ab6683d 100644
--- a/engines/ags/engine/media/audio/sound.cpp
+++ b/engines/ags/engine/media/audio/sound.cpp
@@ -61,11 +61,8 @@ namespace AGS3 {
 #error Either JGMOD_MOD_PLAYER or DUMB_MOD_PLAYER should be defined.
 #endif
 
-extern "C"
-{
-	// Load MIDI from PACKFILE stream
-	MIDI *load_midi_pf(PACKFILE *pf);
-}
+// Load MIDI from PACKFILE stream
+extern MIDI *load_midi_pf(PACKFILE *pf);
 
 
 int use_extra_sound_offset = 0;
diff --git a/engines/ags/lib/allegro.cpp b/engines/ags/lib/allegro.cpp
index 90365ef825..bc1f5d24f2 100644
--- a/engines/ags/lib/allegro.cpp
+++ b/engines/ags/lib/allegro.cpp
@@ -24,6 +24,89 @@
 
 namespace AGS3 {
 
+/* default palette structures */
+PALETTE black_palette;
+PALETTE _current_palette;
+
+int _current_palette_changed = 0xFFFFFFFF;
+
+
+PALETTE desktop_palette = {
+   { 63, 63, 63, 0 },   { 63, 0,  0,  0 },   { 0,  63, 0,  0 },   { 63, 63, 0,  0 },
+   { 0,  0,  63, 0 },   { 63, 0,  63, 0 },   { 0,  63, 63, 0 },   { 16, 16, 16, 0 },
+   { 31, 31, 31, 0 },   { 63, 31, 31, 0 },   { 31, 63, 31, 0 },   { 63, 63, 31, 0 },
+   { 31, 31, 63, 0 },   { 63, 31, 63, 0 },   { 31, 63, 63, 0 },   { 0,  0,  0,  0 }
+};
+
+
+PALETTE default_palette = {
+   { 0,  0,  0,  0 },   { 0,  0,  42, 0 },   { 0,  42, 0,  0 },   { 0,  42, 42, 0 },
+   { 42, 0,  0,  0 },   { 42, 0,  42, 0 },   { 42, 21, 0,  0 },   { 42, 42, 42, 0 },
+   { 21, 21, 21, 0 },   { 21, 21, 63, 0 },   { 21, 63, 21, 0 },   { 21, 63, 63, 0 },
+   { 63, 21, 21, 0 },   { 63, 21, 63, 0 },   { 63, 63, 21, 0 },   { 63, 63, 63, 0 },
+   { 0,  0,  0,  0 },   { 5,  5,  5,  0 },   { 8,  8,  8,  0 },   { 11, 11, 11, 0 },
+   { 14, 14, 14, 0 },   { 17, 17, 17, 0 },   { 20, 20, 20, 0 },   { 24, 24, 24, 0 },
+   { 28, 28, 28, 0 },   { 32, 32, 32, 0 },   { 36, 36, 36, 0 },   { 40, 40, 40, 0 },
+   { 45, 45, 45, 0 },   { 50, 50, 50, 0 },   { 56, 56, 56, 0 },   { 63, 63, 63, 0 },
+   { 0,  0,  63, 0 },   { 16, 0,  63, 0 },   { 31, 0,  63, 0 },   { 47, 0,  63, 0 },
+   { 63, 0,  63, 0 },   { 63, 0,  47, 0 },   { 63, 0,  31, 0 },   { 63, 0,  16, 0 },
+   { 63, 0,  0,  0 },   { 63, 16, 0,  0 },   { 63, 31, 0,  0 },   { 63, 47, 0,  0 },
+   { 63, 63, 0,  0 },   { 47, 63, 0,  0 },   { 31, 63, 0,  0 },   { 16, 63, 0,  0 },
+   { 0,  63, 0,  0 },   { 0,  63, 16, 0 },   { 0,  63, 31, 0 },   { 0,  63, 47, 0 },
+   { 0,  63, 63, 0 },   { 0,  47, 63, 0 },   { 0,  31, 63, 0 },   { 0,  16, 63, 0 },
+   { 31, 31, 63, 0 },   { 39, 31, 63, 0 },   { 47, 31, 63, 0 },   { 55, 31, 63, 0 },
+   { 63, 31, 63, 0 },   { 63, 31, 55, 0 },   { 63, 31, 47, 0 },   { 63, 31, 39, 0 },
+   { 63, 31, 31, 0 },   { 63, 39, 31, 0 },   { 63, 47, 31, 0 },   { 63, 55, 31, 0 },
+   { 63, 63, 31, 0 },   { 55, 63, 31, 0 },   { 47, 63, 31, 0 },   { 39, 63, 31, 0 },
+   { 31, 63, 31, 0 },   { 31, 63, 39, 0 },   { 31, 63, 47, 0 },   { 31, 63, 55, 0 },
+   { 31, 63, 63, 0 },   { 31, 55, 63, 0 },   { 31, 47, 63, 0 },   { 31, 39, 63, 0 },
+   { 45, 45, 63, 0 },   { 49, 45, 63, 0 },   { 54, 45, 63, 0 },   { 58, 45, 63, 0 },
+   { 63, 45, 63, 0 },   { 63, 45, 58, 0 },   { 63, 45, 54, 0 },   { 63, 45, 49, 0 },
+   { 63, 45, 45, 0 },   { 63, 49, 45, 0 },   { 63, 54, 45, 0 },   { 63, 58, 45, 0 },
+   { 63, 63, 45, 0 },   { 58, 63, 45, 0 },   { 54, 63, 45, 0 },   { 49, 63, 45, 0 },
+   { 45, 63, 45, 0 },   { 45, 63, 49, 0 },   { 45, 63, 54, 0 },   { 45, 63, 58, 0 },
+   { 45, 63, 63, 0 },   { 45, 58, 63, 0 },   { 45, 54, 63, 0 },   { 45, 49, 63, 0 },
+   { 0,  0,  28, 0 },   { 7,  0,  28, 0 },   { 14, 0,  28, 0 },   { 21, 0,  28, 0 },
+   { 28, 0,  28, 0 },   { 28, 0,  21, 0 },   { 28, 0,  14, 0 },   { 28, 0,  7,  0 },
+   { 28, 0,  0,  0 },   { 28, 7,  0,  0 },   { 28, 14, 0,  0 },   { 28, 21, 0,  0 },
+   { 28, 28, 0,  0 },   { 21, 28, 0,  0 },   { 14, 28, 0,  0 },   { 7,  28, 0,  0 },
+   { 0,  28, 0,  0 },   { 0,  28, 7,  0 },   { 0,  28, 14, 0 },   { 0,  28, 21, 0 },
+   { 0,  28, 28, 0 },   { 0,  21, 28, 0 },   { 0,  14, 28, 0 },   { 0,  7,  28, 0 },
+   { 14, 14, 28, 0 },   { 17, 14, 28, 0 },   { 21, 14, 28, 0 },   { 24, 14, 28, 0 },
+   { 28, 14, 28, 0 },   { 28, 14, 24, 0 },   { 28, 14, 21, 0 },   { 28, 14, 17, 0 },
+   { 28, 14, 14, 0 },   { 28, 17, 14, 0 },   { 28, 21, 14, 0 },   { 28, 24, 14, 0 },
+   { 28, 28, 14, 0 },   { 24, 28, 14, 0 },   { 21, 28, 14, 0 },   { 17, 28, 14, 0 },
+   { 14, 28, 14, 0 },   { 14, 28, 17, 0 },   { 14, 28, 21, 0 },   { 14, 28, 24, 0 },
+   { 14, 28, 28, 0 },   { 14, 24, 28, 0 },   { 14, 21, 28, 0 },   { 14, 17, 28, 0 },
+   { 20, 20, 28, 0 },   { 22, 20, 28, 0 },   { 24, 20, 28, 0 },   { 26, 20, 28, 0 },
+   { 28, 20, 28, 0 },   { 28, 20, 26, 0 },   { 28, 20, 24, 0 },   { 28, 20, 22, 0 },
+   { 28, 20, 20, 0 },   { 28, 22, 20, 0 },   { 28, 24, 20, 0 },   { 28, 26, 20, 0 },
+   { 28, 28, 20, 0 },   { 26, 28, 20, 0 },   { 24, 28, 20, 0 },   { 22, 28, 20, 0 },
+   { 20, 28, 20, 0 },   { 20, 28, 22, 0 },   { 20, 28, 24, 0 },   { 20, 28, 26, 0 },
+   { 20, 28, 28, 0 },   { 20, 26, 28, 0 },   { 20, 24, 28, 0 },   { 20, 22, 28, 0 },
+   { 0,  0,  16, 0 },   { 4,  0,  16, 0 },   { 8,  0,  16, 0 },   { 12, 0,  16, 0 },
+   { 16, 0,  16, 0 },   { 16, 0,  12, 0 },   { 16, 0,  8,  0 },   { 16, 0,  4,  0 },
+   { 16, 0,  0,  0 },   { 16, 4,  0,  0 },   { 16, 8,  0,  0 },   { 16, 12, 0,  0 },
+   { 16, 16, 0,  0 },   { 12, 16, 0,  0 },   { 8,  16, 0,  0 },   { 4,  16, 0,  0 },
+   { 0,  16, 0,  0 },   { 0,  16, 4,  0 },   { 0,  16, 8,  0 },   { 0,  16, 12, 0 },
+   { 0,  16, 16, 0 },   { 0,  12, 16, 0 },   { 0,  8,  16, 0 },   { 0,  4,  16, 0 },
+   { 8,  8,  16, 0 },   { 10, 8,  16, 0 },   { 12, 8,  16, 0 },   { 14, 8,  16, 0 },
+   { 16, 8,  16, 0 },   { 16, 8,  14, 0 },   { 16, 8,  12, 0 },   { 16, 8,  10, 0 },
+   { 16, 8,  8,  0 },   { 16, 10, 8,  0 },   { 16, 12, 8,  0 },   { 16, 14, 8,  0 },
+   { 16, 16, 8,  0 },   { 14, 16, 8,  0 },   { 12, 16, 8,  0 },   { 10, 16, 8,  0 },
+   { 8,  16, 8,  0 },   { 8,  16, 10, 0 },   { 8,  16, 12, 0 },   { 8,  16, 14, 0 },
+   { 8,  16, 16, 0 },   { 8,  14, 16, 0 },   { 8,  12, 16, 0 },   { 8,  10, 16, 0 },
+   { 11, 11, 16, 0 },   { 12, 11, 16, 0 },   { 13, 11, 16, 0 },   { 15, 11, 16, 0 },
+   { 16, 11, 16, 0 },   { 16, 11, 15, 0 },   { 16, 11, 13, 0 },   { 16, 11, 12, 0 },
+   { 16, 11, 11, 0 },   { 16, 12, 11, 0 },   { 16, 13, 11, 0 },   { 16, 15, 11, 0 },
+   { 16, 16, 11, 0 },   { 15, 16, 11, 0 },   { 13, 16, 11, 0 },   { 12, 16, 11, 0 },
+   { 11, 16, 11, 0 },   { 11, 16, 12, 0 },   { 11, 16, 13, 0 },   { 11, 16, 15, 0 },
+   { 11, 16, 16, 0 },   { 11, 15, 16, 0 },   { 11, 13, 16, 0 },   { 11, 12, 16, 0 },
+   { 0,  0,  0,  0 },   { 0,  0,  0,  0 },   { 0,  0,  0,  0 },   { 0,  0,  0,  0 },
+   { 0,  0,  0,  0 },   { 0,  0,  0,  0 },   { 0,  0,  0,  0 },   { 63, 63, 63, 0 }
+};
+
+
 int install_allegro() {
 	errnum = 0;
 	return 0;
diff --git a/engines/ags/lib/allegro/colblend.cpp b/engines/ags/lib/allegro/colblend.cpp
index 4b623a190d..20581c2f21 100644
--- a/engines/ags/lib/allegro/colblend.cpp
+++ b/engines/ags/lib/allegro/colblend.cpp
@@ -21,6 +21,7 @@
  */
 
 #include "ags/lib/allegro/colblend.h"
+#include "ags/lib/allegro/color.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/lib/allegro/color.cpp b/engines/ags/lib/allegro/color.cpp
index 41eed40000..14243c7656 100644
--- a/engines/ags/lib/allegro/color.cpp
+++ b/engines/ags/lib/allegro/color.cpp
@@ -43,10 +43,9 @@ int _rgb_g_shift_32 = 0;
 int _rgb_b_shift_32 = 0;
 int _rgb_a_shift_32 = 0;
 
-AL_ARRAY(int, _rgb_scale_5);
-AL_ARRAY(int, _rgb_scale_6);
+RGB_MAP *rgb_map;
+COLOR_MAP *color_map;
 
-PALETTE _current_palette;
 
 void set_color(int idx, const RGB *p) {
 	_current_palette[idx] = *p;
diff --git a/engines/ags/lib/allegro/color.h b/engines/ags/lib/allegro/color.h
index 2ab216255d..8dc105c491 100644
--- a/engines/ags/lib/allegro/color.h
+++ b/engines/ags/lib/allegro/color.h
@@ -42,6 +42,7 @@ class BITMAP;
 
 struct color {
 	byte r, g, b;
+	byte filler;
 } PACKED_STRUCT;
 
 typedef color RGB;
diff --git a/engines/ags/lib/allegro/gfx.cpp b/engines/ags/lib/allegro/gfx.cpp
index a14bf1dda8..9111935848 100644
--- a/engines/ags/lib/allegro/gfx.cpp
+++ b/engines/ags/lib/allegro/gfx.cpp
@@ -208,7 +208,7 @@ void draw_sprite(BITMAP *bmp, const BITMAP *sprite, int x, int y) {
 	bmpS.blitFrom(spriteS, Common::Point(x, y));
 }
 
-void stretch_sprite(BITMAP *bmp, BITMAP *sprite, int x, int y, int w, int h) {
+void stretch_sprite(BITMAP *bmp, const BITMAP *sprite, int x, int y, int w, int h) {
 	Graphics::ManagedSurface &bmpS = **bmp;
 	Graphics::ManagedSurface &spriteS = **sprite;
 
@@ -403,4 +403,9 @@ void circlefill(BITMAP *bmp, int x, int y, int radius, int color) {
 	error("TODO: circlefill");
 }
 
+void clear_bitmap(BITMAP *bmp) {
+	error("TODO: clear_bitmap");
+}
+
+
 } // namespace AGS3
diff --git a/engines/ags/lib/allegro/graphics.cpp b/engines/ags/lib/allegro/graphics.cpp
index cc435162ea..f7b717f69c 100644
--- a/engines/ags/lib/allegro/graphics.cpp
+++ b/engines/ags/lib/allegro/graphics.cpp
@@ -34,4 +34,25 @@ BLENDER_FUNC _blender_func32 = NULL;
 
 int _blender_alpha;
 
+/* lookup table for scaling 5 bit colors up to 8 bits */
+int _rgb_scale_5[32] = {
+   0,   8,   16,  24,  33,  41,  49,  57,
+   66,  74,  82,  90,  99,  107, 115, 123,
+   132, 140, 148, 156, 165, 173, 181, 189,
+   198, 206, 214, 222, 231, 239, 247, 255
+};
+
+
+/* lookup table for scaling 6 bit colors up to 8 bits */
+int _rgb_scale_6[64] = {
+   0,   4,   8,   12,  16,  20,  24,  28,
+   32,  36,  40,  44,  48,  52,  56,  60,
+   65,  69,  73,  77,  81,  85,  89,  93,
+   97,  101, 105, 109, 113, 117, 121, 125,
+   130, 134, 138, 142, 146, 150, 154, 158,
+   162, 166, 170, 174, 178, 182, 186, 190,
+   195, 199, 203, 207, 211, 215, 219, 223,
+   227, 231, 235, 239, 243, 247, 251, 255
+};
+
 } // namespace AGS3
diff --git a/engines/ags/lib/allegro/math.cpp b/engines/ags/lib/allegro/math.cpp
index 88c1a5eafa..19413b2cf6 100644
--- a/engines/ags/lib/allegro/math.cpp
+++ b/engines/ags/lib/allegro/math.cpp
@@ -23,13 +23,12 @@
 #ifndef AGS_LIB_ALLEGRO_MATH_H
 #define AGS_LIB_ALLEGRO_MATH_H
 
+#include "ags/lib/allegro/error.h"
 #include "ags/lib/allegro/fixed.h"
 
 namespace AGS3 {
 
-
-fixed _cos_tbl[512] =
-{
+fixed _cos_tbl[512] = {
 	/* precalculated fixed point (16.16) cosines for a full circle (0-255) */
 
 	65536L,  65531L,  65516L,  65492L,  65457L,  65413L,  65358L,  65294L,
@@ -98,10 +97,7 @@ fixed _cos_tbl[512] =
 	65220L,  65294L,  65358L,  65413L,  65457L,  65492L,  65516L,  65531L
 };
 
-
-
-fixed _tan_tbl[256] =
-{
+fixed _tan_tbl[256] = {
 	/* precalculated fixed point (16.16) tangents for a half circle (0-127) */
 
 	0L,      804L,    1609L,   2414L,   3220L,   4026L,   4834L,   5644L,
@@ -138,10 +134,7 @@ fixed _tan_tbl[256] =
 	-6455L,  -5644L,  -4834L,  -4026L,  -3220L,  -2414L,  -1609L,  -804L
 };
 
-
-
-fixed _acos_tbl[513] =
-{
+fixed _acos_tbl[513] = {
 	/* precalculated fixed point (16.16) inverse cosines (-1 to 1) */
 
 	0x800000L,  0x7C65C7L,  0x7AE75AL,  0x79C19EL,  0x78C9BEL,  0x77EF25L,  0x772953L,  0x76733AL,
@@ -212,7 +205,6 @@ fixed _acos_tbl[513] =
 };
 
 
-
 /* fixatan:
  *  Fixed point inverse tangent. Does a binary search on the tan table.
  */
diff --git a/engines/ags/lib/audio/aldumb.h b/engines/ags/lib/audio/aldumb.h
index 61ede22bd8..32270f78e0 100644
--- a/engines/ags/lib/audio/aldumb.h
+++ b/engines/ags/lib/audio/aldumb.h
@@ -43,7 +43,7 @@
 #define AGS_LIB_ALDUMB_H
 
 #include "ags/lib/allegro.h"
-#include "ags/lib/dumb-0.9.2/dumbfile.h"
+#include "ags/lib/dumb-0.9.2/dumb.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/lib/audio/midi.cpp b/engines/ags/lib/audio/midi.cpp
index 96ed12eb10..5be76b1468 100644
--- a/engines/ags/lib/audio/midi.cpp
+++ b/engines/ags/lib/audio/midi.cpp
@@ -21,10 +21,14 @@
  */
 
 #include "ags/lib/audio/midi.h"
+#include "ags/lib/allegro/file.h"
 #include "common/textconsole.h"
 
 namespace AGS3 {
 
+BEGIN_MIDI_DRIVER_LIST
+END_MIDI_DRIVER_LIST
+
 MIDI_DRIVER *midi_driver;
 
 MIDI_DRIVER *midi_input_driver;
@@ -80,4 +84,8 @@ int load_midi_patches() {
 	return 0;
 }
 
+MIDI *load_midi_pf(PACKFILE *fp) {
+	error("TODO: load_midi_pf");
+}
+
 } // namespace AGS3
diff --git a/engines/ags/lib/audio/mp3.cpp b/engines/ags/lib/audio/mp3.cpp
index b948acdbf7..d6fd91ecfe 100644
--- a/engines/ags/lib/audio/mp3.cpp
+++ b/engines/ags/lib/audio/mp3.cpp
@@ -114,4 +114,9 @@ AUDIOSTREAM *almp3_get_audiostream_mp3stream(ALMP3_MP3STREAM *mp3) {
 	return nullptr;
 }
 
+int almp3_get_length_msecs_mp3stream(ALMP3_MP3STREAM *mp3, int total_size) {
+	warning("TODO: almp3_get_length_msecs_mp3stream");
+	return 0;
+}
+
 } // namespace AGS3
diff --git a/engines/ags/lib/dumb-0.9.2/dumb.cpp b/engines/ags/lib/dumb-0.9.2/dumb.cpp
new file mode 100644
index 0000000000..215fb76828
--- /dev/null
+++ b/engines/ags/lib/dumb-0.9.2/dumb.cpp
@@ -0,0 +1,182 @@
+/* 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 "ags/lib/dumb-0.9.2/dumb.h"
+#include "common/textconsole.h"
+
+namespace AGS3 {
+
+void dumb_exit() {
+	// No implementation
+}
+
+DUH *dumb_load_it(const char *filename) {
+	warning("TODO: dumb_load_it");
+	return nullptr;
+}
+
+DUH *dumb_load_xm(const char *filename) {
+	warning("TODO: dumb_load_xm");
+	return nullptr;
+}
+
+DUH *dumb_load_s3m(const char *filename) {
+	warning("TODO: dumb_load_s3m");
+	return nullptr;
+}
+
+DUH *dumb_load_mod(const char *filename) {
+	warning("TODO: dumb_load_mod");
+	return nullptr;
+}
+
+DUH *dumb_read_it(DUMBFILE *f) {
+	warning("TODO: dumb_read_it");
+	return nullptr;
+}
+DUH *dumb_read_xm(DUMBFILE *f) {
+	warning("TODO: dumb_read_xm");
+	return nullptr;
+}
+
+DUH *dumb_read_s3m(DUMBFILE *f) {
+	warning("TODO: dumb_read_s3m");
+	return nullptr;
+}
+
+DUH *dumb_read_mod(DUMBFILE *f) {
+	warning("TODO: dumb_read_mod");
+	return nullptr;
+}
+
+int dumb_it_sd_get_n_orders(DUMB_IT_SIGDATA *sd) {
+	warning("TODO: dumb_it_sd_get_n_orders");
+	return 0;
+}
+
+int dumb_it_sd_get_initial_global_volume(DUMB_IT_SIGDATA *sd) {
+	warning("TODO: dumb_it_sd_get_initial_global_volume");
+	return 0;
+}
+
+void dumb_it_sd_set_initial_global_volume(DUMB_IT_SIGDATA *sd, int gv) {
+	warning("TODO: dumb_it_sd_set_initial_global_volume");
+}
+
+int dumb_it_sd_get_mixing_volume(DUMB_IT_SIGDATA *sd) {
+	warning("TODO: dumb_it_sd_get_mixing_volume");
+	return 0;
+}
+
+void dumb_it_sd_set_mixing_volume(DUMB_IT_SIGDATA *sd, int mv) {
+	warning("TODO: dumb_it_sd_set_mixing_volume");
+}
+
+int dumb_it_sd_get_initial_speed(DUMB_IT_SIGDATA *sd) {
+	warning("TODO: dumb_it_sd_get_initial_speed");
+	return 0;
+}
+
+void dumb_it_sd_set_initial_speed(DUMB_IT_SIGDATA *sd, int speed) {
+	warning("TODO: dumb_it_sd_set_initial_speed");
+}
+
+int dumb_it_sd_get_initial_tempo(DUMB_IT_SIGDATA *sd) {
+	warning("TODO: dumb_it_sd_get_initial_tempo");
+	return 0;
+}
+
+void dumb_it_sd_set_initial_tempo(DUMB_IT_SIGDATA *sd, int tempo) {
+	warning("TODO: dumb_it_sd_set_initial_tempo");
+}
+
+int dumb_it_sd_get_initial_channel_volume(DUMB_IT_SIGDATA *sd, int channel) {
+	warning("TODO: dumb_it_sd_get_initial_channel_volume");
+	return 0;
+}
+
+void dumb_it_sd_set_initial_channel_volume(DUMB_IT_SIGDATA *sd, int channel, int volume) {
+	warning("TODO: dumb_it_sd_set_initial_channel_volume");
+}
+
+int dumb_it_sr_get_current_order(DUMB_IT_SIGRENDERER *sr) {
+	warning("TODO: dumb_it_sr_get_current_order");
+	return 0;
+}
+
+int dumb_it_sr_get_current_row(DUMB_IT_SIGRENDERER *sr) {
+	warning("TODO: dumb_it_sr_get_current_row");
+	return 0;
+}
+
+int dumb_it_sr_get_global_volume(DUMB_IT_SIGRENDERER *sr) {
+	warning("TODO: dumb_it_sr_get_global_volume");
+	return 0;
+}
+
+void dumb_it_sr_set_global_volume(DUMB_IT_SIGRENDERER *sr, int gv) {
+	warning("TODO: dumb_it_sr_set_global_volume");
+}
+
+int dumb_it_sr_get_tempo(DUMB_IT_SIGRENDERER *sr) {
+	warning("TODO: dumb_it_sr_get_tempo");
+	return 0;
+}
+
+void dumb_it_sr_set_tempo(DUMB_IT_SIGRENDERER *sr, int tempo) {
+	warning("TODO: dumb_it_sr_set_tempo");
+}
+
+int dumb_it_sr_get_speed(DUMB_IT_SIGRENDERER *sr) {
+	warning("TODO: dumb_it_sr_get_speed");
+	return 0;
+}
+
+void dumb_it_sr_set_speed(DUMB_IT_SIGRENDERER *sr, int speed) {
+	warning("TODO: dumb_it_sr_set_speed");
+}
+
+void unload_duh(DUH *duh) {
+	warning("TODO: unload_duh");
+}
+
+DUH *load_duh(const char *filename) {
+	warning("TODO: load_duh");
+	return nullptr;
+}
+
+DUH *read_duh(DUMBFILE *f) {
+	warning("TODO: load_duh");
+	return nullptr;
+}
+
+long duh_get_length(DUH *duh) {
+	warning("TODO: duh_get_length");
+	return 0;
+}
+
+void duh_end_sigrenderer(DUH_SIGRENDERER *sigrenderer) {
+	warning("TODO: duh_end_sigrenderer");
+}
+
+
+} // namespace AGS3
diff --git a/engines/ags/lib/dumb-0.9.2/dumbfile.h b/engines/ags/lib/dumb-0.9.2/dumb.h
similarity index 100%
rename from engines/ags/lib/dumb-0.9.2/dumbfile.h
rename to engines/ags/lib/dumb-0.9.2/dumb.h
diff --git a/engines/ags/lib/dumb-0.9.2/dumbfile.cpp b/engines/ags/lib/dumb-0.9.2/dumbfile.cpp
index 60d82b5801..496d26935d 100644
--- a/engines/ags/lib/dumb-0.9.2/dumbfile.cpp
+++ b/engines/ags/lib/dumb-0.9.2/dumbfile.cpp
@@ -41,7 +41,7 @@
 
 //include <stdlib.h>
 
-#include "ags/lib/dumb-0.9.2/dumbfile.h"
+#include "ags/lib/dumb-0.9.2/dumb.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/lib/dumb-0.9.2/helpers/clickrem.cpp b/engines/ags/lib/dumb-0.9.2/helpers/clickrem.cpp
new file mode 100644
index 0000000000..11bb8814f8
--- /dev/null
+++ b/engines/ags/lib/dumb-0.9.2/helpers/clickrem.cpp
@@ -0,0 +1,278 @@
+/* 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.
+ *
+ */
+
+/*  _______         ____    __         ___    ___
+ * \    _  \       \    /  \  /       \   \  /   /       '   '  '
+ *  |  | \  \       |  |    ||         |   \/   |         .      .
+ *  |  |  |  |      |  |    ||         ||\  /|  |
+ *  |  |  |  |      |  |    ||         || \/ |  |         '  '  '
+ *  |  |  |  |      |  |    ||         ||    |  |         .      .
+ *  |  |_/  /        \  \__//          ||    |  |
+ * /_______/ynamic    \____/niversal  /__\  /____\usic   /|  .  . ibliotheque
+ *                                                      /  \
+ *                                                     / .  \
+ * clickrem.c - Click removal helpers.                / / \  \
+ *                                                   | <  /   \_
+ * By entheh.                                        |  \/ /\   /
+ *                                                    \_  /  > /
+ *                                                      | \ / /
+ *                                                      |  ' /
+ *                                                       \__/
+ */
+
+#include "ags/lib/dumb-0.9.2/dumb.h"
+
+namespace AGS3 {
+
+typedef struct DUMB_CLICK DUMB_CLICK;
+
+
+struct DUMB_CLICK_REMOVER {
+	DUMB_CLICK *click;
+	int n_clicks;
+
+	int offset;
+};
+
+
+struct DUMB_CLICK {
+	DUMB_CLICK *next;
+	long pos;
+	sample_t step;
+};
+
+
+
+DUMB_CLICK_REMOVER *dumb_create_click_remover(void) {
+	DUMB_CLICK_REMOVER *cr = (DUMB_CLICK_REMOVER *)malloc(sizeof(*cr));
+	if (!cr) return NULL;
+
+	cr->click = NULL;
+	cr->n_clicks = 0;
+
+	cr->offset = 0;
+
+	return cr;
+}
+
+
+
+void dumb_record_click(DUMB_CLICK_REMOVER *cr, long pos, sample_t step) {
+	DUMB_CLICK *click;
+
+	ASSERT(pos >= 0);
+
+	if (!cr || !step) return;
+
+	if (pos == 0) {
+		cr->offset -= step;
+		return;
+	}
+
+	click = (DUMB_CLICK *)malloc(sizeof(*click));
+	if (!click) return;
+
+	click->pos = pos;
+	click->step = step;
+
+	click->next = cr->click;
+	cr->click = click;
+	cr->n_clicks++;
+}
+
+
+
+static DUMB_CLICK *dumb_click_mergesort(DUMB_CLICK *click, int n_clicks) {
+	int i;
+	DUMB_CLICK *c1, *c2, **cp;
+
+	if (n_clicks <= 1) return click;
+
+	/* Split the list into two */
+	c1 = click;
+	cp = &c1;
+	for (i = 0; i < n_clicks; i += 2) cp = &(*cp)->next;
+	c2 = *cp;
+	*cp = NULL;
+
+	/* Sort the sublists */
+	c1 = dumb_click_mergesort(c1, (n_clicks + 1) >> 1);
+	c2 = dumb_click_mergesort(c2, n_clicks >> 1);
+
+	/* Merge them */
+	cp = &click;
+	while (c1 && c2) {
+		if (c1->pos > c2->pos) {
+			*cp = c2;
+			c2 = c2->next;
+		} else {
+			*cp = c1;
+			c1 = c1->next;
+		}
+		cp = &(*cp)->next;
+	}
+	if (c2)
+		*cp = c2;
+	else
+		*cp = c1;
+
+	return click;
+}
+
+
+
+void dumb_remove_clicks(DUMB_CLICK_REMOVER *cr, sample_t *samples, long length, float halflife) {
+	DUMB_CLICK *click;
+	long pos = 0;
+	int offset;
+	int factor;
+
+	if (!cr) return;
+
+	factor = (int)floor(pow(0.5, 1.0 / halflife) * (1U << 31));
+
+	click = dumb_click_mergesort(cr->click, cr->n_clicks);
+	cr->click = NULL;
+	cr->n_clicks = 0;
+
+	while (click) {
+		DUMB_CLICK *next = click->next;
+		ASSERT(click->pos <= length);
+		offset = cr->offset;
+		if (offset < 0) {
+			offset = -offset;
+			while (pos < click->pos) {
+				samples[pos++] -= offset;
+				offset = (int)((LONG_LONG)(offset << 1) * factor >> 32);
+			}
+			offset = -offset;
+		} else {
+			while (pos < click->pos) {
+				samples[pos++] += offset;
+				offset = (int)((LONG_LONG)(offset << 1) * factor >> 32);
+			}
+		}
+		cr->offset = offset - click->step;
+		free(click);
+		click = next;
+	}
+
+	offset = cr->offset;
+	if (offset < 0) {
+		offset = -offset;
+		while (pos < length) {
+			samples[pos++] -= offset;
+			offset = (int)((LONG_LONG)(offset << 1) * factor >> 32);
+		}
+		offset = -offset;
+	} else {
+		while (pos < length) {
+			samples[pos++] += offset;
+			offset = (int)((LONG_LONG)(offset << 1) * factor >> 32);
+		}
+	}
+	cr->offset = offset;
+}
+
+
+
+sample_t dumb_click_remover_get_offset(DUMB_CLICK_REMOVER *cr) {
+	return cr ? cr->offset : 0;
+}
+
+
+
+void dumb_destroy_click_remover(DUMB_CLICK_REMOVER *cr) {
+	if (cr) {
+		DUMB_CLICK *click = cr->click;
+		while (click) {
+			DUMB_CLICK *next = click->next;
+			free(click);
+			click = next;
+		}
+		free(cr);
+	}
+}
+
+
+
+DUMB_CLICK_REMOVER **dumb_create_click_remover_array(int n) {
+	int i;
+	DUMB_CLICK_REMOVER **cr;
+	if (n <= 0) return NULL;
+	cr = (DUMB_CLICK_REMOVER **)malloc(n * sizeof(*cr));
+	if (!cr) return NULL;
+	for (i = 0; i < n; i++) cr[i] = dumb_create_click_remover();
+	return cr;
+}
+
+
+
+void dumb_record_click_array(int n, DUMB_CLICK_REMOVER **cr, long pos, sample_t *step) {
+	if (cr) {
+		int i;
+		for (i = 0; i < n; i++)
+			dumb_record_click(cr[i], pos, step[i]);
+	}
+}
+
+
+
+void dumb_record_click_negative_array(int n, DUMB_CLICK_REMOVER **cr, long pos, sample_t *step) {
+	if (cr) {
+		int i;
+		for (i = 0; i < n; i++)
+			dumb_record_click(cr[i], pos, -step[i]);
+	}
+}
+
+
+
+void dumb_remove_clicks_array(int n, DUMB_CLICK_REMOVER **cr, sample_t **samples, long length, float halflife) {
+	if (cr) {
+		int i;
+		for (i = 0; i < n; i++)
+			dumb_remove_clicks(cr[i], samples[i], length, halflife);
+	}
+}
+
+
+
+void dumb_click_remover_get_offset_array(int n, DUMB_CLICK_REMOVER **cr, sample_t *offset) {
+	if (cr) {
+		int i;
+		for (i = 0; i < n; i++)
+			if (cr[i]) offset[i] += cr[i]->offset;
+	}
+}
+
+
+
+void dumb_destroy_click_remover_array(int n, DUMB_CLICK_REMOVER **cr) {
+	if (cr) {
+		int i;
+		for (i = 0; i < n; i++) dumb_destroy_click_remover(cr[i]);
+		free(cr);
+	}
+}
+
+} // namespace AGS3
diff --git a/engines/ags/lib/dumb-0.9.2/helpers/memfile.c b/engines/ags/lib/dumb-0.9.2/helpers/memfile.c
new file mode 100644
index 0000000000..b65ab5f78d
--- /dev/null
+++ b/engines/ags/lib/dumb-0.9.2/helpers/memfile.c
@@ -0,0 +1,96 @@
+/*  _______         ____    __         ___    ___
+ * \    _  \       \    /  \  /       \   \  /   /       '   '  '
+ *  |  | \  \       |  |    ||         |   \/   |         .      .
+ *  |  |  |  |      |  |    ||         ||\  /|  |
+ *  |  |  |  |      |  |    ||         || \/ |  |         '  '  '
+ *  |  |  |  |      |  |    ||         ||    |  |         .      .
+ *  |  |_/  /        \  \__//          ||    |  |
+ * /_______/ynamic    \____/niversal  /__\  /____\usic   /|  .  . ibliotheque
+ *                                                      /  \
+ *                                                     / .  \
+ * memfile.c - Module for reading data from           / / \  \
+ *             memory using a DUMBFILE.              | <  /   \_
+ *                                                   |  \/ /\   /
+ * By entheh.                                         \_  /  > /
+ *                                                      | \ / /
+ *                                                      |  ' /
+ *                                                       \__/
+ */
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "dumb.h"
+
+
+
+typedef struct MEMFILE MEMFILE;
+
+struct MEMFILE
+{
+	const char *ptr;
+	long left;
+};
+
+
+
+static int dumb_memfile_skip(void *f, long n)
+{
+	MEMFILE *m = f;
+	if (n > m->left) return -1;
+	m->ptr += n;
+	m->left -= n;
+	return 0;
+}
+
+
+
+static int dumb_memfile_getc(void *f)
+{
+	MEMFILE *m = f;
+	if (m->left <= 0) return -1;
+	m->left--;
+	return *(const unsigned char *)m->ptr++;
+}
+
+
+
+static long dumb_memfile_getnc(char *ptr, long n, void *f)
+{
+	MEMFILE *m = f;
+	if (n > m->left) n = m->left;
+	memcpy(ptr, m->ptr, n);
+	m->ptr += n;
+	m->left -= n;
+	return n;
+}
+
+
+
+static void dumb_memfile_close(void *f)
+{
+	free(f);
+}
+
+
+
+static DUMBFILE_SYSTEM memfile_dfs = {
+	NULL,
+	&dumb_memfile_skip,
+	&dumb_memfile_getc,
+	&dumb_memfile_getnc,
+	&dumb_memfile_close
+};
+
+
+
+DUMBFILE *dumbfile_open_memory(const char *data, long size)
+{
+	MEMFILE *m = malloc(sizeof(*m));
+	if (!m) return NULL;
+
+	m->ptr = data;
+	m->left = size;
+
+	return dumbfile_open_ex(m, &memfile_dfs);
+}
diff --git a/engines/ags/lib/dumb-0.9.2/helpers/resample.c b/engines/ags/lib/dumb-0.9.2/helpers/resample.c
new file mode 100644
index 0000000000..d8b238fc71
--- /dev/null
+++ b/engines/ags/lib/dumb-0.9.2/helpers/resample.c
@@ -0,0 +1,1177 @@
+/*  _______         ____    __         ___    ___
+ * \    _  \       \    /  \  /       \   \  /   /       '   '  '
+ *  |  | \  \       |  |    ||         |   \/   |         .      .
+ *  |  |  |  |      |  |    ||         ||\  /|  |
+ *  |  |  |  |      |  |    ||         || \/ |  |         '  '  '
+ *  |  |  |  |      |  |    ||         ||    |  |         .      .
+ *  |  |_/  /        \  \__//          ||    |  |
+ * /_______/ynamic    \____/niversal  /__\  /____\usic   /|  .  . ibliotheque
+ *                                                      /  \
+ *                                                     / .  \
+ * resample.c - Resampling helper.                    / / \  \
+ *                                                   | <  /   \_
+ * By Bob and entheh.                                |  \/ /\   /
+ *                                                    \_  /  > /
+ * In order to find a good trade-off between            | \ / /
+ * speed and accuracy in this code, some tests          |  ' /
+ * were carried out regarding the behaviour of           \__/
+ * long long ints with gcc. The following code
+ * was tested:
+ *
+ * int a, b, c;
+ * c = ((long long)a * b) >> 16;
+ *
+ * DJGPP GCC Version 3.0.3 generated the following assembly language code for
+ * the multiplication and scaling, leaving the 32-bit result in EAX.
+ *
+ * movl  -8(%ebp), %eax    ; read one int into EAX
+ * imull -4(%ebp)          ; multiply by the other; result goes in EDX:EAX
+ * shrdl $16, %edx, %eax   ; shift EAX right 16, shifting bits in from EDX
+ *
+ * Note that a 32*32->64 multiplication is performed, allowing for high
+ * accuracy. On the Pentium 2 and above, shrdl takes two cycles (generally),
+ * so it is a minor concern when four multiplications are being performed
+ * (the cubic resampler). On the Pentium MMX and earlier, it takes four or
+ * more cycles, so this method is unsuitable for use in the low-quality
+ * resamplers.
+ *
+ * Since "long long" is a gcc-specific extension, we use LONG_LONG instead,
+ * defined in dumb.h. We may investigate later what code MSVC generates, but
+ * if it seems too slow then we suggest you use a good compiler.
+ *
+ * FIXME: these comments are somewhat out of date now.
+ */
+
+#include <math.h>
+#include "dumb.h"
+
+
+
+/* Compile with -DHEAVYDEBUG if you want to make sure the pick-up function is
+ * called when it should be. There will be a considerable performance hit,
+ * since at least one condition has to be tested for every sample generated.
+ */
+#ifdef HEAVYDEBUG
+#define HEAVYASSERT(cond) ASSERT(cond)
+#else
+#define HEAVYASSERT(cond)
+#endif
+
+
+
+//#define MULSC(a, b) ((int)((LONG_LONG)(a) * (b) >> 16))
+//#define MULSC(a, b) ((a) * ((b) >> 2) >> 14)
+#define MULSC(a, b) ((int)((LONG_LONG)((a) << 4) * ((b) << 12) >> 32))
+
+
+
+/* A global variable for controlling resampling quality wherever a local
+ * specification doesn't override it. The following values are valid:
+ *
+ *  0 - DUMB_RQ_ALIASING - fastest
+ *  1 - DUMB_RQ_LINEAR
+ *  2 - DUMB_RQ_CUBIC    - nicest
+ *
+ * Values outside the range 0-2 will behave the same as the nearest
+ * value within the range.
+ */
+int dumb_resampling_quality = 2;
+
+
+
+void dumb_reset_resampler(DUMB_RESAMPLER *resampler, sample_t *src, long pos, long start, long end)
+{
+	resampler->src = src;
+	resampler->pos = pos;
+	resampler->subpos = 0;
+	resampler->start = start;
+	resampler->end = end;
+	resampler->dir = 1;
+	resampler->pickup = NULL;
+	resampler->pickup_data = NULL;
+	resampler->min_quality = 0;
+	resampler->max_quality = DUMB_RQ_N_LEVELS - 1;
+	resampler->x[2] = resampler->x[1] = resampler->x[0] = 0;
+	resampler->overshot = -1;
+}
+
+
+
+DUMB_RESAMPLER *dumb_start_resampler(sample_t *src, long pos, long start, long end)
+{
+	DUMB_RESAMPLER *resampler = malloc(sizeof(*resampler));
+	if (!resampler) return NULL;
+	dumb_reset_resampler(resampler, src, pos, start, end);
+	return resampler;
+}
+
+
+
+/* For convenience, returns nonzero on stop. */
+static int process_pickup(DUMB_RESAMPLER *resampler)
+{
+	if (resampler->overshot < 0) {
+		resampler->overshot = 0;
+		dumb_resample(resampler, NULL, 2, 0, 1.0f);
+		resampler->x[0] = resampler->x[1];
+	}
+
+	for (;;) {
+		if (resampler->dir < 0) {
+			if (resampler->overshot >= 3 && resampler->pos+3 >= resampler->start) resampler->x[0] = resampler->src[resampler->pos+3];
+			if (resampler->overshot >= 2 && resampler->pos+2 >= resampler->start) resampler->x[1] = resampler->src[resampler->pos+2];
+			if (resampler->overshot >= 1 && resampler->pos+1 >= resampler->start) resampler->x[2] = resampler->src[resampler->pos+1];
+			resampler->overshot = resampler->start - resampler->pos - 1;
+		} else {
+			if (resampler->overshot >= 3 && resampler->pos-3 < resampler->end) resampler->x[0] = resampler->src[resampler->pos-3];
+			if (resampler->overshot >= 2 && resampler->pos-2 < resampler->end) resampler->x[1] = resampler->src[resampler->pos-2];
+			if (resampler->overshot >= 1 && resampler->pos-1 < resampler->end) resampler->x[2] = resampler->src[resampler->pos-1];
+			resampler->overshot = resampler->pos - resampler->end;
+		}
+
+		if (resampler->overshot < 0) {
+			resampler->overshot = 0;
+			return 0;
+		}
+
+		if (!resampler->pickup) {
+			resampler->dir = 0;
+			return 1;
+		}
+		(*resampler->pickup)(resampler, resampler->pickup_data);
+		if (resampler->dir == 0) return 1;
+		ASSERT(resampler->dir == -1 || resampler->dir == 1);
+	}
+}
+
+
+
+/* Executes the content 'iterator' times.
+ * Clobbers the 'iterator' variable.
+ * The loop is unrolled by four.
+ */
+#define LOOP4(iterator, CONTENT) \
+{ \
+	if ((iterator) & 2) { \
+		CONTENT; \
+		CONTENT; \
+	} \
+	if ((iterator) & 1) { \
+		CONTENT; \
+	} \
+	(iterator) >>= 2; \
+	while (iterator) { \
+		CONTENT; \
+		CONTENT; \
+		CONTENT; \
+		CONTENT; \
+		(iterator)--; \
+	} \
+}
+
+
+
+long dumb_resample(DUMB_RESAMPLER *resampler, sample_t *dst, long dst_size, float volume, float delta)
+{
+	int dt;
+	int vol;
+	long done;
+	long todo;
+	int quality;
+
+	if (!resampler || resampler->dir == 0) return 0;
+	ASSERT(resampler->dir == -1 || resampler->dir == 1);
+
+	done = 0;
+	dt = (int)(delta * 65536.0 + 0.5);
+	vol = (int)floor(volume * 65536.0 + 0.5);
+
+	if (vol == 0) dst = NULL;
+
+	quality = dumb_resampling_quality;
+	if (quality > resampler->max_quality) quality = resampler->max_quality;
+	else if (quality < resampler->min_quality) quality = resampler->min_quality;
+
+	while (done < dst_size) {
+		if (process_pickup(resampler)) return done;
+
+		if ((resampler->dir ^ dt) < 0)
+			dt = -dt;
+
+		if (resampler->dir < 0)
+			todo = (long)((((LONG_LONG)(resampler->pos - resampler->start) << 16) + resampler->subpos - dt) / -dt);
+		else
+			todo = (long)((((LONG_LONG)(resampler->end - resampler->pos) << 16) - resampler->subpos - 1 + dt) / dt);
+
+		if (todo < 0)
+			todo = 0;
+		else if (todo > dst_size - done)
+			todo = dst_size - done;
+
+		done += todo;
+
+		{
+			sample_t *src = resampler->src;
+			long pos = resampler->pos;
+			int subpos = resampler->subpos;
+			long diff = pos;
+			long overshot;
+			if (resampler->dir < 0) {
+				if (!dst) {
+					/* Silence or simulation */
+					LONG_LONG new_subpos = subpos + dt * todo;
+					pos += (long)(new_subpos >> 16);
+					subpos = (long)new_subpos & 65535;
+				} else if (quality <= DUMB_RQ_ALIASING) {
+					/* Aliasing, backwards */
+					sample_t xbuf[2];
+					sample_t *x = &xbuf[0];
+					sample_t *xstart;
+					xbuf[0] = resampler->x[1];
+					xbuf[1] = resampler->x[2];
+					while (todo && x < &xbuf[2]) {
+						HEAVYASSERT(pos >= resampler->start);
+						*dst++ += MULSC(x[0], vol);
+						subpos += dt;
+						pos += subpos >> 16;
+						x -= subpos >> 16;
+						subpos &= 65535;
+						todo--;
+					}
+					x = xstart = &src[pos];
+					LOOP4(todo,
+						*dst++ += MULSC(x[2], vol);
+						subpos += dt;
+						x += subpos >> 16;
+						subpos &= 65535;
+					);
+					pos += x - xstart;
+				} else if (quality <= DUMB_RQ_LINEAR) {
+					/* Linear interpolation, backwards */
+					sample_t xbuf[3];
+					sample_t *x = &xbuf[1];
+					xbuf[0] = resampler->x[1];
+					xbuf[1] = resampler->x[2];
+					xbuf[2] = src[pos];
+					while (todo && x < &xbuf[3]) {
+						HEAVYASSERT(pos >= resampler->start);
+						*dst++ += MULSC(x[0] + MULSC(x[-1] - x[0], subpos), vol);
+						subpos += dt;
+						pos += subpos >> 16;
+						x -= subpos >> 16;
+						subpos &= 65535;
+						todo--;
+					}
+					x = &src[pos];
+					LOOP4(todo,
+						HEAVYASSERT(pos >= resampler->start);
+						*dst++ += MULSC(x[1] + MULSC(x[2] - x[1], subpos), vol);
+						subpos += dt;
+						pos += subpos >> 16;
+						x += subpos >> 16;
+						subpos &= 65535;
+					);
+				} else {
+					/* Cubic interpolation, backwards */
+					sample_t xbuf[6];
+					sample_t *x = &xbuf[3];
+					sample_t *lastx = NULL;
+					int a = 0, b = 0, c = 0;
+					xbuf[0] = resampler->x[0];
+					xbuf[1] = resampler->x[1];
+					xbuf[2] = resampler->x[2];
+					xbuf[3] = src[pos];
+					if (pos-1 >= resampler->start) xbuf[4] = src[pos-1];
+					if (pos-2 >= resampler->start) xbuf[5] = src[pos-2];
+					while (todo && x < &xbuf[6]) {
+						HEAVYASSERT(pos >= resampler->start);
+						if (lastx != x) {
+							lastx = x;
+							a = (((x[-1] - x[-2]) << 1) + (x[-1] - x[-2]) + (x[-3] - x[0])) >> 1;
+							b = (x[-2] << 1) + x[0] - ((5 * x[-1] + x[-3]) >> 1);
+							c = (x[-2] - x[0]) >> 1;
+						}
+						*dst++ += MULSC(MULSC(MULSC(MULSC(a, subpos) + b, subpos) + c, subpos) + x[-1], vol);
+						subpos += dt;
+						pos += subpos >> 16;
+						x -= subpos >> 16;
+						subpos &= 65535;
+						todo--;
+					}
+					x = &src[pos];
+					lastx = NULL;
+					LOOP4(todo,
+						HEAVYASSERT(pos >= resampler->start);
+						if (lastx != x) {
+							lastx = x;
+							a = (((x[1] - x[2]) << 1) + (x[1] - x[2]) + (x[3] - x[0])) >> 1;
+							b = (x[2] << 1) + x[0] - ((5 * x[1] + x[3]) >> 1);
+							c = (x[2] - x[0]) >> 1;
+						}
+						*dst++ += MULSC(MULSC(MULSC(MULSC(a, subpos) + b, subpos) + c, subpos) + x[1], vol);
+						subpos += dt;
+						pos += subpos >> 16;
+						x += subpos >> 16;
+						subpos &= 65535;
+					);
+				}
+				diff = diff - pos;
+				overshot = resampler->start - pos - 1;
+				if (diff >= 3) {
+					resampler->x[0] = overshot >= 3 ? 0 : src[pos+3];
+					resampler->x[1] = overshot >= 2 ? 0 : src[pos+2];
+					resampler->x[2] = overshot >= 1 ? 0 : src[pos+1];
+				} else if (diff >= 2) {
+					resampler->x[0] = resampler->x[2];
+					resampler->x[1] = overshot >= 2 ? 0 : src[pos+2];
+					resampler->x[2] = overshot >= 1 ? 0 : src[pos+1];
+				} else if (diff >= 1) {
+					resampler->x[0] = resampler->x[1];
+					resampler->x[1] = resampler->x[2];
+					resampler->x[2] = overshot >= 1 ? 0 : src[pos+1];
+				}
+			} else {
+				if (!dst) {
+					/* Silence or simulation */
+					LONG_LONG new_subpos = subpos + dt * todo;
+					pos += (long)(new_subpos >> 16);
+					subpos = (long)new_subpos & 65535;
+				} else if (dumb_resampling_quality <= DUMB_RQ_ALIASING) {
+					/* Aliasing, forwards */
+					sample_t xbuf[2];
+					sample_t *x = &xbuf[0];
+					sample_t *xstart;
+					xbuf[0] = resampler->x[1];
+					xbuf[1] = resampler->x[2];
+					while (todo && x < &xbuf[2]) {
+						HEAVYASSERT(pos < resampler->end);
+						*dst++ += MULSC(x[0], vol);
+						subpos += dt;
+						pos += subpos >> 16;
+						x += subpos >> 16;
+						subpos &= 65535;
+						todo--;
+					}
+					x = xstart = &src[pos];
+					LOOP4(todo,
+						*dst++ += MULSC(x[-2], vol);
+						subpos += dt;
+						x += subpos >> 16;
+						subpos &= 65535;
+					);
+					pos += x - xstart;
+				} else if (dumb_resampling_quality <= DUMB_RQ_LINEAR) {
+					/* Linear interpolation, forwards */
+					sample_t xbuf[3];
+					sample_t *x = &xbuf[1];
+					xbuf[0] = resampler->x[1];
+					xbuf[1] = resampler->x[2];
+					xbuf[2] = src[pos];
+					while (todo && x < &xbuf[3]) {
+						HEAVYASSERT(pos < resampler->end);
+						*dst++ += MULSC(x[-1] + MULSC(x[0] - x[-1], subpos), vol);
+						subpos += dt;
+						pos += subpos >> 16;
+						x += subpos >> 16;
+						subpos &= 65535;
+						todo--;
+					}
+					x = &src[pos];
+					LOOP4(todo,
+						HEAVYASSERT(pos < resampler->end);
+						*dst++ += MULSC(x[-2] + MULSC(x[-1] - x[-2], subpos), vol);
+						subpos += dt;
+						pos += subpos >> 16;
+						x += subpos >> 16;
+						subpos &= 65535;
+					);
+				} else {
+					/* Cubic interpolation, forwards */
+					sample_t xbuf[6];
+					sample_t *x = &xbuf[3];
+					sample_t *lastx = NULL;
+					int a = 0, b = 0, c = 0;
+					xbuf[0] = resampler->x[0];
+					xbuf[1] = resampler->x[1];
+					xbuf[2] = resampler->x[2];
+					xbuf[3] = src[pos];
+					if (pos+1 < resampler->end) xbuf[4] = src[pos+1];
+					if (pos+2 < resampler->end) xbuf[5] = src[pos+2];
+					while (todo && x < &xbuf[6]) {
+						HEAVYASSERT(pos < resampler->end);
+						if (lastx != x) {
+							lastx = x;
+							a = (((x[-2] - x[-1]) << 1) + (x[-2] - x[-1]) + (x[0] - x[-3])) >> 1;
+							b = (x[-1] << 1) + x[-3] - ((5 * x[-2] + x[0]) >> 1);
+							c = (x[-1] - x[-3]) >> 1;
+						}
+						*dst++ += MULSC(MULSC(MULSC(MULSC(a, subpos) + b, subpos) + c, subpos) + x[-2], vol);
+						subpos += dt;
+						pos += subpos >> 16;
+						x += subpos >> 16;
+						subpos &= 65535;
+						todo--;
+					}
+					x = &src[pos];
+					lastx = NULL;
+					LOOP4(todo,
+						HEAVYASSERT(pos < resampler->end);
+						if (lastx != x) {
+							lastx = x;
+							a = (((x[-2] - x[-1]) << 1) + (x[-2] - x[-1]) + (x[0] - x[-3])) >> 1;
+							b = (x[-1] << 1) + x[-3] - ((5 * x[-2] + x[0]) >> 1);
+							c = (x[-1] - x[-3]) >> 1;
+						}
+						*dst++ += MULSC(MULSC(MULSC(MULSC(a, subpos) + b, subpos) + c, subpos) + x[-2], vol);
+						subpos += dt;
+						pos += subpos >> 16;
+						x += subpos >> 16;
+						subpos &= 65535;
+					);
+				}
+				diff = pos - diff;
+				overshot = pos - resampler->end;
+				if (diff >= 3) {
+					resampler->x[0] = overshot >= 3 ? 0 : src[pos-3];
+					resampler->x[1] = overshot >= 2 ? 0 : src[pos-2];
+					resampler->x[2] = overshot >= 1 ? 0 : src[pos-1];
+				} else if (diff >= 2) {
+					resampler->x[0] = resampler->x[2];
+					resampler->x[1] = overshot >= 2 ? 0 : src[pos-2];
+					resampler->x[2] = overshot >= 1 ? 0 : src[pos-1];
+				} else if (diff >= 1) {
+					resampler->x[0] = resampler->x[1];
+					resampler->x[1] = resampler->x[2];
+					resampler->x[2] = overshot >= 1 ? 0 : src[pos-1];
+				}
+			}
+			resampler->pos = pos;
+			resampler->subpos = subpos;
+		}
+	}
+
+	return done;
+}
+
+
+
+sample_t dumb_resample_get_current_sample(DUMB_RESAMPLER *resampler, float volume)
+{
+	int vol;
+	sample_t *src;
+	long pos;
+	int subpos;
+	int quality;
+
+	if (!resampler || resampler->dir == 0) return 0;
+	ASSERT(resampler->dir == -1 || resampler->dir == 1);
+
+	if (process_pickup(resampler)) return 0;
+
+	vol = (int)floor(volume * 65536.0 + 0.5);
+	if (vol == 0) return 0;
+
+	quality = dumb_resampling_quality;
+	if (quality > resampler->max_quality) quality = resampler->max_quality;
+	else if (quality < resampler->min_quality) quality = resampler->min_quality;
+
+	src = resampler->src;
+	pos = resampler->pos;
+	subpos = resampler->subpos;
+
+	if (resampler->dir < 0) {
+		HEAVYASSERT(pos >= resampler->start);
+		if (dumb_resampling_quality <= 0) {
+			/* Aliasing, backwards */
+			return MULSC(src[pos], vol);
+		} else if (quality <= DUMB_RQ_LINEAR) {
+			/* Linear interpolation, backwards */
+			return MULSC(resampler->x[2] + MULSC(resampler->x[1] - resampler->x[2], subpos), vol);
+		} else {
+			/* Cubic interpolation, backwards */
+			sample_t *x = resampler->x;
+			int a, b, c;
+			a = (((x[2] - x[1]) << 1) + (x[2] - x[1]) + (x[0] - src[pos])) >> 1;
+			b = (x[1] << 1) + src[pos] - ((5 * x[2] + x[0]) >> 1);
+			c = (x[1] - src[pos]) >> 1;
+			return MULSC(MULSC(MULSC(MULSC(a, subpos) + b, subpos) + c, subpos) + x[2], vol);
+		}
+	} else {
+		HEAVYASSERT(pos < resampler->end);
+		if (dumb_resampling_quality <= 0) {
+			/* Aliasing */
+			return MULSC(src[pos], vol);
+		} else if (dumb_resampling_quality <= DUMB_RQ_LINEAR) {
+			/* Linear interpolation, forwards */
+			return MULSC(resampler->x[1] + MULSC(resampler->x[2] - resampler->x[1], subpos), vol);
+		} else {
+			/* Cubic interpolation, forwards */
+			sample_t *x = resampler->x;
+			int a, b, c;
+			a = (((x[1] - x[2]) << 1) + (x[1] - x[2]) + (src[pos] - x[0])) >> 1;
+			b = (x[2] << 1) + x[0] - ((5 * x[1] + src[pos]) >> 1);
+			c = (x[2] - x[0]) >> 1;
+			return MULSC(MULSC(MULSC(MULSC(a, subpos) + b, subpos) + c, subpos) + x[1], vol);
+		}
+	}
+}
+
+
+
+void dumb_end_resampler(DUMB_RESAMPLER *resampler)
+{
+	if (resampler)
+		free(resampler);
+}
+
+
+
+#if 0
+/* The following macro is used to overcome the fact that most C
+ * compilers (including gcc and MSVC) can't correctly multiply signed
+ * integers outside the range -32768 to 32767. i86 assembler versions
+ * don't need to use this method, since the processor does in fact
+ * have instructions to multiply large numbers correctly - which
+ * means using assembly language could make a significant difference
+ * to the speed.
+ *
+ * The basic method is as follows. We halve the subposition (how far
+ * we are between samples), so it never exceeds 32767. We also halve
+ * the delta, which is the amount to be added to the subposition each
+ * time. Then we unroll the loop twofold, so that we can add the lost
+ * one every other time if necessary (since the halving may have
+ * resulted in rounding down).
+ *
+ * This method doesn't incur any cumulative inaccuracies. There is a
+ * very slight loss of quality, which I challenge anyone to notice -
+ * but the position will advance at *exactly* the same rate as it
+ * would if we didn't use this method. This also means the pitch is
+ * exactly the same, which may even make a difference to trained
+ * musicians when resampling down a lot :)
+ *
+ * Each time this macro is invoked, DO_RESAMPLE(inc) must be defined
+ * to calculate the samples by the appropriate equation (linear,
+ * cubic, etc.). See the individual cases for examples of how this is
+ * done.
+ */
+#define MAKE_RESAMPLER()							\
+{													\
+	if (dt & 1) {									\
+		long todo2;									\
+													\
+		dt >>= 1;									\
+													\
+		if (src_subpos & 1) {						\
+			src_subpos >>= 1;						\
+			DO_RESAMPLE(1);							\
+			todo--;									\
+		} else										\
+			src_subpos >>= 1;						\
+													\
+		todo2 = todo >> 1;							\
+													\
+		while (todo2) {								\
+			DO_RESAMPLE(0);							\
+			DO_RESAMPLE(1);							\
+			todo2--;								\
+		}											\
+													\
+		if (todo & 1) {								\
+			DO_RESAMPLE(0);							\
+			src_subpos = (src_subpos << 1) | 1;		\
+		} else										\
+			src_subpos <<= 1;						\
+													\
+		todo = 0;									\
+		dt = (dt << 1) | 1;							\
+	} else {										\
+		long subposbit = src_subpos & 1;			\
+		dt >>= 1;									\
+		src_subpos >>= 1;							\
+													\
+		if (todo & 1) {								\
+			DO_RESAMPLE(0);							\
+		}											\
+													\
+		todo >>= 1;									\
+													\
+		while (todo) {								\
+			DO_RESAMPLE(0);							\
+			DO_RESAMPLE(0);							\
+			todo--;									\
+		}											\
+													\
+		src_subpos = (src_subpos << 1) | subposbit; \
+		dt <<= 1;									\
+	}												\
+}
+
+
+
+sample_t dumb_resample_get_current_sample(
+	sample_t *src, long *_src_pos, int *_src_subpos,
+	long src_start, long src_end,
+	float volume, int *_dir,
+	DUMB_RESAMPLE_PICKUP pickup, void *pickup_data
+)
+{
+	long src_pos = *_src_pos;
+	int src_subpos = *_src_subpos;
+	int dir = _dir ? *_dir : 1;
+
+	sample_t value = 0;
+
+	if (dir == 0)
+		return 0;
+
+	ASSERT(dir == 1 || dir == -1);
+
+	if (dir < 0 ? (src_pos < src_start) : (src_pos >= src_end)) {
+
+		/* If there's no pick-up function, we stop. */
+		if (!pickup) {
+			dir = 0;
+			goto end;
+		}
+
+		/* Process the pick-up. It may need invoking more than once. */
+		do {
+			dir = (*pickup)(src, &src_pos, &src_subpos, &src_start, &src_end, dir, pickup_data);
+
+			if (dir == 0)
+				goto end;
+
+			ASSERT(dir == 1 || dir == -1);
+		} while (dir < 0 ? (src_pos < src_start) : (src_pos >= src_end));
+	}
+
+	HEAVYASSERT(dir < 0 ? (src_pos >= src_start) : (src_pos < src_end));
+
+	if (dumb_resampling_quality == 0) {
+		/* Aliasing (coarse) */
+		int volume_fact = (int)(volume * 16384.0);
+		value = (src[src_pos] * volume_fact) >> 14;
+	} else if (dumb_resampling_quality <= 2) {
+		/* Linear interpolation */
+		int volume_fact = (int)(volume * 16384.0);
+		int subpos = src_subpos >> 1;
+		value = ((src[src_pos] + ((((src[src_pos + 1] - src[src_pos]) >> 1) * subpos) >> 14)) * volume_fact) >> 14;
+	} else if (dumb_resampling_quality == 3) {
+		/* Quadratic interpolation */
+		int volume_fact = (int)(volume * 16384.0);
+		int a, b;
+		sample_t *x;
+		int subpos = src_subpos >> 1;
+		x = &src[src_pos];
+		a = ((x[0] + x[2]) >> 1) - x[1];
+		b = ((x[2] - x[0]) >> 1) - (a << 1);
+		value = (((((((a * subpos) >> 15) + b) * subpos) >> 15) + x[0]) * volume_fact) >> 14;
+	} else {
+		/* Cubic interpolation */
+		int volume_fact = (int)(volume * 16384.0);
+		int a, b, c;
+		sample_t *x;
+		int subpos = src_subpos >> 1;
+		x = &src[src_pos];
+		a = (((x[1] - x[2]) << 1) + (x[1] - x[2]) + (x[3] - x[0])) >> 1;
+		b = (x[2] << 1) + x[0] - ((5 * x[1] + x[3]) >> 1);
+		c = (x[2] - x[0]) >> 1;
+		value = (((int)(((LONG_LONG)((int)(((LONG_LONG)((int)(((LONG_LONG)a * subpos) >> 15) + b) * subpos) >> 15) + c) * subpos) >> 15) + x[1]) * volume_fact) >> 14;
+	}
+
+	end:
+
+	*_src_pos = src_pos;
+	*_src_subpos = src_subpos;
+	if (_dir) *_dir = dir;
+
+	return value;
+}
+
+
+
+long dumb_resample(
+	sample_t *src, long *_src_pos, int *_src_subpos,
+	long src_start, long src_end,
+	sample_t *dst, long dst_size,
+	float volume, float delta, int *_dir,
+	DUMB_RESAMPLE_PICKUP pickup, void *pickup_data
+)
+{
+	int dt = (int)(delta * 65536.0 + 0.5);
+	long s = 0; /* Current position in the destination buffer */
+
+	long src_pos = *_src_pos;
+	int src_subpos = *_src_subpos;
+	int dir = _dir ? *_dir : 1;
+
+	int linear_average;
+
+	if (dir == 0)
+		return 0;
+
+	ASSERT(dir == 1 || dir == -1);
+
+	linear_average = dst && dumb_resampling_quality >= 2 && dt > 65536;
+
+	if (dir < 0) dt = -dt;
+
+	if (linear_average)
+		volume /= delta;
+
+	while (s < dst_size) {
+
+		long todo;
+
+		/* Process pick-ups first, just in case. */
+
+		if (linear_average) {
+
+			/* For linear average, the pick-up point could split a sum into
+			 * two parts. We handle this by putting the pick-up code inside
+			 * the summing loop. Note that this code is only executed when we
+			 * know that a pick-up is necessary somewhere during this sum
+			 * (although it is always executed once for the first sample).
+			 * We use a separate loop further down when we know we won't have
+			 * to do a pick-up, so the condition does not need testing inside
+			 * the loop.
+			 */
+
+			float sum;
+			long i;
+			int advance;
+			int x[3];
+
+			advance = src_subpos + dt;
+
+			/* Make these negative. Then they stay within the necessary
+			 * range for integer multiplication, -32768 to 32767 ;)
+			 */
+			x[0] = ~(src_subpos >> 1); /* = -1 - (src_subpos >> 1) */
+			x[2] = x[0] ^ 0x7FFF; /* = -32768 + (src_subpos >> 1) */
+
+			sum = (float)(-((src[src_pos] * (x+1)[dir]) >> 15));
+
+			i = src_pos + (advance >> 16);
+			src_pos += dir;
+			src_subpos = (dir >> 1) & 65535; /* changes 1,-1 to 0,65535 */
+
+			advance &= 65535;
+
+			/* i is the index of the first sample NOT to sum fully,
+			 * regardless of the direction of resampling.
+			 */
+
+			while (dir < 0 ? (i < src_start) : (i >= src_end)) {
+				if (dir < 0) {
+					while (src_pos >= src_start)
+						sum += src[src_pos--];
+				} else {
+					while (src_pos < src_end)
+						sum += src[src_pos++];
+				}
+
+				i -= src_pos;
+				/* i is now the number of samples left to sum fully, except
+				 * it's negative if we're going backwards.
+				 */
+
+				if (!pickup) {
+					dir = 0;
+					goto endsum;
+				}
+
+				dir = (*pickup)(src, &src_pos, &src_subpos, &src_start, &src_end, dir, pickup_data);
+
+				if (dir == 0)
+					goto endsum;
+
+				ASSERT(dir == 1 || dir == -1);
+
+				if ((dir ^ dt) < 0) {
+					dt = -dt;
+					advance ^= 65535;
+					i = -i;
+				}
+
+				i += src_pos;
+				/* There, i is back to normal. */
+			}
+
+			for (; src_pos != i; src_pos += dir)
+				sum += src[src_pos];
+
+			src_subpos = advance;
+
+			x[2] = src_subpos >> 1;
+			x[0] = x[2] ^ 0x7FFF; /* = 32767 - (src_subpos >> 1) */
+
+			sum += (src[src_pos] * (x+1)[dir]) >> 15;
+
+			endsum:
+
+			sum *= volume;
+			dst[s] += (int)sum;
+
+			s++;
+
+			if (dir == 0)
+				break;
+
+		} else if (dir < 0 ? (src_pos < src_start) : (src_pos >= src_end)) {
+
+			/* If there's no pick-up function, we stop. */
+			if (!pickup) {
+				dir = 0;
+				break;
+			}
+
+			/* Process the pick-up. It may need invoking more than once. */
+			do {
+				dir = (*pickup)(src, &src_pos, &src_subpos, &src_start, &src_end, dir, pickup_data);
+
+				if (dir == 0)
+					goto end;
+
+				ASSERT(dir == 1 || dir == -1);
+			} while (dir < 0 ? (src_pos < src_start) : (src_pos >= src_end));
+
+			/* Update sign of dt to match that of dir. */
+			if ((dir ^ dt) < 0)
+				dt = -dt;
+		}
+
+		/* Work out how many contiguous samples we can now render. */
+		if (dir < 0)
+			todo = (long)((((LONG_LONG)(src_pos - src_start) << 16) + src_subpos) / -dt);
+		else
+			todo = (long)((((LONG_LONG)(src_end - src_pos) << 16) - src_subpos - 1) / dt);
+
+		/* The above equations work out how many complete dt-sized
+		 * intervals there are between the current position and the loop
+		 * point (provided there is a little fractional extra). The linear
+		 * average function needs complete intervals - but the other
+		 * resamplers only read a sample from the beginning of each interval,
+		 * so they can process one extra sample in their main loops (so we
+		 * increment todo in a moment).
+		 *
+		 * The linear average function makes up the extra sample using the
+		 * specialised pick-up code above.
+		 *
+		 * Note that our above pick-up process should have absolutely ensured
+		 * that the result of this function will be nonnegative.
+		 */
+
+		ASSERT(todo >= 0);
+
+		if (!linear_average)
+			todo++;
+
+		/* Of course we don't want to overrun the output buffer! */
+		if (todo > dst_size - s)
+			todo = dst_size - s;
+
+		if (!dst) {
+
+			LONG_LONG t = src_subpos + (LONG_LONG)dt * todo;
+			src_pos += (long)(t >> 16);
+			src_subpos = (int)t & 0xFFFFl;
+
+			s += todo;
+
+		} else if (linear_average) {
+
+			float sum;
+			long i;
+			int advance;
+			int x[3];
+
+			while (todo) {
+
+				advance = src_subpos + dt;
+
+				/* Make these negative. Then they stay within the necessary
+				 * range for integer multiplication, -32768 to 32767 ;)
+				 */
+				x[0] = ~(src_subpos >> 1); /* = -1 - (src_subpos >> 1) */
+				x[2] = x[0] ^ 0x7FFF; /* = -32768 + (src_subpos >> 1) */
+
+				sum = (float)(-((src[src_pos] * (x+1)[dir]) >> 15));
+
+				i = src_pos + (advance >> 16);
+				src_pos += dir;
+				src_subpos = (dir >> 1) & 65535; /* changes 1,-1 to 0,65535 */
+
+				advance &= 65535;
+
+				/* i is the index of the first sample NOT to sum fully,
+				 * regardless of the direction of resampling.
+				 */
+
+				HEAVYASSERT(dir < 0 ? (i >= src_start) : (i < src_end));
+
+				for (; src_pos != i; src_pos += dir)
+					sum += src[src_pos];
+
+				src_subpos = advance;
+
+				x[2] = src_subpos >> 1;
+				x[0] = x[2] ^ 0x7FFF; /* = 32767 - (src_subpos >> 1) */
+
+				sum += (src[src_pos] * (x+1)[dir]) >> 15;
+
+				sum *= volume;
+				dst[s] += (int)sum;
+
+				s++;
+				todo--;
+			}
+
+		} else if (dumb_resampling_quality == 0 || (dumb_resampling_quality == 1 && delta >= 1.0)) {
+
+			/* Aliasing (coarse) */
+			int volume_fact = (int)(volume * 16384.0);
+
+			do {
+				HEAVYASSERT(dir < 0 ? (src_pos >= src_start) : (src_pos < src_end));
+				dst[s] += ((src[src_pos] * volume_fact) >> 14);
+				src_subpos += dt;
+				src_pos += src_subpos >> 16;
+				src_subpos &= 0xFFFFl;
+				s++;
+			} while (--todo);
+
+		} else if (dumb_resampling_quality <= 2) {
+
+			/* Linear interpolation */
+			int volume_fact = (int)(volume * 16384.0);
+
+			#define DO_RESAMPLE(inc)		 \
+			{								 \
+				HEAVYASSERT(dir < 0 ? (src_pos >= src_start) : (src_pos < src_end)); \
+											 \
+				dst[s] += (((src[src_pos] + ((((src[src_pos + 1] - src[src_pos]) >> 1) * src_subpos) >> 14)) * volume_fact) >> 14); \
+											 \
+				src_subpos += dt + inc;		 \
+				src_pos += src_subpos >> 15; \
+				src_subpos &= 0x7FFFl;		 \
+				s++;						 \
+			}
+
+			MAKE_RESAMPLER();
+
+			#undef DO_RESAMPLE
+
+		} else if (dumb_resampling_quality == 3) {
+
+			/* Quadratic interpolation */
+
+			int volume_fact = (int)(volume * 16384.0);
+			int a = 0, b = 0;
+			sample_t *x = NULL;
+			int last_src_pos = -1;
+
+			/* AIM: no integer multiplicands must transcend the range -32768 to 32767.
+			 * This limitation is imposed by most compilers, including gcc and MSVC.
+			 *
+			 * a = 0.5 * (s0 + s2) - s1
+			 * b = -1.5 * s0 + 2 * s1 - 0.5 * s2
+			 * c = s0
+			 *
+			 * s = (a * t + b) * t + c
+			 *
+			 * In fixed-point:
+			 *
+			 * a = ((s0 + s2) >> 1) - s1
+			 * b = ((-3 * s0 - s2) >> 1) + (s1 << 1)
+			 *
+			 * s = (((((a * t) >> 16) + b) * t) >> 16) + s0
+			 *
+			 * With t halved (since t can reach 65535):
+			 *
+			 * s = (((((a * t) >> 15) + b) * t) >> 15) + s0
+			 *
+			 * a currently reaches 65536
+			 * b currently reaches 131072
+			 *
+			 * So we must use aon2
+			 *
+			 * s = (((((aon2 * t) >> 14) + b) * t) >> 15) + s0
+			 *
+			 * ((aon2 * t) >> 14) + b is 5 times too big
+			 * so we must divide by 8
+			 *
+			 * s = (((((aon2 * t) >> 17) + bon8) * t) >> 12) + s0
+			 *
+			 * aon2 = ((s0 + s2) >> 2) - (s1 >> 1)
+			 * bon8 = ((-3 * s0 - s2) >> 4) + (s1 >> 2)
+			 * or:
+			 * bon8 = ((s2 - s0) >> 4) - (aon2 >> 1)
+			 */
+
+			/* Unh4x0r3d version:
+			#define DO_RESAMPLE(inc)						\
+			{												\
+				HEAVYASSERT(dir < 0 ? (src_pos >= src_start) : (src_pos < src_end)); \
+															\
+				if (src_pos != last_src_pos) {				\
+					last_src_pos = src_pos;					\
+					x = &src[src_pos];						\
+					a = ((x[0] + x[2]) >> 2) - (x[1] >> 1); \
+					b = ((x[2] - x[0]) >> 4) - (a >> 1);	\
+				}											\
+															\
+				dst[s] += ((((((((a * src_subpos) >> 17) + b) * src_subpos) >> 12) + x[0]) * volume_fact) >> 14); \
+															\
+				src_subpos += dt + inc;						\
+				src_pos += src_subpos >> 15;				\
+				src_subpos &= 0x7FFFl;						\
+				s++;										\
+			}
+			*/
+
+			/* H4x0r3d version: */
+			#define DO_RESAMPLE(inc)						\
+			{												\
+				HEAVYASSERT(dir < 0 ? (src_pos >= src_start) : (src_pos < src_end)); \
+															\
+				if (src_pos != last_src_pos) {				\
+					last_src_pos = src_pos;					\
+					x = &src[src_pos];						\
+					a = ((x[0] + x[2]) >> 1) - x[1];		\
+					b = ((x[2] - x[0]) >> 1) - (a << 1);	\
+				}											\
+															\
+				dst[s] += ((((((((a * src_subpos) >> 15) + b) * src_subpos) >> 15) + x[0]) * volume_fact) >> 14); \
+															\
+				src_subpos += dt + inc;						\
+				src_pos += src_subpos >> 15;				\
+				src_subpos &= 0x7FFFl;						\
+				s++;										\
+			}
+
+			MAKE_RESAMPLER();
+
+			#undef DO_RESAMPLE
+
+		} else {
+
+			/* Cubic interpolation */
+
+			int volume_fact = (int)(volume * 16384.0);
+			int a = 0, b = 0, c = 0;
+			sample_t *x = NULL;
+			int last_src_pos = -1;
+
+			/* AIM: never multiply integers outside the range -32768 to 32767.
+			 *
+			 * a = 1.5f * (x[1] - x[2]) + (x[3] - x[0]) * 0.5f;
+			 * b = 2.0f * x[2] + x[0] - 2.5f * x[1] - x[3] * 0.5f;
+			 * c = (x[2] - x[0]) * 0.5f;
+			 *
+			 * s = ((a * t + b) * t + c) * t + x[1];
+			 *
+			 * Fixed-point version:
+			 *
+			 * a = (((x[1] - x[2]) << 1) + (x[1] - x[2]) + (x[3] - x[0])) >> 1;
+			 * b = (x[2] << 1) + x[0] - ((5 * x[1] + x[3]) >> 1);
+			 * c = (x[2] - x[0]) >> 1;
+			 *
+			 * s = ((((((((a * t) >> 15) + b) * t) >> 15) + c) * t) >> 15) + x[1];
+			 *   (with t already halved, maximum 32767)
+			 *
+			 * a is in (((1+1)*2)+(1+1)+(1+1))/2 = 8 times the required range
+			 * b is in (1*2)+1+((5*1+1)/2) = 6 times
+			 * c is in the required range
+			 *
+			 * We must use aon8
+			 *
+			 * s = ((((((((aon8 * t) >> 12) + b) * t) >> 15) + c) * t) >> 15) + x[1];
+			 *
+			 * But ((aon8 * t) >> 12) is in 2^(15+15-12) = 2^18 = 8 times
+			 * b is in 6 times
+			 * so we divide both ((aon8 * t) >> 12) and b by 16
+			 *
+			 * s = ((((((((aon8 * t) >> 16) + bon16) * t) >> 11) + c) * t) >> 15) + x[1];
+			 *
+			 * ((... + bon16) * t) >> 11 is 16 times too big
+			 * c is in the correct range
+			 * we must divide both by 32
+			 *
+			 * s = ((((((((aon8 * t) >> 16) + bon16) * t) >> 16) + con32) * t) >> 10) + x[1];
+			 *
+			 * aon8  = (((x[1] - x[2]) << 1) + (x[1] - x[2]) + (x[3] - x[0])) >> 4;
+			 * bon16 = ((x[2] << 2) + (x[0] << 1) - (5 * x[1] + x[3])) >> 5;
+			 * con32 = (x[2] - x[0]) >> 6;
+			 *
+			 * A lot of accuracy is lost here. It is quite likely that some
+			 * of the above would cancel anyway, so the scaling down wouldn't
+			 * have to be so severe. However, I'm not in the mood to work it
+			 * out now :P
+			 *
+			 * It may also be worth investigating whether doing this stuff
+			 * in floats would be faster.
+			 */
+
+			/* Unh4x0r3d version:
+			#define DO_RESAMPLE(inc)		   \
+			{								   \
+				HEAVYASSERT(dir < 0 ? (src_pos >= src_start) : (src_pos < src_end)); \
+											   \
+				if (src_pos != last_src_pos) { \
+					last_src_pos = src_pos;	   \
+					x = &src[src_pos];		   \
+					a = (((x[1] - x[2]) << 1) + (x[1] - x[2]) + (x[3] - x[0])) >> 4; \
+					b = ((x[2] << 2) + (x[0] << 1) - (5 * x[1] + x[3])) >> 5; \
+					c = (x[2] - x[0]) >> 6;	   \
+				}							   \
+											   \
+				dst[s] += ((((((((((a * src_subpos) >> 16) + b) * src_subpos) >> 16) + c) * src_subpos) >> 10) + x[1]) * volume_fact) >> 14; \
+											   \
+				src_subpos += dt + inc;		   \
+				src_pos += src_subpos >> 15;   \
+				src_subpos &= 0x7FFFl;		   \
+				s++;						   \
+			}
+			*/
+
+			/* H4x0r3d version: */
+			#define DO_RESAMPLE(inc)		   \
+			{								   \
+				HEAVYASSERT(dir < 0 ? (src_pos >= src_start) : (src_pos < src_end)); \
+											   \
+				if (src_pos != last_src_pos) { \
+					last_src_pos = src_pos;	   \
+					x = &src[src_pos];		   \
+					a = (((x[1] - x[2]) << 1) + (x[1] - x[2]) + (x[3] - x[0])) >> 1; \
+					b = (x[2] << 1) + x[0] - ((5 * x[1] + x[3]) >> 1); \
+					c = (x[2] - x[0]) >> 1;	   \
+				}							   \
+											   \
+				dst[s] += (((int)(((LONG_LONG)((int)(((LONG_LONG)((int)(((LONG_LONG)a * src_subpos) >> 15) + b) * src_subpos) >> 15) + c) * src_subpos) >> 15) + x[1]) * volume_fact) >> 14; \
+											   \
+				src_subpos += dt + inc;		   \
+				src_pos += src_subpos >> 15;   \
+				src_subpos &= 0x7FFFl;		   \
+				s++;						   \
+			}
+
+			MAKE_RESAMPLER();
+
+			#undef DO_RESAMPLE
+
+		}
+
+	}
+
+	end:
+
+	ASSERT(s <= dst_size);
+
+	*_src_pos = src_pos;
+	*_src_subpos = src_subpos;
+	if (_dir) *_dir = dir;
+
+	return s;
+}
+#endif
diff --git a/engines/ags/lib/dumb-0.9.2/helpers/sampbuf.c b/engines/ags/lib/dumb-0.9.2/helpers/sampbuf.c
new file mode 100644
index 0000000000..75510c729a
--- /dev/null
+++ b/engines/ags/lib/dumb-0.9.2/helpers/sampbuf.c
@@ -0,0 +1,47 @@
+/*  _______         ____    __         ___    ___
+ * \    _  \       \    /  \  /       \   \  /   /       '   '  '
+ *  |  | \  \       |  |    ||         |   \/   |         .      .
+ *  |  |  |  |      |  |    ||         ||\  /|  |
+ *  |  |  |  |      |  |    ||         || \/ |  |         '  '  '
+ *  |  |  |  |      |  |    ||         ||    |  |         .      .
+ *  |  |_/  /        \  \__//          ||    |  |
+ * /_______/ynamic    \____/niversal  /__\  /____\usic   /|  .  . ibliotheque
+ *                                                      /  \
+ *                                                     / .  \
+ * sampbuf.c - Helper for allocating sample           / / \  \
+ *             buffers.                              | <  /   \_
+ *                                                   |  \/ /\   /
+ * By entheh.                                         \_  /  > /
+ *                                                      | \ / /
+ *                                                      |  ' /
+ *                                                       \__/
+ */
+
+#include <stdlib.h>
+#include "dumb.h"
+
+
+
+sample_t **create_sample_buffer(int n_channels, long length)
+{
+	int i;
+	sample_t **samples = malloc(n_channels * sizeof(*samples));
+	if (!samples) return NULL;
+	samples[0] = malloc(n_channels * length * sizeof(*samples[0]));
+	if (!samples[0]) {
+		free(samples);
+		return NULL;
+	}
+	for (i = 1; i < n_channels; i++) samples[i] = samples[i-1] + length;
+	return samples;
+}
+
+
+
+void destroy_sample_buffer(sample_t **samples)
+{
+	if (samples) {
+		free(samples[0]);
+		free(samples);
+	}
+}
diff --git a/engines/ags/lib/dumb-0.9.2/helpers/silence.c b/engines/ags/lib/dumb-0.9.2/helpers/silence.c
new file mode 100644
index 0000000000..4d5fdcf4da
--- /dev/null
+++ b/engines/ags/lib/dumb-0.9.2/helpers/silence.c
@@ -0,0 +1,29 @@
+/*  _______         ____    __         ___    ___
+ * \    _  \       \    /  \  /       \   \  /   /       '   '  '
+ *  |  | \  \       |  |    ||         |   \/   |         .      .
+ *  |  |  |  |      |  |    ||         ||\  /|  |
+ *  |  |  |  |      |  |    ||         || \/ |  |         '  '  '
+ *  |  |  |  |      |  |    ||         ||    |  |         .      .
+ *  |  |_/  /        \  \__//          ||    |  |
+ * /_______/ynamic    \____/niversal  /__\  /____\usic   /|  .  . ibliotheque
+ *                                                      /  \
+ *                                                     / .  \
+ * silence.c - Silencing helper.                      / / \  \
+ *                                                   | <  /   \_
+ * By entheh.                                        |  \/ /\   /
+ *                                                    \_  /  > /
+ *                                                      | \ / /
+ *                                                      |  ' /
+ *                                                       \__/
+ */
+
+#include <string.h>
+#include "dumb.h"
+
+
+
+void dumb_silence(sample_t *samples, long length)
+{
+	memset(samples, 0, length * sizeof(*samples));
+}
+
diff --git a/engines/ags/lib/dumb-0.9.2/helpers/stdfile.c b/engines/ags/lib/dumb-0.9.2/helpers/stdfile.c
new file mode 100644
index 0000000000..2f02539a92
--- /dev/null
+++ b/engines/ags/lib/dumb-0.9.2/helpers/stdfile.c
@@ -0,0 +1,93 @@
+/*  _______         ____    __         ___    ___
+ * \    _  \       \    /  \  /       \   \  /   /       '   '  '
+ *  |  | \  \       |  |    ||         |   \/   |         .      .
+ *  |  |  |  |      |  |    ||         ||\  /|  |
+ *  |  |  |  |      |  |    ||         || \/ |  |         '  '  '
+ *  |  |  |  |      |  |    ||         ||    |  |         .      .
+ *  |  |_/  /        \  \__//          ||    |  |
+ * /_______/ynamic    \____/niversal  /__\  /____\usic   /|  .  . ibliotheque
+ *                                                      /  \
+ *                                                     / .  \
+ * stdfile.c - stdio file input module.               / / \  \
+ *                                                   | <  /   \_
+ * By entheh.                                        |  \/ /\   /
+ *                                                    \_  /  > /
+ *                                                      | \ / /
+ *                                                      |  ' /
+ *                                                       \__/
+ */
+
+#include <stdio.h>
+
+#include "dumb.h"
+
+
+
+static void *dumb_stdfile_open(const char *filename)
+{
+	return fopen(filename, "rb");
+}
+
+
+
+static int dumb_stdfile_skip(void *f, long n)
+{
+	return fseek(f, n, SEEK_CUR);
+}
+
+
+
+static int dumb_stdfile_getc(void *f)
+{
+	return fgetc(f);
+}
+
+
+
+static long dumb_stdfile_getnc(char *ptr, long n, void *f)
+{
+	return fread(ptr, 1, n, f);
+}
+
+
+
+static void dumb_stdfile_close(void *f)
+{
+	fclose(f);
+}
+
+
+
+static DUMBFILE_SYSTEM stdfile_dfs = {
+	&dumb_stdfile_open,
+	&dumb_stdfile_skip,
+	&dumb_stdfile_getc,
+	&dumb_stdfile_getnc,
+	&dumb_stdfile_close
+};
+
+
+
+void dumb_register_stdfiles(void)
+{
+	register_dumbfile_system(&stdfile_dfs);
+}
+
+
+
+static DUMBFILE_SYSTEM stdfile_dfs_leave_open = {
+	NULL,
+	&dumb_stdfile_skip,
+	&dumb_stdfile_getc,
+	&dumb_stdfile_getnc,
+	NULL
+};
+
+
+
+DUMBFILE *dumbfile_open_stdfile(FILE *p)
+{
+	DUMBFILE *d = dumbfile_open_ex(p, &stdfile_dfs_leave_open);
+
+	return d;
+}
diff --git a/engines/ags/lib/dumb-0.9.2/it/it.h b/engines/ags/lib/dumb-0.9.2/it/it.h
new file mode 100644
index 0000000000..bf19d3703b
--- /dev/null
+++ b/engines/ags/lib/dumb-0.9.2/it/it.h
@@ -0,0 +1,714 @@
+/* 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.
+ *
+ */
+
+/*  _______         ____    __         ___    ___
+ * \    _  \       \    /  \  /       \   \  /   /       '   '  '
+ *  |  | \  \       |  |    ||         |   \/   |         .      .
+ *  |  |  |  |      |  |    ||         ||\  /|  |
+ *  |  |  |  |      |  |    ||         || \/ |  |         '  '  '
+ *  |  |  |  |      |  |    ||         ||    |  |         .      .
+ *  |  |_/  /        \  \__//          ||    |  |
+ * /_______/ynamic    \____/niversal  /__\  /____\usic   /|  .  . ibliotheque
+ *                                                      /  \
+ *                                                     / .  \
+ * internal/it.h - Internal stuff for IT playback     / / \  \
+ *                 and MOD/XM/S3M conversion.        | <  /   \_
+ *                                                   |  \/ /\   /
+ *                                                    \_  /  > /
+ *                                                      | \ / /
+ *                                                      |  ' /
+ *                                                       \__/
+ */
+
+#ifndef AGS_LIB_DUMB_INTERNAL_IT_H
+#define AGS_LIB_DUMB_INTERNAL_IT_H
+
+namespace AGS3 {
+
+/** TO DO: THINK ABOUT THE FOLLOWING:
+
+sigdata->flags & IT_COMPATIBLE_GXX
+
+				Bit 5: On = Link Effect G's memory with Effect E/F. Also
+							Gxx with an instrument present will cause the
+							envelopes to be retriggered. If you change a
+							sample on a row with Gxx, it'll adjust the
+							frequency of the current note according to:
+
+							  NewFrequency = OldFrequency * NewC5 / OldC5;
+*/
+
+
+
+/* These #defines are TEMPORARY. They are used to write alternative code to
+ * handle ambiguities in the format specification. The correct code in each
+ * case will be determined most likely by experimentation.
+ */
+#define STEREO_SAMPLES_COUNT_AS_TWO
+#define INVALID_ORDERS_END_SONG
+#define INVALID_NOTES_CAUSE_NOTE_CUT
+#define SUSTAIN_LOOP_OVERRIDES_NORMAL_LOOP
+#define VOLUME_OUT_OF_RANGE_SETS_MAXIMUM
+
+
+
+#define SIGTYPE_IT DUMB_ID('I', 'T', ' ', ' ')
+
+#define IT_SIGNATURE            DUMB_ID('I', 'M', 'P', 'M')
+#define IT_INSTRUMENT_SIGNATURE DUMB_ID('I', 'M', 'P', 'I')
+#define IT_SAMPLE_SIGNATURE     DUMB_ID('I', 'M', 'P', 'S')
+
+
+
+ /* 1 minute per 4 rows, each row 6 ticks; this is divided by the tempo to get
+  * the interval between ticks.
+  */
+#define TICK_TIME_DIVIDEND ((65536 * 60) / (4 * 6))
+
+
+
+  /* I'm not going to try to explain this, because I didn't derive it very
+   * formally ;)
+   */
+   /* #define AMIGA_DIVISOR ((float)(4.0 * 14317056.0)) */
+   /* I believe the following one to be more accurate. */
+#define AMIGA_DIVISOR ((float)(8.0 * 7159090.5))
+
+
+
+typedef struct IT_MIDI IT_MIDI;
+typedef struct IT_FILTER_STATE IT_FILTER_STATE;
+typedef struct IT_ENVELOPE IT_ENVELOPE;
+typedef struct IT_INSTRUMENT IT_INSTRUMENT;
+typedef struct IT_SAMPLE IT_SAMPLE;
+typedef struct IT_ENTRY IT_ENTRY;
+typedef struct IT_PATTERN IT_PATTERN;
+typedef struct IT_PLAYING_ENVELOPE IT_PLAYING_ENVELOPE;
+typedef struct IT_PLAYING IT_PLAYING;
+typedef struct IT_CHANNEL IT_CHANNEL;
+typedef struct IT_CHECKPOINT IT_CHECKPOINT;
+typedef struct IT_CALLBACKS IT_CALLBACKS;
+
+
+
+struct IT_MIDI {
+	unsigned char SFmacro[16][16]; // read these from 0x120
+	unsigned char SFmacrolen[16];
+	unsigned short SFmacroz[16]; /* Bitfield; bit 0 set = z in first position */
+	unsigned char Zmacro[128][16]; // read these from 0x320
+	unsigned char Zmacrolen[128];
+};
+
+
+
+struct IT_FILTER_STATE {
+	float currsample, prevsample;
+};
+
+
+
+#define IT_ENVELOPE_ON                1
+#define IT_ENVELOPE_LOOP_ON           2
+#define IT_ENVELOPE_SUSTAIN_LOOP      4
+#define IT_ENVELOPE_PITCH_IS_FILTER 128
+
+struct IT_ENVELOPE {
+	unsigned char flags;
+	unsigned char n_nodes;
+	unsigned char loop_start;
+	unsigned char loop_end;
+	unsigned char sus_loop_start;
+	unsigned char sus_loop_end;
+	signed char node_y[25];
+	unsigned short node_t[25];
+};
+
+
+
+#define NNA_NOTE_CUT      0
+#define NNA_NOTE_CONTINUE 1
+#define NNA_NOTE_OFF      2
+#define NNA_NOTE_FADE     3
+
+#define DCT_OFF        0
+#define DCT_NOTE       1
+#define DCT_SAMPLE     2
+#define DCT_INSTRUMENT 3
+
+#define DCA_NOTE_CUT  0
+#define DCA_NOTE_OFF  1
+#define DCA_NOTE_FADE 2
+
+struct IT_INSTRUMENT {
+	int fadeout;
+
+	IT_ENVELOPE volume_envelope;
+	IT_ENVELOPE pan_envelope;
+	IT_ENVELOPE pitch_envelope;
+
+	unsigned char new_note_action;
+	unsigned char dup_check_type;
+	unsigned char dup_check_action;
+	unsigned char pp_separation;
+	unsigned char pp_centre;
+	unsigned char global_volume;
+	unsigned char default_pan;
+	unsigned char random_volume;
+	unsigned char random_pan;
+
+	unsigned char filter_cutoff;
+	unsigned char filter_resonance;
+
+	unsigned char map_note[120];
+	unsigned short map_sample[120];
+};
+
+
+
+#define IT_SAMPLE_EXISTS              1
+#define IT_SAMPLE_16BIT               2
+#define IT_SAMPLE_STEREO              4
+#define IT_SAMPLE_LOOP               16
+#define IT_SAMPLE_SUS_LOOP           32
+#define IT_SAMPLE_PINGPONG_LOOP      64
+#define IT_SAMPLE_PINGPONG_SUS_LOOP 128
+
+#define IT_VIBRATO_SINE     0
+#define IT_VIBRATO_SAWTOOTH 1 /* Ramp down */
+#define IT_VIBRATO_SQUARE   2
+#define IT_VIBRATO_RANDOM   3
+
+struct IT_SAMPLE {
+	unsigned char flags;
+	unsigned char global_volume;
+	unsigned char default_volume;
+	unsigned char default_pan;
+
+	long length;
+	long loop_start;
+	long loop_end;
+	long C5_speed;
+	long sus_loop_start;
+	long sus_loop_end;
+
+	unsigned char vibrato_speed;
+	unsigned char vibrato_depth;
+	unsigned char vibrato_rate;
+	unsigned char vibrato_waveform;
+
+	sample_t *left;
+	sample_t *right;
+};
+
+
+
+#define IT_ENTRY_NOTE       1
+#define IT_ENTRY_INSTRUMENT 2
+#define IT_ENTRY_VOLPAN     4
+#define IT_ENTRY_EFFECT     8
+
+#define IT_SET_END_ROW(entry) ((entry)->channel = 255)
+#define IT_IS_END_ROW(entry) ((entry)->channel >= DUMB_IT_N_CHANNELS)
+
+#define IT_NOTE_OFF 255
+#define IT_NOTE_CUT 254
+
+#define IT_ENVELOPE_SHIFT 8
+
+#define IT_SURROUND 100
+#define IT_IS_SURROUND(pan) ((pan) > 64)
+#define IT_IS_SURROUND_SHIFTED(pan) ((pan) > 64 << IT_ENVELOPE_SHIFT)
+
+#define IT_SET_SPEED              1
+#define IT_JUMP_TO_ORDER          2
+#define IT_BREAK_TO_ROW           3
+#define IT_VOLUME_SLIDE           4
+#define IT_PORTAMENTO_DOWN        5
+#define IT_PORTAMENTO_UP          6
+#define IT_TONE_PORTAMENTO        7
+#define IT_VIBRATO                8
+#define IT_TREMOR                 9
+#define IT_ARPEGGIO              10
+#define IT_VOLSLIDE_VIBRATO      11
+#define IT_VOLSLIDE_TONEPORTA    12
+#define IT_SET_CHANNEL_VOLUME    13
+#define IT_CHANNEL_VOLUME_SLIDE  14
+#define IT_SET_SAMPLE_OFFSET     15
+#define IT_PANNING_SLIDE         16
+#define IT_RETRIGGER_NOTE        17
+#define IT_TREMOLO               18
+#define IT_S                     19
+#define IT_SET_SONG_TEMPO        20
+#define IT_FINE_VIBRATO          21
+#define IT_SET_GLOBAL_VOLUME     22
+#define IT_GLOBAL_VOLUME_SLIDE   23
+#define IT_SET_PANNING           24
+#define IT_PANBRELLO             25
+#define IT_MIDI_MACRO            26 //see MIDI.TXT
+
+/* Some effects needed for XM compatibility */
+#define IT_XM_PORTAMENTO_DOWN    27
+#define IT_XM_PORTAMENTO_UP      28
+#define IT_XM_FINE_VOLSLIDE_DOWN 29
+#define IT_XM_FINE_VOLSLIDE_UP   30
+#define IT_XM_RETRIGGER_NOTE     31
+
+#define IT_N_EFFECTS             32
+
+/* These represent the top nibble of the command value. */
+#define IT_S_SET_FILTER              0 /* Greyed out in IT... */
+#define IT_S_SET_GLISSANDO_CONTROL   1 /* Greyed out in IT... */
+#define IT_S_FINETUNE                2 /* Greyed out in IT... */
+#define IT_S_SET_VIBRATO_WAVEFORM    3
+#define IT_S_SET_TREMOLO_WAVEFORM    4
+#define IT_S_SET_PANBRELLO_WAVEFORM  5
+#define IT_S_FINE_PATTERN_DELAY      6
+#define IT_S7                        7
+#define IT_S_SET_PAN                 8
+#define IT_S_SET_SURROUND_SOUND      9
+#define IT_S_SET_HIGH_OFFSET        10
+#define IT_S_PATTERN_LOOP           11
+#define IT_S_DELAYED_NOTE_CUT       12
+#define IT_S_NOTE_DELAY             13
+#define IT_S_PATTERN_DELAY          14
+#define IT_S_SET_MIDI_MACRO         15
+
+/*
+S0x Set filter
+S1x Set glissando control
+S2x Set finetune
+
+
+S3x Set vibrato waveform to type x
+S4x Set tremelo waveform to type x
+S5x Set panbrello waveform to type x
+  Waveforms for commands S3x, S4x and S5x:
+	0: Sine wave
+	1: Ramp down
+	2: Square wave
+	3: Random wave
+S6x Pattern delay for x ticks
+S70 Past note cut
+S71 Past note off
+S72 Past note fade
+S73 Set NNA to note cut
+S74 Set NNA to continue
+S75 Set NNA to note off
+S76 Set NNA to note fade
+S77 Turn off volume envelope
+S78 Turn on volume envelope
+S79 Turn off panning envelope
+S7A Turn on panning envelope
+S7B Turn off pitch envelope
+S7C Turn on pitch envelope
+S8x Set panning position
+S91 Set surround sound
+SAy Set high value of sample offset yxx00h
+SB0 Set loopback point
+SBx Loop x times to loopback point
+SCx Note cut after x ticks
+SDx Note delay for x ticks
+SEx Pattern delay for x rows
+SFx Set parameterised MIDI Macro
+*/
+
+struct IT_ENTRY {
+	unsigned char channel; /* End of row if channel >= DUMB_IT_N_CHANNELS */
+	unsigned char mask;
+	unsigned char note;
+	unsigned char instrument;
+	unsigned char volpan;
+	unsigned char effect;
+	unsigned char effectvalue;
+};
+
+
+
+struct IT_PATTERN {
+	int n_rows;
+	int n_entries;
+	IT_ENTRY *entry;
+};
+
+
+
+#define IT_STEREO            1
+#define IT_USE_INSTRUMENTS   4
+#define IT_LINEAR_SLIDES     8 /* If not set, use Amiga slides */
+#define IT_OLD_EFFECTS      16
+#define IT_COMPATIBLE_GXX   32
+
+/* Make sure IT_WAS_AN_XM and IT_WAS_A_MOD aren't set accidentally */
+#define IT_REAL_FLAGS       63
+
+#define IT_WAS_AN_XM        64 /* Set for both XMs and MODs */
+#define IT_WAS_A_MOD       128
+
+#define IT_ORDER_END  255
+#define IT_ORDER_SKIP 254
+
+struct DUMB_IT_SIGDATA {
+	int n_orders;
+	int n_instruments;
+	int n_samples;
+	int n_patterns;
+
+	int flags;
+
+	int global_volume;
+	int mixing_volume;
+	int speed;
+	int tempo;
+	int pan_separation;
+
+	unsigned char channel_pan[DUMB_IT_N_CHANNELS];
+	unsigned char channel_volume[DUMB_IT_N_CHANNELS];
+
+	unsigned char *order;
+	unsigned char restart_position; /* for XM compatiblity */
+
+	IT_INSTRUMENT *instrument;
+	IT_SAMPLE *sample;
+	IT_PATTERN *pattern;
+
+	IT_MIDI *midi;
+
+	IT_CHECKPOINT *checkpoint;
+};
+
+
+
+struct IT_PLAYING_ENVELOPE {
+	int next_node;
+	int tick;
+};
+
+
+
+#define IT_PLAYING_BACKGROUND 1
+#define IT_PLAYING_SUSTAINOFF 2
+#define IT_PLAYING_FADING     4
+#define IT_PLAYING_DEAD       8
+
+struct IT_PLAYING {
+	int flags;
+
+	IT_CHANNEL *channel;
+	IT_SAMPLE *sample;
+	IT_INSTRUMENT *instrument;
+	IT_INSTRUMENT *env_instrument;
+
+	unsigned short sampnum;
+	unsigned char instnum;
+
+	unsigned char channel_volume;
+
+	unsigned char volume;
+	unsigned short pan;
+
+	unsigned char note;
+
+	unsigned char filter_cutoff;
+	unsigned char filter_resonance;
+
+	unsigned short true_filter_cutoff;   /* These incorporate the filter envelope, and will not */
+	unsigned char true_filter_resonance; /* be changed if they would be set to 127<<8 and 0.    */
+
+	unsigned char vibrato_speed;
+	unsigned char vibrato_depth;
+	unsigned char vibrato_n; /* May be specified twice: volpan & effect. */
+	unsigned char vibrato_time;
+
+	unsigned char tremolo_speed;
+	unsigned char tremolo_depth;
+	unsigned char tremolo_time;
+
+	unsigned char sample_vibrato_time;
+	int sample_vibrato_depth; /* Starts at rate?0:depth, increases by rate */
+
+	int slide;
+	float delta;
+
+	IT_PLAYING_ENVELOPE volume_envelope;
+	IT_PLAYING_ENVELOPE pan_envelope;
+	IT_PLAYING_ENVELOPE pitch_envelope;
+
+	int fadeoutcount;
+
+	IT_FILTER_STATE filter_state[2]; /* Left and right */
+
+	DUMB_RESAMPLER resampler[2];
+
+	/* time_lost is used to emulate Impulse Tracker's sample looping
+	 * characteristics. When time_lost is added to pos, the result represents
+	 * the position in the theoretical version of the sample where all loops
+	 * have been expanded. If this is stored, the resampling helpers will
+	 * safely convert it for use with new loop boundaries. The situation is
+	 * slightly more complicated if dir == -1 when the change takes place; we
+	 * must reflect pos off the loop end point and set dir to 1 before
+	 * proceeding.
+	 */
+	long time_lost;
+};
+
+
+
+#define IT_CHANNEL_MUTED 1
+
+struct IT_CHANNEL {
+	int flags;
+
+	unsigned char volume;
+	signed char volslide;
+	signed char xm_volslide;
+
+	/* xm_volslide is used for volume slides done in the volume column in an
+	 * XM file, since it seems the volume column slide is applied first,
+	 * followed by clamping, followed by the effects column slide. IT does
+	 * not exhibit this behaviour, so xm_volslide is maintained at zero.
+	 */
+
+	unsigned char pan;
+	unsigned short truepan;
+
+	unsigned char channelvolume;
+	signed char channelvolslide;
+
+	unsigned char instrument;
+	unsigned char note;
+
+	unsigned char SFmacro;
+
+	unsigned char filter_cutoff;
+	unsigned char filter_resonance;
+
+	unsigned char note_cut_count;
+	unsigned char note_delay_count;
+	IT_ENTRY *note_delay_entry;
+
+	int arpeggio;
+	unsigned char retrig;
+	unsigned char xm_retrig;
+	int retrig_tick;
+
+	unsigned char tremor;
+	unsigned char tremor_time; /* Bit 6 set if note on; bit 7 set if tremor active. */
+
+	int portamento;
+	int toneporta;
+	unsigned char destnote;
+
+	/** WARNING - for neatness, should one or both of these be in the IT_PLAYING struct? */
+	unsigned short sample;
+	unsigned char truenote;
+
+	unsigned char midi_state;
+
+	signed char lastvolslide;
+	unsigned char lastDKL;
+	unsigned char lastEF; /* Doubles as last portamento up for XM files */
+	unsigned char lastG;
+	unsigned char lastHspeed;
+	unsigned char lastHdepth;
+	unsigned char lastRspeed;
+	unsigned char lastRdepth;
+	unsigned char lastI;
+	unsigned char lastJ; /* Doubles as last portamento down for XM files */
+	unsigned char lastN;
+	unsigned char lastO;
+	unsigned char high_offset;
+	unsigned char lastQ;
+	unsigned char lastS;
+	unsigned char pat_loop_row;
+	unsigned char pat_loop_count;
+	unsigned char lastW;
+
+	unsigned char xm_lastE1;
+	unsigned char xm_lastE2;
+	unsigned char xm_lastEA;
+	unsigned char xm_lastEB;
+	unsigned char xm_lastX1;
+	unsigned char xm_lastX2;
+
+	IT_PLAYING *playing;
+};
+
+
+
+struct DUMB_IT_SIGRENDERER {
+	DUMB_IT_SIGDATA *sigdata;
+
+	int n_channels;
+
+	unsigned char globalvolume;
+	signed char globalvolslide;
+
+	unsigned char tempo;
+	signed char temposlide;
+
+	IT_CHANNEL channel[DUMB_IT_N_CHANNELS];
+
+	IT_PLAYING *playing[DUMB_IT_N_NNA_CHANNELS];
+
+	int tick;
+	int speed;
+	int rowcount;
+
+	int order; /* Set to -1 if the song is terminated by a callback. */
+	int row;
+	int processorder;
+	int processrow;
+	int breakrow;
+	int pat_loop_row;
+
+	int n_rows;
+
+	IT_ENTRY *entry_start;
+	IT_ENTRY *entry;
+	IT_ENTRY *entry_end;
+
+	long time_left; /* Time before the next tick is processed */
+	int sub_time_left;
+
+	DUMB_CLICK_REMOVER **click_remover;
+
+	IT_CALLBACKS *callbacks;
+};
+
+
+
+struct IT_CHECKPOINT {
+	IT_CHECKPOINT *next;
+	long time;
+	DUMB_IT_SIGRENDERER *sigrenderer;
+};
+
+
+
+struct IT_CALLBACKS {
+	int (*loop)(void *data);
+	void *loop_data;
+	/* Return 1 to prevent looping; the music will terminate abruptly. If you
+	 * want to make the music stop but allow samples to fade (beware, as they
+	 * might not fade at all!), use dumb_it_sr_set_speed() and set the speed
+	 * to 0. Note that xm_speed_zero() will not be called if you set the
+	 * speed manually, and also that this will work for IT and S3M files even
+	 * though the music can't stop in this way by itself.
+	 */
+
+	int (*xm_speed_zero)(void *data);
+	void *xm_speed_zero_data;
+	/* Return 1 to terminate the mod, without letting samples fade. */
+
+	int (*midi)(void *data, int channel, unsigned char byte);
+	void *midi_data;
+	/* Return 1 to prevent DUMB from subsequently interpreting the MIDI bytes
+	 * itself. In other words, return 1 if the Zxx macros in an IT file are
+	 * controlling filters and shouldn't be.
+	 */
+};
+
+
+
+void _dumb_it_end_sigrenderer(sigrenderer_t *sigrenderer);
+void _dumb_it_unload_sigdata(sigdata_t *vsigdata);
+
+extern DUH_SIGTYPE_DESC _dumb_sigtype_it;
+
+
+
+long _dumb_it_build_checkpoints(DUMB_IT_SIGDATA *sigdata);
+
+
+
+#define XM_APPREGIO                0
+#define XM_PORTAMENTO_UP           1
+#define XM_PORTAMENTO_DOWN         2
+#define XM_TONE_PORTAMENTO         3
+#define XM_VIBRATO                 4
+#define XM_VOLSLIDE_TONEPORTA      5
+#define XM_VOLSLIDE_VIBRATO        6
+#define XM_TREMOLO                 7
+#define XM_SET_PANNING             8
+#define XM_SAMPLE_OFFSET           9
+#define XM_VOLUME_SLIDE            10 /* A */
+#define XM_POSITION_JUMP           11 /* B */
+#define XM_SET_CHANNEL_VOLUME      12 /* C */
+#define XM_PATTERN_BREAK           13 /* D */
+#define XM_E                       14 /* E */
+#define XM_SET_TEMPO_BPM           15 /* F */
+#define XM_SET_GLOBAL_VOLUME       16 /* G */
+#define XM_GLOBAL_VOLUME_SLIDE     17 /* H */
+#define XM_KEY_OFF                 20 /* K (undocumented) */
+#define XM_SET_ENVELOPE_POSITION   21 /* L */
+#define XM_PANNING_SLIDE           25 /* P */
+#define XM_MULTI_RETRIG            27 /* R */
+#define XM_TREMOR                  29 /* T */
+#define XM_X                       33 /* X */
+#define XM_N_EFFECTS               (10+26)
+
+#define XM_E_SET_FILTER            0x0
+#define XM_E_FINE_PORTA_UP         0x1
+#define XM_E_FINE_PORTA_DOWN       0x2
+#define XM_E_SET_GLISSANDO_CONTROL 0x3
+#define XM_E_SET_VIBRATO_CONTROL   0x4
+#define XM_E_SET_FINETUNE          0x5
+#define XM_E_SET_LOOP              0x6
+#define XM_E_SET_TREMOLO_CONTROL   0x7
+#define XM_E_RETRIG_NOTE           0x9
+#define XM_E_FINE_VOLSLIDE_UP      0xA
+#define XM_E_FINE_VOLSLIDE_DOWN    0xB
+#define XM_E_NOTE_CUT              0xC
+#define XM_E_NOTE_DELAY            0xD
+#define XM_E_PATTERN_DELAY         0xE
+
+#define XM_X_EXTRAFINE_PORTA_UP    1
+#define XM_X_EXTRAFINE_PORTA_DOWN  2
+
+/* To make my life a bit simpler during conversion, effect E:xy is converted
+ * to effect number EBASE+x:y. The same applies to effect X, and IT's S. That
+ * way, these effects can be manipulated like regular effects.
+ */
+#define EBASE              (XM_N_EFFECTS)
+#define XBASE              (EBASE+16)
+#define SBASE              (IT_N_EFFECTS)
+
+#define EFFECT_VALUE(x, y) (((x)<<4)|(y))
+#define HIGH(v)            ((v)>>4)
+#define LOW(v)             ((v)&0x0F)
+#define SET_HIGH(v, x)     v = (((x)<<4)|((v)&0x0F))
+#define SET_LOW(v, y)      v = (((v)&0xF0)|(y))
+#define BCD_TO_NORMAL(v)   (HIGH(v)*10+LOW(v))
+
+
+
+#if 0
+unsigned char **_dumb_malloc2(int w, int h);
+void _dumb_free2(unsigned char **line);
+#endif
+
+void _dumb_it_xm_convert_effect(int effect, int value, IT_ENTRY *entry);
+int _dumb_it_fix_invalid_orders(DUMB_IT_SIGDATA *sigdata);
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/lib/dumb-0.9.2/it/itmisc.cpp b/engines/ags/lib/dumb-0.9.2/it/itmisc.cpp
new file mode 100644
index 0000000000..2971366034
--- /dev/null
+++ b/engines/ags/lib/dumb-0.9.2/it/itmisc.cpp
@@ -0,0 +1,70 @@
+/* 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 "ags/lib/dumb-0.9.2/dumb.h"
+#include "common/textconsole.h"
+
+namespace AGS3 {
+
+DUMB_IT_SIGDATA *duh_get_it_sigdata(DUH *duh) {
+	warning("TODO: duh_get_it_sigdata");
+	return nullptr;
+}
+
+DUH_SIGRENDERER *duh_encapsulate_raw_sigrenderer(sigrenderer_t *vsigrenderer, DUH_SIGTYPE_DESC *desc, int n_channels, long pos) {
+	warning("TODO: duh_encapsulate_raw_sigrenderer");
+	return nullptr;
+}
+
+sigrenderer_t *duh_get_raw_sigrenderer(DUH_SIGRENDERER *sigrenderer, long type) {
+	warning("TODO: duh_get_raw_sigrenderer");
+	return nullptr;
+}
+
+void dumb_silence(sample_t *samples, long length) {
+	warning("TODO: dumb_silence");
+}
+
+long dumb_resample(DUMB_RESAMPLER *resampler, sample_t *dst, long dst_size, float volume, float delta) {
+	warning("TODO: dumb_resample");
+	return 0;
+}
+
+void dumb_reset_resampler(DUMB_RESAMPLER *resampler, sample_t *src, long pos, long start, long end) {
+	warning("TODO: dumb_reset_resampler");
+}
+
+sample_t dumb_resample_get_current_sample(DUMB_RESAMPLER *resampler, float volume) {
+	warning("TODO: dumb_resample_get_current_sample");
+	return (sample_t)0;
+}
+
+sample_t **create_sample_buffer(int n_channels, long length) {
+	warning("TODO: create_sample_buffer");
+	return nullptr;
+}
+
+void destroy_sample_buffer(sample_t **samples) {
+	warning("TODO: destroy_sample_buffer");
+}
+
+} // namespace AGS3
diff --git a/engines/ags/lib/dumb-0.9.2/it/itrender.cpp b/engines/ags/lib/dumb-0.9.2/it/itrender.cpp
new file mode 100644
index 0000000000..31be41914c
--- /dev/null
+++ b/engines/ags/lib/dumb-0.9.2/it/itrender.cpp
@@ -0,0 +1,3533 @@
+/* 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.
+ *
+ */
+
+/*  _______         ____    __         ___    ___
+ * \    _  \       \    /  \  /       \   \  /   /       '   '  '
+ *  |  | \  \       |  |    ||         |   \/   |         .      .
+ *  |  |  |  |      |  |    ||         ||\  /|  |
+ *  |  |  |  |      |  |    ||         || \/ |  |         '  '  '
+ *  |  |  |  |      |  |    ||         ||    |  |         .      .
+ *  |  |_/  /        \  \__//          ||    |  |
+ * /_______/ynamic    \____/niversal  /__\  /____\usic   /|  .  . ibliotheque
+ *                                                      /  \
+ *                                                     / .  \
+ * itrender.c - Code to render an Impulse Tracker     / / \  \
+ *              module.                              | <  /   \_
+ *                                                   |  \/ /\   /
+ * Written - painstakingly - by entheh.               \_  /  > /
+ *                                                      | \ / /
+ *                                                      |  ' /
+ *                                                       \__/
+ */
+
+#include "ags/lib/dumb-0.9.2/dumb.h"
+#include "ags/lib/dumb-0.9.2/it/it.h"
+
+namespace AGS3 {
+
+static IT_PLAYING *dup_playing(IT_PLAYING *src, IT_CHANNEL *dstchannel, IT_CHANNEL *srcchannel)
+{
+	IT_PLAYING *dst;
+
+	if (!src) return NULL;
+
+	dst = (IT_PLAYING *)malloc(sizeof(*dst));
+	if (!dst) return NULL;
+
+	dst->flags = src->flags;
+
+	ASSERT(src->channel);
+	dst->channel = &dstchannel[src->channel - srcchannel];
+	dst->sample = src->sample;
+	dst->instrument = src->instrument;
+	dst->env_instrument = src->env_instrument;
+
+	dst->sampnum = src->sampnum;
+	dst->instnum = src->instnum;
+
+	dst->channel_volume = src->channel_volume;
+
+	dst->volume = src->volume;
+	dst->pan = src->pan;
+
+	dst->note = src->note;
+
+	dst->filter_cutoff = src->filter_cutoff;
+	dst->filter_resonance = src->filter_resonance;
+
+	dst->true_filter_cutoff = src->true_filter_cutoff;
+	dst->true_filter_resonance = src->true_filter_resonance;
+
+	dst->vibrato_speed = src->vibrato_speed;
+	dst->vibrato_depth = src->vibrato_depth;
+	dst->vibrato_n = src->vibrato_n;
+	dst->vibrato_time = src->vibrato_time;
+
+	dst->tremolo_speed = src->tremolo_speed;
+	dst->tremolo_depth = src->tremolo_depth;
+	dst->tremolo_time = src->tremolo_time;
+
+	dst->sample_vibrato_time = src->sample_vibrato_time;
+	dst->sample_vibrato_depth = src->sample_vibrato_depth;
+
+	dst->slide = src->slide;
+	dst->delta = src->delta;
+
+	dst->volume_envelope = src->volume_envelope;
+	dst->pan_envelope = src->pan_envelope;
+	dst->pitch_envelope = src->pitch_envelope;
+
+	dst->fadeoutcount = src->fadeoutcount;
+
+	dst->filter_state[0] = src->filter_state[0];
+	dst->filter_state[1] = src->filter_state[1];
+
+	dst->resampler[0] = src->resampler[0];
+	dst->resampler[1] = src->resampler[1];
+	dst->resampler[1].pickup_data = dst->resampler[0].pickup_data = dst;
+	dst->time_lost = src->time_lost;
+
+	return dst;
+}
+
+
+
+static void dup_channel(IT_CHANNEL *dst, IT_CHANNEL *src)
+{
+	dst->flags = src->flags;
+
+	dst->volume = src->volume;
+	dst->volslide = src->volslide;
+	dst->xm_volslide = src->xm_volslide;
+
+	dst->pan = src->pan;
+	dst->truepan = src->truepan;
+
+	dst->channelvolume = src->channelvolume;
+	dst->channelvolslide = src->channelvolslide;
+
+	dst->instrument = src->instrument;
+	dst->note = src->note;
+
+	dst->SFmacro = src->SFmacro;
+
+	dst->filter_cutoff = src->filter_cutoff;
+	dst->filter_resonance = src->filter_resonance;
+
+	dst->note_cut_count = src->note_cut_count;
+	dst->note_delay_count = src->note_delay_count;
+	dst->note_delay_entry = src->note_delay_entry;
+
+	dst->arpeggio = src->arpeggio;
+	dst->retrig = src->retrig;
+	dst->xm_retrig = src->xm_retrig;
+	dst->retrig_tick = src->retrig_tick;
+
+	dst->tremor_time = src->tremor_time;
+
+	dst->portamento = src->portamento;
+	dst->toneporta = src->toneporta;
+	dst->destnote = src->destnote;
+
+	dst->sample = src->sample;
+	dst->truenote = src->truenote;
+
+	dst->midi_state = src->midi_state;
+
+	dst->lastvolslide = src->lastvolslide;
+	dst->lastDKL = src->lastDKL;
+	dst->lastEF = src->lastEF;
+	dst->lastG = src->lastG;
+	dst->lastHspeed = src->lastHspeed;
+	dst->lastHdepth = src->lastHdepth;
+	dst->lastRspeed = src->lastRspeed;
+	dst->lastRdepth = src->lastRdepth;
+	dst->lastI = src->lastI;
+	dst->lastJ = src->lastJ;
+	dst->lastN = src->lastN;
+	dst->lastO = src->lastO;
+	dst->high_offset = src->high_offset;
+	dst->lastQ = src->lastQ;
+	dst->lastS = src->lastS;
+	dst->pat_loop_row = src->pat_loop_row;
+	dst->pat_loop_count = src->pat_loop_count;
+	dst->lastW = src->lastW;
+
+	dst->xm_lastE1 = src->xm_lastE1;
+	dst->xm_lastE2 = src->xm_lastE2;
+	dst->xm_lastEA = src->xm_lastEA;
+	dst->xm_lastEB = src->xm_lastEB;
+	dst->xm_lastX1 = src->xm_lastX1;
+	dst->xm_lastX2 = src->xm_lastX2;
+
+	dst->playing = dup_playing(src->playing, dst, src);
+}
+
+
+
+/* Allocate the new callbacks first, then pass them to this function!
+ * It will free them on failure.
+ */
+static DUMB_IT_SIGRENDERER *dup_sigrenderer(DUMB_IT_SIGRENDERER *src, int n_channels, IT_CALLBACKS *callbacks)
+{
+	DUMB_IT_SIGRENDERER *dst;
+	int i;
+
+	if (!src) {
+		if (callbacks) free(callbacks);
+		return NULL;
+	}
+
+	dst = (DUMB_IT_SIGRENDERER *)malloc(sizeof(*dst));
+	if (!dst) {
+		if (callbacks) free(callbacks);
+		return NULL;
+	}
+
+	dst->sigdata = src->sigdata;
+
+	dst->n_channels = n_channels;
+
+	dst->globalvolume = src->globalvolume;
+	dst->globalvolslide = src->globalvolslide;
+
+	dst->tempo = src->tempo;
+	dst->temposlide = src->temposlide;
+
+	for (i = 0; i < DUMB_IT_N_CHANNELS; i++)
+		dup_channel(&dst->channel[i], &src->channel[i]);
+
+	for (i = 0; i < DUMB_IT_N_NNA_CHANNELS; i++)
+		dst->playing[i] = dup_playing(src->playing[i], dst->channel, src->channel);
+
+	dst->tick = src->tick;
+	dst->speed = src->speed;
+	dst->rowcount = src->rowcount;
+
+	dst->order = src->order;
+	dst->row = src->row;
+	dst->processorder = src->processorder;
+	dst->processrow = src->processrow;
+	dst->breakrow = src->breakrow;
+	dst->pat_loop_row = src->pat_loop_row;
+
+	dst->n_rows = src->n_rows;
+
+	dst->entry_start = src->entry_start;
+	dst->entry = src->entry;
+	dst->entry_end = src->entry_end;
+
+	dst->time_left = src->time_left;
+	dst->sub_time_left = src->sub_time_left;
+
+	dst->click_remover = NULL;
+
+	dst->callbacks = callbacks;
+
+	return dst;
+}
+
+
+
+static IT_MIDI default_midi = {
+	/* unsigned char SFmacro[16][16]; */
+	{
+		{0xF0, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
+	},
+	/* unsigned char SFmacrolen[16]; */
+	{4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+	/* unsigned short SFmacroz[16]; */
+	/* Bitfield; bit 0 set = z in first position */
+	{
+		0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+		0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000
+	},
+	/* unsigned char Zmacro[128][16]; */
+	{
+		{0xF0, 0xF0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0xF0, 0xF0, 0x01, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0xF0, 0xF0, 0x01, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0xF0, 0xF0, 0x01, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0xF0, 0xF0, 0x01, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0xF0, 0xF0, 0x01, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0xF0, 0xF0, 0x01, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0xF0, 0xF0, 0x01, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0xF0, 0xF0, 0x01, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0xF0, 0xF0, 0x01, 0x48, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0xF0, 0xF0, 0x01, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0xF0, 0xF0, 0x01, 0x58, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0xF0, 0xF0, 0x01, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0xF0, 0xF0, 0x01, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0xF0, 0xF0, 0x01, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0xF0, 0xF0, 0x01, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
+	},
+	/* unsigned char Zmacrolen[128]; */
+	{
+		4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
+		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+	}
+};
+
+
+
+static void it_reset_filter_state(IT_FILTER_STATE *state)
+{
+	state->currsample = 0;
+	state->prevsample = 0;
+}
+
+
+
+#define LOG10 2.30258509299
+
+/* IMPORTANT: This function expects one extra sample in 'src' so it can apply
+ * click removal. It reads size samples, starting from src[0], and writes its
+ * output starting at dst[pos]. The pos parameter is required for getting
+ * click removal right.
+ */
+static void it_filter(DUMB_CLICK_REMOVER *cr, IT_FILTER_STATE *state, sample_t *dst, long pos, sample_t *src, long size, int sampfreq, int cutoff, int resonance)
+{
+	float currsample = state->currsample;
+	float prevsample = state->prevsample;
+
+	float a, b, c;
+
+	{
+		float inv_angle = (float)(sampfreq * pow(0.5, 0.25 + cutoff*(1.0/(24<<IT_ENVELOPE_SHIFT))) * (1.0/(2*3.14159265358979323846*110.0)));
+		float loss = (float)exp(resonance*(-LOG10*1.2/128.0));
+		float d, e;
+#if 0
+		loss *= 2; // This is the mistake most players seem to make!
+#endif
+
+#if 1
+		d = (1.0f - loss) / inv_angle;
+		if (d > 2.0f) d = 2.0f;
+		d = (loss - d) * inv_angle;
+		e = inv_angle * inv_angle;
+		a = 1.0f / (1.0f + d + e);
+		c = -e * a;
+		b = 1.0f - a - c;
+#else
+		a = 1.0f / (inv_angle*inv_angle + inv_angle*loss + loss);
+		c = -(inv_angle*inv_angle) * a;
+		b = 1.0f - a - c;
+#endif
+	}
+
+	dst += pos;
+
+	if (cr) {
+		float startstep = src[0]*a + currsample*b + prevsample*c;
+		dumb_record_click(cr, pos, (sample_t)startstep);
+	}
+
+#define INT_FILTERS
+#ifdef INT_FILTERS
+#define MULSCA(a, b) ((int)((LONG_LONG)((a) << 4) * (b) >> 32))
+#define SCALEB 12
+	{
+		int ai = (int)(a * (1 << (16+SCALEB)));
+		int bi = (int)(b * (1 << (16+SCALEB)));
+		int ci = (int)(c * (1 << (16+SCALEB)));
+		sample_t csi = (sample_t)currsample;
+		sample_t psi = (sample_t)prevsample;
+		sample_t *dst_end = dst + size;
+		while (dst < dst_end) {
+			{
+				sample_t nsi = MULSCA(*src++, ai) + MULSCA(csi, bi) + MULSCA(psi, ci);
+				psi = csi;
+				csi = nsi;
+			}
+			*dst++ += csi;
+		}
+		currsample = csi;
+		prevsample = psi;
+	}
+#else
+	{
+		int i = size % 3;
+		while (i > 0) {
+			{
+				float newsample = *src++*a + currsample*b + prevsample*c;
+				prevsample = currsample;
+				currsample = newsample;
+			}
+			*dst++ += (sample_t)currsample;
+			i--;
+		}
+		i = size / 3;
+		while (i > 0) {
+			float newsample;
+			/* Gotta love unrolled loops! */
+			*dst++ += (sample_t)(newsample = *src++*a + currsample*b + prevsample*c);
+			*dst++ += (sample_t)(prevsample = *src++*a + newsample*b + currsample*c);
+			*dst++ += (sample_t)(currsample = *src++*a + prevsample*b + newsample*c);
+			i--;
+		}
+	}
+#endif
+
+	if (cr) {
+		float endstep = *src*a + currsample*b + prevsample*c;
+		dumb_record_click(cr, pos + size, -(sample_t)endstep);
+	}
+
+	state->currsample = currsample;
+	state->prevsample = prevsample;
+}
+
+#undef LOG10
+
+
+
+static signed char it_sine[256] = {
+	  0,  2,  3,  5,  6,  8,  9, 11, 12, 14, 16, 17, 19, 20, 22, 23,
+	 24, 26, 27, 29, 30, 32, 33, 34, 36, 37, 38, 39, 41, 42, 43, 44,
+	 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 56, 57, 58, 59,
+	 59, 60, 60, 61, 61, 62, 62, 62, 63, 63, 63, 64, 64, 64, 64, 64,
+	 64, 64, 64, 64, 64, 64, 63, 63, 63, 62, 62, 62, 61, 61, 60, 60,
+	 59, 59, 58, 57, 56, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46,
+	 45, 44, 43, 42, 41, 39, 38, 37, 36, 34, 33, 32, 30, 29, 27, 26,
+	 24, 23, 22, 20, 19, 17, 16, 14, 12, 11,  9,  8,  6,  5,  3,  2,
+	  0, -2, -3, -5, -6, -8, -9,-11,-12,-14,-16,-17,-19,-20,-22,-23,
+	-24,-26,-27,-29,-30,-32,-33,-34,-36,-37,-38,-39,-41,-42,-43,-44,
+	-45,-46,-47,-48,-49,-50,-51,-52,-53,-54,-55,-56,-56,-57,-58,-59,
+	-59,-60,-60,-61,-61,-62,-62,-62,-63,-63,-63,-64,-64,-64,-64,-64,
+	-64,-64,-64,-64,-64,-64,-63,-63,-63,-62,-62,-62,-61,-61,-60,-60,
+	-59,-59,-58,-57,-56,-56,-55,-54,-53,-52,-51,-50,-49,-48,-47,-46,
+	-45,-44,-43,-42,-41,-39,-38,-37,-36,-34,-33,-32,-30,-29,-27,-26,
+	-24,-23,-22,-20,-19,-17,-16,-14,-12,-11, -9, -8, -6, -5, -3, -2
+};
+
+
+
+#if 0
+/** WARNING: use these! */
+/** JULIEN: Plus for XM compatibility it could be interesting to rename
+ * it_sawtooth[] to it_rampdown[], and add an it_rampup[].
+ * Also, still for XM compat', twood be good if it was possible to tell the
+ * the player not to retrig' the waveform on a new instrument.
+ * Both of these are only for completness though, as I don't think it would
+ * be very noticeable ;)
+ */
+/** ENTHEH: IT also has the 'don't retrig' thingy :) */
+
+static signed char it_sawtooth[256] = {
+	 64, 63, 63, 62, 62, 61, 61, 60, 60, 59, 59, 58, 58, 57, 57, 56,
+	 56, 55, 55, 54, 54, 53, 53, 52, 52, 51, 51, 50, 50, 49, 49, 48,
+	 48, 47, 47, 46, 46, 45, 45, 44, 44, 43, 43, 42, 42, 41, 41, 40,
+	 40, 39, 39, 38, 38, 37, 37, 36, 36, 35, 35, 34, 34, 33, 33, 32,
+	 32, 31, 31, 30, 30, 29, 29, 28, 28, 27, 27, 26, 26, 25, 25, 24,
+	 24, 23, 23, 22, 22, 21, 21, 20, 20, 19, 19, 18, 18, 17, 17, 16,
+	 16, 15, 15, 14, 14, 13, 13, 12, 12, 11, 11, 10, 10,  9,  9,  8,
+	  8,  7,  7,  6,  6,  5,  5,  4,  4,  3,  3,  2,  2,  1,  1,  0,
+	  0, -1, -1, -2, -2, -3, -3, -4, -4, -5, -5, -6, -6, -7, -7, -8,
+	 -8, -9, -9,-10,-10,-11,-11,-12,-12,-13,-13,-14,-14,-15,-15,-16,
+	-16,-17,-17,-18,-18,-19,-19,-20,-20,-21,-21,-22,-22,-23,-23,-24,
+	-24,-25,-25,-26,-26,-27,-27,-28,-28,-29,-29,-30,-30,-31,-31,-32,
+	-32,-33,-33,-34,-34,-35,-35,-36,-36,-37,-37,-38,-38,-39,-39,-40,
+	-40,-41,-41,-42,-42,-43,-43,-44,-44,-45,-45,-46,-46,-47,-47,-48,
+	-48,-49,-49,-50,-50,-51,-51,-52,-52,-53,-53,-54,-54,-55,-55,-56,
+	-56,-57,-57,-58,-58,-59,-59,-60,-60,-61,-61,-62,-62,-63,-63,-64
+};
+
+
+
+static signed char it_squarewave[256] = {
+	 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
+	 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
+	 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
+	 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
+	 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
+	 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
+	 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
+	 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
+	  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+	  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+	  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+	  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+	  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+	  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+	  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+	  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0
+};
+
+#endif
+
+
+
+static void reset_tick_counts(DUMB_IT_SIGRENDERER *sigrenderer)
+{
+	int i;
+
+	for (i = 0; i < DUMB_IT_N_CHANNELS; i++) {
+		IT_CHANNEL *channel = &sigrenderer->channel[i];
+		channel->note_cut_count = 0;
+		channel->note_delay_count = 0;
+	}
+}
+
+
+
+static void reset_effects(DUMB_IT_SIGRENDERER *sigrenderer)
+{
+	int i;
+
+	sigrenderer->globalvolslide = 0;
+	sigrenderer->temposlide = 0;
+
+	for (i = 0; i < DUMB_IT_N_CHANNELS; i++) {
+		IT_CHANNEL *channel = &sigrenderer->channel[i];
+		channel->volslide = 0;
+		channel->xm_volslide = 0;
+		channel->channelvolslide = 0;
+		channel->arpeggio = 0;
+		channel->retrig = 0;
+		if (channel->xm_retrig) {
+			channel->xm_retrig = 0;
+			channel->retrig_tick = 0;
+		}
+		channel->tremor_time &= 127;
+		channel->portamento = 0;
+		channel->toneporta = 0;
+		if (channel->playing) {
+			channel->playing->vibrato_n = 0;
+			channel->playing->tremolo_speed = 0;
+			channel->playing->tremolo_depth = 0;
+		}
+	}
+}
+
+
+
+static void update_tremor(IT_CHANNEL *channel)
+{
+	if ((channel->tremor_time & 128) && channel->playing) {
+		if (channel->tremor_time == 128)
+			channel->tremor_time = (channel->lastI >> 4) | 192;
+		else if (channel->tremor_time == 192)
+			channel->tremor_time = (channel->lastI & 15) | 128;
+		else
+			channel->tremor_time--;
+	}
+}
+
+
+
+static void it_pickup_loop(DUMB_RESAMPLER *resampler, void *data)
+{
+	resampler->pos -= resampler->end - resampler->start;
+	((IT_PLAYING *)data)->time_lost += resampler->end - resampler->start;
+}
+
+
+
+static void it_pickup_pingpong_loop(DUMB_RESAMPLER *resampler, void *data)
+{
+	if (resampler->dir < 0) {
+		resampler->pos = (resampler->start << 1) - 1 - resampler->pos;
+		resampler->subpos ^= 65535;
+		resampler->dir = 1;
+		((IT_PLAYING *)data)->time_lost += (resampler->end - resampler->start) << 1;
+	} else {
+		resampler->pos = (resampler->end << 1) - 1 - resampler->pos;
+		resampler->subpos ^= 65535;
+		resampler->dir = -1;
+	}
+}
+
+
+
+static void it_pickup_stop_at_end(DUMB_RESAMPLER *resampler, void *data)
+{
+	(void)data;
+
+	if (resampler->dir < 0) {
+		resampler->pos = (resampler->start << 1) - 1 - resampler->pos;
+		resampler->subpos ^= 65535;
+		/* By rights, time_lost would be updated here. However, there is no
+		 * need at this point; it will not be used.
+		 *
+		 * ((IT_PLAYING *)data)->time_lost += (resampler->src_end - resampler->src_start) << 1;
+		 */
+		resampler->dir = 1;
+	} else
+		resampler->dir = 0;
+}
+
+
+
+static void it_playing_update_resamplers(IT_PLAYING *playing)
+{
+	if ((playing->sample->flags & IT_SAMPLE_SUS_LOOP) && !(playing->flags & IT_PLAYING_SUSTAINOFF)) {
+		playing->resampler[0].start = playing->sample->sus_loop_start;
+		playing->resampler[0].end = playing->sample->sus_loop_end;
+		if (playing->sample->flags & IT_SAMPLE_PINGPONG_SUS_LOOP)
+			playing->resampler[0].pickup = &it_pickup_pingpong_loop;
+		else
+			playing->resampler[0].pickup = &it_pickup_loop;
+	} else if (playing->sample->flags & IT_SAMPLE_LOOP) {
+		playing->resampler[0].start = playing->sample->loop_start;
+		playing->resampler[0].end = playing->sample->loop_end;
+		if (playing->sample->flags & IT_SAMPLE_PINGPONG_LOOP)
+			playing->resampler[0].pickup = &it_pickup_pingpong_loop;
+		else
+			playing->resampler[0].pickup = &it_pickup_loop;
+	} else {
+		if (playing->sample->flags & IT_SAMPLE_SUS_LOOP)
+			playing->resampler[0].start = playing->sample->sus_loop_start;
+		else
+			playing->resampler[0].start = 0;
+		playing->resampler[0].end = playing->sample->length;
+		playing->resampler[0].pickup = &it_pickup_stop_at_end;
+	}
+	playing->resampler[1].start = playing->resampler[0].start;
+	playing->resampler[1].end = playing->resampler[0].end;
+	playing->resampler[1].pickup = playing->resampler[0].pickup;
+	ASSERT(playing->resampler[0].pickup_data == playing);
+	ASSERT(playing->resampler[1].pickup_data == playing);
+}
+
+
+
+/* This should be called whenever the sample or sample position changes. */
+static void it_playing_reset_resamplers(IT_PLAYING *playing, long pos)
+{
+	dumb_reset_resampler(&playing->resampler[0], playing->sample->left, pos, 0, 0);
+	dumb_reset_resampler(&playing->resampler[1], playing->sample->right, pos, 0, 0);
+	playing->resampler[1].pickup_data = playing->resampler[0].pickup_data = playing;
+	playing->time_lost = 0;
+	playing->flags &= ~IT_PLAYING_DEAD;
+	it_playing_update_resamplers(playing);
+}
+
+
+
+static void update_retrig(IT_CHANNEL *channel)
+{
+	if (channel->xm_retrig) {
+		channel->retrig_tick--;
+		if (channel->retrig_tick <= 0) {
+			if (channel->playing) it_playing_reset_resamplers(channel->playing, 0);
+			channel->retrig_tick = channel->xm_retrig;
+		}
+	} else if (channel->retrig & 0x0F) {
+		channel->retrig_tick--;
+		if (channel->retrig_tick <= 0) {
+			if (channel->retrig < 0x10) {
+			} else if (channel->retrig < 0x20) {
+				channel->volume--;
+				if (channel->volume > 64) channel->volume = 0;
+			} else if (channel->retrig < 0x30) {
+				channel->volume -= 2;
+				if (channel->volume > 64) channel->volume = 0;
+			} else if (channel->retrig < 0x40) {
+				channel->volume -= 4;
+				if (channel->volume > 64) channel->volume = 0;
+			} else if (channel->retrig < 0x50) {
+				channel->volume -= 8;
+				if (channel->volume > 64) channel->volume = 0;
+			} else if (channel->retrig < 0x60) {
+				channel->volume -= 16;
+				if (channel->volume > 64) channel->volume = 0;
+			} else if (channel->retrig < 0x70) {
+				channel->volume <<= 1;
+				channel->volume /= 3;
+			} else if (channel->retrig < 0x80) {
+				channel->volume >>= 1;
+			} else if (channel->retrig < 0x90) {
+			} else if (channel->retrig < 0xA0) {
+				channel->volume++;
+				if (channel->volume > 64) channel->volume = 64;
+			} else if (channel->retrig < 0xB0) {
+				channel->volume += 2;
+				if (channel->volume > 64) channel->volume = 64;
+			} else if (channel->retrig < 0xC0) {
+				channel->volume += 4;
+				if (channel->volume > 64) channel->volume = 64;
+			} else if (channel->retrig < 0xD0) {
+				channel->volume += 8;
+				if (channel->volume > 64) channel->volume = 64;
+			} else if (channel->retrig < 0xE0) {
+				channel->volume += 16;
+				if (channel->volume > 64) channel->volume = 64;
+			} else if (channel->retrig < 0xF0) {
+				channel->volume *= 3;
+				channel->volume >>= 1;
+				if (channel->volume > 64) channel->volume = 64;
+			} else {
+				channel->volume <<= 1;
+				if (channel->volume > 64) channel->volume = 64;
+			}
+			if (channel->playing) it_playing_reset_resamplers(channel->playing, 0);
+			channel->retrig_tick = channel->retrig & 0x0F;
+		}
+	}
+}
+
+
+
+static void update_smooth_effects(DUMB_IT_SIGRENDERER *sigrenderer)
+{
+	int i;
+
+	for (i = 0; i < DUMB_IT_N_CHANNELS; i++) {
+		IT_CHANNEL *channel = &sigrenderer->channel[i];
+		IT_PLAYING *playing = channel->playing;
+
+		if (playing) {
+			playing->vibrato_time += playing->vibrato_n *
+			                         (playing->vibrato_speed << 2);
+			playing->tremolo_time += playing->tremolo_speed << 2;
+		}
+	}
+}
+
+
+
+static void update_effects(DUMB_IT_SIGRENDERER *sigrenderer)
+{
+	int i;
+
+	if (sigrenderer->globalvolslide) {
+		sigrenderer->globalvolume += sigrenderer->globalvolslide;
+		if (sigrenderer->globalvolume > 128) {
+			if (sigrenderer->globalvolslide >= 0)
+				sigrenderer->globalvolume = 128;
+			else
+				sigrenderer->globalvolume = 0;
+		}
+	}
+
+	if (sigrenderer->temposlide) {
+		sigrenderer->tempo += sigrenderer->temposlide;
+		if (sigrenderer->tempo < 32) {
+			if (sigrenderer->temposlide >= 0)
+				sigrenderer->tempo = 255;
+			else
+				sigrenderer->tempo = 32;
+		}
+	}
+
+	for (i = 0; i < DUMB_IT_N_CHANNELS; i++) {
+		IT_CHANNEL *channel = &sigrenderer->channel[i];
+		IT_PLAYING *playing = channel->playing;
+
+		if (channel->xm_volslide) {
+			channel->volume += channel->xm_volslide;
+			if (channel->volume > 64) {
+				if (channel->xm_volslide >= 0)
+					channel->volume = 64;
+				else
+					channel->volume = 0;
+			}
+		}
+
+		if (channel->volslide) {
+			channel->volume += channel->volslide;
+			if (channel->volume > 64) {
+				if (channel->volslide >= 0)
+					channel->volume = 64;
+				else
+					channel->volume = 0;
+			}
+		}
+
+		if (channel->channelvolslide) {
+			channel->channelvolume += channel->channelvolslide;
+			if (channel->channelvolume > 64) {
+				if (channel->channelvolslide >= 0)
+					channel->channelvolume = 64;
+				else
+					channel->channelvolume = 0;
+			}
+			if (channel->playing)
+				channel->playing->channel_volume = channel->channelvolume;
+		}
+
+		update_tremor(channel);
+
+		channel->arpeggio = (channel->arpeggio << 4) | (channel->arpeggio >> 8);
+		channel->arpeggio &= 0xFFF;
+
+		update_retrig(channel);
+
+		if (playing) {
+			playing->slide += channel->portamento;
+
+			if (sigrenderer->sigdata->flags & IT_LINEAR_SLIDES) {
+				if (channel->toneporta && channel->destnote < 120) {
+					int currpitch = ((playing->note - 60) << 8) + playing->slide;
+					int destpitch = (channel->destnote - 60) << 8;
+					if (currpitch > destpitch) {
+						currpitch -= channel->toneporta;
+						if (currpitch < destpitch) {
+							currpitch = destpitch;
+							channel->destnote = IT_NOTE_OFF;
+						}
+					} else if (currpitch < destpitch) {
+						currpitch += channel->toneporta;
+						if (currpitch > destpitch) {
+							currpitch = destpitch;
+							channel->destnote = IT_NOTE_OFF;
+						}
+					}
+					playing->slide = currpitch - ((playing->note - 60) << 8);
+				}
+			} else {
+				if (channel->toneporta && channel->destnote < 120) {
+					float amiga_multiplier = playing->sample->C5_speed * (1.0f / AMIGA_DIVISOR);
+
+					float deltanote = (float)pow(DUMB_SEMITONE_BASE, 60 - playing->note);
+					/* deltanote is 1.0 for C-5, 0.5 for C-6, etc. */
+
+					float deltaslid = deltanote - playing->slide * amiga_multiplier;
+
+					float destdelta = (float)pow(DUMB_SEMITONE_BASE, 60 - channel->destnote);
+					if (deltaslid < destdelta) {
+						playing->slide -= channel->toneporta;
+						deltaslid = deltanote - playing->slide * amiga_multiplier;
+						if (deltaslid > destdelta) {
+							playing->note = channel->destnote;
+							playing->slide = 0;
+							channel->destnote = IT_NOTE_OFF;
+						}
+					} else {
+						playing->slide += channel->toneporta;
+						deltaslid = deltanote - playing->slide * amiga_multiplier;
+						if (deltaslid < destdelta) {
+							playing->note = channel->destnote;
+							playing->slide = 0;
+							channel->destnote = IT_NOTE_OFF;
+						}
+					}
+				}
+			}
+		}
+	}
+
+	update_smooth_effects(sigrenderer);
+}
+
+
+
+static void update_pattern_variables(DUMB_IT_SIGRENDERER *sigrenderer, IT_ENTRY *entry)
+{
+	IT_CHANNEL *channel = &sigrenderer->channel[(int)entry->channel];
+
+	if (entry->mask & IT_ENTRY_EFFECT) {
+		if (entry->effect == IT_S) {
+			unsigned char effectvalue = entry->effectvalue;
+			if (effectvalue == 0)
+				effectvalue = channel->lastS;
+			channel->lastS = effectvalue;
+			switch (effectvalue >> 4) {
+				//case IT_S7:
+				case IT_S_PATTERN_LOOP:
+					{
+						unsigned char v = effectvalue & 15;
+						if (v == 0)
+							channel->pat_loop_row = sigrenderer->processrow;
+						else {
+							if (channel->pat_loop_count == 0) {
+								channel->pat_loop_count = v;
+								sigrenderer->pat_loop_row = channel->pat_loop_row;
+							} else {
+								if (--channel->pat_loop_count)
+									sigrenderer->pat_loop_row = channel->pat_loop_row;
+								else if (!(sigrenderer->sigdata->flags & IT_WAS_AN_XM))
+									channel->pat_loop_row = sigrenderer->processrow + 1;
+							}
+						}
+					}
+					break;
+				case IT_S_PATTERN_DELAY:
+					sigrenderer->rowcount = 1 + (effectvalue & 15);
+					break;
+			}
+		}
+	}
+}
+
+
+
+/* This function guarantees that channel->sample will always be valid if it
+ * is nonzero. In other words, to check if it is valid, simply check if it is
+ * nonzero.
+ */
+static void instrument_to_sample(DUMB_IT_SIGDATA *sigdata, IT_CHANNEL *channel)
+{
+	if (sigdata->flags & IT_USE_INSTRUMENTS) {
+		if (channel->instrument >= 1 && channel->instrument <= sigdata->n_instruments) {
+			if (channel->note < 120) {
+				channel->sample = sigdata->instrument[channel->instrument-1].map_sample[channel->note];
+				channel->truenote = sigdata->instrument[channel->instrument-1].map_note[channel->note];
+			} else
+				channel->sample = 0;
+		} else
+			channel->sample = 0;
+	} else {
+		channel->sample = channel->instrument;
+		channel->truenote = channel->note;
+	}
+	if (!(channel->sample >= 1 && channel->sample <= sigdata->n_samples && (sigdata->sample[channel->sample-1].flags & IT_SAMPLE_EXISTS)))
+		channel->sample = 0;
+}
+
+
+
+static void fix_sample_looping(IT_PLAYING *playing)
+{
+	if ((playing->sample->flags & (IT_SAMPLE_LOOP | IT_SAMPLE_SUS_LOOP)) ==
+	                              (IT_SAMPLE_LOOP | IT_SAMPLE_SUS_LOOP)) {
+		if (playing->resampler[0].dir < 0) {
+			playing->resampler[1].pos = playing->resampler[0].pos = (playing->sample->sus_loop_end << 1) - 1 - playing->resampler[0].pos;
+			playing->resampler[1].subpos = playing->resampler[0].subpos ^= 65535;
+			playing->resampler[1].dir = playing->resampler[0].dir = 1;
+		}
+
+		playing->resampler[1].pos = playing->resampler[0].pos += playing->time_lost;
+	}
+}
+
+
+
+static void retrigger_it_envelopes(DUMB_IT_SIGDATA *sigdata, IT_CHANNEL *channel)
+{
+	channel->playing->volume_envelope.next_node = 0;
+	channel->playing->volume_envelope.tick = -1;
+	channel->playing->pan_envelope.next_node = 0;
+	channel->playing->pan_envelope.tick = -1;
+	channel->playing->pitch_envelope.next_node = 0;
+	channel->playing->pitch_envelope.tick = -1;
+	channel->playing->fadeoutcount = 1024;
+	// Should we remove IT_PLAYING_BACKGROUND? Test with sample with sustain loop...
+	channel->playing->flags &= ~(IT_PLAYING_BACKGROUND | IT_PLAYING_SUSTAINOFF | IT_PLAYING_FADING | IT_PLAYING_DEAD);
+	it_playing_update_resamplers(channel->playing);
+
+	if (channel->sample)
+		if (sigdata->flags & IT_USE_INSTRUMENTS)
+			channel->playing->env_instrument = &sigdata->instrument[channel->instrument-1];
+}
+
+
+
+static void it_retrigger_note(DUMB_IT_SIGRENDERER *sigrenderer, IT_CHANNEL *channel)
+{
+	DUMB_IT_SIGDATA *sigdata = sigrenderer->sigdata;
+	unsigned char nna;
+	int i;
+
+	if (channel->playing) {
+#ifdef INVALID_NOTES_CAUSE_NOTE_CUT
+		if (channel->note == IT_NOTE_OFF)
+			nna = NNA_NOTE_OFF;
+		else if (channel->note >= 120 || !channel->playing->instrument || (channel->playing->flags & IT_PLAYING_DEAD))
+			nna = NNA_NOTE_CUT;
+		else
+			nna = channel->playing->instrument->new_note_action;
+#else
+		if (channel->note == IT_NOTE_CUT)
+			nna = NNA_NOTE_CUT;
+		if (channel->note >= 120)
+			nna = NNA_NOTE_OFF;
+		else if (!channel->playing->instrument || (channel->playing->flags & IT_PLAYING_DEAD))
+			nna = NNA_NOTE_CUT;
+		else
+			nna = channel->playing->instrument->new_note_action;
+#endif
+
+		switch (nna) {
+			case NNA_NOTE_CUT:
+				free(channel->playing);
+				channel->playing = NULL;
+				break;
+			case NNA_NOTE_OFF:
+				channel->playing->flags |= IT_PLAYING_BACKGROUND | IT_PLAYING_SUSTAINOFF;
+				fix_sample_looping(channel->playing);
+				it_playing_update_resamplers(channel->playing);
+				if (channel->playing->instrument)
+					if ((channel->playing->instrument->volume_envelope.flags & (IT_ENVELOPE_ON | IT_ENVELOPE_LOOP_ON)) != IT_ENVELOPE_ON)
+						channel->playing->flags |= IT_PLAYING_FADING;
+				break;
+			case NNA_NOTE_FADE:
+				channel->playing->flags |= IT_PLAYING_BACKGROUND | IT_PLAYING_FADING;
+				break;
+		}
+	}
+
+	if (channel->sample == 0 || channel->note >= 120)
+		return;
+
+	channel->destnote = IT_NOTE_OFF;
+
+	if (channel->playing) {
+		for (i = 0; i < DUMB_IT_N_NNA_CHANNELS; i++) {
+			if (!sigrenderer->playing[i]) {
+				sigrenderer->playing[i] = channel->playing;
+				channel->playing = NULL;
+				break;
+			}
+		}
+/** WARNING - come up with some more heuristics for replacing old notes */
+#if 0
+		if (channel->playing) {
+			for (i = 0; i < DUMB_IT_N_NNA_CHANNELS; i++) {
+				if (sigrenderer->playing[i]->flags & IT_PLAYING_BACKGROUND) {
+					write_seqtime();
+					sequence_c(SEQUENCE_STOP_SIGNAL);
+					sequence_c(i);
+					channel->VChannel = &module->VChannel[i];
+					break;
+				}
+			}
+		}
+#endif
+	}
+
+	if (channel->playing)
+		free(channel->playing);
+
+	channel->playing = (IT_PLAYING *)malloc(sizeof(*channel->playing));
+
+	if (!channel->playing)
+		return;
+
+	channel->playing->flags = 0;
+	channel->playing->channel = channel;
+	channel->playing->sample = &sigdata->sample[channel->sample-1];
+	if (sigdata->flags & IT_USE_INSTRUMENTS)
+		channel->playing->instrument = &sigdata->instrument[channel->instrument-1];
+	else
+		channel->playing->instrument = NULL;
+	channel->playing->env_instrument = channel->playing->instrument;
+	channel->playing->sampnum = channel->sample;
+	channel->playing->instnum = channel->instrument;
+	channel->playing->channel_volume = channel->channelvolume;
+	channel->playing->note = channel->truenote;
+	channel->playing->filter_cutoff = 127;
+	channel->playing->filter_resonance = 0;
+	channel->playing->true_filter_cutoff = 127 << 8;
+	channel->playing->true_filter_resonance = 0;
+	channel->playing->vibrato_speed = 0;
+	channel->playing->vibrato_depth = 0;
+	channel->playing->vibrato_n = 0;
+	channel->playing->vibrato_time = 0;
+	channel->playing->tremolo_speed = 0;
+	channel->playing->tremolo_depth = 0;
+	channel->playing->tremolo_time = 0;
+	channel->playing->sample_vibrato_time = 0;
+	channel->playing->sample_vibrato_depth = 0;
+	channel->playing->slide = 0;
+	channel->playing->volume_envelope.next_node = 0;
+	channel->playing->volume_envelope.tick = -1;
+	channel->playing->pan_envelope.next_node = 0;
+	channel->playing->pan_envelope.tick = -1;
+	channel->playing->pitch_envelope.next_node = 0;
+	channel->playing->pitch_envelope.tick = -1;
+	channel->playing->fadeoutcount = 1024;
+	it_reset_filter_state(&channel->playing->filter_state[0]);
+	it_reset_filter_state(&channel->playing->filter_state[1]);
+	it_playing_reset_resamplers(channel->playing, 0);
+
+	/** WARNING - is everything initialised? */
+}
+
+
+
+static void get_default_volpan(DUMB_IT_SIGDATA *sigdata, IT_CHANNEL *channel)
+{
+	if (channel->sample == 0)
+		return;
+
+	channel->volume = sigdata->sample[channel->sample-1].default_volume;
+
+	{
+		int pan = sigdata->sample[channel->sample-1].default_pan;
+		if (pan >= 128 && pan <= 192) {
+			channel->pan = pan - 128;
+			return;
+		}
+	}
+
+	if (sigdata->flags & IT_USE_INSTRUMENTS) {
+		IT_INSTRUMENT *instrument = &sigdata->instrument[channel->instrument-1];
+		if (instrument->default_pan <= 64)
+			channel->pan = instrument->default_pan;
+		if (instrument->filter_cutoff >= 128)
+			channel->filter_cutoff = instrument->filter_cutoff - 128;
+		if (instrument->filter_resonance >= 128)
+			channel->filter_resonance = instrument->filter_resonance - 128;
+	}
+}
+
+
+
+static void get_true_pan(DUMB_IT_SIGDATA *sigdata, IT_CHANNEL *channel)
+{
+	channel->truepan = channel->pan << IT_ENVELOPE_SHIFT;
+
+	if (!IT_IS_SURROUND_SHIFTED(channel->truepan) && (sigdata->flags & IT_USE_INSTRUMENTS)) {
+		IT_INSTRUMENT *instrument = &sigdata->instrument[channel->instrument-1];
+		int truepan = channel->truepan;
+		truepan += (channel->note - instrument->pp_centre) * instrument->pp_separation << (IT_ENVELOPE_SHIFT - 3);
+		channel->truepan = MID(0, truepan, 64 << IT_ENVELOPE_SHIFT);
+	}
+}
+
+
+
+static void post_process_it_volpan(DUMB_IT_SIGRENDERER *sigrenderer, IT_ENTRY *entry)
+{
+	IT_CHANNEL *channel = &sigrenderer->channel[(int)entry->channel];
+
+	if (entry->mask & IT_ENTRY_VOLPAN) {
+		if (entry->volpan <= 84) {
+			/* Volume */
+			/* Fine volume slide up */
+			/* Fine volume slide down */
+		} else if (entry->volpan <= 94) {
+			/* Volume slide up */
+			unsigned char v = entry->volpan - 85;
+			if (v == 0)
+				v = channel->lastvolslide;
+			channel->lastvolslide = v;
+			/* = effect Dx0 where x == entry->volpan - 85 */
+			channel->volslide = v;
+		} else if (entry->volpan <= 104) {
+			/* Volume slide down */
+			unsigned char v = entry->volpan - 95;
+			if (v == 0)
+				v = channel->lastvolslide;
+			channel->lastvolslide = v;
+			/* = effect D0x where x == entry->volpan - 95 */
+			channel->volslide = -v;
+		} else if (entry->volpan <= 114) {
+			/* Portamento down */
+			unsigned char v = (entry->volpan - 105) << 2;
+			if (v == 0)
+				v = channel->lastEF;
+			channel->lastEF = v;
+			channel->portamento -= v << 4;
+		} else if (entry->volpan <= 124) {
+			/* Portamento up */
+			unsigned char v = (entry->volpan - 115) << 2;
+			if (v == 0)
+				v = channel->lastEF;
+			channel->lastEF = v;
+			channel->portamento += v << 4;
+		} else if (entry->volpan <= 202) {
+			/* Pan */
+			/* Tone Portamento */
+		} else if (entry->volpan <= 212) {
+			/* Vibrato */
+			unsigned char v = entry->volpan - 203;
+			if (v == 0)
+				v = channel->lastHdepth;
+			else {
+				v <<= 2;
+				channel->lastHdepth = v;
+			}
+			if (channel->playing) {
+				channel->playing->vibrato_speed = channel->lastHspeed;
+				channel->playing->vibrato_depth = v;
+				channel->playing->vibrato_n++;
+			}
+		}
+	}
+}
+
+
+
+static void it_send_midi(DUMB_IT_SIGRENDERER *sigrenderer, IT_CHANNEL *channel, unsigned char byte)
+{
+	if (sigrenderer->callbacks->midi)
+		if ((*sigrenderer->callbacks->midi)(sigrenderer->callbacks->midi_data, channel - sigrenderer->channel, byte))
+			return;
+
+	switch (channel->midi_state) {
+		case 4: /* Ready to receive resonance parameter */
+			if (byte < 0x80) channel->filter_resonance = byte;
+			channel->midi_state = 0;
+			break;
+		case 3: /* Ready to receive cutoff parameter */
+			if (byte < 0x80) channel->filter_cutoff = byte;
+			channel->midi_state = 0;
+			break;
+		case 2: /* Ready for byte specifying which parameter will follow */
+			if (byte == 0) /* Cutoff */
+				channel->midi_state = 3;
+			else if (byte == 1) /* Resonance */
+				channel->midi_state = 4;
+			else
+				channel->midi_state = 0;
+			break;
+		default: /* Counting initial F0 bytes */
+			switch (byte) {
+				case 0xF0:
+					channel->midi_state++;
+					break;
+				case 0xFA:
+				case 0xFC:
+				case 0xFF:
+					/* Reset filter parameters for all channels */
+					{
+						int i;
+						for (i = 0; i < DUMB_IT_N_CHANNELS; i++) {
+							sigrenderer->channel[i].filter_cutoff = 127;
+							sigrenderer->channel[i].filter_resonance = 0;
+							//// should we be resetting channel[i].playing->filter_* here?
+						}
+					}
+					/* Fall through */
+				default:
+					channel->midi_state = 0;
+					break;
+			}
+	}
+}
+
+
+
+/* Returns 1 if a callback caused termination of playback. */
+static int process_effects(DUMB_IT_SIGRENDERER *sigrenderer, IT_ENTRY *entry)
+{
+	DUMB_IT_SIGDATA *sigdata = sigrenderer->sigdata;
+
+	IT_CHANNEL *channel = &sigrenderer->channel[(int)entry->channel];
+
+	if (entry->mask & IT_ENTRY_EFFECT) {
+		switch (entry->effect) {
+/*
+Notes about effects (as compared to other module formats)
+
+C               This is now in *HEX*. (Used to be in decimal in ST3)
+E/F/G/H/U       You need to check whether the song uses Amiga/Linear slides.
+H/U             Vibrato in Impulse Tracker is two times finer than in
+                any other tracker and is updated EVERY tick.
+                If "Old Effects" is *ON*, then the vibrato is played in the
+                normal manner (every non-row tick and normal depth)
+E/F/G           These commands ALL share the same memory.
+Oxx             Offsets to samples are to the 'xx00th' SAMPLE. (ie. for
+                16 bit samples, the offset is xx00h*2)
+                Oxx past the sample end will be ignored, unless "Old Effects"
+                is ON, in which case the Oxx will play from the end of the
+                sample.
+Yxy             This uses a table 4 times larger (hence 4 times slower) than
+                vibrato or tremelo. If the waveform is set to random, then
+                the 'speed' part of the command is interpreted as a delay.
+*/
+			case IT_SET_SPEED:
+				if (entry->effectvalue)
+					sigrenderer->tick = sigrenderer->speed = entry->effectvalue;
+				else if (sigdata->flags & IT_WAS_AN_XM) {
+					sigrenderer->speed = 0;
+					if (sigrenderer->callbacks->xm_speed_zero && (*sigrenderer->callbacks->xm_speed_zero)(sigrenderer->callbacks->xm_speed_zero_data))
+						return 1;
+				}
+				break;
+
+			case IT_JUMP_TO_ORDER: sigrenderer->processorder = entry->effectvalue - 1; sigrenderer->processrow = 0xFFFE; break;
+			case IT_BREAK_TO_ROW: sigrenderer->breakrow = entry->effectvalue; sigrenderer->processrow = 0xFFFE; break;
+
+			case IT_VOLSLIDE_VIBRATO:
+				if (channel->playing) {
+					channel->playing->vibrato_speed = channel->lastHspeed;
+					channel->playing->vibrato_depth = channel->lastHdepth;
+					channel->playing->vibrato_n++;
+				}
+				/* Fall through and process volume slide. */
+			case IT_VOLUME_SLIDE:
+			case IT_VOLSLIDE_TONEPORTA:
+				/* The tone portamento component is handled elsewhere. */
+				{
+					unsigned char v = entry->effectvalue;
+					if (!(sigdata->flags & IT_WAS_A_MOD)) {
+						if (v == 0)
+							v = channel->lastDKL;
+						channel->lastDKL = v;
+					}
+					if ((v & 0x0F) == 0) { /* Dx0 */
+						channel->volslide = v >> 4;
+						if (channel->volslide == 15 && !(sigdata->flags & IT_WAS_AN_XM)) {
+							channel->volume += 15;
+							if (channel->volume > 64) channel->volume = 64;
+						}
+					} else if ((v & 0xF0) == 0) { /* D0x */
+						channel->volslide = -v;
+						if (channel->volslide == -15 && !(sigdata->flags & IT_WAS_AN_XM)) {
+							channel->volume -= 15;
+							if (channel->volume > 64) channel->volume = 0;
+						}
+					} else if ((v & 0x0F) == 0x0F) { /* DxF */
+						channel->volume += v >> 4;
+						if (channel->volume > 64) channel->volume = 64;
+					} else if ((v & 0xF0) == 0xF0) { /* DFx */
+						channel->volume -= v & 15;
+						if (channel->volume > 64) channel->volume = 0;
+					}
+				}
+				break;
+			case IT_XM_FINE_VOLSLIDE_DOWN:
+				{
+					unsigned char v = entry->effectvalue;
+					if (v == 0)
+						v = channel->xm_lastEB;
+					channel->xm_lastEB = v;
+					channel->volume -= v;
+					if (channel->volume > 64) channel->volume = 0;
+				}
+				break;
+			case IT_XM_FINE_VOLSLIDE_UP:
+				{
+					unsigned char v = entry->effectvalue;
+					if (v == 0)
+						v = channel->xm_lastEA;
+					channel->xm_lastEA = v;
+					channel->volume += v;
+					if (channel->volume > 64) channel->volume = 64;
+				}
+				break;
+			case IT_PORTAMENTO_DOWN:
+				{
+					unsigned char v = entry->effectvalue;
+					if (sigdata->flags & IT_WAS_AN_XM) {
+						if (!(sigdata->flags & IT_WAS_A_MOD)) {
+							if (v == 0xF0)
+								v |= channel->xm_lastE2;
+							else if (v >= 0xF0)
+								channel->xm_lastE2 = v & 15;
+							else if (v == 0xE0)
+								v |= channel->xm_lastX2;
+							else
+								channel->xm_lastX2 = v & 15;
+						}
+					} else {
+						if (v == 0)
+							v = channel->lastEF;
+						channel->lastEF = v;
+					}
+					if (channel->playing) {
+						if ((v & 0xF0) == 0xF0)
+							channel->playing->slide -= (v & 15) << 4;
+						else if ((v & 0xF0) == 0xE0)
+							channel->playing->slide -= (v & 15) << 2;
+						else
+							channel->portamento -= v << 4;
+					}
+				}
+				break;
+			case IT_PORTAMENTO_UP:
+				{
+					unsigned char v = entry->effectvalue;
+					if (sigdata->flags & IT_WAS_AN_XM) {
+						if (!(sigdata->flags & IT_WAS_A_MOD)) {
+							if (v == 0xF0)
+								v |= channel->xm_lastE1;
+							else if (v >= 0xF0)
+								channel->xm_lastE1 = v & 15;
+							else if (v == 0xE0)
+								v |= channel->xm_lastX1;
+							else
+								channel->xm_lastX1 = v & 15;
+						}
+					} else {
+						if (v == 0)
+							v = channel->lastEF;
+						channel->lastEF = v;
+					}
+					if (channel->playing) {
+						if ((v & 0xF0) == 0xF0)
+							channel->playing->slide += (v & 15) << 4;
+						else if ((v & 0xF0) == 0xE0)
+							channel->playing->slide += (v & 15) << 2;
+						else
+							channel->portamento += v << 4;
+					}
+				}
+				break;
+			case IT_XM_PORTAMENTO_DOWN:
+				{
+					unsigned char v = entry->effectvalue;
+					if (!(sigdata->flags & IT_WAS_A_MOD)) {
+						if (v == 0)
+							v = channel->lastJ;
+						channel->lastJ = v;
+					}
+					if (channel->playing)
+						channel->portamento -= v << 4;
+				}
+				break;
+			case IT_XM_PORTAMENTO_UP:
+				{
+					unsigned char v = entry->effectvalue;
+					if (!(sigdata->flags & IT_WAS_A_MOD)) {
+						if (v == 0)
+							v = channel->lastEF;
+						channel->lastEF = v;
+					}
+					if (channel->playing)
+						channel->portamento += v << 4;
+				}
+				break;
+			case IT_VIBRATO:
+				{
+					unsigned char speed = entry->effectvalue >> 4;
+					unsigned char depth = entry->effectvalue & 15;
+					if (speed == 0)
+						speed = channel->lastHspeed;
+					channel->lastHspeed = speed;
+					if (depth == 0)
+						depth = channel->lastHdepth;
+					else {
+						if (sigdata->flags & IT_OLD_EFFECTS)
+							depth <<= 3;
+						else
+							depth <<= 2;
+						channel->lastHdepth = depth;
+					}
+					if (channel->playing) {
+						channel->playing->vibrato_speed = speed;
+						channel->playing->vibrato_depth = depth;
+						channel->playing->vibrato_n++;
+					}
+				}
+				break;
+			case IT_TREMOR:
+				{
+					unsigned char v = entry->effectvalue;
+					if (v == 0)
+						v = channel->lastI;
+					else if (!(sigdata->flags & IT_OLD_EFFECTS)) {
+						if (v & 0xF0) v -= 0x10;
+						if (v & 0x0F) v -= 0x01;
+					}
+					channel->lastI = v;
+					channel->tremor_time |= 128;
+				}
+				update_tremor(channel);
+				break;
+			case IT_ARPEGGIO:
+				{
+					unsigned char v = entry->effectvalue;
+					/* XM files have no memory for arpeggio (000 = no effect)
+					 * and we use lastJ for portamento down instead.
+					 */
+					if (!(sigdata->flags & IT_WAS_AN_XM)) {
+						if (v == 0)
+							v = channel->lastJ;
+						channel->lastJ = v;
+					}
+					channel->arpeggio = v;
+				}
+				break;
+			case IT_SET_CHANNEL_VOLUME:
+				if (sigdata->flags & IT_WAS_AN_XM)
+					channel->volume = MIN(entry->effectvalue, 64);
+				else if (entry->effectvalue <= 64)
+					channel->channelvolume = entry->effectvalue;
+#ifdef VOLUME_OUT_OF_RANGE_SETS_MAXIMUM
+				else
+					channel->channelvolume = 64;
+#endif
+				if (channel->playing)
+					channel->playing->channel_volume = channel->channelvolume;
+				break;
+			case IT_CHANNEL_VOLUME_SLIDE:
+				{
+					unsigned char v = entry->effectvalue;
+					if (v == 0)
+						v = channel->lastN;
+					channel->lastN = v;
+					if ((v & 0x0F) == 0) { /* Nx0 */
+						channel->channelvolslide = v >> 4;
+					} else if ((v & 0xF0) == 0) { /* N0x */
+						channel->channelvolslide = -v;
+					} else {
+						if ((v & 0x0F) == 0x0F) { /* NxF */
+							channel->channelvolume += v >> 4;
+							if (channel->channelvolume > 64) channel->channelvolume = 64;
+						} else if ((v & 0xF0) == 0xF0) { /* NFx */
+							channel->channelvolume -= v & 15;
+							if (channel->channelvolume > 64) channel->channelvolume = 0;
+						} else
+							break;
+						if (channel->playing)
+							channel->playing->channel_volume = channel->channelvolume;
+					}
+				}
+				break;
+			case IT_SET_SAMPLE_OFFSET:
+				{
+					unsigned char v = entry->effectvalue;
+					if (sigdata->flags & IT_WAS_A_MOD) {
+						if (v == 0) break;
+					} else {
+						if (v == 0)
+							v = channel->lastO;
+						channel->lastO = v;
+					}
+					/* Note: we set the offset even if tone portamento is
+					 * specified. Impulse Tracker does the same.
+					 */
+					if (entry->mask & IT_ENTRY_NOTE) {
+						if (channel->playing) {
+							int offset = ((int)channel->high_offset << 16) | ((int)v << 8);
+							IT_PLAYING *playing = channel->playing;
+							IT_SAMPLE *sample = playing->sample;
+							int end;
+							if ((sample->flags & IT_SAMPLE_SUS_LOOP) && !(playing->flags & IT_PLAYING_SUSTAINOFF))
+								end = sample->sus_loop_end;
+							else if (sample->flags & IT_SAMPLE_LOOP)
+								end = sample->loop_end;
+							else
+								end = sample->length;
+							if (offset < end)
+								it_playing_reset_resamplers(playing, offset);
+							else if (sigdata->flags & IT_OLD_EFFECTS)
+								it_playing_reset_resamplers(playing, end);
+						}
+					}
+				}
+				break;
+			//case IT_PANNING_SLIDE:
+				/** JULIEN: guess what? the docs are wrong! (how unusual ;)
+				 * Pxy seems to memorize its previous value... and there
+				 * might be other mistakes like that... (sigh!)
+				 */
+				/** ENTHEH: umm... but... the docs say that Pxy memorises its
+				 * value... don't they? :o
+				 */
+			case IT_RETRIGGER_NOTE:
+				{
+					unsigned char v = entry->effectvalue;
+					if (sigdata->flags & IT_WAS_AN_XM) {
+						if ((v & 0x0F) == 0) v |= channel->lastQ & 0x0F;
+						if ((v & 0xF0) == 0) v |= channel->lastQ & 0xF0;
+					} else {
+						if (v == 0)
+							v = channel->lastQ;
+					}
+					channel->lastQ = v;
+					if ((v & 0x0F) == 0) v |= 0x01;
+					channel->retrig = v;
+					if (entry->mask & IT_ENTRY_NOTE) {
+						channel->retrig_tick = v & 0x0F;
+						/* Emulate a bug */
+						if (sigdata->flags & IT_WAS_AN_XM)
+							update_retrig(channel);
+					} else
+						update_retrig(channel);
+				}
+				break;
+			case IT_XM_RETRIGGER_NOTE:
+				channel->retrig_tick = channel->xm_retrig = entry->effectvalue;
+				if (entry->effectvalue == 0)
+					if (channel->playing) it_playing_reset_resamplers(channel->playing, 0);
+				break;
+			case IT_TREMOLO:
+				{
+					unsigned char speed = entry->effectvalue >> 4;
+					unsigned char depth = entry->effectvalue & 15;
+					if (speed == 0)
+						speed = channel->lastRspeed;
+					channel->lastRspeed = speed;
+					if (depth == 0)
+						depth = channel->lastRdepth;
+					channel->lastRdepth = depth;
+					if (channel->playing) {
+						channel->playing->tremolo_speed = speed;
+						channel->playing->tremolo_depth = depth;
+					}
+				}
+				break;
+			case IT_S:
+				{
+					/* channel->lastS was set in update_pattern_variables(). */
+					unsigned char effectvalue = channel->lastS;
+					switch (effectvalue >> 4) {
+						//case IT_S_SET_FILTER:
+						//case IT_S_SET_GLISSANDO_CONTROL:
+						//case IT_S_FINETUNE:
+						//case IT_S_SET_VIBRATO_WAVEFORM:
+						//case IT_S_SET_TREMOLO_WAVEFORM:
+						//case IT_S_SET_PANBRELLO_WAVEFORM:
+							/* Waveforms for commands S3x, S4x and S5x:
+							 *   0: Sine wave
+							 *   1: Ramp down
+							 *   2: Square wave
+							 *   3: Random wave
+							 */
+						case IT_S_FINE_PATTERN_DELAY:
+							sigrenderer->tick += effectvalue & 15;
+							break;
+						//case IT_S7:
+						case IT_S_SET_PAN:
+							channel->pan =
+								((effectvalue & 15) << 2) |
+								((effectvalue & 15) >> 2);
+							channel->truepan = channel->pan << IT_ENVELOPE_SHIFT;
+							break;
+						case IT_S_SET_SURROUND_SOUND:
+							if ((effectvalue & 15) == 1)
+								channel->pan = IT_SURROUND;
+								channel->truepan = channel->pan << IT_ENVELOPE_SHIFT;
+							break;
+						case IT_S_SET_HIGH_OFFSET:
+							channel->high_offset = effectvalue & 15;
+							break;
+						//case IT_S_PATTERN_LOOP:
+						case IT_S_DELAYED_NOTE_CUT:
+							channel->note_cut_count = effectvalue & 15;
+							if (!channel->note_cut_count) {
+								if (sigdata->flags & IT_WAS_AN_XM)
+									channel->volume = 0;
+								else
+									channel->note_cut_count = 1;
+							}
+							break;
+						case IT_S_SET_MIDI_MACRO:
+							channel->SFmacro = effectvalue & 15;
+							break;
+					}
+				}
+				break;
+			case IT_SET_SONG_TEMPO:
+				{
+					unsigned char v = entry->effectvalue;
+					if (v == 0)
+						v = channel->lastW;
+					channel->lastW = v;
+					if (v < 0x10)
+						sigrenderer->temposlide = -v;
+					else if (v < 0x20)
+						sigrenderer->temposlide = v & 15;
+					else
+						sigrenderer->tempo = v;
+				}
+				break;
+			case IT_FINE_VIBRATO:
+				{
+					unsigned char speed = entry->effectvalue >> 4;
+					unsigned char depth = entry->effectvalue & 15;
+					if (speed == 0)
+						speed = channel->lastHspeed;
+					channel->lastHspeed = speed;
+					if (depth == 0)
+						depth = channel->lastHdepth;
+					else {
+						if (sigdata->flags & IT_OLD_EFFECTS)
+							depth <<= 1;
+						channel->lastHdepth = depth;
+					}
+					if (channel->playing) {
+						channel->playing->vibrato_speed = speed;
+						channel->playing->vibrato_depth = depth;
+						channel->playing->vibrato_n++;
+					}
+				}
+				break;
+			case IT_SET_GLOBAL_VOLUME:
+				if (entry->effectvalue <= 128)
+					sigrenderer->globalvolume = entry->effectvalue;
+#ifdef VOLUME_OUT_OF_RANGE_SETS_MAXIMUM
+				else
+					sigrenderer->globalvolume = 128;
+#endif
+				break;
+			case IT_GLOBAL_VOLUME_SLIDE:
+				{
+					unsigned char v = entry->effectvalue;
+					if (v == 0)
+						v = channel->lastW;
+					channel->lastW = v;
+					if ((v & 0x0F) == 0) { /* Wx0 */
+						sigrenderer->globalvolslide =
+							(sigdata->flags & IT_WAS_AN_XM) ? (v >> 4)*2 : (v >> 4);
+					} else if ((v & 0xF0) == 0) { /* W0x */
+						sigrenderer->globalvolslide =
+							(sigdata->flags & IT_WAS_AN_XM) ? (-v)*2 : (-v);
+					} else if ((v & 0x0F) == 0x0F) { /* WxF */
+						sigrenderer->globalvolume += v >> 4;
+						if (sigrenderer->globalvolume > 128) sigrenderer->globalvolume = 128;
+					} else if ((v & 0xF0) == 0xF0) { /* WFx */
+						sigrenderer->globalvolume -= v & 15;
+						if (sigrenderer->globalvolume > 128) sigrenderer->globalvolume = 0;
+					}
+				}
+				break;
+			case IT_SET_PANNING:
+				channel->pan = (entry->effectvalue + 2) >> 2;
+				channel->truepan = channel->pan << IT_ENVELOPE_SHIFT;
+				break;
+			//case IT_PANBRELLO:
+			case IT_MIDI_MACRO:
+				{
+					IT_MIDI *midi = sigdata->midi ? sigdata->midi : &default_midi;
+					if (entry->effectvalue >= 0x80) {
+						int n = midi->Zmacrolen[entry->effectvalue-0x80];
+						int i;
+						for (i = 0; i < n; i++)
+							it_send_midi(sigrenderer, channel, midi->Zmacro[entry->effectvalue-0x80][i]);
+					} else {
+						int n = midi->SFmacrolen[channel->SFmacro];
+						int i, j;
+						for (i = 0, j = 1; i < n; i++, j <<= 1)
+							it_send_midi(sigrenderer, channel,
+								midi->SFmacroz[channel->SFmacro] & j ?
+									entry->effectvalue : midi->SFmacro[channel->SFmacro][i]);
+					}
+				}
+				break;
+		}
+	}
+
+	if (!(sigdata->flags & IT_WAS_AN_XM))
+		post_process_it_volpan(sigrenderer, entry);
+
+	return 0;
+}
+
+
+
+static int process_it_note_data(DUMB_IT_SIGRENDERER *sigrenderer, IT_ENTRY *entry)
+{
+	DUMB_IT_SIGDATA *sigdata = sigrenderer->sigdata;
+	IT_CHANNEL *channel = &sigrenderer->channel[(int)entry->channel];
+
+	// When tone portamento and instrument are specified:
+	// If Gxx is off:
+	//   - same sample, do nothing but portamento
+	//   - diff sample, retrigger all but keep current note+slide + do porta
+	//   - if instrument is invalid, nothing; if sample is invalid, cut
+	// If Gxx is on:
+	//   - same sample or new sample invalid, retrigger envelopes
+	//   - diff sample/inst, start using new envelopes
+	// When tone portamento is specified alone, sample won't change.
+	// TODO: consider what happens with instrument alone after all this...
+
+	if (entry->mask & (IT_ENTRY_NOTE | IT_ENTRY_INSTRUMENT)) {
+		if (entry->mask & IT_ENTRY_INSTRUMENT)
+			channel->instrument = entry->instrument;
+		instrument_to_sample(sigdata, channel);
+		if (channel->note < 120) {
+			if ((sigdata->flags & IT_USE_INSTRUMENTS) && channel->sample == 0)
+				return 1;
+			if (entry->mask & IT_ENTRY_INSTRUMENT)
+				get_default_volpan(sigdata, channel);
+		} else
+			it_retrigger_note(sigrenderer, channel);
+	}
+
+	/** WARNING: This is not ideal, since channel->playing might not get allocated owing to lack of memory... */
+	if (channel->playing &&
+	   (((entry->mask & IT_ENTRY_VOLPAN) && entry->volpan >= 193 && entry->volpan <= 202) ||
+	    ((entry->mask & IT_ENTRY_EFFECT) && (entry->effect == IT_TONE_PORTAMENTO || entry->effect == IT_VOLSLIDE_TONEPORTA))))
+	{
+		if (entry->mask & IT_ENTRY_INSTRUMENT) {
+			if (sigdata->flags & IT_COMPATIBLE_GXX)
+				retrigger_it_envelopes(sigdata, channel);
+			else if ((!(sigdata->flags & IT_USE_INSTRUMENTS) ||
+				(channel->instrument >= 1 && channel->instrument <= sigdata->n_instruments)) &&
+				channel->sample != channel->playing->sampnum)
+			{
+				unsigned char note = channel->playing->note;
+				int slide = channel->playing->slide;
+				it_retrigger_note(sigrenderer, channel);
+				if (channel->playing) {
+					channel->playing->note = note;
+					channel->playing->slide = slide;
+					// Should we be preserving sample_vibrato_time? depth?
+				}
+			}
+		}
+
+		if ((entry->mask & IT_ENTRY_VOLPAN) && entry->volpan >= 193 && entry->volpan <= 202) {
+			/* Tone Portamento in the volume column */
+			static const unsigned char slidetable[] = {0, 1, 4, 8, 16, 32, 64, 96, 128, 255};
+			unsigned char v = slidetable[entry->volpan - 193];
+			if (sigdata->flags & IT_COMPATIBLE_GXX) {
+				if (v == 0)
+					v = channel->lastG;
+				channel->lastG = v;
+			} else {
+				if (v == 0)
+					v = channel->lastEF;
+				channel->lastEF = v;
+			}
+			if (entry->mask & IT_ENTRY_NOTE)
+				if (channel->sample)
+					channel->destnote = channel->truenote;
+			channel->toneporta = v << 4;
+		} else {
+			/* Tone Portamento in the effect column */
+			unsigned char v;
+			if (entry->effect == IT_TONE_PORTAMENTO)
+				v = entry->effectvalue;
+			else
+				v = 0;
+			if (sigdata->flags & IT_COMPATIBLE_GXX) {
+				if (v == 0)
+					v = channel->lastG;
+				channel->lastG = v;
+			} else {
+				if (v == 0)
+					v = channel->lastEF;
+				channel->lastEF = v;
+			}
+			if (entry->mask & IT_ENTRY_NOTE)
+				if (channel->sample)
+					channel->destnote = channel->truenote;
+			channel->toneporta = v << 4;
+		}
+	} else if ((entry->mask & IT_ENTRY_NOTE) ||
+		((entry->mask & IT_ENTRY_INSTRUMENT) && (!channel->playing || entry->instrument != channel->playing->instnum)))
+	{
+		if (channel->note < 120) {
+			get_true_pan(sigdata, channel);
+			it_retrigger_note(sigrenderer, channel);
+		}
+	}
+
+	if (entry->mask & IT_ENTRY_VOLPAN) {
+		if (entry->volpan <= 64) {
+			/* Volume */
+			channel->volume = entry->volpan;
+		} else if (entry->volpan <= 74) {
+			/* Fine volume slide up */
+			unsigned char v = entry->volpan - 65;
+			if (v == 0)
+				v = channel->lastvolslide;
+			channel->lastvolslide = v;
+			/* = effect DxF where x == entry->volpan - 65 */
+			channel->volume += v;
+			if (channel->volume > 64) channel->volume = 64;
+		} else if (entry->volpan <= 84) {
+			/* Fine volume slide down */
+			unsigned char v = entry->volpan - 75;
+			if (v == 0)
+				v = channel->lastvolslide;
+			channel->lastvolslide = v;
+			/* = effect DFx where x == entry->volpan - 75 */
+			channel->volume -= v;
+			if (channel->volume > 64) channel->volume = 0;
+		} else if (entry->volpan < 128) {
+			/* Volume slide up */
+			/* Volume slide down */
+			/* Portamento down */
+			/* Portamento up */
+		} else if (entry->volpan <= 192) {
+			/* Pan */
+			channel->pan = entry->volpan - 128;
+			channel->truepan = channel->pan << IT_ENVELOPE_SHIFT;
+		}
+		/* else */
+		/* Tone Portamento */
+		/* Vibrato */
+	}
+	return 0;
+}
+
+
+
+static void retrigger_xm_envelopes(IT_PLAYING *playing)
+{
+	playing->volume_envelope.next_node = 0;
+	playing->volume_envelope.tick = -1;
+	playing->pan_envelope.next_node = 0;
+	playing->pan_envelope.tick = -1;
+	playing->fadeoutcount = 1024;
+}
+
+
+
+static void process_xm_note_data(DUMB_IT_SIGRENDERER *sigrenderer, IT_ENTRY *entry)
+{
+	DUMB_IT_SIGDATA *sigdata = sigrenderer->sigdata;
+	IT_CHANNEL *channel = &sigrenderer->channel[(int)entry->channel];
+
+	if (entry->mask & IT_ENTRY_INSTRUMENT) {
+		channel->instrument = entry->instrument;
+		instrument_to_sample(sigdata, channel);
+		if (channel->playing) {
+			/* Retrigger vol/pan envelopes if enabled, and cancel fadeout.
+			 * Also reset vol/pan to that of _original_ instrument.
+			 */
+			channel->playing->flags &= ~(IT_PLAYING_SUSTAINOFF | IT_PLAYING_FADING);
+			it_playing_update_resamplers(channel->playing);
+
+			channel->volume = channel->playing->sample->default_volume;
+			if (channel->pan >= 128 && channel->pan <= 192)
+				channel->pan = channel->playing->sample->default_pan - 128;
+
+			retrigger_xm_envelopes(channel->playing);
+		}
+	}
+
+	if (entry->mask & IT_ENTRY_NOTE) {
+		if (!(entry->mask & IT_ENTRY_INSTRUMENT))
+			instrument_to_sample(sigdata, channel);
+
+		if (channel->note >= 120) {
+			if (channel->playing) {
+				if (!(sigdata->instrument[channel->instrument-1].volume_envelope.flags & IT_ENVELOPE_ON))
+					if (!(entry->mask & IT_ENTRY_INSTRUMENT))
+						channel->volume = 0;
+				channel->playing->flags |= IT_PLAYING_SUSTAINOFF | IT_PLAYING_FADING;
+				it_playing_update_resamplers(channel->playing);
+			}
+		} else if (channel->sample == 0) {
+			/** If we get here, one of the following is the case:
+			 ** 1. The instrument has never been specified on this channel.
+			 ** 2. The specified instrument is invalid.
+			 ** 3. The instrument has no sample mapped to the selected note.
+			 ** What should happen?
+			 **
+			 ** Experimentation shows that any existing note stops and cannot
+			 ** be brought back. A subsequent instrument change fixes that.
+			 **/
+			if (channel->playing) {
+				free(channel->playing);
+				channel->playing = NULL;
+			}
+			return;
+		} else if (channel->playing && (entry->mask & IT_ENTRY_VOLPAN) && ((entry->volpan>>4) == 0xF)) {
+			/* Don't retrigger note; portamento in the volume column. */
+		} else if (channel->playing &&
+		           (entry->mask & IT_ENTRY_EFFECT) &&
+		           (entry->effect == IT_TONE_PORTAMENTO ||
+		            entry->effect == IT_VOLSLIDE_TONEPORTA)) {
+			/* Don't retrigger note; portamento in the effects column. */
+		} else {
+			channel->destnote = IT_NOTE_OFF;
+
+			if (!channel->playing) {
+				channel->playing = (IT_PLAYING *)malloc(sizeof(*channel->playing));
+				if (!channel->playing)
+					return;
+				// Adding the following seems to do the trick for the case where a piece starts with an instrument alone and then some notes alone.
+				retrigger_xm_envelopes(channel->playing);
+			}
+
+			channel->playing->flags = 0;
+			channel->playing->channel = channel;
+			channel->playing->sample = &sigdata->sample[channel->sample-1];
+			if (sigdata->flags & IT_USE_INSTRUMENTS)
+				channel->playing->instrument = &sigdata->instrument[channel->instrument-1];
+			else
+				channel->playing->instrument = NULL;
+			channel->playing->env_instrument = channel->playing->instrument;
+			channel->playing->sampnum = channel->sample;
+			channel->playing->instnum = channel->instrument;
+			channel->playing->channel_volume = channel->channelvolume;
+			channel->playing->note = channel->truenote;
+			channel->playing->filter_cutoff = 127;
+			channel->playing->filter_resonance = 0;
+			channel->playing->true_filter_cutoff = 127 << 8;
+			channel->playing->true_filter_resonance = 0;
+			channel->playing->vibrato_speed = 0;
+			channel->playing->vibrato_depth = 0;
+			channel->playing->vibrato_n = 0;
+			channel->playing->vibrato_time = 0;
+			channel->playing->tremolo_speed = 0;
+			channel->playing->tremolo_depth = 0;
+			channel->playing->tremolo_time = 0;
+			channel->playing->sample_vibrato_time = 0;
+			channel->playing->sample_vibrato_depth = 0;
+			channel->playing->slide = 0;
+			it_reset_filter_state(&channel->playing->filter_state[0]); // Are these
+			it_reset_filter_state(&channel->playing->filter_state[1]); // necessary?
+			it_playing_reset_resamplers(channel->playing, 0);
+
+			/** WARNING - is everything initialised? */
+		}
+	}
+
+	if ((entry->mask & (IT_ENTRY_NOTE | IT_ENTRY_INSTRUMENT)) == (IT_ENTRY_NOTE | IT_ENTRY_INSTRUMENT)) {
+		if (channel->playing) retrigger_xm_envelopes(channel->playing);
+		get_default_volpan(sigdata, channel);
+		channel->truepan = channel->pan << IT_ENVELOPE_SHIFT;
+	}
+
+	if ((entry->mask & IT_ENTRY_VOLPAN) && ((entry->volpan>>4) == 0xF)) {
+		/* Tone Portamento */
+		unsigned char v = (entry->volpan & 15) << 4;
+		if (v == 0)
+			v = channel->lastG;
+		channel->lastG = v;
+		if (entry->mask & IT_ENTRY_NOTE)
+			if (channel->sample)
+				channel->destnote = channel->truenote;
+		channel->toneporta = v << 4;
+	} else if ((entry->mask & IT_ENTRY_EFFECT) &&
+	           (entry->effect == IT_TONE_PORTAMENTO ||
+	            entry->effect == IT_VOLSLIDE_TONEPORTA)) {
+		unsigned char v;
+		if (entry->effect == IT_TONE_PORTAMENTO)
+			v = entry->effectvalue;
+		else
+			v = 0;
+		if (v == 0)
+			v = channel->lastG;
+		channel->lastG = v;
+		if (entry->mask & IT_ENTRY_NOTE)
+			if (channel->sample)
+				channel->destnote = channel->truenote;
+		channel->toneporta = v << 4;
+	}
+
+	if (entry->mask & IT_ENTRY_VOLPAN) {
+		int effect = entry->volpan >> 4;
+		int value  = entry->volpan & 15;
+		switch (effect) {
+			case 0x6: /* Volume slide down */
+				channel->xm_volslide = -value;
+				break;
+			case 0x7: /* Volume slide up */
+				channel->xm_volslide = value;
+				break;
+			case 0x8: /* Fine volume slide down */
+				channel->volume -= value;
+				if (channel->volume > 64) channel->volume = 0;
+				break;
+			case 0x9: /* Fine volume slide up */
+				channel->volume += value;
+				if (channel->volume > 64) channel->volume = 64;
+				break;
+			case 0xA: /* Set vibrato speed */
+				if (value)
+					channel->lastHspeed = value;
+				if (channel->playing)
+					channel->playing->vibrato_speed = channel->lastHspeed;
+				break;
+			case 0xB: /* Vibrato */
+				if (value)
+					channel->lastHdepth = value << 2; /** WARNING: correct ? */
+				if (channel->playing) {
+					channel->playing->vibrato_depth = channel->lastHdepth;
+					channel->playing->vibrato_speed = channel->lastHspeed;
+					channel->playing->vibrato_n++;
+				}
+				break;
+			case 0xC: /* Set panning */
+				channel->pan = (value*64)/15;
+				channel->truepan = channel->pan << IT_ENVELOPE_SHIFT;
+				break;
+			case 0xD: /* Pan slide left */
+				// TODO
+				// channel->xm_panslide = -value;
+				break;
+			case 0xE: /* Pan slide Right */
+				// TODO
+				// channel->xm_panslide = value;
+				break;
+			case 0xF: /* Tone porta */
+				break;
+			default:  /* Volume */
+				channel->volume = entry->volpan - 0x10;
+				break;
+		}
+	}
+}
+
+
+
+/* This function assumes !IT_IS_END_ROW(entry). */
+static int process_note_data(DUMB_IT_SIGRENDERER *sigrenderer, IT_ENTRY *entry)
+{
+	DUMB_IT_SIGDATA *sigdata = sigrenderer->sigdata;
+
+	if (sigdata->flags & IT_WAS_AN_XM)
+		process_xm_note_data(sigrenderer, entry);
+	else
+		if (process_it_note_data(sigrenderer, entry)) return 0;
+
+	return process_effects(sigrenderer, entry);
+}
+
+
+
+static int process_entry(DUMB_IT_SIGRENDERER *sigrenderer, IT_ENTRY *entry)
+{
+	IT_CHANNEL *channel = &sigrenderer->channel[(int)entry->channel];
+
+	if (entry->mask & IT_ENTRY_NOTE)
+		channel->note = entry->note;
+
+	if ((entry->mask & IT_ENTRY_EFFECT) && entry->effect == IT_S) {
+		/* channel->lastS was set in update_pattern_variables(). */
+		unsigned char effectvalue = channel->lastS;
+		if (effectvalue >> 4 == IT_S_NOTE_DELAY) {
+			channel->note_delay_count = effectvalue & 15;
+			if (channel->note_delay_count == 0)
+				channel->note_delay_count = 1;
+			channel->note_delay_entry = entry;
+			return 0;
+		}
+	}
+
+	return process_note_data(sigrenderer, entry);
+}
+
+
+
+static void update_tick_counts(DUMB_IT_SIGRENDERER *sigrenderer)
+{
+	int i;
+
+	for (i = 0; i < DUMB_IT_N_CHANNELS; i++) {
+		IT_CHANNEL *channel = &sigrenderer->channel[i];
+
+		if (channel->note_cut_count) {
+			channel->note_cut_count--;
+			if (channel->note_cut_count == 0) {
+				if (sigrenderer->sigdata->flags & IT_WAS_AN_XM)
+					channel->volume = 0;
+				else if (channel->playing) {
+					free(channel->playing);
+					channel->playing = NULL;
+				}
+			}
+		} else if (channel->note_delay_count) {
+			channel->note_delay_count--;
+			if (channel->note_delay_count == 0)
+				process_note_data(sigrenderer, channel->note_delay_entry);
+					/* Don't bother checking the return value; if the note
+					 * was delayed, there can't have been a speed=0.
+					 */
+		}
+	}
+}
+
+
+
+static int envelope_get_y(IT_ENVELOPE *envelope, IT_PLAYING_ENVELOPE *pe)
+{
+	int ys, ye;
+	int ts, te;
+	int t;
+
+	if (pe->next_node <= 0)
+		return envelope->node_y[0] << IT_ENVELOPE_SHIFT;
+
+	if (pe->next_node >= envelope->n_nodes)
+		return envelope->node_y[envelope->n_nodes-1] << IT_ENVELOPE_SHIFT;
+
+	ys = envelope->node_y[pe->next_node-1] << IT_ENVELOPE_SHIFT;
+	ts = envelope->node_t[pe->next_node-1];
+	te = envelope->node_t[pe->next_node];
+
+	if (ts == te)
+		return ys;
+
+	ye = envelope->node_y[pe->next_node] << IT_ENVELOPE_SHIFT;
+
+	t = pe->tick;
+
+	return ys + (ye - ys) * (t - ts) / (te - ts);
+}
+
+
+
+static int it_envelope_end(IT_PLAYING *playing, IT_ENVELOPE *envelope, IT_PLAYING_ENVELOPE *pe)
+{
+	if (pe->next_node >= envelope->n_nodes)
+		return 1;
+
+	if (pe->tick < envelope->node_t[pe->next_node]) return 0;
+
+	if ((envelope->flags & IT_ENVELOPE_LOOP_ON) &&
+	    envelope->loop_end >= pe->next_node &&
+	    envelope->node_t[envelope->loop_end] <= pe->tick) return 0;
+
+	if ((envelope->flags & IT_ENVELOPE_SUSTAIN_LOOP) &&
+	    !(playing->flags & IT_PLAYING_SUSTAINOFF) &&
+	    envelope->sus_loop_end >= pe->next_node &&
+	    envelope->node_t[envelope->sus_loop_end] <= pe->tick) return 0;
+
+	if (envelope->node_t[envelope->n_nodes-1] <= pe->tick) return 1;
+
+	return 0;
+}
+
+
+
+/* This returns 1 if the envelope finishes. */
+static int update_it_envelope(IT_PLAYING *playing, IT_ENVELOPE *envelope, IT_PLAYING_ENVELOPE *pe)
+{
+	if (!(envelope->flags & IT_ENVELOPE_ON))
+		return 0;
+
+	if (pe->next_node >= envelope->n_nodes)
+		return 1;
+
+	while (pe->tick >= envelope->node_t[pe->next_node]) {
+		if ((envelope->flags & IT_ENVELOPE_LOOP_ON) && pe->next_node == envelope->loop_end) {
+			pe->next_node = envelope->loop_start;
+			pe->tick = envelope->node_t[envelope->loop_start];
+			return it_envelope_end(playing, envelope, pe);
+		}
+		if ((envelope->flags & IT_ENVELOPE_SUSTAIN_LOOP) && !(playing->flags & IT_PLAYING_SUSTAINOFF) && pe->next_node == envelope->sus_loop_end) {
+			pe->next_node = envelope->sus_loop_start;
+			pe->tick = envelope->node_t[envelope->sus_loop_start];
+			return it_envelope_end(playing, envelope, pe);
+		}
+
+		pe->next_node++;
+
+		if (pe->next_node >= envelope->n_nodes)
+			return 1;
+	}
+
+	pe->tick++;
+
+	return it_envelope_end(playing, envelope, pe);
+}
+
+
+
+static void update_it_envelopes(IT_PLAYING *playing)
+{
+	IT_ENVELOPE *envelope = &playing->env_instrument->volume_envelope;
+
+	if (update_it_envelope(playing, envelope, &playing->volume_envelope)) {
+		playing->flags |= IT_PLAYING_FADING;
+		if (envelope->n_nodes && envelope->node_y[envelope->n_nodes-1] == 0)
+			playing->flags |= IT_PLAYING_DEAD;
+	}
+
+	update_it_envelope(playing, &playing->env_instrument->pan_envelope, &playing->pan_envelope);
+	update_it_envelope(playing, &playing->env_instrument->pitch_envelope, &playing->pitch_envelope);
+}
+
+
+
+static int xm_envelope_is_sustaining(IT_PLAYING *playing, IT_ENVELOPE *envelope, IT_PLAYING_ENVELOPE *pe)
+{
+	if ((envelope->flags & IT_ENVELOPE_SUSTAIN_LOOP) && !(playing->flags & IT_PLAYING_SUSTAINOFF))
+		if (envelope->sus_loop_start < envelope->n_nodes)
+			if (pe->tick == envelope->node_t[envelope->sus_loop_start])
+				return 1;
+	return 0;
+}
+
+
+
+static void update_xm_envelope(IT_PLAYING *playing, IT_ENVELOPE *envelope, IT_PLAYING_ENVELOPE *pe)
+{
+	if (!(envelope->flags & IT_ENVELOPE_ON))
+		return;
+
+	if (xm_envelope_is_sustaining(playing, envelope, pe))
+		return;
+
+	if (pe->tick >= envelope->node_t[envelope->n_nodes-1])
+		return;
+
+	pe->tick++;
+
+	/* pe->next_node must be kept up to date for envelope_get_y(). */
+	while (pe->tick > envelope->node_t[pe->next_node])
+		pe->next_node++;
+
+	if ((envelope->flags & IT_ENVELOPE_LOOP_ON) && envelope->loop_end < envelope->n_nodes) {
+		if (pe->tick == envelope->node_t[envelope->loop_end]) {
+			pe->next_node = MID(0, envelope->loop_start, envelope->n_nodes - 1);
+			pe->tick = envelope->node_t[pe->next_node];
+		}
+	}
+
+	if (xm_envelope_is_sustaining(playing, envelope, pe))
+		return;
+
+	if (pe->tick >= envelope->node_t[envelope->n_nodes-1])
+		return;
+}
+
+
+
+static void update_xm_envelopes(IT_PLAYING *playing)
+{
+	update_xm_envelope(playing, &playing->env_instrument->volume_envelope, &playing->volume_envelope);
+	update_xm_envelope(playing, &playing->env_instrument->pan_envelope, &playing->pan_envelope);
+}
+
+
+
+static void update_fadeout(DUMB_IT_SIGDATA *sigdata, IT_PLAYING *playing)
+{
+	if (playing->flags & IT_PLAYING_FADING) {
+		playing->fadeoutcount -= playing->env_instrument->fadeout;
+		if (playing->fadeoutcount <= 0) {
+			playing->fadeoutcount = 0;
+			if (!(sigdata->flags & IT_WAS_AN_XM))
+				playing->flags |= IT_PLAYING_DEAD;
+		}
+	}
+}
+
+
+
+static void process_playing(DUMB_IT_SIGDATA *sigdata, IT_PLAYING *playing)
+{
+	if (playing->instrument) {
+		if (sigdata->flags & IT_WAS_AN_XM)
+			update_xm_envelopes(playing);
+		else
+			update_it_envelopes(playing);
+		update_fadeout(sigdata, playing);
+	}
+
+	//Calculate final volume if required
+	//Calculate final pan if required
+
+	if (sigdata->flags & IT_WAS_AN_XM) {
+		/* 'depth' is used to store the tick number for XM files. */
+		if (playing->sample_vibrato_depth < playing->sample->vibrato_rate)
+			playing->sample_vibrato_depth++;
+	} else {
+		playing->sample_vibrato_depth += playing->sample->vibrato_rate;
+		if (playing->sample_vibrato_depth > playing->sample->vibrato_depth << 8)
+			playing->sample_vibrato_depth = playing->sample->vibrato_depth << 8;
+	}
+
+	playing->sample_vibrato_time += playing->sample->vibrato_speed;
+}
+
+
+
+static void process_all_playing(DUMB_IT_SIGRENDERER *sigrenderer)
+{
+	DUMB_IT_SIGDATA *sigdata = sigrenderer->sigdata;
+	int i;
+
+	for (i = 0; i < DUMB_IT_N_CHANNELS; i++) {
+		IT_CHANNEL *channel = &sigrenderer->channel[i];
+		IT_PLAYING *playing = channel->playing;
+
+		if (playing) {
+			int vibrato_shift = it_sine[playing->vibrato_time];
+			vibrato_shift *= playing->vibrato_n;
+			vibrato_shift *= playing->vibrato_depth;
+			vibrato_shift >>= 4;
+
+			if (sigdata->flags & IT_OLD_EFFECTS)
+				vibrato_shift = -vibrato_shift;
+
+			playing->volume = channel->volume;
+			playing->pan = channel->truepan;
+
+			if (sigdata->flags & IT_LINEAR_SLIDES) {
+				int currpitch = ((playing->note - 60) << 8) + playing->slide
+				                                            + vibrato_shift;
+
+				/* We add a feature here, which is that of keeping the pitch
+				 * within range. Otherwise it crashes. Trust me. It happened.
+				 * The limit 32768 gives almost 11 octaves either way.
+				 */
+				if (currpitch < -32768)
+					currpitch = -32768;
+				else if (currpitch > 32767)
+					currpitch = 32767;
+
+				playing->delta = (float)pow(DUMB_PITCH_BASE, currpitch);
+				playing->delta *= playing->sample->C5_speed / 65536.0f;
+			} else {
+				int slide = playing->slide + vibrato_shift;
+
+				playing->delta = (float)pow(DUMB_SEMITONE_BASE, 60 - playing->note);
+				/* playing->delta is 1.0 for C-5, 0.5 for C-6, etc. */
+
+				playing->delta *= 1.0f / playing->sample->C5_speed;
+
+				playing->delta -= slide / AMIGA_DIVISOR;
+
+				if (playing->delta < (1.0f / 65536.0f) / 32768.0f) {
+					// Should XM notes die if Amiga slides go out of range?
+					playing->flags |= IT_PLAYING_DEAD;
+					continue;
+				}
+
+				playing->delta = (1.0f / 65536.0f) / playing->delta;
+			}
+
+			playing->delta *= (float)pow(DUMB_SEMITONE_BASE, channel->arpeggio >> 8);
+
+			playing->filter_cutoff = channel->filter_cutoff;
+			playing->filter_resonance = channel->filter_resonance;
+		}
+	}
+
+	for (i = 0; i < DUMB_IT_N_CHANNELS; i++) {
+		if (sigrenderer->channel[i].playing) {
+			process_playing(sigdata, sigrenderer->channel[i].playing);
+			if (!(sigdata->flags & IT_WAS_AN_XM)) {
+				if ((sigrenderer->channel[i].playing->flags & (IT_PLAYING_BACKGROUND | IT_PLAYING_DEAD)) == (IT_PLAYING_BACKGROUND | IT_PLAYING_DEAD)) {
+					free(sigrenderer->channel[i].playing);
+					sigrenderer->channel[i].playing = NULL;
+				}
+			}
+		}
+	}
+
+	for (i = 0; i < DUMB_IT_N_NNA_CHANNELS; i++) {
+		if (sigrenderer->playing[i]) {
+			process_playing(sigdata, sigrenderer->playing[i]);
+			if (sigrenderer->playing[i]->flags & IT_PLAYING_DEAD) {
+				free(sigrenderer->playing[i]);
+				sigrenderer->playing[i] = NULL;
+			}
+		}
+	}
+}
+
+
+
+static int process_tick(DUMB_IT_SIGRENDERER *sigrenderer)
+{
+	DUMB_IT_SIGDATA *sigdata = sigrenderer->sigdata;
+
+	// Set note vol/freq to vol/freq set for each channel
+
+	if (sigrenderer->speed && --sigrenderer->tick == 0) {
+		reset_tick_counts(sigrenderer);
+		sigrenderer->tick = sigrenderer->speed;
+		sigrenderer->rowcount--;
+		if (sigrenderer->rowcount == 0) {
+			sigrenderer->rowcount = 1;
+			if (sigrenderer->pat_loop_row >= 0) {
+				int n = sigrenderer->pat_loop_row - 1;
+				sigrenderer->row = sigrenderer->processrow = n;
+				sigrenderer->pat_loop_row = -1;
+				if (n < 0)
+					sigrenderer->entry = NULL;
+				else {
+					sigrenderer->entry = sigrenderer->entry_start;
+					while (n) {
+						while (sigrenderer->entry < sigrenderer->entry_end) {
+							if (IT_IS_END_ROW(sigrenderer->entry)) {
+								sigrenderer->entry++;
+								break;
+							}
+							sigrenderer->entry++;
+						}
+						n--;
+					}
+				}
+			}
+
+			sigrenderer->processrow++;
+
+			if (sigrenderer->processrow >= sigrenderer->n_rows) {
+				IT_PATTERN *pattern;
+				int n;
+
+				sigrenderer->processrow = sigrenderer->breakrow;
+				sigrenderer->breakrow = 0;
+
+				for (;;) {
+					sigrenderer->processorder++;
+
+					if (sigrenderer->processorder >= sigdata->n_orders) {
+						sigrenderer->processorder = sigdata->restart_position;
+						if (sigrenderer->processorder >= sigdata->n_orders) {
+							/* Restarting beyond end. We'll loop for now. */
+							sigrenderer->processorder = -1;
+							continue;
+						}
+					}
+
+					n = sigdata->order[sigrenderer->processorder];
+
+					if (n < sigdata->n_patterns)
+						break;
+
+#ifdef INVALID_ORDERS_END_SONG
+					if (n != IT_ORDER_SKIP)
+						sigrenderer->processorder = -1;
+#else
+					if (n == IT_ORDER_END)
+						sigrenderer->processorder = -1;
+#endif
+				}
+
+				pattern = &sigdata->pattern[n];
+
+				sigrenderer->n_rows = pattern->n_rows;
+
+				if (sigrenderer->processrow >= sigrenderer->n_rows)
+					sigrenderer->processrow = 0;
+
+/** WARNING - everything pertaining to a new pattern initialised? */
+
+				sigrenderer->entry = sigrenderer->entry_start = pattern->entry;
+				sigrenderer->entry_end = sigrenderer->entry + pattern->n_entries;
+
+				if (sigrenderer->order >= sigrenderer->processorder) {
+					if (sigrenderer->callbacks->loop) {
+						if ((*sigrenderer->callbacks->loop)(sigrenderer->callbacks->loop_data))
+							return 1;
+						if (sigrenderer->speed == 0)
+							goto speed0; /* I love goto */
+					}
+				}
+				sigrenderer->order = sigrenderer->processorder;
+
+				n = sigrenderer->processrow;
+				while (n) {
+					while (sigrenderer->entry < sigrenderer->entry_end) {
+						if (IT_IS_END_ROW(sigrenderer->entry)) {
+							sigrenderer->entry++;
+							break;
+						}
+						sigrenderer->entry++;
+					}
+					n--;
+				}
+				sigrenderer->row = sigrenderer->processrow;
+			} else {
+				if (sigrenderer->entry) {
+					while (sigrenderer->entry < sigrenderer->entry_end) {
+						if (IT_IS_END_ROW(sigrenderer->entry)) {
+							sigrenderer->entry++;
+							break;
+						}
+						sigrenderer->entry++;
+					}
+					sigrenderer->row++;
+				} else {
+					sigrenderer->entry = sigrenderer->entry_start;
+					sigrenderer->row = 0;
+				}
+			}
+
+			reset_effects(sigrenderer);
+
+			{
+				IT_ENTRY *entry = sigrenderer->entry;
+
+				while (entry < sigrenderer->entry_end && !IT_IS_END_ROW(entry))
+					update_pattern_variables(sigrenderer, entry++);
+			}
+
+			{
+				IT_ENTRY *entry = sigrenderer->entry;
+
+				while (entry < sigrenderer->entry_end && !IT_IS_END_ROW(entry))
+					if (process_entry(sigrenderer, entry++))
+						return 1;
+			}
+
+			if (!(sigdata->flags & IT_OLD_EFFECTS))
+				update_smooth_effects(sigrenderer);
+		} else {
+			{
+				IT_ENTRY *entry = sigrenderer->entry;
+
+				while (entry < sigrenderer->entry_end && !IT_IS_END_ROW(entry))
+					process_effects(sigrenderer, entry++);
+						/* Don't bother checking the return value; if there
+						 * was a pattern delay, there can't be a speed=0.
+						 */
+			}
+
+			update_effects(sigrenderer);
+		}
+	} else {
+		speed0:
+		update_effects(sigrenderer);
+		update_tick_counts(sigrenderer);
+	}
+
+	process_all_playing(sigrenderer);
+
+	sigrenderer->time_left += TICK_TIME_DIVIDEND / sigrenderer->tempo;
+
+	return 0;
+}
+
+
+
+int dumb_it_max_to_mix = 64;
+
+
+
+static float calculate_volume(DUMB_IT_SIGRENDERER *sigrenderer, IT_PLAYING *playing, float volume)
+{
+	if (volume != 0) {
+		int vol;
+
+		if (playing->channel->flags & IT_CHANNEL_MUTED)
+			return 0;
+
+		if ((playing->channel->tremor_time & 192) == 128)
+			return 0;
+
+		vol = it_sine[playing->tremolo_time];
+		vol *= playing->tremolo_depth;
+
+		vol = (playing->volume << 5) + vol;
+
+		if (vol <= 0)
+			return 0;
+
+		if (vol > 64 << 5)
+			vol = 64 << 5;
+
+		volume *= vol; /* 64 << 5 */
+		volume *= playing->sample->global_volume; /* 64 */
+		volume *= playing->channel_volume; /* 64 */
+		volume *= sigrenderer->globalvolume; /* 128 */
+		volume *= sigrenderer->sigdata->mixing_volume; /* 128 */
+		volume *= 1.0f / ((64 << 5) * 64.0f * 64.0f * 128.0f * 128.0f);
+
+		if (volume && playing->instrument) {
+			if (playing->env_instrument->volume_envelope.flags & IT_ENVELOPE_ON) {
+				volume *= envelope_get_y(&playing->env_instrument->volume_envelope, &playing->volume_envelope);
+				volume *= 1.0f / (64 << IT_ENVELOPE_SHIFT);
+			}
+			volume *= playing->instrument->global_volume; /* 128 */
+			volume *= playing->fadeoutcount; /* 1024 */
+			volume *= 1.0f / (128.0f * 1024.0f);
+		}
+	}
+
+	return volume;
+}
+
+
+
+static int apply_pan_envelope(IT_PLAYING *playing)
+{
+	int pan = playing->pan;
+	if (pan <= 64 << IT_ENVELOPE_SHIFT && playing->env_instrument && (playing->env_instrument->pan_envelope.flags & IT_ENVELOPE_ON)) {
+		int p = envelope_get_y(&playing->env_instrument->pan_envelope, &playing->pan_envelope);
+		if (pan > 32 << IT_ENVELOPE_SHIFT)
+			p *= (64 << IT_ENVELOPE_SHIFT) - pan;
+		else
+			p *= pan;
+		pan += p >> (5 + IT_ENVELOPE_SHIFT);
+	}
+	return pan;
+}
+
+
+
+/* Note: if a click remover is provided, and store_end_sample is set, then
+ * the end point will be computed twice. This situation should not arise.
+ */
+static long render_playing(DUMB_IT_SIGRENDERER *sigrenderer, IT_PLAYING *playing, float volume, float delta, long pos, long size, sample_t **samples, int store_end_sample, int *left_to_mix)
+{
+	int pan;
+
+	long size_rendered;
+
+	if (playing->flags & IT_PLAYING_DEAD)
+		return 0;
+
+	if (*left_to_mix <= 0)
+		volume = 0;
+
+	pan = apply_pan_envelope(playing);
+
+#define RESAMPLERV(rv, resampler, dst, volume)				 \
+{															 \
+	rv = dumb_resample(resampler, dst, size, volume, delta); \
+	if (store_end_sample)									 \
+		(dst)[rv] = RESAMPLE_VALUE(resampler, volume);		 \
+}
+
+#define RESAMPLE(resampler, dst, volume)   \
+{										   \
+	int i;								   \
+	RESAMPLERV(i, resampler, dst, volume); \
+}
+
+#define RESAMPLE_VALUE(resampler, volume) \
+	dumb_resample_get_current_sample(resampler, volume)
+
+	if (volume == 0) {
+		size_rendered = dumb_resample(&playing->resampler[0], NULL, size, 0, delta);
+		if (playing->sample->flags & IT_SAMPLE_STEREO)
+			dumb_resample(&playing->resampler[1], NULL, size, 0, delta);
+	} else {
+		if (sigrenderer->n_channels == 2) {
+			float vol = volume;
+			DUMB_RESAMPLER start = playing->resampler[0];
+			if (!IT_IS_SURROUND_SHIFTED(pan)) vol *= 2.0f - pan * (1.0f / (32 << IT_ENVELOPE_SHIFT));
+			if (sigrenderer->click_remover && sigrenderer->click_remover[0])
+				dumb_record_click(sigrenderer->click_remover[0], pos, RESAMPLE_VALUE(&playing->resampler[0], vol));
+			RESAMPLERV(size_rendered, &playing->resampler[0], samples[0] + pos, vol);
+			if (sigrenderer->click_remover && sigrenderer->click_remover[0])
+				dumb_record_click(sigrenderer->click_remover[0], pos + size_rendered, -RESAMPLE_VALUE(&playing->resampler[0], vol));
+			vol = -vol;
+			if (!IT_IS_SURROUND_SHIFTED(pan)) vol += 2.0f * volume;
+			if (playing->sample->flags & IT_SAMPLE_STEREO) {
+				if (sigrenderer->click_remover && sigrenderer->click_remover[1])
+					dumb_record_click(sigrenderer->click_remover[1], pos, RESAMPLE_VALUE(&playing->resampler[1], vol));
+				RESAMPLE(&playing->resampler[1], samples[1] + pos, vol);
+				if (sigrenderer->click_remover && sigrenderer->click_remover[1])
+					dumb_record_click(sigrenderer->click_remover[1], pos + size_rendered, -RESAMPLE_VALUE(&playing->resampler[1], vol));
+			} else {
+				playing->resampler[0] = start;
+				if (sigrenderer->click_remover && sigrenderer->click_remover[1])
+					dumb_record_click(sigrenderer->click_remover[1], pos, RESAMPLE_VALUE(&playing->resampler[0], vol));
+				RESAMPLE(&playing->resampler[0], samples[1] + pos, vol);
+				if (sigrenderer->click_remover && sigrenderer->click_remover[1])
+					dumb_record_click(sigrenderer->click_remover[1], pos + size_rendered, -RESAMPLE_VALUE(&playing->resampler[0], vol));
+			}
+		} else {
+			if (playing->sample->flags & IT_SAMPLE_STEREO) {
+				float vol = 0.5f * volume;
+				if (!IT_IS_SURROUND_SHIFTED(pan)) vol *= 2.0f - pan * (1.0f / (32 << IT_ENVELOPE_SHIFT));
+				if (sigrenderer->click_remover && sigrenderer->click_remover[0]) {
+					sample_t startstep, endstep;
+					startstep = RESAMPLE_VALUE(&playing->resampler[0], vol);
+					RESAMPLE(&playing->resampler[0], samples[0] + pos, vol);
+					endstep = RESAMPLE_VALUE(&playing->resampler[0], vol);
+					if (!IT_IS_SURROUND_SHIFTED(pan)) vol = 2.0f * volume - vol;
+					startstep += RESAMPLE_VALUE(&playing->resampler[1], vol);
+					RESAMPLERV(size_rendered, &playing->resampler[1], samples[0] + pos, vol);
+					endstep += RESAMPLE_VALUE(&playing->resampler[1], vol);
+					dumb_record_click(sigrenderer->click_remover[0], pos, startstep);
+					dumb_record_click(sigrenderer->click_remover[0], pos + size_rendered, -endstep);
+				} else {
+					RESAMPLE(&playing->resampler[0], samples[0] + pos, vol);
+					if (!IT_IS_SURROUND_SHIFTED(pan)) vol = 2.0f * volume - vol;
+					RESAMPLERV(size_rendered, &playing->resampler[1], samples[0] + pos, vol);
+				}
+			} else {
+				if (sigrenderer->click_remover && sigrenderer->click_remover[0])
+					dumb_record_click(sigrenderer->click_remover[0], pos, RESAMPLE_VALUE(&playing->resampler[0], volume));
+				RESAMPLERV(size_rendered, &playing->resampler[0], samples[0] + pos, volume);
+				if (sigrenderer->click_remover && sigrenderer->click_remover[0])
+					dumb_record_click(sigrenderer->click_remover[0], pos + size_rendered, -RESAMPLE_VALUE(&playing->resampler[0], volume));
+			}
+		}
+		(*left_to_mix)--;
+	}
+
+	if (playing->resampler[0].dir == 0)
+		playing->flags |= IT_PLAYING_DEAD;
+
+	return size_rendered;
+}
+
+
+
+typedef struct IT_TO_MIX
+{
+	IT_PLAYING *playing;
+	float volume;
+}
+IT_TO_MIX;
+
+
+
+static int it_to_mix_compare(const void *e1, const void *e2)
+{
+	if (((const IT_TO_MIX *)e1)->volume > ((const IT_TO_MIX *)e2)->volume)
+		return -1;
+
+	if (((const IT_TO_MIX *)e1)->volume < ((const IT_TO_MIX *)e2)->volume)
+		return 1;
+
+	return 0;
+}
+
+
+
+static void apply_pitch_modifications(DUMB_IT_SIGDATA *sigdata, IT_PLAYING *playing, float *delta, int *cutoff)
+{
+	{
+		int sample_vibrato_shift = it_sine[playing->sample_vibrato_time];
+
+		if (sigdata->flags & IT_WAS_AN_XM) {
+			int depth = playing->sample->vibrato_depth; /* True depth */
+			if (playing->sample->vibrato_rate) {
+				depth *= playing->sample_vibrato_depth; /* Tick number */
+				depth /= playing->sample->vibrato_rate; /* XM sweep */
+			}
+			sample_vibrato_shift *= depth;
+		} else
+			sample_vibrato_shift *= playing->sample_vibrato_depth >> 8;
+
+		sample_vibrato_shift >>= 4;
+
+		*delta *= (float)pow(DUMB_PITCH_BASE, sample_vibrato_shift);
+	}
+
+	if (playing->env_instrument &&
+		(playing->env_instrument->pitch_envelope.flags & IT_ENVELOPE_ON))
+	{
+		int p = envelope_get_y(&playing->env_instrument->pitch_envelope, &playing->pitch_envelope);
+		if (playing->env_instrument->pitch_envelope.flags & IT_ENVELOPE_PITCH_IS_FILTER)
+			*cutoff = (*cutoff * (p+(32<<IT_ENVELOPE_SHIFT))) >> (6 + IT_ENVELOPE_SHIFT);
+		else
+			*delta *= (float)pow(DUMB_PITCH_BASE, p >> (IT_ENVELOPE_SHIFT - 7));
+	}
+}
+
+
+
+static void render(DUMB_IT_SIGRENDERER *sigrenderer, float volume, float delta, long pos, long size, sample_t **samples)
+{
+	int i;
+
+	int n_to_mix = 0;
+	IT_TO_MIX to_mix[DUMB_IT_TOTAL_CHANNELS];
+	int left_to_mix = dumb_it_max_to_mix;
+
+	sample_t **samples_to_filter = NULL;
+
+	for (i = 0; i < DUMB_IT_N_CHANNELS; i++) {
+		if (sigrenderer->channel[i].playing && !(sigrenderer->channel[i].playing->flags & IT_PLAYING_DEAD)) {
+			to_mix[n_to_mix].playing = sigrenderer->channel[i].playing;
+			to_mix[n_to_mix].volume = volume == 0 ? 0 : calculate_volume(sigrenderer, sigrenderer->channel[i].playing, volume);
+			n_to_mix++;
+		}
+	}
+
+	for (i = 0; i < DUMB_IT_N_NNA_CHANNELS; i++) {
+		if (sigrenderer->playing[i]) { /* Won't be dead; it would have been freed. */
+			to_mix[n_to_mix].playing = sigrenderer->playing[i];
+			to_mix[n_to_mix].volume = volume == 0 ? 0 : calculate_volume(sigrenderer, sigrenderer->playing[i], volume);
+			n_to_mix++;
+		}
+	}
+
+	if (volume != 0)
+		qsort(to_mix, n_to_mix, sizeof(IT_TO_MIX), &it_to_mix_compare);
+
+	for (i = 0; i < n_to_mix; i++) {
+		IT_PLAYING *playing = to_mix[i].playing;
+		float note_delta = delta * playing->delta;
+		int cutoff = playing->filter_cutoff << IT_ENVELOPE_SHIFT;
+
+		apply_pitch_modifications(sigrenderer->sigdata, playing, &note_delta, &cutoff);
+
+		if (cutoff != 127 << IT_ENVELOPE_SHIFT || playing->filter_resonance != 0) {
+			playing->true_filter_cutoff = cutoff;
+			playing->true_filter_resonance = playing->filter_resonance;
+		}
+
+		if (to_mix[i].volume && (playing->true_filter_cutoff != 127 << IT_ENVELOPE_SHIFT || playing->true_filter_resonance != 0)) {
+			if (!samples_to_filter) {
+				samples_to_filter = create_sample_buffer(sigrenderer->n_channels, size + 1);
+				if (!samples_to_filter) {
+					render_playing(sigrenderer, playing, 0, note_delta, pos, size, NULL, 0, &left_to_mix);
+					continue;
+				}
+			}
+			{
+				long size_rendered;
+				DUMB_CLICK_REMOVER **cr = sigrenderer->click_remover;
+				dumb_silence(samples_to_filter[0], sigrenderer->n_channels * (size + 1));
+				sigrenderer->click_remover = NULL;
+				size_rendered = render_playing(sigrenderer, playing, to_mix[i].volume, note_delta, 0, size, samples_to_filter, 1, &left_to_mix);
+				sigrenderer->click_remover = cr;
+				it_filter(cr ? cr[0] : NULL, &playing->filter_state[0], samples[0], pos, samples_to_filter[0], size_rendered,
+					65536.0f/delta, playing->true_filter_cutoff, playing->true_filter_resonance);
+				if (sigrenderer->n_channels == 2)
+					it_filter(cr ? cr[1] : NULL, &playing->filter_state[1], samples[1], pos, samples_to_filter[1], size_rendered,
+						65536.0f/delta, playing->true_filter_cutoff, playing->true_filter_resonance);
+				// warning: filtering is not prevented by low left_to_mix!
+			}
+		} else {
+			it_reset_filter_state(&playing->filter_state[0]);
+			it_reset_filter_state(&playing->filter_state[1]);
+			render_playing(sigrenderer, playing, to_mix[i].volume, note_delta, pos, size, samples, 0, &left_to_mix);
+		}
+	}
+
+	destroy_sample_buffer(samples_to_filter);
+
+	for (i = 0; i < DUMB_IT_N_CHANNELS; i++) {
+		if (sigrenderer->channel[i].playing) {
+			if ((sigrenderer->channel[i].playing->flags & (IT_PLAYING_BACKGROUND | IT_PLAYING_DEAD)) == (IT_PLAYING_BACKGROUND | IT_PLAYING_DEAD)) {
+				free(sigrenderer->channel[i].playing);
+				sigrenderer->channel[i].playing = NULL;
+			}
+		}
+	}
+
+	for (i = 0; i < DUMB_IT_N_NNA_CHANNELS; i++) {
+		if (sigrenderer->playing[i]) {
+			if (sigrenderer->playing[i]->flags & IT_PLAYING_DEAD) {
+				free(sigrenderer->playing[i]);
+				sigrenderer->playing[i] = NULL;
+			}
+		}
+	}
+}
+
+
+
+static DUMB_IT_SIGRENDERER *init_sigrenderer(DUMB_IT_SIGDATA *sigdata, int n_channels, int startorder, IT_CALLBACKS *callbacks, DUMB_CLICK_REMOVER **cr)
+{
+	DUMB_IT_SIGRENDERER *sigrenderer;
+	int i;
+
+	if (startorder > sigdata->n_orders) {
+		free(callbacks);
+		dumb_destroy_click_remover_array(n_channels, cr);
+		return NULL;
+	}
+
+	sigrenderer = (DUMB_IT_SIGRENDERER *)malloc(sizeof(*sigrenderer));
+	if (!sigrenderer) {
+		free(callbacks);
+		dumb_destroy_click_remover_array(n_channels, cr);
+		return NULL;
+	}
+
+	sigrenderer->callbacks = callbacks;
+	sigrenderer->click_remover = cr;
+
+	sigrenderer->sigdata = sigdata;
+	sigrenderer->n_channels = n_channels;
+	sigrenderer->globalvolume = sigdata->global_volume;
+	sigrenderer->tempo = sigdata->tempo;
+
+	for (i = 0; i < DUMB_IT_N_CHANNELS; i++) {
+		IT_CHANNEL *channel = &sigrenderer->channel[i];
+#if IT_CHANNEL_MUTED != 1
+#error this is wrong
+#endif
+		channel->flags = sigdata->channel_pan[i] >> 7;
+		channel->volume = (sigdata->flags & IT_WAS_AN_XM) ? 0 : 64;
+		channel->pan = sigdata->channel_pan[i] & 0x7F;
+		channel->truepan = channel->pan << IT_ENVELOPE_SHIFT;
+		channel->channelvolume = sigdata->channel_volume[i];
+		channel->instrument = 0;
+		channel->note = 0;
+		channel->SFmacro = 0;
+		channel->filter_cutoff = 127;
+		channel->filter_resonance = 0;
+		channel->xm_retrig = 0;
+		channel->retrig_tick = 0;
+		channel->tremor_time = 0;
+		channel->midi_state = 0;
+		channel->lastvolslide = 0;
+		channel->lastDKL = 0;
+		channel->lastEF = 0;
+		channel->lastG = 0;
+		channel->lastHspeed = 0;
+		channel->lastHdepth = 0;
+		channel->lastRspeed = 0;
+		channel->lastRdepth = 0;
+		channel->lastI = 0;
+		channel->lastJ = 0;
+		channel->lastN = 0;
+		channel->lastO = 0;
+		channel->high_offset = 0;
+		channel->lastQ = 0;
+		channel->lastS = 0;
+		channel->pat_loop_row = 0;
+		channel->pat_loop_count = 0;
+		channel->lastW = 0;
+		channel->xm_lastE1 = 0;
+		channel->xm_lastE2 = 0;
+		channel->xm_lastEA = 0;
+		channel->xm_lastEB = 0;
+		channel->xm_lastX1 = 0;
+		channel->xm_lastX2 = 0;
+		channel->playing = NULL;
+	}
+
+	for (i = 0; i < DUMB_IT_N_NNA_CHANNELS; i++)
+		sigrenderer->playing[i] = NULL;
+
+	sigrenderer->speed = sigdata->speed;
+
+	sigrenderer->processrow = 0;
+	sigrenderer->breakrow = 0;
+	sigrenderer->pat_loop_row = -1;
+	sigrenderer->rowcount = 1;
+
+	reset_tick_counts(sigrenderer);
+
+	sigrenderer->tick = sigrenderer->speed;
+
+	{
+		IT_PATTERN *pattern;
+		int n;
+
+		sigrenderer->processorder = startorder;
+		for (;;) {
+			n = sigdata->order[sigrenderer->processorder];
+
+			if (n < sigdata->n_patterns)
+				break;
+
+#ifdef INVALID_ORDERS_END_SONG
+			if (n != IT_ORDER_SKIP)
+#else
+			if (n == IT_ORDER_END)
+#endif
+			{
+				_dumb_it_end_sigrenderer(sigrenderer);
+				return NULL;
+			}
+
+			sigrenderer->processorder++;
+			if (sigrenderer->processorder >= sigdata->n_orders)
+				sigrenderer->processorder = 0;
+			if (sigrenderer->processorder == startorder) {
+				_dumb_it_end_sigrenderer(sigrenderer);
+				return NULL;
+			}
+		}
+
+		pattern = &sigdata->pattern[n];
+
+		sigrenderer->n_rows = pattern->n_rows;
+
+/** WARNING - everything pertaining to a new pattern initialised? */
+
+		sigrenderer->entry = sigrenderer->entry_start = pattern->entry;
+		sigrenderer->entry_end = sigrenderer->entry + pattern->n_entries;
+
+		sigrenderer->order = sigrenderer->processorder;
+		sigrenderer->row = 0;
+	}
+
+	reset_effects(sigrenderer);
+
+	{
+		IT_ENTRY *entry = sigrenderer->entry;
+
+		while (entry < sigrenderer->entry_end && !IT_IS_END_ROW(entry))
+			update_pattern_variables(sigrenderer, entry++);
+	}
+
+	{
+		IT_ENTRY *entry = sigrenderer->entry;
+
+		while (entry < sigrenderer->entry_end && !IT_IS_END_ROW(entry)) {
+			if (process_entry(sigrenderer, entry++)) {
+				/* Oops, that song ended quickly! */
+				_dumb_it_end_sigrenderer(sigrenderer);
+				return NULL;
+			}
+		}
+	}
+
+	if (!(sigdata->flags & IT_OLD_EFFECTS))
+		update_smooth_effects(sigrenderer);
+
+	process_all_playing(sigrenderer);
+
+	sigrenderer->time_left = TICK_TIME_DIVIDEND / sigrenderer->tempo;
+	sigrenderer->sub_time_left = 0;
+
+	return sigrenderer;
+}
+
+
+
+void dumb_it_set_loop_callback(DUMB_IT_SIGRENDERER *sigrenderer, int (*callback)(void *data), void *data)
+{
+	if (sigrenderer) {
+		sigrenderer->callbacks->loop = callback;
+		sigrenderer->callbacks->loop_data = data;
+	}
+}
+
+
+
+void dumb_it_set_xm_speed_zero_callback(DUMB_IT_SIGRENDERER *sigrenderer, int (*callback)(void *data), void *data)
+{
+	if (sigrenderer) {
+		sigrenderer->callbacks->xm_speed_zero = callback;
+		sigrenderer->callbacks->xm_speed_zero_data = data;
+	}
+}
+
+
+
+void dumb_it_set_midi_callback(DUMB_IT_SIGRENDERER *sigrenderer, int (*callback)(void *data, int channel, unsigned char byte), void *data)
+{
+	if (sigrenderer) {
+		sigrenderer->callbacks->midi = callback;
+		sigrenderer->callbacks->midi_data = data;
+	}
+}
+
+
+
+static IT_CALLBACKS *create_callbacks(void)
+{
+	IT_CALLBACKS *callbacks = (IT_CALLBACKS *)malloc(sizeof(*callbacks));
+	if (!callbacks) return NULL;
+	callbacks->loop = NULL;
+	callbacks->xm_speed_zero = NULL;
+	callbacks->midi = NULL;
+	return callbacks;
+}
+
+
+
+static DUMB_IT_SIGRENDERER *dumb_it_init_sigrenderer(DUMB_IT_SIGDATA *sigdata, int n_channels, int startorder)
+{
+	IT_CALLBACKS *callbacks;
+
+	if (!sigdata) return NULL;
+
+	callbacks = create_callbacks();
+	if (!callbacks) return NULL;
+
+	return init_sigrenderer(sigdata, n_channels, startorder, callbacks,
+		dumb_create_click_remover_array(n_channels));
+}
+
+
+
+DUH_SIGRENDERER *dumb_it_start_at_order(DUH *duh, int n_channels, int startorder)
+{
+	DUMB_IT_SIGDATA *itsd = duh_get_it_sigdata(duh);
+	DUMB_IT_SIGRENDERER *itsr = dumb_it_init_sigrenderer(itsd, n_channels, startorder);
+	return duh_encapsulate_it_sigrenderer(itsr, n_channels, 0);
+}
+
+
+
+static sigrenderer_t *it_start_sigrenderer(DUH *duh, sigdata_t *vsigdata, int n_channels, long pos)
+{
+	DUMB_IT_SIGDATA *sigdata = (DUMB_IT_SIGDATA *)vsigdata;
+	DUMB_IT_SIGRENDERER *sigrenderer;
+
+	(void)duh;
+
+	{
+		IT_CALLBACKS *callbacks = create_callbacks();
+		if (!callbacks) return NULL;
+
+		if (sigdata->checkpoint) {
+			IT_CHECKPOINT *checkpoint = sigdata->checkpoint;
+			while (checkpoint->next && checkpoint->next->time < pos)
+				checkpoint = checkpoint->next;
+			sigrenderer = dup_sigrenderer(checkpoint->sigrenderer, n_channels, callbacks);
+			if (!sigrenderer) return NULL;
+			sigrenderer->click_remover = dumb_create_click_remover_array(n_channels);
+			pos -= checkpoint->time;
+		} else {
+			sigrenderer = init_sigrenderer(sigdata, n_channels, 0, callbacks,
+				dumb_create_click_remover_array(n_channels));
+			if (!sigrenderer) return NULL;
+		}
+	}
+
+	for (;;) {
+		if (sigrenderer->time_left >= pos)
+			break;
+
+		render(sigrenderer, 0, 1.0f, 0, sigrenderer->time_left, NULL);
+
+		pos -= sigrenderer->time_left;
+		sigrenderer->time_left = 0;
+
+		if (process_tick(sigrenderer)) {
+			_dumb_it_end_sigrenderer(sigrenderer);
+			return NULL;
+		}
+	}
+
+	render(sigrenderer, 0, 1.0f, 0, pos, NULL);
+	sigrenderer->time_left -= pos;
+
+	/** WARNING - everything initialised? */
+
+	return sigrenderer;
+}
+
+
+
+static long it_sigrenderer_get_samples(
+	sigrenderer_t *vsigrenderer,
+	float volume, float delta,
+	long size, sample_t **samples
+)
+{
+	DUMB_IT_SIGRENDERER *sigrenderer = (DUMB_IT_SIGRENDERER *)vsigrenderer;
+	long pos;
+	int dt;
+	long todo;
+	LONG_LONG t;
+
+	if (sigrenderer->order < 0) return 0;
+
+	pos = 0;
+	dt = (int)(delta * 65536.0f + 0.5f);
+
+	/* When samples is finally used in render_playing(), it won't be used if
+	 * volume is 0.
+	 */
+	if (!samples) volume = 0;
+
+	for (;;) {
+		todo = (long)((((LONG_LONG)sigrenderer->time_left << 16) | sigrenderer->sub_time_left) / dt);
+
+		if (todo >= size)
+			break;
+
+		render(sigrenderer, volume, delta, pos, todo, samples);
+
+		pos += todo;
+		size -= todo;
+
+		t = sigrenderer->sub_time_left - (LONG_LONG)todo * dt;
+		sigrenderer->sub_time_left = (long)t & 65535;
+		sigrenderer->time_left += (long)(t >> 16);
+
+		if (process_tick(sigrenderer)) {
+			sigrenderer->order = -1;
+			sigrenderer->row = -1;
+			return pos;
+		}
+	}
+
+	render(sigrenderer, volume, delta, pos, size, samples);
+
+	pos += size;
+
+	t = sigrenderer->sub_time_left - (LONG_LONG)size * dt;
+	sigrenderer->sub_time_left = (long)t & 65535;
+	sigrenderer->time_left += (long)(t >> 16);
+
+	dumb_remove_clicks_array(sigrenderer->n_channels, sigrenderer->click_remover, samples, pos, 512.0f / delta);
+
+	return pos;
+}
+
+
+
+static void it_sigrenderer_get_current_sample(sigrenderer_t *vsigrenderer, float volume, sample_t *samples)
+{
+	DUMB_IT_SIGRENDERER *sigrenderer = (DUMB_IT_SIGRENDERER *)vsigrenderer;
+	(void)volume; // for consideration: in any of these such functions, is 'volume' going to be required?
+	dumb_click_remover_get_offset_array(sigrenderer->n_channels, sigrenderer->click_remover, samples);
+}
+
+
+
+void _dumb_it_end_sigrenderer(sigrenderer_t *vsigrenderer)
+{
+	DUMB_IT_SIGRENDERER *sigrenderer = (DUMB_IT_SIGRENDERER *)vsigrenderer;
+
+	int i;
+
+	if (sigrenderer) {
+		for (i = 0; i < DUMB_IT_N_CHANNELS; i++)
+			if (sigrenderer->channel[i].playing)
+				free(sigrenderer->channel[i].playing);
+
+		for (i = 0; i < DUMB_IT_N_NNA_CHANNELS; i++)
+			if (sigrenderer->playing[i])
+				free(sigrenderer->playing[i]);
+
+		dumb_destroy_click_remover_array(sigrenderer->n_channels, sigrenderer->click_remover);
+
+		if (sigrenderer->callbacks)
+			free(sigrenderer->callbacks);
+
+		free(vsigrenderer);
+	}
+}
+
+
+
+DUH_SIGTYPE_DESC _dumb_sigtype_it = {
+	SIGTYPE_IT,
+	NULL,
+	&it_start_sigrenderer,
+	NULL,
+	&it_sigrenderer_get_samples,
+	&it_sigrenderer_get_current_sample,
+	&_dumb_it_end_sigrenderer,
+	&_dumb_it_unload_sigdata
+};
+
+
+
+DUH_SIGRENDERER *duh_encapsulate_it_sigrenderer(DUMB_IT_SIGRENDERER *it_sigrenderer, int n_channels, long pos)
+{
+	return duh_encapsulate_raw_sigrenderer(it_sigrenderer, &_dumb_sigtype_it, n_channels, pos);
+}
+
+
+
+DUMB_IT_SIGRENDERER *duh_get_it_sigrenderer(DUH_SIGRENDERER *sigrenderer)
+{
+	return (DUMB_IT_SIGRENDERER *)duh_get_raw_sigrenderer(sigrenderer, SIGTYPE_IT);
+}
+
+
+
+/* Values of 64 or more will access NNA channels here. */
+void dumb_it_sr_get_channel_state(DUMB_IT_SIGRENDERER *sr, int channel, DUMB_IT_CHANNEL_STATE *state)
+{
+	IT_PLAYING *playing;
+	int t; /* temporary var for holding accurate pan and filter cutoff */
+	float delta;
+	ASSERT(channel < DUMB_IT_TOTAL_CHANNELS);
+	if (!sr) { state->sample = 0; return; }
+	if (channel >= DUMB_IT_N_CHANNELS) {
+		playing = sr->playing[channel - DUMB_IT_N_CHANNELS];
+		if (!playing) { state->sample = 0; return; }
+	} else {
+		playing = sr->channel[channel].playing;
+		if (!playing) { state->sample = 0; return; }
+	}
+
+	if (playing->flags & IT_PLAYING_DEAD) { state->sample = 0; return; }
+
+	state->channel = playing->channel - sr->channel;
+	state->sample = playing->sampnum;
+	state->volume = calculate_volume(sr, playing, 1.0f);
+
+	t = apply_pan_envelope(playing);
+	state->pan = (unsigned char)((t + 128) >> IT_ENVELOPE_SHIFT);
+	state->subpan = (signed char)t;
+
+	delta = playing->delta * 65536.0f;
+	t = playing->filter_cutoff << IT_ENVELOPE_SHIFT;
+	apply_pitch_modifications(sr->sigdata, playing, &delta, &t);
+	state->freq = (int)delta;
+	if (t == 127 << IT_ENVELOPE_SHIFT && playing->filter_resonance == 0) {
+		state->filter_resonance = playing->true_filter_resonance;
+		t = playing->true_filter_cutoff;
+	} else
+		state->filter_resonance = playing->filter_resonance;
+	state->filter_cutoff = (unsigned char)(t >> 8);
+	state->filter_subcutoff = (unsigned char)t;
+}
+
+
+
+int dumb_it_callback_terminate(void *data)
+{
+	(void)data;
+	return 1;
+}
+
+
+
+int dumb_it_callback_midi_block(void *data, int channel, unsigned char byte)
+{
+	(void)data;
+	(void)channel;
+	(void)byte;
+	return 1;
+}
+
+
+
+#define IT_CHECKPOINT_INTERVAL (30 * 65536) /* Half a minute */
+
+
+
+/* Returns the length of the module, up until it first loops. */
+long _dumb_it_build_checkpoints(DUMB_IT_SIGDATA *sigdata)
+{
+	IT_CHECKPOINT *checkpoint = (IT_CHECKPOINT *)malloc(sizeof(*checkpoint));
+	if (!checkpoint) return 0;
+	checkpoint->time = 0;
+	checkpoint->sigrenderer = dumb_it_init_sigrenderer(sigdata, 0, 0);
+	if (!checkpoint->sigrenderer) {
+		free(checkpoint);
+		return 0;
+	}
+	checkpoint->sigrenderer->callbacks->loop = &dumb_it_callback_terminate;
+	checkpoint->sigrenderer->callbacks->xm_speed_zero = &dumb_it_callback_terminate;
+	sigdata->checkpoint = checkpoint;
+
+	for (;;) {
+		long l;
+		DUMB_IT_SIGRENDERER *sigrenderer = dup_sigrenderer(checkpoint->sigrenderer, 0, checkpoint->sigrenderer->callbacks);
+		checkpoint->sigrenderer->callbacks = NULL;
+		if (!sigrenderer) {
+			checkpoint->next = NULL;
+			return checkpoint->time;
+		}
+
+		l = it_sigrenderer_get_samples(sigrenderer, 0, 1.0f, IT_CHECKPOINT_INTERVAL, NULL);
+		if (l < IT_CHECKPOINT_INTERVAL) {
+			_dumb_it_end_sigrenderer(sigrenderer);
+			checkpoint->next = NULL;
+			return checkpoint->time + l;
+		}
+
+		checkpoint->next = (IT_CHECKPOINT *)malloc(sizeof(*checkpoint->next));
+		if (!checkpoint->next) {
+			_dumb_it_end_sigrenderer(sigrenderer);
+			return checkpoint->time + IT_CHECKPOINT_INTERVAL;
+		}
+
+		checkpoint->next->time = checkpoint->time + IT_CHECKPOINT_INTERVAL;
+		checkpoint = checkpoint->next;
+		checkpoint->sigrenderer = sigrenderer;
+	}
+}
+
+} // namespace AGS3
diff --git a/engines/ags/lib/dumb-0.9.2/it/itunload.cpp b/engines/ags/lib/dumb-0.9.2/it/itunload.cpp
new file mode 100644
index 0000000000..d94a9ecac9
--- /dev/null
+++ b/engines/ags/lib/dumb-0.9.2/it/itunload.cpp
@@ -0,0 +1,92 @@
+/* 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.
+ *
+ */
+
+/*  _______         ____    __         ___    ___
+ * \    _  \       \    /  \  /       \   \  /   /       '   '  '
+ *  |  | \  \       |  |    ||         |   \/   |         .      .
+ *  |  |  |  |      |  |    ||         ||\  /|  |
+ *  |  |  |  |      |  |    ||         || \/ |  |         '  '  '
+ *  |  |  |  |      |  |    ||         ||    |  |         .      .
+ *  |  |_/  /        \  \__//          ||    |  |
+ * /_______/ynamic    \____/niversal  /__\  /____\usic   /|  .  . ibliotheque
+ *                                                      /  \
+ *                                                     / .  \
+ * itunload.c - Code to free an Impulse Tracker       / / \  \
+ *              module from memory.                  | <  /   \_
+ *                                                   |  \/ /\   /
+ * By entheh.                                         \_  /  > /
+ *                                                      | \ / /
+ *                                                      |  ' /
+ *                                                       \__/
+ */
+
+#include "ags/lib/dumb-0.9.2/dumb.h"
+#include "ags/lib/dumb-0.9.2/it/it.h"
+
+namespace AGS3 {
+
+void _dumb_it_unload_sigdata(sigdata_t *vsigdata) {
+	if (vsigdata) {
+		DUMB_IT_SIGDATA *sigdata = (DUMB_IT_SIGDATA *)vsigdata;
+		int n;
+
+		if (sigdata->order)
+			free(sigdata->order);
+
+		if (sigdata->instrument)
+			free(sigdata->instrument);
+
+		if (sigdata->sample) {
+			for (n = 0; n < sigdata->n_samples; n++) {
+				if (sigdata->sample[n].left)
+					free(sigdata->sample[n].left);
+				if (sigdata->sample[n].right)
+					free(sigdata->sample[n].right);
+			}
+			free(sigdata->sample);
+		}
+
+		if (sigdata->pattern) {
+			for (n = 0; n < sigdata->n_patterns; n++)
+				if (sigdata->pattern[n].entry)
+					free(sigdata->pattern[n].entry);
+			free(sigdata->pattern);
+		}
+
+		if (sigdata->midi)
+			free(sigdata->midi);
+
+		{
+			IT_CHECKPOINT *checkpoint = sigdata->checkpoint;
+			while (checkpoint) {
+				IT_CHECKPOINT *next = checkpoint->next;
+				_dumb_it_end_sigrenderer(checkpoint->sigrenderer);
+				free(checkpoint);
+				checkpoint = next;
+			}
+		}
+
+		free(vsigdata);
+	}
+}
+
+} // namespace AGS3
diff --git a/engines/ags/lib/std/queue.h b/engines/ags/lib/std/queue.h
index b8846fd8c4..3026295ee5 100644
--- a/engines/ags/lib/std/queue.h
+++ b/engines/ags/lib/std/queue.h
@@ -39,7 +39,7 @@ private:
 	Container _container;
 	Comparitor _comparitor;
 public:
-	priority_queue();
+	priority_queue() {}
 
 	bool empty() const { return _container.empty(); }
 
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 8c278fbe87..af96975957 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -8,6 +8,7 @@ MODULE_OBJS = \
 	lib/aastr-0.1.1/aautil.o \
 	lib/alfont/alfont.o \
 	lib/allegro.o \
+	lib/allegro/colblend.o \
 	lib/allegro/color.o \
 	lib/allegro/config.o \
 	lib/allegro/draw.o \
@@ -17,6 +18,7 @@ MODULE_OBJS = \
 	lib/allegro/gfx.o \
 	lib/allegro/graphics.o \
 	lib/allegro/keyboard.o \
+	lib/allegro/math.o \
 	lib/allegro/mouse.o \
 	lib/allegro/system.o \
 	lib/allegro/unicode.o \
@@ -27,7 +29,12 @@ MODULE_OBJS = \
 	lib/audio/ogg.o \
 	lib/audio/sound.o \
 	lib/audio/wav.o \
+	lib/dumb-0.9.2/dumb.o \
 	lib/dumb-0.9.2/dumbfile.o \
+	lib/dumb-0.9.2/helpers/clickrem.o \
+	lib/dumb-0.9.2/it/itmisc.o \
+	lib/dumb-0.9.2/it/itrender.o \
+	lib/dumb-0.9.2/it/itunload.o \
 	lib/hq2x/hq2x3x.o \
 	lib/opengl/opengl.o \
 	lib/std/std.o \
@@ -246,6 +253,7 @@ MODULE_OBJS = \
 	engine/gfx/gfxdriverbase.o \
 	engine/gfx/gfxdriverfactory.o \
 	engine/gfx/gfxfilter_aad3d.o \
+	engine/gfx/gfxfilter_aaogl.o \
 	engine/gfx/gfxfilter_allegro.o \
 	engine/gfx/gfxfilter_d3d.o \
 	engine/gfx/gfxfilter_hqx.o \


Commit: 1192e1c35350316e87d4f747be2d217932623142
    https://github.com/scummvm/scummvm/commit/1192e1c35350316e87d4f747be2d217932623142
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Add overall main code

Changed paths:
    engines/ags/ags.cpp


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index c5dc3afa71..ad075c5865 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -28,6 +28,296 @@
 #include "common/events.h"
 #include "common/file.h"
 
+#include "ags/shared/core/platform.h"
+#define AGS_PLATFORM_DEFINES_PSP_VARS (AGS_PLATFORM_OS_IOS || AGS_PLATFORM_OS_ANDROID)
+
+#include "ags/lib/std/set.h"
+#include "ags/shared/ac/common.h"
+#include "ags/engine/ac/gamesetup.h"
+#include "ags/engine/ac/gamestate.h"
+#include "ags/shared/core/def_version.h"
+#include "ags/engine/debugging/debugger.h"
+#include "ags/engine/debugging/debug_log.h"
+#include "ags/shared/debugging/out.h"
+#include "ags/engine/main/config.h"
+#include "ags/engine/main/engine.h"
+#include "ags/engine/main/mainheader.h"
+#include "ags/engine/main/main.h"
+#include "ags/engine/platform/base/agsplatformdriver.h"
+#include "ags/engine/ac/route_finder.h"
+#include "ags/shared/core/assetmanager.h"
+#include "ags/shared/util/directory.h"
+#include "ags/shared/util/path.h"
+
+
+namespace AGS3 {
+
+extern char return_to_roomedit[30];
+extern char return_to_room[150];
+
+using namespace Shared;
+using namespace Engine;
+
+String appDirectory; // Needed for library loading
+String cmdGameDataPath;
+
+char **global_argv = nullptr;
+int    global_argc = 0;
+
+extern GameSetup usetup;
+extern GameState play;
+extern int our_eip;
+extern AGSPlatformDriver *platform;
+extern int convert_16bit_bgr;
+extern int editor_debugging_enabled;
+extern int editor_debugging_initialized;
+extern char editor_debugger_instance_token[100];
+
+
+// Startup flags, set from parameters to engine
+int force_window = 0;
+int override_start_room = 0;
+bool justDisplayHelp = false;
+bool justDisplayVersion = false;
+bool justRunSetup = false;
+bool justRegisterGame = false;
+bool justUnRegisterGame = false;
+bool justTellInfo = false;
+std::set<String> tellInfoKeys;
+const char *loadSaveGameOnStartup = nullptr;
+
+#if ! AGS_PLATFORM_DEFINES_PSP_VARS
+int psp_video_framedrop = 1;
+int psp_audio_enabled = 1;
+int psp_midi_enabled = 1;
+int psp_ignore_acsetup_cfg_file = 0;
+int psp_clear_cache_on_room_change = 0;
+
+int psp_midi_preload_patches = 0;
+int psp_audio_cachesize = 10;
+char psp_game_file_name[] = "";
+char psp_translation[] = "default";
+
+int psp_gfx_renderer = 0;
+int psp_gfx_scaling = 1;
+int psp_gfx_smoothing = 0;
+int psp_gfx_super_sampling = 1;
+int psp_gfx_smooth_sprites = 0;
+#endif
+
+// this needs to be updated if the "play" struct changes
+#define SVG_VERSION_BWCOMPAT_MAJOR      3
+#define SVG_VERSION_BWCOMPAT_MINOR      2
+#define SVG_VERSION_BWCOMPAT_RELEASE    0
+#define SVG_VERSION_BWCOMPAT_REVISION   1103
+// CHECKME: we may lower this down, if we find that earlier versions may still
+// load new savedgames
+#define SVG_VERSION_FWCOMPAT_MAJOR      3
+#define SVG_VERSION_FWCOMPAT_MINOR      2
+#define SVG_VERSION_FWCOMPAT_RELEASE    1
+#define SVG_VERSION_FWCOMPAT_REVISION   1111
+
+// Current engine version
+Version EngineVersion;
+// Lowest savedgame version, accepted by this engine
+Version SavedgameLowestBackwardCompatVersion;
+// Lowest engine version, which would accept current savedgames
+Version SavedgameLowestForwardCompatVersion;
+
+
+void main_pre_init() {
+	our_eip = -999;
+	Shared::AssetManager::SetSearchPriority(Shared::kAssetPriorityDir);
+	play.takeover_data = 0;
+}
+
+void main_create_platform_driver() {
+	platform = AGSPlatformDriver::GetDriver();
+}
+
+void main_init(int argc, char *argv[]) {
+	EngineVersion = Version(ACI_VERSION_STR " " SPECIAL_VERSION);
+
+	SavedgameLowestBackwardCompatVersion = Version(SVG_VERSION_BWCOMPAT_MAJOR, SVG_VERSION_BWCOMPAT_MINOR, SVG_VERSION_BWCOMPAT_RELEASE, SVG_VERSION_BWCOMPAT_REVISION);
+	SavedgameLowestForwardCompatVersion = Version(SVG_VERSION_FWCOMPAT_MAJOR, SVG_VERSION_FWCOMPAT_MINOR, SVG_VERSION_FWCOMPAT_RELEASE, SVG_VERSION_FWCOMPAT_REVISION);
+
+	Shared::AssetManager::CreateInstance();
+	main_pre_init();
+	main_create_platform_driver();
+
+	global_argv = argv;
+	global_argc = argc;
+}
+
+String get_engine_string() {
+	return String::FromFormat("Adventure Game Studio v%s Interpreter\n"
+		"Copyright (c) 1999-2011 Chris Jones and " ACI_COPYRIGHT_YEARS " others\n"
+		"ACI version %s\n", EngineVersion.ShortString.GetCStr(), EngineVersion.LongString.GetCStr());
+}
+
+void main_print_help() {
+	// No implementation
+}
+
+static int main_process_cmdline(ConfigTree &cfg, int argc, char *argv[]) {
+	int datafile_argv = 0;
+	for (int ee = 1; ee < argc; ++ee) {
+		const char *arg = argv[ee];
+		//
+		// Startup options
+		//
+		if (scumm_stricmp(arg, "--help") == 0 || scumm_stricmp(arg, "/?") == 0 || scumm_stricmp(arg, "-?") == 0) {
+			justDisplayHelp = true;
+			return 0;
+		}
+		if (scumm_stricmp(arg, "-v") == 0 || scumm_stricmp(arg, "--version") == 0) {
+			justDisplayVersion = true;
+			return 0;
+		} else if (scumm_stricmp(arg, "-updatereg") == 0)
+			debug_flags |= DBG_REGONLY;
+#if AGS_PLATFORM_DEBUG
+		else if ((scumm_stricmp(arg, "--startr") == 0) && (ee < argc - 1)) {
+			override_start_room = atoi(argv[ee + 1]);
+			ee++;
+		}
+#endif
+		else if ((scumm_stricmp(arg, "--testre") == 0) && (ee < argc - 2)) {
+			strcpy(return_to_roomedit, argv[ee + 1]);
+			strcpy(return_to_room, argv[ee + 2]);
+			ee += 2;
+		} else if (scumm_stricmp(arg, "-noexceptionhandler") == 0) usetup.disable_exception_handling = true;
+		else if (scumm_stricmp(arg, "--setup") == 0) {
+			justRunSetup = true;
+		} else if (scumm_stricmp(arg, "-registergame") == 0) {
+			justRegisterGame = true;
+		} else if (scumm_stricmp(arg, "-unregistergame") == 0) {
+			justUnRegisterGame = true;
+		} else if ((scumm_stricmp(arg, "-loadsavedgame") == 0) && (argc > ee + 1)) {
+			loadSaveGameOnStartup = argv[ee + 1];
+			ee++;
+		} else if ((scumm_stricmp(arg, "--enabledebugger") == 0) && (argc > ee + 1)) {
+			strcpy(editor_debugger_instance_token, argv[ee + 1]);
+			editor_debugging_enabled = 1;
+			force_window = 1;
+			ee++;
+		} else if (scumm_stricmp(arg, "--runfromide") == 0 && (argc > ee + 3)) {
+			usetup.install_dir = argv[ee + 1];
+			usetup.install_audio_dir = argv[ee + 2];
+			usetup.install_voice_dir = argv[ee + 3];
+			ee += 3;
+		} else if (scumm_stricmp(arg, "--takeover") == 0) {
+			if (argc < ee + 2)
+				break;
+			play.takeover_data = atoi(argv[ee + 1]);
+			strncpy(play.takeover_from, argv[ee + 2], 49);
+			play.takeover_from[49] = 0;
+			ee += 2;
+		} else if (scumm_strnicmp(arg, "--tell", 6) == 0) {
+			if (arg[6] == 0)
+				tellInfoKeys.insert(String("all"));
+			else if (arg[6] == '-' && arg[7] != 0)
+				tellInfoKeys.insert(String(arg + 7));
+		}
+		//
+		// Config overrides
+		//
+		else if (scumm_stricmp(arg, "-windowed") == 0 || scumm_stricmp(arg, "--windowed") == 0)
+			force_window = 1;
+		else if (scumm_stricmp(arg, "-fullscreen") == 0 || scumm_stricmp(arg, "--fullscreen") == 0)
+			force_window = 2;
+		else if ((scumm_stricmp(arg, "-gfxdriver") == 0 || scumm_stricmp(arg, "--gfxdriver") == 0) && (argc > ee + 1)) {
+			INIwritestring(cfg, "graphics", "driver", argv[++ee]);
+		} else if ((scumm_stricmp(arg, "-gfxfilter") == 0 || scumm_stricmp(arg, "--gfxfilter") == 0) && (argc > ee + 1)) {
+			// NOTE: we make an assumption here that if user provides scaling factor,
+			// this factor means to be applied to windowed mode only.
+			INIwritestring(cfg, "graphics", "filter", argv[++ee]);
+			if (argc > ee + 1 && argv[ee + 1][0] != '-')
+				INIwritestring(cfg, "graphics", "game_scale_win", argv[++ee]);
+			else
+				INIwritestring(cfg, "graphics", "game_scale_win", "max_round");
+		} else if (scumm_stricmp(arg, "--fps") == 0) display_fps = kFPS_Forced;
+		else if (scumm_stricmp(arg, "--test") == 0) debug_flags |= DBG_DEBUGMODE;
+		else if (scumm_stricmp(arg, "-noiface") == 0) debug_flags |= DBG_NOIFACE;
+		else if (scumm_stricmp(arg, "-nosprdisp") == 0) debug_flags |= DBG_NODRAWSPRITES;
+		else if (scumm_stricmp(arg, "-nospr") == 0) debug_flags |= DBG_NOOBJECTS;
+		else if (scumm_stricmp(arg, "-noupdate") == 0) debug_flags |= DBG_NOUPDATE;
+		else if (scumm_stricmp(arg, "-nosound") == 0) debug_flags |= DBG_NOSFX;
+		else if (scumm_stricmp(arg, "-nomusic") == 0) debug_flags |= DBG_NOMUSIC;
+		else if (scumm_stricmp(arg, "-noscript") == 0) debug_flags |= DBG_NOSCRIPT;
+		else if (scumm_stricmp(arg, "-novideo") == 0) debug_flags |= DBG_NOVIDEO;
+		else if (scumm_stricmp(arg, "-dbgscript") == 0) debug_flags |= DBG_DBGSCRIPT;
+		else if (scumm_stricmp(arg, "--log") == 0) INIwriteint(cfg, "misc", "log", 1);
+		else if (scumm_stricmp(arg, "--no-log") == 0) INIwriteint(cfg, "misc", "log", 0);
+		//
+		// Special case: data file location
+		//
+		else if (arg[0] != '-') datafile_argv = ee;
+	}
+
+	if (datafile_argv > 0) {
+		cmdGameDataPath = GetPathFromCmdArg(datafile_argv);
+	} else {
+		// assign standard path for mobile/consoles (defined in their own platform implementation)
+		cmdGameDataPath = psp_game_file_name;
+	}
+
+	if (!tellInfoKeys.empty())
+		justTellInfo = true;
+
+	return 0;
+}
+
+void main_set_gamedir(int argc, char *argv[]) {
+	appDirectory = Path::GetDirectoryPath(GetPathFromCmdArg(0));
+
+	if ((loadSaveGameOnStartup != nullptr) && (argv[0] != nullptr)) {
+		// When launched by double-clicking a save game file, the curdir will
+		// be the save game folder unless we correct it
+		Directory::SetCurrentDirectory(appDirectory);
+	} else {
+		// It looks like Allegro library does not like ANSI (ACP) paths.
+		// When *not* working in U_UNICODE filepath mode, whenever it gets
+		// current directory for its own operations, it "fixes" it by
+		// substituting non-ASCII symbols with '^'.
+		// Here we explicitly set current directory to ASCII path.
+		String cur_dir = Directory::GetCurrentDirectory();
+		String path = Path::GetPathInASCII(cur_dir);
+		if (!path.IsEmpty())
+			Directory::SetCurrentDirectory(Path::MakeAbsolutePath(path));
+		else
+			Debug::Printf(kDbgMsg_Error, "Unable to determine current directory: GetPathInASCII failed.\nArg: %s", cur_dir.GetCStr());
+	}
+}
+
+String GetPathFromCmdArg(int arg_index) {
+	if (arg_index < 0 || arg_index >= global_argc)
+		return "";
+	String path = Path::GetCmdLinePathInASCII(global_argv[arg_index], arg_index);
+	if (!path.IsEmpty())
+		return Path::MakeAbsolutePath(path);
+	Debug::Printf(kDbgMsg_Error, "Unable to determine path: GetCmdLinePathInASCII failed.\nCommand line argument %i: %s", arg_index, global_argv[arg_index]);
+	return global_argv[arg_index];
+}
+
+const char *get_allegro_error() {
+	return "ERROR"; // allegro_error;
+}
+
+#define ALLEGRO_ERROR_SIZE 256
+char allegro_error[ALLEGRO_ERROR_SIZE];
+
+const char *set_allegro_error(const char *format, ...) {
+	va_list argptr;
+	va_start(argptr, format);
+	Common::String msg = Common::String::format(format, argptr);
+	strncpy(allegro_error, msg.c_str(), ALLEGRO_ERROR_SIZE);
+
+	va_end(argptr);
+	return allegro_error;
+}
+
+} // namespace AGS3
+
 namespace AGS {
 
 AGSEngine *g_vm;
@@ -49,6 +339,63 @@ uint32 AGSEngine::getFeatures() const {
 }
 
 Common::Error AGSEngine::run() {
+	char exeName[16], gameName[16];
+	strcpy(exeName, "scummvm.exe");
+	strcpy(gameName, "bc.exe");
+	int argc = 3;
+	char *argv[] = { exeName, gameName };
+
+#ifdef AGS_RUN_TESTS
+	Test_DoAllTests();
+#endif
+	AGS3::main_init(argc, argv);
+
+#if AGS_PLATFORM_OS_WINDOWS
+	setup_malloc_handling();
+#endif
+	AGS3::debug_flags = 0;
+
+	AGS3::ConfigTree startup_opts;
+	int res = AGS3::main_process_cmdline(startup_opts, argc, argv);
+	if (res != 0)
+		return Common::kUnknownError;
+
+	if (AGS3::justDisplayVersion) {
+		AGS3::platform->WriteStdOut(AGS3::get_engine_string());
+		return Common::kNoError;
+	}
+
+	if (AGS3::justDisplayHelp) {
+		AGS3::main_print_help();
+		return Common::kNoError;
+	}
+
+	if (!AGS3::justTellInfo)
+		AGS3::platform->SetGUIMode(true);
+	AGS3::init_debug(startup_opts, AGS3::justTellInfo);
+	AGS3::Debug::Printf("%s", AGS3::get_engine_string().GetNullableCStr());
+
+	AGS3::main_set_gamedir(argc, argv);
+
+	// Update shell associations and exit
+	if (AGS3::debug_flags & DBG_REGONLY)
+		return Common::kNoError;
+
+#ifdef USE_CUSTOM_EXCEPTION_HANDLER
+	if (usetup.disable_exception_handling)
+#endif
+	{
+		int result = AGS3::initialize_engine(startup_opts);
+		// TODO: refactor engine shutdown routine (must shutdown and delete everything started and created)
+		AGS3::platform->PostAllegroExit();
+		return result ? Common::kUnknownError : Common::kNoError;
+	}
+#ifdef USE_CUSTOM_EXCEPTION_HANDLER
+	else {
+		return initialize_engine_with_exception_handling(initialize_engine, startup_opts);
+	}
+#endif
+
 	return Common::kNoError;
 }
 


Commit: 8c72948dee337e35b00ee7b5263f137e54f63cb1
    https://github.com/scummvm/scummvm/commit/8c72948dee337e35b00ee7b5263f137e54f63cb1
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix global objects crashing ScummVM on startup

Changed paths:
    engines/ags/ags.h
    engines/ags/engine/ac/timer.cpp
    engines/ags/engine/main/game_run.cpp
    engines/ags/engine/media/audio/audio.cpp
    engines/ags/engine/media/audio/audio.h
    engines/ags/engine/media/audio/clip_mymp3.cpp
    engines/ags/engine/media/audio/clip_mymp3.h
    engines/ags/engine/media/audio/clip_mystaticmp3.cpp
    engines/ags/engine/media/audio/clip_mystaticmp3.h
    engines/ags/engine/media/audio/sound.cpp
    engines/ags/engine/media/audio/soundcache.cpp
    engines/ags/lib/std/thread.h


diff --git a/engines/ags/ags.h b/engines/ags/ags.h
index 6e947b7c63..5099d68c83 100644
--- a/engines/ags/ags.h
+++ b/engines/ags/ags.h
@@ -35,6 +35,7 @@
 
 #include "ags/shared/gfx/bitmap.h"
 #include "ags/lib/allegro/system.h"
+#include "ags/engine/util/mutex_std.h"
 
 namespace AGS {
 
@@ -55,6 +56,9 @@ private:
 public:
 	::AGS3::BITMAP *_screen;
 	::AGS3::GFX_DRIVER *_gfxDriver;
+	::AGS3::AGS::Engine::Mutex _sMutex;
+	::AGS3::AGS::Engine::Mutex _soundCacheMutex;
+	::AGS3::AGS::Engine::Mutex _mp3Mutex;
 protected:
 	// Engine APIs
 	virtual Common::Error run();
diff --git a/engines/ags/engine/ac/timer.cpp b/engines/ags/engine/ac/timer.cpp
index 5eb0e31c3f..5f26a9c5af 100644
--- a/engines/ags/engine/ac/timer.cpp
+++ b/engines/ags/engine/ac/timer.cpp
@@ -40,8 +40,8 @@ const auto MAXIMUM_FALL_BEHIND = 3;
 auto tick_duration = std::chrono::microseconds(1000000LL / 40);
 auto framerate_maxed = false;
 
-auto last_tick_time = AGS_Clock::now();
-auto next_frame_timestamp = AGS_Clock::now();
+uint32 last_tick_time = 0; // AGS_Clock::now();
+uint32 next_frame_timestamp = 0; // AGS_Clock::now();
 
 }
 
diff --git a/engines/ags/engine/main/game_run.cpp b/engines/ags/engine/main/game_run.cpp
index a695db97ac..1e82cc4714 100644
--- a/engines/ags/engine/main/game_run.cpp
+++ b/engines/ags/engine/main/game_run.cpp
@@ -102,7 +102,7 @@ extern int cur_mode, cur_cursor;
 static int ShouldStayInWaitMode();
 
 static int numEventsAtStartOfFunction;
-static auto t1 = AGS_Clock::now();  // timer for FPS // ... 't1'... how very appropriate.. :)
+static uint32 t1 = 0; // AGS_Clock::now();  // timer for FPS // ... 't1'... how very appropriate.. :)
 
 #define UNTIL_ANIMEND   1
 #define UNTIL_MOVEEND   2
diff --git a/engines/ags/engine/media/audio/audio.cpp b/engines/ags/engine/media/audio/audio.cpp
index 0d4ca41d3b..954f229278 100644
--- a/engines/ags/engine/media/audio/audio.cpp
+++ b/engines/ags/engine/media/audio/audio.cpp
@@ -44,6 +44,7 @@
 #include "ags/engine/ac/timer.h"
 #include "ags/engine/main/game_run.h"
 #include "ags/lib/audio/sound.h"
+#include "ags/ags.h"
 
 namespace AGS3 {
 
@@ -54,7 +55,9 @@ using namespace AGS::Engine;
 //sound channel management; all access goes through here, which can't be done without a lock
 
 static std::array<SOUNDCLIP *> _channels(MAX_SOUND_CHANNELS + 1);
-AGS::Engine::Mutex AudioChannelsLock::s_mutex;
+
+AudioChannelsLock::AudioChannelsLock() : MutexLock(::AGS::g_vm->_sMutex) {
+}
 
 SOUNDCLIP *AudioChannelsLock::GetChannel(int index) {
 	return _channels[index];
@@ -731,7 +734,7 @@ SOUNDCLIP *cachedQueuedMusic = nullptr;
 // Music update is scheduled when the voice speech stops;
 // we do a small delay before reverting any volume adjustments
 static bool music_update_scheduled = false;
-static auto music_update_at = AGS_Clock::now();
+static uint32 music_update_at = 0; // AGS_Clock::now();
 
 void cancel_scheduled_music_update() {
 	music_update_scheduled = false;
diff --git a/engines/ags/engine/media/audio/audio.h b/engines/ags/engine/media/audio/audio.h
index 192de3246e..ec12575e5e 100644
--- a/engines/ags/engine/media/audio/audio.h
+++ b/engines/ags/engine/media/audio/audio.h
@@ -48,10 +48,7 @@ private:
 	AudioChannelsLock &operator=(AudioChannelsLock const &); // not copy-assignable
 
 public:
-	static AGS::Engine::Mutex s_mutex;
-	AudioChannelsLock()
-		: MutexLock(s_mutex) {
-	}
+	AudioChannelsLock();
 
 	// Gets a clip from the channel
 	SOUNDCLIP *GetChannel(int index);
diff --git a/engines/ags/engine/media/audio/clip_mymp3.cpp b/engines/ags/engine/media/audio/clip_mymp3.cpp
index 66e9674d3d..ce87812b46 100644
--- a/engines/ags/engine/media/audio/clip_mymp3.cpp
+++ b/engines/ags/engine/media/audio/clip_mymp3.cpp
@@ -29,8 +29,8 @@
 #include "ags/shared/ac/common.h"               // quit()
 #include "ags/engine/ac/asset_helper.h"
 #include "ags/engine/util/mutex_lock.h"
-
 #include "ags/engine/platform/base/agsplatformdriver.h"
+#include "ags/ags.h"
 
 namespace AGS3 {
 
@@ -42,7 +42,7 @@ void MYMP3::poll() {
 	// update the buffer
 	char *tempbuf = nullptr;
 	{
-		AGS::Engine::MutexLock _lockMp3(_mp3_mutex);
+		AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
 		tempbuf = (char *)almp3_get_mp3stream_buffer(stream);
 	}
 
@@ -56,13 +56,13 @@ void MYMP3::poll() {
 		pack_fread(tempbuf, chunksize, in);
 
 		{
-			AGS::Engine::MutexLock _lockMp3(_mp3_mutex);
+			AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
 			almp3_free_mp3stream_buffer(stream, free_val);
 		}
 	}
 #endif
 	{
-		AGS::Engine::MutexLock _lockMp3(_mp3_mutex);
+		AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
 		if (almp3_poll_mp3stream(stream) == ALMP3_POLL_PLAYJUSTFINISHED) {
 			state_ = SoundClipStopped;
 		}
@@ -73,7 +73,7 @@ void MYMP3::adjust_stream() {
 	if (!is_playing()) {
 		return;
 	}
-	AGS::Engine::MutexLock _lockMp3(_mp3_mutex);
+	AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
 	almp3_adjust_mp3stream(stream, get_final_volume(), panning, speed);
 }
 
@@ -98,7 +98,7 @@ void MYMP3::set_speed(int new_speed) {
 
 void MYMP3::destroy() {
 	if (stream) {
-		AGS::Engine::MutexLock _lockMp3(_mp3_mutex);
+		AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
 		almp3_stop_mp3stream(stream);
 		almp3_destroy_mp3stream(stream);
 	}
@@ -129,7 +129,7 @@ int MYMP3::get_pos_ms() {
 	if (!is_playing()) {
 		return -1;
 	}
-	AGS::Engine::MutexLock _lockMp3(_mp3_mutex);
+	AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
 	return almp3_get_pos_msecs_mp3stream(stream);
 }
 
@@ -137,7 +137,7 @@ int MYMP3::get_length_ms() {
 	if (!is_playing()) {
 		return -1;
 	}
-	AGS::Engine::MutexLock _lockMp3(_mp3_mutex);
+	AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
 	return almp3_get_length_msecs_mp3stream(stream, filesize);
 }
 
@@ -145,7 +145,7 @@ int MYMP3::get_voice() {
 	if (!is_playing()) {
 		return -1;
 	}
-	AGS::Engine::MutexLock _lockMp3(_mp3_mutex);
+	AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
 	AUDIOSTREAM *ast = almp3_get_audiostream_mp3stream(stream);
 	return (ast != nullptr ? ast->voice : -1);
 }
@@ -160,7 +160,7 @@ int MYMP3::play() {
 	}
 
 	{
-		AGS::Engine::MutexLock _lockMp3(_mp3_mutex);
+		AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
 		if (almp3_play_mp3stream(stream, chunksize, (vol > 230) ? vol : vol + 20, panning) != ALMP3_OK) {
 			return 0;
 		}
diff --git a/engines/ags/engine/media/audio/clip_mymp3.h b/engines/ags/engine/media/audio/clip_mymp3.h
index 787bd5a3f3..148799b015 100644
--- a/engines/ags/engine/media/audio/clip_mymp3.h
+++ b/engines/ags/engine/media/audio/clip_mymp3.h
@@ -29,8 +29,6 @@
 
 namespace AGS3 {
 
-extern AGS::Engine::Mutex _mp3_mutex;
-
 struct MYMP3 : public SOUNDCLIP {
 	ALMP3_MP3STREAM *stream;
 	PACKFILE *in;
diff --git a/engines/ags/engine/media/audio/clip_mystaticmp3.cpp b/engines/ags/engine/media/audio/clip_mystaticmp3.cpp
index 9f27f55461..65ae8b3ef6 100644
--- a/engines/ags/engine/media/audio/clip_mystaticmp3.cpp
+++ b/engines/ags/engine/media/audio/clip_mystaticmp3.cpp
@@ -28,17 +28,13 @@
 #include "ags/engine/media/audio/audiointernaldefs.h"
 #include "ags/engine/media/audio/soundcache.h"
 #include "ags/engine/util/mutex_lock.h"
-
 #include "ags/engine/platform/base/agsplatformdriver.h"
+#include "ags/ags.h"
 
 namespace AGS3 {
 
 extern int our_eip;
 
-// ALMP3 functions are not reentrant! This mutex should be locked before calling any
-// of the mp3 functions and unlocked afterwards.
-AGS::Engine::Mutex _mp3_mutex;
-
 void MYSTATICMP3::poll() {
 	if (state_ != SoundClipPlaying) {
 		return;
@@ -47,7 +43,7 @@ void MYSTATICMP3::poll() {
 	int oldeip = our_eip;
 	our_eip = 5997;
 
-	AGS::Engine::MutexLock _lockMp3(_mp3_mutex);
+	AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
 	int result = almp3_poll_mp3(tune);
 
 	if (result == ALMP3_POLL_PLAYJUSTFINISHED) {
@@ -62,7 +58,7 @@ void MYSTATICMP3::adjust_stream() {
 	if (!is_playing()) {
 		return;
 	}
-	AGS::Engine::MutexLock _lockMp3(_mp3_mutex);
+	AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
 	almp3_adjust_mp3(tune, get_final_volume(), panning, speed, repeat);
 }
 
@@ -82,7 +78,7 @@ void MYSTATICMP3::set_speed(int new_speed) {
 
 void MYSTATICMP3::destroy() {
 	if (tune) {
-		AGS::Engine::MutexLock _lockMp3(_mp3_mutex);
+		AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
 		almp3_stop_mp3(tune);
 		almp3_destroy_mp3(tune);
 	}
@@ -100,7 +96,7 @@ void MYSTATICMP3::seek(int pos) {
 	if (!is_playing()) {
 		return;
 	}
-	AGS::Engine::MutexLock _lockMp3(_mp3_mutex);
+	AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
 	almp3_seek_abs_msecs_mp3(tune, pos);
 }
 
@@ -108,7 +104,7 @@ int MYSTATICMP3::get_pos() {
 	if (!is_playing()) {
 		return -1;
 	}
-	AGS::Engine::MutexLock _lockMp3(_mp3_mutex);
+	AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
 	return almp3_get_pos_msecs_mp3(tune);
 }
 
@@ -121,7 +117,7 @@ int MYSTATICMP3::get_length_ms() {
 	if (tune == nullptr) {
 		return -1;
 	}
-	AGS::Engine::MutexLock _lockMp3(_mp3_mutex);
+	AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
 	return almp3_get_length_msecs_mp3(tune);
 }
 
@@ -129,7 +125,7 @@ int MYSTATICMP3::get_voice() {
 	if (!is_playing()) {
 		return -1;
 	}
-	AGS::Engine::MutexLock _lockMp3(_mp3_mutex);
+	AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
 	AUDIOSTREAM *ast = almp3_get_audiostream_mp3(tune);
 	return (ast != nullptr ? ast->voice : -1);
 }
@@ -144,7 +140,7 @@ int MYSTATICMP3::play() {
 	}
 
 	{
-		AGS::Engine::MutexLock _lockMp3(_mp3_mutex);
+		AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
 		int result = almp3_play_ex_mp3(tune, 16384, vol, panning, 1000, repeat);
 		if (result != ALMP3_OK) {
 			return 0;
diff --git a/engines/ags/engine/media/audio/clip_mystaticmp3.h b/engines/ags/engine/media/audio/clip_mystaticmp3.h
index c849a1803b..575df1583b 100644
--- a/engines/ags/engine/media/audio/clip_mystaticmp3.h
+++ b/engines/ags/engine/media/audio/clip_mystaticmp3.h
@@ -28,8 +28,6 @@
 
 namespace AGS3 {
 
-extern AGS::Engine::Mutex _mp3_mutex;
-
 // pre-loaded (non-streaming) MP3 file
 struct MYSTATICMP3 : public SOUNDCLIP {
 	ALMP3_MP3 *tune;
diff --git a/engines/ags/engine/media/audio/sound.cpp b/engines/ags/engine/media/audio/sound.cpp
index f92ab6683d..98134b9456 100644
--- a/engines/ags/engine/media/audio/sound.cpp
+++ b/engines/ags/engine/media/audio/sound.cpp
@@ -50,6 +50,7 @@
 #endif
 #include "ags/engine/media/audio/soundcache.h"
 #include "ags/engine/util/mutex_lock.h"
+#include "ags/ags.h"
 
 namespace AGS3 {
 
@@ -117,7 +118,7 @@ SOUNDCLIP *my_load_mp3(const AssetPath &asset_name, int voll) {
 	thistune->buffer = (char *)tmpbuffer;
 
 	{
-		AGS::Engine::MutexLock _lockMp3(_mp3_mutex);
+		AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
 		thistune->stream = almp3_create_mp3stream(tmpbuffer, thistune->chunksize, (thistune->filesize < 1));
 	}
 
@@ -152,7 +153,7 @@ SOUNDCLIP *my_load_static_mp3(const AssetPath &asset_name, int voll, bool loop)
 	thismp3->repeat = loop;
 
 	{
-		AGS::Engine::MutexLock _lockMp3(_mp3_mutex);
+		AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
 		thismp3->tune = almp3_create_mp3(mp3buffer, muslen);
 	}
 
diff --git a/engines/ags/engine/media/audio/soundcache.cpp b/engines/ags/engine/media/audio/soundcache.cpp
index 81eb9737a7..84865d61a3 100644
--- a/engines/ags/engine/media/audio/soundcache.cpp
+++ b/engines/ags/engine/media/audio/soundcache.cpp
@@ -30,6 +30,7 @@
 #include "ags/engine/util/mutex_lock.h"
 #include "ags/shared/util/string.h"
 #include "ags/shared/debugging/out.h"
+#include "ags/ags.h"
 
 namespace AGS3 {
 
@@ -38,11 +39,8 @@ using namespace Shared;
 sound_cache_entry_t *sound_cache_entries = nullptr;
 unsigned int sound_cache_counter = 0;
 
-AGS::Engine::Mutex _sound_cache_mutex;
-
-
 void clear_sound_cache() {
-	AGS::Engine::MutexLock _lock(_sound_cache_mutex);
+	AGS::Engine::MutexLock _lock(::AGS::g_vm->_soundCacheMutex);
 
 	if (sound_cache_entries) {
 		int i;
@@ -62,7 +60,7 @@ void clear_sound_cache() {
 }
 
 void sound_cache_free(char *buffer, bool is_wave) {
-	AGS::Engine::MutexLock _lock(_sound_cache_mutex);
+	AGS::Engine::MutexLock _lock(::AGS::g_vm->_soundCacheMutex);
 
 #ifdef SOUND_CACHE_DEBUG
 	Debug::Printf("sound_cache_free(%p %d)\n", buffer, (unsigned int)is_wave);
@@ -95,7 +93,7 @@ void sound_cache_free(char *buffer, bool is_wave) {
 
 
 char *get_cached_sound(const AssetPath &asset_name, bool is_wave, size_t &size) {
-	AGS::Engine::MutexLock _lock(_sound_cache_mutex);
+	AGS::Engine::MutexLock _lock(::AGS::g_vm->_soundCacheMutex);
 
 #ifdef SOUND_CACHE_DEBUG
 	Debug::Printf("get_cached_sound(%s %d)\n", asset_name.first.GetCStr(), (unsigned int)is_wave);
diff --git a/engines/ags/lib/std/thread.h b/engines/ags/lib/std/thread.h
index bdd43e6cf7..3577b7747d 100644
--- a/engines/ags/lib/std/thread.h
+++ b/engines/ags/lib/std/thread.h
@@ -44,8 +44,8 @@ public:
 		warning("TODO: thread::join");
 	}
 	bool joinable() const {
-		warning("TODO: thread::joinable");
-		return true;
+		// TODO: thread::joinable
+		return false;
 	}
 };
 


Commit: c9351d3a8d3f7c8ceda16e63137644e3ba17b965
    https://github.com/scummvm/scummvm/commit/c9351d3a8d3f7c8ceda16e63137644e3ba17b965
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Remove mistake settings from configure.engine

Changed paths:
    engines/ags/configure.engine


diff --git a/engines/ags/configure.engine b/engines/ags/configure.engine
index 6149895b71..55cba93bb4 100644
--- a/engines/ags/configure.engine
+++ b/engines/ags/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 ags "Adventure Game Studio" no "" "" "cxx11 mp3 ogg"
+add_engine ags "Adventure Game Studio" no "" "" "cxx11"


Commit: 75183a5a03b32c291c2ef8efa7e4071ec12af96a
    https://github.com/scummvm/scummvm/commit/75183a5a03b32c291c2ef8efa7e4071ec12af96a
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: gcc compilation fixes

Changed paths:
    engines/ags/engine/ac/dynobj/cc_character.cpp
    engines/ags/engine/ac/route_finder_impl_legacy.cpp
    engines/ags/engine/ac/scriptcontainers.cpp
    engines/ags/engine/ac/timer.cpp
    engines/ags/lib/allegro/color.cpp
    engines/ags/lib/dumb-0.9.2/it/itrender.cpp
    engines/ags/lib/std/type_traits.h
    engines/ags/shared/ac/dynobj/scriptaudioclip.h
    engines/ags/shared/font/fonts.cpp
    engines/ags/shared/font/ttffontrenderer.h
    engines/ags/shared/font/wfnfont.cpp
    engines/ags/shared/font/wfnfontrenderer.h


diff --git a/engines/ags/engine/ac/dynobj/cc_character.cpp b/engines/ags/engine/ac/dynobj/cc_character.cpp
index c114d94801..3aacebafae 100644
--- a/engines/ags/engine/ac/dynobj/cc_character.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_character.cpp
@@ -58,7 +58,7 @@ void CCCharacter::WriteInt16(const char *address, intptr_t offset, int16_t val)
 	// inventory for older games that reply on the previous behaviour.
 	if (loaded_game_file_version < kGameVersion_270) {
 		const int invoffset = 112;
-		if (offset >= invoffset && offset < (invoffset + MAX_INV * sizeof(short))) {
+		if (offset >= invoffset && (int)offset < (invoffset + MAX_INV * sizeof(short))) {
 			update_invorder();
 		}
 	}
diff --git a/engines/ags/engine/ac/route_finder_impl_legacy.cpp b/engines/ags/engine/ac/route_finder_impl_legacy.cpp
index 067900745e..b0d6782ffd 100644
--- a/engines/ags/engine/ac/route_finder_impl_legacy.cpp
+++ b/engines/ags/engine/ac/route_finder_impl_legacy.cpp
@@ -801,7 +801,7 @@ int find_route(short srcx, short srcy, short xx, short yy, Bitmap *onscreen, int
 		numstages++;
 		nearestindx = -1;
 
-		int lastpbs = pathbackstage;
+//		int lastpbs = pathbackstage;
 
 stage_again:
 		nearestpos = 0;
@@ -835,7 +835,7 @@ stage_again:
 #ifdef DEBUG_PATHFINDER
 			AGS::Shared::Debug::Printf("Added: %d, %d pbs:%d", srcx, srcy, pathbackstage);
 #endif
-			lastpbs = pathbackstage;
+//			lastpbs = pathbackstage;
 			pathbackstage = nearestindx;
 			goto stage_again;
 		}
diff --git a/engines/ags/engine/ac/scriptcontainers.cpp b/engines/ags/engine/ac/scriptcontainers.cpp
index e67e3a1ed3..d079ec312e 100644
--- a/engines/ags/engine/ac/scriptcontainers.cpp
+++ b/engines/ags/engine/ac/scriptcontainers.cpp
@@ -71,7 +71,7 @@ ScriptDictBase *Dict_Create(bool sorted, bool case_sensitive) {
 
 // TODO: we need memory streams
 ScriptDictBase *Dict_Unserialize(int index, const char *serializedData, int dataSize) {
-	if (dataSize < sizeof(int32_t) * 2)
+	if (dataSize < (int)sizeof(int32_t) * 2)
 		quit("Dict_Unserialize: not enough data.");
 	const char *ptr = serializedData;
 	const int sorted = BBOp::Int32FromLE(*((int *)ptr));
diff --git a/engines/ags/engine/ac/timer.cpp b/engines/ags/engine/ac/timer.cpp
index 5f26a9c5af..891471d03f 100644
--- a/engines/ags/engine/ac/timer.cpp
+++ b/engines/ags/engine/ac/timer.cpp
@@ -99,11 +99,12 @@ bool waitingForNextTick() {
 	if (is_lagging) {
 #if AGS_PLATFORM_DEBUG && defined (__GNUC__)
 		auto missed_ticks = ((now - last_tick_time) / tick_duration);
-		printf("Lagging! Missed %lld ticks!\n", (long long)missed_ticks);
-		void *array[10];
+		warning("Lagging! Missed %lld ticks!\n", (long long)missed_ticks);
+/*		void *array[10];
 		auto size = backtrace(array, 10);
 		backtrace_symbols_fd(array, size, STDOUT_FILENO);
-		printf("\n");
+*/
+		warning("\n");
 #endif
 		last_tick_time = now;
 		return false;
diff --git a/engines/ags/lib/allegro/color.cpp b/engines/ags/lib/allegro/color.cpp
index 14243c7656..bc1bdc25ea 100644
--- a/engines/ags/lib/allegro/color.cpp
+++ b/engines/ags/lib/allegro/color.cpp
@@ -23,6 +23,7 @@
 #include "ags/lib/allegro/color.h"
 #include "ags/lib/allegro/system.h"
 #include "ags/lib/allegro/aintern.h"
+#include "ags/shared/core/types.h"
 #include "common/textconsole.h"
 #include "common/system.h"
 #include "graphics/palette.h"
diff --git a/engines/ags/lib/dumb-0.9.2/it/itrender.cpp b/engines/ags/lib/dumb-0.9.2/it/itrender.cpp
index 31be41914c..aaed5e799e 100644
--- a/engines/ags/lib/dumb-0.9.2/it/itrender.cpp
+++ b/engines/ags/lib/dumb-0.9.2/it/itrender.cpp
@@ -1731,7 +1731,7 @@ Yxy             This uses a table 4 times larger (hence 4 times slower) than
 						case IT_S_SET_SURROUND_SOUND:
 							if ((effectvalue & 15) == 1)
 								channel->pan = IT_SURROUND;
-								channel->truepan = channel->pan << IT_ENVELOPE_SHIFT;
+							channel->truepan = channel->pan << IT_ENVELOPE_SHIFT;
 							break;
 						case IT_S_SET_HIGH_OFFSET:
 							channel->high_offset = effectvalue & 15;
diff --git a/engines/ags/lib/std/type_traits.h b/engines/ags/lib/std/type_traits.h
index 564a663ce6..cc33200a82 100644
--- a/engines/ags/lib/std/type_traits.h
+++ b/engines/ags/lib/std/type_traits.h
@@ -23,6 +23,8 @@
 #ifndef AGS_STD_TYPE_TRAITS_H
 #define AGS_STD_TYPE_TRAITS_H
 
+#include "common/scummsys.h"
+
 namespace AGS3 {
 namespace std {
 
diff --git a/engines/ags/shared/ac/dynobj/scriptaudioclip.h b/engines/ags/shared/ac/dynobj/scriptaudioclip.h
index dfde8e752e..317ce5d64c 100644
--- a/engines/ags/shared/ac/dynobj/scriptaudioclip.h
+++ b/engines/ags/shared/ac/dynobj/scriptaudioclip.h
@@ -54,7 +54,7 @@ struct ScriptAudioClip {
 	Shared::String scriptName;
 	Shared::String fileName;
 	char bundlingType = AUCL_BUNDLE_EXE;
-	char type = 0;
+	int8 type = 0;
 	char fileType = eAudioFileOGG;
 	char defaultRepeat = 0;
 	short defaultPriority = 50;
diff --git a/engines/ags/shared/font/fonts.cpp b/engines/ags/shared/font/fonts.cpp
index 5ffaf7788f..fda7bfbbf9 100644
--- a/engines/ags/shared/font/fonts.cpp
+++ b/engines/ags/shared/font/fonts.cpp
@@ -273,7 +273,7 @@ size_t split_lines(const char *todis, SplitLines &lines, int wii, int fonnt, siz
 		// restore the character that was there before
 		theline[i + 1] = nextCharWas;
 
-		if (splitAt != -1) {
+		if (splitAt != (size_t)-1) {
 			if (splitAt == 0 && !((theline[0] == ' ') || (theline[0] == '\n'))) {
 				// cannot split with current width restriction
 				lines.Reset();
diff --git a/engines/ags/shared/font/ttffontrenderer.h b/engines/ags/shared/font/ttffontrenderer.h
index 033425cdc6..3a49157fc4 100644
--- a/engines/ags/shared/font/ttffontrenderer.h
+++ b/engines/ags/shared/font/ttffontrenderer.h
@@ -31,6 +31,8 @@ namespace AGS3 {
 
 class TTFFontRenderer : public IAGSFontRenderer, public IAGSFontRenderer2 {
 public:
+	virtual ~TTFFontRenderer() {}
+
 	// IAGSFontRenderer implementation
 	bool LoadFromDisk(int fontNumber, int fontSize) override;
 	void FreeMemory(int fontNumber) override;
diff --git a/engines/ags/shared/font/wfnfont.cpp b/engines/ags/shared/font/wfnfont.cpp
index 2e07a5955c..5b7ce14654 100644
--- a/engines/ags/shared/font/wfnfont.cpp
+++ b/engines/ags/shared/font/wfnfont.cpp
@@ -67,7 +67,7 @@ WFNError WFNFont::ReadFromFile(Stream *in, const soff_t data_size) {
 	}
 
 	const soff_t table_addr = static_cast<uint16_t>(in->ReadInt16()); // offset table relative address
-	if (table_addr < WFN_FILE_SIG_LENGTH + sizeof(uint16_t) || table_addr >= used_data_size) {
+	if ((int)table_addr < WFN_FILE_SIG_LENGTH + sizeof(uint16_t) || table_addr >= used_data_size) {
 		Debug::Printf(kDbgMsg_Error, "\tWFN: bad table address: %lld (%d - %d)", table_addr, WFN_FILE_SIG_LENGTH + sizeof(uint16_t), used_data_size);
 		return kWFNErr_BadTableAddress; // bad table address
 	}
@@ -99,7 +99,7 @@ WFNError WFNFont::ReadFromFile(Stream *in, const soff_t data_size) {
 	offs.reserve(char_count); // reserve max possible offsets
 	for (size_t i = 0; i < char_count; ++i) {
 		const uint16_t off = offset_table[i];
-		if (off < raw_data_offset || off + MinCharDataSize > table_addr) {
+		if (off < raw_data_offset || (int)(off + MinCharDataSize) > table_addr) {
 			Debug::Printf("\tWFN: character %d -- bad item offset: %d (%d - %d, +%d)",
 				i, off, raw_data_offset, table_addr, MinCharDataSize);
 			err = kWFNErr_HasBadCharacters; // warn about potentially corrupt format
@@ -142,7 +142,7 @@ WFNError WFNFont::ReadFromFile(Stream *in, const soff_t data_size) {
 		}
 		const uint16_t raw_off = offs[i] - raw_data_offset + MinCharDataSize; // offset in raw array
 		size_t src_size = pixel_data_size;
-		if (i + 1 != _items.size() && raw_off + src_size > offs[i + 1] - raw_data_offset) {
+		if (i + 1 != _items.size() && (int)(raw_off + src_size) > (offs[i + 1] - raw_data_offset)) {
 			// character pixel data overlaps next character
 			Debug::Printf("\tWFN: item at off %d -- pixel data overlaps next known item (at %d, +%d)",
 				offs[i], offs[i + 1], MinCharDataSize + src_size);
@@ -170,7 +170,7 @@ WFNError WFNFont::ReadFromFile(Stream *in, const soff_t data_size) {
 	for (size_t i = 0; i < char_count; ++i) {
 		const uint16_t off = offset_table[i];
 		// if bad character offset - reference empty character
-		if (off < raw_data_offset || off + MinCharDataSize > table_addr) {
+		if (off < raw_data_offset || (int)(off + MinCharDataSize) > table_addr) {
 			_refs[i] = &_emptyChar;
 		} else {
 			// in usual case the offset table references items in strict order
diff --git a/engines/ags/shared/font/wfnfontrenderer.h b/engines/ags/shared/font/wfnfontrenderer.h
index 47341efe48..6b06dfdf3b 100644
--- a/engines/ags/shared/font/wfnfontrenderer.h
+++ b/engines/ags/shared/font/wfnfontrenderer.h
@@ -32,6 +32,8 @@ class WFNFont;
 
 class WFNFontRenderer : public IAGSFontRenderer, public IAGSFontRenderer2 {
 public:
+	virtual ~WFNFontRenderer() {}
+
 	bool LoadFromDisk(int fontNumber, int fontSize) override;
 	void FreeMemory(int fontNumber) override;
 	bool SupportsExtendedCharacters(int fontNumber) override;


Commit: 739c02d5c09fbba0ac27ec7667ffcef7a14f2e66
    https://github.com/scummvm/scummvm/commit/739c02d5c09fbba0ac27ec7667ffcef7a14f2e66
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix a bunch of warnings about const loss

Some of these are legitimate, because the AGS source did some
nasty code sharing a char * buffer for both reading and writing
stuff to savegames. Will need to refactor it at some point to
use the Common::Serializer

Changed paths:
    engines/ags/engine/ac/dynobj/cc_audiochannel.cpp
    engines/ags/engine/ac/dynobj/cc_audioclip.cpp
    engines/ags/engine/ac/dynobj/cc_character.cpp
    engines/ags/engine/ac/dynobj/scriptcamera.cpp
    engines/ags/engine/ac/dynobj/scriptviewport.cpp
    engines/ags/engine/ac/scriptcontainers.cpp
    engines/ags/engine/ac/statobj/agsstaticobject.cpp
    engines/ags/engine/ac/string.cpp
    engines/ags/shared/font/wfnfont.cpp
    engines/ags/shared/game/main_game_file.cpp


diff --git a/engines/ags/engine/ac/dynobj/cc_audiochannel.cpp b/engines/ags/engine/ac/dynobj/cc_audiochannel.cpp
index ae636d4de8..1edc98acab 100644
--- a/engines/ags/engine/ac/dynobj/cc_audiochannel.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_audiochannel.cpp
@@ -33,7 +33,7 @@ const char *CCAudioChannel::GetType() {
 }
 
 int CCAudioChannel::Serialize(const char *address, char *buffer, int bufsize) {
-	ScriptAudioChannel *ach = (ScriptAudioChannel *)address;
+	ScriptAudioChannel *ach = (ScriptAudioChannel *)const_cast<char *>(address);
 	StartSerialize(buffer);
 	SerializeInt(ach->id);
 	return EndSerialize();
diff --git a/engines/ags/engine/ac/dynobj/cc_audioclip.cpp b/engines/ags/engine/ac/dynobj/cc_audioclip.cpp
index cebe70e779..01351f4eef 100644
--- a/engines/ags/engine/ac/dynobj/cc_audioclip.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_audioclip.cpp
@@ -33,7 +33,7 @@ const char *CCAudioClip::GetType() {
 }
 
 int CCAudioClip::Serialize(const char *address, char *buffer, int bufsize) {
-	ScriptAudioClip *ach = (ScriptAudioClip *)address;
+	ScriptAudioClip *ach = (ScriptAudioClip *)const_cast<char *>(address);
 	StartSerialize(buffer);
 	SerializeInt(ach->id);
 	return EndSerialize();
diff --git a/engines/ags/engine/ac/dynobj/cc_character.cpp b/engines/ags/engine/ac/dynobj/cc_character.cpp
index 3aacebafae..6d8d283142 100644
--- a/engines/ags/engine/ac/dynobj/cc_character.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_character.cpp
@@ -38,7 +38,7 @@ const char *CCCharacter::GetType() {
 // serialize the object into BUFFER (which is BUFSIZE bytes)
 // return number of bytes used
 int CCCharacter::Serialize(const char *address, char *buffer, int bufsize) {
-	CharacterInfo *chaa = (CharacterInfo *)address;
+	CharacterInfo *chaa = (CharacterInfo *)const_cast<char *>(address);
 	StartSerialize(buffer);
 	SerializeInt(chaa->index_id);
 	return EndSerialize();
@@ -51,7 +51,7 @@ void CCCharacter::Unserialize(int index, const char *serializedData, int dataSiz
 }
 
 void CCCharacter::WriteInt16(const char *address, intptr_t offset, int16_t val) {
-	*(int16_t *)(address + offset) = val;
+	*(int16_t *)(const_cast<char *>(address) + offset) = val;
 
 	// Detect when a game directly modifies the inventory, which causes the displayed
 	// and actual inventory to diverge since 2.70. Force an update of the displayed
diff --git a/engines/ags/engine/ac/dynobj/scriptcamera.cpp b/engines/ags/engine/ac/dynobj/scriptcamera.cpp
index aa7aa5d8bd..be9f7bacd6 100644
--- a/engines/ags/engine/ac/dynobj/scriptcamera.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptcamera.cpp
@@ -59,7 +59,7 @@ ScriptCamera *Camera_Unserialize(int handle, const char *serializedData, int dat
 	// but acquire one from the GameState, which keeps the first reference.
 	// This is essential because GameState should be able to invalidate any
 	// script references when Camera gets removed.
-	const int id = BBOp::Int32FromLE(*((int *)serializedData));
+	const int id = BBOp::Int32FromLE(*((const int *)serializedData));
 	if (id >= 0) {
 		auto scam = play.RegisterRoomCamera(id, handle);
 		if (scam)
diff --git a/engines/ags/engine/ac/dynobj/scriptviewport.cpp b/engines/ags/engine/ac/dynobj/scriptviewport.cpp
index e578dce594..99c3eae0e3 100644
--- a/engines/ags/engine/ac/dynobj/scriptviewport.cpp
+++ b/engines/ags/engine/ac/dynobj/scriptviewport.cpp
@@ -59,7 +59,7 @@ ScriptViewport *Viewport_Unserialize(int handle, const char *serializedData, int
 	// but acquire one from the GameState, which keeps the first reference.
 	// This is essential because GameState should be able to invalidate any
 	// script references when Viewport gets removed.
-	const int id = BBOp::Int32FromLE(*((int *)serializedData));
+	const int id = BBOp::Int32FromLE(*((const int *)serializedData));
 	if (id >= 0) {
 		auto scview = play.RegisterRoomViewport(id, handle);
 		if (scview)
diff --git a/engines/ags/engine/ac/scriptcontainers.cpp b/engines/ags/engine/ac/scriptcontainers.cpp
index d079ec312e..4bf42ca474 100644
--- a/engines/ags/engine/ac/scriptcontainers.cpp
+++ b/engines/ags/engine/ac/scriptcontainers.cpp
@@ -74,9 +74,9 @@ ScriptDictBase *Dict_Unserialize(int index, const char *serializedData, int data
 	if (dataSize < (int)sizeof(int32_t) * 2)
 		quit("Dict_Unserialize: not enough data.");
 	const char *ptr = serializedData;
-	const int sorted = BBOp::Int32FromLE(*((int *)ptr));
+	const int sorted = BBOp::Int32FromLE(*((const int *)ptr));
 	ptr += sizeof(int32_t);
-	const int cs = BBOp::Int32FromLE(*((int *)ptr));
+	const int cs = BBOp::Int32FromLE(*((const int *)ptr));
 	ptr += sizeof(int32_t);
 	ScriptDictBase *dic = Dict_CreateImpl(sorted != 0, cs != 0);
 	dic->Unserialize(index, ptr, dataSize -= sizeof(int32_t) * 2);
@@ -208,12 +208,12 @@ ScriptSetBase *Set_Create(bool sorted, bool case_sensitive) {
 
 // TODO: we need memory streams
 ScriptSetBase *Set_Unserialize(int index, const char *serializedData, int dataSize) {
-	if (dataSize < sizeof(int32_t) * 2)
+	if (dataSize < (int)sizeof(int32_t) * 2)
 		quit("Set_Unserialize: not enough data.");
 	const char *ptr = serializedData;
-	const int sorted = BBOp::Int32FromLE(*((int *)ptr));
+	const int sorted = BBOp::Int32FromLE(*((const int *)ptr));
 	ptr += sizeof(int32_t);
-	const int cs = BBOp::Int32FromLE(*((int *)ptr));
+	const int cs = BBOp::Int32FromLE(*((const int *)ptr));
 	ptr += sizeof(int32_t);
 	ScriptSetBase *set = Set_CreateImpl(sorted != 0, cs != 0);
 	set->Unserialize(index, ptr, dataSize -= sizeof(int32_t) * 2);
diff --git a/engines/ags/engine/ac/statobj/agsstaticobject.cpp b/engines/ags/engine/ac/statobj/agsstaticobject.cpp
index 1351b69952..e76e5c0149 100644
--- a/engines/ags/engine/ac/statobj/agsstaticobject.cpp
+++ b/engines/ags/engine/ac/statobj/agsstaticobject.cpp
@@ -39,39 +39,39 @@ void AGSStaticObject::Read(const char *address, intptr_t offset, void *dest, int
 }
 
 uint8_t AGSStaticObject::ReadInt8(const char *address, intptr_t offset) {
-	return *(uint8_t *)(address + offset);
+	return *(const uint8_t *)(address + offset);
 }
 
 int16_t AGSStaticObject::ReadInt16(const char *address, intptr_t offset) {
-	return *(int16_t *)(address + offset);
+	return *(const int16_t *)(address + offset);
 }
 
 int32_t AGSStaticObject::ReadInt32(const char *address, intptr_t offset) {
-	return *(int32_t *)(address + offset);
+	return *(const int32_t *)(address + offset);
 }
 
 float AGSStaticObject::ReadFloat(const char *address, intptr_t offset) {
-	return *(float *)(address + offset);
+	return *(const float *)(address + offset);
 }
 
 void AGSStaticObject::Write(const char *address, intptr_t offset, void *src, int size) {
-	memcpy((void *)(address + offset), src, size);
+	memcpy((void *)(const_cast<char *>(address) + offset), src, size);
 }
 
 void AGSStaticObject::WriteInt8(const char *address, intptr_t offset, uint8_t val) {
-	*(uint8_t *)(address + offset) = val;
+	*(uint8_t *)(const_cast<char *>(address) + offset) = val;
 }
 
 void AGSStaticObject::WriteInt16(const char *address, intptr_t offset, int16_t val) {
-	*(int16_t *)(address + offset) = val;
+	*(int16_t *)(const_cast<char *>(address) + offset) = val;
 }
 
 void AGSStaticObject::WriteInt32(const char *address, intptr_t offset, int32_t val) {
-	*(int32_t *)(address + offset) = val;
+	*(int32_t *)(const_cast<char *>(address) + offset) = val;
 }
 
 void AGSStaticObject::WriteFloat(const char *address, intptr_t offset, float val) {
-	*(float *)(address + offset) = val;
+	*(float *)(const_cast<char *>(address) + offset) = val;
 }
 
 
@@ -83,7 +83,7 @@ void StaticGame::WriteInt32(const char *address, intptr_t offset, int32_t val) {
 		// game.text_align, game.speech_text_align
 		*(int32_t *)(address + offset) = ReadScriptAlignment(val);
 	} else {
-		*(int32_t *)(address + offset) = val;
+		*(int32_t *)(const_cast<char *>(address) + offset) = val;
 	}
 }
 
diff --git a/engines/ags/engine/ac/string.cpp b/engines/ags/engine/ac/string.cpp
index b1ac38d05c..b33ee59eb4 100644
--- a/engines/ags/engine/ac/string.cpp
+++ b/engines/ags/engine/ac/string.cpp
@@ -222,7 +222,7 @@ DynObjectRef CreateNewScriptStringObj(const char *fromText, bool reAllocate) {
 		str = new ScriptString(fromText);
 	} else {
 		str = new ScriptString();
-		str->text = (char *)fromText;
+		str->text = const_cast<char *>(fromText);
 	}
 	void *obj_ptr = str->text;
 	int32_t handle = ccRegisterManagedObject(obj_ptr, str);
diff --git a/engines/ags/shared/font/wfnfont.cpp b/engines/ags/shared/font/wfnfont.cpp
index 5b7ce14654..d4a8b96c8b 100644
--- a/engines/ags/shared/font/wfnfont.cpp
+++ b/engines/ags/shared/font/wfnfont.cpp
@@ -67,7 +67,7 @@ WFNError WFNFont::ReadFromFile(Stream *in, const soff_t data_size) {
 	}
 
 	const soff_t table_addr = static_cast<uint16_t>(in->ReadInt16()); // offset table relative address
-	if ((int)table_addr < WFN_FILE_SIG_LENGTH + sizeof(uint16_t) || table_addr >= used_data_size) {
+	if (table_addr < (int)(WFN_FILE_SIG_LENGTH + sizeof(uint16_t)) || table_addr >= used_data_size) {
 		Debug::Printf(kDbgMsg_Error, "\tWFN: bad table address: %lld (%d - %d)", table_addr, WFN_FILE_SIG_LENGTH + sizeof(uint16_t), used_data_size);
 		return kWFNErr_BadTableAddress; // bad table address
 	}
diff --git a/engines/ags/shared/game/main_game_file.cpp b/engines/ags/shared/game/main_game_file.cpp
index 48edb9ab8b..8f6c7f0084 100644
--- a/engines/ags/shared/game/main_game_file.cpp
+++ b/engines/ags/shared/game/main_game_file.cpp
@@ -310,8 +310,8 @@ void ReadDialogs(DialogTopic *&dialog,
 	} else {
 		// Encrypted text on > 2.60
 		while (1) {
-			size_t newlen = in->ReadInt32();
-			if (static_cast<int32_t>(newlen) == 0xCAFEBEEF) { // GUI magic
+			size_t newlen = (size_t)in->ReadInt32();
+			if (newlen == 0xCAFEBEEF) { // GUI magic
 				in->Seek(-4);
 				break;
 			}


Commit: 2df81063409cfc0b5b434203154c3d3422f56970
    https://github.com/scummvm/scummvm/commit/2df81063409cfc0b5b434203154c3d3422f56970
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Further gcc warning fixes

Changed paths:
    engines/ags/engine/ac/dynobj/managedobjectpool.cpp
    engines/ags/lib/std/algorithm.h


diff --git a/engines/ags/engine/ac/dynobj/managedobjectpool.cpp b/engines/ags/engine/ac/dynobj/managedobjectpool.cpp
index f89fe38698..1b6b6f08dc 100644
--- a/engines/ags/engine/ac/dynobj/managedobjectpool.cpp
+++ b/engines/ags/engine/ac/dynobj/managedobjectpool.cpp
@@ -49,7 +49,9 @@ int ManagedObjectPool::Remove(ManagedObject &o, bool force) {
 		return 0;
 	}
 
+#ifdef DEBUG_MANAGED_OBJECTS
 	auto handle = o.handle;
+#endif
 	available_ids.push(o.handle);
 
 	handleByAddress.erase(o.addr);
@@ -141,7 +143,7 @@ ScriptValueType ManagedObjectPool::HandleToAddressAndManager(int32_t handle, voi
 		return kScValUndefined;
 	}
 
-	object = (void *)o.addr;  // WARNING: This strips the const from the char* pointer.
+	object = const_cast<char *>(o.addr);  // WARNING: This strips the const from the char* pointer.
 	manager = o.callback;
 	return o.obj_type;
 }
@@ -259,7 +261,7 @@ void ManagedObjectPool::WriteToDisk(Stream *out) {
 		// handle
 		out->WriteInt32(o.handle);
 		// write the type of the object
-		StrUtil::WriteCStr((char *)o.callback->GetType(), out);
+		StrUtil::WriteCStr(const_cast<char *>(o.callback->GetType()), out);
 		// now write the object data
 		int bytesWritten = o.callback->Serialize(o.addr, &serializeBuffer.front(), serializeBuffer.size());
 		if ((bytesWritten < 0) && ((size_t)(-bytesWritten) > serializeBuffer.size())) {
diff --git a/engines/ags/lib/std/algorithm.h b/engines/ags/lib/std/algorithm.h
index f95335f351..427779ca84 100644
--- a/engines/ags/lib/std/algorithm.h
+++ b/engines/ags/lib/std/algorithm.h
@@ -65,7 +65,9 @@ T unique(T first, T last) {
 			if (*pos == *existingPos) {
 				// Found a match, so shift values over the duplicate
 				while (pos < (last - 1)) {
-					*pos++ = *(pos + 1);
+					T &prior = pos;
+					++pos;
+					prior = pos;
 				}
 
 				--last;


Commit: 24ff2a9753c9e10eeb21663928dd869cc0dfe4c9
    https://github.com/scummvm/scummvm/commit/24ff2a9753c9e10eeb21663928dd869cc0dfe4c9
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Add detection for Black Cauldron Remake

Changed paths:
    engines/ags/detection_tables.h


diff --git a/engines/ags/detection_tables.h b/engines/ags/detection_tables.h
index 29a04e180b..d7c4411af8 100644
--- a/engines/ags/detection_tables.h
+++ b/engines/ags/detection_tables.h
@@ -24,10 +24,25 @@ namespace AGS {
 
 static const PlainGameDescriptor AGS_GAMES[] = {
 	{ "ags", "Adventure Game Studio Game" },
+
+	{ "bcremake", "Black Cauldron Remake" },
 	{ 0, 0 }
 };
 
+
 static const AGSGameDescription GAME_DESCRIPTIONS[] = {
+	{
+		{
+			"bcremake",
+			nullptr,
+			AD_ENTRY1s("bc.exe", "0710e2ec71042617f565c01824f0cf3c", 7683255),
+			Common::EN_ANY,
+			Common::kPlatformDOS,
+			ADGF_NO_FLAGS,
+			GUIO1(GUIO_NOSPEECH)
+		}
+	},
+
 	{ AD_TABLE_END_MARKER }
 };
 


Commit: 7efe9249f84413bbe0052bb40bce025b765cffa2
    https://github.com/scummvm/scummvm/commit/7efe9249f84413bbe0052bb40bce025b765cffa2
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Further const loss warning fixes

Changed paths:
    engines/ags/engine/ac/character.cpp
    engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp
    engines/ags/engine/ac/dynobj/cc_character.cpp
    engines/ags/engine/ac/dynobj/cc_dialog.cpp
    engines/ags/engine/ac/dynobj/cc_dynamicarray.cpp
    engines/ags/engine/ac/dynobj/cc_gui.cpp
    engines/ags/engine/ac/dynobj/cc_hotspot.cpp
    engines/ags/engine/ac/dynobj/cc_inventory.cpp
    engines/ags/engine/ac/dynobj/cc_object.cpp
    engines/ags/engine/ac/dynobj/cc_region.cpp
    engines/ags/engine/ac/statobj/agsstaticobject.cpp
    engines/ags/engine/ac/statobj/staticarray.cpp


diff --git a/engines/ags/engine/ac/character.cpp b/engines/ags/engine/ac/character.cpp
index cfee01f260..3bb7e6c740 100644
--- a/engines/ags/engine/ac/character.cpp
+++ b/engines/ags/engine/ac/character.cpp
@@ -745,7 +745,7 @@ void Character_Say(CharacterInfo *chaa, const char *text) {
 
 void Character_SayAt(CharacterInfo *chaa, int x, int y, int width, const char *texx) {
 
-	DisplaySpeechAt(x, y, width, chaa->index_id, (char *)texx);
+	DisplaySpeechAt(x, y, width, chaa->index_id, texx);
 }
 
 ScriptOverlay *Character_SayBackground(CharacterInfo *chaa, const char *texx) {
diff --git a/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp b/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp
index c0d4d780f0..e711ba3963 100644
--- a/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_agsdynamicobject.cpp
@@ -63,25 +63,25 @@ int AGSCCDynamicObject::EndSerialize() {
 void AGSCCDynamicObject::StartUnserialize(const char *sbuffer, int pTotalBytes) {
 	bytesSoFar = 0;
 	totalBytes = pTotalBytes;
-	serbuffer = (char *)sbuffer;
+	serbuffer = const_cast<char *>(sbuffer);
 }
 
 int AGSCCDynamicObject::UnserializeInt() {
 	if (bytesSoFar >= totalBytes)
 		quit("Unserialise: internal error: read past EOF");
 
-	char *chptr = &serbuffer[bytesSoFar];
+	const char *chptr = &serbuffer[bytesSoFar];
 	bytesSoFar += 4;
-	return BBOp::Int32FromLE(*((int *)chptr));
+	return BBOp::Int32FromLE(*((const int *)chptr));
 }
 
 float AGSCCDynamicObject::UnserializeFloat() {
 	if (bytesSoFar >= totalBytes)
 		quit("Unserialise: internal error: read past EOF");
 
-	char *chptr = &serbuffer[bytesSoFar];
+	const char *chptr = &serbuffer[bytesSoFar];
 	bytesSoFar += 4;
-	return BBOp::FloatFromLE(*((float *)chptr));
+	return BBOp::FloatFromLE(*((const float *)chptr));
 }
 
 const char *AGSCCDynamicObject::GetFieldPtr(const char *address, intptr_t offset) {
@@ -93,39 +93,39 @@ void AGSCCDynamicObject::Read(const char *address, intptr_t offset, void *dest,
 }
 
 uint8_t AGSCCDynamicObject::ReadInt8(const char *address, intptr_t offset) {
-	return *(uint8_t *)(address + offset);
+	return *(const uint8_t *)(address + offset);
 }
 
 int16_t AGSCCDynamicObject::ReadInt16(const char *address, intptr_t offset) {
-	return *(int16_t *)(address + offset);
+	return *(const int16_t *)(address + offset);
 }
 
 int32_t AGSCCDynamicObject::ReadInt32(const char *address, intptr_t offset) {
-	return *(int32_t *)(address + offset);
+	return *(const int32_t *)(address + offset);
 }
 
 float AGSCCDynamicObject::ReadFloat(const char *address, intptr_t offset) {
-	return *(float *)(address + offset);
+	return *(const float *)(address + offset);
 }
 
 void AGSCCDynamicObject::Write(const char *address, intptr_t offset, void *src, int size) {
-	memcpy((void *)(address + offset), src, size);
+	memcpy((void *)(const_cast<char *>(address) + offset), src, size);
 }
 
 void AGSCCDynamicObject::WriteInt8(const char *address, intptr_t offset, uint8_t val) {
-	*(uint8_t *)(address + offset) = val;
+	*(uint8_t *)(const_cast<char *>(address) + offset) = val;
 }
 
 void AGSCCDynamicObject::WriteInt16(const char *address, intptr_t offset, int16_t val) {
-	*(int16_t *)(address + offset) = val;
+	*(int16_t *)(const_cast<char *>(address) + offset) = val;
 }
 
 void AGSCCDynamicObject::WriteInt32(const char *address, intptr_t offset, int32_t val) {
-	*(int32_t *)(address + offset) = val;
+	*(int32_t *)(const_cast<char *>(address) + offset) = val;
 }
 
 void AGSCCDynamicObject::WriteFloat(const char *address, intptr_t offset, float val) {
-	*(float *)(address + offset) = val;
+	*(float *)(const_cast<char *>(address) + offset) = val;
 }
 
 } // namespace AGS3
diff --git a/engines/ags/engine/ac/dynobj/cc_character.cpp b/engines/ags/engine/ac/dynobj/cc_character.cpp
index 6d8d283142..a4a03ad253 100644
--- a/engines/ags/engine/ac/dynobj/cc_character.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_character.cpp
@@ -58,7 +58,7 @@ void CCCharacter::WriteInt16(const char *address, intptr_t offset, int16_t val)
 	// inventory for older games that reply on the previous behaviour.
 	if (loaded_game_file_version < kGameVersion_270) {
 		const int invoffset = 112;
-		if (offset >= invoffset && (int)offset < (invoffset + MAX_INV * sizeof(short))) {
+		if (offset >= invoffset && offset < (int)(invoffset + MAX_INV * sizeof(short))) {
 			update_invorder();
 		}
 	}
diff --git a/engines/ags/engine/ac/dynobj/cc_dialog.cpp b/engines/ags/engine/ac/dynobj/cc_dialog.cpp
index 6be1090ecc..e6283dec2a 100644
--- a/engines/ags/engine/ac/dynobj/cc_dialog.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_dialog.cpp
@@ -35,7 +35,7 @@ const char *CCDialog::GetType() {
 // serialize the object into BUFFER (which is BUFSIZE bytes)
 // return number of bytes used
 int CCDialog::Serialize(const char *address, char *buffer, int bufsize) {
-	ScriptDialog *shh = (ScriptDialog *)address;
+	ScriptDialog *shh = (ScriptDialog *)const_cast<char *>(address);
 	StartSerialize(buffer);
 	SerializeInt(shh->id);
 	return EndSerialize();
diff --git a/engines/ags/engine/ac/dynobj/cc_dynamicarray.cpp b/engines/ags/engine/ac/dynobj/cc_dynamicarray.cpp
index 03fe679707..0d12ddb439 100644
--- a/engines/ags/engine/ac/dynobj/cc_dynamicarray.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_dynamicarray.cpp
@@ -37,7 +37,7 @@ int CCDynamicArray::Dispose(const char *address, bool force) {
 	// except if this array is forcefully removed from the managed pool,
 	// in which case just ignore these.
 	if (!force) {
-		int *elementCount = (int *)address;
+		int *elementCount = (int *)const_cast<char *>(address);
 		if (elementCount[0] & ARRAY_MANAGED_TYPE_FLAG) {
 			elementCount[0] &= ~ARRAY_MANAGED_TYPE_FLAG;
 			for (int i = 0; i < elementCount[0]; i++) {
@@ -55,7 +55,7 @@ int CCDynamicArray::Dispose(const char *address, bool force) {
 // serialize the object into BUFFER (which is BUFSIZE bytes)
 // return number of bytes used
 int CCDynamicArray::Serialize(const char *address, char *buffer, int bufsize) {
-	int *sizeInBytes = &((int *)address)[-1];
+	const int *sizeInBytes = &((const int *)address)[-1];
 	int sizeToWrite = *sizeInBytes + 8;
 	if (sizeToWrite > bufsize) {
 		// buffer not big enough, ask for a bigger one
@@ -98,39 +98,39 @@ void CCDynamicArray::Read(const char *address, intptr_t offset, void *dest, int
 }
 
 uint8_t CCDynamicArray::ReadInt8(const char *address, intptr_t offset) {
-	return *(uint8_t *)(address + offset);
+	return *(const uint8_t *)(address + offset);
 }
 
 int16_t CCDynamicArray::ReadInt16(const char *address, intptr_t offset) {
-	return *(int16_t *)(address + offset);
+	return *(const int16_t *)(address + offset);
 }
 
 int32_t CCDynamicArray::ReadInt32(const char *address, intptr_t offset) {
-	return *(int32_t *)(address + offset);
+	return *(const int32_t *)(address + offset);
 }
 
 float CCDynamicArray::ReadFloat(const char *address, intptr_t offset) {
-	return *(float *)(address + offset);
+	return *(const float *)(address + offset);
 }
 
 void CCDynamicArray::Write(const char *address, intptr_t offset, void *src, int size) {
-	memcpy((void *)(address + offset), src, size);
+	memcpy((void *)(const_cast<char *>(address) + offset), src, size);
 }
 
 void CCDynamicArray::WriteInt8(const char *address, intptr_t offset, uint8_t val) {
-	*(uint8_t *)(address + offset) = val;
+	*(uint8_t *)(const_cast<char *>(address) + offset) = val;
 }
 
 void CCDynamicArray::WriteInt16(const char *address, intptr_t offset, int16_t val) {
-	*(int16_t *)(address + offset) = val;
+	*(int16_t *)(const_cast<char *>(address) + offset) = val;
 }
 
 void CCDynamicArray::WriteInt32(const char *address, intptr_t offset, int32_t val) {
-	*(int32_t *)(address + offset) = val;
+	*(int32_t *)(const_cast<char *>(address) + offset) = val;
 }
 
 void CCDynamicArray::WriteFloat(const char *address, intptr_t offset, float val) {
-	*(float *)(address + offset) = val;
+	*(float *)(const_cast<char *>(address) + offset) = val;
 }
 
 CCDynamicArray globalDynamicArray;
diff --git a/engines/ags/engine/ac/dynobj/cc_gui.cpp b/engines/ags/engine/ac/dynobj/cc_gui.cpp
index 4c9b46482f..cdc7c871b6 100644
--- a/engines/ags/engine/ac/dynobj/cc_gui.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_gui.cpp
@@ -35,7 +35,7 @@ const char *CCGUI::GetType() {
 // serialize the object into BUFFER (which is BUFSIZE bytes)
 // return number of bytes used
 int CCGUI::Serialize(const char *address, char *buffer, int bufsize) {
-	ScriptGUI *shh = (ScriptGUI *)address;
+	ScriptGUI *shh = (ScriptGUI *)const_cast<char *>(address);
 	StartSerialize(buffer);
 	SerializeInt(shh->id);
 	return EndSerialize();
diff --git a/engines/ags/engine/ac/dynobj/cc_hotspot.cpp b/engines/ags/engine/ac/dynobj/cc_hotspot.cpp
index 8a46774042..33fe02d823 100644
--- a/engines/ags/engine/ac/dynobj/cc_hotspot.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_hotspot.cpp
@@ -37,7 +37,7 @@ const char *CCHotspot::GetType() {
 // serialize the object into BUFFER (which is BUFSIZE bytes)
 // return number of bytes used
 int CCHotspot::Serialize(const char *address, char *buffer, int bufsize) {
-	ScriptHotspot *shh = (ScriptHotspot *)address;
+	ScriptHotspot *shh = (ScriptHotspot *)const_cast<char *>(address);
 	StartSerialize(buffer);
 	SerializeInt(shh->id);
 	return EndSerialize();
diff --git a/engines/ags/engine/ac/dynobj/cc_inventory.cpp b/engines/ags/engine/ac/dynobj/cc_inventory.cpp
index 60cae380be..f453395f7a 100644
--- a/engines/ags/engine/ac/dynobj/cc_inventory.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_inventory.cpp
@@ -36,7 +36,7 @@ const char *CCInventory::GetType() {
 // serialize the object into BUFFER (which is BUFSIZE bytes)
 // return number of bytes used
 int CCInventory::Serialize(const char *address, char *buffer, int bufsize) {
-	ScriptInvItem *shh = (ScriptInvItem *)address;
+	ScriptInvItem *shh = (ScriptInvItem *)const_cast<char *>(address);
 	StartSerialize(buffer);
 	SerializeInt(shh->id);
 	return EndSerialize();
diff --git a/engines/ags/engine/ac/dynobj/cc_object.cpp b/engines/ags/engine/ac/dynobj/cc_object.cpp
index abcd84f8dc..35b61676e7 100644
--- a/engines/ags/engine/ac/dynobj/cc_object.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_object.cpp
@@ -37,7 +37,7 @@ const char *CCObject::GetType() {
 // serialize the object into BUFFER (which is BUFSIZE bytes)
 // return number of bytes used
 int CCObject::Serialize(const char *address, char *buffer, int bufsize) {
-	ScriptObject *shh = (ScriptObject *)address;
+	ScriptObject *shh = (ScriptObject *)const_cast<char *>(address);
 	StartSerialize(buffer);
 	SerializeInt(shh->id);
 	return EndSerialize();
diff --git a/engines/ags/engine/ac/dynobj/cc_region.cpp b/engines/ags/engine/ac/dynobj/cc_region.cpp
index a6fc8910b5..56d099b1c4 100644
--- a/engines/ags/engine/ac/dynobj/cc_region.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_region.cpp
@@ -37,7 +37,7 @@ const char *CCRegion::GetType() {
 // serialize the object into BUFFER (which is BUFSIZE bytes)
 // return number of bytes used
 int CCRegion::Serialize(const char *address, char *buffer, int bufsize) {
-	ScriptRegion *shh = (ScriptRegion *)address;
+	ScriptRegion *shh = (ScriptRegion *)const_cast<char *>(address);
 	StartSerialize(buffer);
 	SerializeInt(shh->id);
 	return EndSerialize();
diff --git a/engines/ags/engine/ac/statobj/agsstaticobject.cpp b/engines/ags/engine/ac/statobj/agsstaticobject.cpp
index e76e5c0149..4cc1f476cc 100644
--- a/engines/ags/engine/ac/statobj/agsstaticobject.cpp
+++ b/engines/ags/engine/ac/statobj/agsstaticobject.cpp
@@ -81,7 +81,7 @@ void StaticGame::WriteInt32(const char *address, intptr_t offset, int32_t val) {
 		set_debug_mode(val != 0);
 	} else if (offset == 99 * sizeof(int32_t) || offset == 112 * sizeof(int32_t)) {
 		// game.text_align, game.speech_text_align
-		*(int32_t *)(address + offset) = ReadScriptAlignment(val);
+		*(int32_t *)(const_cast<char *>(address) + offset) = ReadScriptAlignment(val);
 	} else {
 		*(int32_t *)(const_cast<char *>(address) + offset) = val;
 	}
diff --git a/engines/ags/engine/ac/statobj/staticarray.cpp b/engines/ags/engine/ac/statobj/staticarray.cpp
index b70c029d2e..dd02d047cf 100644
--- a/engines/ags/engine/ac/statobj/staticarray.cpp
+++ b/engines/ags/engine/ac/statobj/staticarray.cpp
@@ -79,7 +79,7 @@ uint8_t StaticArray::ReadInt8(const char *address, intptr_t offset) {
 	} else if (_dynamicMgr) {
 		return _dynamicMgr->ReadInt8(el_ptr, offset % _elemLegacySize);
 	}
-	return *(uint8_t *)(el_ptr + offset % _elemLegacySize);
+	return *(const uint8_t *)(el_ptr + offset % _elemLegacySize);
 }
 
 int16_t StaticArray::ReadInt16(const char *address, intptr_t offset) {
@@ -89,7 +89,7 @@ int16_t StaticArray::ReadInt16(const char *address, intptr_t offset) {
 	} else if (_dynamicMgr) {
 		return _dynamicMgr->ReadInt16(el_ptr, offset % _elemLegacySize);
 	}
-	return *(uint16_t *)(el_ptr + offset % _elemLegacySize);
+	return *(const uint16_t *)(el_ptr + offset % _elemLegacySize);
 }
 
 int32_t StaticArray::ReadInt32(const char *address, intptr_t offset) {
@@ -99,7 +99,7 @@ int32_t StaticArray::ReadInt32(const char *address, intptr_t offset) {
 	} else if (_dynamicMgr) {
 		return _dynamicMgr->ReadInt32(el_ptr, offset % _elemLegacySize);
 	}
-	return *(uint32_t *)(el_ptr + offset % _elemLegacySize);
+	return *(const uint32_t *)(el_ptr + offset % _elemLegacySize);
 }
 
 float StaticArray::ReadFloat(const char *address, intptr_t offset) {
@@ -109,7 +109,7 @@ float StaticArray::ReadFloat(const char *address, intptr_t offset) {
 	} else if (_dynamicMgr) {
 		return _dynamicMgr->ReadFloat(el_ptr, offset % _elemLegacySize);
 	}
-	return *(float *)(el_ptr + offset % _elemLegacySize);
+	return *(const float *)(el_ptr + offset % _elemLegacySize);
 }
 
 void StaticArray::Write(const char *address, intptr_t offset, void *src, int size) {
@@ -119,7 +119,7 @@ void StaticArray::Write(const char *address, intptr_t offset, void *src, int siz
 	} else if (_dynamicMgr) {
 		return _dynamicMgr->Write(el_ptr, offset % _elemLegacySize, src, size);
 	} else {
-		memcpy((void *)(el_ptr + offset % _elemLegacySize), src, size);
+		memcpy((void *)(const_cast<char *>(el_ptr) + offset % _elemLegacySize), src, size);
 	}
 }
 
@@ -130,7 +130,7 @@ void StaticArray::WriteInt8(const char *address, intptr_t offset, uint8_t val) {
 	} else if (_dynamicMgr) {
 		return _dynamicMgr->WriteInt8(el_ptr, offset % _elemLegacySize, val);
 	} else {
-		*(uint8_t *)(el_ptr + offset % _elemLegacySize) = val;
+		*(uint8_t *)(const_cast<char *>(el_ptr) + offset % _elemLegacySize) = val;
 	}
 }
 
@@ -141,7 +141,7 @@ void StaticArray::WriteInt16(const char *address, intptr_t offset, int16_t val)
 	} else if (_dynamicMgr) {
 		return _dynamicMgr->WriteInt16(el_ptr, offset % _elemLegacySize, val);
 	} else {
-		*(uint16_t *)(el_ptr + offset % _elemLegacySize) = val;
+		*(uint16_t *)(const_cast<char *>(el_ptr) + offset % _elemLegacySize) = val;
 	}
 }
 
@@ -152,7 +152,7 @@ void StaticArray::WriteInt32(const char *address, intptr_t offset, int32_t val)
 	} else if (_dynamicMgr) {
 		return _dynamicMgr->WriteInt32(el_ptr, offset % _elemLegacySize, val);
 	} else {
-		*(uint32_t *)(el_ptr + offset % _elemLegacySize) = val;
+		*(uint32_t *)(const_cast<char *>(el_ptr) + offset % _elemLegacySize) = val;
 	}
 }
 
@@ -163,7 +163,7 @@ void StaticArray::WriteFloat(const char *address, intptr_t offset, float val) {
 	} else if (_dynamicMgr) {
 		return _dynamicMgr->WriteFloat(el_ptr, offset % _elemLegacySize, val);
 	} else {
-		*(float *)(el_ptr + offset % _elemLegacySize) = val;
+		*(float *)(const_cast<char *>(el_ptr) + offset % _elemLegacySize) = val;
 	}
 }
 


Commit: 1b86461eda8228aa4dc315aabd8563e7a97ff311
    https://github.com/scummvm/scummvm/commit/1b86461eda8228aa4dc315aabd8563e7a97ff311
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix const warnings in macro expansions

Changed paths:
    engines/ags/engine/ac/button.cpp
    engines/ags/engine/ac/character.cpp
    engines/ags/engine/ac/dialog.cpp
    engines/ags/engine/ac/file.cpp
    engines/ags/engine/ac/game.cpp
    engines/ags/engine/ac/global_api.cpp
    engines/ags/engine/ac/hotspot.cpp
    engines/ags/engine/ac/inventoryitem.cpp
    engines/ags/engine/ac/label.cpp
    engines/ags/engine/ac/listbox.cpp
    engines/ags/engine/ac/object.cpp
    engines/ags/engine/ac/parser.cpp
    engines/ags/engine/ac/room.cpp
    engines/ags/engine/ac/route_finder.cpp
    engines/ags/engine/ac/scriptcontainers.cpp
    engines/ags/engine/ac/string.cpp
    engines/ags/engine/ac/system.cpp
    engines/ags/engine/ac/textbox.cpp
    engines/ags/engine/script/script_api.h


diff --git a/engines/ags/engine/ac/button.cpp b/engines/ags/engine/ac/button.cpp
index e533a6384b..e6e1267e95 100644
--- a/engines/ags/engine/ac/button.cpp
+++ b/engines/ags/engine/ac/button.cpp
@@ -315,7 +315,7 @@ RuntimeScriptValue Sc_Button_Animate(void *self, const RuntimeScriptValue *param
 
 // const char* | GUIButton *butt
 RuntimeScriptValue Sc_Button_GetText_New(void *self, const RuntimeScriptValue *params, int32_t param_count) {
-	API_OBJCALL_OBJ(GUIButton, const char, myScriptStringImpl, Button_GetText_New);
+	API_CONST_OBJCALL_OBJ(GUIButton, const char, myScriptStringImpl, Button_GetText_New);
 }
 
 // void | GUIButton *butt, char *buffer
diff --git a/engines/ags/engine/ac/character.cpp b/engines/ags/engine/ac/character.cpp
index 3bb7e6c740..5e7623a7aa 100644
--- a/engines/ags/engine/ac/character.cpp
+++ b/engines/ags/engine/ac/character.cpp
@@ -2930,7 +2930,7 @@ RuntimeScriptValue Sc_Character_GetPropertyText(void *self, const RuntimeScriptV
 
 // const char* (CharacterInfo *chaa, const char *property)
 RuntimeScriptValue Sc_Character_GetTextProperty(void *self, const RuntimeScriptValue *params, int32_t param_count) {
-	API_OBJCALL_OBJ_POBJ(CharacterInfo, const char, myScriptStringImpl, Character_GetTextProperty, const char);
+	API_CONST_OBJCALL_OBJ_POBJ(CharacterInfo, const char, myScriptStringImpl, Character_GetTextProperty, const char);
 }
 
 RuntimeScriptValue Sc_Character_SetProperty(void *self, const RuntimeScriptValue *params, int32_t param_count) {
@@ -3364,7 +3364,7 @@ RuntimeScriptValue Sc_Character_GetDestinationY(void *self, const RuntimeScriptV
 
 // const char* (CharacterInfo *chaa)
 RuntimeScriptValue Sc_Character_GetName(void *self, const RuntimeScriptValue *params, int32_t param_count) {
-	API_OBJCALL_OBJ(CharacterInfo, const char, myScriptStringImpl, Character_GetName);
+	API_CONST_OBJCALL_OBJ(CharacterInfo, const char, myScriptStringImpl, Character_GetName);
 }
 
 // void (CharacterInfo *chaa, const char *newName)
diff --git a/engines/ags/engine/ac/dialog.cpp b/engines/ags/engine/ac/dialog.cpp
index 6c7d6d9f1a..92c3e0fb45 100644
--- a/engines/ags/engine/ac/dialog.cpp
+++ b/engines/ags/engine/ac/dialog.cpp
@@ -1182,7 +1182,7 @@ RuntimeScriptValue Sc_Dialog_GetOptionState(void *self, const RuntimeScriptValue
 
 // const char* (ScriptDialog *sd, int option)
 RuntimeScriptValue Sc_Dialog_GetOptionText(void *self, const RuntimeScriptValue *params, int32_t param_count) {
-	API_OBJCALL_OBJ_PINT(ScriptDialog, const char, myScriptStringImpl, Dialog_GetOptionText);
+	API_CONST_OBJCALL_OBJ_PINT(ScriptDialog, const char, myScriptStringImpl, Dialog_GetOptionText);
 }
 
 // int (ScriptDialog *sd, int option)
diff --git a/engines/ags/engine/ac/file.cpp b/engines/ags/engine/ac/file.cpp
index ae826d9489..d20793aaea 100644
--- a/engines/ags/engine/ac/file.cpp
+++ b/engines/ags/engine/ac/file.cpp
@@ -662,7 +662,7 @@ RuntimeScriptValue Sc_File_ReadRawLine(void *self, const RuntimeScriptValue *par
 
 // const char* (sc_File *fil)
 RuntimeScriptValue Sc_File_ReadRawLineBack(void *self, const RuntimeScriptValue *params, int32_t param_count) {
-	API_OBJCALL_OBJ(sc_File, const char, myScriptStringImpl, File_ReadRawLineBack);
+	API_CONST_OBJCALL_OBJ(sc_File, const char, myScriptStringImpl, File_ReadRawLineBack);
 }
 
 // void (sc_File *fil, char *toread)
@@ -672,7 +672,7 @@ RuntimeScriptValue Sc_File_ReadString(void *self, const RuntimeScriptValue *para
 
 // const char* (sc_File *fil)
 RuntimeScriptValue Sc_File_ReadStringBack(void *self, const RuntimeScriptValue *params, int32_t param_count) {
-	API_OBJCALL_OBJ(sc_File, const char, myScriptStringImpl, File_ReadStringBack);
+	API_CONST_OBJCALL_OBJ(sc_File, const char, myScriptStringImpl, File_ReadStringBack);
 }
 
 // void (sc_File *fil, int towrite)
diff --git a/engines/ags/engine/ac/game.cpp b/engines/ags/engine/ac/game.cpp
index b1f40dc1aa..561a0d0c8f 100644
--- a/engines/ags/engine/ac/game.cpp
+++ b/engines/ags/engine/ac/game.cpp
@@ -1988,7 +1988,7 @@ RuntimeScriptValue Sc_Game_GetFrameCountForLoop(const RuntimeScriptValue *params
 
 // const char* (int x, int y)
 RuntimeScriptValue Sc_Game_GetLocationName(const RuntimeScriptValue *params, int32_t param_count) {
-	API_SCALL_OBJ_PINT2(const char, myScriptStringImpl, Game_GetLocationName);
+	API_CONST_SCALL_OBJ_PINT2(const char, myScriptStringImpl, Game_GetLocationName);
 }
 
 // int (int viewNumber)
@@ -2008,7 +2008,7 @@ RuntimeScriptValue Sc_Game_GetRunNextSettingForLoop(const RuntimeScriptValue *pa
 
 // const char* (int slnum)
 RuntimeScriptValue Sc_Game_GetSaveSlotDescription(const RuntimeScriptValue *params, int32_t param_count) {
-	API_SCALL_OBJ_PINT(const char, myScriptStringImpl, Game_GetSaveSlotDescription);
+	API_CONST_SCALL_OBJ_PINT(const char, myScriptStringImpl, Game_GetSaveSlotDescription);
 }
 
 // ScriptViewFrame* (int viewNumber, int loopNumber, int frame)
@@ -2018,7 +2018,7 @@ RuntimeScriptValue Sc_Game_GetViewFrame(const RuntimeScriptValue *params, int32_
 
 // const char* (const char *msg)
 RuntimeScriptValue Sc_Game_InputBox(const RuntimeScriptValue *params, int32_t param_count) {
-	API_SCALL_OBJ_POBJ(const char, myScriptStringImpl, Game_InputBox, const char);
+	API_CONST_SCALL_OBJ_POBJ(const char, myScriptStringImpl, Game_InputBox, const char);
 }
 
 // int (const char *newFolder)
@@ -2043,7 +2043,7 @@ RuntimeScriptValue Sc_Game_GetDialogCount(const RuntimeScriptValue *params, int3
 
 // const char *()
 RuntimeScriptValue Sc_Game_GetFileName(const RuntimeScriptValue *params, int32_t param_count) {
-	API_SCALL_OBJ(const char, myScriptStringImpl, Game_GetFileName);
+	API_CONST_SCALL_OBJ(const char, myScriptStringImpl, Game_GetFileName);
 }
 
 // int ()
@@ -2053,12 +2053,12 @@ RuntimeScriptValue Sc_Game_GetFontCount(const RuntimeScriptValue *params, int32_
 
 // const char* (int index)
 RuntimeScriptValue Sc_Game_GetGlobalMessages(const RuntimeScriptValue *params, int32_t param_count) {
-	API_SCALL_OBJ_PINT(const char, myScriptStringImpl, Game_GetGlobalMessages);
+	API_CONST_SCALL_OBJ_PINT(const char, myScriptStringImpl, Game_GetGlobalMessages);
 }
 
 // const char* (int index)
 RuntimeScriptValue Sc_Game_GetGlobalStrings(const RuntimeScriptValue *params, int32_t param_count) {
-	API_SCALL_OBJ_PINT(const char, myScriptStringImpl, Game_GetGlobalStrings);
+	API_CONST_SCALL_OBJ_PINT(const char, myScriptStringImpl, Game_GetGlobalStrings);
 }
 
 // void  (int index, char *newval);
@@ -2108,7 +2108,7 @@ RuntimeScriptValue Sc_Game_GetMouseCursorCount(const RuntimeScriptValue *params,
 
 // const char *()
 RuntimeScriptValue Sc_Game_GetName(const RuntimeScriptValue *params, int32_t param_count) {
-	API_SCALL_OBJ(const char, myScriptStringImpl, Game_GetName);
+	API_CONST_SCALL_OBJ(const char, myScriptStringImpl, Game_GetName);
 }
 
 // void (const char *newName)
@@ -2163,7 +2163,7 @@ RuntimeScriptValue Sc_Game_SetTextReadingSpeed(const RuntimeScriptValue *params,
 
 // const char* ()
 RuntimeScriptValue Sc_Game_GetTranslationFilename(const RuntimeScriptValue *params, int32_t param_count) {
-	API_SCALL_OBJ(const char, myScriptStringImpl, Game_GetTranslationFilename);
+	API_CONST_SCALL_OBJ(const char, myScriptStringImpl, Game_GetTranslationFilename);
 }
 
 // int ()
diff --git a/engines/ags/engine/ac/global_api.cpp b/engines/ags/engine/ac/global_api.cpp
index 49d411b5e8..20fd5507a4 100644
--- a/engines/ags/engine/ac/global_api.cpp
+++ b/engines/ags/engine/ac/global_api.cpp
@@ -691,7 +691,7 @@ RuntimeScriptValue Sc_sc_GetTime(const RuntimeScriptValue *params, int32_t param
 
 // char * (const char *text)
 RuntimeScriptValue Sc_get_translation(const RuntimeScriptValue *params, int32_t param_count) {
-	API_SCALL_OBJ_POBJ(char, myScriptStringImpl, get_translation, const char);
+	API_CONST_SCALL_OBJ_POBJ(const char, myScriptStringImpl, get_translation, const char);
 }
 
 // int  (char* buffer)
diff --git a/engines/ags/engine/ac/hotspot.cpp b/engines/ags/engine/ac/hotspot.cpp
index 09e4948d33..02f9189158 100644
--- a/engines/ags/engine/ac/hotspot.cpp
+++ b/engines/ags/engine/ac/hotspot.cpp
@@ -166,7 +166,7 @@ RuntimeScriptValue Sc_Hotspot_GetPropertyText(void *self, const RuntimeScriptVal
 
 // const char* (ScriptHotspot *hss, const char *property)
 RuntimeScriptValue Sc_Hotspot_GetTextProperty(void *self, const RuntimeScriptValue *params, int32_t param_count) {
-	API_OBJCALL_OBJ_POBJ(ScriptHotspot, const char, myScriptStringImpl, Hotspot_GetTextProperty, const char);
+	API_CONST_OBJCALL_OBJ_POBJ(ScriptHotspot, const char, myScriptStringImpl, Hotspot_GetTextProperty, const char);
 }
 
 RuntimeScriptValue Sc_Hotspot_SetProperty(void *self, const RuntimeScriptValue *params, int32_t param_count) {
@@ -203,7 +203,7 @@ RuntimeScriptValue Sc_Hotspot_GetID(void *self, const RuntimeScriptValue *params
 
 // const char* (ScriptHotspot *hss)
 RuntimeScriptValue Sc_Hotspot_GetName_New(void *self, const RuntimeScriptValue *params, int32_t param_count) {
-	API_OBJCALL_OBJ(ScriptHotspot, const char, myScriptStringImpl, Hotspot_GetName_New);
+	API_CONST_OBJCALL_OBJ(ScriptHotspot, const char, myScriptStringImpl, Hotspot_GetName_New);
 }
 
 // int (ScriptHotspot *hss)
diff --git a/engines/ags/engine/ac/inventoryitem.cpp b/engines/ags/engine/ac/inventoryitem.cpp
index a9b45c23e6..8701a874d2 100644
--- a/engines/ags/engine/ac/inventoryitem.cpp
+++ b/engines/ags/engine/ac/inventoryitem.cpp
@@ -160,7 +160,7 @@ RuntimeScriptValue Sc_InventoryItem_GetPropertyText(void *self, const RuntimeScr
 
 // const char* (ScriptInvItem *scii, const char *property)
 RuntimeScriptValue Sc_InventoryItem_GetTextProperty(void *self, const RuntimeScriptValue *params, int32_t param_count) {
-	API_OBJCALL_OBJ_POBJ(ScriptInvItem, const char, myScriptStringImpl, InventoryItem_GetTextProperty, const char);
+	API_CONST_OBJCALL_OBJ_POBJ(ScriptInvItem, const char, myScriptStringImpl, InventoryItem_GetTextProperty, const char);
 }
 
 RuntimeScriptValue Sc_InventoryItem_SetProperty(void *self, const RuntimeScriptValue *params, int32_t param_count) {
@@ -208,7 +208,7 @@ RuntimeScriptValue Sc_InventoryItem_GetID(void *self, const RuntimeScriptValue *
 
 // const char* (ScriptInvItem *invitem)
 RuntimeScriptValue Sc_InventoryItem_GetName_New(void *self, const RuntimeScriptValue *params, int32_t param_count) {
-	API_OBJCALL_OBJ(ScriptInvItem, const char, myScriptStringImpl, InventoryItem_GetName_New);
+	API_CONST_OBJCALL_OBJ(ScriptInvItem, const char, myScriptStringImpl, InventoryItem_GetName_New);
 }
 
 
diff --git a/engines/ags/engine/ac/label.cpp b/engines/ags/engine/ac/label.cpp
index 29249cef09..92876a3188 100644
--- a/engines/ags/engine/ac/label.cpp
+++ b/engines/ags/engine/ac/label.cpp
@@ -130,7 +130,7 @@ RuntimeScriptValue Sc_Label_SetFont(void *self, const RuntimeScriptValue *params
 
 // const char* (GUILabel *labl)
 RuntimeScriptValue Sc_Label_GetText_New(void *self, const RuntimeScriptValue *params, int32_t param_count) {
-	API_OBJCALL_OBJ(GUILabel, const char, myScriptStringImpl, Label_GetText_New);
+	API_CONST_OBJCALL_OBJ(GUILabel, const char, myScriptStringImpl, Label_GetText_New);
 }
 
 // int (GUILabel *labl)
diff --git a/engines/ags/engine/ac/listbox.cpp b/engines/ags/engine/ac/listbox.cpp
index baeeab7222..c24a6a2db4 100644
--- a/engines/ags/engine/ac/listbox.cpp
+++ b/engines/ags/engine/ac/listbox.cpp
@@ -489,7 +489,7 @@ RuntimeScriptValue Sc_ListBox_GetItemCount(void *self, const RuntimeScriptValue
 
 // const char* (GUIListBox *listbox, int index)
 RuntimeScriptValue Sc_ListBox_GetItems(void *self, const RuntimeScriptValue *params, int32_t param_count) {
-	API_OBJCALL_OBJ_PINT(GUIListBox, const char, myScriptStringImpl, ListBox_GetItems);
+	API_CONST_OBJCALL_OBJ_PINT(GUIListBox, const char, myScriptStringImpl, ListBox_GetItems);
 }
 
 // int (GUIListBox *listbox)
diff --git a/engines/ags/engine/ac/object.cpp b/engines/ags/engine/ac/object.cpp
index 58b52be1a1..64871509e8 100644
--- a/engines/ags/engine/ac/object.cpp
+++ b/engines/ags/engine/ac/object.cpp
@@ -596,7 +596,7 @@ RuntimeScriptValue Sc_Object_GetPropertyText(void *self, const RuntimeScriptValu
 
 //const char* (ScriptObject *objj, const char *property)
 RuntimeScriptValue Sc_Object_GetTextProperty(void *self, const RuntimeScriptValue *params, int32_t param_count) {
-	API_OBJCALL_OBJ_POBJ(ScriptObject, const char, myScriptStringImpl, Object_GetTextProperty, const char);
+	API_CONST_OBJCALL_OBJ_POBJ(ScriptObject, const char, myScriptStringImpl, Object_GetTextProperty, const char);
 }
 
 RuntimeScriptValue Sc_Object_SetProperty(void *self, const RuntimeScriptValue *params, int32_t param_count) {
@@ -802,7 +802,7 @@ RuntimeScriptValue Sc_Object_GetMoving(void *self, const RuntimeScriptValue *par
 
 // const char* (ScriptObject *objj)
 RuntimeScriptValue Sc_Object_GetName_New(void *self, const RuntimeScriptValue *params, int32_t param_count) {
-	API_OBJCALL_OBJ(ScriptObject, const char, myScriptStringImpl, Object_GetName_New);
+	API_CONST_OBJCALL_OBJ(ScriptObject, const char, myScriptStringImpl, Object_GetName_New);
 }
 
 RuntimeScriptValue Sc_Object_GetScaling(void *self, const RuntimeScriptValue *params, int32_t param_count) {
diff --git a/engines/ags/engine/ac/parser.cpp b/engines/ags/engine/ac/parser.cpp
index 43a3ddc63f..ec949675ad 100644
--- a/engines/ags/engine/ac/parser.cpp
+++ b/engines/ags/engine/ac/parser.cpp
@@ -320,7 +320,7 @@ RuntimeScriptValue Sc_ParseText(const RuntimeScriptValue *params, int32_t param_
 
 // const char* ()
 RuntimeScriptValue Sc_Parser_SaidUnknownWord(const RuntimeScriptValue *params, int32_t param_count) {
-	API_SCALL_OBJ(const char, myScriptStringImpl, Parser_SaidUnknownWord);
+	API_CONST_SCALL_OBJ(const char, myScriptStringImpl, Parser_SaidUnknownWord);
 }
 
 // int  (char*checkwords)
diff --git a/engines/ags/engine/ac/room.cpp b/engines/ags/engine/ac/room.cpp
index 1cf81d7c5d..6fa660d393 100644
--- a/engines/ags/engine/ac/room.cpp
+++ b/engines/ags/engine/ac/room.cpp
@@ -1121,7 +1121,7 @@ RuntimeScriptValue Sc_Room_GetProperty(const RuntimeScriptValue *params, int32_t
 
 // const char* (const char *property)
 RuntimeScriptValue Sc_Room_GetTextProperty(const RuntimeScriptValue *params, int32_t param_count) {
-	API_SCALL_OBJ_POBJ(const char, myScriptStringImpl, Room_GetTextProperty, const char);
+	API_CONST_SCALL_OBJ_POBJ(const char, myScriptStringImpl, Room_GetTextProperty, const char);
 }
 
 RuntimeScriptValue Sc_Room_SetProperty(const RuntimeScriptValue *params, int32_t param_count) {
@@ -1155,7 +1155,7 @@ RuntimeScriptValue Sc_Room_GetLeftEdge(const RuntimeScriptValue *params, int32_t
 
 // const char* (int index)
 RuntimeScriptValue Sc_Room_GetMessages(const RuntimeScriptValue *params, int32_t param_count) {
-	API_SCALL_OBJ_PINT(const char, myScriptStringImpl, Room_GetMessages);
+	API_CONST_SCALL_OBJ_PINT(const char, myScriptStringImpl, Room_GetMessages);
 }
 
 // int ()
diff --git a/engines/ags/engine/ac/route_finder.cpp b/engines/ags/engine/ac/route_finder.cpp
index b5722d3b10..421f08cb54 100644
--- a/engines/ags/engine/ac/route_finder.cpp
+++ b/engines/ags/engine/ac/route_finder.cpp
@@ -33,6 +33,7 @@ using AGS::Shared::Bitmap;
 
 class IRouteFinder {
 public:
+	virtual ~IRouteFinder() {}
 	virtual void init_pathfinder() = 0;
 	virtual void shutdown_pathfinder() = 0;
 	virtual void set_wallscreen(Bitmap *wallscreen) = 0;
@@ -45,6 +46,8 @@ public:
 
 class AGSRouteFinder : public IRouteFinder {
 public:
+	virtual ~AGSRouteFinder() {}
+
 	void init_pathfinder() override {
 		AGS::Engine::RouteFinder::init_pathfinder();
 	}
@@ -73,6 +76,8 @@ public:
 
 class AGSLegacyRouteFinder : public IRouteFinder {
 public:
+	virtual ~AGSLegacyRouteFinder() {}
+
 	void init_pathfinder() override {
 		AGS::Engine::RouteFinderLegacy::init_pathfinder();
 	}
diff --git a/engines/ags/engine/ac/scriptcontainers.cpp b/engines/ags/engine/ac/scriptcontainers.cpp
index 4bf42ca474..10700dca70 100644
--- a/engines/ags/engine/ac/scriptcontainers.cpp
+++ b/engines/ags/engine/ac/scriptcontainers.cpp
@@ -147,7 +147,7 @@ RuntimeScriptValue Sc_Dict_Contains(void *self, const RuntimeScriptValue *params
 }
 
 RuntimeScriptValue Sc_Dict_Get(void *self, const RuntimeScriptValue *params, int32_t param_count) {
-	API_OBJCALL_OBJ_POBJ(ScriptDictBase, const char, myScriptStringImpl, Dict_Get, const char);
+	API_CONST_OBJCALL_OBJ_POBJ(ScriptDictBase, const char, myScriptStringImpl, Dict_Get, const char);
 }
 
 RuntimeScriptValue Sc_Dict_Remove(void *self, const RuntimeScriptValue *params, int32_t param_count) {
diff --git a/engines/ags/engine/ac/string.cpp b/engines/ags/engine/ac/string.cpp
index b33ee59eb4..305629a497 100644
--- a/engines/ags/engine/ac/string.cpp
+++ b/engines/ags/engine/ac/string.cpp
@@ -310,12 +310,12 @@ RuntimeScriptValue Sc_String_IsNullOrEmpty(const RuntimeScriptValue *params, int
 
 // const char* (const char *thisString, const char *extrabit)
 RuntimeScriptValue Sc_String_Append(void *self, const RuntimeScriptValue *params, int32_t param_count) {
-	API_OBJCALL_OBJ_POBJ(const char, const char, myScriptStringImpl, String_Append, const char);
+	API_CONST_OBJCALL_OBJ_POBJ(const char, const char, myScriptStringImpl, String_Append, const char);
 }
 
 // const char* (const char *thisString, char extraOne)
 RuntimeScriptValue Sc_String_AppendChar(void *self, const RuntimeScriptValue *params, int32_t param_count) {
-	API_OBJCALL_OBJ_PINT(const char, const char, myScriptStringImpl, String_AppendChar);
+	API_CONST_OBJCALL_OBJ_PINT(const char, const char, myScriptStringImpl, String_AppendChar);
 }
 
 // int (const char *thisString, const char *otherString, bool caseSensitive)
@@ -330,7 +330,7 @@ RuntimeScriptValue Sc_StrContains(void *self, const RuntimeScriptValue *params,
 
 // const char* (const char *srcString)
 RuntimeScriptValue Sc_String_Copy(void *self, const RuntimeScriptValue *params, int32_t param_count) {
-	API_OBJCALL_OBJ(const char, const char, myScriptStringImpl, String_Copy);
+	API_CONST_OBJCALL_OBJ(const char, const char, myScriptStringImpl, String_Copy);
 }
 
 // int (const char *thisString, const char *checkForString, bool caseSensitive)
@@ -341,22 +341,22 @@ RuntimeScriptValue Sc_String_EndsWith(void *self, const RuntimeScriptValue *para
 // const char* (const char *texx, ...)
 RuntimeScriptValue Sc_String_Format(const RuntimeScriptValue *params, int32_t param_count) {
 	API_SCALL_SCRIPT_SPRINTF(String_Format, 1);
-	return RuntimeScriptValue().SetDynamicObject((void *)CreateNewScriptString(scsf_buffer), &myScriptStringImpl);
+	return RuntimeScriptValue().SetDynamicObject(const_cast<char *>(CreateNewScriptString(scsf_buffer)), &myScriptStringImpl);
 }
 
 // const char* (const char *thisString)
 RuntimeScriptValue Sc_String_LowerCase(void *self, const RuntimeScriptValue *params, int32_t param_count) {
-	API_OBJCALL_OBJ(const char, const char, myScriptStringImpl, String_LowerCase);
+	API_CONST_OBJCALL_OBJ(const char, const char, myScriptStringImpl, String_LowerCase);
 }
 
 // const char* (const char *thisString, const char *lookForText, const char *replaceWithText, bool caseSensitive)
 RuntimeScriptValue Sc_String_Replace(void *self, const RuntimeScriptValue *params, int32_t param_count) {
-	API_OBJCALL_OBJ_POBJ2_PBOOL(const char, const char, myScriptStringImpl, String_Replace, const char, const char);
+	API_CONST_OBJCALL_OBJ_POBJ2_PBOOL(const char, const char, myScriptStringImpl, String_Replace, const char, const char);
 }
 
 // const char* (const char *thisString, int index, char newChar)
 RuntimeScriptValue Sc_String_ReplaceCharAt(void *self, const RuntimeScriptValue *params, int32_t param_count) {
-	API_OBJCALL_OBJ_PINT2(const char, const char, myScriptStringImpl, String_ReplaceCharAt);
+	API_CONST_OBJCALL_OBJ_PINT2(const char, const char, myScriptStringImpl, String_ReplaceCharAt);
 }
 
 // int (const char *thisString, const char *checkForString, bool caseSensitive)
@@ -366,17 +366,17 @@ RuntimeScriptValue Sc_String_StartsWith(void *self, const RuntimeScriptValue *pa
 
 // const char* (const char *thisString, int index, int length)
 RuntimeScriptValue Sc_String_Substring(void *self, const RuntimeScriptValue *params, int32_t param_count) {
-	API_OBJCALL_OBJ_PINT2(const char, const char, myScriptStringImpl, String_Substring);
+	API_CONST_OBJCALL_OBJ_PINT2(const char, const char, myScriptStringImpl, String_Substring);
 }
 
 // const char* (const char *thisString, int length)
 RuntimeScriptValue Sc_String_Truncate(void *self, const RuntimeScriptValue *params, int32_t param_count) {
-	API_OBJCALL_OBJ_PINT(const char, const char, myScriptStringImpl, String_Truncate);
+	API_CONST_OBJCALL_OBJ_PINT(const char, const char, myScriptStringImpl, String_Truncate);
 }
 
 // const char* (const char *thisString)
 RuntimeScriptValue Sc_String_UpperCase(void *self, const RuntimeScriptValue *params, int32_t param_count) {
-	API_OBJCALL_OBJ(const char, const char, myScriptStringImpl, String_UpperCase);
+	API_CONST_OBJCALL_OBJ(const char, const char, myScriptStringImpl, String_UpperCase);
 }
 
 // FLOAT_RETURN_TYPE (const char *theString);
diff --git a/engines/ags/engine/ac/system.cpp b/engines/ags/engine/ac/system.cpp
index 954d8ff9cd..02d4c0a2d7 100644
--- a/engines/ags/engine/ac/system.cpp
+++ b/engines/ags/engine/ac/system.cpp
@@ -305,7 +305,7 @@ RuntimeScriptValue Sc_System_GetSupportsGammaControl(const RuntimeScriptValue *p
 
 // const char *()
 RuntimeScriptValue Sc_System_GetVersion(const RuntimeScriptValue *params, int32_t param_count) {
-	API_SCALL_OBJ(const char, myScriptStringImpl, System_GetVersion);
+	API_CONST_SCALL_OBJ(const char, myScriptStringImpl, System_GetVersion);
 }
 
 // int ()
@@ -348,7 +348,7 @@ RuntimeScriptValue Sc_System_SetWindowed(const RuntimeScriptValue *params, int32
 
 // const char *()
 RuntimeScriptValue Sc_System_GetRuntimeInfo(const RuntimeScriptValue *params, int32_t param_count) {
-	API_SCALL_OBJ(const char, myScriptStringImpl, System_GetRuntimeInfo);
+	API_CONST_SCALL_OBJ(const char, myScriptStringImpl, System_GetRuntimeInfo);
 }
 
 RuntimeScriptValue Sc_System_GetRenderAtScreenResolution(const RuntimeScriptValue *params, int32_t param_count) {
diff --git a/engines/ags/engine/ac/textbox.cpp b/engines/ags/engine/ac/textbox.cpp
index 31b35d74cb..c8cea8558e 100644
--- a/engines/ags/engine/ac/textbox.cpp
+++ b/engines/ags/engine/ac/textbox.cpp
@@ -128,7 +128,7 @@ RuntimeScriptValue Sc_TextBox_SetShowBorder(void *self, const RuntimeScriptValue
 
 // const char* (GUITextBox *texbox)
 RuntimeScriptValue Sc_TextBox_GetText_New(void *self, const RuntimeScriptValue *params, int32_t param_count) {
-	API_OBJCALL_OBJ(GUITextBox, const char *, myScriptStringImpl, TextBox_GetText_New);
+	API_CONST_OBJCALL_OBJ(GUITextBox, const char, myScriptStringImpl, TextBox_GetText_New);
 }
 
 // int (GUITextBox *guit)
diff --git a/engines/ags/engine/script/script_api.h b/engines/ags/engine/script/script_api.h
index 6cd64d87a0..15c129c889 100644
--- a/engines/ags/engine/script/script_api.h
+++ b/engines/ags/engine/script/script_api.h
@@ -287,10 +287,17 @@ inline const char *ScriptVSprintf(char *buffer, size_t buf_length, const char *f
 #define API_SCALL_OBJ(RET_CLASS, RET_MGR, FUNCTION) \
 	return RuntimeScriptValue().SetDynamicObject((void*)(RET_CLASS*)FUNCTION(), &RET_MGR)
 
+#define API_CONST_SCALL_OBJ(RET_CLASS, RET_MGR, FUNCTION) \
+	return RuntimeScriptValue().SetDynamicObject(const_cast<void *>((const void *)(RET_CLASS*)FUNCTION()), &RET_MGR)
+
 #define API_SCALL_OBJ_PINT(RET_CLASS, RET_MGR, FUNCTION) \
 	ASSERT_PARAM_COUNT(FUNCTION, 1); \
 	return RuntimeScriptValue().SetDynamicObject((void*)(RET_CLASS*)FUNCTION(params[0].IValue), &RET_MGR)
 
+#define API_CONST_SCALL_OBJ_PINT(RET_CLASS, RET_MGR, FUNCTION) \
+	ASSERT_PARAM_COUNT(FUNCTION, 1); \
+	return RuntimeScriptValue().SetDynamicObject(const_cast<void *>((const void *)(RET_CLASS*)FUNCTION(params[0].IValue)), &RET_MGR)
+
 #define API_SCALL_OBJ_POBJ_PINT_PBOOL(RET_CLASS, RET_MGR, FUNCTION, P1CLASS) \
 	ASSERT_PARAM_COUNT(FUNCTION, 3); \
 	return RuntimeScriptValue().SetDynamicObject((void*)(RET_CLASS*)FUNCTION((P1CLASS*)params[0].Ptr, params[1].IValue, params[2].GetAsBool()), &RET_MGR)
@@ -299,6 +306,10 @@ inline const char *ScriptVSprintf(char *buffer, size_t buf_length, const char *f
 	ASSERT_PARAM_COUNT(FUNCTION, 2); \
 	return RuntimeScriptValue().SetDynamicObject((void*)(RET_CLASS*)FUNCTION(params[0].IValue, params[1].IValue), &RET_MGR)
 
+#define API_CONST_SCALL_OBJ_PINT2(RET_CLASS, RET_MGR, FUNCTION) \
+	ASSERT_PARAM_COUNT(FUNCTION, 2); \
+	return RuntimeScriptValue().SetDynamicObject(const_cast<void *>((const void *)(RET_CLASS*)FUNCTION(params[0].IValue, params[1].IValue)), &RET_MGR)
+
 #define API_SCALL_OBJ_PINT3_POBJ(RET_CLASS, RET_MGR, FUNCTION, P1CLASS) \
 	ASSERT_PARAM_COUNT(FUNCTION, 4); \
 	return RuntimeScriptValue().SetDynamicObject((void*)(RET_CLASS*)FUNCTION(params[0].IValue, params[1].IValue, params[2].IValue, (P1CLASS*)params[3].Ptr), &RET_MGR)
@@ -307,6 +318,10 @@ inline const char *ScriptVSprintf(char *buffer, size_t buf_length, const char *f
 	ASSERT_PARAM_COUNT(FUNCTION, 1); \
 	return RuntimeScriptValue().SetDynamicObject((void*)(RET_CLASS*)FUNCTION((P1CLASS*)params[0].Ptr), &RET_MGR)
 
+#define API_CONST_SCALL_OBJ_POBJ(RET_CLASS, RET_MGR, FUNCTION, P1CLASS) \
+	ASSERT_PARAM_COUNT(FUNCTION, 1); \
+	return RuntimeScriptValue().SetDynamicObject(const_cast<void *>((const void *)(RET_CLASS*)FUNCTION((P1CLASS*)params[0].Ptr)), &RET_MGR)
+
 #define API_SCALL_OBJAUTO(RET_CLASS, FUNCTION) \
 	RET_CLASS* ret_obj = FUNCTION(); \
 	return RuntimeScriptValue().SetDynamicObject(ret_obj, ret_obj)
@@ -523,18 +538,34 @@ inline const char *ScriptVSprintf(char *buffer, size_t buf_length, const char *f
 	ASSERT_OBJ_PARAM_COUNT(METHOD, 3); \
 	return RuntimeScriptValue().SetDynamicObject((void*)METHOD((CLASS*)self, (P1CLASS*)params[0].Ptr, (P2CLASS*)params[1].Ptr, params[2].GetAsBool()), &RET_MGR)
 
+#define API_CONST_OBJCALL_OBJ_POBJ2_PBOOL(CLASS, RET_CLASS, RET_MGR, METHOD, P1CLASS, P2CLASS) \
+	ASSERT_OBJ_PARAM_COUNT(METHOD, 3); \
+	return RuntimeScriptValue().SetDynamicObject(const_cast<void *>((const void *)METHOD((CLASS*)self, (P1CLASS*)params[0].Ptr, (P2CLASS*)params[1].Ptr, params[2].GetAsBool())), &RET_MGR)
+
 #define API_OBJCALL_OBJ(CLASS, RET_CLASS, RET_MGR, METHOD) \
 	ASSERT_SELF(METHOD); \
 	return RuntimeScriptValue().SetDynamicObject((void*)(RET_CLASS*)METHOD((CLASS*)self), &RET_MGR)
 
+#define API_CONST_OBJCALL_OBJ(CLASS, RET_CLASS, RET_MGR, METHOD) \
+	ASSERT_SELF(METHOD); \
+	return RuntimeScriptValue().SetDynamicObject(const_cast<void *>((const void *)(RET_CLASS*)METHOD((CLASS*)self)), &RET_MGR)
+
 #define API_OBJCALL_OBJ_PINT(CLASS, RET_CLASS, RET_MGR, METHOD) \
 	ASSERT_OBJ_PARAM_COUNT(METHOD, 1); \
 	return RuntimeScriptValue().SetDynamicObject((void*)(RET_CLASS*)METHOD((CLASS*)self, params[0].IValue), &RET_MGR)
 
+#define API_CONST_OBJCALL_OBJ_PINT(CLASS, RET_CLASS, RET_MGR, METHOD) \
+	ASSERT_OBJ_PARAM_COUNT(METHOD, 1); \
+	return RuntimeScriptValue().SetDynamicObject(const_cast<void *>((const void *)(RET_CLASS*)METHOD((CLASS*)self, params[0].IValue)), &RET_MGR)
+
 #define API_OBJCALL_OBJ_PINT2(CLASS, RET_CLASS, RET_MGR, METHOD) \
 	ASSERT_OBJ_PARAM_COUNT(METHOD, 2); \
 	return RuntimeScriptValue().SetDynamicObject((void*)(RET_CLASS*)METHOD((CLASS*)self, params[0].IValue, params[1].IValue), &RET_MGR)
 
+#define API_CONST_OBJCALL_OBJ_PINT2(CLASS, RET_CLASS, RET_MGR, METHOD) \
+	ASSERT_OBJ_PARAM_COUNT(METHOD, 2); \
+	return RuntimeScriptValue().SetDynamicObject(const_cast<void *>((const void *)(RET_CLASS*)METHOD((CLASS*)self, params[0].IValue, params[1].IValue)), &RET_MGR)
+
 #define API_OBJCALL_OBJ_PINT3(CLASS, RET_CLASS, RET_MGR, METHOD) \
 	ASSERT_OBJ_PARAM_COUNT(METHOD, 3); \
 	return RuntimeScriptValue().SetDynamicObject((void*)(RET_CLASS*)METHOD((CLASS*)self, params[0].IValue, params[1].IValue, params[2].IValue), &RET_MGR)
@@ -543,6 +574,10 @@ inline const char *ScriptVSprintf(char *buffer, size_t buf_length, const char *f
 	ASSERT_OBJ_PARAM_COUNT(METHOD, 1); \
 	return RuntimeScriptValue().SetDynamicObject((void*)(RET_CLASS*)METHOD((CLASS*)self, (P1CLASS*)params[0].Ptr), &RET_MGR)
 
+#define API_CONST_OBJCALL_OBJ_POBJ(CLASS, RET_CLASS, RET_MGR, METHOD, P1CLASS) \
+	ASSERT_OBJ_PARAM_COUNT(METHOD, 1); \
+	return RuntimeScriptValue().SetDynamicObject(const_cast<void *>((const void *)(RET_CLASS*)METHOD((CLASS*)self, (P1CLASS*)params[0].Ptr)), &RET_MGR)
+
 #define API_OBJCALL_OBJAUTO(CLASS, RET_CLASS, METHOD) \
 	ASSERT_SELF(METHOD); \
 	RET_CLASS* ret_obj = METHOD((CLASS*)self); \


Commit: bb23db380f732a8c47f205871461a454c3b5850c
    https://github.com/scummvm/scummvm/commit/bb23db380f732a8c47f205871461a454c3b5850c
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Get game filename from detection entry

Changed paths:
    engines/ags/ags.cpp
    engines/ags/engine/main/main.h


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index ad075c5865..79f95a1278 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -61,7 +61,7 @@ using namespace Engine;
 String appDirectory; // Needed for library loading
 String cmdGameDataPath;
 
-char **global_argv = nullptr;
+const char **global_argv = nullptr;
 int    global_argc = 0;
 
 extern GameSetup usetup;
@@ -135,7 +135,7 @@ void main_create_platform_driver() {
 	platform = AGSPlatformDriver::GetDriver();
 }
 
-void main_init(int argc, char *argv[]) {
+void main_init(int argc, const char *argv[]) {
 	EngineVersion = Version(ACI_VERSION_STR " " SPECIAL_VERSION);
 
 	SavedgameLowestBackwardCompatVersion = Version(SVG_VERSION_BWCOMPAT_MAJOR, SVG_VERSION_BWCOMPAT_MINOR, SVG_VERSION_BWCOMPAT_RELEASE, SVG_VERSION_BWCOMPAT_REVISION);
@@ -159,7 +159,7 @@ void main_print_help() {
 	// No implementation
 }
 
-static int main_process_cmdline(ConfigTree &cfg, int argc, char *argv[]) {
+static int main_process_cmdline(ConfigTree &cfg, int argc, const char *argv[]) {
 	int datafile_argv = 0;
 	for (int ee = 1; ee < argc; ++ee) {
 		const char *arg = argv[ee];
@@ -267,7 +267,7 @@ static int main_process_cmdline(ConfigTree &cfg, int argc, char *argv[]) {
 	return 0;
 }
 
-void main_set_gamedir(int argc, char *argv[]) {
+void main_set_gamedir(int argc, const char *argv[]) {
 	appDirectory = Path::GetDirectoryPath(GetPathFromCmdArg(0));
 
 	if ((loadSaveGameOnStartup != nullptr) && (argv[0] != nullptr)) {
@@ -339,16 +339,14 @@ uint32 AGSEngine::getFeatures() const {
 }
 
 Common::Error AGSEngine::run() {
-	char exeName[16], gameName[16];
-	strcpy(exeName, "scummvm.exe");
-	strcpy(gameName, "bc.exe");
-	int argc = 3;
-	char *argv[] = { exeName, gameName };
+	const char *filename = _gameDescription->desc.filesDescriptions[0].fileName;
+	const char *ARGV[] = { nullptr, filename };
+	const int ARGC = 2;
 
 #ifdef AGS_RUN_TESTS
 	Test_DoAllTests();
 #endif
-	AGS3::main_init(argc, argv);
+	AGS3::main_init(ARGC, ARGV);
 
 #if AGS_PLATFORM_OS_WINDOWS
 	setup_malloc_handling();
@@ -356,7 +354,7 @@ Common::Error AGSEngine::run() {
 	AGS3::debug_flags = 0;
 
 	AGS3::ConfigTree startup_opts;
-	int res = AGS3::main_process_cmdline(startup_opts, argc, argv);
+	int res = AGS3::main_process_cmdline(startup_opts, ARGC, ARGV);
 	if (res != 0)
 		return Common::kUnknownError;
 
@@ -375,7 +373,7 @@ Common::Error AGSEngine::run() {
 	AGS3::init_debug(startup_opts, AGS3::justTellInfo);
 	AGS3::Debug::Printf("%s", AGS3::get_engine_string().GetNullableCStr());
 
-	AGS3::main_set_gamedir(argc, argv);
+	AGS3::main_set_gamedir(ARGC, ARGV);
 
 	// Update shell associations and exit
 	if (AGS3::debug_flags & DBG_REGONLY)
diff --git a/engines/ags/engine/main/main.h b/engines/ags/engine/main/main.h
index d0efac6425..235c6e7c14 100644
--- a/engines/ags/engine/main/main.h
+++ b/engines/ags/engine/main/main.h
@@ -37,7 +37,7 @@ extern AGS::Shared::Version SavedgameLowestForwardCompatVersion;
 
 //=============================================================================
 
-extern char **global_argv;
+extern const char **global_argv;
 
 // Location of the engine executable
 extern AGS::Shared::String appDirectory;


Commit: 1f78ef4eb7add54ff71955aa906948f15c09e5a6
    https://github.com/scummvm/scummvm/commit/1f78ef4eb7add54ff71955aa906948f15c09e5a6
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Add tests as an optional sub-engine

Changed paths:
  A engines/ags/tests/test_all.cpp
  A engines/ags/tests/test_all.h
  A engines/ags/tests/test_file.cpp
  A engines/ags/tests/test_gfx.cpp
  A engines/ags/tests/test_inifile.cpp
  A engines/ags/tests/test_math.cpp
  A engines/ags/tests/test_memory.cpp
  A engines/ags/tests/test_sprintf.cpp
  A engines/ags/tests/test_string.cpp
  A engines/ags/tests/test_version.cpp
    engines/ags/ags.cpp
    engines/ags/configure.engine
    engines/ags/lib/std/map.h
    engines/ags/module.mk


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index 79f95a1278..83b599dfd7 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -49,6 +49,9 @@
 #include "ags/shared/util/directory.h"
 #include "ags/shared/util/path.h"
 
+#ifdef ENABLE_AGS_TESTS
+#include "ags/tests/test_all.h"
+#endif
 
 namespace AGS3 {
 
@@ -343,8 +346,9 @@ Common::Error AGSEngine::run() {
 	const char *ARGV[] = { nullptr, filename };
 	const int ARGC = 2;
 
-#ifdef AGS_RUN_TESTS
-	Test_DoAllTests();
+#ifdef ENABLE_AGS_TESTS
+	AGS3::Test_DoAllTests();
+	return Common::kNoError;
 #endif
 	AGS3::main_init(ARGC, ARGV);
 
diff --git a/engines/ags/configure.engine b/engines/ags/configure.engine
index 55cba93bb4..0fb88d9de1 100644
--- a/engines/ags/configure.engine
+++ b/engines/ags/configure.engine
@@ -1,3 +1,4 @@
 # This file is included from the main "configure" script
 # add_engine [name] [desc] [build-by-default] [subengines] [base games] [deps]
-add_engine ags "Adventure Game Studio" no "" "" "cxx11"
+add_engine ags "Adventure Game Studio" no "ags_tests" "" "cxx11"
+add_engine ags_tests "AGS Tests" no "" "" ""
diff --git a/engines/ags/lib/std/map.h b/engines/ags/lib/std/map.h
index 3d596dc0c7..a5f080952b 100644
--- a/engines/ags/lib/std/map.h
+++ b/engines/ags/lib/std/map.h
@@ -50,6 +50,20 @@ public:
 
 		return it;
 	}
+
+	/**
+	 * Checks if the maps have identical contents
+	 */
+	bool operator==(const map &rhs) {
+		if (this->size() != rhs.size())
+			return false;
+		for (iterator it = this->begin(); it != this->end(); ++it) {
+			if (!(it->_value == rhs[it->_key]))
+				return false;
+		}
+
+		return true;
+	}
 };
 
 template<class Key, class Val, class HashFunc = Common::Hash<Key>,
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index af96975957..07c1145c9c 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -308,6 +308,18 @@ MODULE_OBJS = \
 	engine/script/script_runtime.o \
 	engine/script/systemimports.o
 
+ifdef ENABLE_AGS_TESTS
+MODULE_OBJS += \
+	tests/test_all.o \
+	tests/test_file.o \
+	tests/test_gfx.o \
+	tests/test_inifile.o \
+	tests/test_math.o \
+	tests/test_memory.o \
+	tests/test_sprintf.o \
+	tests/test_string.o \
+	tests/test_version.o
+endif
 
 # This module can be built as a plugin
 ifeq ($(ENABLE_AGS), DYNAMIC_PLUGIN)
diff --git a/engines/ags/tests/test_all.cpp b/engines/ags/tests/test_all.cpp
new file mode 100644
index 0000000000..08cfce5c48
--- /dev/null
+++ b/engines/ags/tests/test_all.cpp
@@ -0,0 +1,41 @@
+/* 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 "ags/shared/core/platform.h"
+#include "ags/tests/test_all.h"
+
+namespace AGS3 {
+
+void Test_DoAllTests() {
+	Test_Math();
+	Test_Memory();
+	Test_Path();
+	Test_ScriptSprintf();
+	Test_String();
+	Test_Version();
+	Test_File();
+	Test_IniFile();
+
+	Test_Gfx();
+}
+
+} // namespace AGS3
diff --git a/engines/ags/tests/test_all.h b/engines/ags/tests/test_all.h
new file mode 100644
index 0000000000..f05f3a5c7a
--- /dev/null
+++ b/engines/ags/tests/test_all.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.
+ *
+ */
+
+#include "ags/shared/core/platform.h"
+
+namespace AGS3 {
+
+extern void Test_DoAllTests();
+
+// Math tests
+extern void Test_Math();
+
+// File tests
+extern void Test_File();
+extern void Test_IniFile();
+
+// Graphics tests
+extern void Test_Gfx();
+
+// Memory / bit-byte operations
+extern void Test_Memory();
+
+// String tests
+extern void Test_ScriptSprintf();
+extern void Test_String();
+extern void Test_Path();
+extern void Test_Version();
+
+} // namespace AGS3
diff --git a/engines/ags/tests/test_file.cpp b/engines/ags/tests/test_file.cpp
new file mode 100644
index 0000000000..b3ed8f0b59
--- /dev/null
+++ b/engines/ags/tests/test_file.cpp
@@ -0,0 +1,196 @@
+/* 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 "ags/shared/core/platform.h"
+#include <string.h>
+#include "ags/shared/debugging/assert.h"
+#include "ags/shared/util/alignedstream.h"
+#include "ags/shared/util/file.h"
+
+namespace AGS3 {
+
+using namespace AGS::Shared;
+
+struct TTrickyAlignedData {
+	char    a;
+	int     b;
+	int     c;
+	short   d[3];
+	int     e;
+	char    f[17];
+	int     g[4];
+	short   h[13];
+	char    i[3];
+	short   j;
+	int     k;
+	short   l;
+	short   m;
+	int     n;
+	int64_t i64a;
+	char    o;
+	int64_t i64b;
+	short   p;
+	int64_t i64c;
+	short   q;
+	short   r;
+	int64_t i64d;
+	char    final;
+};
+
+void Test_File() {
+	//-----------------------------------------------------
+	// Operations
+	Stream *out = File::OpenFile("test.tmp", AGS::Shared::kFile_CreateAlways, AGS::Shared::kFile_Write);
+
+	out->WriteInt16(10);
+	out->WriteInt64(-20202);
+	String::WriteString("test.tmp", out);
+	String very_long_string;
+	very_long_string.FillString('a', 10000);
+	very_long_string.Write(out);
+
+	TTrickyAlignedData tricky_data_out;
+	memset(&tricky_data_out, 0xAA, sizeof(tricky_data_out));
+	{
+		tricky_data_out.a = 11;
+		tricky_data_out.b = 12;
+		tricky_data_out.c = 13;
+		tricky_data_out.d[0] = 14;
+		tricky_data_out.d[1] = 15;
+		tricky_data_out.d[2] = 16;
+		tricky_data_out.e = 17;
+		memset(tricky_data_out.f, 0, 17);
+		tricky_data_out.g[0] = 18;
+		tricky_data_out.g[1] = 19;
+		tricky_data_out.g[2] = 20;
+		tricky_data_out.g[3] = 21;
+		memset(tricky_data_out.h, 0, 13 * sizeof(short));
+		tricky_data_out.i[0] = 22;
+		tricky_data_out.i[1] = 23;
+		tricky_data_out.i[2] = 24;
+		tricky_data_out.j = 25;
+		tricky_data_out.k = 26;
+		tricky_data_out.l = 27;
+		tricky_data_out.m = 28;
+		tricky_data_out.n = 29;
+		tricky_data_out.i64a = 30;
+		tricky_data_out.o = 31;
+		tricky_data_out.i64b = 32;
+		tricky_data_out.p = 33;
+		tricky_data_out.i64c = 34;
+		tricky_data_out.q = 35;
+		tricky_data_out.r = 36;
+		tricky_data_out.i64d = 37;
+		tricky_data_out.final = 38;
+#if defined (TEST_BIGENDIAN)
+		TTrickyAlignedData bigend_data = tricky_data_out;
+		bigend_data.b = BBOp::SwapBytesInt32(bigend_data.b);
+		bigend_data.c = BBOp::SwapBytesInt32(bigend_data.c);
+		for (int i = 0; i < 3; ++i) {
+			bigend_data.d[i] = BBOp::SwapBytesInt16(bigend_data.d[i]);
+		}
+		bigend_data.e = BBOp::SwapBytesInt32(bigend_data.e);
+		for (int i = 0; i < 4; ++i) {
+			bigend_data.g[i] = BBOp::SwapBytesInt32(bigend_data.g[i]);
+		}
+		for (int i = 0; i < 13; ++i) {
+			bigend_data.h[i] = BBOp::SwapBytesInt16(bigend_data.h[i]);
+		}
+		bigend_data.j = BBOp::SwapBytesInt16(bigend_data.j);
+		bigend_data.k = BBOp::SwapBytesInt32(bigend_data.k);
+		bigend_data.l = BBOp::SwapBytesInt16(bigend_data.l);
+		bigend_data.m = BBOp::SwapBytesInt16(bigend_data.m);
+		bigend_data.n = BBOp::SwapBytesInt32(bigend_data.n);
+		bigend_data.i64a = BBOp::SwapBytesInt64(bigend_data.i64a);
+		bigend_data.i64b = BBOp::SwapBytesInt64(bigend_data.i64b);
+		bigend_data.p = BBOp::SwapBytesInt16(bigend_data.p);
+		bigend_data.i64c = BBOp::SwapBytesInt64(bigend_data.i64c);
+		bigend_data.q = BBOp::SwapBytesInt16(bigend_data.q);
+		bigend_data.r = BBOp::SwapBytesInt16(bigend_data.r);
+		bigend_data.i64d = BBOp::SwapBytesInt64(bigend_data.i64d);
+		out->Write(&bigend_data, sizeof(TTrickyAlignedData));
+#else
+		out->Write(&tricky_data_out, sizeof(TTrickyAlignedData));
+#endif
+	}
+
+	out->WriteInt32(20);
+
+	delete out;
+
+	//-------------------------------------------------------------------------
+
+	Stream *in = File::OpenFile("test.tmp", AGS::Shared::kFile_Open, AGS::Shared::kFile_Read);
+
+	int16_t int16val = in->ReadInt16();
+	int64_t int64val = in->ReadInt64();
+	String str1 = String::FromStream(in);
+	String str2 = String::FromStream(in);
+
+	TTrickyAlignedData tricky_data_in;
+	memset(&tricky_data_in, 0xAA, sizeof(tricky_data_in));
+	{
+		AlignedStream as(in, AGS::Shared::kAligned_Read);
+		tricky_data_in.a = as.ReadInt8();
+		tricky_data_in.b = as.ReadInt32();
+		tricky_data_in.c = as.ReadInt32();
+		as.ReadArrayOfInt16(tricky_data_in.d, 3);
+		tricky_data_in.e = as.ReadInt32();
+		as.Read(tricky_data_in.f, 17);
+		as.ReadArrayOfInt32(tricky_data_in.g, 4);
+		as.ReadArrayOfInt16(tricky_data_in.h, 13);
+		as.Read(tricky_data_in.i, 3);
+		tricky_data_in.j = as.ReadInt16();
+		tricky_data_in.k = as.ReadInt32();
+		tricky_data_in.l = as.ReadInt16();
+		tricky_data_in.m = as.ReadInt16();
+		tricky_data_in.n = as.ReadInt32();
+		tricky_data_in.i64a = as.ReadInt64();
+		tricky_data_in.o = as.ReadInt8();
+		tricky_data_in.i64b = as.ReadInt64();
+		tricky_data_in.p = as.ReadInt16();
+		tricky_data_in.i64c = as.ReadInt64();
+		tricky_data_in.q = as.ReadInt16();
+		tricky_data_in.r = as.ReadInt16();
+		tricky_data_in.i64d = as.ReadInt64();
+		tricky_data_in.final = as.ReadInt8();
+	}
+
+	int32_t int32val = in->ReadInt32();
+
+	delete in;
+
+	File::DeleteFile("test.tmp");
+
+	//-----------------------------------------------------
+	// Assertions
+	assert(int16val == 10);
+	assert(int64val == -20202);
+	assert(strcmp(str1, "test.tmp") == 0);
+	assert(strcmp(str2, very_long_string) == 0);
+	assert(memcmp(&tricky_data_in, &tricky_data_out, sizeof(TTrickyAlignedData)) == 0);
+	assert(int32val == 20);
+
+	assert(!File::TestReadFile("test.tmp"));
+}
+
+} // namespace AGS3
diff --git a/engines/ags/tests/test_gfx.cpp b/engines/ags/tests/test_gfx.cpp
new file mode 100644
index 0000000000..04072ae09d
--- /dev/null
+++ b/engines/ags/tests/test_gfx.cpp
@@ -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.
+ *
+ */
+
+#include "common/scummsys.h"
+#include "ags/shared/core/platform.h"
+#include "ags/shared/gfx/gfx_def.h"
+#include "ags/shared/debugging/assert.h"
+
+namespace AGS3 {
+
+namespace GfxDef = AGS::Shared::GfxDef;
+
+void Test_Gfx() {
+	// Test that every transparency which is a multiple of 10 is converted
+	// forth and back without loosing precision
+	const size_t arr_sz = 11;
+	const int trans100[arr_sz] = { 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
+	int trans255[arr_sz] = { 0 };
+	int trans100_back[arr_sz] = { 0 };
+
+	for (int i = 0; i < arr_sz; ++i) {
+		trans255[i] = GfxDef::Trans100ToLegacyTrans255(trans100[i]);
+		trans100_back[i] = GfxDef::LegacyTrans255ToTrans100(trans255[i]);
+		assert(trans100[i] == trans100_back[i]);
+	}
+}
+
+} // namespace AGS3
diff --git a/engines/ags/tests/test_inifile.cpp b/engines/ags/tests/test_inifile.cpp
new file mode 100644
index 0000000000..75781c427a
--- /dev/null
+++ b/engines/ags/tests/test_inifile.cpp
@@ -0,0 +1,304 @@
+/* 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 "ags/shared/core/platform.h"
+#include "ags/lib/std/algorithm.h"
+#include "ags/shared/debugging/assert.h"
+#include "ags/shared/util/file.h"
+#include "ags/shared/util/ini_util.h"
+#include "ags/shared/util/inifile.h"
+#include "ags/shared/util/stream.h"
+
+namespace AGS3 {
+
+using namespace AGS::Shared;
+
+#if AGS_PLATFORM_OS_WINDOWS
+#define ENDL "\r\n"
+#else
+#define ENDL "\n"
+#endif
+
+const char *IniFileText = ""
+"global_item=global_value" ENDL
+"[section1]" ENDL
+"item1" ENDL
+"//this is comment" ENDL
+"item2=" ENDL
+"item3=value" ENDL
+"item4=another value" ENDL
+"[this_section_should_be_deleted]" ENDL
+"item1=value1" ENDL
+"item2=value2" ENDL
+";this is comment" ENDL
+"[section3]" ENDL
+"item_to_be_deleted=value" ENDL
+"item_to_be_kept=another value" ENDL
+"     [     section4     ]      " ENDL
+"        item1     =     value  " ENDL;
+
+const char *IniFileText2 = ""
+"global_item=global_value" ENDL
+"[section1]" ENDL
+"item1=value1" ENDL
+"//this is comment" ENDL
+"item2=value2" ENDL
+"item3=value3" ENDL
+"new_item=new_value" ENDL
+"[section3]" ENDL
+"item_to_be_kept=another value" ENDL
+"     [     section4     ]      " ENDL
+"new_item1=new_value1" ENDL
+"        item1     =     value  " ENDL
+"new_item2=new_value2" ENDL
+"[section5]" ENDL
+"item5_1=value5_1" ENDL
+"item5_2=value5_2" ENDL
+"item5_3=value5_3" ENDL;
+
+
+void Test_IniFile() {
+	Stream *fs = File::CreateFile("test.ini");
+	fs->Write(IniFileText, strlen(IniFileText));
+	delete fs;
+
+	IniFile ini;
+	fs = File::OpenFileRead("test.ini");
+	ini.Read(fs);
+	delete fs;
+
+	// there are explicit sections and 1 implicit global one
+	const int section_count = 5;
+	// Test reading from the custom ini file
+	{
+		assert(ini.GetSectionCount() == section_count);
+		IniFile::ConstSectionIterator sec = ini.CBegin();
+
+		assert(sec->GetItemCount() == 1);
+		IniFile::ConstItemIterator item = sec->CBegin();
+		assert(item->GetKey() == "global_item");
+		assert(item->GetValue() == "global_value");
+
+		++sec;
+		assert(sec->GetName() == "section1");
+		assert(sec->GetItemCount() == 5);
+		item = sec->CBegin();
+		assert(item->GetKey() == "item1");
+		assert(item->GetValue() == "");
+		++item;
+		assert(item->GetLine() == "//this is comment");
+		++item;
+		assert(item->GetKey() == "item2");
+		assert(item->GetValue() == "");
+		++item;
+		assert(item->GetKey() == "item3");
+		assert(item->GetValue() == "value");
+		++item;
+		assert(item->GetKey() == "item4");
+		assert(item->GetValue() == "another value");
+
+		++sec;
+		assert(sec->GetName() == "this_section_should_be_deleted");
+		assert(sec->GetItemCount() == 3);
+		item = sec->CBegin();
+		assert(item->GetKey() == "item1");
+		assert(item->GetValue() == "value1");
+		++item;
+		assert(item->GetKey() == "item2");
+		assert(item->GetValue() == "value2");
+		++item;
+		assert(item->GetLine() == ";this is comment");
+
+		++sec;
+		assert(sec->GetName() == "section3");
+		assert(sec->GetItemCount() == 2);
+		item = sec->CBegin();
+		assert(item->GetKey() == "item_to_be_deleted");
+		assert(item->GetValue() == "value");
+		++item;
+		assert(item->GetKey() == "item_to_be_kept");
+		assert(item->GetValue() == "another value");
+
+		++sec;
+		assert(sec->GetName() == "section4");
+		assert(sec->GetItemCount() == 1);
+		item = sec->CBegin();
+		assert(item->GetKey() == "item1");
+		assert(item->GetValue() == "value");
+	}
+
+	// Test altering INI data and saving to file
+	{
+		// Modiying item values
+		IniFile::SectionIterator sec = ini.Begin();
+		++sec;
+		IniFile::ItemIterator item = sec->Begin();
+		item->SetValue("value1");
+		++item; ++item;
+		item->SetValue("value2");
+		++item;
+		item->SetValue("value3");
+		++item;
+		item->SetKey("new_item");
+		item->SetValue("new_value");
+
+		// Removing a section
+		sec = ini.Begin(); ++sec; ++sec;
+		ini.RemoveSection(sec);
+		assert(ini.GetSectionCount() == section_count - 1);
+
+		// Removing an item
+		sec = ini.Begin(); ++sec; ++sec;
+		assert(sec->GetName() == "section3");
+		item = sec->Begin();
+		assert(item->GetKey() == "item_to_be_deleted");
+		sec->EraseItem(item);
+
+		// Inserting new items
+		++sec;
+		assert(sec->GetName() == "section4");
+		ini.InsertItem(sec, sec->Begin(), "new_item1", "new_value1");
+		ini.InsertItem(sec, sec->End(), "new_item2", "new_value2");
+
+		// Append new section
+		sec = ini.InsertSection(ini.End(), "section5");
+		ini.InsertItem(sec, sec->End(), "item5_1", "value5_1");
+		ini.InsertItem(sec, sec->End(), "item5_2", "value5_2");
+		ini.InsertItem(sec, sec->End(), "item5_3", "value5_3");
+
+		fs = File::CreateFile("test.ini");
+		ini.Write(fs);
+		delete fs;
+
+		fs = File::OpenFileRead("test.ini");
+		String ini_content;
+		ini_content.ReadCount(fs, static_cast<size_t>(fs->GetLength()));
+
+		assert(ini_content == IniFileText2);
+	}
+
+	// Test creating KeyValueTree from existing ini file
+	{
+		ConfigTree tree;
+		IniUtil::Read("test.ini", tree);
+
+		assert(tree.size() == 5);
+		assert(tree.find("") != tree.end()); // global section
+		assert(tree.find("section1") != tree.end());
+		assert(tree.find("section3") != tree.end());
+		assert(tree.find("section4") != tree.end());
+		assert(tree.find("section5") != tree.end());
+		StringOrderMap &sub_tree = tree[""];
+		assert(sub_tree.size() == 1);
+		assert(sub_tree.find("global_item") != sub_tree.end());
+		assert(sub_tree["global_item"] == "global_value");
+		sub_tree = tree["section1"];
+		assert(sub_tree.size() == 4);
+		assert(sub_tree.find("item1") != sub_tree.end());
+		assert(sub_tree.find("item2") != sub_tree.end());
+		assert(sub_tree.find("item3") != sub_tree.end());
+		assert(sub_tree.find("new_item") != sub_tree.end());
+		assert(sub_tree["item1"] == "value1");
+		assert(sub_tree["item2"] == "value2");
+		assert(sub_tree["item3"] == "value3");
+		assert(sub_tree["new_item"] == "new_value");
+		sub_tree = tree["section3"];
+		assert(sub_tree.size() == 1);
+		assert(sub_tree.find("item_to_be_kept") != sub_tree.end());
+		assert(sub_tree["item_to_be_kept"] == "another value");
+		sub_tree = tree["section4"];
+		assert(sub_tree.size() == 3);
+		assert(sub_tree.find("new_item1") != sub_tree.end());
+		assert(sub_tree.find("item1") != sub_tree.end());
+		assert(sub_tree.find("new_item2") != sub_tree.end());
+		assert(sub_tree["new_item1"] == "new_value1");
+		assert(sub_tree["item1"] == "value");
+		assert(sub_tree["new_item2"] == "new_value2");
+		sub_tree = tree["section5"];
+		assert(sub_tree.size() == 3);
+		assert(sub_tree.find("item5_1") != sub_tree.end());
+		assert(sub_tree.find("item5_2") != sub_tree.end());
+		assert(sub_tree.find("item5_3") != sub_tree.end());
+		assert(sub_tree["item5_1"] == "value5_1");
+		assert(sub_tree["item5_2"] == "value5_2");
+		assert(sub_tree["item5_3"] == "value5_3");
+	}
+
+	// Test self-serialization
+	ConfigTree tree1;
+	{
+		ConfigTree tree2;
+
+		// construct the tree
+		{
+			StringOrderMap &audio_tree = tree1["audio"];
+			audio_tree["volume"] = "100.0";
+			audio_tree["driver"] = "midi";
+			StringOrderMap &video_tree = tree1["video"];
+			video_tree["gfx_mode"] = "standard mode";
+			video_tree["gamma"] = "1.0";
+			video_tree["vsync"] = "false";
+		}
+
+		IniUtil::Write("test.ini", tree1);
+		IniUtil::Read("test.ini", tree2);
+
+		// Assert, that tree2 has exactly same items as tree1
+		assert(tree1 == tree2);
+	}
+
+	// Test merging
+	{
+		ConfigTree tree3;
+		ConfigTree tree4;
+
+		// Try merging altered tree into existing file
+		tree3 = tree1;
+		{
+			StringOrderMap &audio_tree = tree3["audio"];
+			audio_tree["extra_option1"] = "extra value 1";
+			audio_tree["extra_option2"] = "extra value 2";
+			audio_tree["extra_option3"] = "extra value 3";
+			StringOrderMap &video_tree = tree3["video"];
+			video_tree["gfx_mode"] = "alternate mode";
+			video_tree["gamma"] = "2.0";
+			StringOrderMap &new_tree = tree3["other1"];
+			new_tree["item1_1"] = "value1_1";
+			new_tree["item1_2"] = "value1_2";
+			new_tree["item1_3"] = "value1_3";
+			StringOrderMap &new_tree2 = tree3["other2"];
+			new_tree2["item2_1"] = "value2_1";
+			new_tree2["item2_2"] = "value2_2";
+			new_tree2["item2_3"] = "value2_3";
+		}
+
+		IniUtil::Merge("test.ini", tree3);
+		IniUtil::Read("test.ini", tree4);
+
+		// Assert, that tree4 has all the items from tree3
+		assert(tree3 == tree4);
+	}
+
+	File::DeleteFile("test.ini");
+}
+
+} // namespace AGS3
diff --git a/engines/ags/tests/test_math.cpp b/engines/ags/tests/test_math.cpp
new file mode 100644
index 0000000000..3d752d03ba
--- /dev/null
+++ b/engines/ags/tests/test_math.cpp
@@ -0,0 +1,69 @@
+/* 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 "ags/shared/core/platform.h"
+#include "ags/shared/debugging/assert.h"
+#include "ags/engine/util/scaling.h"
+
+namespace AGS3 {
+
+using namespace AGS::Shared;
+using namespace AGS::Engine;
+
+void Test_Scaling(int src, int dst) {
+	int x;
+	AxisScaling sc;
+	sc.Init(src, dst);
+	x = sc.ScalePt(0);
+	assert(x == 0);
+	x = sc.ScalePt(src);
+	assert(x == dst);
+	x = sc.UnScalePt(dst);
+	assert(x == src);
+}
+
+void Test_Math() {
+	Test_Scaling(100, 100);
+
+	Test_Scaling(100, 1000);
+	Test_Scaling(320, 1280);
+	Test_Scaling(200, 400);
+
+	Test_Scaling(1000, 100);
+	Test_Scaling(1280, 320);
+	Test_Scaling(400, 200);
+
+	Test_Scaling(300, 900);
+	Test_Scaling(100, 700);
+	Test_Scaling(200, 2200);
+
+	Test_Scaling(900, 300);
+	Test_Scaling(700, 100);
+	Test_Scaling(2200, 200);
+
+	for (int i = 250; i < 2000; i += 25) {
+		Test_Scaling(200, i);
+		Test_Scaling(i, 200);
+	}
+}
+
+} // namespace AGS3
diff --git a/engines/ags/tests/test_memory.cpp b/engines/ags/tests/test_memory.cpp
new file mode 100644
index 0000000000..950978d724
--- /dev/null
+++ b/engines/ags/tests/test_memory.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 "ags/shared/core/platform.h"
+#include "ags/shared/util/memory.h"
+#include "ags/shared/debugging/assert.h"
+
+namespace AGS3 {
+
+using namespace AGS::Shared;
+
+void Test_Memory() {
+	int16_t i16 = (int16_t)0xABCD;
+	int32_t i32 = (int32_t)0xABCDEF12;
+	int64_t i64 = (int64_t)0xABCDEF1234567890;
+
+	assert(BBOp::SwapBytesInt16(i16) == (int16_t)0xCDAB);
+	assert(BBOp::SwapBytesInt32(i32) == (int32_t)0x12EFCDABu);
+	assert(BBOp::SwapBytesInt64(i64) == (int64_t)0x9078563412EFCDABul);
+
+#if defined (BITBYTE_BIG_ENDIAN)
+	assert(BBOp::Int16FromLE(i16) == (int16_t)0xCDAB);
+	assert(BBOp::Int32FromLE(i32) == (int32_t)0x12EFCDABu);
+	assert(BBOp::Int64FromLE(i64) == (int64_t)0x9078563412EFCDABul);
+
+	assert(BBOp::Int16FromBE(i16) == (int16_t)0xABCD);
+	assert(BBOp::Int32FromBE(i32) == (int32_t)0xABCDEF12);
+	assert(BBOp::Int64FromBE(i64) == (int64_t)0xABCDEF1234567890);
+#else
+	assert(BBOp::Int16FromLE(i16) == (int16_t)0xABCD);
+	assert(BBOp::Int32FromLE(i32) == (int32_t)0xABCDEF12);
+	assert(BBOp::Int64FromLE(i64) == (int64_t)0xABCDEF1234567890);
+
+	assert(BBOp::Int16FromBE(i16) == (int16_t)0xCDAB);
+	assert(BBOp::Int32FromBE(i32) == (int32_t)0x12EFCDABu);
+	assert(BBOp::Int64FromBE(i64) == (int64_t)0x9078563412EFCDABul);
+#endif
+
+	int16_t dst_i16 = (int16_t)0xABCD;
+	int32_t dst_i32 = (int32_t)0xABCDEF12;
+	int64_t dst_i64 = (int64_t)0xABCDEF1234567890;
+	void *p_i16 = &dst_i16;
+	void *p_i32 = &dst_i32;
+	void *p_i64 = &dst_i64;
+
+#if defined (TEST_BIGENDIAN)
+	dst_i16 = BBOp::SwapBytesInt16(dst_i16);
+	dst_i32 = BBOp::SwapBytesInt32(dst_i32);
+	dst_i64 = BBOp::SwapBytesInt64(dst_i64);
+#endif
+
+	assert(Memory::ReadInt16(p_i16) == (int16_t)0xABCD);
+	assert(Memory::ReadInt32(p_i32) == (int32_t)0xABCDEF12);
+	assert(Memory::ReadInt64(p_i64) == (int64_t)0xABCDEF1234567890);
+
+	Memory::WriteInt16(p_i16, (int16_t)0xCDAB);
+	Memory::WriteInt32(p_i32, (int32_t)0x12EFCDAB);
+	Memory::WriteInt64(p_i64, (int64_t)0x9078563412EFCDAB);
+
+#if defined (TEST_BIGENDIAN)
+	dst_i16 = BBOp::SwapBytesInt16(dst_i16);
+	dst_i32 = BBOp::SwapBytesInt32(dst_i32);
+	dst_i64 = BBOp::SwapBytesInt64(dst_i64);
+#endif
+
+	assert(dst_i16 == (int16_t)0xCDAB);
+	assert(dst_i32 == (int32_t)0x12EFCDAB);
+	assert(dst_i64 == (int64_t)0x9078563412EFCDAB);
+}
+
+} // namespace AGS3
diff --git a/engines/ags/tests/test_sprintf.cpp b/engines/ags/tests/test_sprintf.cpp
new file mode 100644
index 0000000000..5ad2fb80a8
--- /dev/null
+++ b/engines/ags/tests/test_sprintf.cpp
@@ -0,0 +1,133 @@
+/* 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 "ags/shared/core/platform.h"
+#include <string.h>
+#include "ags/shared/ac/game_version.h"
+#include "ags/shared/debugging/assert.h"
+#include "ags/engine/script/script_api.h"
+#include "ags/engine/script/runtimescriptvalue.h"
+
+namespace AGS3 {
+
+const char *ScriptVSprintf__(char *buffer, size_t buf_length, const char *format, ...) {
+	va_list args;
+	va_start(args, format);
+	const char *res_buffer = ScriptVSprintf(buffer, buf_length, format, args);
+	va_end(args);
+	return res_buffer;
+}
+
+void Test_ScriptSprintf() {
+	const int argi = 123;
+	const float argf = 0.456F;
+	const char *argcc = "string literal";
+	RuntimeScriptValue params[10];
+	params[0].SetInt32(argi);
+	params[1].SetFloat(argf);
+	params[2].SetStringLiteral(argcc);
+
+	char ScSfBuffer[STD_BUFFER_SIZE];
+	//
+	// Called-from-script variant
+	//
+	// Correct format, extra placeholder
+	const char *result =
+		ScriptSprintf(ScSfBuffer, STD_BUFFER_SIZE,
+			"testing ScriptSprintf:\nThis is int: %10d\nThis is float: %.4f\nThis is string: '%s'\nThis placeholder will be ignored: %d",
+			params, 3);
+	assert(strcmp(result, "testing ScriptSprintf:\nThis is int:        123\nThis is float: 0.4560\nThis is string: 'string literal'\nThis placeholder will be ignored: %d") == 0);
+	// Literal percent sign
+	result = ScriptSprintf(ScSfBuffer, STD_BUFFER_SIZE, "%d%%", params, 3);
+	assert(strcmp(result, "123%") == 0);
+	result = ScriptSprintf(ScSfBuffer, STD_BUFFER_SIZE, "123%%", NULL, 0);
+	assert(strcmp(result, "123%") == 0);
+	result = ScriptSprintf(ScSfBuffer, STD_BUFFER_SIZE, "%%5d%%0.5f%%s", params, 3);
+	assert(strcmp(result, "%5d%0.5f%s") == 0);
+
+	// Invalid format
+	result = ScriptSprintf(ScSfBuffer, STD_BUFFER_SIZE, "%zzzzzz", params, 3);
+	assert(strcmp(result, "%zzzzzz") == 0);
+	result = ScriptSprintf(ScSfBuffer, STD_BUFFER_SIZE, "%12.34%d", params, 3);
+	assert(strcmp(result, "%12.34123") == 0);
+
+	// Not enough arguments
+	result = ScriptSprintf(ScSfBuffer, STD_BUFFER_SIZE, "%5d%0.5f%s", params, 0);
+	assert(strcmp(result, "%5d%0.5f%s") == 0);
+
+	// Not enough buffer space
+	result = ScriptSprintf(ScSfBuffer, 9, "12345678%d", params, 3);
+	assert(strcmp(result, "12345678") == 0);
+	result = ScriptSprintf(ScSfBuffer, 11, "12345678%d", params, 3);
+	assert(strcmp(result, "1234567812") == 0);
+	// Not enough buffer space and not enough params
+	result = ScriptSprintf(ScSfBuffer, 10, "12345678%d", params, 0);
+	assert(strcmp(result, "12345678%") == 0);
+	result = ScriptSprintf(ScSfBuffer, 11, "12345678%d", params, 0);
+	assert(strcmp(result, "12345678%d") == 0);
+
+	// Test null string pointer in backward-compatibility mode
+	loaded_game_file_version = kGameVersion_312;
+	params[0].SetStringLiteral(NULL);
+	result = ScriptSprintf(ScSfBuffer, 10, "A%sB", params, 1);
+	assert(strcmp(result, "A(null)B") == 0);
+	loaded_game_file_version = kGameVersion_Undefined;
+
+	//
+	// Called-from-plugin variant
+	// Note that since this is variadic function, number of parameters must
+	// always be equal or higher than number of placeholders in buffer string.
+	//
+	// Correct format, matching number of arguments
+	result =
+		ScriptVSprintf__(ScSfBuffer, STD_BUFFER_SIZE,
+			"testing ScriptVSprintf:\nThis is int: %10d\nThis is float: %.4f\nThis is string: '%s'\n",
+			argi, argf, argcc);
+	assert(strcmp(result, "testing ScriptVSprintf:\nThis is int:        123\nThis is float: 0.4560\nThis is string: 'string literal'\n") == 0);
+	// Literal percent sign
+	result = ScriptVSprintf__(ScSfBuffer, STD_BUFFER_SIZE, "%d%%", argi);
+	assert(strcmp(result, "123%") == 0);
+	result = ScriptVSprintf__(ScSfBuffer, STD_BUFFER_SIZE, "123%%");
+	assert(strcmp(result, "123%") == 0);
+	result = ScriptVSprintf__(ScSfBuffer, STD_BUFFER_SIZE, "%%5d%%0.5f%%s");
+	assert(strcmp(result, "%5d%0.5f%s") == 0);
+
+	// Invalid format
+	result = ScriptVSprintf__(ScSfBuffer, STD_BUFFER_SIZE, "%zzzzzz", argi, argf, argcc);
+	assert(strcmp(result, "%zzzzzz") == 0);
+	result = ScriptVSprintf__(ScSfBuffer, STD_BUFFER_SIZE, "%12.34%d", argi, argf, argcc);
+	assert(strcmp(result, "%12.34123") == 0);
+
+	// Not enough buffer space
+	result = ScriptVSprintf__(ScSfBuffer, 9, "12345678%d", argi, argf, argcc);
+	assert(strcmp(result, "12345678") == 0);
+	result = ScriptVSprintf__(ScSfBuffer, 11, "12345678%d", argi, argf, argcc);
+	assert(strcmp(result, "1234567812") == 0);
+
+	// Test null string pointer in backward-compatibility mode
+	loaded_game_file_version = kGameVersion_312;
+	result = ScriptVSprintf__(ScSfBuffer, 10, "A%sB", NULL);
+	assert(strcmp(result, "A(null)B") == 0);
+	loaded_game_file_version = kGameVersion_Undefined;
+}
+
+} // namespace AGS3
diff --git a/engines/ags/tests/test_string.cpp b/engines/ags/tests/test_string.cpp
new file mode 100644
index 0000000000..edaeca6fdc
--- /dev/null
+++ b/engines/ags/tests/test_string.cpp
@@ -0,0 +1,506 @@
+/* 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 "ags/shared/core/platform.h"
+#include "ags/lib/std/vector.h"
+#include "ags/shared/util/path.h"
+#include "ags/shared/util/string.h"
+#include "ags/shared/debugging/assert.h"
+
+namespace AGS3 {
+
+using namespace AGS::Shared;
+
+void Test_Path() {
+	assert(Path::IsSameOrSubDir(".", "dir1/") == true);
+	assert(Path::IsSameOrSubDir(".", "dir1/dir2/dir3/") == true);
+	assert(Path::IsSameOrSubDir(".", "dir1/../") == true);
+	assert(Path::IsSameOrSubDir(".", "dir1/dir2/../../") == true);
+	assert(Path::IsSameOrSubDir(".", "dir1/../dir2/../dir3/") == true);
+	assert(Path::IsSameOrSubDir(".", "..dir/") == true);
+
+	assert(Path::IsSameOrSubDir(".", "../") == false);
+	assert(Path::IsSameOrSubDir(".", "../") == false);
+	assert(Path::IsSameOrSubDir(".", "/dir1/") == false);
+	assert(Path::IsSameOrSubDir(".", "dir1/../../") == false);
+	assert(Path::IsSameOrSubDir(".", "dir1/../dir2/../../dir3/") == false);
+}
+
+void Test_String() {
+	// Test string's internal work
+	{
+		String s1 = "abcdefghijklmnop";
+		String s2 = s1;
+		String s3 = s1;
+		assert(s1.GetRefCount() == 3);
+		assert(s1.GetBuffer() == s2.GetBuffer());
+		assert(s2.GetBuffer() == s3.GetBuffer());
+
+		size_t cap1 = s1.GetCapacity();
+		assert(cap1 == s1.GetLength());
+
+		s2.TruncateToLeft(10);
+		assert(cap1 == s2.GetCapacity());
+		s3.TruncateToRight(10);
+		assert(cap1 == s3.GetCapacity());
+		assert(s1.GetRefCount() == 1);
+
+		s2.AppendChar('z');
+		assert(cap1 == s2.GetCapacity());
+
+		s3.Append("1234");
+		assert(cap1 == s3.GetCapacity());
+		s3.Append("1234567890123");
+		assert(27 == s3.GetCapacity());
+		s3.Append("1234567890123");
+		assert(40 == s3.GetCapacity());
+		s3.Append("1234567890123");
+		assert(60 == s3.GetCapacity());
+
+		String s4 = "12345678901234567890";
+		const char *cstr = s4.GetCStr();
+		s4.ClipLeft(10);
+		assert(s4.GetCStr() == cstr + 10);
+		s4.Prepend("12345");
+		assert(s4.GetCStr() == cstr + 5);
+		s4.Append("12345");
+		assert(s4.GetCStr() == cstr);
+		assert(strcmp(s4, "12345123456789012345") == 0);
+	}
+
+	// Test Compare
+	{
+		String s1 = "abcdabcdabcd";
+		String s2 = "abcdbfghijklmn";
+		int cmp1 = s1.Compare(s2);
+		int cmp2 = s1.CompareLeft("abcd");
+		int cmp3 = s1.CompareLeft("abcdxxx");
+		int cmp4 = s1.CompareLeft("abcdxxx", 4);
+		int cmp5 = s1.CompareMid(s2, 2, 4);
+		int cmp6 = s1.CompareMid(s2, 8, 4);
+		int cmp7 = s1.CompareMid(s2, 8, 9);
+		int cmp8 = s1.CompareLeft("abcdabcdabcdxxxx");
+		int cmp9 = s1.CompareMid("ab", 8);
+		int cmp10 = s1.CompareMid("ab", 8, 4);
+		int cmp11 = s1.CompareRight("abcd");
+		int cmp12 = s1.CompareRight("bcdxxx", 3);
+		int cmp13 = s1.CompareRight("abc", 4);
+		int cmp14 = s1.CompareRight("abcdxxxx");
+		assert(cmp1 < 0);
+		assert(cmp2 == 0);
+		assert(cmp3 < 0);
+		assert(cmp4 == 0);
+		assert(cmp5 > 0);
+		assert(cmp6 == 0);
+		assert(cmp7 < 0);
+		assert(cmp8 < 0);
+		assert(cmp9 == 0);
+		assert(cmp10 > 0);
+		assert(cmp11 == 0);
+		assert(cmp12 == 0);
+		assert(cmp13 > 0);
+		assert(cmp14 < 0);
+	}
+
+	// Test FindChar
+	{
+		String s1 = "findsomethinginhere";
+		String s2 = "stringtofindsomethinginside";
+		String s3 = "findsomethinginherex";
+		String s4 = "xstringtofindsomethinginside";
+		String s5;
+		size_t find1 = s1.FindChar('o');
+		size_t find2 = s2.FindCharReverse('o');
+		size_t find3 = s1.FindChar('x');
+		size_t find4 = s2.FindCharReverse('x');
+		size_t find5 = s3.FindChar('x');
+		size_t find6 = s4.FindCharReverse('x');
+		size_t find7 = s5.FindChar('x');
+		size_t find8 = s5.FindCharReverse('x');
+		size_t find9 = s1.FindChar('i', 2);
+		size_t find10 = s1.FindCharReverse('i', 12);
+		assert(find1 == 5);
+		assert(find2 == 13);
+		assert(find3 == -1);
+		assert(find4 == -1);
+		assert(find5 == 19);
+		assert(find6 == 0);
+		assert(find7 == -1);
+		assert(find8 == -1);
+		assert(find9 == 10);
+		assert(find10 == 10);
+	}
+
+	// Test GetAt
+	{
+		String s1 = "abcdefghijklmnop";
+		String s2;
+		char c1 = s1.GetAt(0);
+		char c2 = s1.GetAt(15);
+		char c3 = s1.GetAt(16);
+		char c4 = s2.GetAt(0);
+		assert(c1 == 'a');
+		assert(c2 == 'p');
+		assert(c3 == 0);
+		assert(c4 == 0);
+	}
+
+	// Test ToInt
+	{
+		String s1;
+		String s2 = "100";
+		String s3 = "202aaa";
+		String s4 = "aaa333";
+		int i1 = s1.ToInt();
+		int i2 = s2.ToInt();
+		int i3 = s3.ToInt();
+		int i4 = s4.ToInt();
+		assert(i1 == 0);
+		assert(i2 == 100);
+		assert(i3 == 202);
+		assert(i4 == 0);
+	}
+
+	// Test Left/Right/Mid
+	{
+		String s1 = "this is a string to be split";
+		String s2 = s1.Left(4);
+		String s3 = s1.Left(100);
+		String s4 = s1.Mid(10);
+		String s5 = s1.Mid(10, 6);
+		String s6 = s1.Mid(0, 200);
+		String s7 = s1.Right(5);
+		String s8 = s1.Right(100);
+		String s9 = s1.Left(0);
+		String s10 = s1.Mid((size_t)-1, 0);
+		String s11 = s1.Right(0);
+
+		assert(strcmp(s2, "this") == 0);
+		assert(strcmp(s3, "this is a string to be split") == 0);
+		assert(strcmp(s4, "string to be split") == 0);
+		assert(strcmp(s5, "string") == 0);
+		assert(strcmp(s6, "this is a string to be split") == 0);
+		assert(strcmp(s7, "split") == 0);
+		assert(strcmp(s8, "this is a string to be split") == 0);
+		assert(strcmp(s9, "") == 0);
+		assert(strcmp(s10, "") == 0);
+		assert(strcmp(s11, "") == 0);
+	}
+
+	// Test Section
+	{
+		String s = "_123_567_";
+		size_t from;
+		size_t to;
+		assert(s.FindSection('_', 0, 0, true, true, from, to));
+		assert(from == 0 && to == 0);
+		assert(s.FindSection('_', 0, 0, false, true, from, to));
+		assert(from == 0 && to == 0);
+		assert(s.FindSection('_', 0, 0, true, false, from, to));
+		assert(from == 0 && to == 1);
+		assert(s.FindSection('_', 0, 0, false, false, from, to));
+		assert(from == 0 && to == 1);
+		assert(s.FindSection('_', 3, 3, true, true, from, to));
+		assert(from == 9 && to == 9);
+		assert(s.FindSection('_', 3, 3, false, true, from, to));
+		assert(from == 8 && to == 9);
+		assert(s.FindSection('_', 3, 3, true, false, from, to));
+		assert(from == 9 && to == 9);
+		assert(s.FindSection('_', 3, 3, false, false, from, to));
+		assert(from == 8 && to == 9);
+		assert(s.FindSection('_', 1, 1, true, true, from, to));
+		assert(from == 1 && to == 4);
+		assert(s.FindSection('_', 1, 1, false, true, from, to));
+		assert(from == 0 && to == 4);
+		assert(s.FindSection('_', 1, 1, true, false, from, to));
+		assert(from == 1 && to == 5);
+		assert(s.FindSection('_', 1, 1, false, false, from, to));
+		assert(from == 0 && to == 5);
+	}
+
+	// Test Append
+	{
+		String s1 = "a string to enlarge - ";
+		s1.Append("make it bigger");
+		assert(strcmp(s1, "a string to enlarge - make it bigger") == 0);
+		s1.AppendChar('!');
+		assert(strcmp(s1, "a string to enlarge - make it bigger!") == 0);
+		s1.AppendChar(' ');
+		assert(strcmp(s1, "a string to enlarge - make it bigger! ") == 0);
+		s1.Append("much much bigger!");
+		assert(strcmp(s1, "a string to enlarge - make it bigger! much much bigger!") == 0);
+	}
+
+	// Test Clip
+	{
+		String str1 = "long truncateable string";
+		String str2 = str1;
+		String str3 = str1;
+		String str4 = str1;
+		String str5 = str1;
+
+		str1.ClipLeft(4);
+		str2.ClipRight(6);
+		str3.ClipMid(5, 12);
+		str4.ClipMid(5, 0);
+		str5.ClipMid(0);
+		assert(strcmp(str1, " truncateable string") == 0);
+		assert(strcmp(str2, "long truncateable ") == 0);
+		assert(strcmp(str3, "long  string") == 0);
+		assert(strcmp(str4, "long truncateable string") == 0);
+		assert(strcmp(str5, "") == 0);
+	}
+
+	// Test ClipSection
+	{
+		String str1 = "C:\\Games\\AGS\\MyNewGame";
+		String str2 = str1;
+		String str3 = str1;
+		String str4 = str1;
+		String str5 = str1;
+		String str6 = str1;
+		String str7 = str1;
+		String str8 = str1;
+		String str9 = str1;
+		String str10 = str1;
+		String str11 = str1;
+
+		str1.ClipLeftSection('\\');
+		str2.ClipLeftSection('\\', false);
+		str3.ClipRightSection('\\');
+		str4.ClipRightSection('\\', false);
+		str5.ClipSection('\\', 1, 2);
+		str6.ClipSection('\\', 1, 2, false, false);
+		str7.ClipSection('|', 1, 2);
+		str8.ClipSection('\\', 0, 2);
+		str9.ClipSection('\\', 1, 3);
+		str10.ClipSection('\\', 3, 1);
+		str11.ClipSection('\\', 0, 4);
+		assert(strcmp(str1, "Games\\AGS\\MyNewGame") == 0);
+		assert(strcmp(str2, "\\Games\\AGS\\MyNewGame") == 0);
+		assert(strcmp(str3, "C:\\Games\\AGS") == 0);
+		assert(strcmp(str4, "C:\\Games\\AGS\\") == 0);
+		assert(strcmp(str5, "C:MyNewGame") == 0);
+		assert(strcmp(str6, "C:\\\\MyNewGame") == 0);
+		assert(strcmp(str7, "C:\\Games\\AGS\\MyNewGame") == 0);
+		assert(strcmp(str8, "MyNewGame") == 0);
+		assert(strcmp(str9, "C:") == 0);
+		assert(strcmp(str10, "C:\\Games\\AGS\\MyNewGame") == 0);
+		assert(strcmp(str11, "") == 0);
+	}
+
+	// Test making new string
+	{
+		String s1 = "we have some string here";
+		assert(strcmp(s1, "we have some string here") == 0);
+		s1.Empty();
+		assert(strcmp(s1, "") == 0);
+		s1.FillString('z', 10);
+		assert(strcmp(s1, "zzzzzzzzzz") == 0);
+		s1.FillString('a', 0);
+		assert(strcmp(s1, "") == 0);
+		s1.Format("this %d is %9ld a %x formatted %0.2f string %s", 1, 2, 100, 22.55F, "abcd");
+		assert(strcmp(s1, "this 1 is         2 a 64 formatted 22.55 string abcd") == 0);
+		s1.SetString("some string");
+		assert(strcmp(s1, "some string") == 0);
+		s1.SetString("some string", 4);
+		assert(strcmp(s1, "some") == 0);
+	}
+
+	// Test Upper/Lower case
+	{
+		String s1 = "ThIs StRiNg Is TwIsTeD";
+		String s2 = s1;
+		String s3 = s1;
+		s2.MakeLower();
+		s3.MakeUpper();
+		assert(strcmp(s2, "this string is twisted") == 0);
+		assert(strcmp(s3, "THIS STRING IS TWISTED") == 0);
+	}
+
+	// Test Prepend
+	{
+		String s1 = "- a string to enlarge";
+		s1.Prepend("make it bigger ");
+		assert(strcmp(s1, "make it bigger - a string to enlarge") == 0);
+		s1.PrependChar('!');
+		assert(strcmp(s1, "!make it bigger - a string to enlarge") == 0);
+		s1.PrependChar(' ');
+		assert(strcmp(s1, " !make it bigger - a string to enlarge") == 0);
+		s1.Prepend("much much bigger!");
+		assert(strcmp(s1, "much much bigger! !make it bigger - a string to enlarge") == 0);
+	}
+
+	// Test ReplaceMid
+	{
+		String s1 = "we need to replace PRECISELY THIS PART in this string";
+		String s2 = s1;
+		String new_long = "WITH A NEW TAD LONGER SUBSTRING";
+		String new_short = "SMALL STRING";
+		s1.ReplaceMid(19, 19, new_long);
+		assert(strcmp(s1, "we need to replace WITH A NEW TAD LONGER SUBSTRING in this string") == 0);
+		s2.ReplaceMid(19, 19, new_short);
+		assert(strcmp(s2, "we need to replace SMALL STRING in this string") == 0);
+		String s3 = "insert new string here: ";
+		s3.ReplaceMid(s3.GetLength(), 0, "NEW STRING");
+		assert(strcmp(s3, "insert new string here: NEW STRING") == 0);
+	}
+
+	// Test SetAt
+	{
+		String s1 = "strimg wiyh typos";
+		s1.SetAt((size_t)-1, 'a');
+		assert(strcmp(s1, "strimg wiyh typos") == 0);
+		s1.SetAt(100, 'a');
+		assert(strcmp(s1, "strimg wiyh typos") == 0);
+		s1.SetAt(1, 0);
+		assert(strcmp(s1, "strimg wiyh typos") == 0);
+		s1.SetAt(4, 'n');
+		s1.SetAt(9, 't');
+		assert(strcmp(s1, "string with typos") == 0);
+	}
+
+	// Test Trim
+	{
+		String str1 = "\t   This string is quite long and should be cut a little bit\r\n    ";
+		String str2 = str1;
+		String str3 = str1;
+		String str4 = str1;
+		String str5 = "There's nothing to trim here";
+
+		str1.TrimLeft();
+		str2.TrimRight();
+		str3.Trim();
+		str4.Trim('|');
+		str5.Trim();
+
+		assert(strcmp(str1, "This string is quite long and should be cut a little bit\r\n    ") == 0);
+		assert(strcmp(str2, "\t   This string is quite long and should be cut a little bit") == 0);
+		assert(strcmp(str3, "This string is quite long and should be cut a little bit") == 0);
+		assert(strcmp(str4, "\t   This string is quite long and should be cut a little bit\r\n    ") == 0);
+		assert(strcmp(str5, "There's nothing to trim here") == 0);
+	}
+
+	// Test Truncate
+	{
+		String str1 = "long truncateable string";
+		String str2 = str1;
+		String str3 = str1;
+		String str4 = str1;
+		String str5 = str1;
+
+		str1.TruncateToLeft(4);
+		str2.TruncateToRight(6);
+		str3.TruncateToMid(5, 12);
+		str4.TruncateToMid(5, 0);
+		str5.TruncateToMid(0);
+		assert(strcmp(str1, "long") == 0);
+		assert(strcmp(str2, "string") == 0);
+		assert(strcmp(str3, "truncateable") == 0);
+		assert(strcmp(str4, "") == 0);
+		assert(strcmp(str5, "long truncateable string") == 0);
+	}
+
+	// Test TruncateToSection
+	{
+		String str1 = "C:\\Games\\AGS\\MyNewGame";
+		String str2 = str1;
+		String str3 = str1;
+		String str4 = str1;
+		String str5 = str1;
+		String str6 = str1;
+		String str7 = str1;
+		String str8 = str1;
+		String str9 = str1;
+		String str10 = str1;
+		String str11 = str1;
+		String str12 = str1;
+
+		str1.TruncateToLeftSection('\\');
+		str2.TruncateToLeftSection('\\', false);
+		str3.TruncateToRightSection('\\');
+		str4.TruncateToRightSection('\\', false);
+		str5.TruncateToSection('\\', 1, 2);
+		str6.TruncateToSection('\\', 1, 2, false, false);
+		str7.TruncateToSection('|', 1, 3);
+		str8.TruncateToSection('\\', 0, 2);
+		str9.TruncateToSection('\\', 1, 3);
+		str10.TruncateToSection('\\', 3, 1);
+		str11.TruncateToSection('\\', 3, 3);
+		str12.TruncateToSection('\\', 3, 3, false, false);
+		assert(strcmp(str1, "C:") == 0);
+		assert(strcmp(str2, "C:\\") == 0);
+		assert(strcmp(str3, "MyNewGame") == 0);
+		assert(strcmp(str4, "\\MyNewGame") == 0);
+		assert(strcmp(str5, "Games\\AGS") == 0);
+		assert(strcmp(str6, "\\Games\\AGS\\") == 0);
+		assert(strcmp(str7, "") == 0);
+		assert(strcmp(str8, "C:\\Games\\AGS") == 0);
+		assert(strcmp(str9, "Games\\AGS\\MyNewGame") == 0);
+		assert(strcmp(str10, "") == 0);
+		assert(strcmp(str11, "MyNewGame") == 0);
+		assert(strcmp(str12, "\\MyNewGame") == 0);
+	}
+
+	// Test Split
+	{
+		String str1 = "C:\\Games\\AGS\\MyNewGame\\";
+		std::vector<String> result = str1.Split('\\');
+		assert(result.size() == 5);
+		assert(strcmp(result[0], "C:") == 0);
+		assert(strcmp(result[1], "Games") == 0);
+		assert(strcmp(result[2], "AGS") == 0);
+		assert(strcmp(result[3], "MyNewGame") == 0);
+		assert(strcmp(result[4], "") == 0);
+		String str2 = "test,,,test";
+		result = str2.Split(',');
+		assert(result.size() == 4);
+		assert(strcmp(result[0], "test") == 0);
+		assert(strcmp(result[1], "") == 0);
+		assert(strcmp(result[2], "") == 0);
+		assert(strcmp(result[3], "test") == 0);
+		String str3 = ",,test,,";
+		result = str3.Split(',');
+		assert(result.size() == 5);
+		assert(strcmp(result[0], "") == 0);
+		assert(strcmp(result[1], "") == 0);
+		assert(strcmp(result[2], "test") == 0);
+		assert(strcmp(result[3], "") == 0);
+		assert(strcmp(result[4], "") == 0);
+	}
+
+	// Test Wrap
+	{
+		const char *cstr = "This is a string literal";
+		String str1 = String::Wrapper(cstr);
+		String str2 = str1;
+		assert(str1.GetCStr() == cstr);
+		assert(str2.GetCStr() == cstr);
+		assert(str1.GetRefCount() == 0);
+		assert(str2.GetRefCount() == 0);
+		str2.SetAt(0, 'A');
+		assert(str2.GetCStr() != cstr);
+		assert(str2.GetRefCount() == 1);
+	}
+}
+
+} // namespace AGS3
diff --git a/engines/ags/tests/test_version.cpp b/engines/ags/tests/test_version.cpp
new file mode 100644
index 0000000000..81d67aec2c
--- /dev/null
+++ b/engines/ags/tests/test_version.cpp
@@ -0,0 +1,117 @@
+/* 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 "ags/shared/core/platform.h"
+#include "ags/shared/debugging/assert.h"
+#include "ags/shared/util/version.h"
+
+namespace AGS3 {
+
+using AGS::Shared::Version;
+
+void Test_Version() {
+	// Old version format
+	Version test_ver1 = Version("2.06.101");
+	Version test_ver2 = Version("2.56.654");
+	Version test_ver3 = Version("2.7.722");
+	Version test_ver4 = Version("2.72.872NMP");
+	Version test_ver5 = Version("3.2.0");
+	Version test_ver6 = Version("3.21.1115");
+	Version test_ver7 = Version("3.21.1115NMP");
+	// New version format
+	Version test_ver8 = Version("3.3.0.1130");
+	Version test_ver9 = Version("3.3.0.1130 BETA");
+
+	assert(test_ver1.Major == 2);
+	assert(test_ver1.Minor == 0);
+	assert(test_ver1.Release == 6);
+	assert(test_ver1.Revision == 101);
+	assert(strcmp(test_ver1.LongString.GetCStr(), "2.0.6.101") == 0);
+	assert(strcmp(test_ver1.BackwardCompatibleString.GetCStr(), "2.06.101") == 0);
+	assert(strcmp(test_ver1.ShortString.GetCStr(), "2.0") == 0);
+
+	assert(test_ver2.Major == 2);
+	assert(test_ver2.Minor == 5);
+	assert(test_ver2.Release == 6);
+	assert(test_ver2.Revision == 654);
+	assert(strcmp(test_ver2.LongString.GetCStr(), "2.5.6.654") == 0);
+	assert(strcmp(test_ver2.BackwardCompatibleString.GetCStr(), "2.56.654") == 0);
+	assert(strcmp(test_ver2.ShortString.GetCStr(), "2.5") == 0);
+
+	assert(test_ver3.Major == 2);
+	assert(test_ver3.Minor == 7);
+	assert(test_ver3.Release == 0);
+	assert(test_ver3.Revision == 722);
+	assert(strcmp(test_ver3.LongString.GetCStr(), "2.7.0.722") == 0);
+	assert(strcmp(test_ver3.BackwardCompatibleString.GetCStr(), "2.70.722") == 0);
+	assert(strcmp(test_ver3.ShortString.GetCStr(), "2.7") == 0);
+
+	assert(test_ver4.Major == 2);
+	assert(test_ver4.Minor == 7);
+	assert(test_ver4.Release == 2);
+	assert(test_ver4.Revision == 872);
+	assert(strcmp(test_ver4.LongString.GetCStr(), "2.7.2.872 NMP") == 0);
+	assert(strcmp(test_ver4.BackwardCompatibleString.GetCStr(), "2.72.872NMP") == 0);
+	assert(strcmp(test_ver4.ShortString.GetCStr(), "2.7") == 0);
+
+	assert(test_ver5.Major == 3);
+	assert(test_ver5.Minor == 2);
+	assert(test_ver5.Release == 0);
+	assert(test_ver5.Revision == 0);
+	assert(strcmp(test_ver5.LongString.GetCStr(), "3.2.0.0") == 0);
+	assert(strcmp(test_ver5.BackwardCompatibleString.GetCStr(), "3.20.0") == 0);
+	assert(strcmp(test_ver5.ShortString.GetCStr(), "3.2") == 0);
+
+	assert(test_ver6.Major == 3);
+	assert(test_ver6.Minor == 2);
+	assert(test_ver6.Release == 1);
+	assert(test_ver6.Revision == 1115);
+	assert(strcmp(test_ver6.LongString.GetCStr(), "3.2.1.1115") == 0);
+	assert(strcmp(test_ver6.BackwardCompatibleString.GetCStr(), "3.21.1115") == 0);
+	assert(strcmp(test_ver6.ShortString.GetCStr(), "3.2") == 0);
+
+	assert(test_ver7.Major == 3);
+	assert(test_ver7.Minor == 2);
+	assert(test_ver7.Release == 1);
+	assert(test_ver7.Revision == 1115);
+	assert(strcmp(test_ver7.LongString.GetCStr(), "3.2.1.1115 NMP") == 0);
+	assert(strcmp(test_ver7.BackwardCompatibleString.GetCStr(), "3.21.1115NMP") == 0);
+	assert(strcmp(test_ver7.ShortString.GetCStr(), "3.2") == 0);
+
+	assert(test_ver8.Major == 3);
+	assert(test_ver8.Minor == 3);
+	assert(test_ver8.Release == 0);
+	assert(test_ver8.Revision == 1130);
+	assert(strcmp(test_ver8.LongString.GetCStr(), "3.3.0.1130") == 0);
+	assert(strcmp(test_ver8.BackwardCompatibleString.GetCStr(), "3.30.1130") == 0);
+	assert(strcmp(test_ver8.ShortString.GetCStr(), "3.3") == 0);
+
+	assert(test_ver9.Major == 3);
+	assert(test_ver9.Minor == 3);
+	assert(test_ver9.Release == 0);
+	assert(test_ver9.Revision == 1130);
+	assert(strcmp(test_ver9.LongString.GetCStr(), "3.3.0.1130 BETA") == 0);
+	assert(strcmp(test_ver9.BackwardCompatibleString.GetCStr(), "3.30.1130BETA") == 0);
+	assert(strcmp(test_ver9.ShortString.GetCStr(), "3.3") == 0);
+}
+
+} // namespace AGS3


Commit: 2aaf78cf5229d58546b4e33fabea6cd43c9e3169
    https://github.com/scummvm/scummvm/commit/2aaf78cf5229d58546b4e33fabea6cd43c9e3169
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Remove directory logic from startup

Changed paths:
    engines/ags/ags.cpp
    engines/ags/engine/main/engine.cpp
    engines/ags/engine/main/main.h


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index 83b599dfd7..9b018673b1 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -258,7 +258,7 @@ static int main_process_cmdline(ConfigTree &cfg, int argc, const char *argv[]) {
 	}
 
 	if (datafile_argv > 0) {
-		cmdGameDataPath = GetPathFromCmdArg(datafile_argv);
+		cmdGameDataPath = "./";
 	} else {
 		// assign standard path for mobile/consoles (defined in their own platform implementation)
 		cmdGameDataPath = psp_game_file_name;
@@ -271,8 +271,8 @@ static int main_process_cmdline(ConfigTree &cfg, int argc, const char *argv[]) {
 }
 
 void main_set_gamedir(int argc, const char *argv[]) {
-	appDirectory = Path::GetDirectoryPath(GetPathFromCmdArg(0));
-
+	appDirectory = Path::GetDirectoryPath("./");
+#ifdef DEPRECATED
 	if ((loadSaveGameOnStartup != nullptr) && (argv[0] != nullptr)) {
 		// When launched by double-clicking a save game file, the curdir will
 		// be the save game folder unless we correct it
@@ -290,16 +290,7 @@ void main_set_gamedir(int argc, const char *argv[]) {
 		else
 			Debug::Printf(kDbgMsg_Error, "Unable to determine current directory: GetPathInASCII failed.\nArg: %s", cur_dir.GetCStr());
 	}
-}
-
-String GetPathFromCmdArg(int arg_index) {
-	if (arg_index < 0 || arg_index >= global_argc)
-		return "";
-	String path = Path::GetCmdLinePathInASCII(global_argv[arg_index], arg_index);
-	if (!path.IsEmpty())
-		return Path::MakeAbsolutePath(path);
-	Debug::Printf(kDbgMsg_Error, "Unable to determine path: GetCmdLinePathInASCII failed.\nCommand line argument %i: %s", arg_index, global_argv[arg_index]);
-	return global_argv[arg_index];
+#endif
 }
 
 const char *get_allegro_error() {
@@ -343,7 +334,7 @@ uint32 AGSEngine::getFeatures() const {
 
 Common::Error AGSEngine::run() {
 	const char *filename = _gameDescription->desc.filesDescriptions[0].fileName;
-	const char *ARGV[] = { nullptr, filename };
+	const char *ARGV[] = { "scummvm.exe", filename };
 	const int ARGC = 2;
 
 #ifdef ENABLE_AGS_TESTS
diff --git a/engines/ags/engine/main/engine.cpp b/engines/ags/engine/main/engine.cpp
index a2cf6c6f3d..48a33cd002 100644
--- a/engines/ags/engine/main/engine.cpp
+++ b/engines/ags/engine/main/engine.cpp
@@ -270,6 +270,7 @@ bool search_for_game_data_file(String &filename, String &search_path) {
 	}
 	// 3. Look in known locations
 	else {
+#ifdef DEPRECATED
 		// 3.1. Look for attachment in the running executable
 		//
 		// this will use argument zero, the executable's name
@@ -286,6 +287,7 @@ bool search_for_game_data_file(String &filename, String &search_path) {
 				}
 			}
 		}
+#endif
 	}
 
 	// Finally, store game file's absolute path, or report error
diff --git a/engines/ags/engine/main/main.h b/engines/ags/engine/main/main.h
index 235c6e7c14..fdc9da0b6a 100644
--- a/engines/ags/engine/main/main.h
+++ b/engines/ags/engine/main/main.h
@@ -44,8 +44,6 @@ extern AGS::Shared::String appDirectory;
 // Game path from the startup options (before reading config)
 extern AGS::Shared::String cmdGameDataPath;
 
-AGS::Shared::String GetPathFromCmdArg(int arg_index);
-
 // Startup flags, set from parameters to engine
 extern int force_window;
 extern int override_start_room;


Commit: 255ec516538083767230dead04ef4f5072eaf438
    https://github.com/scummvm/scummvm/commit/255ec516538083767230dead04ef4f5072eaf438
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix directory/file exists methods

Changed paths:
    engines/ags/shared/util/stdio_compat.cpp


diff --git a/engines/ags/shared/util/stdio_compat.cpp b/engines/ags/shared/util/stdio_compat.cpp
index e5fe999338..3a4c32b018 100644
--- a/engines/ags/shared/util/stdio_compat.cpp
+++ b/engines/ags/shared/util/stdio_compat.cpp
@@ -22,6 +22,7 @@
 
 #include "ags/shared/util/stdio_compat.h"
 #include "ags/shared/core/platform.h"
+#include "common/config-manager.h"
 #include "common/file.h"
 #include "common/fs.h"
 #include "common/textconsole.h"
@@ -46,24 +47,50 @@ file_off_t ags_ftell(Common::Stream *stream) {
 	return rs->pos();
 }
 
+Common::FSNode getFSNOde(const char *path) {
+	Common::FSNode node(ConfMan.get("path"));
+	Common::String filePath(path);
+
+	// If it's the root game folder, return the node for it
+	if (filePath.empty() || filePath == "." || filePath == "./")
+		return node;
+
+	assert(filePath.hasPrefix("./"));
+	filePath = Common::String(filePath.c_str() + 2);
+
+	// Iterate through any further subfolders or filename
+	size_t separator;
+	while ((separator = filePath.find('/')) != Common::String::npos) {
+		node = node.getChild(filePath.substr(0, separator));
+		filePath = Common::String(filePath.c_str() + separator + 1);
+	}
+
+	if (!filePath.empty())
+		node = node.getChild(filePath);
+
+	return node;
+}
+
 int  ags_file_exists(const char *path) {
-	Common::FSNode fs(path);
-	return fs.exists() && !fs.isDirectory()  ? 0 : -1;
+	Common::FSNode node = getFSNOde(path);
+	return node.exists() && !node.isDirectory()  ? 1 : 0;
 }
 
 int ags_directory_exists(const char *path) {
-	Common::FSNode fs(path);
-	return fs.exists() && fs.isDirectory() ? 0 : -1;
+	Common::FSNode node = getFSNOde(path);
+	return node.exists() && node.isDirectory() ? 1 : 0;
 }
 
 int ags_path_exists(const char *path) {
-	return Common::FSNode(path).exists() ? 0 : -1;
+	Common::FSNode node = getFSNOde(path);
+	return node.exists() && node.isDirectory() ? 1 : 0;
 }
 
 file_off_t ags_file_size(const char *path) {
+	Common::FSNode node = getFSNOde(path);
 	Common::File f;
 
-	return f.open(path) ? f.size() : (file_off_t )-1;
+	return f.open(node) ? f.size() : (file_off_t )-1;
 }
 
 } // namespace AGS3


Commit: 01967d483c7d8dc4b9bc11ffa9992520f02b6cff
    https://github.com/scummvm/scummvm/commit/01967d483c7d8dc4b9bc11ffa9992520f02b6cff
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix specifying game filename

Changed paths:
    engines/ags/ags.cpp
    engines/ags/shared/util/stdio_compat.cpp


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index 9b018673b1..a872f7d09b 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -258,7 +258,7 @@ static int main_process_cmdline(ConfigTree &cfg, int argc, const char *argv[]) {
 	}
 
 	if (datafile_argv > 0) {
-		cmdGameDataPath = "./";
+		cmdGameDataPath = argv[datafile_argv];
 	} else {
 		// assign standard path for mobile/consoles (defined in their own platform implementation)
 		cmdGameDataPath = psp_game_file_name;
diff --git a/engines/ags/shared/util/stdio_compat.cpp b/engines/ags/shared/util/stdio_compat.cpp
index 3a4c32b018..595a858ce6 100644
--- a/engines/ags/shared/util/stdio_compat.cpp
+++ b/engines/ags/shared/util/stdio_compat.cpp
@@ -55,8 +55,8 @@ Common::FSNode getFSNOde(const char *path) {
 	if (filePath.empty() || filePath == "." || filePath == "./")
 		return node;
 
-	assert(filePath.hasPrefix("./"));
-	filePath = Common::String(filePath.c_str() + 2);
+	if (filePath.hasPrefix("./"))
+		filePath = Common::String(filePath.c_str() + 2);
 
 	// Iterate through any further subfolders or filename
 	size_t separator;
@@ -83,7 +83,7 @@ int ags_directory_exists(const char *path) {
 
 int ags_path_exists(const char *path) {
 	Common::FSNode node = getFSNOde(path);
-	return node.exists() && node.isDirectory() ? 1 : 0;
+	return node.exists() ? 1 : 0;
 }
 
 file_off_t ags_file_size(const char *path) {


Commit: 599b724cfd62def78b23a4b45e7fcc90abf74221
    https://github.com/scummvm/scummvm/commit/599b724cfd62def78b23a4b45e7fcc90abf74221
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix opening game filename

Changed paths:
    engines/ags/shared/util/bufferedstream.cpp
    engines/ags/shared/util/filestream.cpp
    engines/ags/shared/util/stdio_compat.cpp
    engines/ags/shared/util/stdio_compat.h


diff --git a/engines/ags/shared/util/bufferedstream.cpp b/engines/ags/shared/util/bufferedstream.cpp
index 63f2bc0990..f94cc6a3ab 100644
--- a/engines/ags/shared/util/bufferedstream.cpp
+++ b/engines/ags/shared/util/bufferedstream.cpp
@@ -44,7 +44,6 @@ BufferedStream::BufferedStream(const String &file_name, FileOpenMode open_mode,
 		error("Error determining stream end.");
 
 	_buffer.resize(0);
-
 }
 
 void BufferedStream::FillBufferFromPosition(soff_t position) {
diff --git a/engines/ags/shared/util/filestream.cpp b/engines/ags/shared/util/filestream.cpp
index 5134f2e046..ca762af07d 100644
--- a/engines/ags/shared/util/filestream.cpp
+++ b/engines/ags/shared/util/filestream.cpp
@@ -169,7 +169,7 @@ bool FileStream::Seek(soff_t offset, StreamSeek origin) {
 void FileStream::Open(const String &file_name, FileOpenMode open_mode, FileWorkMode work_mode) {
 	if (open_mode == kFile_Open) {
 		Common::File *f = new Common::File();
-		if (!f->open(file_name.GetNullableCStr())) {
+		if (!f->open(getFSNode(file_name.GetNullableCStr()))) {
 			delete f;
 			_file = nullptr;
 		} else {
diff --git a/engines/ags/shared/util/stdio_compat.cpp b/engines/ags/shared/util/stdio_compat.cpp
index 595a858ce6..2bdd48ea29 100644
--- a/engines/ags/shared/util/stdio_compat.cpp
+++ b/engines/ags/shared/util/stdio_compat.cpp
@@ -34,9 +34,9 @@ int ags_fseek(Common::Stream *stream, file_off_t offset, int whence) {
 	Common::SeekableWriteStream *ws = dynamic_cast<Common::SeekableWriteStream *>(stream);
 
 	if (rs)
-		return rs->seek(offset, whence);
+		return rs->seek(offset, whence) ? 0 : 1;
 	else if (ws)
-		return ws->seek(offset, whence);
+		return ws->seek(offset, whence) ? 0 : 1;
 	else
 		error("Seek on null stream");
 }
@@ -47,7 +47,7 @@ file_off_t ags_ftell(Common::Stream *stream) {
 	return rs->pos();
 }
 
-Common::FSNode getFSNOde(const char *path) {
+Common::FSNode getFSNode(const char *path) {
 	Common::FSNode node(ConfMan.get("path"));
 	Common::String filePath(path);
 
@@ -72,22 +72,22 @@ Common::FSNode getFSNOde(const char *path) {
 }
 
 int  ags_file_exists(const char *path) {
-	Common::FSNode node = getFSNOde(path);
+	Common::FSNode node = getFSNode(path);
 	return node.exists() && !node.isDirectory()  ? 1 : 0;
 }
 
 int ags_directory_exists(const char *path) {
-	Common::FSNode node = getFSNOde(path);
+	Common::FSNode node = getFSNode(path);
 	return node.exists() && node.isDirectory() ? 1 : 0;
 }
 
 int ags_path_exists(const char *path) {
-	Common::FSNode node = getFSNOde(path);
+	Common::FSNode node = getFSNode(path);
 	return node.exists() ? 1 : 0;
 }
 
 file_off_t ags_file_size(const char *path) {
-	Common::FSNode node = getFSNOde(path);
+	Common::FSNode node = getFSNode(path);
 	Common::File f;
 
 	return f.open(node) ? f.size() : (file_off_t )-1;
diff --git a/engines/ags/shared/util/stdio_compat.h b/engines/ags/shared/util/stdio_compat.h
index f3bfc73999..65e8371107 100644
--- a/engines/ags/shared/util/stdio_compat.h
+++ b/engines/ags/shared/util/stdio_compat.h
@@ -24,18 +24,21 @@
 #define AGS_SHARED_UTIL_STDIO_COMPAT_H
 
 #include "common/stream.h"
+#include "common/fs.h"
 
 namespace AGS3 {
 
 typedef int64 file_off_t;
 
-int  ags_fseek(Common::Stream *stream, file_off_t offset, int whence);
-file_off_t ags_ftell(Common::Stream *stream);
+extern Common::FSNode getFSNode(const char *path);
 
-int ags_file_exists(const char *path);
-int ags_directory_exists(const char *path);
-int ags_path_exists(const char *path);
-file_off_t ags_file_size(const char *path);
+extern int  ags_fseek(Common::Stream *stream, file_off_t offset, int whence);
+extern file_off_t ags_ftell(Common::Stream *stream);
+
+extern int ags_file_exists(const char *path);
+extern int ags_directory_exists(const char *path);
+extern int ags_path_exists(const char *path);
+extern file_off_t ags_file_size(const char *path);
 
 } // namespace AGS3
 


Commit: 071f0766658318fe44e3c8d542486bbec59c2f01
    https://github.com/scummvm/scummvm/commit/071f0766658318fe44e3c8d542486bbec59c2f01
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix tyring to read config file when not present

Changed paths:
    engines/ags/engine/main/engine.cpp
    engines/ags/shared/game/main_game_file.cpp
    engines/ags/shared/util/bufferedstream.cpp
    engines/ags/shared/util/file.cpp
    engines/ags/shared/util/filestream.cpp


diff --git a/engines/ags/engine/main/engine.cpp b/engines/ags/engine/main/engine.cpp
index 48a33cd002..f0e03a60ac 100644
--- a/engines/ags/engine/main/engine.cpp
+++ b/engines/ags/engine/main/engine.cpp
@@ -1199,7 +1199,8 @@ void engine_read_config(const String &exe_path, ConfigTree &cfg) {
 	// Disabled on Windows because people were afraid that this config could be mistakenly
 	// created by some installer and screw up their games. Until any kind of solution is found.
 	String user_global_cfg_file;
-#if ! AGS_PLATFORM_OS_WINDOWS
+#if !AGS_PLATFORM_SCUMMVM
+#if !AGS_PLATFORM_OS_WINDOWS
 	// Read user global configuration file
 	user_global_cfg_file = find_user_global_cfg_file();
 	if (Path::ComparePaths(user_global_cfg_file, def_cfg_file) != 0)
@@ -1211,6 +1212,7 @@ void engine_read_config(const String &exe_path, ConfigTree &cfg) {
 	if (Path::ComparePaths(user_cfg_file, def_cfg_file) != 0 &&
 	        Path::ComparePaths(user_cfg_file, user_global_cfg_file) != 0)
 		IniUtil::Read(user_cfg_file, cfg);
+#endif
 
 	// Apply overriding options from mobile port settings
 	// TODO: normally, those should be instead stored in the same config file in a uniform way
diff --git a/engines/ags/shared/game/main_game_file.cpp b/engines/ags/shared/game/main_game_file.cpp
index 8f6c7f0084..ad42434759 100644
--- a/engines/ags/shared/game/main_game_file.cpp
+++ b/engines/ags/shared/game/main_game_file.cpp
@@ -607,6 +607,7 @@ void SetDefaultGlobalMessages(GameSetupStruct &game) {
 }
 
 void FixupSaveDirectory(GameSetupStruct &game) {
+#ifdef DEPRECATED
 	// If the save game folder was not specified by game author, create one of
 	// the game name, game GUID, or uniqueid, as a last resort
 	if (!game.saveGameFolderName[0]) {
@@ -620,6 +621,9 @@ void FixupSaveDirectory(GameSetupStruct &game) {
 	// Lastly, fixup folder name by removing any illegal characters
 	String s = Path::FixupSharedFilename(game.saveGameFolderName);
 	snprintf(game.saveGameFolderName, MAX_SG_FOLDER_LEN, "%s", s.GetCStr());
+#else
+	sprintf(game.saveGameFolderName, "");
+#endif
 }
 
 HGameFileError ReadSpriteFlags(LoadedGameEntities &ents, Stream *in, GameDataVersion data_ver) {
diff --git a/engines/ags/shared/util/bufferedstream.cpp b/engines/ags/shared/util/bufferedstream.cpp
index f94cc6a3ab..973f3d693a 100644
--- a/engines/ags/shared/util/bufferedstream.cpp
+++ b/engines/ags/shared/util/bufferedstream.cpp
@@ -32,17 +32,8 @@ namespace AGS {
 namespace Shared {
 
 BufferedStream::BufferedStream(const String &file_name, FileOpenMode open_mode, FileWorkMode work_mode, DataEndianess stream_endianess)
-	: FileStream(file_name, open_mode, work_mode, stream_endianess), _buffer(BufferStreamSize), _bufferPosition(0), _position(0) {
-	if (FileStream::Seek(0, kSeekEnd) == false)
-		error("Error determining stream end.");
-
-	_end = FileStream::GetPosition();
-	if (_end == -1)
-		error("Error determining stream end.");
-
-	if (FileStream::Seek(0, kSeekBegin) == false)
-		error("Error determining stream end.");
-
+		: FileStream(file_name, open_mode, work_mode, stream_endianess), _buffer(BufferStreamSize), _bufferPosition(0), _position(0) {
+	_end = GetLength();
 	_buffer.resize(0);
 }
 
diff --git a/engines/ags/shared/util/file.cpp b/engines/ags/shared/util/file.cpp
index e94d56e9e0..8324e363de 100644
--- a/engines/ags/shared/util/file.cpp
+++ b/engines/ags/shared/util/file.cpp
@@ -120,7 +120,7 @@ Stream *File::OpenFile(const String &filename, FileOpenMode open_mode, FileWorkM
 			fs = new BufferedStream(filename, open_mode, work_mode);
 		else
 			fs = new FileStream(filename, open_mode, work_mode);
-		if (fs != nullptr && !fs->IsValid()) {
+ 		if (fs != nullptr && !fs->IsValid()) {
 			delete fs;
 			fs = nullptr;
 		}
diff --git a/engines/ags/shared/util/filestream.cpp b/engines/ags/shared/util/filestream.cpp
index ca762af07d..b512fc4505 100644
--- a/engines/ags/shared/util/filestream.cpp
+++ b/engines/ags/shared/util/filestream.cpp
@@ -185,9 +185,6 @@ void FileStream::Open(const String &file_name, FileOpenMode open_mode, FileWorkM
 			_file = f;
 		}
 	}
-
-	if (_file == nullptr)
-		error("Error opening file.");
 }
 
 } // namespace Shared


Commit: f4dad65589425b4b8692f09660ade4c17b0ce3fc
    https://github.com/scummvm/scummvm/commit/f4dad65589425b4b8692f09660ade4c17b0ce3fc
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix ustrsize stub

Changed paths:
    engines/ags/lib/allegro/unicode.cpp


diff --git a/engines/ags/lib/allegro/unicode.cpp b/engines/ags/lib/allegro/unicode.cpp
index 073fda45ec..4c70f2fc6e 100644
--- a/engines/ags/lib/allegro/unicode.cpp
+++ b/engines/ags/lib/allegro/unicode.cpp
@@ -30,7 +30,7 @@ void set_uformat(int format) {
 }
 
 size_t ustrsize(const char *s) {
-	error("TODO: ustrsize");
+	return strlen(s);
 }
 
 


Commit: e22019dcf46a3ef680ec82890dd2e0c08e7fce57
    https://github.com/scummvm/scummvm/commit/e22019dcf46a3ef680ec82890dd2e0c08e7fce57
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Create ScummVM SYSTEM_DRIVER

Changed paths:
    engines/ags/lib/allegro/system.cpp
    engines/ags/lib/allegro/system.h


diff --git a/engines/ags/lib/allegro/system.cpp b/engines/ags/lib/allegro/system.cpp
index a27cb655b3..31f858b4a6 100644
--- a/engines/ags/lib/allegro/system.cpp
+++ b/engines/ags/lib/allegro/system.cpp
@@ -27,13 +27,57 @@
 namespace AGS3 {
 
 SYSTEM_DRIVER system_none;
-SYSTEM_DRIVER *system_driver;
+
+SYSTEM_DRIVER system_scummvm = {
+	SYSTEM_SCUMMVM,
+	nullptr,
+	nullptr,
+	"ScummVM Device",
+	nullptr, // TODO: ios_sys_init,
+	nullptr, // TODO: ios_sys_exit,
+	nullptr,  /* AL_METHOD(void, get_executable_name, (char *output, int size)); */
+	nullptr,  /* AL_METHOD(int, find_resource, (char *dest, AL_CONST char *resource, int size)); */
+	nullptr,  /* AL_METHOD(void, set_window_title, (AL_CONST char *name)); */
+	nullptr,  /* AL_METHOD(int, set_close_button_callback, (AL_METHOD(void, proc, (void)))); */
+	nullptr,  /* AL_METHOD(void, message, (AL_CONST char *msg)); */
+	nullptr,  /* AL_METHOD(void, assert, (AL_CONST char *msg)); */
+	nullptr,  /* AL_METHOD(void, save_console_state, (void)); */
+	nullptr,  /* AL_METHOD(void, restore_console_state, (void)); */
+	nullptr,  /* AL_METHOD(struct BITMAP *, create_bitmap, (int color_depth, int width, int height)); */
+	nullptr,  /* AL_METHOD(void, created_bitmap, (struct BITMAP *bmp)); */
+	nullptr,  /* AL_METHOD(struct BITMAP *, create_sub_bitmap, (struct BITMAP *parent, int x, int y, int width, int height)); */
+	nullptr,  /* AL_METHOD(void, created_sub_bitmap, (struct BITMAP *bmp, struct BITMAP *parent)); */
+	nullptr,  /* AL_METHOD(int, destroy_bitmap, (struct BITMAP *bitmap)); */
+	nullptr,  /* AL_METHOD(void, read_hardware_palette, (void)); */
+	nullptr,  /* AL_METHOD(void, set_palette_range, (AL_CONST struct RGB *p, int from, int to, int retracesync)); */
+	nullptr,  /* AL_METHOD(struct GFX_VTABLE *, get_vtable, (int color_depth)); */
+	nullptr,  /* AL_METHOD(int, set_display_switch_mode, (int mode)); */
+	nullptr,  /* AL_METHOD(void, display_switch_lock, (int lock, int foreground)); */
+	nullptr,  /* AL_METHOD(int, desktop_color_depth, (void)); */
+	nullptr,  /* AL_METHOD(int, get_desktop_resolution, (int *width, int *height)); */
+	nullptr, // TODO: ios_get_gfx_safe_mode,  /*AL_METHOD(void, get_gfx_safe_mode, (int *driver, struct GFX_MODE *mode));*/
+	nullptr,  /* AL_METHOD(void, yield_timeslice, (void)); */
+	nullptr, // TODO: _ios_create_mutex,  /* AL_METHOD(void *, create_mutex, (void)); */
+	nullptr, // TODO: _ios_destroy_mutex,  /* AL_METHOD(void, destroy_mutex, (void *handle)); */
+	nullptr, // TODO: _ios_lock_mutex,  /* AL_METHOD(void, lock_mutex, (void *handle)); */
+	nullptr, // TODO: _ios_unlock_mutex,  /* AL_METHOD(void, unlock_mutex, (void *handle)); */
+	nullptr,  /* AL_METHOD(_DRIVER_INFO *, gfx_drivers, (void)); */
+	nullptr,  /* AL_METHOD(_DRIVER_INFO *, digi_drivers, (void)); */
+	nullptr,  /* AL_METHOD(_DRIVER_INFO *, midi_drivers, (void)); */
+	nullptr,  /* AL_METHOD(_DRIVER_INFO *, keyboard_drivers, (void)); */
+	nullptr,  /* AL_METHOD(_DRIVER_INFO *, mouse_drivers, (void)); */
+	nullptr,  /* AL_METHOD(_DRIVER_INFO *, joystick_drivers, (void)); */
+	nullptr   /* AL_METHOD(_DRIVER_INFO *, timer_drivers, (void)); */
+};
 
 _DRIVER_INFO _system_driver_list[] = {
+	{ SYSTEM_SCUMMVM, &system_scummvm, true },
 	{ SYSTEM_NONE, &system_none, false },
 	{ 0, nullptr , 0     }
 };
 
+SYSTEM_DRIVER *system_driver = &system_scummvm;
+
 
 GFX_MODE_LIST *get_gfx_mode_list(int card) {
 	assert(card == 0);
diff --git a/engines/ags/lib/allegro/system.h b/engines/ags/lib/allegro/system.h
index c44eedd84d..aef878d8ed 100644
--- a/engines/ags/lib/allegro/system.h
+++ b/engines/ags/lib/allegro/system.h
@@ -34,6 +34,7 @@ namespace AGS3 {
 #endif
 
 #define SYSTEM_AUTODETECT  0
+#define SYSTEM_SCUMMVM     AL_ID('S','C','V','M')
 #define SYSTEM_NONE        AL_ID('N','O','N','E')
 
 #define SWITCH_NONE           0
@@ -56,9 +57,9 @@ struct GFX_MODE_LIST {
 
 struct SYSTEM_DRIVER {
 	int  id;
-	char *name;
-	char *desc;
-	char *ascii_name;
+	const char *name;
+	const char *desc;
+	const char *ascii_name;
 	AL_METHOD(int, init, (void));
 	AL_METHOD(void, exit, (void));
 	AL_METHOD(void, get_executable_name, (char *output, int size));


Commit: 95703bb52668655d4751b808e12509afe5e4d3cd
    https://github.com/scummvm/scummvm/commit/95703bb52668655d4751b808e12509afe5e4d3cd
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Change sound method stubs from errors to warnings

Changed paths:
    engines/ags/lib/audio/sound.cpp


diff --git a/engines/ags/lib/audio/sound.cpp b/engines/ags/lib/audio/sound.cpp
index e8d197b660..db82aa061b 100644
--- a/engines/ags/lib/audio/sound.cpp
+++ b/engines/ags/lib/audio/sound.cpp
@@ -22,6 +22,8 @@
 
 #include "ags/lib/audio/sound.h"
 #include "common/textconsole.h"
+#include "ags/ags.h"
+#include "audio/mixer.h"
 
 namespace AGS3 {
 
@@ -40,67 +42,72 @@ void remove_sound() {
 }
 
 void reserve_voices(int digi_voices, int midi_voices) {
-	error("reserve_voices");
+	// TODO: reserve_voices
 }
 
 void set_volume_per_voice(int scale) {
-	error("set_volume_per_voice");
-
+	// TODO: set_volume_per_voice
 }
 
 int install_sound_input(int digi, int midi) {
-	error("install_sound_input");
+	// TODO: install_sound_input
+	return 0;
 }
 
 void remove_sound_input() {
-	error("remove_sound_input");
+	// TODO: remove_sound_input
 }
 
 void set_volume(int digi_volume, int midi_volume) {
-	error("set_volume");
+	// TODO: set_volume
 }
 
 void set_hardware_volume(int digi_volume, int midi_volume) {
-	error("set_hardware_volume");
+	// TODO: set_hardware_volume
 }
 
 void get_volume(int *digi_volume, int *midi_volume) {
-	error("get_volume");
+	// TODO: get_volume
+	*digi_volume = 255;
+	*midi_volume = 255;
 }
 
 void get_hardware_volume(int *digi_volume, int *midi_volume) {
-	error("get_hardware_volume"); 
+	// TODO: get_hardware_volume
 }
 
 void set_mixer_quality(int quality) {
-	error("set_mixer_quality");
+	// TODO: set_mixer_quality
 }
 
 int get_mixer_quality() {
-	error("get_mixer_quality");
+	warning("TODO: get_mixer_quality");
+	return 0;
 }
 
 int get_mixer_frequency() {
-	error("get_mixer_frequency");
+	return ::AGS::g_vm->_mixer->getOutputRate();
 }
 
 int get_mixer_bits() {
-	error("get_mixer_bits");
+	return 16;
 }
 
 int get_mixer_channels() {
-	error("get_mixer_channels");
+	warning("TODO: get_mixer_channels");
+	return 10;
 }
 
 int get_mixer_voices() {
-	error("get_mixer_voices");
+	warning("TODO: get_mixer_voices");
+	return 1;
 }
 
 int get_mixer_buffer_length() {
-	error("get_mixer_buffer_length");
+	warning("TODO: get_mixer_buffer_length");
+	return 22040;
 }
 
-
 void stop_audio_stream(AUDIOSTREAM *stream) {
 	warning("TODO: stop_audio_stream");
 }


Commit: 2f8cbfcfef2d0919ca92cbdbcd820d3bb13ef794
    https://github.com/scummvm/scummvm/commit/2f8cbfcfef2d0919ca92cbdbcd820d3bb13ef794
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Set up digi driver detection

Changed paths:
    engines/ags/lib/allegro/base.h
    engines/ags/lib/audio/digi.cpp
    engines/ags/lib/audio/sound.cpp


diff --git a/engines/ags/lib/allegro/base.h b/engines/ags/lib/allegro/base.h
index 88a91e082e..01eb8d0a32 100644
--- a/engines/ags/lib/allegro/base.h
+++ b/engines/ags/lib/allegro/base.h
@@ -25,6 +25,7 @@
 
 #include "common/scummsys.h"
 #include "common/algorithm.h"
+#include "common/endian.h"
 
 namespace AGS3 {
 
@@ -55,6 +56,8 @@ struct _DRIVER_INFO {
 
 #define AL_FUNC(type, name, args)               type name args
 
+#define SCUMMVM_ID MKTAG('S', 'C', 'V', 'M')
+
 } // namespace AGS3
 
 #endif
diff --git a/engines/ags/lib/audio/digi.cpp b/engines/ags/lib/audio/digi.cpp
index 6e34e036e9..03efcaaae9 100644
--- a/engines/ags/lib/audio/digi.cpp
+++ b/engines/ags/lib/audio/digi.cpp
@@ -33,9 +33,15 @@ int digi_card;
 
 int digi_input_card;
 
+static byte dummy_driver_data[1] = { 0 };
+
+BEGIN_DIGI_DRIVER_LIST
+	{ SCUMMVM_ID, &dummy_driver_data, true },
+END_DIGI_DRIVER_LIST
+
 
 int detect_digi_driver(int driver_id) {
-	return 0;
+	return 1;
 }
 
 SAMPLE *load_wav_pf(PACKFILE *f) {
diff --git a/engines/ags/lib/audio/sound.cpp b/engines/ags/lib/audio/sound.cpp
index db82aa061b..f87fdef389 100644
--- a/engines/ags/lib/audio/sound.cpp
+++ b/engines/ags/lib/audio/sound.cpp
@@ -27,11 +27,6 @@
 
 namespace AGS3 {
 
-_DRIVER_INFO _digi_driver_list[] = {
-	{ 0, nullptr, 0     }
-};
-
-
 int install_sound(int digi, int midi, const char *cfg_path) {
 	// TODO: install_sound
 	return 0;


Commit: 89eed25fd0dc4a3879a5830785ab5b6c38d03a91
    https://github.com/scummvm/scummvm/commit/89eed25fd0dc4a3879a5830785ab5b6c38d03a91
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Further fixes for audio init

Changed paths:
    engines/ags/engine/main/engine.cpp
    engines/ags/lib/audio/digi.cpp
    engines/ags/lib/audio/digi.h
    engines/ags/lib/audio/midi.cpp


diff --git a/engines/ags/engine/main/engine.cpp b/engines/ags/engine/main/engine.cpp
index f0e03a60ac..b90cee75c1 100644
--- a/engines/ags/engine/main/engine.cpp
+++ b/engines/ags/engine/main/engine.cpp
@@ -451,18 +451,24 @@ std::pair<int, int> autodetect_driver(_DRIVER_INFO *driver_list, int (*detect_au
 // Returns a pair of audio card ID and max available voices.
 std::pair<int, int> decide_audiodriver(int try_id, _DRIVER_INFO *driver_list,
                                        int(*detect_audio_driver)(int), int &al_drv_id, const char *type) {
-	if (try_id == 0) // no driver
+	if (try_id == 0)
+		// No driver
 		return std::make_pair(0, 0);
-	al_drv_id = 0; // the driver id will be set by library if one was found
+	al_drv_id = 0;
+
 	if (try_id > 0) {
 		int voices = detect_audio_driver(try_id);
-		if (al_drv_id == try_id && voices != 0) // found and detected
+		if (al_drv_id == try_id && voices != 0) {
+			// found and detected
 			return std::make_pair(try_id, voices);
+		}
 		if (voices == 0) // found in list but detect failed
 			Debug::Printf(kDbgMsg_Error, "Failed to detect %s driver %s; Error: '%s'.", type, AlIDToChars(try_id).s, get_allegro_error());
 		else // not found at all
 			Debug::Printf(kDbgMsg_Error, "Unknown %s driver: %s, will try to find suitable one.", type, AlIDToChars(try_id).s);
 	}
+
+	al_drv_id = 1;
 	return autodetect_driver(driver_list, detect_audio_driver, type);
 }
 
diff --git a/engines/ags/lib/audio/digi.cpp b/engines/ags/lib/audio/digi.cpp
index 03efcaaae9..c28fe3eb73 100644
--- a/engines/ags/lib/audio/digi.cpp
+++ b/engines/ags/lib/audio/digi.cpp
@@ -25,6 +25,63 @@
 
 namespace AGS3 {
 
+/*------------------------------------------------------------------*/
+
+DIGI_DRIVER::DIGI_DRIVER() :
+	id(0), name(nullptr),
+	desc(nullptr),
+	ascii_name(nullptr),
+	voices(0),
+	basevoice(0),
+	max_voices(0),
+	def_voices(0),
+	detect(nullptr),
+	init(nullptr),
+	exit_(nullptr),
+	set_mixer_volume(nullptr),
+	get_mixer_volume(nullptr),
+	lock_voice(nullptr),
+	unlock_voice(nullptr),
+	buffer_size(nullptr),
+	init_voice(nullptr),
+	release_voice(nullptr),
+	start_voice(nullptr),
+	stop_voice(nullptr),
+	loop_voice(nullptr),
+	get_position(nullptr),
+	set_position(nullptr),
+	get_volume(nullptr),
+	set_volume(nullptr),
+	ramp_volume(nullptr),
+	stop_volume_ramp(nullptr),
+	get_frequency(nullptr),
+	set_frequency(nullptr),
+	sweep_frequency(nullptr),
+	stop_frequency_sweep(nullptr),
+	get_pan(nullptr),
+	set_pan(nullptr),
+	sweep_pan(nullptr),
+	stop_pan_sweep(nullptr),
+	set_echo(nullptr),
+	set_tremolo(nullptr),
+	set_vibrato(nullptr),
+	rec_cap_bits(0),
+	rec_cap_stereo(0),
+	rec_cap_rate(nullptr),
+	rec_cap_parm(nullptr),
+	rec_source(nullptr),
+	rec_start(nullptr),
+	rec_stop(nullptr),
+	rec_read(nullptr) {
+}
+
+/*------------------------------------------------------------------*/
+
+class ScummVMDigiDriver : public DIGI_DRIVER {
+};
+
+/*------------------------------------------------------------------*/
+
 DIGI_DRIVER *digi_driver;
 
 DIGI_DRIVER *digi_input_driver;
@@ -41,7 +98,9 @@ END_DIGI_DRIVER_LIST
 
 
 int detect_digi_driver(int driver_id) {
-	return 1;
+	assert(driver_id == SCUMMVM_ID);
+	digi_driver = new ScummVMDigiDriver();
+	return 16;
 }
 
 SAMPLE *load_wav_pf(PACKFILE *f) {
diff --git a/engines/ags/lib/audio/digi.h b/engines/ags/lib/audio/digi.h
index 904c40fb3f..da058b11df 100644
--- a/engines/ags/lib/audio/digi.h
+++ b/engines/ags/lib/audio/digi.h
@@ -66,7 +66,7 @@ struct DIGI_DRIVER {
 	/* setup routines */
 	AL_METHOD(int, detect, (int input));
 	AL_METHOD(int, init, (int input, int voices));
-	AL_METHOD(void, exit, (int input));
+	AL_METHOD(void, exit_, (int input));
 	AL_METHOD(int, set_mixer_volume, (int volume));
 	AL_METHOD(int, get_mixer_volume, (void));
 
@@ -118,6 +118,8 @@ struct DIGI_DRIVER {
 	AL_METHOD(int, rec_start, (int rate, int bits, int stereo));
 	AL_METHOD(void, rec_stop, (void));
 	AL_METHOD(int, rec_read, (void *buf));
+
+	DIGI_DRIVER();
 };
 
 AL_ARRAY(_DRIVER_INFO, _digi_driver_list);
diff --git a/engines/ags/lib/audio/midi.cpp b/engines/ags/lib/audio/midi.cpp
index 5be76b1468..96de121a66 100644
--- a/engines/ags/lib/audio/midi.cpp
+++ b/engines/ags/lib/audio/midi.cpp
@@ -26,7 +26,10 @@
 
 namespace AGS3 {
 
+static byte dummy_driver_data[1] = { 0 };
+
 BEGIN_MIDI_DRIVER_LIST
+{ SCUMMVM_ID, &dummy_driver_data, true },
 END_MIDI_DRIVER_LIST
 
 MIDI_DRIVER *midi_driver;
@@ -45,7 +48,7 @@ long midi_loop_end;           /* loop when we hit this position */
 
 
 int detect_midi_driver(int driver_id) {
-	return 0;
+	return 16;
 }
 
 


Commit: c0913b7ed7afd4e0406ee8038056722d7b7937a3
    https://github.com/scummvm/scummvm/commit/c0913b7ed7afd4e0406ee8038056722d7b7937a3
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Properly load fonts via asset manager

Changed paths:
    engines/ags/lib/alfont/alfont.cpp
    engines/ags/lib/alfont/alfont.h
    engines/ags/shared/font/ttffontrenderer.cpp


diff --git a/engines/ags/lib/alfont/alfont.cpp b/engines/ags/lib/alfont/alfont.cpp
index 3a69e8e7b4..e538baf601 100644
--- a/engines/ags/lib/alfont/alfont.cpp
+++ b/engines/ags/lib/alfont/alfont.cpp
@@ -28,12 +28,8 @@ namespace AGS3 {
 
 Graphics::Font *ALFONT_FONT::getFont() {
 	if (!_fonts.contains(_size)) {
-		Common::File f;
-		if (!f.open(_filename))
-			error("Could not read font - %s", _filename.c_str());
-		_fonts[_size] = Graphics::loadTTFFont(f, f.size());
-		f.close();
-
+		// Instantiate the raw TTF data into a font of the given size
+		_fonts[_size] = Graphics::loadTTFFont(_ttfData, _size);
 		assert(_fonts[_size]);
 	}
 
@@ -42,11 +38,8 @@ Graphics::Font *ALFONT_FONT::getFont() {
 
 /*------------------------------------------------------------------*/
 
-ALFONT_FONT *alfont_loadFont(const Common::String &filename) {
-	ALFONT_FONT *result = new ALFONT_FONT();
-	result->_filename = filename;
-
-	return result;
+ALFONT_FONT *alfont_load_font_from_mem(const byte *data, int data_len) {
+	return new ALFONT_FONT(data, data_len);
 }
 
 void alfont_destroy_font(ALFONT_FONT *font) {
diff --git a/engines/ags/lib/alfont/alfont.h b/engines/ags/lib/alfont/alfont.h
index d3f92e2451..5cf57a407c 100644
--- a/engines/ags/lib/alfont/alfont.h
+++ b/engines/ags/lib/alfont/alfont.h
@@ -24,18 +24,19 @@
 #define AGS_LIB_ALFONT_H
 
 #include "common/hashmap.h"
+#include "common/memstream.h"
 #include "graphics/font.h"
 #include "ags/lib/allegro/gfx.h"
 
 namespace AGS3 {
 
 struct ALFONT_FONT {
-	Common::String _filename;
+	Common::MemoryReadStream _ttfData;
 	int _size;
 	Common::HashMap<int, Graphics::Font *> _fonts;
 
-	ALFONT_FONT() : _size(-1) {}
-	ALFONT_FONT(const Common::String &filename) : _filename(filename), _size(-1) {}
+	ALFONT_FONT() : _size(-1), _ttfData(nullptr, 0) {}
+	ALFONT_FONT(const byte *data, size_t size) : _size(-1), _ttfData(data, size, DisposeAfterUse::YES) {}
 
 	~ALFONT_FONT() {
 		for (Common::HashMap<int, Graphics::Font *>::iterator it = _fonts.begin();
@@ -49,7 +50,7 @@ struct ALFONT_FONT {
 inline void alfont_init() {}
 inline void alfont_exit() {}
 inline void alfont_text_mode(int val) {}
-extern ALFONT_FONT *alfont_loadFont(const Common::String &filename);
+extern ALFONT_FONT *alfont_load_font_from_mem(const byte *data, int data_len);
 extern void alfont_destroy_font(ALFONT_FONT *font);
 
 extern size_t alfont_text_length(ALFONT_FONT *font, const char *text);
diff --git a/engines/ags/shared/font/ttffontrenderer.cpp b/engines/ags/shared/font/ttffontrenderer.cpp
index 34a5489fa9..bf675a62f8 100644
--- a/engines/ags/shared/font/ttffontrenderer.cpp
+++ b/engines/ags/shared/font/ttffontrenderer.cpp
@@ -92,22 +92,35 @@ bool TTFFontRenderer::IsBitmapFont() {
 
 bool TTFFontRenderer::LoadFromDiskEx(int fontNumber, int fontSize, const FontRenderParams *params) {
 	String file_name = String::FromFormat("agsfnt%d.ttf", fontNumber);
+	Stream *reader = AssetManager::OpenAsset(file_name);
+	byte *membuffer;
+
+	if (reader == nullptr)
+		return false;
+
+	long lenof = AssetManager::GetLastAssetSize();
+
+	membuffer = (byte *)malloc(lenof);
+	reader->ReadArray(membuffer, lenof, 1);
+	delete reader;
+
+	ALFONT_FONT *alfptr = alfont_load_font_from_mem(membuffer, lenof);
+	free(membuffer);
 
-	ALFONT_FONT *alfptr = alfont_loadFont(file_name);
 	if (alfptr == nullptr)
 		return false;
 
 	// TODO: move this somewhere, should not be right here
 #if AGS_OUTLINE_FONT_FIX
-	// FIXME: (!!!) this fix should be done differently:
-	// 1. Find out which OUTLINE font was causing troubles;
-	// 2. Replace outline method ONLY if that troublesome font is used as outline.
-	// 3. Move this fix somewhere else!! (right after game load routine?)
-	//
-	// Check for the LucasFan font since it comes with an outline font that
-	// is drawn incorrectly with Freetype versions > 2.1.3.
-	// A simple workaround is to disable outline fonts for it and use
-	// automatic outline drawing.
+  // FIXME: (!!!) this fix should be done differently:
+  // 1. Find out which OUTLINE font was causing troubles;
+  // 2. Replace outline method ONLY if that troublesome font is used as outline.
+  // 3. Move this fix somewhere else!! (right after game load routine?)
+  //
+  // Check for the LucasFan font since it comes with an outline font that
+  // is drawn incorrectly with Freetype versions > 2.1.3.
+  // A simple workaround is to disable outline fonts for it and use
+  // automatic outline drawing.
 	if (get_font_outline(fontNumber) >= 0 &&
 		strcmp(alfont_get_name(alfptr), "LucasFan-Font") == 0)
 		set_font_outline(fontNumber, FONT_OUTLINE_AUTO);


Commit: 377a0ffe7b27e14fb84727df29b9bb1c27bdb71c
    https://github.com/scummvm/scummvm/commit/377a0ffe7b27e14fb84727df29b9bb1c27bdb71c
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fixes for setup of screen resolutions

Changed paths:
    engines/ags/lib/allegro/system.cpp


diff --git a/engines/ags/lib/allegro/system.cpp b/engines/ags/lib/allegro/system.cpp
index 31f858b4a6..765fdee3c4 100644
--- a/engines/ags/lib/allegro/system.cpp
+++ b/engines/ags/lib/allegro/system.cpp
@@ -80,8 +80,6 @@ SYSTEM_DRIVER *system_driver = &system_scummvm;
 
 
 GFX_MODE_LIST *get_gfx_mode_list(int card) {
-	assert(card == 0);
-
 	GFX_MODE_LIST *list = new GFX_MODE_LIST();
 	list->num_modes = 1;
 	list->mode = new GFX_MODE[1];
@@ -89,7 +87,7 @@ GFX_MODE_LIST *get_gfx_mode_list(int card) {
 	GFX_MODE &gm = list->mode[0];
 	gm.width = 320;
 	gm.height = 200;
-	gm.bpp = 16;
+	gm.bpp = 32;
 
 	return list;
 }
@@ -108,10 +106,12 @@ int get_color_depth() {
 }
 
 int get_desktop_resolution(int *width, int *height) {
-	if (*width)
-		*width = g_system->getWidth();
-	if (*height)
-		*height = g_system->getHeight();
+	// TODO: ScummVM has a hardcoded dummy desktop resolution. See if there's any
+	// need to change the values, given we're hardcoded for pretend full-screen
+	if (width)
+		*width = 640;
+	if (height)
+		*height = 480;
 
 	return 0;
 }


Commit: 00e29a1382cd25bcbc3de48b353cf2e1fe6fc41b
    https://github.com/scummvm/scummvm/commit/00e29a1382cd25bcbc3de48b353cf2e1fe6fc41b
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix creating and clearing bitmaps

Changed paths:
    engines/ags/engine/gfx/ali3dogl.cpp
    engines/ags/lib/allegro/gfx.cpp
    engines/ags/lib/allegro/gfx.h
    engines/ags/lib/opengl/opengl.cpp


diff --git a/engines/ags/engine/gfx/ali3dogl.cpp b/engines/ags/engine/gfx/ali3dogl.cpp
index 6d621b1c02..6c74ecc518 100644
--- a/engines/ags/engine/gfx/ali3dogl.cpp
+++ b/engines/ags/engine/gfx/ali3dogl.cpp
@@ -192,7 +192,12 @@ OGLGraphicsDriver::ShaderProgram::ShaderProgram() : Program(0), SamplerVar(0), C
 
 
 OGLGraphicsDriver::OGLGraphicsDriver() {
-#if AGS_PLATFORM_OS_WINDOWS
+#if AGS_PLATFORM_SCUMMVM
+	device_screen_physical_width = 640;
+	device_screen_physical_height = 480;
+	_glxContext = nullptr;
+	_have_window = false;
+#elif AGS_PLATFORM_OS_WINDOWS
 	_hDC = NULL;
 	_hRC = NULL;
 	_hWnd = NULL;
diff --git a/engines/ags/lib/allegro/gfx.cpp b/engines/ags/lib/allegro/gfx.cpp
index 9111935848..3dcec8f2df 100644
--- a/engines/ags/lib/allegro/gfx.cpp
+++ b/engines/ags/lib/allegro/gfx.cpp
@@ -105,8 +105,10 @@ BITMAP *create_bitmap_ex(int color_depth, int width, int height) {
 	switch (color_depth) {
 	case 16:
 		format = Graphics::PixelFormat(2, 5, 6, 5, 0, 11, 5, 0, 0);
+		break;
 	case 32:
 		format = Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0);
+		break;
 	default:
 		error("Invalid color depth");
 	}
@@ -404,7 +406,7 @@ void circlefill(BITMAP *bmp, int x, int y, int radius, int color) {
 }
 
 void clear_bitmap(BITMAP *bmp) {
-	error("TODO: clear_bitmap");
+	bmp->clear();
 }
 
 
diff --git a/engines/ags/lib/allegro/gfx.h b/engines/ags/lib/allegro/gfx.h
index 11a1c07a16..ea415a05f9 100644
--- a/engines/ags/lib/allegro/gfx.h
+++ b/engines/ags/lib/allegro/gfx.h
@@ -203,6 +203,10 @@ public:
 	}
 
 	int getpixel(int x, int y) const;
+
+	void clear() {
+		_owner->clear();
+	}
 };
 
 AL_FUNC(void, set_color_conversion, (int mode));
diff --git a/engines/ags/lib/opengl/opengl.cpp b/engines/ags/lib/opengl/opengl.cpp
index ba367d0067..b60f9f768d 100644
--- a/engines/ags/lib/opengl/opengl.cpp
+++ b/engines/ags/lib/opengl/opengl.cpp
@@ -56,7 +56,6 @@ GLint glGetUniformLocation(GLuint program, const GLchar *name) {
 }
 
 void glShadeModel(GLenum mode) {
-	error("TODO: glShadeMode");
 }
 
 void glGetProgramiv(GLuint program, GLenum pname, GLint *params) {
@@ -75,7 +74,6 @@ void glClearColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) {
 }
 
 void glClear(GLbitfield mask) {
-	warning("TODO: glClear");
 }
 
 void glDrawArrays(GLenum mode, GLint first, GLsizei count) {


Commit: 7d4ef226f931a6ce6ff6840f71c46913a868d325
    https://github.com/scummvm/scummvm/commit/7d4ef226f931a6ce6ff6840f71c46913a868d325
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Implement glGetIntegerv method

Changed paths:
    engines/ags/lib/opengl/opengl.cpp


diff --git a/engines/ags/lib/opengl/opengl.cpp b/engines/ags/lib/opengl/opengl.cpp
index b60f9f768d..d2d098d17c 100644
--- a/engines/ags/lib/opengl/opengl.cpp
+++ b/engines/ags/lib/opengl/opengl.cpp
@@ -89,8 +89,14 @@ void glReadPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format
 }
 
 void glGetIntegerv(GLenum pname, GLint *data) {
-	// TODO: glGetIntegerv
-	*data = 0;
+	switch (pname) {
+	case GL_MAX_TEXTURE_SIZE:
+		*data = 512;
+		break;
+	default:
+		*data = 0;
+		break;
+	}
 }
 
 void glGetFloatv(GLenum pname, GLfloat *params) {


Commit: 9701be90f275820b19683e45e66a07ad0286cf92
    https://github.com/scummvm/scummvm/commit/9701be90f275820b19683e45e66a07ad0286cf92
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Implement load_pcx method

Changed paths:
    engines/ags/lib/allegro/gfx.cpp
    engines/ags/lib/allegro/gfx.h
    engines/ags/shared/gfx/image.cpp


diff --git a/engines/ags/lib/allegro/gfx.cpp b/engines/ags/lib/allegro/gfx.cpp
index 3dcec8f2df..672b3b4fa1 100644
--- a/engines/ags/lib/allegro/gfx.cpp
+++ b/engines/ags/lib/allegro/gfx.cpp
@@ -53,21 +53,6 @@ int BITMAP::getpixel(int x, int y) const {
 
 /*-------------------------------------------------------------------*/
 
-/**
- * Derived surface class
- */
-class Surface : public Graphics::ManagedSurface, public BITMAP {
-public:
-	Surface() : Graphics::ManagedSurface(), BITMAP(this) {}
-	Surface(const Graphics::ManagedSurface &surf) : Graphics::ManagedSurface(surf), BITMAP(this) {}
-	Surface(int width, int height) : Graphics::ManagedSurface(width, height), BITMAP(this) {}
-	Surface(int width, int height, const Graphics::PixelFormat &pixelFormat) :
-		Graphics::ManagedSurface(width, height, pixelFormat), BITMAP(this) {}
-	Surface(Graphics::ManagedSurface &surf, const Common::Rect &bounds) :
-		Graphics::ManagedSurface(surf, bounds), BITMAP(this) {}
-	~Surface() override {}
-};
-
 /**
  * Dervied screen surface
  */
diff --git a/engines/ags/lib/allegro/gfx.h b/engines/ags/lib/allegro/gfx.h
index ea415a05f9..ee2189429c 100644
--- a/engines/ags/lib/allegro/gfx.h
+++ b/engines/ags/lib/allegro/gfx.h
@@ -209,6 +209,28 @@ public:
 	}
 };
 
+/**
+ * Derived surface class
+ */
+class Surface : public Graphics::ManagedSurface, public BITMAP {
+public:
+	Surface() : Graphics::ManagedSurface(), BITMAP(this) {
+	}
+	Surface(const Graphics::ManagedSurface &surf) : Graphics::ManagedSurface(surf), BITMAP(this) {
+	}
+	Surface(int width, int height) : Graphics::ManagedSurface(width, height), BITMAP(this) {
+	}
+	Surface(int width, int height, const Graphics::PixelFormat &pixelFormat) :
+		Graphics::ManagedSurface(width, height, pixelFormat), BITMAP(this) {
+	}
+	Surface(Graphics::ManagedSurface &surf, const Common::Rect &bounds) :
+		Graphics::ManagedSurface(surf, bounds), BITMAP(this) {
+	}
+	~Surface() override {
+	}
+};
+
+
 AL_FUNC(void, set_color_conversion, (int mode));
 AL_FUNC(int, get_color_conversion, ());
 AL_FUNC(int, set_gfx_mode, (int card, int w, int h, int v_w, int v_h));
diff --git a/engines/ags/shared/gfx/image.cpp b/engines/ags/shared/gfx/image.cpp
index 8de490b338..914c4d84bf 100644
--- a/engines/ags/shared/gfx/image.cpp
+++ b/engines/ags/shared/gfx/image.cpp
@@ -22,11 +22,44 @@
 
 #include "ags/shared/gfx/image.h"
 #include "ags/lib/allegro.h"
+#include "common/file.h"
 #include "common/str.h"
 #include "common/textconsole.h"
+#include "image/pcx.h"
 
 namespace AGS3 {
 
+template<class DECODER>
+BITMAP *decodeImage(const char *filename, color *pal) {
+	DECODER decoder;
+	Common::File f;
+
+	if (f.open(filename) && decoder.loadStream(f)) {
+		// Create the output surface
+		const Graphics::Surface *src = decoder.getSurface();
+
+		// Copy the decoded surface
+		Surface *dest = new Surface();
+		dest->create(src->w, src->h, src->format);
+		dest->blitFrom(*src);
+
+		// Copy the palette
+		const byte *palP = decoder.getPalette();
+		if (palP) {
+			for (int idx = 0; idx < 256; ++idx, palP += 3) {
+				pal[idx].r = palP[0];
+				pal[idx].g = palP[1];
+				pal[idx].b = palP[2];
+				pal[idx].filler = 0xff;
+			}
+		}
+
+		return dest;
+	} else {
+		return nullptr;
+	}
+}
+
 BITMAP *load_bmp_pf(PACKFILE *f, color *pal) {
 	error("TODO: load_bmp_pf");
 }
@@ -48,7 +81,7 @@ BITMAP *load_lbm(const char *filename, color *pal) {
 }
 
 BITMAP *load_pcx(const char *filename, color *pal) {
-	error("TODO: load_pcx");
+	return decodeImage<Image::PCXDecoder>(filename, pal);
 }
 
 BITMAP *load_tga(const char *filename, color *pal) {


Commit: cf969752fe242fe7cc5441daca704efa56572c08
    https://github.com/scummvm/scummvm/commit/cf969752fe242fe7cc5441daca704efa56572c08
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Allow paletted bitmaps in create_bitmap_ex method

Changed paths:
    engines/ags/lib/allegro/gfx.cpp


diff --git a/engines/ags/lib/allegro/gfx.cpp b/engines/ags/lib/allegro/gfx.cpp
index 672b3b4fa1..5e09aba5f3 100644
--- a/engines/ags/lib/allegro/gfx.cpp
+++ b/engines/ags/lib/allegro/gfx.cpp
@@ -88,6 +88,9 @@ BITMAP *create_bitmap_ex(int color_depth, int width, int height) {
 	Graphics::PixelFormat format;
 
 	switch (color_depth) {
+	case 8:
+		format = Graphics::PixelFormat::createFormatCLUT8();
+		break;
 	case 16:
 		format = Graphics::PixelFormat(2, 5, 6, 5, 0, 11, 5, 0, 0);
 		break;


Commit: 447072fcf263ba0ff2d022fc913e2cfaf14d2298
    https://github.com/scummvm/scummvm/commit/447072fcf263ba0ff2d022fc913e2cfaf14d2298
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Initialize screen with the needed resolution

Changed paths:
    engines/ags/engine/gfx/ali3dogl.cpp


diff --git a/engines/ags/engine/gfx/ali3dogl.cpp b/engines/ags/engine/gfx/ali3dogl.cpp
index 6c74ecc518..9ea547a8e7 100644
--- a/engines/ags/engine/gfx/ali3dogl.cpp
+++ b/engines/ags/engine/gfx/ali3dogl.cpp
@@ -35,6 +35,7 @@
 #include "ags/shared/util/math.h"
 #include "ags/engine/ac/timer.h"
 #include "ags/ags.h"
+#include "engines/util.h"
 
 namespace AGS3 {
 
@@ -540,7 +541,11 @@ void OGLGraphicsDriver::InitGlParams(const DisplayMode &mode) {
 	}
 #endif
 
-#if !AGS_PLATFORM_SCUMMVM
+#if AGS_PLATFORM_SCUMMVM
+	assert(mode.ColorDepth == 32);
+	const Graphics::PixelFormat PIXEL_FORMAT(4, 8, 8, 8, 8, 24, 16, 8, 0);
+	initGraphics(mode.Width, mode.Height, &PIXEL_FORMAT);
+#else
 #if AGS_PLATFORM_OS_LINUX
 	if (GLAD_GLX_EXT_swap_control) {
 		glXSwapIntervalEXT(_xwin.display, _xwin.window, interval);
@@ -577,7 +582,7 @@ void OGLGraphicsDriver::InitGlParams(const DisplayMode &mode) {
 
 bool OGLGraphicsDriver::CreateGlContext(const DisplayMode &mode) {
 #if AGS_PLATFORM_SCUMMVM
-	warning("TODO: CreateGlContext");
+	// TODO: Do we need to do anything here
 #elif AGS_PLATFORM_OS_WINDOWS
 	PIXELFORMATDESCRIPTOR pfd = {
 		sizeof(PIXELFORMATDESCRIPTOR),


Commit: 519004004afc1fbd89e0df1792881d4d234d2ed8
    https://github.com/scummvm/scummvm/commit/519004004afc1fbd89e0df1792881d4d234d2ed8
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix returning GetColorDepth for paletted surfaces

Changed paths:
    engines/ags/shared/gfx/allegrobitmap.h


diff --git a/engines/ags/shared/gfx/allegrobitmap.h b/engines/ags/shared/gfx/allegrobitmap.h
index 3b04c369eb..76ba4ec596 100644
--- a/engines/ags/shared/gfx/allegrobitmap.h
+++ b/engines/ags/shared/gfx/allegrobitmap.h
@@ -105,7 +105,7 @@ public:
 		return Size(_alBitmap->w, _alBitmap->h);
 	}
 	inline int  GetColorDepth() const {
-		return _alBitmap->format.bpp();
+		return (_alBitmap->format.bytesPerPixel == 1) ? 8 : _alBitmap->format.bpp();
 	}
 	// BPP: bytes per pixel
 	inline int  GetBPP() const {


Commit: 0fabbbed939f18265826b5cc8a459c640cf4c75b
    https://github.com/scummvm/scummvm/commit/0fabbbed939f18265826b5cc8a459c640cf4c75b
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Switch to using software graphics driver

Changed paths:
  R engines/ags/engine/gfx/ali3dogl.cpp
  R engines/ags/engine/gfx/ali3dogl.h
    engines/ags/engine/gfx/gfxdriverfactory.cpp
    engines/ags/module.mk


diff --git a/engines/ags/engine/gfx/ali3dogl.cpp b/engines/ags/engine/gfx/ali3dogl.cpp
deleted file mode 100644
index 9ea547a8e7..0000000000
--- a/engines/ags/engine/gfx/ali3dogl.cpp
+++ /dev/null
@@ -1,1913 +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 "ags/shared/core/platform.h"
-
-#if AGS_PLATFORM_OS_WINDOWS || AGS_PLATFORM_OS_ANDROID || AGS_PLATFORM_OS_IOS || AGS_PLATFORM_OS_LINUX
-
-#include "ags/lib/std/algorithm.h"
-#include "ags/engine/gfx/ali3dexception.h"
-#include "ags/engine/gfx/ali3dogl.h"
-#include "ags/engine/gfx/gfxfilter_ogl.h"
-#include "ags/engine/gfx/gfxfilter_aaogl.h"
-#include "ags/engine/gfx/gfx_util.h"
-#include "ags/engine/main/main_allegro.h"
-#include "ags/engine/platform/base/agsplatformdriver.h"
-#include "ags/shared/util/math.h"
-#include "ags/engine/ac/timer.h"
-#include "ags/ags.h"
-#include "engines/util.h"
-
-namespace AGS3 {
-
-#if AGS_PLATFORM_OS_ANDROID
-
-#define glOrtho glOrthof
-#define GL_CLAMP GL_CLAMP_TO_EDGE
-
-// Defined in Allegro
-extern "C"
-{
-	void android_swap_buffers();
-	void android_create_screen(int width, int height, int color_depth);
-	void android_mouse_setup(int left, int right, int top, int bottom, float scaling_x, float scaling_y);
-}
-
-extern "C" void android_debug_printf(char *format, ...);
-
-extern unsigned int android_screen_physical_width;
-extern unsigned int android_screen_physical_height;
-extern int android_screen_initialized;
-
-#define device_screen_initialized android_screen_initialized
-#define device_mouse_setup android_mouse_setup
-#define device_swap_buffers android_swap_buffers
-
-const char *fbo_extension_string = "GL_OES_framebuffer_object";
-
-#define glGenFramebuffersEXT glGenFramebuffersOES
-#define glDeleteFramebuffersEXT glDeleteFramebuffersOES
-#define glBindFramebufferEXT glBindFramebufferOES
-#define glCheckFramebufferStatusEXT glCheckFramebufferStatusOES
-#define glGetFramebufferAttachmentParameterivEXT glGetFramebufferAttachmentParameterivOES
-#define glGenerateMipmapEXT glGenerateMipmapOES
-#define glFramebufferTexture2DEXT glFramebufferTexture2DOES
-#define glFramebufferRenderbufferEXT glFramebufferRenderbufferOES
-// TODO: probably should use EGL and function eglSwapInterval on Android to support setting swap interval
-// For now this is a dummy function pointer which is only used to test that function is not supported
-const void (*glSwapIntervalEXT)(int) = NULL;
-
-#define GL_FRAMEBUFFER_EXT GL_FRAMEBUFFER_OES
-#define GL_COLOR_ATTACHMENT0_EXT GL_COLOR_ATTACHMENT0_OES
-
-#elif AGS_PLATFORM_OS_IOS
-
-extern "C"
-{
-	void ios_swap_buffers();
-	void ios_select_buffer();
-	void ios_create_screen();
-	float get_device_scale();
-	void ios_mouse_setup(int left, int right, int top, int bottom, float scaling_x, float scaling_y);
-}
-
-#define glOrtho glOrthof
-#define GL_CLAMP GL_CLAMP_TO_EDGE
-
-extern unsigned int ios_screen_physical_width;
-extern unsigned int ios_screen_physical_height;
-extern int ios_screen_initialized;
-
-#define device_screen_initialized ios_screen_initialized
-#define device_mouse_setup ios_mouse_setup
-#define device_swap_buffers ios_swap_buffers
-
-const char *fbo_extension_string = "GL_OES_framebuffer_object";
-
-#define glGenFramebuffersEXT glGenFramebuffersOES
-#define glDeleteFramebuffersEXT glDeleteFramebuffersOES
-#define glBindFramebufferEXT glBindFramebufferOES
-#define glCheckFramebufferStatusEXT glCheckFramebufferStatusOES
-#define glGetFramebufferAttachmentParameterivEXT glGetFramebufferAttachmentParameterivOES
-#define glGenerateMipmapEXT glGenerateMipmapOES
-#define glFramebufferTexture2DEXT glFramebufferTexture2DOES
-#define glFramebufferRenderbufferEXT glFramebufferRenderbufferOES
-// TODO: find out how to support swap interval setting on iOS
-// For now this is a dummy function pointer which is only used to test that function is not supported
-const void (*glSwapIntervalEXT)(int) = NULL;
-
-#define GL_FRAMEBUFFER_EXT GL_FRAMEBUFFER_OES
-#define GL_COLOR_ATTACHMENT0_EXT GL_COLOR_ATTACHMENT0_OES
-
-#endif
-
-// Necessary to update textures from 8-bit bitmaps
-extern RGB palette[256];
-
-
-namespace AGS {
-namespace Engine {
-namespace OGL {
-
-using namespace AGS::Shared;
-
-void ogl_dummy_vsync() { }
-
-#define GFX_OPENGL  AL_ID('O','G','L',' ')
-
-static const char *empty_string = "";
-
-GFX_DRIVER gfx_opengl = {
-	GFX_OPENGL,
-	empty_string,
-	empty_string,
-	"OpenGL",
-	nullptr,    // init
-	nullptr,   // exit
-	nullptr,                        // AL_METHOD(int, scroll, (int x, int y));
-	ogl_dummy_vsync,   // vsync
-	nullptr,  // setpalette
-	nullptr,                        // AL_METHOD(int, request_scroll, (int x, int y));
-	nullptr,                        // AL_METHOD(int, poll_scroll, (void));
-	nullptr,                        // AL_METHOD(void, enable_triple_buffer, (void));
-	nullptr,  //create_video_bitmap
-	nullptr,  //destroy_video_bitmap
-	nullptr,   //show_video_bitmap
-	nullptr,
-	nullptr,  //gfx_directx_create_system_bitmap,
-	nullptr, //gfx_directx_destroy_system_bitmap,
-	nullptr, //gfx_directx_set_mouse_sprite,
-	nullptr, //gfx_directx_show_mouse,
-	nullptr, //gfx_directx_hide_mouse,
-	nullptr, //gfx_directx_move_mouse,
-	nullptr,                        // AL_METHOD(void, drawing_mode, (void));
-	nullptr,                        // AL_METHOD(void, save_video_state, (void*));
-	nullptr,                        // AL_METHOD(void, restore_video_state, (void*));
-	nullptr,                        // AL_METHOD(void, set_blender_mode, (int mode, int r, int g, int b, int a));
-	nullptr,                        // AL_METHOD(int, fetch_mode_list, (void));
-	0, 0,                        // int w, h;
-	FALSE,                        // int linear;
-	0,                           // long bank_size;
-	0,                           // long bank_gran;
-	0,                           // long vid_mem;
-	0,                           // long vid_phys_base;
-	TRUE                         // int windowed;
-};
-
-void OGLBitmap::Dispose() {
-	if (_tiles != nullptr) {
-		for (int i = 0; i < _numTiles; i++)
-			glDeleteTextures(1, &(_tiles[i].texture));
-
-		free(_tiles);
-		_tiles = nullptr;
-		_numTiles = 0;
-	}
-	if (_vertex != nullptr) {
-		free(_vertex);
-		_vertex = nullptr;
-	}
-}
-
-
-OGLGraphicsDriver::ShaderProgram::ShaderProgram() : Program(0), SamplerVar(0), ColorVar(0), AuxVar(0) {}
-
-
-OGLGraphicsDriver::OGLGraphicsDriver() {
-#if AGS_PLATFORM_SCUMMVM
-	device_screen_physical_width = 640;
-	device_screen_physical_height = 480;
-	_glxContext = nullptr;
-	_have_window = false;
-#elif AGS_PLATFORM_OS_WINDOWS
-	_hDC = NULL;
-	_hRC = NULL;
-	_hWnd = NULL;
-	_hInstance = NULL;
-	device_screen_physical_width  = 0;
-	device_screen_physical_height = 0;
-#elif AGS_PLATFORM_OS_LINUX
-	device_screen_physical_width  = 0;
-	device_screen_physical_height = 0;
-	_glxContext = nullptr;
-	_have_window = false;
-#elif AGS_PLATFORM_OS_ANDROID
-	device_screen_physical_width  = android_screen_physical_width;
-	device_screen_physical_height = android_screen_physical_height;
-#elif AGS_PLATFORM_OS_IOS
-	device_screen_physical_width  = ios_screen_physical_width;
-	device_screen_physical_height = ios_screen_physical_height;
-#endif
-
-	_firstTimeInit = false;
-	_backbuffer = 0;
-	_fbo = 0;
-	_legacyPixelShader = false;
-	_can_render_to_texture = false;
-	_do_render_to_texture = false;
-	_super_sampling = 1;
-	SetupDefaultVertices();
-
-	// Shifts comply to GL_RGBA
-	_vmem_r_shift_32 = 0;
-	_vmem_g_shift_32 = 8;
-	_vmem_b_shift_32 = 16;
-	_vmem_a_shift_32 = 24;
-}
-
-
-void OGLGraphicsDriver::SetupDefaultVertices() {
-	std::fill(_backbuffer_vertices, _backbuffer_vertices + sizeof(_backbuffer_vertices) / sizeof(GLfloat), 0.0f);
-	std::fill(_backbuffer_texture_coordinates, _backbuffer_texture_coordinates + sizeof(_backbuffer_texture_coordinates) / sizeof(GLfloat), 0.0f);
-
-	defaultVertices[0].position.x = 0.0f;
-	defaultVertices[0].position.y = 0.0f;
-	defaultVertices[0].tu = 0.0;
-	defaultVertices[0].tv = 0.0;
-
-	defaultVertices[1].position.x = 1.0f;
-	defaultVertices[1].position.y = 0.0f;
-	defaultVertices[1].tu = 1.0;
-	defaultVertices[1].tv = 0.0;
-
-	defaultVertices[2].position.x = 0.0f;
-	defaultVertices[2].position.y = -1.0f;
-	defaultVertices[2].tu = 0.0;
-	defaultVertices[2].tv = 1.0;
-
-	defaultVertices[3].position.x = 1.0f;
-	defaultVertices[3].position.y = -1.0f;
-	defaultVertices[3].tu = 1.0;
-	defaultVertices[3].tv = 1.0;
-}
-
-#if AGS_PLATFORM_OS_WINDOWS || AGS_PLATFORM_OS_LINUX
-
-void OGLGraphicsDriver::CreateDesktopScreen(int width, int height, int depth) {
-	device_screen_physical_width = width;
-	device_screen_physical_height = height;
-}
-
-#elif AGS_PLATFORM_OS_ANDROID || AGS_PLATFORM_OS_IOS
-
-void OGLGraphicsDriver::UpdateDeviceScreen() {
-#if AGS_PLATFORM_OS_ANDROID
-	device_screen_physical_width  = android_screen_physical_width;
-	device_screen_physical_height = android_screen_physical_height;
-#elif AGS_PLATFORM_OS_IOS
-	device_screen_physical_width  = ios_screen_physical_width;
-	device_screen_physical_height = ios_screen_physical_height;
-#endif
-
-	Debug::Printf("OGL: notified of device screen updated to %d x %d, resizing viewport", device_screen_physical_width, device_screen_physical_height);
-	_mode.Width = device_screen_physical_width;
-	_mode.Height = device_screen_physical_height;
-	InitGlParams(_mode);
-	if (_initSurfaceUpdateCallback)
-		_initSurfaceUpdateCallback();
-}
-
-#endif
-
-void OGLGraphicsDriver::Vsync() {
-	// do nothing on OpenGL
-}
-
-void OGLGraphicsDriver::RenderSpritesAtScreenResolution(bool enabled, int supersampling) {
-	if (_can_render_to_texture) {
-		_do_render_to_texture = !enabled;
-		_super_sampling = supersampling;
-		TestSupersampling();
-	}
-
-	if (_do_render_to_texture)
-		glDisable(GL_SCISSOR_TEST);
-}
-
-bool OGLGraphicsDriver::IsModeSupported(const DisplayMode &mode) {
-	if (mode.Width <= 0 || mode.Height <= 0 || mode.ColorDepth <= 0) {
-		set_allegro_error("Invalid resolution parameters: %d x %d x %d", mode.Width, mode.Height, mode.ColorDepth);
-		return false;
-	}
-	return true;
-}
-
-bool OGLGraphicsDriver::SupportsGammaControl() {
-	return false;
-}
-
-void OGLGraphicsDriver::SetGamma(int newGamma) {
-}
-
-void OGLGraphicsDriver::SetGraphicsFilter(POGLFilter filter) {
-	_filter = filter;
-	OnSetFilter();
-}
-
-void OGLGraphicsDriver::SetTintMethod(TintMethod method) {
-	_legacyPixelShader = (method == TintReColourise);
-}
-
-void OGLGraphicsDriver::FirstTimeInit() {
-	String ogl_v_str;
-#ifdef GLAPI
-	ogl_v_str.Format("%d.%d", GLVersion.major, GLVersion.minor);
-#else
-	ogl_v_str = (const char *)glGetString(GL_VERSION);
-#endif
-	Debug::Printf(kDbgMsg_Info, "Running OpenGL: %s", ogl_v_str.GetCStr());
-
-	// Initialize default sprite batch, it will be used when no other batch was activated
-	OGLGraphicsDriver::InitSpriteBatch(0, _spriteBatchDesc[0]);
-
-	TestRenderToTexture();
-	CreateShaders();
-	_firstTimeInit = true;
-}
-
-#if !AGS_PLATFORM_SCUMMVM
-#if AGS_PLATFORM_OS_LINUX
-Atom get_x_atom(const char *atom_name) {
-	Atom atom = XInternAtom(_xwin.display, atom_name, False);
-	if (atom == None) {
-		Debug::Printf(kDbgMsg_Error, "ERROR: X11 atom \"%s\" not found.\n", atom_name);
-	}
-	return atom;
-}
-#endif
-#endif
-
-bool OGLGraphicsDriver::InitGlScreen(const DisplayMode &mode) {
-#if AGS_PLATFORM_OS_ANDROID
-	android_create_screen(mode.Width, mode.Height, mode.ColorDepth);
-#elif AGS_PLATFORM_OS_IOS
-	ios_create_screen();
-	ios_select_buffer();
-#elif AGS_PLATFORM_OS_WINDOWS
-	if (mode.Windowed) {
-		platform->AdjustWindowStyleForWindowed();
-	} else {
-		if (platform->EnterFullscreenMode(mode))
-			platform->AdjustWindowStyleForFullscreen();
-	}
-
-	// NOTE: adjust_window may leave task bar visible, so we do not use it for fullscreen mode
-	if (mode.Windowed && adjust_window(mode.Width, mode.Height) != 0) {
-		set_allegro_error("Window size not supported");
-		return false;
-	}
-
-	_hWnd = win_get_window();
-	if (!(_hDC = GetDC(_hWnd)))
-		return false;
-
-	// First check if we need to recreate GL context, this will only be
-	// required if different color depth is requested.
-	if (_hRC) {
-		GLuint pixel_fmt = GetPixelFormat(_hDC);
-		PIXELFORMATDESCRIPTOR pfd;
-		DescribePixelFormat(_hDC, pixel_fmt, sizeof(PIXELFORMATDESCRIPTOR), &pfd);
-		if (pfd.cColorBits != mode.ColorDepth) {
-			DeleteGlContext();
-		}
-	}
-
-	if (!_hRC) {
-		if (!CreateGlContext(mode))
-			return false;
-	}
-
-	if (!gladLoadWGL(_hDC)) {
-		Debug::Printf(kDbgMsg_Error, "Failed to load WGL.");
-		return false;
-	}
-
-	if (!gladLoadGL()) {
-		Debug::Printf(kDbgMsg_Error, "Failed to load GL.");
-		return false;
-	}
-
-	CreateDesktopScreen(mode.Width, mode.Height, mode.ColorDepth);
-	win_grab_input();
-#elif AGS_PLATFORM_SCUMMVM
-	warning("TODO: InitGlScreen");
-
-#elif AGS_PLATFORM_OS_LINUX
-	if (!_have_window) {
-		// Use Allegro to create our window. We don't care what size Allegro uses
-		// here, we will set that ourselves below by manipulating members of
-		// Allegro's_xwin structure. We need to use the Allegro routine here (rather
-		// than create our own X window) to remain compatible with Allegro's mouse &
-		// keyboard handling.
-		//
-		// Note that although _xwin contains a special "fullscreen" Window member
-		// (_xwin.fs_window), we do not use it for going fullscreen. Instead we ask
-		// the window manager to take the "managed" Window (_xwin.wm_window)
-		// fullscreen for us. All drawing goes to the "real" Window (_xwin.window).
-		if (set_gfx_mode(GFX_AUTODETECT_WINDOWED, 0, 0, 0, 0) != 0)
-			return false;
-		_have_window = true;
-	}
-
-	if (!gladLoadGLX(_xwin.display, DefaultScreen(_xwin.display))) {
-		Debug::Printf(kDbgMsg_Error, "Failed to load GLX.");
-		return false;
-	}
-
-	if (!_glxContext && !CreateGlContext(mode))
-		return false;
-
-	if (!gladLoadGL()) {
-		Debug::Printf(kDbgMsg_Error, "Failed to load GL.");
-		return false;
-	}
-
-	{
-		// Set the size of our "managed" window.
-		XSizeHints *hints = XAllocSizeHints();
-
-		if (hints) {
-			if (mode.Windowed) {
-				// Set a fixed-size window. This is copied from Allegro 4's
-				// _xwin_private_create_screen().
-				hints->flags = PMinSize | PMaxSize | PBaseSize;
-				hints->min_width  = hints->max_width  = hints->base_width  = mode.Width;
-				hints->min_height = hints->max_height = hints->base_height = mode.Height;
-			} else {
-				// Clear any previously set demand for a fixed-size window, otherwise
-				// the window manager will ignore our request to go full-screen.
-				hints->flags = 0;
-			}
-
-			XSetWMNormalHints(_xwin.display, _xwin.wm_window, hints);
-		}
-
-		XFree(hints);
-	}
-
-	// Set the window we are actually drawing into to the desired size.
-	XResizeWindow(_xwin.display, _xwin.window, mode.Width, mode.Height);
-
-	// Make Allegro aware of the new window size, otherwise the mouse cursor
-	// movement may be erratic.
-	_xwin.window_width = mode.Width;
-	_xwin.window_height = mode.Height;
-
-	{
-		// Ask the window manager to add (or remove) the "fullscreen" property on
-		// our top-level window.
-		const Atom wm_state = get_x_atom("_NET_WM_STATE");
-		const Atom fullscreen = get_x_atom("_NET_WM_STATE_FULLSCREEN");
-		const long remove_property = 0;
-		const long add_property = 1;
-
-		XEvent xev;
-		memset(&xev, 0, sizeof(xev));
-		xev.type = ClientMessage;
-		xev.xclient.window = _xwin.wm_window;
-		xev.xclient.message_type = wm_state;
-		xev.xclient.format = 32;
-		xev.xclient.data.l[0] = mode.Windowed ? remove_property : add_property;
-		xev.xclient.data.l[1] = fullscreen;
-		xev.xclient.data.l[2] = 0;
-		xev.xclient.data.l[3] = 1; // Message source is a regular application.
-		Status status = XSendEvent(_xwin.display, DefaultRootWindow(_xwin.display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
-		if (status == 0) {
-			Debug::Printf(kDbgMsg_Error, "ERROR: Failed to encode window state message.\n");
-		}
-	}
-
-	CreateDesktopScreen(mode.Width, mode.Height, mode.ColorDepth);
-#endif
-
-	gfx_driver = &gfx_opengl;
-	return true;
-}
-
-void OGLGraphicsDriver::InitGlParams(const DisplayMode &mode) {
-	glDisable(GL_CULL_FACE);
-	glDisable(GL_DEPTH_TEST);
-	glDisable(GL_LIGHTING);
-	glShadeModel(GL_FLAT);
-
-	glEnable(GL_TEXTURE_2D);
-
-	glEnable(GL_BLEND);
-	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
-
-	glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
-	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
-	glClear(GL_COLOR_BUFFER_BIT);
-
-	glViewport(0, 0, device_screen_physical_width, device_screen_physical_height);
-	glMatrixMode(GL_PROJECTION);
-	glLoadIdentity();
-	glOrtho(0, device_screen_physical_width, 0, device_screen_physical_height, 0, 1);
-	glMatrixMode(GL_MODELVIEW);
-	glLoadIdentity();
-
-	glDisableClientState(GL_COLOR_ARRAY);
-	glDisableClientState(GL_NORMAL_ARRAY);
-	glEnableClientState(GL_VERTEX_ARRAY);
-	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
-
-#if !AGS_PLATFORM_SCUMMVM
-	auto interval = mode.Vsync ? 1 : 0;
-#endif
-	bool vsyncEnabled = false;
-
-#if AGS_PLATFORM_OS_WINDOWS
-	if (GLAD_WGL_EXT_swap_control) {
-		vsyncEnabled = wglSwapIntervalEXT(interval) != FALSE;
-	}
-#endif
-
-#if AGS_PLATFORM_SCUMMVM
-	assert(mode.ColorDepth == 32);
-	const Graphics::PixelFormat PIXEL_FORMAT(4, 8, 8, 8, 8, 24, 16, 8, 0);
-	initGraphics(mode.Width, mode.Height, &PIXEL_FORMAT);
-#else
-#if AGS_PLATFORM_OS_LINUX
-	if (GLAD_GLX_EXT_swap_control) {
-		glXSwapIntervalEXT(_xwin.display, _xwin.window, interval);
-		// glx requires hooking into XSetErrorHandler to test for BadWindow or BadValue
-		vsyncEnabled = true;
-	} else if (GLAD_GLX_MESA_swap_control) {
-		vsyncEnabled = glXSwapIntervalMESA(interval) == 0;
-	} else if (GLAD_GLX_SGI_swap_control) {
-		vsyncEnabled = glXSwapIntervalSGI(interval) == 0;
-	}
-#endif
-#endif
-
-	// TODO: find out how to implement SwapInterval on other platforms, and how to check if it's supported
-
-	if (mode.Vsync && !vsyncEnabled) {
-		Debug::Printf(kDbgMsg_Warn, "WARNING: Vertical sync could not be enabled. Setting will be kept at driver default.");
-	}
-
-#if AGS_PLATFORM_OS_ANDROID || AGS_PLATFORM_OS_IOS
-	// Setup library mouse to have 1:1 coordinate transformation.
-	// NOTE: cannot move this call to general mouse handling mode. Unfortunately, much of the setup and rendering
-	// is duplicated in the Android/iOS ports' Allegro library patches, and is run when the Software renderer
-	// is selected in AGS. This ugly situation causes trouble...
-	float device_scale = 1.0f;
-
-#if AGS_PLATFORM_OS_IOS
-	device_scale = get_device_scale();
-#endif
-
-	device_mouse_setup(0, device_screen_physical_width - 1, 0, device_screen_physical_height - 1, device_scale, device_scale);
-#endif
-}
-
-bool OGLGraphicsDriver::CreateGlContext(const DisplayMode &mode) {
-#if AGS_PLATFORM_SCUMMVM
-	// TODO: Do we need to do anything here
-#elif AGS_PLATFORM_OS_WINDOWS
-	PIXELFORMATDESCRIPTOR pfd = {
-		sizeof(PIXELFORMATDESCRIPTOR),
-		1,
-		PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
-		PFD_TYPE_RGBA,
-		(BYTE)mode.ColorDepth,
-		0, 0, 0, 0, 0, 0,
-		0,
-		0,
-		0,
-		0, 0, 0, 0,
-		0,
-		0,
-		0,
-		PFD_MAIN_PLANE,
-		0,
-		0, 0, 0
-	};
-
-	_oldPixelFormat = GetPixelFormat(_hDC);
-	DescribePixelFormat(_hDC, _oldPixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &_oldPixelFormatDesc);
-
-	GLuint pixel_fmt;
-	if (!(pixel_fmt = ChoosePixelFormat(_hDC, &pfd)))
-		return false;
-
-	if (!SetPixelFormat(_hDC, pixel_fmt, &pfd))
-		return false;
-
-	if (!(_hRC = wglCreateContext(_hDC)))
-		return false;
-
-	if (!wglMakeCurrent(_hDC, _hRC))
-		return false;
-#elif AGS_PLATFORM_OS_LINUX
-	int attrib[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
-	XVisualInfo *vi = glXChooseVisual(_xwin.display, DefaultScreen(_xwin.display), attrib);
-	if (!vi) {
-		Debug::Printf(kDbgMsg_Error, "ERROR: glXChooseVisual() failed.\n");
-		return false;
-	}
-
-	if (!(_glxContext = glXCreateContext(_xwin.display, vi, None, True))) {
-		Debug::Printf(kDbgMsg_Error, "ERROR: glXCreateContext() failed.\n");
-		return false;
-	}
-
-	if (!glXMakeCurrent(_xwin.display, _xwin.window, _glxContext)) {
-		Debug::Printf(kDbgMsg_Error, "ERROR: glXMakeCurrent() failed.\n");
-		return false;
-	}
-#endif
-	return true;
-}
-
-void OGLGraphicsDriver::DeleteGlContext() {
-#if AGS_PLATFORM_SCUMMVM
-	warning("TODO: DeleteGlContext");
-#elif AGS_PLATFORM_OS_WINDOWS
-	if (_hRC) {
-		wglMakeCurrent(NULL, NULL);
-		wglDeleteContext(_hRC);
-		_hRC = NULL;
-	}
-
-	if (_oldPixelFormat > 0)
-		SetPixelFormat(_hDC, _oldPixelFormat, &_oldPixelFormatDesc);
-#elif AGS_PLATFORM_OS_LINUX
-	if (_glxContext) {
-		glXMakeCurrent(_xwin.display, None, nullptr);
-		glXDestroyContext(_xwin.display, _glxContext);
-		_glxContext = nullptr;
-	}
-#endif
-}
-
-inline bool CanDoFrameBuffer() {
-#ifdef GLAPI
-	return GLAD_GL_EXT_framebuffer_object != 0;
-#else
-#if AGS_PLATFORM_OS_ANDROID || AGS_PLATFORM_OS_IOS
-	const char *fbo_extension_string = "GL_OES_framebuffer_object";
-#else
-	const char *fbo_extension_string = "GL_EXT_framebuffer_object";
-#endif
-	const char *extensions = (const char *)glGetString(GL_EXTENSIONS);
-	return extensions && strstr(extensions, fbo_extension_string) != NULL;
-#endif
-}
-
-void OGLGraphicsDriver::TestRenderToTexture() {
-	if (CanDoFrameBuffer()) {
-		_can_render_to_texture = true;
-		TestSupersampling();
-	} else {
-		_can_render_to_texture = false;
-		Debug::Printf(kDbgMsg_Warn, "WARNING: OpenGL extension 'GL_EXT_framebuffer_object' not supported, rendering to texture mode will be disabled.");
-	}
-
-	if (!_can_render_to_texture)
-		_do_render_to_texture = false;
-}
-
-void OGLGraphicsDriver::TestSupersampling() {
-#if !AGS_PLATFORM_SCUMMVM
-	if (!_can_render_to_texture)
-		return;
-	// Disable super-sampling if it would cause a too large texture size
-	if (_super_sampling > 1) {
-		int max = 1024;
-		glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max);
-		if ((max < _srcRect.GetWidth() * _super_sampling) || (max < _srcRect.GetHeight() * _super_sampling))
-			_super_sampling = 1;
-	}
-#endif
-}
-
-void OGLGraphicsDriver::CreateShaders() {
-	if (!GLAD_GL_VERSION_2_0) {
-		Debug::Printf(kDbgMsg_Error, "ERROR: Shaders require a minimum of OpenGL 2.0 support.");
-		return;
-	}
-	CreateTintShader();
-	CreateLightShader();
-}
-
-void OGLGraphicsDriver::CreateTintShader() {
-	const char *fragment_shader_src =
-	    // NOTE: this shader emulates "historical" AGS software tinting; it is not
-	    // necessarily "proper" tinting in modern terms.
-	    // The RGB-HSV-RGB conversion found in the Internet (copyright unknown);
-	    // Color processing is replicated from Direct3D shader by Chris Jones
-	    // (Engine/resource/tintshaderLegacy.fx).
-	    // Uniforms:
-	    // textID - texture index (usually 0),
-	    // tintHSV - tint color in HSV,
-	    // tintAmnTrsLum - tint parameters: amount, translucence (alpha), luminance.
-	    "\
-                                #version 120\n\
-                                uniform sampler2D textID;\n\
-                                uniform vec3 tintHSV;\n\
-                                uniform vec3 tintAmnTrsLum;\n\
-                                \
-                                vec3 rgb2hsv(vec3 c)\n\
-                                {\n\
-                                    vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);\n\
-                                    vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));\n\
-                                    vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));\n\
-                                \
-                                    float d = q.x - min(q.w, q.y);\n\
-                                    const float e = 1.0e-10;\n\
-                                    return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);\n\
-                                }\n\
-                                \
-                                vec3 hsv2rgb(vec3 c)\n\
-                                {\n\
-                                    vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);\n\
-                                    vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);\n\
-                                    return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);\n\
-                                }\n\
-                                \
-                                float getValue(vec3 color)\n\
-                                {\n\
-                                    float colorMax = max (color[0], color[1]);\n\
-                                    colorMax = max (colorMax, color[2]);\n\
-                                    return colorMax;\n\
-                                }\n\
-                                \
-                                void main()\n\
-                                {\n\
-                                    vec4 src_col = texture2D(textID, gl_TexCoord[0].xy);\n\
-                                    float amount = tintAmnTrsLum[0];\n\
-                                    float lum = getValue(src_col.xyz);\n\
-                                    lum = max(lum - (1.0 - tintAmnTrsLum[2]), 0.0);\n\
-                                    vec3 new_col = (hsv2rgb(vec3(tintHSV[0], tintHSV[1], lum)) * amount + src_col.xyz * (1.0 - amount));\n\
-                                    gl_FragColor = vec4(new_col, src_col.w * tintAmnTrsLum[1]);\n\
-                                }\n\
-    ";
-	CreateShaderProgram(_tintShader, "Tinting", fragment_shader_src, "textID", "tintHSV", "tintAmnTrsLum");
-}
-
-void OGLGraphicsDriver::CreateLightShader() {
-	const char *fragment_shader_src =
-	    // NOTE: due to how the lighting works in AGS, this is combined MODULATE / ADD shader.
-	    // if the light is < 0, then MODULATE operation is used, otherwise ADD is used.
-	    // NOTE: it's been said that using branching in shaders produces inefficient code.
-	    // If that will ever become a real problem, we can easily split this shader in two.
-	    // Uniforms:
-	    // textID - texture index (usually 0),
-	    // light - light level,
-	    // alpha - color alpha value.
-	    "\
-                                #version 120\n\
-                                uniform sampler2D textID;\n\
-                                uniform float light;\n\
-                                uniform float alpha;\n\
-                                \
-                                void main()\n\
-                                {\n\
-                                    vec4 src_col = texture2D(textID, gl_TexCoord[0].xy);\n\
-                                    if (light >= 0.0)\n\
-                                        gl_FragColor = vec4(src_col.xyz + vec3(light, light, light), src_col.w * alpha);\n\
-                                    else\n\
-                                        gl_FragColor = vec4(src_col.xyz * abs(light), src_col.w * alpha);\n\
-                                }\n\
-    ";
-	CreateShaderProgram(_lightShader, "Lighting", fragment_shader_src, "textID", "light", "alpha");
-}
-
-void OGLGraphicsDriver::CreateShaderProgram(ShaderProgram &prg, const char *name, const char *fragment_shader_src,
-        const char *sampler_var, const char *color_var, const char *aux_var) {
-#if !AGS_PLATFORM_SCUMMVM
-	GLint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
-	glShaderSource(fragment_shader, 1, &fragment_shader_src, nullptr);
-	glCompileShader(fragment_shader);
-	GLint result;
-	glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &result);
-	if (result == GL_FALSE) {
-		OutputShaderError(fragment_shader, String::FromFormat("%s program's fragment shader", name), true);
-		glDeleteShader(fragment_shader);
-		return;
-	}
-
-	GLuint program = glCreateProgram();
-	glAttachShader(program, fragment_shader);
-	glLinkProgram(program);
-	glGetProgramiv(program, GL_LINK_STATUS, &result);
-	if (result == GL_FALSE) {
-		OutputShaderError(program, String::FromFormat("%s program", name), false);
-		glDeleteProgram(program);
-		glDeleteShader(fragment_shader);
-		return;
-	}
-	glDetachShader(program, fragment_shader);
-	glDeleteShader(fragment_shader);
-
-	prg.Program = program;
-	prg.SamplerVar = glGetUniformLocation(program, sampler_var);
-	prg.ColorVar = glGetUniformLocation(program, color_var);
-	prg.AuxVar = glGetUniformLocation(program, aux_var);
-	Debug::Printf("OGL: %s shader program created successfully", name);
-#endif
-}
-
-void OGLGraphicsDriver::DeleteShaderProgram(ShaderProgram &prg) {
-	if (prg.Program)
-		glDeleteProgram(prg.Program);
-	prg.Program = 0;
-}
-
-void OGLGraphicsDriver::OutputShaderError(GLuint obj_id, const String &obj_name, bool is_shader) {
-#ifdef TODO
-	GLint log_len;
-	if (is_shader)
-		glGetShaderiv(obj_id, GL_INFO_LOG_LENGTH, &log_len);
-	else
-		glGetProgramiv(obj_id, GL_INFO_LOG_LENGTH, &log_len);
-	std::vector<GLchar> errorLog(log_len);
-	if (log_len > 0) {
-		if (is_shader)
-			glGetShaderInfoLog(obj_id, log_len, &log_len, &errorLog[0]);
-		else
-			glGetProgramInfoLog(obj_id, log_len, &log_len, &errorLog[0]);
-	}
-
-	Debug::Printf(kDbgMsg_Error, "ERROR: OpenGL: %s %s:", obj_name.GetCStr(), is_shader ? "failed to compile" : "failed to link");
-	if (errorLog.size() > 0) {
-		Debug::Printf(kDbgMsg_Error, "----------------------------------------");
-		Debug::Printf(kDbgMsg_Error, "%s", &errorLog[0]);
-		Debug::Printf(kDbgMsg_Error, "----------------------------------------");
-	} else {
-		Debug::Printf(kDbgMsg_Error, "Shader info log was empty.");
-	}
-#else
-	error("Obj Id=%u, Name=%s, Is Shader=%d", obj_id, obj_name.GetNullableCStr(), (int)is_shader);
-#endif
-}
-
-void OGLGraphicsDriver::SetupBackbufferTexture() {
-	// NOTE: ability to render to texture depends on OGL context, which is
-	// created in SetDisplayMode, therefore creation of textures require
-	// both native size set and context capabilities test passed.
-	if (!IsNativeSizeValid() || !_can_render_to_texture)
-		return;
-#if !AGS_PLATFORM_SCUMMVM
-	DeleteBackbufferTexture();
-
-	// _backbuffer_texture_coordinates defines translation from wanted texture size to actual supported texture size
-	_backRenderSize = _srcRect.GetSize() * _super_sampling;
-	_backTextureSize = _backRenderSize;
-	AdjustSizeToNearestSupportedByCard(&_backTextureSize.Width, &_backTextureSize.Height);
-	const float back_ratio_w = (float)_backRenderSize.Width / (float)_backTextureSize.Width;
-	const float back_ratio_h = (float)_backRenderSize.Height / (float)_backTextureSize.Height;
-	std::fill(_backbuffer_texture_coordinates, _backbuffer_texture_coordinates + sizeof(_backbuffer_texture_coordinates) / sizeof(GLfloat), 0.0f);
-	_backbuffer_texture_coordinates[2] = _backbuffer_texture_coordinates[6] = back_ratio_w;
-	_backbuffer_texture_coordinates[5] = _backbuffer_texture_coordinates[7] = back_ratio_h;
-
-	glGenTextures(1, &_backbuffer);
-	glBindTexture(GL_TEXTURE_2D, _backbuffer);
-
-	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
-	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
-	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
-	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, _backTextureSize.Width, _backTextureSize.Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
-	glBindTexture(GL_TEXTURE_2D, 0);
-
-	glGenFramebuffersEXT(1, &_fbo);
-	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _fbo);
-	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, _backbuffer, 0);
-
-	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
-#endif
-	// Assign vertices of the backbuffer texture position in the scene
-	_backbuffer_vertices[0] = _backbuffer_vertices[4] = 0;
-	_backbuffer_vertices[2] = _backbuffer_vertices[6] = _srcRect.GetWidth();
-	_backbuffer_vertices[5] = _backbuffer_vertices[7] = _srcRect.GetHeight();
-	_backbuffer_vertices[1] = _backbuffer_vertices[3] = 0;
-}
-
-void OGLGraphicsDriver::DeleteBackbufferTexture() {
-	if (_backbuffer)
-		glDeleteTextures(1, &_backbuffer);
-	if (_fbo)
-		glDeleteFramebuffersEXT(1, &_fbo);
-	_backbuffer = 0;
-	_fbo = 0;
-}
-
-void OGLGraphicsDriver::SetupViewport() {
-	if (!IsModeSet() || !IsRenderFrameValid())
-		return;
-
-	// Setup viewport rect and scissor
-	_viewportRect = ConvertTopDownRect(_dstRect, device_screen_physical_height);
-	glScissor(_viewportRect.Left, _viewportRect.Top, _viewportRect.GetWidth(), _viewportRect.GetHeight());
-}
-
-Rect OGLGraphicsDriver::ConvertTopDownRect(const Rect &rect, int surface_height) {
-	return RectWH(rect.Left, surface_height - 1 - rect.Bottom, rect.GetWidth(), rect.GetHeight());
-}
-
-bool OGLGraphicsDriver::SetDisplayMode(const DisplayMode &mode, volatile int *loopTimer) {
-	ReleaseDisplayMode();
-
-	if (mode.ColorDepth < 15) {
-		set_allegro_error("OpenGL driver does not support 256-color display mode");
-		return false;
-	}
-
-//	try {
-		if (!InitGlScreen(mode))
-			return false;
-		if (!_firstTimeInit)
-			FirstTimeInit();
-		InitGlParams(mode);
-/*	} catch (Ali3DException exception) {
-		if (exception._message != get_allegro_error())
-			set_allegro_error(exception._message);
-		return false;
-	}*/
-
-	OnInit(loopTimer);
-
-	// On certain platforms OpenGL renderer ignores requested screen sizes
-	// and uses values imposed by the operating system (device).
-	DisplayMode final_mode = mode;
-	final_mode.Width = device_screen_physical_width;
-	final_mode.Height = device_screen_physical_height;
-	OnModeSet(final_mode);
-
-	// If we already have a native size set, then update virtual screen and setup backbuffer texture immediately
-	CreateVirtualScreen();
-	SetupBackbufferTexture();
-	// If we already have a render frame configured, then setup viewport and backbuffer mappings immediately
-	SetupViewport();
-	return true;
-}
-
-void OGLGraphicsDriver::CreateVirtualScreen() {
-	if (!IsModeSet() || !IsNativeSizeValid())
-		return;
-	// create initial stage screen for plugin raw drawing
-	_stageVirtualScreen = CreateStageScreen(0, _srcRect.GetSize());
-	// we must set Allegro's screen pointer to **something**
-	screen = (BITMAP *)_stageVirtualScreen->GetAllegroBitmap();
-}
-
-bool OGLGraphicsDriver::SetNativeSize(const Size &src_size) {
-	OnSetNativeSize(src_size);
-	SetupBackbufferTexture();
-	// If we already have a gfx mode set, then update virtual screen immediately
-	CreateVirtualScreen();
-	TestSupersampling();
-	return !_srcRect.IsEmpty();
-}
-
-bool OGLGraphicsDriver::SetRenderFrame(const Rect &dst_rect) {
-	if (!IsNativeSizeValid())
-		return false;
-	OnSetRenderFrame(dst_rect);
-	// Also make sure viewport and backbuffer mappings are updated using new native & destination rectangles
-	SetupViewport();
-	return !_dstRect.IsEmpty();
-}
-
-int OGLGraphicsDriver::GetDisplayDepthForNativeDepth(int native_color_depth) const {
-	// TODO: check for device caps to know which depth is supported?
-	return 32;
-}
-
-IGfxModeList *OGLGraphicsDriver::GetSupportedModeList(int color_depth) {
-	std::vector<DisplayMode> modes;
-	platform->GetSystemDisplayModes(modes);
-	return new OGLDisplayModeList(modes);
-}
-
-PGfxFilter OGLGraphicsDriver::GetGraphicsFilter() const {
-	return _filter;
-}
-
-void OGLGraphicsDriver::ReleaseDisplayMode() {
-	if (!IsModeSet())
-		return;
-
-	OnModeReleased();
-	ClearDrawLists();
-	ClearDrawBackups();
-	DeleteBackbufferTexture();
-	DestroyFxPool();
-	DestroyAllStageScreens();
-
-	gfx_driver = nullptr;
-
-	platform->ExitFullscreenMode();
-}
-
-void OGLGraphicsDriver::UnInit() {
-	OnUnInit();
-	ReleaseDisplayMode();
-
-	DeleteGlContext();
-#if AGS_PLATFORM_OS_WINDOWS
-	_hWnd = NULL;
-	_hDC = NULL;
-#endif
-
-	DeleteShaderProgram(_tintShader);
-	DeleteShaderProgram(_lightShader);
-}
-
-OGLGraphicsDriver::~OGLGraphicsDriver() {
-	OGLGraphicsDriver::UnInit();
-}
-
-void OGLGraphicsDriver::ClearRectangle(int x1, int y1, int x2, int y2, RGB *colorToUse) {
-	// NOTE: this function is practically useless at the moment, because OGL redraws whole game frame each time
-}
-
-bool OGLGraphicsDriver::GetCopyOfScreenIntoBitmap(Bitmap *destination, bool at_native_res, GraphicResolution *want_fmt) {
-	(void)at_native_res; // TODO: support this at some point
-
-	// TODO: following implementation currently only reads GL pixels in 32-bit RGBA.
-	// this **should** work regardless of actual display mode because OpenGL is
-	// responsible to convert and fill pixel buffer correctly.
-	// If you like to support writing directly into 16-bit bitmap, please take
-	// care of ammending the pixel reading code below.
-	const int read_in_colordepth = 32;
-	Size need_size = _do_render_to_texture ? _backRenderSize : _dstRect.GetSize();
-	if (destination->GetColorDepth() != read_in_colordepth || destination->GetSize() != need_size) {
-		if (want_fmt)
-			*want_fmt = GraphicResolution(need_size.Width, need_size.Height, read_in_colordepth);
-		return false;
-	}
-
-	Rect retr_rect;
-	if (_do_render_to_texture) {
-		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _fbo);
-		retr_rect = RectWH(0, 0, _backRenderSize.Width, _backRenderSize.Height);
-	} else {
-#if AGS_PLATFORM_OS_IOS
-		ios_select_buffer();
-#elif AGS_PLATFORM_OS_WINDOWS || AGS_PLATFORM_OS_LINUX
-		glReadBuffer(GL_FRONT);
-#endif
-		retr_rect = _dstRect;
-	}
-
-	int bpp = read_in_colordepth / 8;
-	int bufferSize = retr_rect.GetWidth() * retr_rect.GetHeight() * bpp;
-
-	unsigned char *buffer = new unsigned char[bufferSize];
-	if (buffer) {
-		glReadPixels(retr_rect.Left, retr_rect.Top, retr_rect.GetWidth(), retr_rect.GetHeight(), GL_RGBA, GL_UNSIGNED_BYTE, buffer);
-
-		unsigned char *sourcePtr = buffer;
-		for (int y = destination->GetHeight() - 1; y >= 0; y--) {
-			unsigned int *destPtr = reinterpret_cast<unsigned int *>(&destination->GetScanLineForWriting(y)[0]);
-			for (int dx = 0, sx = 0; dx < destination->GetWidth(); ++dx, sx = dx * bpp) {
-				destPtr[dx] = makeacol32(sourcePtr[sx + 0], sourcePtr[sx + 1], sourcePtr[sx + 2], sourcePtr[sx + 3]);
-			}
-			sourcePtr += retr_rect.GetWidth() * bpp;
-		}
-
-		if (_pollingCallback)
-			_pollingCallback();
-
-		delete [] buffer;
-	}
-	return true;
-}
-
-void OGLGraphicsDriver::RenderToBackBuffer() {
-	error("OGL driver does not have a back buffer");
-}
-
-void OGLGraphicsDriver::Render() {
-	Render(0, 0, kFlip_None);
-}
-
-void OGLGraphicsDriver::Render(int /*xoff*/, int /*yoff*/, GlobalFlipType /*flip*/) {
-	_render(true);
-}
-
-void OGLGraphicsDriver::_reDrawLastFrame() {
-	RestoreDrawLists();
-}
-
-void OGLGraphicsDriver::_renderSprite(const OGLDrawListEntry *drawListEntry, const GLMATRIX &matGlobal) {
-	OGLBitmap *bmpToDraw = drawListEntry->bitmap;
-
-	if (bmpToDraw->_transparency >= 255)
-		return;
-
-	const bool do_tint = bmpToDraw->_tintSaturation > 0 && _tintShader.Program > 0;
-	const bool do_light = bmpToDraw->_tintSaturation == 0 && bmpToDraw->_lightLevel > 0 && _lightShader.Program > 0;
-	if (do_tint) {
-		// Use tinting shader
-		glUseProgram(_tintShader.Program);
-		float rgb[3];
-		float sat_trs_lum[3]; // saturation / transparency / luminance
-		if (_legacyPixelShader) {
-			rgb_to_hsv(bmpToDraw->_red, bmpToDraw->_green, bmpToDraw->_blue, &rgb[0], &rgb[1], &rgb[2]);
-			rgb[0] /= 360.0; // In HSV, Hue is 0-360
-		} else {
-			rgb[0] = (float)bmpToDraw->_red / 255.0;
-			rgb[1] = (float)bmpToDraw->_green / 255.0;
-			rgb[2] = (float)bmpToDraw->_blue / 255.0;
-		}
-
-		sat_trs_lum[0] = (float)bmpToDraw->_tintSaturation / 255.0;
-
-		if (bmpToDraw->_transparency > 0)
-			sat_trs_lum[1] = (float)bmpToDraw->_transparency / 255.0;
-		else
-			sat_trs_lum[1] = 1.0f;
-
-		if (bmpToDraw->_lightLevel > 0)
-			sat_trs_lum[2] = (float)bmpToDraw->_lightLevel / 255.0;
-		else
-			sat_trs_lum[2] = 1.0f;
-
-		glUniform1i(_tintShader.SamplerVar, 0);
-		glUniform3f(_tintShader.ColorVar, rgb[0], rgb[1], rgb[2]);
-		glUniform3f(_tintShader.AuxVar, sat_trs_lum[0], sat_trs_lum[1], sat_trs_lum[2]);
-	} else if (do_light) {
-		// Use light shader
-		glUseProgram(_lightShader.Program);
-		float light_lev = 1.0f;
-		float alpha = 1.0f;
-
-		// Light level parameter in DDB is weird, it is measured in units of
-		// 1/255 (although effectively 1/250, see draw.cpp), but contains two
-		// ranges: 1-255 is darker range and 256-511 is brighter range.
-		// (light level of 0 means "default color")
-		if ((bmpToDraw->_lightLevel > 0) && (bmpToDraw->_lightLevel < 256)) {
-			// darkening the sprite... this stupid calculation is for
-			// consistency with the allegro software-mode code that does
-			// a trans blend with a (8,8,8) sprite
-			light_lev = -((bmpToDraw->_lightLevel * 192) / 256 + 64) / 255.f; // darker, uses MODULATE op
-		} else if (bmpToDraw->_lightLevel > 256) {
-			light_lev = ((bmpToDraw->_lightLevel - 256) / 2) / 255.f; // brighter, uses ADD op
-		}
-
-		if (bmpToDraw->_transparency > 0)
-			alpha = bmpToDraw->_transparency / 255.f;
-
-		glUniform1i(_lightShader.SamplerVar, 0);
-		glUniform1f(_lightShader.ColorVar, light_lev);
-		glUniform1f(_lightShader.AuxVar, alpha);
-	} else {
-		// Use default processing
-		if (bmpToDraw->_transparency == 0)
-			glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
-		else
-			glColor4f(1.0f, 1.0f, 1.0f, bmpToDraw->_transparency / 255.0f);
-	}
-
-	float width = bmpToDraw->GetWidthToRender();
-	float height = bmpToDraw->GetHeightToRender();
-	float xProportion = (float)width / (float)bmpToDraw->_width;
-	float yProportion = (float)height / (float)bmpToDraw->_height;
-	int drawAtX = drawListEntry->x;
-	int drawAtY = drawListEntry->y;
-
-	for (int ti = 0; ti < bmpToDraw->_numTiles; ti++) {
-		width = bmpToDraw->_tiles[ti].width * xProportion;
-		height = bmpToDraw->_tiles[ti].height * yProportion;
-		float xOffs;
-		float yOffs = bmpToDraw->_tiles[ti].y * yProportion;
-		if (bmpToDraw->_flipped)
-			xOffs = (bmpToDraw->_width - (bmpToDraw->_tiles[ti].x + bmpToDraw->_tiles[ti].width)) * xProportion;
-		else
-			xOffs = bmpToDraw->_tiles[ti].x * xProportion;
-		int thisX = drawAtX + xOffs;
-		int thisY = drawAtY + yOffs;
-		thisX = (-(_srcRect.GetWidth() / 2)) + thisX;
-		thisY = (_srcRect.GetHeight() / 2) - thisY;
-
-		//Setup translation and scaling matrices
-		float widthToScale = (float)width;
-		float heightToScale = (float)height;
-		if (bmpToDraw->_flipped) {
-			// The usual transform changes 0..1 into 0..width
-			// So first negate it (which changes 0..w into -w..0)
-			widthToScale = -widthToScale;
-			// and now shift it over to make it 0..w again
-			thisX += width;
-		}
-
-		glMatrixMode(GL_MODELVIEW);
-		glLoadIdentity();
-
-		//
-		// IMPORTANT: in OpenGL order of transformation is REVERSE to the order of commands!
-		//
-		// Origin is at the middle of the surface
-		if (_do_render_to_texture)
-			glTranslatef(_backRenderSize.Width / 2.0f, _backRenderSize.Height / 2.0f, 0.0f);
-		else
-			glTranslatef(_srcRect.GetWidth() / 2.0f, _srcRect.GetHeight() / 2.0f, 0.0f);
-
-		// Global batch transform
-		glMultMatrixf(matGlobal.m);
-		// Self sprite transform (first scale, then rotate and then translate, reversed)
-		glTranslatef((float)thisX, (float)thisY, 0.0f);
-		glRotatef(0.f, 0.f, 0.f, 1.f);
-		glScalef(widthToScale, heightToScale, 1.0f);
-
-		glBindTexture(GL_TEXTURE_2D, bmpToDraw->_tiles[ti].texture);
-
-		if ((_smoothScaling) && bmpToDraw->_useResampler && (bmpToDraw->_stretchToHeight > 0) &&
-		        ((bmpToDraw->_stretchToHeight != bmpToDraw->_height) ||
-		         (bmpToDraw->_stretchToWidth != bmpToDraw->_width))) {
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
-		} else if (_do_render_to_texture) {
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
-		} else {
-			_filter->SetFilteringForStandardSprite();
-		}
-		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
-		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
-
-		if (bmpToDraw->_vertex != nullptr) {
-			glTexCoordPointer(2, GL_FLOAT, sizeof(OGLCUSTOMVERTEX), &(bmpToDraw->_vertex[ti * 4].tu));
-			glVertexPointer(2, GL_FLOAT, sizeof(OGLCUSTOMVERTEX), &(bmpToDraw->_vertex[ti * 4].position));
-		} else {
-			glTexCoordPointer(2, GL_FLOAT, sizeof(OGLCUSTOMVERTEX), &defaultVertices[0].tu);
-			glVertexPointer(2, GL_FLOAT, sizeof(OGLCUSTOMVERTEX), &defaultVertices[0].position);
-		}
-
-		glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
-	}
-	glUseProgram(0);
-}
-
-void OGLGraphicsDriver::_render(bool clearDrawListAfterwards) {
-#if AGS_PLATFORM_OS_IOS
-	ios_select_buffer();
-#endif
-
-#if AGS_PLATFORM_OS_ANDROID || AGS_PLATFORM_OS_IOS
-	// TODO:
-	// For some reason, mobile ports initialize actual display size after a short delay.
-	// This is why we update display mode and related parameters (projection, viewport)
-	// at the first render pass.
-	// Ofcourse this is not a good thing, ideally the display size should be made
-	// known before graphic mode is initialized. This would require analysis and rewrite
-	// of the platform-specific part of the code (Java app for Android / XCode for iOS).
-	if (!device_screen_initialized) {
-		UpdateDeviceScreen();
-		device_screen_initialized = 1;
-	}
-#endif
-
-	if (_do_render_to_texture) {
-		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _fbo);
-
-		glClear(GL_COLOR_BUFFER_BIT);
-
-		glViewport(0, 0, _backRenderSize.Width, _backRenderSize.Height);
-		glMatrixMode(GL_PROJECTION);
-		glLoadIdentity();
-		glOrtho(0, _backRenderSize.Width, 0, _backRenderSize.Height, 0, 1);
-		glMatrixMode(GL_MODELVIEW);
-		glLoadIdentity();
-	} else {
-		glDisable(GL_SCISSOR_TEST);
-		glClear(GL_COLOR_BUFFER_BIT);
-		glEnable(GL_SCISSOR_TEST);
-
-		glViewport(_viewportRect.Left, _viewportRect.Top, _viewportRect.GetWidth(), _viewportRect.GetHeight());
-		glMatrixMode(GL_PROJECTION);
-		glLoadIdentity();
-		glOrtho(0, _srcRect.GetWidth(), 0, _srcRect.GetHeight(), 0, 1);
-		glMatrixMode(GL_MODELVIEW);
-		glLoadIdentity();
-	}
-
-	RenderSpriteBatches();
-
-	if (_do_render_to_texture) {
-		// Texture is ready, now create rectangle in the world space and draw texture upon it
-#if AGS_PLATFORM_OS_IOS
-		ios_select_buffer();
-#else
-		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
-#endif
-
-		glViewport(_viewportRect.Left, _viewportRect.Top, _viewportRect.GetWidth(), _viewportRect.GetHeight());
-		glMatrixMode(GL_PROJECTION);
-		glLoadIdentity();
-		glOrtho(0, _srcRect.GetWidth(), 0, _srcRect.GetHeight(), 0, 1);
-		glMatrixMode(GL_MODELVIEW);
-		glLoadIdentity();
-
-		glDisable(GL_BLEND);
-		glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
-
-		// use correct sampling method when stretching buffer to the final rect
-		_filter->SetFilteringForStandardSprite();
-
-		glBindTexture(GL_TEXTURE_2D, _backbuffer);
-
-		glTexCoordPointer(2, GL_FLOAT, 0, _backbuffer_texture_coordinates);
-		glVertexPointer(2, GL_FLOAT, 0, _backbuffer_vertices);
-		glClear(GL_COLOR_BUFFER_BIT);
-		glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
-
-		glEnable(GL_BLEND);
-	}
-
-	glFinish();
-
-#if AGS_PLATFORM_SCUMMVM
-	g_system->updateScreen();
-#elif AGS_PLATFORM_OS_WINDOWS
-	SwapBuffers(_hDC);
-#elif AGS_PLATFORM_OS_LINUX
-	glXSwapBuffers(_xwin.display, _xwin.window);
-#elif AGS_PLATFORM_OS_ANDROID || AGS_PLATFORM_OS_IOS
-	device_swap_buffers();
-#endif
-
-	if (clearDrawListAfterwards) {
-		BackupDrawLists();
-		ClearDrawLists();
-	}
-	ResetFxPool();
-}
-
-void OGLGraphicsDriver::RenderSpriteBatches() {
-	// Render all the sprite batches with necessary transformations
-	Rect main_viewport = _do_render_to_texture ? _srcRect : _viewportRect;
-	int surface_height = _do_render_to_texture ? _srcRect.GetHeight() : device_screen_physical_height;
-	// TODO: see if it's possible to refactor and not enable/disable scissor test
-	// TODO: also maybe sync scissor code logic with D3D renderer
-	if (_do_render_to_texture)
-		glEnable(GL_SCISSOR_TEST);
-
-	for (size_t i = 0; i <= _actSpriteBatch; ++i) {
-		const Rect &viewport = _spriteBatches[i].Viewport;
-		const OGLSpriteBatch &batch = _spriteBatches[i];
-		if (!viewport.IsEmpty()) {
-			Rect scissor = _do_render_to_texture ? viewport : _scaling.ScaleRange(viewport);
-			scissor = ConvertTopDownRect(scissor, surface_height);
-			glScissor(scissor.Left, scissor.Top, scissor.GetWidth(), scissor.GetHeight());
-		} else {
-			glScissor(main_viewport.Left, main_viewport.Top, main_viewport.GetWidth(), main_viewport.GetHeight());
-		}
-		_stageVirtualScreen = GetStageScreen(i);
-		RenderSpriteBatch(batch);
-	}
-
-	_stageVirtualScreen = GetStageScreen(0);
-	glScissor(main_viewport.Left, main_viewport.Top, main_viewport.GetWidth(), main_viewport.GetHeight());
-	if (_do_render_to_texture)
-		glDisable(GL_SCISSOR_TEST);
-}
-
-void OGLGraphicsDriver::RenderSpriteBatch(const OGLSpriteBatch &batch) {
-	OGLDrawListEntry stageEntry; // raw-draw plugin support
-
-	const std::vector<OGLDrawListEntry> &listToDraw = batch.List;
-	for (size_t i = 0; i < listToDraw.size(); i++) {
-		if (listToDraw[i].skip)
-			continue;
-
-		const OGLDrawListEntry *sprite = &listToDraw[i];
-		if (listToDraw[i].bitmap == nullptr) {
-			if (DoNullSpriteCallback(listToDraw[i].x, listToDraw[i].y))
-				stageEntry = OGLDrawListEntry((OGLBitmap *)_stageVirtualScreenDDB);
-			else
-				continue;
-			sprite = &stageEntry;
-		}
-
-		this->_renderSprite(sprite, batch.Matrix);
-	}
-}
-
-void OGLGraphicsDriver::InitSpriteBatch(size_t index, const SpriteBatchDesc &desc) {
-	if (_spriteBatches.size() <= index)
-		_spriteBatches.resize(index + 1);
-	_spriteBatches[index].List.clear();
-
-	Rect orig_viewport = desc.Viewport;
-	Rect node_viewport = desc.Viewport;
-	// Combine both world transform and viewport transform into one matrix for faster perfomance
-	// NOTE: in OpenGL order of transformation is REVERSE to the order of commands!
-	glMatrixMode(GL_MODELVIEW);
-	glLoadIdentity();
-	// Global node transformation (flip and offset)
-	int node_tx = desc.Offset.X, node_ty = desc.Offset.Y;
-	float node_sx = 1.f, node_sy = 1.f;
-	if ((desc.Flip == kFlip_Vertical) || (desc.Flip == kFlip_Both)) {
-		int left = _srcRect.GetWidth() - (orig_viewport.Right + 1);
-		node_viewport.MoveToX(left);
-		node_sx = -1.f;
-	}
-	if ((desc.Flip == kFlip_Horizontal) || (desc.Flip == kFlip_Both)) {
-		int top = _srcRect.GetHeight() - (orig_viewport.Bottom + 1);
-		node_viewport.MoveToY(top);
-		node_sy = -1.f;
-	}
-	_spriteBatches[index].Viewport = Rect::MoveBy(node_viewport, node_tx, node_ty);
-	glTranslatef(node_tx, -(node_ty), 0.0f);
-	glScalef(node_sx, node_sy, 1.f);
-	// NOTE: before node, translate to viewport position; remove this if this
-	// is changed to a separate operation at some point
-	// TODO: find out if this is an optimal way to translate scaled room into Top-Left screen coordinates
-	float scaled_offx = (_srcRect.GetWidth() - desc.Transform.ScaleX * (float)_srcRect.GetWidth()) / 2.f;
-	float scaled_offy = (_srcRect.GetHeight() - desc.Transform.ScaleY * (float)_srcRect.GetHeight()) / 2.f;
-	glTranslatef((float)(orig_viewport.Left - scaled_offx), (float) - (orig_viewport.Top - scaled_offy), 0.0f);
-	// IMPORTANT: while the sprites are usually transformed in the order of Scale-Rotate-Translate,
-	// the camera's transformation is essentially reverse world transformation. And the operations
-	// are inverse: Translate-Rotate-Scale (here they are double inverse because OpenGL).
-	glScalef(desc.Transform.ScaleX, desc.Transform.ScaleY, 1.f); // scale camera
-	glRotatef(Math::RadiansToDegrees(desc.Transform.Rotate), 0.f, 0.f, 1.f); // rotate camera
-	glTranslatef((float)desc.Transform.X, (float) - desc.Transform.Y, 0.0f); // translate camera
-	glGetFloatv(GL_MODELVIEW_MATRIX, _spriteBatches[index].Matrix.m);
-	glLoadIdentity();
-
-	// create stage screen for plugin raw drawing
-	int src_w = orig_viewport.GetWidth() / desc.Transform.ScaleX;
-	int src_h = orig_viewport.GetHeight() / desc.Transform.ScaleY;
-	CreateStageScreen(index, Size(src_w, src_h));
-}
-
-void OGLGraphicsDriver::ResetAllBatches() {
-	for (size_t i = 0; i < _spriteBatches.size(); ++i)
-		_spriteBatches[i].List.clear();
-}
-
-void OGLGraphicsDriver::ClearDrawBackups() {
-	_backupBatchDescs.clear();
-	_backupBatches.clear();
-}
-
-void OGLGraphicsDriver::BackupDrawLists() {
-	ClearDrawBackups();
-	for (size_t i = 0; i <= _actSpriteBatch; ++i) {
-		_backupBatchDescs.push_back(_spriteBatchDesc[i]);
-		_backupBatches.push_back(_spriteBatches[i]);
-	}
-}
-
-void OGLGraphicsDriver::RestoreDrawLists() {
-	if (_backupBatchDescs.size() == 0) {
-		ClearDrawLists();
-		return;
-	}
-	_spriteBatchDesc = _backupBatchDescs;
-	_spriteBatches = _backupBatches;
-	_actSpriteBatch = _backupBatchDescs.size() - 1;
-}
-
-void OGLGraphicsDriver::DrawSprite(int x, int y, IDriverDependantBitmap *bitmap) {
-	_spriteBatches[_actSpriteBatch].List.push_back(OGLDrawListEntry((OGLBitmap *)bitmap, x, y));
-}
-
-void OGLGraphicsDriver::DestroyDDB(IDriverDependantBitmap *bitmap) {
-	// Remove deleted DDB from backups
-	for (OGLSpriteBatches::iterator it = _backupBatches.begin(); it != _backupBatches.end(); ++it) {
-		std::vector<OGLDrawListEntry> &drawlist = it->List;
-		for (size_t i = 0; i < drawlist.size(); i++) {
-			if (drawlist[i].bitmap == bitmap)
-				drawlist[i].skip = true;
-		}
-	}
-	delete bitmap;
-}
-
-
-void OGLGraphicsDriver::UpdateTextureRegion(OGLTextureTile *tile, Bitmap *bitmap, OGLBitmap *target, bool hasAlpha) {
-	int textureHeight = tile->height;
-	int textureWidth = tile->width;
-
-	// TODO: this seem to be tad overcomplicated, these conversions were made
-	// when texture is just created. Check later if this operation here may be removed.
-	AdjustSizeToNearestSupportedByCard(&textureWidth, &textureHeight);
-
-	int tilex = 0, tiley = 0, tileWidth = tile->width, tileHeight = tile->height;
-	if (textureWidth > tile->width) {
-		int texxoff = Math::Min(textureWidth - tile->width - 1, 1);
-		tilex = texxoff;
-		tileWidth += 1 + texxoff;
-	}
-	if (textureHeight > tile->height) {
-		int texyoff = Math::Min(textureHeight - tile->height - 1, 1);
-		tiley = texyoff;
-		tileHeight += 1 + texyoff;
-	}
-
-	const bool usingLinearFiltering = _filter->UseLinearFiltering();
-	char *origPtr = (char *)malloc(sizeof(int) * tileWidth * tileHeight);
-	const int pitch = tileWidth * sizeof(int);
-	char *memPtr = origPtr + pitch * tiley + tilex * sizeof(int);
-
-	TextureTile fixedTile;
-	fixedTile.x = tile->x;
-	fixedTile.y = tile->y;
-	fixedTile.width = Math::Min(tile->width, tileWidth);
-	fixedTile.height = Math::Min(tile->height, tileHeight);
-	if (target->_opaque)
-		BitmapToVideoMemOpaque(bitmap, hasAlpha, &fixedTile, target, memPtr, pitch);
-	else
-		BitmapToVideoMem(bitmap, hasAlpha, &fixedTile, target, memPtr, pitch, usingLinearFiltering);
-
-	// Mimic the behaviour of GL_CLAMP_EDGE for the tile edges
-	// NOTE: on some platforms GL_CLAMP_EDGE does not work with the version of OpenGL we're using.
-	if (tile->width < tileWidth) {
-		if (tilex > 0) {
-			for (int y = 0; y < tileHeight; y++) {
-				unsigned int *edge_left_col = (unsigned int *)(origPtr + y * pitch + (tilex - 1) * sizeof(int));
-				unsigned int *bm_left_col = (unsigned int *)(origPtr + y * pitch + (tilex) * sizeof(int));
-				*edge_left_col = *bm_left_col & 0x00FFFFFF;
-			}
-		}
-		for (int y = 0; y < tileHeight; y++) {
-			unsigned int *edge_right_col = (unsigned int *)(origPtr + y * pitch + (tilex + tile->width) * sizeof(int));
-			unsigned int *bm_right_col = edge_right_col - 1;
-			*edge_right_col = *bm_right_col & 0x00FFFFFF;
-		}
-	}
-	if (tile->height < tileHeight) {
-		if (tiley > 0) {
-			unsigned int *edge_top_row = (unsigned int *)(origPtr + pitch * (tiley - 1));
-			unsigned int *bm_top_row = (unsigned int *)(origPtr + pitch * (tiley));
-			for (int x = 0; x < tileWidth; x++) {
-				edge_top_row[x] = bm_top_row[x] & 0x00FFFFFF;
-			}
-		}
-		unsigned int *edge_bottom_row = (unsigned int *)(origPtr + pitch * (tiley + tile->height));
-		unsigned int *bm_bottom_row = (unsigned int *)(origPtr + pitch * (tiley + tile->height - 1));
-		for (int x = 0; x < tileWidth; x++) {
-			edge_bottom_row[x] = bm_bottom_row[x] & 0x00FFFFFF;
-		}
-	}
-
-	glBindTexture(GL_TEXTURE_2D, tile->texture);
-	glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, tileWidth, tileHeight, GL_RGBA, GL_UNSIGNED_BYTE, origPtr);
-
-	free(origPtr);
-}
-
-void OGLGraphicsDriver::UpdateDDBFromBitmap(IDriverDependantBitmap *bitmapToUpdate, Bitmap *bitmap, bool hasAlpha) {
-	OGLBitmap *target = (OGLBitmap *)bitmapToUpdate;
-	if (target->_width != bitmap->GetWidth() || target->_height != bitmap->GetHeight())
-		error("UpdateDDBFromBitmap: mismatched bitmap size");
-	const int color_depth = bitmap->GetColorDepth();
-	if (color_depth != target->_colDepth)
-		error("UpdateDDBFromBitmap: mismatched colour depths");
-
-	target->_hasAlpha = hasAlpha;
-	if (color_depth == 8)
-		select_palette(palette);
-
-	for (int i = 0; i < target->_numTiles; i++) {
-		UpdateTextureRegion(&target->_tiles[i], bitmap, target, hasAlpha);
-	}
-
-	if (color_depth == 8)
-		unselect_palette();
-}
-
-int OGLGraphicsDriver::GetCompatibleBitmapFormat(int color_depth) {
-	if (color_depth == 8)
-		return 8;
-	if (color_depth > 8 && color_depth <= 16)
-		return 16;
-	return 32;
-}
-
-void OGLGraphicsDriver::AdjustSizeToNearestSupportedByCard(int *width, int *height) {
-	int allocatedWidth = *width, allocatedHeight = *height;
-
-	bool foundWidth = false, foundHeight = false;
-	int tryThis = 2;
-	while ((!foundWidth) || (!foundHeight)) {
-		if ((tryThis >= allocatedWidth) && (!foundWidth)) {
-			allocatedWidth = tryThis;
-			foundWidth = true;
-		}
-
-		if ((tryThis >= allocatedHeight) && (!foundHeight)) {
-			allocatedHeight = tryThis;
-			foundHeight = true;
-		}
-
-		tryThis = tryThis << 1;
-	}
-
-	*width = allocatedWidth;
-	*height = allocatedHeight;
-}
-
-
-
-IDriverDependantBitmap *OGLGraphicsDriver::CreateDDBFromBitmap(Bitmap *bitmap, bool hasAlpha, bool opaque) {
-	int allocatedWidth = bitmap->GetWidth();
-	int allocatedHeight = bitmap->GetHeight();
-	// NOTE: original bitmap object is not modified in this function
-	if (bitmap->GetColorDepth() != GetCompatibleBitmapFormat(bitmap->GetColorDepth()))
-		error("CreateDDBFromBitmap: bitmap colour depth not supported");
-	int colourDepth = bitmap->GetColorDepth();
-
-	OGLBitmap *ddb = new OGLBitmap(bitmap->GetWidth(), bitmap->GetHeight(), colourDepth, opaque);
-
-	AdjustSizeToNearestSupportedByCard(&allocatedWidth, &allocatedHeight);
-	int tilesAcross = 1, tilesDown = 1;
-
-	// Calculate how many textures will be necessary to
-	// store this image
-
-	int MaxTextureWidth = 512;
-	int MaxTextureHeight = 512;
-	glGetIntegerv(GL_MAX_TEXTURE_SIZE, &MaxTextureWidth);
-	MaxTextureHeight = MaxTextureWidth;
-
-	tilesAcross = (allocatedWidth + MaxTextureWidth - 1) / MaxTextureWidth;
-	tilesDown = (allocatedHeight + MaxTextureHeight - 1) / MaxTextureHeight;
-	int tileWidth = bitmap->GetWidth() / tilesAcross;
-	int lastTileExtraWidth = bitmap->GetWidth() % tilesAcross;
-	int tileHeight = bitmap->GetHeight() / tilesDown;
-	int lastTileExtraHeight = bitmap->GetHeight() % tilesDown;
-	int tileAllocatedWidth = tileWidth;
-	int tileAllocatedHeight = tileHeight;
-
-	AdjustSizeToNearestSupportedByCard(&tileAllocatedWidth, &tileAllocatedHeight);
-
-	int numTiles = tilesAcross * tilesDown;
-	OGLTextureTile *tiles = (OGLTextureTile *)malloc(sizeof(OGLTextureTile) * numTiles);
-	memset(tiles, 0, sizeof(OGLTextureTile) * numTiles);
-
-	OGLCUSTOMVERTEX *vertices = nullptr;
-
-	if ((numTiles == 1) &&
-	        (allocatedWidth == bitmap->GetWidth()) &&
-	        (allocatedHeight == bitmap->GetHeight())) {
-		// use default whole-image vertices
-	} else {
-		// The texture is not the same as the bitmap, so create some custom vertices
-		// so that only the relevant portion of the texture is rendered
-		int vertexBufferSize = numTiles * 4 * sizeof(OGLCUSTOMVERTEX);
-
-		ddb->_vertex = vertices = (OGLCUSTOMVERTEX *)malloc(vertexBufferSize);
-	}
-
-	for (int x = 0; x < tilesAcross; x++) {
-		for (int y = 0; y < tilesDown; y++) {
-			OGLTextureTile *thisTile = &tiles[y * tilesAcross + x];
-			int thisAllocatedWidth = tileAllocatedWidth;
-			int thisAllocatedHeight = tileAllocatedHeight;
-			thisTile->x = x * tileWidth;
-			thisTile->y = y * tileHeight;
-			thisTile->width = tileWidth;
-			thisTile->height = tileHeight;
-			if (x == tilesAcross - 1) {
-				thisTile->width += lastTileExtraWidth;
-				thisAllocatedWidth = thisTile->width;
-				AdjustSizeToNearestSupportedByCard(&thisAllocatedWidth, &thisAllocatedHeight);
-			}
-			if (y == tilesDown - 1) {
-				thisTile->height += lastTileExtraHeight;
-				thisAllocatedHeight = thisTile->height;
-				AdjustSizeToNearestSupportedByCard(&thisAllocatedWidth, &thisAllocatedHeight);
-			}
-
-			if (vertices != nullptr) {
-				const int texxoff = (thisAllocatedWidth - thisTile->width) > 1 ? 1 : 0;
-				const int texyoff = (thisAllocatedHeight - thisTile->height) > 1 ? 1 : 0;
-				for (int vidx = 0; vidx < 4; vidx++) {
-					int i = (y * tilesAcross + x) * 4 + vidx;
-					vertices[i] = defaultVertices[vidx];
-					if (vertices[i].tu > 0.0) {
-						vertices[i].tu = (float)(texxoff + thisTile->width) / (float)thisAllocatedWidth;
-					} else {
-						vertices[i].tu = (float)(texxoff) / (float)thisAllocatedWidth;
-					}
-					if (vertices[i].tv > 0.0) {
-						vertices[i].tv = (float)(texyoff + thisTile->height) / (float)thisAllocatedHeight;
-					} else {
-						vertices[i].tv = (float)(texyoff) / (float)thisAllocatedHeight;
-					}
-				}
-			}
-
-			glGenTextures(1, &thisTile->texture);
-			glBindTexture(GL_TEXTURE_2D, thisTile->texture);
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
-			// NOTE: pay attention that the texture format depends on the **display mode**'s format,
-			// rather than source bitmap's color depth!
-			glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, thisAllocatedWidth, thisAllocatedHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
-		}
-	}
-
-	ddb->_numTiles = numTiles;
-	ddb->_tiles = tiles;
-
-	UpdateDDBFromBitmap(ddb, bitmap, hasAlpha);
-
-	return ddb;
-}
-
-void OGLGraphicsDriver::do_fade(bool fadingOut, int speed, int targetColourRed, int targetColourGreen, int targetColourBlue) {
-	// Construct scene in order: game screen, fade fx, post game overlay
-	// NOTE: please keep in mind: redrawing last saved frame here instead of constructing new one
-	// is done because of backwards-compatibility issue: originally AGS faded out using frame
-	// drawn before the script that triggers blocking fade (e.g. instigated by ChangeRoom).
-	// Unfortunately some existing games were changing looks of the screen during same function,
-	// but these were not supposed to get on screen until before fade-in.
-	if (fadingOut)
-		this->_reDrawLastFrame();
-	else if (_drawScreenCallback != nullptr)
-		_drawScreenCallback();
-	Bitmap *blackSquare = BitmapHelper::CreateBitmap(16, 16, 32);
-	blackSquare->Clear(makecol32(targetColourRed, targetColourGreen, targetColourBlue));
-	IDriverDependantBitmap *d3db = this->CreateDDBFromBitmap(blackSquare, false, true);
-	delete blackSquare;
-	BeginSpriteBatch(_srcRect, SpriteTransform());
-	d3db->SetStretch(_srcRect.GetWidth(), _srcRect.GetHeight(), false);
-	this->DrawSprite(0, 0, d3db);
-	if (_drawPostScreenCallback != NULL)
-		_drawPostScreenCallback();
-
-	if (speed <= 0) speed = 16;
-	speed *= 2;  // harmonise speeds with software driver which is faster
-	for (int a = 1; a < 255; a += speed) {
-		d3db->SetTransparency(fadingOut ? a : (255 - a));
-		this->_render(false);
-
-		if (_pollingCallback)
-			_pollingCallback();
-		WaitForNextFrame();
-	}
-
-	if (fadingOut) {
-		d3db->SetTransparency(0);
-		this->_render(false);
-	}
-
-	this->DestroyDDB(d3db);
-	this->ClearDrawLists();
-	ResetFxPool();
-}
-
-void OGLGraphicsDriver::FadeOut(int speed, int targetColourRed, int targetColourGreen, int targetColourBlue) {
-	do_fade(true, speed, targetColourRed, targetColourGreen, targetColourBlue);
-}
-
-void OGLGraphicsDriver::FadeIn(int speed, PALETTE p, int targetColourRed, int targetColourGreen, int targetColourBlue) {
-	do_fade(false, speed, targetColourRed, targetColourGreen, targetColourBlue);
-}
-
-void OGLGraphicsDriver::BoxOutEffect(bool blackingOut, int speed, int delay) {
-	// Construct scene in order: game screen, fade fx, post game overlay
-	if (blackingOut)
-		this->_reDrawLastFrame();
-	else if (_drawScreenCallback != nullptr)
-		_drawScreenCallback();
-	Bitmap *blackSquare = BitmapHelper::CreateBitmap(16, 16, 32);
-	blackSquare->Clear();
-	IDriverDependantBitmap *d3db = this->CreateDDBFromBitmap(blackSquare, false, true);
-	delete blackSquare;
-	BeginSpriteBatch(_srcRect, SpriteTransform());
-	size_t fx_batch = _actSpriteBatch;
-	d3db->SetStretch(_srcRect.GetWidth(), _srcRect.GetHeight(), false);
-	this->DrawSprite(0, 0, d3db);
-	if (!blackingOut) {
-		// when fading in, draw four black boxes, one
-		// across each side of the screen
-		this->DrawSprite(0, 0, d3db);
-		this->DrawSprite(0, 0, d3db);
-		this->DrawSprite(0, 0, d3db);
-	}
-	if (_drawPostScreenCallback != NULL)
-		_drawPostScreenCallback();
-
-	int yspeed = _srcRect.GetHeight() / (_srcRect.GetWidth() / speed);
-	int boxWidth = speed;
-	int boxHeight = yspeed;
-
-	while (boxWidth < _srcRect.GetWidth()) {
-		boxWidth += speed;
-		boxHeight += yspeed;
-		OGLSpriteBatch &batch = _spriteBatches[fx_batch];
-		std::vector<OGLDrawListEntry> &drawList = batch.List;
-		size_t last = drawList.size() - 1;
-		if (blackingOut) {
-			drawList[last].x = _srcRect.GetWidth() / 2 - boxWidth / 2;
-			drawList[last].y = _srcRect.GetHeight() / 2 - boxHeight / 2;
-			d3db->SetStretch(boxWidth, boxHeight, false);
-		} else {
-			drawList[last - 3].x = _srcRect.GetWidth() / 2 - boxWidth / 2 - _srcRect.GetWidth();
-			drawList[last - 2].y = _srcRect.GetHeight() / 2 - boxHeight / 2 - _srcRect.GetHeight();
-			drawList[last - 1].x = _srcRect.GetWidth() / 2 + boxWidth / 2;
-			drawList[last    ].y = _srcRect.GetHeight() / 2 + boxHeight / 2;
-			d3db->SetStretch(_srcRect.GetWidth(), _srcRect.GetHeight(), false);
-		}
-
-		this->_render(false);
-
-		if (_pollingCallback)
-			_pollingCallback();
-		platform->Delay(delay);
-	}
-
-	this->DestroyDDB(d3db);
-	this->ClearDrawLists();
-	ResetFxPool();
-}
-
-void OGLGraphicsDriver::SetScreenFade(int red, int green, int blue) {
-	OGLBitmap *ddb = static_cast<OGLBitmap *>(MakeFx(red, green, blue));
-	ddb->SetStretch(_spriteBatches[_actSpriteBatch].Viewport.GetWidth(),
-	                _spriteBatches[_actSpriteBatch].Viewport.GetHeight(), false);
-	ddb->SetTransparency(0);
-	_spriteBatches[_actSpriteBatch].List.push_back(OGLDrawListEntry(ddb));
-}
-
-void OGLGraphicsDriver::SetScreenTint(int red, int green, int blue) {
-	if (red == 0 && green == 0 && blue == 0) return;
-	OGLBitmap *ddb = static_cast<OGLBitmap *>(MakeFx(red, green, blue));
-	ddb->SetStretch(_spriteBatches[_actSpriteBatch].Viewport.GetWidth(),
-	                _spriteBatches[_actSpriteBatch].Viewport.GetHeight(), false);
-	ddb->SetTransparency(128);
-	_spriteBatches[_actSpriteBatch].List.push_back(OGLDrawListEntry(ddb));
-}
-
-
-OGLGraphicsFactory *OGLGraphicsFactory::_factory = nullptr;
-
-OGLGraphicsFactory::~OGLGraphicsFactory() {
-	_factory = nullptr;
-}
-
-size_t OGLGraphicsFactory::GetFilterCount() const {
-	return 2;
-}
-
-const GfxFilterInfo *OGLGraphicsFactory::GetFilterInfo(size_t index) const {
-	switch (index) {
-	case 0:
-		return &OGLGfxFilter::FilterInfo;
-	case 1:
-		return &AAOGLGfxFilter::FilterInfo;
-	default:
-		return nullptr;
-	}
-}
-
-String OGLGraphicsFactory::GetDefaultFilterID() const {
-	return OGLGfxFilter::FilterInfo.Id;
-}
-
-/* static */ OGLGraphicsFactory *OGLGraphicsFactory::GetFactory() {
-	if (!_factory)
-		_factory = new OGLGraphicsFactory();
-	return _factory;
-}
-
-OGLGraphicsDriver *OGLGraphicsFactory::EnsureDriverCreated() {
-	if (!_driver)
-		_driver = new OGLGraphicsDriver();
-	return _driver;
-}
-
-OGLGfxFilter *OGLGraphicsFactory::CreateFilter(const String &id) {
-	if (OGLGfxFilter::FilterInfo.Id.CompareNoCase(id) == 0)
-		return new OGLGfxFilter();
-	else if (AAOGLGfxFilter::FilterInfo.Id.CompareNoCase(id) == 0)
-		return new AAOGLGfxFilter();
-	return nullptr;
-}
-
-} // namespace OGL
-} // namespace Engine
-} // namespace AGS
-} // namespace AGS3
-
-#endif // only on Windows, Android and iOS
diff --git a/engines/ags/engine/gfx/ali3dogl.h b/engines/ags/engine/gfx/ali3dogl.h
deleted file mode 100644
index e6dd2e35e8..0000000000
--- a/engines/ags/engine/gfx/ali3dogl.h
+++ /dev/null
@@ -1,378 +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.
- *
- */
-
-//=============================================================================
-//
-// OpenGL graphics factory
-//
-//=============================================================================
-
-#ifndef AGS_ENGINE_GFX_ALI3DOGL_H
-#define AGS_ENGINE_GFX_ALI3DOGL_H
-
-#include "ags/lib/std/memory.h"
-#include "ags/shared/gfx/bitmap.h"
-#include "ags/engine/gfx/ddb.h"
-#include "ags/engine/gfx/gfxdriverfactorybase.h"
-#include "ags/engine/gfx/gfxdriverbase.h"
-#include "ags/shared/util/string.h"
-#include "ags/shared/util/version.h"
-
-#include "ags/engine/gfx/ogl_headers.h"
-
-namespace AGS3 {
-namespace AGS {
-namespace Engine {
-
-namespace OGL {
-
-using Shared::Bitmap;
-using Shared::String;
-using Shared::Version;
-
-typedef struct _OGLVECTOR {
-	float x;
-	float y;
-} OGLVECTOR2D;
-
-
-struct OGLCUSTOMVERTEX {
-	OGLVECTOR2D position;
-	float tu;
-	float tv;
-};
-
-struct OGLTextureTile : public TextureTile {
-	unsigned int texture;
-};
-
-class OGLBitmap : public VideoMemDDB {
-public:
-	// Transparency is a bit counter-intuitive
-	// 0=not transparent, 255=invisible, 1..254 barely visible .. mostly visible
-	void SetTransparency(int transparency) override {
-		_transparency = transparency;
-	}
-	void SetFlippedLeftRight(bool isFlipped) override {
-		_flipped = isFlipped;
-	}
-	void SetStretch(int width, int height, bool useResampler = true) override {
-		_stretchToWidth = width;
-		_stretchToHeight = height;
-		_useResampler = useResampler;
-	}
-	void SetLightLevel(int lightLevel) override {
-		_lightLevel = lightLevel;
-	}
-	void SetTint(int red, int green, int blue, int tintSaturation) override {
-		_red = red;
-		_green = green;
-		_blue = blue;
-		_tintSaturation = tintSaturation;
-	}
-
-	bool _flipped;
-	int _stretchToWidth, _stretchToHeight;
-	bool _useResampler;
-	int _red, _green, _blue;
-	int _tintSaturation;
-	int _lightLevel;
-	bool _hasAlpha;
-	int _transparency;
-	OGLCUSTOMVERTEX *_vertex;
-	OGLTextureTile *_tiles;
-	int _numTiles;
-
-	OGLBitmap(int width, int height, int colDepth, bool opaque) {
-		_width = width;
-		_height = height;
-		_colDepth = colDepth;
-		_flipped = false;
-		_hasAlpha = false;
-		_stretchToWidth = 0;
-		_stretchToHeight = 0;
-		_useResampler = false;
-		_red = _green = _blue = 0;
-		_tintSaturation = 0;
-		_lightLevel = 0;
-		_transparency = 0;
-		_opaque = opaque;
-		_vertex = nullptr;
-		_tiles = nullptr;
-		_numTiles = 0;
-	}
-
-	int GetWidthToRender() const {
-		return (_stretchToWidth > 0) ? _stretchToWidth : _width;
-	}
-	int GetHeightToRender() const {
-		return (_stretchToHeight > 0) ? _stretchToHeight : _height;
-	}
-
-	void Dispose();
-
-	~OGLBitmap() override {
-		Dispose();
-	}
-};
-
-typedef SpriteDrawListEntry<OGLBitmap> OGLDrawListEntry;
-typedef struct GLMATRIX {
-	GLfloat m[16];
-} GLMATRIX;
-struct OGLSpriteBatch {
-	// List of sprites to render
-	std::vector<OGLDrawListEntry> List;
-	// Clipping viewport
-	Rect Viewport;
-	// Transformation matrix, built from the batch description
-	GLMATRIX Matrix;
-};
-typedef std::vector<OGLSpriteBatch>    OGLSpriteBatches;
-
-
-class OGLDisplayModeList : public IGfxModeList {
-public:
-	OGLDisplayModeList(const std::vector<DisplayMode> &modes)
-		: _modes(modes) {
-	}
-
-	int GetModeCount() const override {
-		return _modes.size();
-	}
-
-	bool GetMode(int index, DisplayMode &mode) const override {
-		if (index >= 0 && (size_t)index < _modes.size()) {
-			mode = _modes[index];
-			return true;
-		}
-		return false;
-	}
-
-private:
-	std::vector<DisplayMode> _modes;
-};
-
-
-class OGLGfxFilter;
-
-class OGLGraphicsDriver : public VideoMemoryGraphicsDriver {
-public:
-	const char *GetDriverName() override {
-		return "OpenGL";
-	}
-	const char *GetDriverID() override {
-		return "OGL";
-	}
-	void SetTintMethod(TintMethod method) override;
-	bool SetDisplayMode(const DisplayMode &mode, volatile int *loopTimer) override;
-	bool SetNativeSize(const Size &src_size) override;
-	bool SetRenderFrame(const Rect &dst_rect) override;
-	int GetDisplayDepthForNativeDepth(int native_color_depth) const override;
-	IGfxModeList *GetSupportedModeList(int color_depth) override;
-	bool IsModeSupported(const DisplayMode &mode) override;
-	PGfxFilter GetGraphicsFilter() const override;
-	void UnInit();
-	// Clears the screen rectangle. The coordinates are expected in the **native game resolution**.
-	void ClearRectangle(int x1, int y1, int x2, int y2, RGB *colorToUse) override;
-	int  GetCompatibleBitmapFormat(int color_depth) override;
-	IDriverDependantBitmap *CreateDDBFromBitmap(Bitmap *bitmap, bool hasAlpha, bool opaque) override;
-	void UpdateDDBFromBitmap(IDriverDependantBitmap *bitmapToUpdate, Bitmap *bitmap, bool hasAlpha) override;
-	void DestroyDDB(IDriverDependantBitmap *bitmap) override;
-	void DrawSprite(int x, int y, IDriverDependantBitmap *bitmap) override;
-	void RenderToBackBuffer() override;
-	void Render() override;
-	void Render(int xoff, int yoff, GlobalFlipType flip) override;
-	bool GetCopyOfScreenIntoBitmap(Bitmap *destination, bool at_native_res, GraphicResolution *want_fmt) override;
-	void EnableVsyncBeforeRender(bool enabled) override {
-	}
-	void Vsync() override;
-	void RenderSpritesAtScreenResolution(bool enabled, int supersampling) override;
-	void FadeOut(int speed, int targetColourRed, int targetColourGreen, int targetColourBlue) override;
-	void FadeIn(int speed, PALETTE p, int targetColourRed, int targetColourGreen, int targetColourBlue) override;
-	void BoxOutEffect(bool blackingOut, int speed, int delay) override;
-	bool SupportsGammaControl() override;
-	void SetGamma(int newGamma) override;
-	void UseSmoothScaling(bool enabled) override {
-		_smoothScaling = enabled;
-	}
-	bool RequiresFullRedrawEachFrame() override {
-		return true;
-	}
-	bool HasAcceleratedTransform() override {
-		return true;
-	}
-	void SetScreenFade(int red, int green, int blue) override;
-	void SetScreenTint(int red, int green, int blue) override;
-
-	typedef std::shared_ptr<OGLGfxFilter> POGLFilter;
-
-	void SetGraphicsFilter(POGLFilter filter);
-
-	OGLGraphicsDriver();
-	~OGLGraphicsDriver() override;
-
-private:
-	POGLFilter _filter;
-
-#if AGS_PLATFORM_OS_WINDOWS
-	HDC _hDC;
-	HGLRC _hRC;
-	HWND _hWnd;
-	HINSTANCE _hInstance;
-	GLuint _oldPixelFormat;
-	PIXELFORMATDESCRIPTOR _oldPixelFormatDesc;
-#endif
-#if AGS_PLATFORM_OS_LINUX
-	bool _have_window;
-	GLXContext _glxContext;
-#endif
-	bool _firstTimeInit;
-	// Position of backbuffer texture in world space
-	GLfloat _backbuffer_vertices[8];
-	// Relative position of source image on the backbuffer texture,
-	// in local coordinates
-	GLfloat _backbuffer_texture_coordinates[8];
-	OGLCUSTOMVERTEX defaultVertices[4];
-	String previousError;
-	bool _smoothScaling;
-	bool _legacyPixelShader;
-	// Shader program and its variable references;
-	// the variables are rather specific for AGS use (sprite tinting).
-	struct ShaderProgram {
-		GLuint Program;
-		GLuint SamplerVar;      // texture ID
-		GLuint ColorVar;        // primary operation variable
-		GLuint AuxVar;          // auxiliary variable
-
-		ShaderProgram();
-	};
-	ShaderProgram _tintShader;
-	ShaderProgram _lightShader;
-
-	int device_screen_physical_width;
-	int device_screen_physical_height;
-
-	// Viewport and scissor rect, in OpenGL screen coordinates (0,0 is at left-bottom)
-	Rect _viewportRect;
-
-	// These two flags define whether driver can, and should (respectively)
-	// render sprites to texture, and then texture to screen, as opposed to
-	// rendering to screen directly. This is known as supersampling mode
-	bool _can_render_to_texture;
-	bool _do_render_to_texture;
-	// Backbuffer texture multiplier, used to determine a size of texture
-	// relative to the native game size.
-	int _super_sampling;
-	unsigned int _backbuffer;
-	unsigned int _fbo;
-	// Size of the backbuffer drawing area, equals to native size
-	// multiplied by _super_sampling
-	Size _backRenderSize;
-	// Actual size of the backbuffer texture, created by OpenGL
-	Size _backTextureSize;
-
-	OGLSpriteBatches _spriteBatches;
-	// TODO: these draw list backups are needed only for the fade-in/out effects
-	// find out if it's possible to reimplement these effects in main drawing routine.
-	SpriteBatchDescs _backupBatchDescs;
-	OGLSpriteBatches _backupBatches;
-
-	void InitSpriteBatch(size_t index, const SpriteBatchDesc &desc) override;
-	void ResetAllBatches() override;
-
-	// Sets up GL objects not related to particular display mode
-	void FirstTimeInit();
-	// Initializes Gl rendering context
-	bool InitGlScreen(const DisplayMode &mode);
-	bool CreateGlContext(const DisplayMode &mode);
-	void DeleteGlContext();
-	// Sets up general rendering parameters
-	void InitGlParams(const DisplayMode &mode);
-	void SetupDefaultVertices();
-	// Test if rendering to texture is supported
-	void TestRenderToTexture();
-	// Test if supersampling should be allowed with the current setup
-	void TestSupersampling();
-	// Create shader programs for sprite tinting and changing light level
-	void CreateShaders();
-	void CreateTintShader();
-	void CreateLightShader();
-	void CreateShaderProgram(ShaderProgram &prg, const char *name, const char *fragment_shader_src,
-		const char *sampler_var, const char *color_var, const char *aux_var);
-	void DeleteShaderProgram(ShaderProgram &prg);
-	void OutputShaderError(GLuint obj_id, const String &obj_name, bool is_shader);
-	// Configure backbuffer texture, that is used in render-to-texture mode
-	void SetupBackbufferTexture();
-	void DeleteBackbufferTexture();
-#if AGS_PLATFORM_OS_WINDOWS || AGS_PLATFORM_OS_LINUX
-	void CreateDesktopScreen(int width, int height, int depth);
-#elif AGS_PLATFORM_OS_ANDROID || AGS_PLATFORM_OS_IOS
-	void UpdateDeviceScreen();
-#endif
-	// Unset parameters and release resources related to the display mode
-	void ReleaseDisplayMode();
-	void AdjustSizeToNearestSupportedByCard(int *width, int *height);
-	void UpdateTextureRegion(OGLTextureTile *tile, Bitmap *bitmap, OGLBitmap *target, bool hasAlpha);
-	void CreateVirtualScreen();
-	void do_fade(bool fadingOut, int speed, int targetColourRed, int targetColourGreen, int targetColourBlue);
-	void _renderSprite(const OGLDrawListEntry *entry, const GLMATRIX &matGlobal);
-	void SetupViewport();
-	// Converts rectangle in top->down coordinates into OpenGL's native bottom->up coordinates
-	Rect ConvertTopDownRect(const Rect &top_down_rect, int surface_height);
-
-	// Backup all draw lists in the temp storage
-	void BackupDrawLists();
-	// Restore draw lists from the temp storage
-	void RestoreDrawLists();
-	// Deletes draw list backups
-	void ClearDrawBackups();
-	void _render(bool clearDrawListAfterwards);
-	void RenderSpriteBatches();
-	void RenderSpriteBatch(const OGLSpriteBatch &batch);
-	void _reDrawLastFrame();
-};
-
-
-class OGLGraphicsFactory : public GfxDriverFactoryBase<OGLGraphicsDriver, OGLGfxFilter> {
-public:
-	~OGLGraphicsFactory() override;
-
-	size_t               GetFilterCount() const override;
-	const GfxFilterInfo *GetFilterInfo(size_t index) const override;
-	String               GetDefaultFilterID() const override;
-
-	static OGLGraphicsFactory *GetFactory();
-
-private:
-	OGLGraphicsDriver *EnsureDriverCreated() override;
-	OGLGfxFilter *CreateFilter(const String &id) override;
-
-	static OGLGraphicsFactory *_factory;
-};
-
-} // namespace OGL
-} // namespace Engine
-} // namespace AGS
-} // namespace AGS3
-
-#endif
diff --git a/engines/ags/engine/gfx/gfxdriverfactory.cpp b/engines/ags/engine/gfx/gfxdriverfactory.cpp
index 61954f52d2..8ef707e14f 100644
--- a/engines/ags/engine/gfx/gfxdriverfactory.cpp
+++ b/engines/ags/engine/gfx/gfxdriverfactory.cpp
@@ -57,16 +57,9 @@ void GetGfxDriverFactoryNames(StringV &ids) {
 }
 
 IGfxDriverFactory *GetGfxDriverFactory(const String id) {
-#if AGS_HAS_DIRECT3D
-	if (id.CompareNoCase("D3D9") == 0)
-		return D3D::D3DGraphicsFactory::GetFactory();
-#endif
-#if AGS_HAS_OPENGL
-	if (id.CompareNoCase("OGL") == 0)
-		return OGL::OGLGraphicsFactory::GetFactory();
-#endif
 	if (id.CompareNoCase("Software") == 0)
 		return ALSW::ALSWGraphicsFactory::GetFactory();
+
 	set_allegro_error("No graphics factory with such id: %s", id.GetCStr());
 	return nullptr;
 }
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 07c1145c9c..2e50b7b520 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -245,7 +245,6 @@ MODULE_OBJS = \
 	engine/game/savegame.o \
 	engine/game/savegame_components.o \
 	engine/game/viewport.o \
-	engine/gfx/ali3dogl.o \
 	engine/gfx/ali3dsw.o \
 	engine/gfx/blender.o \
 	engine/gfx/color_engine.o \


Commit: ea07ed59e5d4e434035a72e0b57363a90127b241
    https://github.com/scummvm/scummvm/commit/ea07ed59e5d4e434035a72e0b57363a90127b241
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Rename software graphics driver to ScummVM

This will be the basis of the ScummVM implementation

Changed paths:
  A engines/ags/engine/gfx/ali3dscummvm.cpp
  A engines/ags/engine/gfx/ali3dscummvm.h
  R engines/ags/engine/gfx/ali3dsw.cpp
  R engines/ags/engine/gfx/ali3dsw.h
    engines/ags/engine/gfx/gfxdriverfactory.cpp
    engines/ags/engine/gfx/gfxfilter_allegro.cpp
    engines/ags/engine/gfx/gfxfilter_allegro.h
    engines/ags/engine/gfx/gfxfilter_hqx.cpp
    engines/ags/engine/gfx/gfxfilter_hqx.h
    engines/ags/engine/main/config.cpp
    engines/ags/module.mk


diff --git a/engines/ags/engine/gfx/ali3dsw.cpp b/engines/ags/engine/gfx/ali3dscummvm.cpp
similarity index 81%
rename from engines/ags/engine/gfx/ali3dsw.cpp
rename to engines/ags/engine/gfx/ali3dscummvm.cpp
index 3e67d37602..b588693eb4 100644
--- a/engines/ags/engine/gfx/ali3dsw.cpp
+++ b/engines/ags/engine/gfx/ali3dscummvm.cpp
@@ -26,7 +26,7 @@
 //
 //=============================================================================
 
-#include "ags/engine/gfx/ali3dsw.h"
+#include "ags/engine/gfx/ali3dscummvm.h"
 #include "ags/shared/core/platform.h"
 #include "ags/engine/gfx/ali3dexception.h"
 #include "ags/engine/gfx/gfxfilter_allegro.h"
@@ -63,11 +63,11 @@ extern int dxmedia_play_video(const char *, bool, int, int);
 
 namespace AGS {
 namespace Engine {
-namespace ALSW {
+namespace ALGfx {
 
 using namespace Shared;
 
-bool ALSoftwareGfxModeList::GetMode(int index, DisplayMode &mode) const {
+bool ALScummVMGfxModeList::GetMode(int index, DisplayMode &mode) const {
 	if (_gfxModeList && index >= 0 && index < _gfxModeList->num_modes) {
 		mode.Width = _gfxModeList->mode[index].width;
 		mode.Height = _gfxModeList->mode[index].height;
@@ -81,7 +81,7 @@ unsigned long _trans_alpha_blender32(unsigned long x, unsigned long y, unsigned
 RGB faded_out_palette[256];
 
 
-ALSoftwareGraphicsDriver::ALSoftwareGraphicsDriver() {
+ALScummVMGraphicsDriver::ALScummVMGraphicsDriver() {
 	_tint_red = 0;
 	_tint_green = 0;
 	_tint_blue = 0;
@@ -97,10 +97,10 @@ ALSoftwareGraphicsDriver::ALSoftwareGraphicsDriver() {
 	_stageVirtualScreen = nullptr;
 
 	// Initialize default sprite batch, it will be used when no other batch was activated
-	ALSoftwareGraphicsDriver::InitSpriteBatch(0, _spriteBatchDesc[0]);
+	ALScummVMGraphicsDriver::InitSpriteBatch(0, _spriteBatchDesc[0]);
 }
 
-bool ALSoftwareGraphicsDriver::IsModeSupported(const DisplayMode &mode) {
+bool ALScummVMGraphicsDriver::IsModeSupported(const DisplayMode &mode) {
 	if (mode.Width <= 0 || mode.Height <= 0 || mode.ColorDepth <= 0) {
 		set_allegro_error("Invalid resolution parameters: %d x %d x %d", mode.Width, mode.Height, mode.ColorDepth);
 		return false;
@@ -132,28 +132,28 @@ bool ALSoftwareGraphicsDriver::IsModeSupported(const DisplayMode &mode) {
 	return true;
 }
 
-int ALSoftwareGraphicsDriver::GetDisplayDepthForNativeDepth(int native_color_depth) const {
+int ALScummVMGraphicsDriver::GetDisplayDepthForNativeDepth(int native_color_depth) const {
 	// TODO: check for device caps to know which depth is supported?
 	if (native_color_depth > 8)
 		return 32;
 	return native_color_depth;
 }
 
-IGfxModeList *ALSoftwareGraphicsDriver::GetSupportedModeList(int color_depth) {
+IGfxModeList *ALScummVMGraphicsDriver::GetSupportedModeList(int color_depth) {
 	if (_gfxModeList == nullptr) {
 		_gfxModeList = get_gfx_mode_list(GetAllegroGfxDriverID(false));
 	}
 	if (_gfxModeList == nullptr) {
 		return nullptr;
 	}
-	return new ALSoftwareGfxModeList(_gfxModeList);
+	return new ALScummVMGfxModeList(_gfxModeList);
 }
 
-PGfxFilter ALSoftwareGraphicsDriver::GetGraphicsFilter() const {
+PGfxFilter ALScummVMGraphicsDriver::GetGraphicsFilter() const {
 	return _filter;
 }
 
-int ALSoftwareGraphicsDriver::GetAllegroGfxDriverID(bool windowed) {
+int ALScummVMGraphicsDriver::GetAllegroGfxDriverID(bool windowed) {
 #if AGS_PLATFORM_OS_WINDOWS
 	if (windowed)
 		return GFX_DIRECTX_WIN;
@@ -174,7 +174,7 @@ int ALSoftwareGraphicsDriver::GetAllegroGfxDriverID(bool windowed) {
 #endif
 }
 
-void ALSoftwareGraphicsDriver::SetGraphicsFilter(PALSWFilter filter) {
+void ALScummVMGraphicsDriver::SetGraphicsFilter(PALScummVMFilter filter) {
 	_filter = filter;
 	OnSetFilter();
 
@@ -182,11 +182,11 @@ void ALSoftwareGraphicsDriver::SetGraphicsFilter(PALSWFilter filter) {
 	CreateVirtualScreen();
 }
 
-void ALSoftwareGraphicsDriver::SetTintMethod(TintMethod method) {
+void ALScummVMGraphicsDriver::SetTintMethod(TintMethod method) {
 	// TODO: support new D3D-style tint method
 }
 
-bool ALSoftwareGraphicsDriver::SetDisplayMode(const DisplayMode &mode, volatile int *loopTimer) {
+bool ALScummVMGraphicsDriver::SetDisplayMode(const DisplayMode &mode, volatile int *loopTimer) {
 	ReleaseDisplayMode();
 
 	const int driver = GetAllegroGfxDriverID(mode.Windowed);
@@ -226,7 +226,7 @@ bool ALSoftwareGraphicsDriver::SetDisplayMode(const DisplayMode &mode, volatile
 	return true;
 }
 
-void ALSoftwareGraphicsDriver::CreateVirtualScreen() {
+void ALScummVMGraphicsDriver::CreateVirtualScreen() {
 	if (!IsModeSet() || !IsRenderFrameValid() || !IsNativeSizeValid() || !_filter)
 		return;
 	DestroyVirtualScreen();
@@ -246,7 +246,7 @@ void ALSoftwareGraphicsDriver::CreateVirtualScreen() {
 	screen = (BITMAP *)_origVirtualScreen->GetAllegroBitmap();
 }
 
-void ALSoftwareGraphicsDriver::DestroyVirtualScreen() {
+void ALScummVMGraphicsDriver::DestroyVirtualScreen() {
 	if (_filter && _origVirtualScreen) {
 		screen = (BITMAP *)_filter->ShutdownAndReturnRealScreen()->GetAllegroBitmap();
 	}
@@ -255,7 +255,7 @@ void ALSoftwareGraphicsDriver::DestroyVirtualScreen() {
 	_stageVirtualScreen = nullptr;
 }
 
-void ALSoftwareGraphicsDriver::ReleaseDisplayMode() {
+void ALScummVMGraphicsDriver::ReleaseDisplayMode() {
 	OnModeReleased();
 	ClearDrawLists();
 
@@ -273,21 +273,21 @@ void ALSoftwareGraphicsDriver::ReleaseDisplayMode() {
 	_allegroScreenWrapper = nullptr;
 }
 
-bool ALSoftwareGraphicsDriver::SetNativeSize(const Size &src_size) {
+bool ALScummVMGraphicsDriver::SetNativeSize(const Size &src_size) {
 	OnSetNativeSize(src_size);
 	// If we already have a gfx mode and gfx filter set, then use it to update virtual screen immediately
 	CreateVirtualScreen();
 	return !_srcRect.IsEmpty();
 }
 
-bool ALSoftwareGraphicsDriver::SetRenderFrame(const Rect &dst_rect) {
+bool ALScummVMGraphicsDriver::SetRenderFrame(const Rect &dst_rect) {
 	OnSetRenderFrame(dst_rect);
 	// If we already have a gfx mode and gfx filter set, then use it to update virtual screen immediately
 	CreateVirtualScreen();
 	return !_dstRect.IsEmpty();
 }
 
-void ALSoftwareGraphicsDriver::ClearRectangle(int x1, int y1, int x2, int y2, RGB *colorToUse) {
+void ALScummVMGraphicsDriver::ClearRectangle(int x1, int y1, int x2, int y2, RGB *colorToUse) {
 	if (!_filter) return;
 	int color = 0;
 	if (colorToUse != nullptr)
@@ -296,11 +296,11 @@ void ALSoftwareGraphicsDriver::ClearRectangle(int x1, int y1, int x2, int y2, RG
 	_filter->ClearRect(x1, y1, x2, y2, color);
 }
 
-ALSoftwareGraphicsDriver::~ALSoftwareGraphicsDriver() {
-	ALSoftwareGraphicsDriver::UnInit();
+ALScummVMGraphicsDriver::~ALScummVMGraphicsDriver() {
+	ALScummVMGraphicsDriver::UnInit();
 }
 
-void ALSoftwareGraphicsDriver::UnInit() {
+void ALScummVMGraphicsDriver::UnInit() {
 	OnUnInit();
 	ReleaseDisplayMode();
 
@@ -310,7 +310,7 @@ void ALSoftwareGraphicsDriver::UnInit() {
 	}
 }
 
-bool ALSoftwareGraphicsDriver::SupportsGammaControl() {
+bool ALScummVMGraphicsDriver::SupportsGammaControl() {
 #if AGS_DDRAW_GAMMA_CONTROL
 
 	if (dxGammaControl != NULL) {
@@ -322,7 +322,7 @@ bool ALSoftwareGraphicsDriver::SupportsGammaControl() {
 	return 0;
 }
 
-void ALSoftwareGraphicsDriver::SetGamma(int newGamma) {
+void ALScummVMGraphicsDriver::SetGamma(int newGamma) {
 #if AGS_DDRAW_GAMMA_CONTROL
 	for (int i = 0; i < 256; i++) {
 		int newValue = ((int)defaultGammaRamp.red[i] * newGamma) / 100;
@@ -337,26 +337,26 @@ void ALSoftwareGraphicsDriver::SetGamma(int newGamma) {
 #endif
 }
 
-int ALSoftwareGraphicsDriver::GetCompatibleBitmapFormat(int color_depth) {
+int ALScummVMGraphicsDriver::GetCompatibleBitmapFormat(int color_depth) {
 	return color_depth;
 }
 
-IDriverDependantBitmap *ALSoftwareGraphicsDriver::CreateDDBFromBitmap(Bitmap *bitmap, bool hasAlpha, bool opaque) {
-	ALSoftwareBitmap *newBitmap = new ALSoftwareBitmap(bitmap, opaque, hasAlpha);
+IDriverDependantBitmap *ALScummVMGraphicsDriver::CreateDDBFromBitmap(Bitmap *bitmap, bool hasAlpha, bool opaque) {
+	ALScummVMBitmap *newBitmap = new ALScummVMBitmap(bitmap, opaque, hasAlpha);
 	return newBitmap;
 }
 
-void ALSoftwareGraphicsDriver::UpdateDDBFromBitmap(IDriverDependantBitmap *bitmapToUpdate, Bitmap *bitmap, bool hasAlpha) {
-	ALSoftwareBitmap *alSwBmp = (ALSoftwareBitmap *)bitmapToUpdate;
-	alSwBmp->_bmp = bitmap;
-	alSwBmp->_hasAlpha = hasAlpha;
+void ALScummVMGraphicsDriver::UpdateDDBFromBitmap(IDriverDependantBitmap *bitmapToUpdate, Bitmap *bitmap, bool hasAlpha) {
+	ALScummVMBitmap *ALScummVMBmp = (ALScummVMBitmap *)bitmapToUpdate;
+	ALScummVMBmp->_bmp = bitmap;
+	ALScummVMBmp->_hasAlpha = hasAlpha;
 }
 
-void ALSoftwareGraphicsDriver::DestroyDDB(IDriverDependantBitmap *bitmap) {
+void ALScummVMGraphicsDriver::DestroyDDB(IDriverDependantBitmap *bitmap) {
 	delete bitmap;
 }
 
-void ALSoftwareGraphicsDriver::InitSpriteBatch(size_t index, const SpriteBatchDesc &desc) {
+void ALScummVMGraphicsDriver::InitSpriteBatch(size_t index, const SpriteBatchDesc &desc) {
 	if (_spriteBatches.size() <= index)
 		_spriteBatches.resize(index + 1);
 	ALSpriteBatch &batch = _spriteBatches[index];
@@ -393,29 +393,29 @@ void ALSoftwareGraphicsDriver::InitSpriteBatch(size_t index, const SpriteBatchDe
 	}
 }
 
-void ALSoftwareGraphicsDriver::ResetAllBatches() {
+void ALScummVMGraphicsDriver::ResetAllBatches() {
 	for (ALSpriteBatches::iterator it = _spriteBatches.begin(); it != _spriteBatches.end(); ++it)
 		it->List.clear();
 }
 
-void ALSoftwareGraphicsDriver::DrawSprite(int x, int y, IDriverDependantBitmap *bitmap) {
-	_spriteBatches[_actSpriteBatch].List.push_back(ALDrawListEntry((ALSoftwareBitmap *)bitmap, x, y));
+void ALScummVMGraphicsDriver::DrawSprite(int x, int y, IDriverDependantBitmap *bitmap) {
+	_spriteBatches[_actSpriteBatch].List.push_back(ALDrawListEntry((ALScummVMBitmap *)bitmap, x, y));
 }
 
-void ALSoftwareGraphicsDriver::SetScreenFade(int red, int green, int blue) {
+void ALScummVMGraphicsDriver::SetScreenFade(int red, int green, int blue) {
 	// TODO: was not necessary atm
 }
 
-void ALSoftwareGraphicsDriver::SetScreenTint(int red, int green, int blue) {
+void ALScummVMGraphicsDriver::SetScreenTint(int red, int green, int blue) {
 	_tint_red = red;
 	_tint_green = green;
 	_tint_blue = blue;
 	if (((_tint_red > 0) || (_tint_green > 0) || (_tint_blue > 0)) && (_mode.ColorDepth > 8)) {
-		_spriteBatches[_actSpriteBatch].List.push_back(ALDrawListEntry((ALSoftwareBitmap *)0x1, 0, 0));
+		_spriteBatches[_actSpriteBatch].List.push_back(ALDrawListEntry((ALScummVMBitmap *)0x1, 0, 0));
 	}
 }
 
-void ALSoftwareGraphicsDriver::RenderToBackBuffer() {
+void ALScummVMGraphicsDriver::RenderToBackBuffer() {
 	// Render all the sprite batches with necessary transformations
 	//
 	// NOTE: that's not immediately clear whether it would be faster to first draw upon a camera-sized
@@ -452,7 +452,7 @@ void ALSoftwareGraphicsDriver::RenderToBackBuffer() {
 	ClearDrawLists();
 }
 
-void ALSoftwareGraphicsDriver::RenderSpriteBatch(const ALSpriteBatch &batch, Shared::Bitmap *surface, int surf_offx, int surf_offy) {
+void ALScummVMGraphicsDriver::RenderSpriteBatch(const ALSpriteBatch &batch, Shared::Bitmap *surface, int surf_offx, int surf_offy) {
 	const std::vector<ALDrawListEntry> &drawlist = batch.List;
 	for (size_t i = 0; i < drawlist.size(); i++) {
 		if (drawlist[i].bitmap == nullptr) {
@@ -462,14 +462,14 @@ void ALSoftwareGraphicsDriver::RenderSpriteBatch(const ALSpriteBatch &batch, Sha
 				error("Unhandled attempt to draw null sprite");
 
 			continue;
-		} else if (drawlist[i].bitmap == (ALSoftwareBitmap *)0x1) {
+		} else if (drawlist[i].bitmap == (ALScummVMBitmap *)0x1) {
 			// draw screen tint fx
 			set_trans_blender(_tint_red, _tint_green, _tint_blue, 0);
 			surface->LitBlendBlt(surface, 0, 0, 128);
 			continue;
 		}
 
-		ALSoftwareBitmap *bitmap = drawlist[i].bitmap;
+		ALScummVMBitmap *bitmap = drawlist[i].bitmap;
 		int drawAtX = drawlist[i].x + surf_offx;
 		int drawAtY = drawlist[i].y + surf_offy;
 
@@ -511,7 +511,7 @@ void ALSoftwareGraphicsDriver::RenderSpriteBatch(const ALSpriteBatch &batch, Sha
 		Blit(_spareTintingScreen, surface, 0, 0, 0, 0, _spareTintingScreen->GetWidth(), _spareTintingScreen->GetHeight());*/
 }
 
-void ALSoftwareGraphicsDriver::Render(int xoff, int yoff, GlobalFlipType flip) {
+void ALScummVMGraphicsDriver::Render(int xoff, int yoff, GlobalFlipType flip) {
 	RenderToBackBuffer();
 
 	if (_autoVsync)
@@ -523,19 +523,19 @@ void ALSoftwareGraphicsDriver::Render(int xoff, int yoff, GlobalFlipType flip) {
 		_filter->RenderScreenFlipped(virtualScreen, xoff, yoff, flip);
 }
 
-void ALSoftwareGraphicsDriver::Render() {
+void ALScummVMGraphicsDriver::Render() {
 	Render(0, 0, kFlip_None);
 }
 
-void ALSoftwareGraphicsDriver::Vsync() {
+void ALScummVMGraphicsDriver::Vsync() {
 	vsync();
 }
 
-Bitmap *ALSoftwareGraphicsDriver::GetMemoryBackBuffer() {
+Bitmap *ALScummVMGraphicsDriver::GetMemoryBackBuffer() {
 	return virtualScreen;
 }
 
-void ALSoftwareGraphicsDriver::SetMemoryBackBuffer(Bitmap *backBuffer) {
+void ALScummVMGraphicsDriver::SetMemoryBackBuffer(Bitmap *backBuffer) {
 	if (backBuffer) {
 		virtualScreen = backBuffer;
 	} else {
@@ -550,11 +550,11 @@ void ALSoftwareGraphicsDriver::SetMemoryBackBuffer(Bitmap *backBuffer) {
 	}
 }
 
-Bitmap *ALSoftwareGraphicsDriver::GetStageBackBuffer() {
+Bitmap *ALScummVMGraphicsDriver::GetStageBackBuffer() {
 	return _stageVirtualScreen;
 }
 
-bool ALSoftwareGraphicsDriver::GetCopyOfScreenIntoBitmap(Bitmap *destination, bool at_native_res, GraphicResolution *want_fmt) {
+bool ALScummVMGraphicsDriver::GetCopyOfScreenIntoBitmap(Bitmap *destination, bool at_native_res, GraphicResolution *want_fmt) {
 	(void)at_native_res; // software driver always renders at native resolution at the moment
 	// software filter is taught to copy to any size
 	if (destination->GetColorDepth() != _mode.ColorDepth) {
@@ -573,7 +573,7 @@ bool ALSoftwareGraphicsDriver::GetCopyOfScreenIntoBitmap(Bitmap *destination, bo
 
 	Author: Matthew Leverton
 **/
-void ALSoftwareGraphicsDriver::highcolor_fade_in(Bitmap *vs, void(*draw_callback)(), int offx, int offy, int speed, int targetColourRed, int targetColourGreen, int targetColourBlue) {
+void ALScummVMGraphicsDriver::highcolor_fade_in(Bitmap *vs, void(*draw_callback)(), int offx, int offy, int speed, int targetColourRed, int targetColourGreen, int targetColourBlue) {
 	Bitmap *bmp_orig = vs;
 	const int col_depth = bmp_orig->GetColorDepth();
 	const int clearColor = makecol_depth(col_depth, targetColourRed, targetColourGreen, targetColourBlue);
@@ -605,7 +605,7 @@ void ALSoftwareGraphicsDriver::highcolor_fade_in(Bitmap *vs, void(*draw_callback
 	_filter->RenderScreen(vs, offx, offy);
 }
 
-void ALSoftwareGraphicsDriver::highcolor_fade_out(Bitmap *vs, void(*draw_callback)(), int offx, int offy, int speed, int targetColourRed, int targetColourGreen, int targetColourBlue) {
+void ALScummVMGraphicsDriver::highcolor_fade_out(Bitmap *vs, void(*draw_callback)(), int offx, int offy, int speed, int targetColourRed, int targetColourGreen, int targetColourBlue) {
 	Bitmap *bmp_orig = vs;
 	const int col_depth = vs->GetColorDepth();
 	const int clearColor = makecol_depth(col_depth, targetColourRed, targetColourGreen, targetColourBlue);
@@ -650,7 +650,7 @@ void initialize_fade_256(int r, int g, int b) {
 	}
 }
 
-void ALSoftwareGraphicsDriver::__fade_from_range(PALETTE source, PALETTE dest, int speed, int from, int to) {
+void ALScummVMGraphicsDriver::__fade_from_range(PALETTE source, PALETTE dest, int speed, int from, int to) {
 	PALETTE temp;
 	int c;
 
@@ -667,7 +667,7 @@ void ALSoftwareGraphicsDriver::__fade_from_range(PALETTE source, PALETTE dest, i
 	set_palette_range(dest, from, to, TRUE);
 }
 
-void ALSoftwareGraphicsDriver::__fade_out_range(int speed, int from, int to, int targetColourRed, int targetColourGreen, int targetColourBlue) {
+void ALScummVMGraphicsDriver::__fade_out_range(int speed, int from, int to, int targetColourRed, int targetColourGreen, int targetColourBlue) {
 	PALETTE temp;
 
 	initialize_fade_256(targetColourRed, targetColourGreen, targetColourBlue);
@@ -675,7 +675,7 @@ void ALSoftwareGraphicsDriver::__fade_out_range(int speed, int from, int to, int
 	__fade_from_range(temp, faded_out_palette, speed, from, to);
 }
 
-void ALSoftwareGraphicsDriver::FadeOut(int speed, int targetColourRed, int targetColourGreen, int targetColourBlue) {
+void ALScummVMGraphicsDriver::FadeOut(int speed, int targetColourRed, int targetColourGreen, int targetColourBlue) {
 	if (_mode.ColorDepth > 8) {
 		highcolor_fade_out(virtualScreen, _drawPostScreenCallback, 0, 0, speed * 4, targetColourRed, targetColourGreen, targetColourBlue);
 	} else {
@@ -683,7 +683,7 @@ void ALSoftwareGraphicsDriver::FadeOut(int speed, int targetColourRed, int targe
 	}
 }
 
-void ALSoftwareGraphicsDriver::FadeIn(int speed, PALETTE p, int targetColourRed, int targetColourGreen, int targetColourBlue) {
+void ALScummVMGraphicsDriver::FadeIn(int speed, PALETTE p, int targetColourRed, int targetColourGreen, int targetColourBlue) {
 	if (_drawScreenCallback) {
 		_drawScreenCallback();
 		RenderToBackBuffer();
@@ -696,7 +696,7 @@ void ALSoftwareGraphicsDriver::FadeIn(int speed, PALETTE p, int targetColourRed,
 	}
 }
 
-void ALSoftwareGraphicsDriver::BoxOutEffect(bool blackingOut, int speed, int delay) {
+void ALScummVMGraphicsDriver::BoxOutEffect(bool blackingOut, int speed, int delay) {
 	if (blackingOut) {
 		int yspeed = _srcRect.GetHeight() / (_srcRect.GetWidth() / speed);
 		int boxwid = speed, boxhit = yspeed;
@@ -734,7 +734,7 @@ void ALSoftwareGraphicsDriver::BoxOutEffect(bool blackingOut, int speed, int del
 
 #ifndef AGS_NO_VIDEO_PLAYER
 
-bool ALSoftwareGraphicsDriver::PlayVideo(const char *filename, bool useAVISound, VideoSkipType skipType, bool stretchToFullScreen) {
+bool ALScummVMGraphicsDriver::PlayVideo(const char *filename, bool useAVISound, VideoSkipType skipType, bool stretchToFullScreen) {
 #if AGS_PLATFORM_OS_WINDOWS
 	int result = dxmedia_play_video(filename, useAVISound, skipType, stretchToFullScreen ? 1 : 0);
 	return (result == 0);
@@ -766,17 +766,17 @@ unsigned long _trans_alpha_blender32(unsigned long x, unsigned long y, unsigned
 }
 
 
-ALSWGraphicsFactory *ALSWGraphicsFactory::_factory = nullptr;
+ALScummVMGraphicsFactory *ALScummVMGraphicsFactory::_factory = nullptr;
 
-ALSWGraphicsFactory::~ALSWGraphicsFactory() {
+ALScummVMGraphicsFactory::~ALScummVMGraphicsFactory() {
 	_factory = nullptr;
 }
 
-size_t ALSWGraphicsFactory::GetFilterCount() const {
+size_t ALScummVMGraphicsFactory::GetFilterCount() const {
 	return 2;
 }
 
-const GfxFilterInfo *ALSWGraphicsFactory::GetFilterInfo(size_t index) const {
+const GfxFilterInfo *ALScummVMGraphicsFactory::GetFilterInfo(size_t index) const {
 	switch (index) {
 	case 0:
 		return &AllegroGfxFilter::FilterInfo;
@@ -787,23 +787,23 @@ const GfxFilterInfo *ALSWGraphicsFactory::GetFilterInfo(size_t index) const {
 	}
 }
 
-String ALSWGraphicsFactory::GetDefaultFilterID() const {
+String ALScummVMGraphicsFactory::GetDefaultFilterID() const {
 	return AllegroGfxFilter::FilterInfo.Id;
 }
 
-/* static */ ALSWGraphicsFactory *ALSWGraphicsFactory::GetFactory() {
+/* static */ ALScummVMGraphicsFactory *ALScummVMGraphicsFactory::GetFactory() {
 	if (!_factory)
-		_factory = new ALSWGraphicsFactory();
+		_factory = new ALScummVMGraphicsFactory();
 	return _factory;
 }
 
-ALSoftwareGraphicsDriver *ALSWGraphicsFactory::EnsureDriverCreated() {
+ALScummVMGraphicsDriver *ALScummVMGraphicsFactory::EnsureDriverCreated() {
 	if (!_driver)
-		_driver = new ALSoftwareGraphicsDriver();
+		_driver = new ALScummVMGraphicsDriver();
 	return _driver;
 }
 
-AllegroGfxFilter *ALSWGraphicsFactory::CreateFilter(const String &id) {
+AllegroGfxFilter *ALScummVMGraphicsFactory::CreateFilter(const String &id) {
 	if (AllegroGfxFilter::FilterInfo.Id.CompareNoCase(id) == 0)
 		return new AllegroGfxFilter();
 	else if (HqxGfxFilter::FilterInfo.Id.CompareNoCase(id) == 0)
@@ -811,7 +811,7 @@ AllegroGfxFilter *ALSWGraphicsFactory::CreateFilter(const String &id) {
 	return nullptr;
 }
 
-} // namespace ALSW
+} // namespace ALScummVM
 } // namespace Engine
 } // namespace AGS
 } // namespace AGS3
diff --git a/engines/ags/engine/gfx/ali3dsw.h b/engines/ags/engine/gfx/ali3dscummvm.h
similarity index 90%
rename from engines/ags/engine/gfx/ali3dsw.h
rename to engines/ags/engine/gfx/ali3dscummvm.h
index c168667c50..4628a4cf9a 100644
--- a/engines/ags/engine/gfx/ali3dsw.h
+++ b/engines/ags/engine/gfx/ali3dscummvm.h
@@ -49,12 +49,12 @@
 namespace AGS3 {
 namespace AGS {
 namespace Engine {
-namespace ALSW {
+namespace ALGfx {
 
 class AllegroGfxFilter;
 using AGS::Shared::Bitmap;
 
-class ALSoftwareBitmap : public IDriverDependantBitmap {
+class ALScummVMBitmap : public IDriverDependantBitmap {
 public:
 	// NOTE by CJ:
 	// Transparency is a bit counter-intuitive
@@ -92,7 +92,7 @@ public:
 	bool _hasAlpha;
 	int _transparency;
 
-	ALSoftwareBitmap(Bitmap *bmp, bool opaque, bool hasAlpha) {
+	ALScummVMBitmap(Bitmap *bmp, bool opaque, bool hasAlpha) {
 		_bmp = bmp;
 		_width = bmp->GetWidth();
 		_height = bmp->GetHeight();
@@ -116,15 +116,15 @@ public:
 		// do we want to free the bitmap?
 	}
 
-	~ALSoftwareBitmap() override {
+	~ALScummVMBitmap() override {
 		Dispose();
 	}
 };
 
 
-class ALSoftwareGfxModeList : public IGfxModeList {
+class ALScummVMGfxModeList : public IGfxModeList {
 public:
-	ALSoftwareGfxModeList(const GFX_MODE_LIST *alsw_gfx_mode_list)
+	ALScummVMGfxModeList(const GFX_MODE_LIST *alsw_gfx_mode_list)
 		: _gfxModeList(alsw_gfx_mode_list) {
 	}
 
@@ -139,7 +139,7 @@ private:
 };
 
 
-typedef SpriteDrawListEntry<ALSoftwareBitmap> ALDrawListEntry;
+typedef SpriteDrawListEntry<ALScummVMBitmap> ALDrawListEntry;
 // Software renderer's sprite batch
 struct ALSpriteBatch {
 	// List of sprites to render
@@ -154,9 +154,9 @@ struct ALSpriteBatch {
 typedef std::vector<ALSpriteBatch> ALSpriteBatches;
 
 
-class ALSoftwareGraphicsDriver : public GraphicsDriverBase {
+class ALScummVMGraphicsDriver : public GraphicsDriverBase {
 public:
-	ALSoftwareGraphicsDriver();
+	ALScummVMGraphicsDriver();
 
 	const char *GetDriverName() override {
 		return "Software renderer";
@@ -216,14 +216,14 @@ public:
 	Bitmap *GetMemoryBackBuffer() override;
 	void SetMemoryBackBuffer(Bitmap *backBuffer) override;
 	Bitmap *GetStageBackBuffer() override;
-	~ALSoftwareGraphicsDriver() override;
+	~ALScummVMGraphicsDriver() override;
 
-	typedef std::shared_ptr<AllegroGfxFilter> PALSWFilter;
+	typedef std::shared_ptr<AllegroGfxFilter> PALScummVMFilter;
 
-	void SetGraphicsFilter(PALSWFilter filter);
+	void SetGraphicsFilter(PALScummVMFilter filter);
 
 private:
-	PALSWFilter _filter;
+	PALScummVMFilter _filter;
 
 	bool _autoVsync;
 	Bitmap *_allegroScreenWrapper;
@@ -273,24 +273,24 @@ private:
 };
 
 
-class ALSWGraphicsFactory : public GfxDriverFactoryBase<ALSoftwareGraphicsDriver, AllegroGfxFilter> {
+class ALScummVMGraphicsFactory : public GfxDriverFactoryBase<ALScummVMGraphicsDriver, AllegroGfxFilter> {
 public:
-	~ALSWGraphicsFactory() override;
+	~ALScummVMGraphicsFactory() override;
 
 	size_t               GetFilterCount() const override;
 	const GfxFilterInfo *GetFilterInfo(size_t index) const override;
 	String               GetDefaultFilterID() const override;
 
-	static  ALSWGraphicsFactory *GetFactory();
+	static  ALScummVMGraphicsFactory *GetFactory();
 
 private:
-	ALSoftwareGraphicsDriver *EnsureDriverCreated() override;
+	ALScummVMGraphicsDriver *EnsureDriverCreated() override;
 	AllegroGfxFilter *CreateFilter(const String &id) override;
 
-	static ALSWGraphicsFactory *_factory;
+	static ALScummVMGraphicsFactory *_factory;
 };
 
-} // namespace ALSW
+} // namespace ALGfx
 } // namespace Engine
 } // namespace AGS
 } // namespace AGS3
diff --git a/engines/ags/engine/gfx/gfxdriverfactory.cpp b/engines/ags/engine/gfx/gfxdriverfactory.cpp
index 8ef707e14f..e08ab1ddfe 100644
--- a/engines/ags/engine/gfx/gfxdriverfactory.cpp
+++ b/engines/ags/engine/gfx/gfxdriverfactory.cpp
@@ -27,19 +27,8 @@
 #define AGS_HAS_DIRECT3D (AGS_PLATFORM_OS_WINDOWS)
 #define AGS_HAS_OPENGL (AGS_PLATFORM_OS_WINDOWS || AGS_PLATFORM_OS_ANDROID || AGS_PLATFORM_OS_IOS || AGS_PLATFORM_OS_LINUX)
 
-#include "ags/engine/gfx/ali3dsw.h"
+#include "ags/engine/gfx/ali3dscummvm.h"
 #include "ags/engine/gfx/gfxfilter_allegro.h"
-
-#if AGS_HAS_OPENGL
-#include "ags/engine/gfx/ali3dogl.h"
-#include "ags/engine/gfx/gfxfilter_ogl.h"
-#endif
-
-#if AGS_HAS_DIRECT3D
-#include "ags/engine/platform/windows/gfx/ali3dd3d.h"
-#include "ags/engine/gfx/gfxfilter_d3d.h"
-#endif
-
 #include "ags/engine/main/main_allegro.h"
 
 namespace AGS3 {
@@ -47,18 +36,12 @@ namespace AGS {
 namespace Engine {
 
 void GetGfxDriverFactoryNames(StringV &ids) {
-#if AGS_HAS_DIRECT3D
-	ids.push_back("D3D9");
-#endif
-#if AGS_HAS_OPENGL
-	ids.push_back("OGL");
-#endif
-	ids.push_back("Software");
+	ids.push_back("ScummVM");
 }
 
 IGfxDriverFactory *GetGfxDriverFactory(const String id) {
-	if (id.CompareNoCase("Software") == 0)
-		return ALSW::ALSWGraphicsFactory::GetFactory();
+	if (id.CompareNoCase("ScummVM") == 0)
+		return ALGfx::ALScummVMGraphicsFactory::GetFactory();
 
 	set_allegro_error("No graphics factory with such id: %s", id.GetCStr());
 	return nullptr;
diff --git a/engines/ags/engine/gfx/gfxfilter_allegro.cpp b/engines/ags/engine/gfx/gfxfilter_allegro.cpp
index 94640f0dae..aa24f8c3b4 100644
--- a/engines/ags/engine/gfx/gfxfilter_allegro.cpp
+++ b/engines/ags/engine/gfx/gfxfilter_allegro.cpp
@@ -25,7 +25,7 @@
 namespace AGS3 {
 namespace AGS {
 namespace Engine {
-namespace ALSW {
+namespace ALGfx {
 
 using namespace Shared;
 
diff --git a/engines/ags/engine/gfx/gfxfilter_allegro.h b/engines/ags/engine/gfx/gfxfilter_allegro.h
index d1aba15421..0a1f953c66 100644
--- a/engines/ags/engine/gfx/gfxfilter_allegro.h
+++ b/engines/ags/engine/gfx/gfxfilter_allegro.h
@@ -36,7 +36,7 @@
 namespace AGS3 {
 namespace AGS {
 namespace Engine {
-namespace ALSW {
+namespace ALGfx {
 
 using Shared::Bitmap;
 
diff --git a/engines/ags/engine/gfx/gfxfilter_hqx.cpp b/engines/ags/engine/gfx/gfxfilter_hqx.cpp
index cd46a97c50..54ee188ee8 100644
--- a/engines/ags/engine/gfx/gfxfilter_hqx.cpp
+++ b/engines/ags/engine/gfx/gfxfilter_hqx.cpp
@@ -27,7 +27,7 @@
 namespace AGS3 {
 namespace AGS {
 namespace Engine {
-namespace ALSW {
+namespace ALGfx {
 
 using namespace Shared;
 
diff --git a/engines/ags/engine/gfx/gfxfilter_hqx.h b/engines/ags/engine/gfx/gfxfilter_hqx.h
index 06a1e45bfd..2a1bfe8455 100644
--- a/engines/ags/engine/gfx/gfxfilter_hqx.h
+++ b/engines/ags/engine/gfx/gfxfilter_hqx.h
@@ -34,7 +34,7 @@
 namespace AGS3 {
 namespace AGS {
 namespace Engine {
-namespace ALSW {
+namespace ALGfx {
 
 class HqxGfxFilter : public AllegroGfxFilter {
 public:
diff --git a/engines/ags/engine/main/config.cpp b/engines/ags/engine/main/config.cpp
index 97d54ac784..52a6dee9c4 100644
--- a/engines/ags/engine/main/config.cpp
+++ b/engines/ags/engine/main/config.cpp
@@ -299,7 +299,7 @@ void config_defaults() {
 #if AGS_PLATFORM_OS_WINDOWS
 	usetup.Screen.DriverID = "D3D9";
 #else
-	usetup.Screen.DriverID = "OGL";
+	usetup.Screen.DriverID = "ScummVM";
 #endif
 #if AGS_PLATFORM_OS_WINDOWS
 	usetup.digicard = DIGI_DIRECTAMX(0);
@@ -401,17 +401,8 @@ void override_config_ext(ConfigTree &cfg) {
 	INIwriteint(cfg, "graphics", "windowed", 0);
 #endif
 
-	// psp_gfx_renderer - rendering mode
-	//    * 0 - software renderer
-	//    * 1 - hardware, render to screen
-	//    * 2 - hardware, render to texture
-	if (psp_gfx_renderer == 0) {
-		INIwritestring(cfg, "graphics", "driver", "Software");
-		INIwriteint(cfg, "graphics", "render_at_screenres", 1);
-	} else {
-		INIwritestring(cfg, "graphics", "driver", "OGL");
-		INIwriteint(cfg, "graphics", "render_at_screenres", psp_gfx_renderer == 1);
-	}
+	INIwritestring(cfg, "graphics", "driver", "ScummVM");
+	INIwriteint(cfg, "graphics", "render_at_screenres", 1);
 
 	// psp_gfx_scaling - scaling style:
 	//    * 0 - no scaling
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 2e50b7b520..f6f087df0a 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -245,7 +245,7 @@ MODULE_OBJS = \
 	engine/game/savegame.o \
 	engine/game/savegame_components.o \
 	engine/game/viewport.o \
-	engine/gfx/ali3dsw.o \
+	engine/gfx/ali3dscummvm.o \
 	engine/gfx/blender.o \
 	engine/gfx/color_engine.o \
 	engine/gfx/gfx_util.o \


Commit: 8924e8819a149a8151c4d9c6f3c35609001d9346
    https://github.com/scummvm/scummvm/commit/8924e8819a149a8151c4d9c6f3c35609001d9346
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Adding ScummVM graphics init code

Changed paths:
    engines/ags/ags.cpp
    engines/ags/ags.h
    engines/ags/engine/gfx/ali3dscummvm.cpp
    engines/ags/lib/allegro/gfx.cpp


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index a872f7d09b..f9481277af 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -27,6 +27,7 @@
 #include "common/debug-channels.h"
 #include "common/events.h"
 #include "common/file.h"
+#include "engines/util.h"
 
 #include "ags/shared/core/platform.h"
 #define AGS_PLATFORM_DEFINES_PSP_VARS (AGS_PLATFORM_OS_IOS || AGS_PLATFORM_OS_ANDROID)
@@ -319,13 +320,16 @@ AGSEngine *g_vm;
 /*------------------------------------------------------------------*/
 
 AGSEngine::AGSEngine(OSystem *syst, const AGSGameDescription *gameDesc) : Engine(syst),
-	_gameDescription(gameDesc), _randomSource("AGS"), _screen(nullptr), _gfxDriver(nullptr) {
+		_gameDescription(gameDesc), _randomSource("AGS"), _rawScreen(nullptr),
+		_screen(nullptr), _gfxDriver(nullptr) {
 	g_vm = this;
 	DebugMan.addDebugChannel(kDebugPath, "Path", "Pathfinding debug level");
 	DebugMan.addDebugChannel(kDebugGraphics, "Graphics", "Graphics debug level");
 }
 
 AGSEngine::~AGSEngine() {
+	delete _screen;
+	delete _rawScreen;
 }
 
 uint32 AGSEngine::getFeatures() const {
@@ -396,4 +400,12 @@ SaveStateList AGSEngine::listSaves() const {
 	return getMetaEngine().listSaves(_targetName.c_str());
 }
 
+void AGSEngine::setGraphicsMode(size_t w, size_t h) {
+	Graphics::PixelFormat FORMAT(4, 8, 8, 8, 8, 24, 16, 8, 0);
+	initGraphics(w, h, &FORMAT);
+
+	_rawScreen = new Graphics::Screen();
+	_screen = new ::AGS3::BITMAP(_rawScreen);
+}
+
 } // namespace AGS
diff --git a/engines/ags/ags.h b/engines/ags/ags.h
index 5099d68c83..9111973097 100644
--- a/engines/ags/ags.h
+++ b/engines/ags/ags.h
@@ -54,6 +54,7 @@ private:
 	const AGSGameDescription *_gameDescription;
 	Common::RandomSource _randomSource;
 public:
+	Graphics::Screen *_rawScreen;
 	::AGS3::BITMAP *_screen;
 	::AGS3::GFX_DRIVER *_gfxDriver;
 	::AGS3::AGS::Engine::Mutex _sMutex;
@@ -91,6 +92,11 @@ public:
 	void setRandomNumberSeed(uint32 seed) {
 		_randomSource.setSeed(seed);
 	}
+
+	/**
+	 * Setse up the graphics mode
+	 */
+	void setGraphicsMode(size_t w, size_t h);
 };
 
 extern AGSEngine *g_vm;
diff --git a/engines/ags/engine/gfx/ali3dscummvm.cpp b/engines/ags/engine/gfx/ali3dscummvm.cpp
index b588693eb4..27cd4a7099 100644
--- a/engines/ags/engine/gfx/ali3dscummvm.cpp
+++ b/engines/ags/engine/gfx/ali3dscummvm.cpp
@@ -201,6 +201,7 @@ bool ALScummVMGraphicsDriver::SetDisplayMode(const DisplayMode &mode, volatile i
 
 	OnInit(loopTimer);
 	OnModeSet(mode);
+
 	// set_gfx_mode is an allegro function that creates screen bitmap;
 	// following code assumes the screen is already created, therefore we should
 	// ensure global bitmap wraps over existing allegro screen bitmap.
diff --git a/engines/ags/lib/allegro/gfx.cpp b/engines/ags/lib/allegro/gfx.cpp
index 5e09aba5f3..cf7c156474 100644
--- a/engines/ags/lib/allegro/gfx.cpp
+++ b/engines/ags/lib/allegro/gfx.cpp
@@ -21,6 +21,7 @@
  */
 
 #include "ags/lib/allegro/gfx.h"
+#include "ags/ags.h"
 #include "common/textconsole.h"
 #include "graphics/screen.h"
 
@@ -77,7 +78,9 @@ int get_color_conversion() {
 }
 
 int set_gfx_mode(int card, int w, int h, int v_w, int v_h) {
-	error("TODO: set_gfx_mode");
+	assert(card == SCUMMVM_ID);
+	::AGS::g_vm->setGraphicsMode(w, h);
+	return 0;
 }
 
 BITMAP *create_bitmap(int width, int height) {


Commit: f54c799a973f7a55fc1d5a224bce6cb771b0666f
    https://github.com/scummvm/scummvm/commit/f54c799a973f7a55fc1d5a224bce6cb771b0666f
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix writing initial save state

Changed paths:
    engines/ags/shared/util/stdio_compat.cpp


diff --git a/engines/ags/shared/util/stdio_compat.cpp b/engines/ags/shared/util/stdio_compat.cpp
index 2bdd48ea29..449aa39eb7 100644
--- a/engines/ags/shared/util/stdio_compat.cpp
+++ b/engines/ags/shared/util/stdio_compat.cpp
@@ -43,8 +43,9 @@ int ags_fseek(Common::Stream *stream, file_off_t offset, int whence) {
 
 file_off_t ags_ftell(Common::Stream *stream) {
 	Common::SeekableReadStream *rs = dynamic_cast<Common::SeekableReadStream *>(stream);
-	assert(rs);
-	return rs->pos();
+	Common::SeekableWriteStream *ws = dynamic_cast<Common::SeekableWriteStream *>(stream);
+	assert(rs || ws);
+	return rs ? rs->pos() : ws->pos();
 }
 
 Common::FSNode getFSNode(const char *path) {


Commit: da6096e16916b370812c2083e7cd1099fd90420f
    https://github.com/scummvm/scummvm/commit/da6096e16916b370812c2083e7cd1099fd90420f
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Implement draw_trans_sprite method

Changed paths:
    engines/ags/lib/allegro/gfx.cpp
    engines/ags/lib/allegro/gfx.h


diff --git a/engines/ags/lib/allegro/gfx.cpp b/engines/ags/lib/allegro/gfx.cpp
index cf7c156474..19ec95583d 100644
--- a/engines/ags/lib/allegro/gfx.cpp
+++ b/engines/ags/lib/allegro/gfx.cpp
@@ -210,7 +210,7 @@ void stretch_sprite(BITMAP *bmp, const BITMAP *sprite, int x, int y, int w, int
 }
 
 void draw_trans_sprite(BITMAP *bmp, const BITMAP *sprite, int x, int y) {
-	error("TODO: draw_trans_sprite");
+	bmp->getSurface().blitFrom(sprite->getSurface(), Common::Point(x, y));
 }
 
 void draw_lit_sprite(BITMAP *bmp, const BITMAP *sprite, int x, int y, int color) {
diff --git a/engines/ags/lib/allegro/gfx.h b/engines/ags/lib/allegro/gfx.h
index ee2189429c..7d83d2b8ed 100644
--- a/engines/ags/lib/allegro/gfx.h
+++ b/engines/ags/lib/allegro/gfx.h
@@ -189,6 +189,12 @@ public:
 	Graphics::ManagedSurface &operator*() const {
 		return *_owner;
 	}
+	Graphics::ManagedSurface &getSurface() {
+		return *_owner;
+	}
+	const Graphics::ManagedSurface &getSurface() const {
+		return *_owner;
+	}
 
 	unsigned char *getPixels() const {
 		return (unsigned char *)_owner->getPixels();


Commit: 137263a6beaa65805f63490b937de124b30d8b54
    https://github.com/scummvm/scummvm/commit/137263a6beaa65805f63490b937de124b30d8b54
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fixes to WaitForNextFrame

Changed paths:
    engines/ags/engine/ac/timer.cpp


diff --git a/engines/ags/engine/ac/timer.cpp b/engines/ags/engine/ac/timer.cpp
index 891471d03f..e958287ffd 100644
--- a/engines/ags/engine/ac/timer.cpp
+++ b/engines/ags/engine/ac/timer.cpp
@@ -30,6 +30,7 @@
 //include <unistd.h>
 #endif
 #include "ags/engine/platform/base/agsplatformdriver.h"
+#include "ags/ags.h"
 
 namespace AGS3 {
 
@@ -79,12 +80,14 @@ void WaitForNextFrame() {
 		next_frame_timestamp = now;
 	}
 
-	auto frame_time_remaining = next_frame_timestamp - now;
-	if (frame_time_remaining > std::chrono::milliseconds::zero()) {
+	if (next_frame_timestamp > now) {
+		auto frame_time_remaining = next_frame_timestamp - now;
 		std::this_thread::sleep_for(frame_time_remaining);
 	}
 
 	next_frame_timestamp += frameDuration;
+
+	::AGS::g_vm->_rawScreen->update();
 }
 
 bool waitingForNextTick() {


Commit: 7089339362034a50f1557e72ed13573a9e31f341
    https://github.com/scummvm/scummvm/commit/7089339362034a50f1557e72ed13573a9e31f341
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Implemented keyboard/mouse event handlers

Changed paths:
  A engines/ags/events.cpp
  A engines/ags/events.h
    engines/ags/ags.cpp
    engines/ags/ags.h
    engines/ags/engine/ac/sys_events.cpp
    engines/ags/engine/platform/base/agsplatformdriver.cpp
    engines/ags/lib/allegro/keyboard.cpp
    engines/ags/lib/allegro/mouse.cpp
    engines/ags/module.mk


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index f9481277af..6189777dec 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -22,6 +22,7 @@
 
 #include "ags/ags.h"
 #include "ags/detection.h"
+#include "ags/events.h"
 #include "common/scummsys.h"
 #include "common/config-manager.h"
 #include "common/debug-channels.h"
@@ -325,11 +326,14 @@ AGSEngine::AGSEngine(OSystem *syst, const AGSGameDescription *gameDesc) : Engine
 	g_vm = this;
 	DebugMan.addDebugChannel(kDebugPath, "Path", "Pathfinding debug level");
 	DebugMan.addDebugChannel(kDebugGraphics, "Graphics", "Graphics debug level");
+
+	_events = new EventsManager();
 }
 
 AGSEngine::~AGSEngine() {
 	delete _screen;
 	delete _rawScreen;
+	delete _events;
 }
 
 uint32 AGSEngine::getFeatures() const {
diff --git a/engines/ags/ags.h b/engines/ags/ags.h
index 9111973097..ae6400c284 100644
--- a/engines/ags/ags.h
+++ b/engines/ags/ags.h
@@ -48,12 +48,14 @@ enum AGSDebugChannels {
 };
 
 struct AGSGameDescription;
+class EventsManager;
 
 class AGSEngine : public Engine {
 private:
 	const AGSGameDescription *_gameDescription;
 	Common::RandomSource _randomSource;
 public:
+	EventsManager *_events;
 	Graphics::Screen *_rawScreen;
 	::AGS3::BITMAP *_screen;
 	::AGS3::GFX_DRIVER *_gfxDriver;
@@ -102,6 +104,7 @@ public:
 extern AGSEngine *g_vm;
 #define screen ::AGS::g_vm->_screen
 #define gfx_driver ::AGS::g_vm->_gfxDriver
+#define SHOULD_QUIT ::AGS::g_vm->shouldQuit()
 
 } // namespace AGS
 
diff --git a/engines/ags/engine/ac/sys_events.cpp b/engines/ags/engine/ac/sys_events.cpp
index 7142cb7792..53bf7375f5 100644
--- a/engines/ags/engine/ac/sys_events.cpp
+++ b/engines/ags/engine/ac/sys_events.cpp
@@ -30,6 +30,7 @@
 #include "ags/engine/device/mousew32.h"
 #include "ags/engine/platform/base/agsplatformdriver.h"
 #include "ags/engine/ac/timer.h"
+#include "ags/ags.h"
 
 namespace AGS3 {
 
@@ -260,14 +261,18 @@ int ags_getch() {
 }
 
 void ags_clear_input_buffer() {
-	while (ags_kbhit()) ags_getch();
-	while (mgetbutton() != NONE);
+	while (!SHOULD_QUIT && ags_kbhit())
+		ags_getch();
+
+	while (!SHOULD_QUIT && mgetbutton() != NONE) {
+	}
 }
 
 void ags_wait_until_keypress() {
-	while (!ags_kbhit()) {
+	while (!SHOULD_QUIT && !ags_kbhit()) {
 		platform->YieldCPU();
 	}
+
 	ags_getch();
 }
 
diff --git a/engines/ags/engine/platform/base/agsplatformdriver.cpp b/engines/ags/engine/platform/base/agsplatformdriver.cpp
index ea977eb504..cfd02ea602 100644
--- a/engines/ags/engine/platform/base/agsplatformdriver.cpp
+++ b/engines/ags/engine/platform/base/agsplatformdriver.cpp
@@ -136,7 +136,7 @@ void AGSPlatformDriver::WriteStdErr(const char *fmt, ...) {
 void AGSPlatformDriver::YieldCPU() {
 	// NOTE: this is called yield, but if we actually yield instead of delay,
 	// we get a massive increase in CPU usage.
-	this->Delay(1);
+	this->Delay(10);
 	//std::this_thread::yield();
 }
 
diff --git a/engines/ags/events.cpp b/engines/ags/events.cpp
new file mode 100644
index 0000000000..be261c0d13
--- /dev/null
+++ b/engines/ags/events.cpp
@@ -0,0 +1,77 @@
+/* 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 "ags/events.h"
+#include "common/system.h"
+
+namespace AGS {
+
+EventsManager *g_events;
+
+EventsManager::EventsManager() {
+	g_events = this;
+}
+
+EventsManager::~EventsManager() {
+	g_events = nullptr;
+}
+
+void EventsManager::pollEvents() {
+	Common::Event e;
+
+	while (g_system->getEventManager()->pollEvent(e)) {
+		if (e.type == Common::EVENT_KEYDOWN) {
+			// Add keypresses to the pending key list
+			_pendingKeys.push(e.kbd.keycode);
+		} else {
+			// Add other event types to the pending events queue. If the event is a
+			// mouse move and the prior one was also, then discard the prior one.
+			// This'll help prevent too many mouse move events accumulating
+			if (e.type == Common::EVENT_MOUSEMOVE && !_pendingEvents.empty() &&
+					_pendingEvents.back().type == Common::EVENT_MOUSEMOVE)
+				_pendingEvents.back() = e;
+			else
+				_pendingEvents.push(e);
+		}
+	}
+}
+
+bool EventsManager::keypressed() {
+	pollEvents();
+	return !_pendingKeys.empty();
+}
+
+int EventsManager::readKey() {
+	pollEvents();
+	return _pendingKeys.empty() ? 0 : _pendingKeys.pop();
+}
+
+Common::Event EventsManager::readEvent() {
+	pollEvents();
+	return _pendingEvents.empty() ? Common::Event() : _pendingEvents.pop();
+}
+
+void EventsManager::warpMouse(const Common::Point &newPos) {
+	g_system->warpMouse(newPos.x, newPos.y);
+}
+
+} // namespace AGS
diff --git a/engines/ags/events.h b/engines/ags/events.h
new file mode 100644
index 0000000000..71126eee9a
--- /dev/null
+++ b/engines/ags/events.h
@@ -0,0 +1,69 @@
+/* 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 AGS_EVENTS_H
+#define AGS_EVENTS_H
+
+#include "common/queue.h"
+#include "common/events.h"
+
+namespace AGS {
+
+class EventsManager {
+private:
+	Common::Queue<Common::Event> _pendingEvents;
+	Common::Queue<Common::KeyCode> _pendingKeys;
+public:
+	EventsManager();
+	~EventsManager();
+
+	/**
+	 * Poll any pending events
+	 */
+	void pollEvents();
+
+	/**
+	 * Returns true if a keypress is pending
+	 */
+	bool keypressed();
+
+	/**
+	 * Returns the next keypress, if any is pending
+	 */
+	int readKey();
+
+	/**
+	 * Returns the next event, if any
+	 */
+	Common::Event readEvent();
+
+	/**
+	 * Sets the mouse position
+	 */
+	void warpMouse(const Common::Point &newPos);
+};
+
+extern EventsManager *g_events;
+
+} // namespace AGS
+
+#endif
diff --git a/engines/ags/lib/allegro/keyboard.cpp b/engines/ags/lib/allegro/keyboard.cpp
index 652e73815e..869ca1655a 100644
--- a/engines/ags/lib/allegro/keyboard.cpp
+++ b/engines/ags/lib/allegro/keyboard.cpp
@@ -26,6 +26,7 @@
 #include "common/system.h"
 #include "common/events.h"
 #include "common/textconsole.h"
+#include "ags/events.h"
 
 namespace AGS3 {
 
@@ -42,14 +43,13 @@ void remove_keyboard() {
 }
 
 bool keyboard_needs_poll() {
-	// TODO: Check if it's okay to be hardcoded for events, since I'm not sure
-	// how to check with ScummVM event manager for pending events
+	// We allow allow keyboard polling in ScummVM
 	return true;
 }
 
 int poll_keyboard() {
-	warning("TODO: poll_keyboard");
-	return false;
+	::AGS::g_events->pollEvents();
+	return 0;
 }
 
 void simulate_keypress(int keycode) {
@@ -69,13 +69,11 @@ void simulate_ukeypress(int keycode, int scancode) {
 }
 
 bool keypressed() {
-	warning("TODO: keypressed");
-	return true;
+	return ::AGS::g_events->keypressed();
 }
 
-int readkey(void) {
-	warning("TODO: readkey");
-	return 0;
+int readkey() {
+	return ::AGS::g_events->readKey();
 }
 
 } // namespace AGS3
diff --git a/engines/ags/lib/allegro/mouse.cpp b/engines/ags/lib/allegro/mouse.cpp
index 9c719db02f..b5cc5ab7ee 100644
--- a/engines/ags/lib/allegro/mouse.cpp
+++ b/engines/ags/lib/allegro/mouse.cpp
@@ -21,6 +21,7 @@
  */
 
 #include "ags/lib/allegro/mouse.h"
+#include "ags/events.h"
 #include "common/textconsole.h"
 
 namespace AGS3 {
@@ -35,16 +36,40 @@ BITMAP *mouse_sprite;
 int mouse_x_focus;
 int mouse_y_focus;
 
-volatile int mouse_x;
-volatile int mouse_y;
-volatile int mouse_z;
-volatile int mouse_w;
-volatile int mouse_b;
-volatile int mouse_pos;
+volatile int mouse_x;	// X position
+volatile int mouse_y;	// Y position
+volatile int mouse_z;	// Mouse wheel vertical
+volatile int mouse_w;	// Mouse wheel horizontal
+volatile int mouse_b;	// Mouse buttons bitflags
+volatile int mouse_pos;	// X position in upper 16 bits, Y in lower 16
 
 volatile int freeze_mouse_flag;
 
+static bool isMouseButtonDown(Common::EventType type) {
+	return type == Common::EVENT_LBUTTONDOWN || type == Common::EVENT_MBUTTONDOWN ||
+		type == Common::EVENT_RBUTTONDOWN;
+}
+
+static bool isMouseButtonUp(Common::EventType type) {
+	return type == Common::EVENT_LBUTTONUP || type == Common::EVENT_MBUTTONUP ||
+		type == Common::EVENT_RBUTTONUP;
+}
+
+static bool isMouseWheel(Common::EventType type) {
+	return type == Common::EVENT_WHEELDOWN || type == Common::EVENT_WHEELUP;
+}
+
+static bool isMouseEvent(Common::EventType type) {
+	return type == Common::EVENT_MOUSEMOVE || isMouseButtonDown(type) ||
+		isMouseButtonUp(type) || isMouseWheel(type);
+}
+
+
 int install_mouse() {
+	mouse_x = mouse_y = mouse_z = 0;
+	mouse_w = mouse_b = 0;
+	mouse_pos = 0;
+
 	return 0;
 }
 
@@ -52,11 +77,52 @@ void remove_mouse() {
 }
 
 int poll_mouse() {
+	::AGS::g_events->pollEvents();
+
+	Common::Event e;
+	while ((e = ::AGS::g_events->readEvent()).type != Common::EVENT_INVALID) {
+		if (isMouseEvent(e.type)) {
+			mouse_x = e.mouse.x;
+			mouse_y = e.mouse.y;
+			mouse_pos = (e.mouse.x << 16) | e.mouse.y;
+		}
+
+		switch (e.type) {
+		case Common::EVENT_LBUTTONDOWN:
+			mouse_b |= 1;
+			break;
+		case Common::EVENT_LBUTTONUP:
+			mouse_b &= ~1;
+			break;
+		case Common::EVENT_RBUTTONDOWN:
+			mouse_b |= 2;
+			break;
+		case Common::EVENT_RBUTTONUP:
+			mouse_b &= ~2;
+			break;
+		case Common::EVENT_MBUTTONDOWN:
+			mouse_b |= 4;
+			break;
+		case Common::EVENT_MBUTTONUP:
+			mouse_b &= ~4;
+			break;
+		case Common::EVENT_WHEELDOWN:
+			++mouse_z;
+			break;
+		case Common::EVENT_WHEELUP:
+			--mouse_z;
+			break;
+		default:
+			break;
+		}
+	}
+
 	return 0;
 }
 
 int mouse_needs_poll() {
-	return 0;
+	// We can always poll mouse in ScummVM
+	return true;
 }
 
 void enable_hardware_cursor() {
@@ -66,6 +132,7 @@ void disable_hardware_cursor() {
 }
 
 void show_mouse(BITMAP *bmp) {
+	warning("TODO: show_mouse");
 }
 
 void scare_mouse() {
@@ -78,12 +145,18 @@ void unscare_mouse() {
 }
 
 void position_mouse(int x, int y) {
+	mouse_x = x;
+	mouse_y = y;
+	mouse_pos = (x << 16) | y;
+	::AGS::g_events->warpMouse(Common::Point(x, y));
 }
 
 void position_mouse_z(int z) {
+	mouse_z = z;
 }
 
 void position_mouse_w(int w) {
+	mouse_w = w;
 }
 
 void set_mouse_range(int x1, int y_1, int x2, int y2) {
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index f6f087df0a..24a508e446 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -2,6 +2,7 @@ MODULE := engines/ags
 
 MODULE_OBJS = \
 	ags.o \
+	events.o \
 	metaengine.o \
 	lib/aastr-0.1.1/aarot.o \
 	lib/aastr-0.1.1/aastr.o \


Commit: 1cb82fde8c761bfc326f3202e6b9679e22db8b7a
    https://github.com/scummvm/scummvm/commit/1cb82fde8c761bfc326f3202e6b9679e22db8b7a
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Palette fixes

Changed paths:
    engines/ags/lib/allegro/color.cpp


diff --git a/engines/ags/lib/allegro/color.cpp b/engines/ags/lib/allegro/color.cpp
index bc1bdc25ea..5bd931a7e7 100644
--- a/engines/ags/lib/allegro/color.cpp
+++ b/engines/ags/lib/allegro/color.cpp
@@ -50,26 +50,17 @@ COLOR_MAP *color_map;
 
 void set_color(int idx, const RGB *p) {
 	_current_palette[idx] = *p;
-	g_system->getPaletteManager()->setPalette((const byte *)p, idx, 1);
 }
 
 void set_palette(const PALETTE p) {
 	for (int idx = 0; idx < PAL_SIZE; ++idx)
 		_current_palette[idx] = p[idx];
-	g_system->getPaletteManager()->setPalette((const byte *)p, 0, PAL_SIZE);
 }
 
 void set_palette_range(const PALETTE p, int from, int to, int retracesync) {
-	byte palette[256 * 3];
-	byte *destP = palette;
-	for (int i = 0; i < 256; ++i, destP += 3) {
-		_current_palette[i] = *p;
-		destP[0] = p->r;
-		destP[1] = p->g;
-		destP[2] = p->b;
+	for (int i = from; i < to; ++i) {
+		_current_palette[i] = p[i];
 	}
-
-	g_system->getPaletteManager()->setPalette(&palette[from], from, to - from + 1);
 }
 
 int makecol15(int r, int g, int b) {


Commit: 2014c3db165e672e5d3fff687a6e361aceea45f6
    https://github.com/scummvm/scummvm/commit/2014c3db165e672e5d3fff687a6e361aceea45f6
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Another fix for getting bitmap color depths

Changed paths:
    engines/ags/lib/allegro/gfx.cpp


diff --git a/engines/ags/lib/allegro/gfx.cpp b/engines/ags/lib/allegro/gfx.cpp
index 19ec95583d..3d7ae5cd17 100644
--- a/engines/ags/lib/allegro/gfx.cpp
+++ b/engines/ags/lib/allegro/gfx.cpp
@@ -154,7 +154,7 @@ void clear_to_color(BITMAP *bitmap, int color) {
 int bitmap_color_depth(BITMAP *bmp) {
 	Graphics::ManagedSurface &surf = **bmp;
 
-	return surf.format.bpp();
+	return (surf.format.bytesPerPixel == 1) ? 8 : surf.format.bpp();
 }
 
 int bitmap_mask_color(BITMAP *bmp) {


Commit: 7463b87bbdcdea13d915a1bdc62d1b33f9a610f3
    https://github.com/scummvm/scummvm/commit/7463b87bbdcdea13d915a1bdc62d1b33f9a610f3
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Implemented Allegro PACKFILE

Changed paths:
    engines/ags/lib/allegro/file.cpp
    engines/ags/lib/allegro/file.h


diff --git a/engines/ags/lib/allegro/file.cpp b/engines/ags/lib/allegro/file.cpp
index 1ab7ebacad..75f32935f6 100644
--- a/engines/ags/lib/allegro/file.cpp
+++ b/engines/ags/lib/allegro/file.cpp
@@ -21,11 +21,87 @@
  */
 
 #include "ags/lib/allegro/file.h"
+#include "common/file.h"
 #include "common/str.h"
 #include "common/textconsole.h"
 
 namespace AGS3 {
 
+PACKFILE *PACKFILE::pack_fopen_chunk(int pack) {
+	error("TODO: pack_fopen_chunk is not yet supported");
+}
+
+PACKFILE *PACKFILE::pack_fclose_chunk() {
+	error("TODO: pack_fclose_chunk is not yet supported");
+}
+
+int PACKFILE::pack_igetw() {
+	byte buf[2];
+	return pack_fread(buf, 2) == 2 ? READ_LE_UINT16(buf) : 0;
+}
+
+long PACKFILE::pack_igetl() {
+	byte buf[4];
+	return pack_fread(buf, 4) == 4 ? READ_LE_UINT32(buf) : 0;
+}
+
+int PACKFILE::pack_iputw(int w) {
+	byte buf[2];
+	WRITE_LE_UINT16(buf, w);
+	pack_fwrite(buf, 2);
+	return 0;
+}
+
+long PACKFILE::pack_iputl(long l) {
+	byte buf[4];
+	WRITE_LE_UINT32(buf, l);
+	pack_fwrite(buf, 4);
+	return 0;
+}
+
+int PACKFILE::pack_mgetw() {
+	byte buf[2];
+	return pack_fread(buf, 2) == 2 ? READ_BE_UINT16(buf) : 0;
+}
+
+long PACKFILE::pack_mgetl() {
+	byte buf[4];
+	return pack_fread(buf, 4) == 4 ? READ_BE_UINT32(buf) : 0;
+}
+
+int PACKFILE::pack_mputw(int w) {
+	byte buf[2];
+	WRITE_BE_UINT16(buf, 2);
+	pack_fwrite(buf, 2);
+	return 0;
+}
+
+long PACKFILE::pack_mputl(long l) {
+	byte buf[4];
+	WRITE_BE_UINT16(buf, 4);
+	pack_fwrite(buf, 4);
+	return 0;
+}
+
+char *PACKFILE::pack_fgets(char *p, int max) {
+	int c;
+	char *dest = p;
+
+	while ((c = pack_getc()) != 0 && !pack_feof() && max-- > 0) {
+		*dest++ = c;
+	}
+
+	return p;
+}
+
+int PACKFILE::pack_fputs(AL_CONST char *p) {
+	pack_fwrite(p, strlen(p));
+	pack_putc(0);
+	return 0;
+}
+
+/*------------------------------------------------------------------*/
+
 char *fix_filename_case(char *path) {
 	return path;
 }
@@ -55,48 +131,61 @@ int is_relative_filename(const char *filename) {
 	return !fname.contains('/') && !fname.contains('\\') ? 0 : -1;
 }
 
+/*------------------------------------------------------------------*/
+
 void packfile_password(AL_CONST char *password) {
 	error("TODO: packfile_password");
 }
 
 PACKFILE *pack_fopen(AL_CONST char *filename, AL_CONST char *mode) {
-	error("TODO: pack_fopen");
+	assert(!strcmp(mode, "r") || !strcmp(mode, "rb"));
+
+	Common::File *f = new Common::File();
+	if (f->open(filename)) {
+		return new ScummVMPackFile(f);
+
+	} else {
+		delete f;
+		return nullptr;
+	}
 }
 
 PACKFILE *pack_fopen_vtable(AL_CONST PACKFILE_VTABLE *vtable, void *userdata) {
-	error("TODO: pack_fopen_vtable");
+	return new VTablePackFile(vtable, userdata);
 }
 
 int pack_fclose(PACKFILE *f) {
-	error("TODO: xxx");
+	f->close();
+	delete f;
+	return 0;
 }
 
 int pack_fseek(PACKFILE *f, int offset) {
-	error("TODO: xxx");
+	return f->pack_fseek(offset);
 }
 
 PACKFILE *pack_fopen_chunk(PACKFILE *f, int pack) {
-	error("TODO: xxx");
+	return f->pack_fopen_chunk(pack);
 }
 
 PACKFILE *pack_fclose_chunk(PACKFILE *f) {
-	error("TODO: xxx");
+	return f->pack_fclose_chunk();
 }
 
 int pack_getc(PACKFILE *f) {
-	error("TODO: xxx");
+	return f->pack_getc();
 }
 
 int pack_putc(int c, PACKFILE *f) {
-	error("TODO: xxx");
+	return f->pack_putc(c);
 }
 
 int pack_feof(PACKFILE *f) {
-	error("TODO: xxx");
+	return f->pack_feof();
 }
 
 int pack_ferror(PACKFILE *f) {
-	error("TODO: xxx");
+	return f->pack_ferror();
 }
 
 int pack_igetw(PACKFILE *f) {
@@ -104,55 +193,55 @@ int pack_igetw(PACKFILE *f) {
 }
 
 long pack_igetl(PACKFILE *f) {
-	error("TODO: xxx");
+	return f->pack_igetl();
 }
 
 int pack_iputw(int w, PACKFILE *f) {
-	error("TODO: xxx");
+	return f->pack_iputw(w);
 }
 
 long pack_iputl(long l, PACKFILE *f) {
-	error("TODO: xxx");
+	return f->pack_iputl(l);
 }
 
 int pack_mgetw(PACKFILE *f) {
-	error("TODO: xxx");
+	return f->pack_mgetw();
 }
 
 long pack_mgetl(PACKFILE *f) {
-	error("TODO: xxx");
+	return f->pack_mgetl();
 }
 
 int pack_mputw(int w, PACKFILE *f) {
-	error("TODO: xxx");
+	return f->pack_mputw(w);
 }
 
 long pack_mputl(long l, PACKFILE *f) {
-	error("TODO: xxx");
+	return f->pack_mputl(l);
 }
 
 long pack_fread(void *p, long n, PACKFILE *f) {
-	error("TODO: xxx");
+	return f->pack_fread(p, n);
 }
 
 long pack_fwrite(AL_CONST void *p, long n, PACKFILE *f) {
-	error("TODO: xxx");
+	return f->pack_fwrite(p, n);
 }
 
 int pack_ungetc(int c, PACKFILE *f) {
-	error("TODO: xxx");
+	return f->pack_ungetc(c);
 }
 
 char *pack_fgets(char *p, int max, PACKFILE *f) {
-	error("TODO: xxx");
+	return f->pack_fgets(p, max);
 }
 
 int pack_fputs(AL_CONST char *p, PACKFILE *f) {
-	error("TODO: xxx");
+	return f->pack_fputs(p);
 }
 
 void *pack_get_userdata(PACKFILE *f) {
-	error("TODO: xxx");
+	return f->pack_get_userdata();
 }
 
 } // namespace AGS3
diff --git a/engines/ags/lib/allegro/file.h b/engines/ags/lib/allegro/file.h
index abf82d97d5..a551b334b1 100644
--- a/engines/ags/lib/allegro/file.h
+++ b/engines/ags/lib/allegro/file.h
@@ -24,6 +24,7 @@
 #define AGS_LIB_ALLEGRO_FILE_H
 
 #include "ags/lib/allegro/alconfig.h"
+#include "common/file.h"
 
 namespace AGS3 {
 
@@ -69,16 +70,130 @@ struct PACKFILE_VTABLE {
  * Allegro file class
  */
 struct PACKFILE {
-	AL_CONST PACKFILE_VTABLE *vtable;
-	void *userdata;
-	int is_normal_packfile;
-
-	/* The following is only to be used for the "normal" PACKFILE vtable,
-	 * i.e. what is implemented by Allegro itself. If is_normal_packfile is
-	 * false then the following is not even allocated. This must be the last
-	 * member in the structure.
-	 */
-	struct _al_normal_packfile_details normal;
+	virtual ~PACKFILE() {
+		close();
+	}
+
+	virtual void close() {}
+	virtual int pack_fseek(int offset) = 0;
+	virtual int pack_getc() = 0;
+	virtual int pack_putc(int c) = 0;
+	virtual int pack_ungetc(int c) = 0;
+	virtual long pack_fread(void *p, long n) = 0;
+	virtual long pack_fwrite(AL_CONST void *p, long n) = 0;
+	virtual int pack_feof() = 0;
+	virtual int pack_ferror() = 0;
+	virtual void *pack_get_userdata() const { return nullptr; }
+
+	PACKFILE *pack_fopen_chunk(int pack);
+	PACKFILE *pack_fclose_chunk();
+	int pack_igetw();
+	long pack_igetl();
+	int pack_iputw(int w);
+	long pack_iputl(long l);
+	int pack_mgetw();
+	long pack_mgetl();
+	int pack_mputw(int w);
+	long pack_mputl(long l);
+	char *pack_fgets(char *p, int max);
+	int pack_fputs(AL_CONST char *p);
+};
+
+struct ScummVMPackFile : public PACKFILE {
+public:
+	Common::SeekableReadStream *_stream;
+
+	ScummVMPackFile(Common::SeekableReadStream *rs) : PACKFILE(), _stream(rs) {
+	}
+
+	virtual ~ScummVMPackFile() {}
+
+	void close() override {
+		delete _stream;
+		_stream = nullptr;
+	}
+
+	int pack_fseek(int offset) override {
+		return _stream->seek(offset);
+	}
+
+	int pack_getc() override {
+		return _stream->readByte();
+	}
+
+	int pack_putc(int c) override {
+		error("pack_putc is not yet supported");
+	}
+
+	int pack_ungetc(int c) override {
+		_stream->seek(-1, SEEK_CUR);
+		return 0;
+	}
+
+	long pack_fread(void *p, long n) override {
+		return _stream->read(p, n);
+	}
+
+	long pack_fwrite(AL_CONST void *p, long n) override {
+		error("pack_fwrite is not yet supported");
+	}
+
+	int pack_feof() override {
+		return _stream->eos();
+	}
+
+	int pack_ferror() override {
+		return _stream->err();
+	}
+};
+
+struct VTablePackFile : public PACKFILE {
+	AL_CONST PACKFILE_VTABLE *_vTable;
+	void *_userData;
+
+	VTablePackFile(AL_CONST PACKFILE_VTABLE *vTable, void *userData) :
+		_vTable(vTable), _userData(userData) {
+	}
+
+	void close() override {
+		_vTable->pf_fclose(_userData);
+	}
+
+	int pack_fseek(int offset) override {
+		return _vTable->pf_fseek(_userData, offset);
+	}
+
+	int pack_getc() override {
+		return _vTable->pf_getc(_userData);
+	}
+
+	int pack_putc(int c) override {
+		return _vTable->pf_putc(c, _userData);
+	}
+
+	int pack_ungetc(int c) override {
+		return _vTable->pf_ungetc(c, _userData);
+	}
+
+	long pack_fread(void *p, long n) override {
+		return _vTable->pf_fread(p, n, _userData);
+	}
+
+	long pack_fwrite(AL_CONST void *p, long n) override {
+		return _vTable->pf_fwrite(p, n, _userData);
+	}
+
+	int pack_feof() override {
+		return _vTable->pf_feof(_userData);
+	}
+
+	int pack_ferror() override {
+		return _vTable->pf_ferror(_userData);
+	}
+
+	virtual void *pack_get_userdata() const override {
+		return _userData;
+	}
 };
 
 extern char *fix_filename_case(char *path);


Commit: 3e190f6c5c0e931f649c707de75f36f4bab7c12f
    https://github.com/scummvm/scummvm/commit/3e190f6c5c0e931f649c707de75f36f4bab7c12f
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Remove deprecated MIDI_DRIVER

Changed paths:
    engines/ags/lib/audio/midi.cpp
    engines/ags/lib/audio/midi.h


diff --git a/engines/ags/lib/audio/midi.cpp b/engines/ags/lib/audio/midi.cpp
index 96de121a66..ace78dccc1 100644
--- a/engines/ags/lib/audio/midi.cpp
+++ b/engines/ags/lib/audio/midi.cpp
@@ -32,10 +32,6 @@ BEGIN_MIDI_DRIVER_LIST
 { SCUMMVM_ID, &dummy_driver_data, true },
 END_MIDI_DRIVER_LIST
 
-MIDI_DRIVER *midi_driver;
-
-MIDI_DRIVER *midi_input_driver;
-
 int midi_card;
 
 int midi_input_card;
diff --git a/engines/ags/lib/audio/midi.h b/engines/ags/lib/audio/midi.h
index a96048191d..37ebf6be81 100644
--- a/engines/ags/lib/audio/midi.h
+++ b/engines/ags/lib/audio/midi.h
@@ -24,67 +24,20 @@
 #define AGS_LIB_AUDIO_MIDI_H
 
 #include "common/scummsys.h"
+#include "common/array.h"
 #include "ags/lib/allegro/base.h"
 #include "ags/lib/allegro/alconfig.h"
 
 namespace AGS3 {
 
-/* Theoretical maximums: */
-#define MIDI_VOICES           64       /* actual drivers may not be */
-#define MIDI_TRACKS           32       /* able to handle this many */
-
 /* a midi file */
-struct MIDI {
-	int divisions;                      /* number of ticks per quarter note */
-	struct {
-		unsigned char *data;             /* MIDI message stream */
-		int len;                         /* length of the track data */
-	} track[MIDI_TRACKS];
-};
+typedef Common::Array<byte> MIDI;
 
 
 #define MIDI_AUTODETECT       -1
 #define MIDI_NONE             0
 #define MIDI_DIGMID           AL_ID('D','I','G','I')
 
-/* driver for playing midi music */
-struct MIDI_DRIVER {
-	int  id;                            /* driver ID code */
-	AL_CONST char *name;                /* driver name */
-	AL_CONST char *desc;                /* description string */
-	AL_CONST char *ascii_name;          /* ASCII format name string */
-	int  voices;                        /* available voices */
-	int  basevoice;                     /* voice number offset */
-	int  max_voices;                    /* maximum voices we can support */
-	int  def_voices;                    /* default number of voices to use */
-	int  xmin, xmax;                    /* reserved voice range */
-
-	/* setup routines */
-	AL_METHOD(int, detect, (int input));
-	AL_METHOD(int, init, (int input, int voices));
-	AL_METHOD(void, exit, (int input));
-	AL_METHOD(int, set_mixer_volume, (int volume));
-	AL_METHOD(int, get_mixer_volume, (void));
-
-	/* raw MIDI output to MPU-401, etc. */
-	AL_METHOD(void, raw_midi, (int data));
-
-	/* dynamic patch loading routines */
-	AL_METHOD(int, load_patches, (AL_CONST char *patches, AL_CONST char *drums));
-	AL_METHOD(void, adjust_patches, (AL_CONST char *patches, AL_CONST char *drums));
-
-	/* note control functions */
-	AL_METHOD(void, key_on, (int inst, int note, int bend, int vol, int pan));
-	AL_METHOD(void, key_off, (int voice));
-	AL_METHOD(void, set_volume, (int voice, int vol));
-	AL_METHOD(void, set_pitch, (int voice, int note, int bend));
-	AL_METHOD(void, set_pan, (int voice, int pan));
-	AL_METHOD(void, set_vibrato, (int voice, int amount));
-};
-
-
-AL_VAR(MIDI_DRIVER, midi_digmid);
-
 AL_ARRAY(_DRIVER_INFO, _midi_driver_list);
 
 
@@ -101,10 +54,6 @@ AL_ARRAY(_DRIVER_INFO, _midi_driver_list);
 	{  MIDI_DIGMID,      &midi_digmid,        TRUE  },
 
 
-AL_VAR(MIDI_DRIVER *, midi_driver);
-
-AL_VAR(MIDI_DRIVER *, midi_input_driver);
-
 AL_VAR(int, midi_card);
 
 AL_VAR(int, midi_input_card);


Commit: 338d08a0cb939efc804ec258772e9a34fd64467a
    https://github.com/scummvm/scummvm/commit/338d08a0cb939efc804ec258772e9a34fd64467a
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Implemented ScummVM MIDI music player

Changed paths:
  A engines/ags/music.cpp
  A engines/ags/music.h
    engines/ags/ags.cpp
    engines/ags/ags.h
    engines/ags/engine/media/audio/clip_mymidi.cpp
    engines/ags/lib/allegro/file.h
    engines/ags/lib/audio/midi.cpp
    engines/ags/lib/audio/midi.h
    engines/ags/module.mk


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index 6189777dec..a7289c88be 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -23,6 +23,7 @@
 #include "ags/ags.h"
 #include "ags/detection.h"
 #include "ags/events.h"
+#include "ags/music.h"
 #include "common/scummsys.h"
 #include "common/config-manager.h"
 #include "common/debug-channels.h"
@@ -321,19 +322,21 @@ AGSEngine *g_vm;
 /*------------------------------------------------------------------*/
 
 AGSEngine::AGSEngine(OSystem *syst, const AGSGameDescription *gameDesc) : Engine(syst),
-		_gameDescription(gameDesc), _randomSource("AGS"), _rawScreen(nullptr),
-		_screen(nullptr), _gfxDriver(nullptr) {
+		_gameDescription(gameDesc), _randomSource("AGS"), _events(nullptr), _music(nullptr),
+		_rawScreen(nullptr), _screen(nullptr), _gfxDriver(nullptr) {
 	g_vm = this;
 	DebugMan.addDebugChannel(kDebugPath, "Path", "Pathfinding debug level");
 	DebugMan.addDebugChannel(kDebugGraphics, "Graphics", "Graphics debug level");
 
 	_events = new EventsManager();
+	_music = new Music(_mixer);
 }
 
 AGSEngine::~AGSEngine() {
 	delete _screen;
 	delete _rawScreen;
 	delete _events;
+	delete _music;
 }
 
 uint32 AGSEngine::getFeatures() const {
diff --git a/engines/ags/ags.h b/engines/ags/ags.h
index ae6400c284..f8d0f7e455 100644
--- a/engines/ags/ags.h
+++ b/engines/ags/ags.h
@@ -49,6 +49,7 @@ enum AGSDebugChannels {
 
 struct AGSGameDescription;
 class EventsManager;
+class Music;
 
 class AGSEngine : public Engine {
 private:
@@ -56,6 +57,7 @@ private:
 	Common::RandomSource _randomSource;
 public:
 	EventsManager *_events;
+	Music *_music;
 	Graphics::Screen *_rawScreen;
 	::AGS3::BITMAP *_screen;
 	::AGS3::GFX_DRIVER *_gfxDriver;
diff --git a/engines/ags/engine/media/audio/clip_mymidi.cpp b/engines/ags/engine/media/audio/clip_mymidi.cpp
index 2dfbb72041..ff0a1fd481 100644
--- a/engines/ags/engine/media/audio/clip_mymidi.cpp
+++ b/engines/ags/engine/media/audio/clip_mymidi.cpp
@@ -113,6 +113,7 @@ int MYMIDI::play() {
 
 	lengthInSeconds = get_midi_length(tune);
 	if (AGS3::play_midi(tune, repeat)) {
+		lengthInSeconds = 0;
 		return 0;
 	}
 
diff --git a/engines/ags/lib/allegro/file.h b/engines/ags/lib/allegro/file.h
index a551b334b1..976cbfc941 100644
--- a/engines/ags/lib/allegro/file.h
+++ b/engines/ags/lib/allegro/file.h
@@ -114,7 +114,7 @@ public:
 	}
 
 	int pack_fseek(int offset) override {
-		return _stream->seek(offset);
+		return _stream->seek(offset, SEEK_CUR);
 	}
 
 	int pack_getc() override {
diff --git a/engines/ags/lib/audio/midi.cpp b/engines/ags/lib/audio/midi.cpp
index ace78dccc1..503b3b14b7 100644
--- a/engines/ags/lib/audio/midi.cpp
+++ b/engines/ags/lib/audio/midi.cpp
@@ -22,6 +22,7 @@
 
 #include "ags/lib/audio/midi.h"
 #include "ags/lib/allegro/file.h"
+#include "ags/music.h"
 #include "common/textconsole.h"
 
 namespace AGS3 {
@@ -49,7 +50,7 @@ int detect_midi_driver(int driver_id) {
 
 
 void stop_midi() {
-	warning("TODO: stop_midi");
+	::AGS::g_music->stop();
 }
 
 void destroy_midi(MIDI *midi) {
@@ -57,7 +58,7 @@ void destroy_midi(MIDI *midi) {
 }
 
 int play_midi(MIDI *tune, bool repeat) {
-	warning("TODO: play_midi");
+	::AGS::g_music->playMusic(tune, repeat);
 	return 0;
 }
 
@@ -67,15 +68,15 @@ size_t get_midi_length(MIDI *tune) {
 }
 
 void midi_seek(int target) {
-	warning("TODO: midi_seek");
+	::AGS::g_music->seek(target);
 }
 
 void midi_pause() {
-	warning("TODO: midi_pause");
+	::AGS::g_music->pause();
 }
 
 void midi_resume() {
-	warning("TODO: midi_resume");
+	::AGS::g_music->resume();
 }
 
 int load_midi_patches() {
@@ -83,8 +84,25 @@ int load_midi_patches() {
 	return 0;
 }
 
+#define MIDI_BLOCK_SIZE 32768
+
 MIDI *load_midi_pf(PACKFILE *fp) {
-	error("TODO: load_midi_pf");
+	MIDI *midi = new MIDI();
+	int bytesRead;
+
+	// Iterate through loading blocks of MIDI data
+	for (;;) {
+		size_t priorSize = midi->size();
+		midi->resize(priorSize + MIDI_BLOCK_SIZE);
+		bytesRead = pack_fread(&(*midi)[priorSize], MIDI_BLOCK_SIZE, fp);
+
+		if (bytesRead < MIDI_BLOCK_SIZE) {
+			midi->resize(priorSize + bytesRead);
+			break;
+		}
+	}
+
+	return midi;
 }
 
 } // namespace AGS3
diff --git a/engines/ags/lib/audio/midi.h b/engines/ags/lib/audio/midi.h
index 37ebf6be81..376f8b919c 100644
--- a/engines/ags/lib/audio/midi.h
+++ b/engines/ags/lib/audio/midi.h
@@ -27,19 +27,17 @@
 #include "common/array.h"
 #include "ags/lib/allegro/base.h"
 #include "ags/lib/allegro/alconfig.h"
+#include "ags/music.h"
 
 namespace AGS3 {
 
-/* a midi file */
-typedef Common::Array<byte> MIDI;
-
-
 #define MIDI_AUTODETECT       -1
 #define MIDI_NONE             0
 #define MIDI_DIGMID           AL_ID('D','I','G','I')
 
 AL_ARRAY(_DRIVER_INFO, _midi_driver_list);
 
+using MIDI = ::AGS::MIDI;
 
 /* macros for constructing the driver lists */
 #define BEGIN_MIDI_DRIVER_LIST                                 \
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 24a508e446..89c56efde0 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -4,6 +4,7 @@ MODULE_OBJS = \
 	ags.o \
 	events.o \
 	metaengine.o \
+	music.o \
 	lib/aastr-0.1.1/aarot.o \
 	lib/aastr-0.1.1/aastr.o \
 	lib/aastr-0.1.1/aautil.o \
diff --git a/engines/ags/music.cpp b/engines/ags/music.cpp
new file mode 100644
index 0000000000..191335d1e7
--- /dev/null
+++ b/engines/ags/music.cpp
@@ -0,0 +1,95 @@
+/* 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 "ags/music.h"
+#include "audio/midiparser.h"
+
+namespace AGS {
+
+Music *g_music;
+
+Music::Music(Audio::Mixer *mixer) :
+		Audio::MidiPlayer(), _mixer(mixer) {
+	g_music = this;
+	Audio::MidiPlayer::createDriver();
+
+	int ret = _driver->open();
+	if (ret == 0) {
+		if (_nativeMT32)
+			_driver->sendMT32Reset();
+		else
+			_driver->sendGMReset();
+
+		_driver->setTimerCallback(this, &timerCallback);
+	}
+}
+
+Music::~Music() {
+	stop();
+	g_music = nullptr;
+}
+
+void Music::sendToChannel(byte channel, uint32 b) {
+	if (!_channelsTable[channel]) {
+		_channelsTable[channel] = (channel == 9) ? _driver->getPercussionChannel() : _driver->allocateChannel();
+		// If a new channel is allocated during the playback, make sure
+		// its volume is correctly initialized.
+		if (_channelsTable[channel])
+			_channelsTable[channel]->volume(_channelsVolume[channel] * _masterVolume / 255);
+	}
+
+	if (_channelsTable[channel])
+		_channelsTable[channel]->send(b);
+}
+
+void Music::playMusic(const MIDI *midi, bool repeat) {
+	stop();
+
+	// Load MIDI resource data
+	int midiMusicSize = midi->size();
+
+	_midiData.resize(midi->size());
+	Common::copy(&(*midi)[0], &(*midi)[0] + midi->size(), &_midiData[0]);
+
+	MidiParser *parser = MidiParser::createParser_SMF();
+	if (parser->loadMusic(&_midiData[0], midiMusicSize)) {
+		parser->setTrack(0);
+		parser->setMidiDriver(this);
+		parser->setTimerRate(_driver->getBaseTempo());
+		parser->property(MidiParser::mpCenterPitchWheelOnUnload, 1);
+
+		_parser = parser;
+
+		syncVolume();
+
+		_isLooping = repeat;
+		_isPlaying = true;
+	} else {
+		delete parser;
+	}
+}
+
+void Music::seek(size_t offset) {
+	warning("TODO: Music::seek to offset %u", offset);
+}
+
+} // End of namespace AGS
diff --git a/engines/ags/music.h b/engines/ags/music.h
new file mode 100644
index 0000000000..6b6f09b569
--- /dev/null
+++ b/engines/ags/music.h
@@ -0,0 +1,63 @@
+/* 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 AGS_MUSIC_H
+#define AGS_MUSIC_H
+
+#include "audio/audiostream.h"
+#include "audio/midiplayer.h"
+#include "audio/mixer.h"
+#include "common/array.h"
+
+namespace AGS {
+
+// A MIDI file
+typedef Common::Array<byte> MIDI;
+
+class Music : public Audio::MidiPlayer {
+private:
+	Audio::Mixer *_mixer;
+	Audio::SoundHandle _soundHandle;
+	Common::Array<byte> _midiData;
+protected:
+	// Overload Audio::MidiPlayer method
+	void sendToChannel(byte channel, uint32 b) override;
+public:
+	Music(Audio::Mixer *mixer);
+	~Music() override;
+
+	/**
+	 * Play music
+	 */
+	void playMusic(const MIDI *midi, bool repeat = false);
+
+	/**
+	 * Seek within the MIDI
+	 */
+	void seek(size_t offset);
+};
+
+extern Music *g_music;
+
+} // End of namespace AGS
+
+#endif


Commit: ab7146ed2ed73408f58e696c3340b062bc12af6e
    https://github.com/scummvm/scummvm/commit/ab7146ed2ed73408f58e696c3340b062bc12af6e
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix shutdown crash in set_gfx_mode

Changed paths:
    engines/ags/lib/allegro/gfx.cpp


diff --git a/engines/ags/lib/allegro/gfx.cpp b/engines/ags/lib/allegro/gfx.cpp
index 3d7ae5cd17..fe8f3e6d9c 100644
--- a/engines/ags/lib/allegro/gfx.cpp
+++ b/engines/ags/lib/allegro/gfx.cpp
@@ -78,8 +78,11 @@ int get_color_conversion() {
 }
 
 int set_gfx_mode(int card, int w, int h, int v_w, int v_h) {
-	assert(card == SCUMMVM_ID);
-	::AGS::g_vm->setGraphicsMode(w, h);
+	// Graphics shutdown can be ignored
+	if (card != -1) {
+		assert(card == SCUMMVM_ID);
+		::AGS::g_vm->setGraphicsMode(w, h);
+	}
 	return 0;
 }
 


Commit: b2ec154bca8985e94c4886b57a0671247f7bedd8
    https://github.com/scummvm/scummvm/commit/b2ec154bca8985e94c4886b57a0671247f7bedd8
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added detection for AGDI KQ2

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


diff --git a/engines/ags/detection.cpp b/engines/ags/detection.cpp
index 7956183a50..204906a2d5 100644
--- a/engines/ags/detection.cpp
+++ b/engines/ags/detection.cpp
@@ -25,10 +25,7 @@
 #include "ags/detection_tables.h"
 
 AGSMetaEngineDetection::AGSMetaEngineDetection() : AdvancedMetaEngineDetection(AGS::GAME_DESCRIPTIONS,
-	        sizeof(AGS::AGSGameDescription), AGS::AGS_GAMES) {
-	static const char *const DIRECTORY_GLOBS[2] = { "usecode", 0 };
-	_maxScanDepth = 2;
-	_directoryGlobs = DIRECTORY_GLOBS;
+	        sizeof(AGS::AGSGameDescription), AGS::GAME_NAMES) {
 }
 
 REGISTER_PLUGIN_STATIC(AGS_DETECTION, PLUGIN_TYPE_ENGINE_DETECTION, AGSMetaEngineDetection);
diff --git a/engines/ags/detection_tables.h b/engines/ags/detection_tables.h
index d7c4411af8..07fcfd54d6 100644
--- a/engines/ags/detection_tables.h
+++ b/engines/ags/detection_tables.h
@@ -22,26 +22,30 @@
 
 namespace AGS {
 
-static const PlainGameDescriptor AGS_GAMES[] = {
+static const PlainGameDescriptor GAME_NAMES[] = {
 	{ "ags", "Adventure Game Studio Game" },
 
 	{ "bcremake", "Black Cauldron Remake" },
+	{ "kq2agdi", "Kings Quest II - Romancing The Stones" },
+
 	{ 0, 0 }
 };
 
+#define ENGLISH_ENTRY(ID, FILENAME, MD5, SIZE) { \
+		{ \
+			ID, \
+			nullptr, \
+			AD_ENTRY1s(FILENAME, MD5, SIZE), \
+			Common::EN_ANY, \
+			Common::kPlatformUnknown, \
+			ADGF_NO_FLAGS, \
+			GUIO1(GUIO_NOSPEECH) \
+		} \
+	}
 
 static const AGSGameDescription GAME_DESCRIPTIONS[] = {
-	{
-		{
-			"bcremake",
-			nullptr,
-			AD_ENTRY1s("bc.exe", "0710e2ec71042617f565c01824f0cf3c", 7683255),
-			Common::EN_ANY,
-			Common::kPlatformDOS,
-			ADGF_NO_FLAGS,
-			GUIO1(GUIO_NOSPEECH)
-		}
-	},
+	ENGLISH_ENTRY("bcremake", "bc.exe", "0710e2ec71042617f565c01824f0cf3c", 7683255),
+	ENGLISH_ENTRY("kq2agdi", "kq2vga.exe", "40cfb7563df7dacf6530b19289a4745b", 12563246),
 
 	{ AD_TABLE_END_MARKER }
 };


Commit: edb16471d0177d273423a346336b576f1e50cdb1
    https://github.com/scummvm/scummvm/commit/edb16471d0177d273423a346336b576f1e50cdb1
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added detection for A Tale of Two Kingdoms

Changed paths:
    engines/ags/detection_tables.h


diff --git a/engines/ags/detection_tables.h b/engines/ags/detection_tables.h
index 07fcfd54d6..ec98ce52e4 100644
--- a/engines/ags/detection_tables.h
+++ b/engines/ags/detection_tables.h
@@ -25,6 +25,7 @@ namespace AGS {
 static const PlainGameDescriptor GAME_NAMES[] = {
 	{ "ags", "Adventure Game Studio Game" },
 
+	{ "atotk", "A Tale Of Two Kingdoms" },
 	{ "bcremake", "Black Cauldron Remake" },
 	{ "kq2agdi", "Kings Quest II - Romancing The Stones" },
 
@@ -45,6 +46,7 @@ static const PlainGameDescriptor GAME_NAMES[] = {
 
 static const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("bcremake", "bc.exe", "0710e2ec71042617f565c01824f0cf3c", 7683255),
+	ENGLISH_ENTRY("atotk", "atotk.exe", "37cf2d4d07842d45b59c6dd9387c1ee7", 42872046),
 	ENGLISH_ENTRY("kq2agdi", "kq2vga.exe", "40cfb7563df7dacf6530b19289a4745b", 12563246),
 
 	{ AD_TABLE_END_MARKER }


Commit: e0ddb50c59dce168a56ea07d7031f7d3b9cc98e6
    https://github.com/scummvm/scummvm/commit/e0ddb50c59dce168a56ea07d7031f7d3b9cc98e6
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added framework for implementing AGS plugin DLLs in code

Changed paths:
  A engines/ags/plugins/agscreditz/agscreditz.cpp
  A engines/ags/plugins/agscreditz/agscreditz.h
  A engines/ags/plugins/dll.cpp
  A engines/ags/plugins/dll.h
    engines/ags/engine/plugin/library.cpp
    engines/ags/module.mk


diff --git a/engines/ags/engine/plugin/library.cpp b/engines/ags/engine/plugin/library.cpp
index 44c6e1a06a..7b64088194 100644
--- a/engines/ags/engine/plugin/library.cpp
+++ b/engines/ags/engine/plugin/library.cpp
@@ -21,24 +21,24 @@
  */
 
 #include "ags/engine/plugin/library.h"
+#include "ags/plugins/dll.h"
 
 namespace AGS3 {
 
 void *dlopen(const char *filename, bool) {
-	// TODO: Reimplement plugins as C++ code that's part of the project
-	return nullptr;
+	return ::AGS::Plugins::dlopen(filename);
 }
 
-int dlclose(void *) {
-	return 0;
+int dlclose(void *lib) {
+	return ::AGS::Plugins::dlclose(lib);
 }
 
 void *dlsym(void *lib, const char *method) {
-	return nullptr;
+	return ::AGS::Plugins::dlsym(lib, method);
 }
 
 const char *dlerror() {
-	return nullptr;
+	return ::AGS::Plugins::dlerror();
 }
 
 } // namespace AGS3
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 89c56efde0..eeda8d7f15 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -307,7 +307,9 @@ MODULE_OBJS = \
 	engine/script/script_api.o \
 	engine/script/script_engine.o \
 	engine/script/script_runtime.o \
-	engine/script/systemimports.o
+	engine/script/systemimports.o \
+	plugins/dll.o \
+	plugins/agscreditz\agscreditz.o
 
 ifdef ENABLE_AGS_TESTS
 MODULE_OBJS += \
diff --git a/engines/ags/plugins/agscreditz/agscreditz.cpp b/engines/ags/plugins/agscreditz/agscreditz.cpp
new file mode 100644
index 0000000000..2c53d438fa
--- /dev/null
+++ b/engines/ags/plugins/agscreditz/agscreditz.cpp
@@ -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.
+ *
+ */
+
+#include "ags/plugins/agscreditz/agscreditz.h"
+
+namespace AGS {
+namespace Plugins {
+namespace AgsCreditz {
+
+AgsCreditz::AgsCreditz() {
+	ADD_METHOD(AGS_GetPluginName);
+}
+
+const char *AgsCreditz::AGS_GetPluginName() {
+	return "agsCreditz v1.1 by AJA";
+}
+
+} // namespace AgsCreditz
+} // namespace Plugins
+} // namespace AGS
diff --git a/engines/ags/plugins/agscreditz/agscreditz.h b/engines/ags/plugins/agscreditz/agscreditz.h
new file mode 100644
index 0000000000..25b5da8b0a
--- /dev/null
+++ b/engines/ags/plugins/agscreditz/agscreditz.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 AGS_PLUGINS_AGSCREDITZ_AGSCREDITZ_H
+#define AGS_PLUGINS_AGSCREDITZ_AGSCREDITZ_H
+
+#include "ags/plugins/dll.h"
+
+namespace AGS {
+namespace Plugins {
+namespace AgsCreditz {
+
+class AgsCreditz : public DLL {
+private:
+	static const char *AGS_GetPluginName();
+public:
+	AgsCreditz();
+};
+
+} // namespace AgsCreditz
+} // namespace Plugins
+} // namespace AGS
+
+#endif
diff --git a/engines/ags/plugins/dll.cpp b/engines/ags/plugins/dll.cpp
new file mode 100644
index 0000000000..65d6d13f6c
--- /dev/null
+++ b/engines/ags/plugins/dll.cpp
@@ -0,0 +1,105 @@
+/* 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 "ags/plugins/dll.h"
+#include "ags/plugins/agscreditz/agscreditz.h"
+#include "common/str.h"
+
+namespace AGS {
+namespace Plugins {
+
+void *dlopen(const char *filename) {
+	Common::String fname(filename);
+
+	if (fname.equalsIgnoreCase("libagsCreditz.so"))
+		return new AgsCreditz::AgsCreditz();
+
+	return nullptr;
+}
+
+int dlclose(void *lib) {
+	delete lib;
+	return 0;
+}
+
+void *dlsym(void *lib, const char *method) {
+	DLL *dll = static_cast<DLL *>(lib);
+	return (*dll)[method];
+}
+
+const char *dlerror() {
+	return nullptr;
+}
+
+/*------------------------------------------------------------------*/
+
+DLL::DLL() {
+	ADD_METHOD(AGS_PluginV2);
+	ADD_METHOD(AGS_EditorStartup);
+	ADD_METHOD(AGS_EditorShutdown);
+	ADD_METHOD(AGS_EditorProperties);
+	ADD_METHOD(AGS_EditorSaveGame);
+	ADD_METHOD(AGS_EditorLoadGame);
+	ADD_METHOD(AGS_EngineStartup);
+	ADD_METHOD(AGS_EngineShutdown);
+	ADD_METHOD(AGS_EngineOnEvent);
+	ADD_METHOD(AGS_EngineDebugHook);
+	ADD_METHOD(AGS_EngineInitGfx);
+}
+
+int DLL::AGS_EditorStartup(IAGSEditor *) {
+	return 0;
+}
+
+void DLL::AGS_EditorShutdown() {
+}
+
+void DLL::AGS_EditorProperties(HWND) {
+}
+
+int DLL::AGS_EditorSaveGame(char *, int) {
+	return 0;
+}
+
+void DLL::AGS_EditorLoadGame(char *, int) {
+}
+
+void DLL::AGS_EngineStartup(IAGSEngine *) {
+}
+
+void DLL::AGS_EngineShutdown() {
+}
+
+int DLL::AGS_EngineOnEvent(int, int) {
+	return 0;
+}
+
+int DLL::AGS_EngineDebugHook(const char *, int, int) {
+	return 0;
+}
+
+void DLL::AGS_EngineInitGfx(const char *driverID, void *data) {
+	assert(!strcmp(driverID, "Software"));
+}
+
+} // namespace Plugins
+} // namespace AGS
diff --git a/engines/ags/plugins/dll.h b/engines/ags/plugins/dll.h
new file mode 100644
index 0000000000..abe2edd14b
--- /dev/null
+++ b/engines/ags/plugins/dll.h
@@ -0,0 +1,75 @@
+/* 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 AGS_PLUGINS_DLL_H
+#define AGS_PLUGINS_DLL_H
+
+#include "common/hashmap.h"
+#include "common/hash-str.h"
+
+namespace AGS {
+namespace Plugins {
+
+#define ADD_METHOD(NAME) _methods[#NAME] = (void *)&NAME
+
+typedef void *IAGSEditor;
+typedef void *IAGSEngine;
+typedef uint32 HWND;
+
+/**
+ * Base class for the implementation of AGS plugin DLLs
+ */
+class DLL {
+protected:
+	Common::HashMap<Common::String, void *, Common::IgnoreCase_Hash, Common::IgnoreCase_EqualTo> _methods;
+
+	static int    AGS_PluginV2() { return 1; }
+	static int    AGS_EditorStartup(IAGSEditor *);
+	static void   AGS_EditorShutdown();
+	static void   AGS_EditorProperties(HWND);
+	static int    AGS_EditorSaveGame(char *, int);
+	static void   AGS_EditorLoadGame(char *, int);
+	static void   AGS_EngineStartup(IAGSEngine *);
+	static void   AGS_EngineShutdown();
+	static int    AGS_EngineOnEvent(int, int);
+	static int    AGS_EngineDebugHook(const char *, int, int);
+	static void   AGS_EngineInitGfx(const char *driverID, void *data);
+public:
+	DLL();
+
+	void *operator[](const Common::String &methodName) const {
+		return _methods[methodName];
+	}
+};
+
+extern void *dlopen(const char *filename);
+
+extern int dlclose(void *lib);
+
+extern void *dlsym(void *lib, const char *method);
+
+extern const char *dlerror();
+
+} // namespace Plugins
+} // namespace AGS
+
+#endif


Commit: 72eec8f2202ec369c33cbb038ee4f8b525981f40
    https://github.com/scummvm/scummvm/commit/72eec8f2202ec369c33cbb038ee4f8b525981f40
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Add script method stubs for AgsCreditZ

Changed paths:
    engines/ags/plugins/agscreditz/agscreditz.cpp
    engines/ags/plugins/agscreditz/agscreditz.h
    engines/ags/plugins/dll.cpp
    engines/ags/plugins/dll.h


diff --git a/engines/ags/plugins/agscreditz/agscreditz.cpp b/engines/ags/plugins/agscreditz/agscreditz.cpp
index 2c53d438fa..bae5322bc0 100644
--- a/engines/ags/plugins/agscreditz/agscreditz.cpp
+++ b/engines/ags/plugins/agscreditz/agscreditz.cpp
@@ -27,13 +27,109 @@ namespace Plugins {
 namespace AgsCreditz {
 
 AgsCreditz::AgsCreditz() {
-	ADD_METHOD(AGS_GetPluginName);
+	DLL_METHOD(AGS_GetPluginName);
+	DLL_METHOD(AGS_EngineStartup);
 }
 
 const char *AgsCreditz::AGS_GetPluginName() {
 	return "agsCreditz v1.1 by AJA";
 }
 
+void AgsCreditz::AGS_EngineStartup(IAGSEngine *engine) {
+	SCRIPT_METHOD(SetCredit);
+	SCRIPT_METHOD(ScrollCredits);
+	SCRIPT_METHOD(GetCredit);
+	SCRIPT_METHOD(IsCreditScrollingFinished);
+	SCRIPT_METHOD(SetCreditImage);
+	SCRIPT_METHOD(PauseScroll);
+	SCRIPT_METHOD(ScrollReset);
+	SCRIPT_METHOD(SetEmptyLineHeight);
+	SCRIPT_METHOD(GetEmptyLineHeight);
+	SCRIPT_METHOD(SetStaticCredit);
+	SCRIPT_METHOD(GetStaticCredit);
+	SCRIPT_METHOD(StartEndStaticCredits);
+	SCRIPT_METHOD(GetCurrentStaticCredit);
+	SCRIPT_METHOD(SetDefaultStaticDelay);
+	SCRIPT_METHOD(SetStaticPause);
+	SCRIPT_METHOD(SetStaticCreditTitle);
+	SCRIPT_METHOD(ShowStaticCredit);
+	SCRIPT_METHOD(StaticReset);
+	SCRIPT_METHOD(GetStaticCreditTitle);
+	SCRIPT_METHOD(SetStaticCreditImage);
+	SCRIPT_METHOD(IsStaticCreditsFinished);
+}
+
+void AgsCreditz::SetCredit(int ID, string credit, int colour, int font, int center, int xpos, int generateoutline) {
+}
+
+void AgsCreditz::ScrollCredits(int onoff, int speed, int fromY, int toY, int isautom, int wait, int res) {
+}
+
+string AgsCreditz::GetCredit(int ID) {
+	return string();
+}
+
+int AgsCreditz::IsCreditScrollingFinished() {
+	return true;
+}
+
+void AgsCreditz::SetCreditImage(int ID, int Slot, int center, int xpos, int pixtonext) {
+}
+
+void AgsCreditz::PauseScroll(int onoff) {
+}
+
+void AgsCreditz::ScrollReset() {
+}
+
+void AgsCreditz::SetEmptyLineHeight(int Height) {
+}
+
+int AgsCreditz::GetEmptyLineHeight() {
+	return 0;
+}
+
+void AgsCreditz::SetStaticCredit(int ID, int x, int y, int creditfont, int creditcolour, int centered, int generateoutline, string credit) {
+
+}
+
+string AgsCreditz::GetStaticCredit(int ID) {
+	return string();
+}
+
+void AgsCreditz::StartEndStaticCredits(int onoff, int res) {
+}
+
+int AgsCreditz::GetCurrentStaticCredit() {
+	return 0;
+}
+
+void AgsCreditz::SetDefaultStaticDelay(int Cyclesperchar) {
+}
+
+void AgsCreditz::SetStaticPause(int ID, int length) {
+}
+
+void AgsCreditz::SetStaticCreditTitle(int ID, int x, int y, int titlefont, int titlecolour, int centered, int generateoutline, string title) {
+}
+
+void AgsCreditz::ShowStaticCredit(int ID, int time, int style, int transtime, int sound, int resolution) {
+}
+
+void AgsCreditz::StaticReset() {
+}
+
+string AgsCreditz::GetStaticCreditTitle(int ID) {
+	return string();
+}
+
+void AgsCreditz::SetStaticCreditImage(int ID, int x, int y, int Slot, int Hcentered, int Vcentered, int time) {
+}
+
+int AgsCreditz::IsStaticCreditsFinished() {
+	return true;
+}
+
 } // namespace AgsCreditz
 } // namespace Plugins
 } // namespace AGS
diff --git a/engines/ags/plugins/agscreditz/agscreditz.h b/engines/ags/plugins/agscreditz/agscreditz.h
index 25b5da8b0a..6096260218 100644
--- a/engines/ags/plugins/agscreditz/agscreditz.h
+++ b/engines/ags/plugins/agscreditz/agscreditz.h
@@ -7,7 +7,7 @@
  * 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.
+ * 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
@@ -32,6 +32,29 @@ namespace AgsCreditz {
 class AgsCreditz : public DLL {
 private:
 	static const char *AGS_GetPluginName();
+	static void AGS_EngineStartup(IAGSEngine *engine);
+
+	static void SetCredit(int ID, string credit, int colour, int font, int center, int xpos, int generateoutline);
+	static void ScrollCredits(int onoff, int speed, int fromY, int toY, int isautom, int wait, int res);
+	static string GetCredit(int ID);
+	static int IsCreditScrollingFinished();
+	static void SetCreditImage(int ID, int Slot, int center, int xpos, int pixtonext);
+	static void PauseScroll(int onoff);
+	static void ScrollReset();
+	static void SetEmptyLineHeight(int Height);
+	static int GetEmptyLineHeight();
+	static void SetStaticCredit(int ID, int x, int y, int creditfont, int creditcolour, int centered, int generateoutline, string credit);
+	static string GetStaticCredit(int ID);
+	static void StartEndStaticCredits(int onoff, int res);
+	static int GetCurrentStaticCredit();
+	static void SetDefaultStaticDelay(int Cyclesperchar);
+	static void SetStaticPause(int ID, int length);
+	static void SetStaticCreditTitle(int ID, int x, int y, int titlefont, int titlecolour, int centered, int generateoutline, string title);
+	static void ShowStaticCredit(int ID, int time, int style, int transtime, int sound, int resolution);
+	static void StaticReset();
+	static string GetStaticCreditTitle(int ID);
+	static void SetStaticCreditImage(int ID, int x, int y, int Slot, int Hcentered, int Vcentered, int time);
+	static int IsStaticCreditsFinished();
 public:
 	AgsCreditz();
 };
diff --git a/engines/ags/plugins/dll.cpp b/engines/ags/plugins/dll.cpp
index 65d6d13f6c..405cecee6b 100644
--- a/engines/ags/plugins/dll.cpp
+++ b/engines/ags/plugins/dll.cpp
@@ -53,17 +53,17 @@ const char *dlerror() {
 /*------------------------------------------------------------------*/
 
 DLL::DLL() {
-	ADD_METHOD(AGS_PluginV2);
-	ADD_METHOD(AGS_EditorStartup);
-	ADD_METHOD(AGS_EditorShutdown);
-	ADD_METHOD(AGS_EditorProperties);
-	ADD_METHOD(AGS_EditorSaveGame);
-	ADD_METHOD(AGS_EditorLoadGame);
-	ADD_METHOD(AGS_EngineStartup);
-	ADD_METHOD(AGS_EngineShutdown);
-	ADD_METHOD(AGS_EngineOnEvent);
-	ADD_METHOD(AGS_EngineDebugHook);
-	ADD_METHOD(AGS_EngineInitGfx);
+	DLL_METHOD(AGS_PluginV2);
+	DLL_METHOD(AGS_EditorStartup);
+	DLL_METHOD(AGS_EditorShutdown);
+	DLL_METHOD(AGS_EditorProperties);
+	DLL_METHOD(AGS_EditorSaveGame);
+	DLL_METHOD(AGS_EditorLoadGame);
+	DLL_METHOD(AGS_EngineStartup);
+	DLL_METHOD(AGS_EngineShutdown);
+	DLL_METHOD(AGS_EngineOnEvent);
+	DLL_METHOD(AGS_EngineDebugHook);
+	DLL_METHOD(AGS_EngineInitGfx);
 }
 
 int DLL::AGS_EditorStartup(IAGSEditor *) {
diff --git a/engines/ags/plugins/dll.h b/engines/ags/plugins/dll.h
index abe2edd14b..e3fedacf88 100644
--- a/engines/ags/plugins/dll.h
+++ b/engines/ags/plugins/dll.h
@@ -23,16 +23,22 @@
 #ifndef AGS_PLUGINS_DLL_H
 #define AGS_PLUGINS_DLL_H
 
+#include "ags/shared/util/string.h"
+#include "ags/engine/plugin/agsplugin.h"
 #include "common/hashmap.h"
 #include "common/hash-str.h"
 
 namespace AGS {
 namespace Plugins {
 
-#define ADD_METHOD(NAME) _methods[#NAME] = (void *)&NAME
+#define DLL_METHOD(NAME) _methods[#NAME] = (void *)&NAME
+#define SCRIPT_METHOD(NAME) engine->RegisterScriptFunction(#NAME, (void *)&NAME)
 
-typedef void *IAGSEditor;
-typedef void *IAGSEngine;
+// TODO: Refactor string into core AGS namespace
+using string = ::AGS3::AGS::Shared::String;
+
+using IAGSEngine = ::AGS3::IAGSEngine;
+using IAGSEditor = ::AGS3::IAGSEditor;
 typedef uint32 HWND;
 
 /**


Commit: 5a8c96982a4be791e947c5215c6d86b153babf01
    https://github.com/scummvm/scummvm/commit/5a8c96982a4be791e947c5215c6d86b153babf01
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Set ManagedSurface palette when blitting to screen

Changed paths:
    engines/ags/lib/allegro/color.cpp
    engines/ags/lib/allegro/color.h
    engines/ags/lib/allegro/gfx.cpp


diff --git a/engines/ags/lib/allegro/color.cpp b/engines/ags/lib/allegro/color.cpp
index 5bd931a7e7..9bbe56d2ec 100644
--- a/engines/ags/lib/allegro/color.cpp
+++ b/engines/ags/lib/allegro/color.cpp
@@ -63,6 +63,16 @@ void set_palette_range(const PALETTE p, int from, int to, int retracesync) {
 	}
 }
 
+void palette_to_rgb8(const PALETTE src, byte dest[PALETTE_SIZE]) {
+	byte *pDest = dest;
+	for (int i = 0; i < 256; ++i, pDest += 3) {
+		pDest[0] = src[i].r;
+		pDest[1] = src[i].g;
+		pDest[2] = src[i].b;
+	}
+}
+
+
 int makecol15(int r, int g, int b) {
 	return (((r >> 3) << _rgb_r_shift_15) |
 		((g >> 3) << _rgb_g_shift_15) |
diff --git a/engines/ags/lib/allegro/color.h b/engines/ags/lib/allegro/color.h
index 8dc105c491..f0a25c0600 100644
--- a/engines/ags/lib/allegro/color.h
+++ b/engines/ags/lib/allegro/color.h
@@ -24,6 +24,7 @@
 #define AGS_LIB_ALLEGRO_COLOR_H
 
 #include "common/scummsys.h"
+#include "graphics/screen.h"
 #include "ags/lib/allegro/base.h"
 #include "ags/lib/allegro/alconfig.h"
 
@@ -89,6 +90,7 @@ AL_ARRAY(int, _rgb_scale_6);
 AL_FUNC(void, set_color, (int idx, AL_CONST RGB *p));
 AL_FUNC(void, set_palette, (AL_CONST PALETTE p));
 AL_FUNC(void, set_palette_range, (AL_CONST PALETTE p, int from, int to, int retracesync));
+AL_FUNC(void, palette_to_rgb8, (AL_CONST PALETTE src, byte dest[PALETTE_SIZE]));
 
 AL_FUNC(void, get_color, (int idx, RGB *p));
 AL_FUNC(void, get_palette, (PALETTE p));
diff --git a/engines/ags/lib/allegro/gfx.cpp b/engines/ags/lib/allegro/gfx.cpp
index fe8f3e6d9c..492bae84fc 100644
--- a/engines/ags/lib/allegro/gfx.cpp
+++ b/engines/ags/lib/allegro/gfx.cpp
@@ -169,6 +169,12 @@ void blit(const BITMAP *src, BITMAP *dest, int src_x, int src_y, int dst_x, int
 	Graphics::ManagedSurface &srcS = **src;
 	Graphics::ManagedSurface &destS = **dest;
 
+	if (srcS.format.bytesPerPixel == 1 && dest->format.bytesPerPixel > 1) {
+		byte pal[PALETTE_SIZE];
+		palette_to_rgb8(_current_palette, pal);
+		srcS.setPalette(pal, 0, PALETTE_COUNT);
+	}
+
 	destS.blitFrom(srcS, Common::Rect(src_x, src_y, src_x + width, src_y + height), Common::Point(dst_x, dst_y));
 }
 


Commit: 27775a43d1de57db4a97f9a8f90433ddd3dc16ca
    https://github.com/scummvm/scummvm/commit/27775a43d1de57db4a97f9a8f90433ddd3dc16ca
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Reimplement std::map from scratch

Previously it was an alias for Common::HashMap, but map needs
to have an array of key/value items ordered by the key.
As such, I changed it to internally use a Common::Array

Changed paths:
    engines/ags/engine/ac/dynobj/scriptdict.h
    engines/ags/lib/std/map.h


diff --git a/engines/ags/engine/ac/dynobj/scriptdict.h b/engines/ags/engine/ac/dynobj/scriptdict.h
index 8d6210da27..89a8cb76e5 100644
--- a/engines/ags/engine/ac/dynobj/scriptdict.h
+++ b/engines/ags/engine/ac/dynobj/scriptdict.h
@@ -187,7 +187,7 @@ private:
 
 typedef ScriptDictImpl< std::map<String, String>, true, true > ScriptDict;
 // TODO: Not sure if current std::map implement works for LessThan to give a key ordering
-typedef ScriptDictImpl< std::map<String, String, IgnoreCase_Hash, IgnoreCase_LessThan>, true, false > ScriptDictCI;
+typedef ScriptDictImpl< std::map<String, String, IgnoreCase_LessThan>, true, false > ScriptDictCI;
 typedef ScriptDictImpl< std::unordered_map<String, String>, false, true > ScriptHashDict;
 typedef ScriptDictImpl< std::unordered_map<String, String, IgnoreCase_Hash, IgnoreCase_EqualTo>, false, false > ScriptHashDictCI;
 
diff --git a/engines/ags/lib/std/map.h b/engines/ags/lib/std/map.h
index a5f080952b..d4d2b87da5 100644
--- a/engines/ags/lib/std/map.h
+++ b/engines/ags/lib/std/map.h
@@ -29,40 +29,153 @@
 namespace AGS3 {
 namespace std {
 
-template<class Key, class Val, class HashFunc = Common::Hash<Key>,
-         class EqualFunc = Common::EqualTo<Key> >
-class map : public Common::HashMap<Key, Val, HashFunc, EqualFunc> {
+template<class Key, class Val, class CompFunc = Common::Less<Key> >
+class map {
+	struct KeyValue {
+		Key _key;
+		Val _value;
+	};
+private:
+	Common::Array<KeyValue> _items;
+	CompFunc _comp;
 public:
-	using iterator = typename Common::HashMap<Key, Val, HashFunc, EqualFunc>::iterator;
+	using iterator = typename Common::Array<KeyValue>::iterator;
+	using const_iterator = typename Common::Array<KeyValue>::const_iterator;
 
-	pair<Key, Val> insert(pair<Key, Val> elem) {
-		this->operator[](elem.first) = elem.second;
-		return elem;
+	/**
+	 * Clears the map
+	 */
+	void clear() {
+		_items.clear();
+	}
+
+	/**
+	 * Gets the iterator start
+	 */
+	iterator begin() {
+		return _items.begin();
+	}
+
+	/**
+	 * Get the iterator end
+	 */
+	iterator end() {
+		return _items.end();
+	}
+
+	/**
+	 * Get the const iterator start
+	 */
+	const_iterator begin() const {
+		return _items.begin();
+	}
+
+	/**
+	 * Get the const iterator end
+	 */
+	const_iterator end() const {
+		return _items.end();
+	}
+
+	/**
+	 * Returns an iterator for the first element of the map that is
+	 * not less than the given key
+	 */
+	const_iterator lower_bound(const Key &theKey) const {
+		const_iterator first = this->begin();
+		const_iterator it;
+		int count = _items.size(), step;
+
+		while (count > 0) {
+			it = first;
+			step = count / 2;
+			it += step;
+
+			if (_comp(it->_key, theKey)) {
+				first = ++it;
+				count -= step + 1;
+			} else {
+				count = step;
+			}
+		}
+
+		return first;
 	}
 
-	// FUNCTION TEMPLATE lower_bound
-	iterator lower_bound(Key &val) {
+	iterator lower_bound(const Key &theKey) {
+		iterator first = this->begin();
 		iterator it;
-		for (it = this->begin(); it != this->end(); ++it) {
-			if (it->_key >= val)
-				break;
+		int count = _items.size(), step;
+
+		while (count > 0) {
+			it = first;
+			step = count / 2;
+			it += step;
+
+			if (_comp(it->_key, theKey)) {
+				first = ++it;
+				count -= step + 1;
+			} else {
+				count = step;
+			}
 		}
 
-		return it;
+		return first;
 	}
 
 	/**
-	 * Checks if the maps have identical contents
+	 * Find the entry with the given key
 	 */
-	bool operator==(const map &rhs) {
-		if (this->size() != rhs.size())
-			return false;
-		for (iterator it = this->begin(); it != this->end(); ++it) {
-			if (!(it->_value == rhs[it->_key]))
-				return false;
+	iterator find(const Key &theKey) {
+		iterator it = this->lower_bound(theKey);
+
+		if (it != this->end() && it->_key == theKey)
+			return it;
+		return this->end();
+	}
+
+	const_iterator find(const Key &theKey) const {
+		const_iterator it = this->lower_bound(theKey);
+
+		if (it != this->end() && it->_key == theKey)
+			return it;
+		return this->end();
+	}
+
+	/**
+	 * Square brackets operator accesses items by key, creating if necessary
+	 */
+	Val &operator[](const Key &theKey) {
+		iterator it = this->lower_bound(theKey);
+		if (it == this->end() || it->_key != theKey) {
+			size_t idx = it - this->begin();
+			_items.insert_at(idx, KeyValue());
+			_items[idx]._key = theKey;
+			return _items[idx]._value;
+		} else {
+			return _items[it - this->begin()]._value;
 		}
+	}
+
+	/**
+	 * Erases an entry in the map
+	 */
+	iterator erase(iterator it) {
+		iterator next = it;
+		++next;
+		_items.remove_at(it - begin());
+		return next;
+	}
+
+	iterator erase(const Key &theKey) {
+		return erase(find(theKey));
+	}
 
-		return true;
+	/**
+	 * Returns the size of the map
+	 */
+	size_t size() const {
+		return _items.size();
 	}
 };
 


Commit: d2abe022bb8cbeac8c574a0a4fbb76a8371eaef1
    https://github.com/scummvm/scummvm/commit/d2abe022bb8cbeac8c574a0a4fbb76a8371eaef1
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Set palette if needed for other blitting methods

Changed paths:
    engines/ags/lib/allegro/gfx.cpp


diff --git a/engines/ags/lib/allegro/gfx.cpp b/engines/ags/lib/allegro/gfx.cpp
index 492bae84fc..21a8cdce17 100644
--- a/engines/ags/lib/allegro/gfx.cpp
+++ b/engines/ags/lib/allegro/gfx.cpp
@@ -165,15 +165,19 @@ int bitmap_mask_color(BITMAP *bmp) {
 	return surf.getTransparentColor();
 }
 
+void add_palette_if_needed(Graphics::ManagedSurface &src, Graphics::ManagedSurface &dest) {
+	if (src.format.bytesPerPixel == 1 && dest.format.bytesPerPixel > 1) {
+		byte pal[PALETTE_SIZE];
+		palette_to_rgb8(_current_palette, pal);
+		src.setPalette(pal, 0, PALETTE_COUNT);
+	}
+}
+
 void blit(const BITMAP *src, BITMAP *dest, int src_x, int src_y, int dst_x, int dst_y, int width, int height) {
 	Graphics::ManagedSurface &srcS = **src;
 	Graphics::ManagedSurface &destS = **dest;
 
-	if (srcS.format.bytesPerPixel == 1 && dest->format.bytesPerPixel > 1) {
-		byte pal[PALETTE_SIZE];
-		palette_to_rgb8(_current_palette, pal);
-		srcS.setPalette(pal, 0, PALETTE_COUNT);
-	}
+	add_palette_if_needed(srcS, destS);
 
 	destS.blitFrom(srcS, Common::Rect(src_x, src_y, src_x + width, src_y + height), Common::Point(dst_x, dst_y));
 }
@@ -183,6 +187,8 @@ void stretch_blit(const BITMAP *src, BITMAP *dest, int source_x, int source_y, i
 	Graphics::ManagedSurface &srcS = **src;
 	Graphics::ManagedSurface &destS = **dest;
 
+	add_palette_if_needed(srcS, destS);
+
 	destS.transBlitFrom(srcS, Common::Rect(source_x, source_y, source_x + source_width, source_y + source_height),
 		Common::Rect(dest_x, dest_y, dest_x + dest_width, dest_y + dest_height));
 }
@@ -191,6 +197,8 @@ void masked_blit(const BITMAP *src, BITMAP *dest, int src_x, int src_y, int dst_
 	Graphics::ManagedSurface &srcS = **src;
 	Graphics::ManagedSurface &destS = **dest;
 
+	add_palette_if_needed(srcS, destS);
+
 	destS.blitFrom(srcS, Common::Rect(src_x, src_y, src_x + width, src_y + height), Common::Point(dst_x, dst_y));
 }
 
@@ -199,6 +207,8 @@ void masked_stretch_blit(const BITMAP *src, BITMAP *dest, int source_x, int sour
 	Graphics::ManagedSurface &srcS = **src;
 	Graphics::ManagedSurface &destS = **dest;
 
+	add_palette_if_needed(srcS, destS);
+
 	destS.transBlitFrom(srcS, Common::Rect(source_x, source_y, source_x + source_width, source_y + source_height),
 		Common::Rect(dest_x, dest_y, dest_x + dest_width, dest_y + dest_height));
 }
@@ -207,6 +217,8 @@ void draw_sprite(BITMAP *bmp, const BITMAP *sprite, int x, int y) {
 	Graphics::ManagedSurface &bmpS = **bmp;
 	Graphics::ManagedSurface &spriteS = **sprite;
 
+	add_palette_if_needed(spriteS, bmpS);
+
 	bmpS.blitFrom(spriteS, Common::Point(x, y));
 }
 
@@ -214,6 +226,8 @@ void stretch_sprite(BITMAP *bmp, const BITMAP *sprite, int x, int y, int w, int
 	Graphics::ManagedSurface &bmpS = **bmp;
 	Graphics::ManagedSurface &spriteS = **sprite;
 
+	add_palette_if_needed(spriteS, bmpS);
+
 	bmpS.transBlitFrom(spriteS, Common::Rect(0, 0, sprite->w, sprite->h),
 		Common::Rect(x, y, x + w, y + h));
 }


Commit: 4e675ea29eb2c7239520742e6db4e284cc99b54b
    https://github.com/scummvm/scummvm/commit/4e675ea29eb2c7239520742e6db4e284cc99b54b
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Implement clipping methods, fixing rendering of text dialogs

Changed paths:
    engines/ags/lib/allegro/gfx.cpp


diff --git a/engines/ags/lib/allegro/gfx.cpp b/engines/ags/lib/allegro/gfx.cpp
index 21a8cdce17..e25484370e 100644
--- a/engines/ags/lib/allegro/gfx.cpp
+++ b/engines/ags/lib/allegro/gfx.cpp
@@ -33,7 +33,7 @@ int color_conversion;
 
 BITMAP::BITMAP(Graphics::ManagedSurface *owner) : _owner(owner),
 		w(owner->w), h(owner->h), format(owner->format),
-		clip(false), ct(0), cb(0), cl(0), cr(0) {
+		clip(false), ct(0), cl(0), cr(owner->w), cb(owner->h) {
 	line.resize(h);
 	for (uint y = 0; y < h; ++y)
 		line[y] = (byte *)_owner->getBasePtr(0, y);
@@ -128,16 +128,25 @@ void destroy_bitmap(BITMAP *bitmap) {
 }
 
 void set_clip_rect(BITMAP *bitmap, int x1, int y1, int x2, int y2) {
-	warning("TODO: set_clip_rect");
+	bitmap->cl = x1;
+	bitmap->ct = y1;
+	bitmap->cr = x2;
+	bitmap->cb = y2;
 }
 
-void add_clip_rect(BITMAP *bitmap, int x1, int y1, int x2, int y2) {
-	warning("TODO: add_clip_rect");
+void get_clip_rect(BITMAP *bitmap, int *x1, int *y1, int *x2, int *y2) {
+	if (x1)
+		*x1 = bitmap->cl;
+	if (y1)
+		*y1 = bitmap->ct;
+	if (x2)
+		*x2 = bitmap->cr;
+	if (y2)
+		*y2 = bitmap->cb;
 }
 
-void get_clip_rect(BITMAP *bitmap, int *x1, int *y1, int *x2, int *y2) {
-	warning("TODO: get_clip_rect");
-	*x1 = *y1 = *x2 = *y2 = 0;
+void add_clip_rect(BITMAP *bitmap, int x1, int y1, int x2, int y2) {
+	warning("TODO: add_clip_rect");
 }
 
 void acquire_bitmap(BITMAP *bitmap) {


Commit: b61dd2c633c02e55571c64b4b3b43dcc00a6b75e
    https://github.com/scummvm/scummvm/commit/b61dd2c633c02e55571c64b4b3b43dcc00a6b75e
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Hook up ScummVM window close to exit game

Changed paths:
    engines/ags/engine/main/engine.cpp
    engines/ags/events.cpp


diff --git a/engines/ags/engine/main/engine.cpp b/engines/ags/engine/main/engine.cpp
index b90cee75c1..626e7ce4dc 100644
--- a/engines/ags/engine/main/engine.cpp
+++ b/engines/ags/engine/main/engine.cpp
@@ -143,18 +143,11 @@ void engine_setup_allegro() {
 	override_config_data(al_config_data, ustrsize(al_config_data));
 }
 
-void winclosehook() {
-	want_exit = 1;
-	abort_engine = 1;
-	check_dynamic_sprites_at_exit = 0;
-}
-
 void engine_setup_window() {
 	Debug::Printf(kDbgMsg_Info, "Setting up window");
 
 	our_eip = -198;
 	//set_window_title("Adventure Game Studio");
-	set_close_button_callback(winclosehook);
 	our_eip = -197;
 
 	platform->SetGameWindowIcon();
diff --git a/engines/ags/events.cpp b/engines/ags/events.cpp
index be261c0d13..c96279ad88 100644
--- a/engines/ags/events.cpp
+++ b/engines/ags/events.cpp
@@ -23,6 +23,11 @@
 #include "ags/events.h"
 #include "common/system.h"
 
+namespace AGS3 {
+extern volatile char want_exit, abort_engine;
+extern char check_dynamic_sprites_at_exit;
+}
+
 namespace AGS {
 
 EventsManager *g_events;
@@ -39,7 +44,12 @@ void EventsManager::pollEvents() {
 	Common::Event e;
 
 	while (g_system->getEventManager()->pollEvent(e)) {
-		if (e.type == Common::EVENT_KEYDOWN) {
+		if (e.type == Common::EVENT_QUIT) {
+			::AGS3::want_exit = 1;
+			::AGS3::abort_engine = 1;
+			::AGS3::check_dynamic_sprites_at_exit = 0;
+
+		} else if (e.type == Common::EVENT_KEYDOWN) {
 			// Add keypresses to the pending key list
 			_pendingKeys.push(e.kbd.keycode);
 		} else {


Commit: 618e89c704b44f3f002631c39b1cb030a93586b8
    https://github.com/scummvm/scummvm/commit/618e89c704b44f3f002631c39b1cb030a93586b8
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix free after delete in PosixLibrary unload

Changed paths:
    engines/ags/engine/util/library_posix.h
    engines/ags/plugins/dll.cpp


diff --git a/engines/ags/engine/util/library_posix.h b/engines/ags/engine/util/library_posix.h
index ceb39cf21b..a966281fa9 100644
--- a/engines/ags/engine/util/library_posix.h
+++ b/engines/ags/engine/util/library_posix.h
@@ -113,7 +113,10 @@ public:
 
 	bool Unload() override {
 		if (_library) {
-			return (dlclose(_library) == 0);
+			void *lib = _library;
+			_library = nullptr;
+
+			return (dlclose(lib) == 0);
 		} else {
 			return true;
 		}
diff --git a/engines/ags/plugins/dll.cpp b/engines/ags/plugins/dll.cpp
index 405cecee6b..a964949027 100644
--- a/engines/ags/plugins/dll.cpp
+++ b/engines/ags/plugins/dll.cpp
@@ -37,7 +37,8 @@ void *dlopen(const char *filename) {
 }
 
 int dlclose(void *lib) {
-	delete lib;
+	DLL *dll = static_cast<DLL *>(lib);
+	delete dll;
 	return 0;
 }
 


Commit: 732f5bac919830cb48064affeaf127cbdb85b659
    https://github.com/scummvm/scummvm/commit/732f5bac919830cb48064affeaf127cbdb85b659
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Disable save_config_file

Changed paths:
    engines/ags/engine/main/config.cpp


diff --git a/engines/ags/engine/main/config.cpp b/engines/ags/engine/main/config.cpp
index 52a6dee9c4..7f5d52e193 100644
--- a/engines/ags/engine/main/config.cpp
+++ b/engines/ags/engine/main/config.cpp
@@ -568,6 +568,8 @@ void post_config() {
 }
 
 void save_config_file() {
+// Change to use ScummVM configuration
+#ifdef TODO
 	ConfigTree cfg;
 
 	// Last display mode
@@ -602,6 +604,7 @@ void save_config_file() {
 	String cfg_file = find_user_cfg_file();
 	if (!cfg_file.IsEmpty())
 		IniUtil::Merge(cfg_file, cfg);
+#endif
 }
 
 } // namespace AGS3


Commit: 3155da5ed4866b1ab596d3e20a59a3d700b1aa8b
    https://github.com/scummvm/scummvm/commit/3155da5ed4866b1ab596d3e20a59a3d700b1aa8b
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Allow graceful exit after call to quit

Changed paths:
    engines/ags/ags.cpp
    engines/ags/engine/main/engine.cpp
    engines/ags/engine/main/quit.cpp


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index a7289c88be..f52f74ef76 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -130,6 +130,7 @@ Version SavedgameLowestBackwardCompatVersion;
 // Lowest engine version, which would accept current savedgames
 Version SavedgameLowestForwardCompatVersion;
 
+extern void quit_free();
 
 void main_pre_init() {
 	our_eip = -999;
@@ -390,8 +391,10 @@ Common::Error AGSEngine::run() {
 #endif
 	{
 		int result = AGS3::initialize_engine(startup_opts);
-		// TODO: refactor engine shutdown routine (must shutdown and delete everything started and created)
-		AGS3::platform->PostAllegroExit();
+
+		// Do shutdown stuff
+		::AGS3::quit_free();
+
 		return result ? Common::kUnknownError : Common::kNoError;
 	}
 #ifdef USE_CUSTOM_EXCEPTION_HANDLER
diff --git a/engines/ags/engine/main/engine.cpp b/engines/ags/engine/main/engine.cpp
index 626e7ce4dc..3aff7ea660 100644
--- a/engines/ags/engine/main/engine.cpp
+++ b/engines/ags/engine/main/engine.cpp
@@ -1464,7 +1464,6 @@ int initialize_engine(const ConfigTree &startup_opts) {
 
 	initialize_start_and_play_game(override_start_room, loadSaveGameOnStartup);
 
-	quit("|bye!");
 	return EXIT_NORMAL;
 }
 
diff --git a/engines/ags/engine/main/quit.cpp b/engines/ags/engine/main/quit.cpp
index 9158366712..f8fa75c215 100644
--- a/engines/ags/engine/main/quit.cpp
+++ b/engines/ags/engine/main/quit.cpp
@@ -67,6 +67,7 @@ extern IAGSEditorDebugger *editor_debugger;
 extern int need_to_stop_cd;
 extern int use_cdplayer;
 extern IGraphicsDriver *gfxDriver;
+extern volatile char abort_engine;
 
 bool handledErrorInEditor;
 
@@ -221,6 +222,8 @@ void allegro_bitmap_test_release() {
 
 char return_to_roomedit[30] = "\0";
 char return_to_room[150] = "\0";
+char quit_message[256] = "\0";
+
 // quit - exits the engine, shutting down everything gracefully
 // The parameter is the message to print. If this message begins with
 // an '!' character, then it is printed as a "contact game author" error.
@@ -229,11 +232,17 @@ char return_to_room[150] = "\0";
 // error.
 // "!|" is a special code used to mean that the player has aborted (Alt+X)
 void quit(const char *quitmsg) {
+	strncpy(quit_message, quitmsg, 256);
+	abort_engine = true;
+}
+
+void quit_free() {
 	String alertis;
+	if (strlen(quit_message) == 0)
+		strcpy(quit_message, "|bye!");
+
+	const char *quitmsg = quit_message;
 	QuitReason qreason = quit_check_for_error_state(quitmsg, alertis);
-	// Need to copy it in case it's from a plugin (since we're
-	// about to free plugins)
-	String qmsg = quitmsg;
 
 	if (qreason & kQuitKind_NormalExit)
 		save_config_file();
@@ -242,7 +251,7 @@ void quit(const char *quitmsg) {
 
 	handledErrorInEditor = false;
 
-	quit_tell_editor_debugger(qmsg, qreason);
+	quit_tell_editor_debugger(quit_message, qreason);
 
 	our_eip = 9900;
 
@@ -275,7 +284,7 @@ void quit(const char *quitmsg) {
 
 	engine_shutdown_gfxmode();
 
-	quit_message_on_exit(qmsg, alertis, qreason);
+	quit_message_on_exit(quitmsg, alertis, qreason);
 
 	quit_release_data();
 
@@ -297,7 +306,6 @@ void quit(const char *quitmsg) {
 	shutdown_debug();
 
 	our_eip = 9904;
-	error("%s", qmsg.GetNullableCStr());
 }
 
 extern "C" {


Commit: 522312989ce8ed0da897b50e79714416a58d3306
    https://github.com/scummvm/scummvm/commit/522312989ce8ed0da897b50e79714416a58d3306
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Set the transparent color on all created surfaces

Changed paths:
    engines/ags/lib/allegro/gfx.h


diff --git a/engines/ags/lib/allegro/gfx.h b/engines/ags/lib/allegro/gfx.h
index 7d83d2b8ed..e0428d0aa5 100644
--- a/engines/ags/lib/allegro/gfx.h
+++ b/engines/ags/lib/allegro/gfx.h
@@ -227,10 +227,16 @@ public:
 	Surface(int width, int height) : Graphics::ManagedSurface(width, height), BITMAP(this) {
 	}
 	Surface(int width, int height, const Graphics::PixelFormat &pixelFormat) :
-		Graphics::ManagedSurface(width, height, pixelFormat), BITMAP(this) {
+			Graphics::ManagedSurface(width, height, pixelFormat), BITMAP(this) {
+		// Allegro uses 255, 0, 255 RGB as the transparent color
+		if (pixelFormat.bytesPerPixel == 4)
+			setTransparentColor(pixelFormat.RGBToColor(255, 0, 255));
 	}
 	Surface(Graphics::ManagedSurface &surf, const Common::Rect &bounds) :
-		Graphics::ManagedSurface(surf, bounds), BITMAP(this) {
+			Graphics::ManagedSurface(surf, bounds), BITMAP(this) {
+		// Allegro uses 255, 0, 255 RGB as the transparent color
+		if (surf.format.bytesPerPixel == 4)
+			setTransparentColor(surf.format.RGBToColor(255, 0, 255));
 	}
 	~Surface() override {
 	}


Commit: 527d73e0e6f99408a393758c29e560ce5c6d7902
    https://github.com/scummvm/scummvm/commit/527d73e0e6f99408a393758c29e560ce5c6d7902
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Handle sprite transparency for cursors

Changed paths:
    engines/ags/lib/allegro/gfx.cpp


diff --git a/engines/ags/lib/allegro/gfx.cpp b/engines/ags/lib/allegro/gfx.cpp
index e25484370e..43eaf29d78 100644
--- a/engines/ags/lib/allegro/gfx.cpp
+++ b/engines/ags/lib/allegro/gfx.cpp
@@ -228,7 +228,10 @@ void draw_sprite(BITMAP *bmp, const BITMAP *sprite, int x, int y) {
 
 	add_palette_if_needed(spriteS, bmpS);
 
-	bmpS.blitFrom(spriteS, Common::Point(x, y));
+	// For Allegro, paletted sprites always use index 0 as the transparent color,
+	// and for higher resolution formats uses bright pink RGB 255, 0, 255
+	bmpS.transBlitFrom(spriteS, Common::Point(x, y),
+		(spriteS.format.bytesPerPixel == 1) ? 0 : spriteS.format.RGBToColor(255, 0, 255));
 }
 
 void stretch_sprite(BITMAP *bmp, const BITMAP *sprite, int x, int y, int w, int h) {


Commit: 5aa27892c6e9e1981fc94ee102741ec7002ceb7a
    https://github.com/scummvm/scummvm/commit/5aa27892c6e9e1981fc94ee102741ec7002ceb7a
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Implementing drawing code used by pathfinder

Changed paths:
  A engines/ags/lib/allegro/flood.cpp
  A engines/ags/lib/allegro/flood.h
    engines/ags/lib/allegro/draw.cpp
    engines/ags/lib/allegro/draw.h
    engines/ags/lib/allegro/gfx.cpp
    engines/ags/lib/allegro/gfx.h
    engines/ags/module.mk
    engines/ags/shared/gfx/allegrobitmap.cpp


diff --git a/engines/ags/lib/allegro/draw.cpp b/engines/ags/lib/allegro/draw.cpp
index e6b467557d..fba3b446a2 100644
--- a/engines/ags/lib/allegro/draw.cpp
+++ b/engines/ags/lib/allegro/draw.cpp
@@ -24,8 +24,81 @@
 
 namespace AGS3 {
 
-void do_line(BITMAP *bmp, int x1, int y_1, int x2, int y2, int d, DrawMethod proc) {
-	warning("TODO: do_line");
+void do_line(BITMAP *bmp, int x1, int y1, int x2, int y2, int d, DrawMethod proc) {
+	int dx = x2 - x1;
+	int dy = y2 - y1;
+	int i1, i2;
+	int x, y;
+	int dd;
+
+	/* worker macro */
+	#define DO_LINE(pri_sign, pri_c, pri_cond, sec_sign, sec_c, sec_cond)     \
+	{                                                                         \
+		if (d##pri_c == 0) {                                                  \
+		    proc(bmp, x1, y1, d);                                             \
+		    return;                                                           \
+		}                                                                     \
+											                                  \
+		i1 = 2 * d##sec_c;                                                    \
+		dd = i1 - (sec_sign (pri_sign d##pri_c));                             \
+		i2 = dd - (sec_sign (pri_sign d##pri_c));                             \
+											                                  \
+		x = x1;                                                               \
+		y = y1;                                                               \
+											                                  \
+		while (pri_c pri_cond pri_c##2) {                                     \
+		    proc(bmp, x, y, d);                                               \
+											                                  \
+		    if (dd sec_cond 0) {                                              \
+		        sec_c = sec_c sec_sign 1;                                     \
+		        dd += i2;                                                     \
+		    }                                                                 \
+		    else                                                              \
+		        dd += i1;                                                     \
+											                                  \
+		    pri_c = pri_c pri_sign 1;                                         \
+		}                                                                     \
+	}
+
+	if (dx >= 0) {
+		if (dy >= 0) {
+			if (dx >= dy) {
+				/* (x1 <= x2) && (y1 <= y2) && (dx >= dy) */
+				DO_LINE(+, x, <= , +, y, >= );
+			} else {
+				/* (x1 <= x2) && (y1 <= y2) && (dx < dy) */
+				DO_LINE(+, y, <= , +, x, >= );
+			}
+		} else {
+			if (dx >= -dy) {
+				/* (x1 <= x2) && (y1 > y2) && (dx >= dy) */
+				DO_LINE(+, x, <= , -, y, <= );
+			} else {
+				/* (x1 <= x2) && (y1 > y2) && (dx < dy) */
+				DO_LINE(-, y, >= , +, x, >= );
+			}
+		}
+	} else {
+		if (dy >= 0) {
+			if (-dx >= dy) {
+				/* (x1 > x2) && (y1 <= y2) && (dx >= dy) */
+				DO_LINE(-, x, >= , +, y, >= );
+			} else {
+				/* (x1 > x2) && (y1 <= y2) && (dx < dy) */
+				DO_LINE(+, y, <= , -, x, <= );
+			}
+		} else {
+			if (-dx >= -dy) {
+				/* (x1 > x2) && (y1 > y2) && (dx >= dy) */
+				DO_LINE(-, x, >= , -, y, <= );
+			} else {
+				/* (x1 > x2) && (y1 > y2) && (dx < dy) */
+				DO_LINE(-, y, >= , -, x, <= );
+			}
+		}
+	}
+
+#undef DO_LINE
 }
 
 } // namespace AGS3
diff --git a/engines/ags/lib/allegro/draw.h b/engines/ags/lib/allegro/draw.h
index 3e16ff8f2e..5c3497a074 100644
--- a/engines/ags/lib/allegro/draw.h
+++ b/engines/ags/lib/allegro/draw.h
@@ -30,7 +30,7 @@ namespace AGS3 {
 
 typedef void (*DrawMethod)(BITMAP *, int, int, int);
 
-AL_FUNC(void, do_line, (BITMAP *bmp, int x1, int y_1, int x2, int y2, int d, DrawMethod proc));
+extern void do_line(BITMAP *bmp, int x1, int y1, int x2, int y2, int d, DrawMethod proc);
 
 } // namespace AGS3
 
diff --git a/engines/ags/lib/allegro/flood.cpp b/engines/ags/lib/allegro/flood.cpp
new file mode 100644
index 0000000000..e5794ce29c
--- /dev/null
+++ b/engines/ags/lib/allegro/flood.cpp
@@ -0,0 +1,227 @@
+/* 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 "ags/lib/allegro/flood.h"
+#include "ags/lib/allegro/gfx.h"
+#include "common/array.h"
+
+namespace AGS3 {
+
+struct FLOODED_LINE {
+	short flags;                  /* status of the segment */
+	short lpos, rpos;             /* left and right ends of segment */
+	short y;                      /* y coordinate of the segment */
+	int next;                     /* linked list if several per line */
+};
+
+#define FLOOD_IN_USE             1
+#define FLOOD_TODO_ABOVE         2
+#define FLOOD_TODO_BELOW         4
+
+#define FLOOD_LINE(c)            (&scratchMem[c])
+
+template<class SIZE>
+static bool scanLine(BITMAP *bmp, int x, int y, int src_color, int &left, int &right) {
+	// check start pixel
+	const SIZE *pixel = (const SIZE *)bmp->getBasePtr(x, y);
+	if (*pixel != src_color)
+		return false;
+
+	// Work left from starting point
+	const SIZE *pixelLeft = pixel - 1;
+	for (left = x - 1; left >= bmp->cl; left--, pixelLeft--) {
+		if (*pixelLeft != src_color)
+			break;
+	}
+
+	// Work right from starting point
+	const SIZE *pixelRight = pixel + 1;
+	for (right = x + 1; right < bmp->cr; right++, pixelRight++) {
+		if (*pixelRight != src_color)
+			break;
+	}
+
+	return true;
+}
+
+/**
+ *  Fills a horizontal line around the specified position, and adds it
+ *  to the list of drawn segments. Returns the first x coordinate after
+ *  the part of the line which it has dealt with.
+ */
+static int flooder(BITMAP *bmp, int x, int y, int src_color, int dest_color,
+		Common::Array<FLOODED_LINE> &scratchMem) {
+	FLOODED_LINE *p;
+	int left = 0, right = 0;
+	int c;
+
+	assert(bmp);
+
+	bool ret;
+	switch (bmp->format.bytesPerPixel) {
+	case 1: ret = scanLine<byte>(bmp, x, y, src_color, left, right); break;
+	case 2: ret = scanLine<byte>(bmp, x, y, src_color, left, right); break;
+	case 4: ret = scanLine<byte>(bmp, x, y, src_color, left, right); break;
+	default:
+		error("Unknown format");
+	}
+	if (!ret)
+		return x + 1;
+
+	left++;
+	right--;
+
+	/* draw the line */
+	bmp->hLine(left, y, right, dest_color);
+
+	/* store it in the list of flooded segments */
+	c = y;
+	p = FLOOD_LINE(c);
+
+	if (p->flags) {
+		while (p->next) {
+			c = p->next;
+			p = FLOOD_LINE(c);
+		}
+
+		p->next = c = scratchMem.size();
+		scratchMem.resize(scratchMem.size() + 1);
+		p = FLOOD_LINE(c);
+	}
+
+	p->flags = FLOOD_IN_USE;
+	p->lpos = left;
+	p->rpos = right;
+	p->y = y;
+	p->next = 0;
+
+	if (y > bmp->ct)
+		p->flags |= FLOOD_TODO_ABOVE;
+
+	if (y + 1 < bmp->cb)
+		p->flags |= FLOOD_TODO_BELOW;
+
+	return right + 2;
+}
+
+
+
+/**
+ *  Checks a line segment, using the scratch buffer is to store a list of
+ *  segments which have already been drawn in order to minimise the required
+ *  number of tests.
+ */
+static bool check_flood_line(BITMAP *bmp, int y, int left, int right, int src_color, int dest_color,
+		Common::Array<FLOODED_LINE> &scratchMem) {
+	int c;
+	FLOODED_LINE *p;
+	bool ret = false;
+
+	while (left <= right) {
+		c = y;
+
+		for (;;) {
+			p = FLOOD_LINE(c);
+
+			if ((left >= p->lpos) && (left <= p->rpos)) {
+				left = p->rpos + 2;
+				break;
+			}
+
+			c = p->next;
+
+			if (!c) {
+				left = flooder(bmp, left, y, src_color, dest_color, scratchMem);
+				ret = true;
+				break;
+			}
+		}
+	}
+
+	return ret;
+}
+
+void floodfill(BITMAP *bmp, int x, int y, int color) {
+	int src_color;
+	int c;
+	bool done;
+	FLOODED_LINE *p;
+	Common::Array<FLOODED_LINE> scratchMem;
+
+	/* make sure we have a valid starting point */
+	if ((x < bmp->cl) || (x >= bmp->cr) || (y < bmp->ct) || (y >= bmp->cb))
+		return;
+
+	/* what color to replace? */
+	src_color = getpixel(bmp, x, y);
+	if (src_color == color) {
+		return;
+	}
+
+	/* set up the list of flooded segments */
+	scratchMem.resize(bmp->cb);
+
+	p = FLOOD_LINE(0);
+	for (c = 0; c < (int)scratchMem.size(); c++) {
+		p[c].flags = 0;
+		p[c].lpos = SHRT_MAX;
+		p[c].rpos = SHRT_MIN;
+		p[c].y = y;
+		p[c].next = 0;
+	}
+
+	/* start up the flood algorithm */
+	flooder(bmp, x, y, src_color, color, scratchMem);
+
+	/* continue as long as there are some segments still to test */
+	do {
+		done = true;
+
+		/* for each line on the screen */
+		for (c = 0; c < (int)scratchMem.size(); c++) {
+			p = FLOOD_LINE(c);
+
+			/* check below the segment? */
+			if (p->flags & FLOOD_TODO_BELOW) {
+				p->flags &= ~FLOOD_TODO_BELOW;
+				if (check_flood_line(bmp, p->y + 1, p->lpos, p->rpos, src_color, color, scratchMem)) {
+					done = false;
+					p = FLOOD_LINE(c);
+				}
+			}
+
+			/* check above the segment? */
+			if (p->flags & FLOOD_TODO_ABOVE) {
+				p->flags &= ~FLOOD_TODO_ABOVE;
+				if (check_flood_line(bmp, p->y - 1, p->lpos, p->rpos, src_color, color, scratchMem)) {
+					done = false;
+					/* special case shortcut for going backwards */
+					if ((c < bmp->cb) && (c > 0))
+						c -= 2;
+				}
+			}
+		}
+
+	} while (!done);
+}
+
+} // namespace AGS3
diff --git a/engines/ags/lib/allegro/flood.h b/engines/ags/lib/allegro/flood.h
new file mode 100644
index 0000000000..0aa0874831
--- /dev/null
+++ b/engines/ags/lib/allegro/flood.h
@@ -0,0 +1,37 @@
+/* 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 AGS_LIB_ALLEGRO_FLOOD_H
+#define AGS_LIB_ALLEGRO_FLOOD_H
+
+#include "graphics/managed_surface.h"
+#include "ags/lib/allegro/base.h"
+
+namespace AGS3 {
+
+class BITMAP;
+
+extern void floodfill(BITMAP *bmp, int x, int y, int color);
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/lib/allegro/gfx.cpp b/engines/ags/lib/allegro/gfx.cpp
index 43eaf29d78..a98541c2bf 100644
--- a/engines/ags/lib/allegro/gfx.cpp
+++ b/engines/ags/lib/allegro/gfx.cpp
@@ -21,6 +21,7 @@
  */
 
 #include "ags/lib/allegro/gfx.h"
+#include "ags/lib/allegro/flood.h"
 #include "ags/ags.h"
 #include "common/textconsole.h"
 #include "graphics/screen.h"
@@ -52,6 +53,46 @@ int BITMAP::getpixel(int x, int y) const {
 		return *(const uint32 *)pixel;
 }
 
+void BITMAP::circlefill(int x, int y, int radius, int color) {
+	int cx = 0;
+	int cy = radius;
+	int df = 1 - radius;
+	int d_e = 3;
+	int d_se = -2 * radius + 5;
+
+	do {
+		_owner->hLine(x - cy, y - cx, x + cy, color);
+
+		if (cx)
+			_owner->hLine(x - cy, y + cx, x + cy, color);
+
+		if (df < 0) {
+			df += d_e;
+			d_e += 2;
+			d_se += 2;
+		} else {
+			if (cx != cy) {
+				_owner->hLine(x - cx, y - cy, x + cx, color);
+
+				if (cy)
+					_owner->hLine(x - cx, y + cy, x + cx, color);
+			}
+
+			df += d_se;
+			d_e += 2;
+			d_se += 4;
+			cy--;
+		}
+
+		cx++;
+
+	} while (cx <= cy);
+}
+
+void BITMAP::floodfill(int x, int y, int color) {
+	AGS3::floodfill(this, x, y, color);
+}
+
 /*-------------------------------------------------------------------*/
 
 /**
@@ -423,17 +464,12 @@ void triangle(BITMAP *bmp, int x1, int y1, int x2, int y2, int x3, int y3, int c
 	surf.drawLine(x3, y3, x1, y1, color);
 }
 
-void floodfill(BITMAP *bmp, int x, int y, int color) {
-	error("TODO: floodfill");
-}
-
 void circlefill(BITMAP *bmp, int x, int y, int radius, int color) {
-	error("TODO: circlefill");
+	bmp->circlefill(x, y, radius, color);
 }
 
 void clear_bitmap(BITMAP *bmp) {
 	bmp->clear();
 }
 
-
 } // namespace AGS3
diff --git a/engines/ags/lib/allegro/gfx.h b/engines/ags/lib/allegro/gfx.h
index e0428d0aa5..2af30ede9f 100644
--- a/engines/ags/lib/allegro/gfx.h
+++ b/engines/ags/lib/allegro/gfx.h
@@ -184,7 +184,8 @@ public:
 	Common::Array<byte *> line;
 public:
 	BITMAP(Graphics::ManagedSurface *owner);
-	virtual ~BITMAP() {}
+	virtual ~BITMAP() {
+	}
 
 	Graphics::ManagedSurface &operator*() const {
 		return *_owner;
@@ -213,6 +214,30 @@ public:
 	void clear() {
 		_owner->clear();
 	}
+
+	/**
+	 * Draws a solid filled in circle
+	 */
+	void circlefill(int x, int y, int radius, int color);
+
+	/**
+	 * Fills an enclosed area starting at a given point
+	 */
+	void floodfill(int x, int y, int color);
+
+	/**
+	 * Draw a horizontal line
+	 */
+	void hLine(int x, int y, int x2, uint32 color) {
+		_owner->hLine(x, y, x2, color);
+	}
+
+	/**
+	 * Draw a vertical line.
+	 */
+	void vLine(int x, int y, int y2, uint32 color) {
+		_owner->vLine(x, y, y2, color);
+	}
 };
 
 /**
@@ -305,7 +330,6 @@ extern void line(BITMAP *bmp, int x1, int y_1, int x2, int y2, int color);
 extern void rect(BITMAP *bmp, int x1, int y_1, int x2, int y2, int color);
 extern void rectfill(BITMAP *bmp, int x1, int y_1, int x2, int y2, int color);
 extern void triangle(BITMAP *bmp, int x1, int y_1, int x2, int y2, int x3, int y3, int color);
-extern void floodfill(BITMAP *bmp, int x, int y, int color);
 extern void circlefill(BITMAP *bmp, int x, int y, int radius, int color);
 
 } // namespace AGS3
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index eeda8d7f15..e19feb3a3c 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -17,6 +17,7 @@ MODULE_OBJS = \
 	lib/allegro/error.o \
 	lib/allegro/file.o \
 	lib/allegro/fixed.o \
+	lib/allegro/flood.o \
 	lib/allegro/gfx.o \
 	lib/allegro/graphics.o \
 	lib/allegro/keyboard.o \
diff --git a/engines/ags/shared/gfx/allegrobitmap.cpp b/engines/ags/shared/gfx/allegrobitmap.cpp
index 9071308340..f627868d7e 100644
--- a/engines/ags/shared/gfx/allegrobitmap.cpp
+++ b/engines/ags/shared/gfx/allegrobitmap.cpp
@@ -366,7 +366,7 @@ void Bitmap::FillTransparent() {
 }
 
 void Bitmap::FloodFill(int x, int y, color_t color) {
-	floodfill(_alBitmap, x, y, color);
+	_alBitmap->floodfill(x, y, color);
 }
 
 //=============================================================================


Commit: f8b95a5d34e9b9711047929a123eb0e1d67f7530
    https://github.com/scummvm/scummvm/commit/f8b95a5d34e9b9711047929a123eb0e1d67f7530
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix closing ScummVM window on title screen

Changed paths:
    engines/ags/engine/main/game_run.cpp
    engines/ags/engine/script/cc_instance.cpp


diff --git a/engines/ags/engine/main/game_run.cpp b/engines/ags/engine/main/game_run.cpp
index 1e82cc4714..c331315f41 100644
--- a/engines/ags/engine/main/game_run.cpp
+++ b/engines/ags/engine/main/game_run.cpp
@@ -946,7 +946,8 @@ static void GameLoopUntilEvent(int untilwhat, const void *daaa) {
 	auto cached_user_disabled_for = user_disabled_for;
 
 	SetupLoopParameters(untilwhat, daaa);
-	while (GameTick() == 0);
+	while (GameTick() == 0 && !abort_engine) {
+	}
 
 	our_eip = 78;
 
diff --git a/engines/ags/engine/script/cc_instance.cpp b/engines/ags/engine/script/cc_instance.cpp
index 4bc07dde52..5a4fd59f31 100644
--- a/engines/ags/engine/script/cc_instance.cpp
+++ b/engines/ags/engine/script/cc_instance.cpp
@@ -58,6 +58,7 @@ extern int maxWhileLoops;
 extern new_line_hook_type new_line_hook;
 
 extern ScriptString myScriptStringImpl;
+extern volatile char abort_engine;
 
 enum ScriptOpArgIsReg {
 	kScOpNoArgIsReg     = 0,
@@ -434,6 +435,8 @@ int ccInstance::Run(int32_t curpc) {
 	FunctionCallStack func_callstack;
 
 	while (1) {
+		if (abort_engine)
+			return -1;
 
 		/*
 		if (!codeInst->ReadOperation(codeOp, pc))


Commit: 765f9cbfee2ee5df16522bbbaca9cd22bd78af73
    https://github.com/scummvm/scummvm/commit/765f9cbfee2ee5df16522bbbaca9cd22bd78af73
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix cursor palette intensity

Changed paths:
    engines/ags/lib/allegro/color.cpp


diff --git a/engines/ags/lib/allegro/color.cpp b/engines/ags/lib/allegro/color.cpp
index 9bbe56d2ec..f66c1d19d7 100644
--- a/engines/ags/lib/allegro/color.cpp
+++ b/engines/ags/lib/allegro/color.cpp
@@ -30,6 +30,8 @@
 
 namespace AGS3 {
 
+#define VGA_COLOR_TRANS(x) ((x) * 255 / 63)
+
 int _rgb_r_shift_15 = 0;
 int _rgb_g_shift_15 = 0;
 int _rgb_b_shift_15 = 0;
@@ -66,9 +68,9 @@ void set_palette_range(const PALETTE p, int from, int to, int retracesync) {
 void palette_to_rgb8(const PALETTE src, byte dest[PALETTE_SIZE]) {
 	byte *pDest = dest;
 	for (int i = 0; i < 256; ++i, pDest += 3) {
-		pDest[0] = src[i].r;
-		pDest[1] = src[i].g;
-		pDest[2] = src[i].b;
+		pDest[0] = VGA_COLOR_TRANS(src[i].r);
+		pDest[1] = VGA_COLOR_TRANS(src[i].g);
+		pDest[2] = VGA_COLOR_TRANS(src[i].b);
 	}
 }
 


Commit: 02ddc563fd8cbd05f3a48b841710e8f1fa2107ec
    https://github.com/scummvm/scummvm/commit/02ddc563fd8cbd05f3a48b841710e8f1fa2107ec
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added engine methods for load/save game

Changed paths:
    engines/ags/ags.cpp
    engines/ags/ags.h
    engines/ags/engine/ac/game.cpp
    engines/ags/engine/main/engine.cpp


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index f52f74ef76..374d67cf6b 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -36,12 +36,14 @@
 
 #include "ags/lib/std/set.h"
 #include "ags/shared/ac/common.h"
+#include "ags/engine/ac/game.h"
 #include "ags/engine/ac/gamesetup.h"
 #include "ags/engine/ac/gamestate.h"
 #include "ags/shared/core/def_version.h"
 #include "ags/engine/debugging/debugger.h"
 #include "ags/engine/debugging/debug_log.h"
 #include "ags/shared/debugging/out.h"
+#include "ags/engine/game/savegame.h"
 #include "ags/engine/main/config.h"
 #include "ags/engine/main/engine.h"
 #include "ags/engine/main/mainheader.h"
@@ -64,6 +66,8 @@ extern char return_to_room[150];
 using namespace Shared;
 using namespace Engine;
 
+extern HSaveError load_game(const String &path, int slotNumber, bool &data_overwritten);
+
 String appDirectory; // Needed for library loading
 String cmdGameDataPath;
 
@@ -418,4 +422,15 @@ void AGSEngine::setGraphicsMode(size_t w, size_t h) {
 	_screen = new ::AGS3::BITMAP(_rawScreen);
 }
 
+Common::Error AGSEngine::loadGameState(int slot) {
+	bool dataOverwritten;
+	(void)AGS3::load_game("", slot, dataOverwritten);
+	return Common::kNoError;
+}
+
+Common::Error AGSEngine::saveGameState(int slot, const Common::String &desc, bool isAutosave) {
+	(void)AGS3::save_game(slot, desc.c_str());
+	return Common::kNoError;
+}
+
 } // namespace AGS
diff --git a/engines/ags/ags.h b/engines/ags/ags.h
index f8d0f7e455..982bf66d54 100644
--- a/engines/ags/ags.h
+++ b/engines/ags/ags.h
@@ -101,6 +101,16 @@ public:
 	 * Setse up the graphics mode
 	 */
 	void setGraphicsMode(size_t w, size_t h);
+
+	/**
+	 * Load a savegame
+	 */
+	Common::Error loadGameState(int slot) override;
+
+	/**
+	 * Save a savegame
+	 */
+	Common::Error saveGameState(int slot, const Common::String &desc, bool isAutosave = false) override;
 };
 
 extern AGSEngine *g_vm;
diff --git a/engines/ags/engine/ac/game.cpp b/engines/ags/engine/ac/game.cpp
index 561a0d0c8f..ec1f052520 100644
--- a/engines/ags/engine/ac/game.cpp
+++ b/engines/ags/engine/ac/game.cpp
@@ -209,7 +209,6 @@ String saveGameDirectory = "./";
 // Custom save game parent directory
 String saveGameParent;
 
-const char *sgnametemplate = "agssave.%03d";
 String saveGameSuffix;
 
 int game_paused = 0;
@@ -361,12 +360,16 @@ void set_save_game_suffix(const String &suffix) {
 }
 
 String get_save_game_path(int slotNum) {
+#if AGS_PLATFORM_SCUMMVM
+	return ::AGS::g_vm->getSaveStateName(slotNum);
+#else
 	String filename;
 	filename.Format(sgnametemplate, slotNum);
 	String path = saveGameDirectory;
 	path.Append(filename);
 	path.Append(saveGameSuffix);
 	return path;
+#endif
 }
 
 // Convert a path possibly containing path tags into acceptable save path
@@ -1041,7 +1044,6 @@ void create_savegame_screenshot(Bitmap *&screenShot) {
 }
 
 void save_game(int slotn, const char *descript) {
-
 	// dont allow save in rep_exec_always, because we dont save
 	// the state of blocked scripts
 	can_run_delayed_command();
diff --git a/engines/ags/engine/main/engine.cpp b/engines/ags/engine/main/engine.cpp
index 3aff7ea660..7d128c19a1 100644
--- a/engines/ags/engine/main/engine.cpp
+++ b/engines/ags/engine/main/engine.cpp
@@ -666,6 +666,9 @@ extern char android_base_directory[256];
 #endif // AGS_PLATFORM_OS_ANDROID
 
 int check_write_access() {
+#if AGS_PLATFORM_SCUMMVM
+	return true;
+#else
 
 	if (platform->GetDiskFreeSpaceMB() < 2)
 		return 0;
@@ -701,6 +704,7 @@ int check_write_access() {
 		return 0;
 
 	return 1;
+#endif
 }
 
 int engine_check_disk_space() {


Commit: 1de35ad633bac0027d5ece3346cbb45a208bf0a1
    https://github.com/scummvm/scummvm/commit/1de35ad633bac0027d5ece3346cbb45a208bf0a1
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Adding saveilfe support to FileStream

Changed paths:
    engines/ags/engine/ac/game.cpp
    engines/ags/shared/util/filestream.cpp
    engines/ags/shared/util/filestream.h


diff --git a/engines/ags/engine/ac/game.cpp b/engines/ags/engine/ac/game.cpp
index ec1f052520..1332850a67 100644
--- a/engines/ags/engine/ac/game.cpp
+++ b/engines/ags/engine/ac/game.cpp
@@ -425,6 +425,9 @@ bool SetCustomSaveParent(const String &path) {
 }
 
 bool SetSaveGameDirectoryPath(const char *newFolder, bool explicit_path) {
+#if AGS_PLATFORM_SCUMMVM
+	return false;
+#else
 	if (!newFolder || newFolder[0] == 0)
 		newFolder = ".";
 	String newSaveGameDir;
@@ -465,6 +468,7 @@ bool SetSaveGameDirectoryPath(const char *newFolder, bool explicit_path) {
 
 	saveGameDirectory = newSaveGameDir;
 	return true;
+#endif
 }
 
 int Game_SetSaveGameDirectory(const char *newFolder) {
diff --git a/engines/ags/shared/util/filestream.cpp b/engines/ags/shared/util/filestream.cpp
index b512fc4505..44988fd5fc 100644
--- a/engines/ags/shared/util/filestream.cpp
+++ b/engines/ags/shared/util/filestream.cpp
@@ -23,7 +23,9 @@
 #include "ags/shared/util/filestream.h"
 #include "ags/shared/util/stdio_compat.h"
 #include "ags/shared/util/string.h"
+#include "ags/ags.h"
 #include "common/file.h"
+#include "common/system.h"
 
 namespace AGS3 {
 namespace AGS {
@@ -31,10 +33,8 @@ namespace Shared {
 
 FileStream::FileStream(const String &file_name, FileOpenMode open_mode, FileWorkMode work_mode,
 	DataEndianess stream_endianess)
-	: DataStream(stream_endianess)
-	, _file(nullptr)
-	, _openMode(open_mode)
-	, _workMode(work_mode) {
+		: DataStream(stream_endianess), _writeBuffer(DisposeAfterUse::YES),
+		_openMode(open_mode), _workMode(work_mode), _file(nullptr), _outSave(nullptr) {
 	Open(file_name, open_mode, work_mode);
 }
 
@@ -47,9 +47,15 @@ bool FileStream::HasErrors() const {
 }
 
 void FileStream::Close() {
-	if (_file) {
+	if (_outSave) {
+		_outSave->write(_writeBuffer.getData(), _writeBuffer.size());
+		_outSave->finalize();
+		delete _outSave;
+
+	} else if (_file) {
 		delete _file;
 	}
+
 	_file = nullptr;
 }
 
@@ -168,21 +174,30 @@ bool FileStream::Seek(soff_t offset, StreamSeek origin) {
 
 void FileStream::Open(const String &file_name, FileOpenMode open_mode, FileWorkMode work_mode) {
 	if (open_mode == kFile_Open) {
+		// First try to open file in game folder
 		Common::File *f = new Common::File();
-		if (!f->open(getFSNode(file_name.GetNullableCStr()))) {
+		if (!file_name.CompareLeftNoCase("agssave.") || !f->open(getFSNode(file_name.GetNullableCStr()))) {
 			delete f;
-			_file = nullptr;
+
+			// Fall back on any save file with the given name
+			String saveName = file_name;
+			if (!file_name.CompareLeftNoCase("agssave.")) {
+				int saveSlot = atoi(file_name.GetNullableCStr() + 8);
+				saveName = ::AGS::g_vm->getSaveStateName(saveSlot);
+			}
+
+			_file = g_system->getSavefileManager()->openForLoading(saveName);
 		} else {
 			_file = f;
 		}
 
 	} else {
-		Common::DumpFile *f = new Common::DumpFile();
-		if (!f->open(file_name.GetNullableCStr())) {
-			delete f;
-			_file = nullptr;
-		} else {
-			_file = f;
+		// All newly created files are created as save files
+		_outSave = g_system->getSavefileManager()->openForSaving(file_name, false);
+		if (_outSave) {
+			// Any data written has to first go through the memory stream buffer,
+			// since the savegame code uses Seeks, which OutSaveFile doesn't support
+			_file = &_writeBuffer;
 		}
 	}
 }
diff --git a/engines/ags/shared/util/filestream.h b/engines/ags/shared/util/filestream.h
index 69d56f6f9a..ff9994c111 100644
--- a/engines/ags/shared/util/filestream.h
+++ b/engines/ags/shared/util/filestream.h
@@ -23,11 +23,11 @@
 #ifndef AGS_SHARED_UTIL_FILESTREAM_H
 #define AGS_SHARED_UTIL_FILESTREAM_H
 
-//include <stdio.h>
-
 #include "ags/shared/util/datastream.h"
 #include "ags/shared/util/file.h" // TODO: extract filestream mode constants
 #include "common/stream.h"
+#include "common/memstream.h"
+#include "common/savefile.h"
 
 namespace AGS3 {
 namespace AGS {
@@ -73,6 +73,8 @@ private:
 	Common::Stream *_file;
 	const FileOpenMode  _openMode;
 	const FileWorkMode  _workMode;
+	Common::MemoryWriteStreamDynamic _writeBuffer;
+	Common::OutSaveFile *_outSave;
 };
 
 } // namespace Shared


Commit: b71eb2de1fbac621772bffff6d54c4cd7e4a7c09
    https://github.com/scummvm/scummvm/commit/b71eb2de1fbac621772bffff6d54c4cd7e4a7c09
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fixing keys - upper/lowercase, function keys, etc

Changed paths:
    engines/ags/engine/ac/sys_events.cpp
    engines/ags/events.cpp
    engines/ags/events.h
    engines/ags/lib/allegro/keyboard.cpp
    engines/ags/lib/allegro/keyboard.h


diff --git a/engines/ags/engine/ac/sys_events.cpp b/engines/ags/engine/ac/sys_events.cpp
index 53bf7375f5..16acd3c0e8 100644
--- a/engines/ags/engine/ac/sys_events.cpp
+++ b/engines/ags/engine/ac/sys_events.cpp
@@ -56,7 +56,7 @@ int ags_kbhit() {
 }
 
 int ags_iskeypressed(int keycode) {
-	if (keycode >= 0 && keycode < __allegro_KEY_MAX) {
+	if (keycode >= 0 && keycode < Common::KEYCODE_LAST) {
 		return key[keycode] != 0;
 	}
 	return 0;
@@ -99,153 +99,100 @@ int ags_check_mouse_wheel() {
 }
 
 int ags_getch() {
-	const int read_key_value = readkey();
-	int gott = read_key_value;
-	const int scancode = ((gott >> 8) & 0x00ff);
-	const int ascii = (gott & 0x00ff);
-
-	bool is_extended = (ascii == EXTENDED_KEY_CODE);
-	// On macos, the extended keycode is the ascii character '?' or '\0' if alt-key
-	// so check it's not actually the character '?'
-#if AGS_PLATFORM_OS_MACOS && ! AGS_PLATFORM_OS_IOS
-	is_extended = is_extended || ((ascii == EXTENDED_KEY_CODE_MACOS) && (scancode != __allegro_KEY_SLASH));
-#endif
-
-	/*  char message[200];
-	sprintf(message, "Scancode: %04X", gott);
-	Debug::Printf(message);*/
-
-	/*if ((scancode >= KEY_0_PAD) && (scancode <= KEY_9_PAD)) {
-	// fix numeric pad keys if numlock is off (allegro 4.2 changed this behaviour)
-	if ((key_shifts & KB_NUMLOCK_FLAG) == 0)
-	gott = (gott & 0xff00) | EXTENDED_KEY_CODE;
-	}*/
-
-	if (gott == READKEY_CODE_ALT_TAB) {
-		// Alt+Tab, it gets stuck down unless we do this
-		gott = AGS_KEYCODE_ALT_TAB;
-	}
-#if AGS_PLATFORM_OS_MACOS
-	else if (scancode == __allegro_KEY_BACKSPACE) {
-		gott = eAGSKeyCodeBackspace;
-	}
-#endif
-	else if (is_extended) {
-
-		// I believe we rely on a lot of keys being converted to ASCII, which is why
-		// the complete scan code list is not here.
-
-		switch (scancode) {
-		case __allegro_KEY_F1:
-			gott = eAGSKeyCodeF1;
-			break;
-		case __allegro_KEY_F2:
-			gott = eAGSKeyCodeF2;
-			break;
-		case __allegro_KEY_F3:
-			gott = eAGSKeyCodeF3;
-			break;
-		case __allegro_KEY_F4:
-			gott = eAGSKeyCodeF4;
-			break;
-		case __allegro_KEY_F5:
-			gott = eAGSKeyCodeF5;
-			break;
-		case __allegro_KEY_F6:
-			gott = eAGSKeyCodeF6;
-			break;
-		case __allegro_KEY_F7:
-			gott = eAGSKeyCodeF7;
-			break;
-		case __allegro_KEY_F8:
-			gott = eAGSKeyCodeF8;
-			break;
-		case __allegro_KEY_F9:
-			gott = eAGSKeyCodeF9;
-			break;
-		case __allegro_KEY_F10:
-			gott = eAGSKeyCodeF10;
-			break;
-		case __allegro_KEY_F11:
-			gott = eAGSKeyCodeF11;
-			break;
-		case __allegro_KEY_F12:
-			gott = eAGSKeyCodeF12;
-			break;
-
-		case __allegro_KEY_INSERT:
-			gott = eAGSKeyCodeInsert;
-			break;
-		case __allegro_KEY_DEL:
-			gott = eAGSKeyCodeDelete;
-			break;
-		case __allegro_KEY_HOME:
-			gott = eAGSKeyCodeHome;
-			break;
-		case __allegro_KEY_END:
-			gott = eAGSKeyCodeEnd;
-			break;
-		case __allegro_KEY_PGUP:
-			gott = eAGSKeyCodePageUp;
-			break;
-		case __allegro_KEY_PGDN:
-			gott = eAGSKeyCodePageDown;
-			break;
-		case __allegro_KEY_LEFT:
-			gott = eAGSKeyCodeLeftArrow;
-			break;
-		case __allegro_KEY_RIGHT:
-			gott = eAGSKeyCodeRightArrow;
-			break;
-		case __allegro_KEY_UP:
-			gott = eAGSKeyCodeUpArrow;
-			break;
-		case __allegro_KEY_DOWN:
-			gott = eAGSKeyCodeDownArrow;
-			break;
-
-		case __allegro_KEY_0_PAD:
-			gott = eAGSKeyCodeInsert;
-			break;
-		case __allegro_KEY_1_PAD:
-			gott = eAGSKeyCodeEnd;
-			break;
-		case __allegro_KEY_2_PAD:
-			gott = eAGSKeyCodeDownArrow;
-			break;
-		case __allegro_KEY_3_PAD:
-			gott = eAGSKeyCodePageDown;
-			break;
-		case __allegro_KEY_4_PAD:
-			gott = eAGSKeyCodeLeftArrow;
-			break;
-		case __allegro_KEY_5_PAD:
-			gott = eAGSKeyCodeNumPad5;
-			break;
-		case __allegro_KEY_6_PAD:
-			gott = eAGSKeyCodeRightArrow;
-			break;
-		case __allegro_KEY_7_PAD:
-			gott = eAGSKeyCodeHome;
-			break;
-		case __allegro_KEY_8_PAD:
-			gott = eAGSKeyCodeUpArrow;
-			break;
-		case __allegro_KEY_9_PAD:
-			gott = eAGSKeyCodePageUp;
-			break;
-		case __allegro_KEY_DEL_PAD:
-			gott = eAGSKeyCodeDelete;
-			break;
-
-		default:
+	const Common::KeyState keyState = readkey();
+	int gott;
+
+	// I believe we rely on a lot of keys being converted to ASCII, which is why
+	// the complete scan code list is not here.
+
+	switch (keyState.keycode) {
+	case Common::KEYCODE_F1:
+		gott = eAGSKeyCodeF1;
+		break;
+	case Common::KEYCODE_F2:
+		gott = eAGSKeyCodeF2;
+		break;
+	case Common::KEYCODE_F3:
+		gott = eAGSKeyCodeF3;
+		break;
+	case Common::KEYCODE_F4:
+		gott = eAGSKeyCodeF4;
+		break;
+	case Common::KEYCODE_F5:
+		gott = eAGSKeyCodeF5;
+		break;
+	case Common::KEYCODE_F6:
+		gott = eAGSKeyCodeF6;
+		break;
+	case Common::KEYCODE_F7:
+		gott = eAGSKeyCodeF7;
+		break;
+	case Common::KEYCODE_F8:
+		gott = eAGSKeyCodeF8;
+		break;
+	case Common::KEYCODE_F9:
+		gott = eAGSKeyCodeF9;
+		break;
+	case Common::KEYCODE_F10:
+		gott = eAGSKeyCodeF10;
+		break;
+	case Common::KEYCODE_F11:
+		gott = eAGSKeyCodeF11;
+		break;
+	case Common::KEYCODE_F12:
+		gott = eAGSKeyCodeF12;
+		break;
+
+	case Common::KEYCODE_INSERT:
+	case Common::KEYCODE_KP0:
+		gott = eAGSKeyCodeInsert;
+		break;
+	case Common::KEYCODE_DELETE:
+	case Common::KEYCODE_KP_PERIOD:
+		gott = eAGSKeyCodeDelete;
+		break;
+	case Common::KEYCODE_HOME:
+	case Common::KEYCODE_KP7:
+		gott = eAGSKeyCodeHome;
+		break;
+	case Common::KEYCODE_END:
+	case Common::KEYCODE_KP1:
+		gott = eAGSKeyCodeEnd;
+		break;
+	case Common::KEYCODE_PAGEUP:
+	case Common::KEYCODE_KP9:
+		gott = eAGSKeyCodePageUp;
+		break;
+	case Common::KEYCODE_PAGEDOWN:
+	case Common::KEYCODE_KP3:
+		gott = eAGSKeyCodePageDown;
+		break;
+	case Common::KEYCODE_LEFT:
+	case Common::KEYCODE_KP4:
+		gott = eAGSKeyCodeLeftArrow;
+		break;
+	case Common::KEYCODE_RIGHT:
+	case Common::KEYCODE_KP6:
+		gott = eAGSKeyCodeRightArrow;
+		break;
+	case Common::KEYCODE_UP:
+	case Common::KEYCODE_KP8:
+		gott = eAGSKeyCodeUpArrow;
+		break;
+	case Common::KEYCODE_DOWN:
+	case Common::KEYCODE_KP2:
+		gott = eAGSKeyCodeDownArrow;
+		break;
+
+	default:
+		if (keyState.flags & (Common::KBD_ALT | Common::KBD_CTRL) &&
+			keyState.keycode >= Common::KEYCODE_a && keyState.keycode <= Common::KEYCODE_z)
 			// no meaningful mappings
 			// this is how we accidentally got the alt-key mappings
-			gott = scancode + AGS_EXT_KEY_SHIFT;
-		}
-	} else {
-		// this includes ascii characters and ctrl-A-Z
-		gott = ascii;
+			gott = AGS_EXT_KEY_SHIFT + (keyState.keycode - Common::KEYCODE_a) + 1;
+		else
+			gott = keyState.ascii;
+		break;
 	}
 
 	// Alt+X, abort (but only once game is loaded)
diff --git a/engines/ags/events.cpp b/engines/ags/events.cpp
index c96279ad88..983dcee60f 100644
--- a/engines/ags/events.cpp
+++ b/engines/ags/events.cpp
@@ -50,8 +50,10 @@ void EventsManager::pollEvents() {
 			::AGS3::check_dynamic_sprites_at_exit = 0;
 
 		} else if (e.type == Common::EVENT_KEYDOWN) {
-			// Add keypresses to the pending key list
-			_pendingKeys.push(e.kbd.keycode);
+			if (!isModifierKey(e.kbd.keycode)) {
+				// Add keypresses to the pending key list
+				_pendingKeys.push(e.kbd);
+			}
 		} else {
 			// Add other event types to the pending events queue. If the event is a
 			// mouse move and the prior one was also, then discard the prior one.
@@ -65,14 +67,23 @@ void EventsManager::pollEvents() {
 	}
 }
 
+bool EventsManager::isModifierKey(const Common::KeyCode &keycode) const {
+	return keycode == Common::KEYCODE_LCTRL || keycode == Common::KEYCODE_LALT
+		|| keycode == Common::KEYCODE_RCTRL || keycode == Common::KEYCODE_RALT
+		|| keycode == Common::KEYCODE_LSHIFT || keycode == Common::KEYCODE_RSHIFT
+		|| keycode == Common::KEYCODE_LSUPER || keycode == Common::KEYCODE_RSUPER
+		|| keycode == Common::KEYCODE_CAPSLOCK || keycode == Common::KEYCODE_NUMLOCK
+		|| keycode == Common::KEYCODE_SCROLLOCK;
+}
+
 bool EventsManager::keypressed() {
 	pollEvents();
 	return !_pendingKeys.empty();
 }
 
-int EventsManager::readKey() {
+Common::KeyState EventsManager::readKey() {
 	pollEvents();
-	return _pendingKeys.empty() ? 0 : _pendingKeys.pop();
+	return _pendingKeys.empty() ? Common::KeyState() : _pendingKeys.pop();
 }
 
 Common::Event EventsManager::readEvent() {
diff --git a/engines/ags/events.h b/engines/ags/events.h
index 71126eee9a..5842bd9548 100644
--- a/engines/ags/events.h
+++ b/engines/ags/events.h
@@ -31,7 +31,9 @@ namespace AGS {
 class EventsManager {
 private:
 	Common::Queue<Common::Event> _pendingEvents;
-	Common::Queue<Common::KeyCode> _pendingKeys;
+	Common::Queue<Common::KeyState> _pendingKeys;
+
+	bool isModifierKey(const Common::KeyCode &keycode) const;
 public:
 	EventsManager();
 	~EventsManager();
@@ -49,7 +51,7 @@ public:
 	/**
 	 * Returns the next keypress, if any is pending
 	 */
-	int readKey();
+	Common::KeyState readKey();
 
 	/**
 	 * Returns the next event, if any
diff --git a/engines/ags/lib/allegro/keyboard.cpp b/engines/ags/lib/allegro/keyboard.cpp
index 869ca1655a..7629e364e7 100644
--- a/engines/ags/lib/allegro/keyboard.cpp
+++ b/engines/ags/lib/allegro/keyboard.cpp
@@ -72,7 +72,7 @@ bool keypressed() {
 	return ::AGS::g_events->keypressed();
 }
 
-int readkey() {
+Common::KeyState readkey() {
 	return ::AGS::g_events->readKey();
 }
 
diff --git a/engines/ags/lib/allegro/keyboard.h b/engines/ags/lib/allegro/keyboard.h
index 01a85e338b..5f5b4ccc1f 100644
--- a/engines/ags/lib/allegro/keyboard.h
+++ b/engines/ags/lib/allegro/keyboard.h
@@ -183,7 +183,7 @@ AL_FUNC(void, simulate_keypress, (int keycode));
 AL_FUNC(void, simulate_ukeypress, (int keycode, int scancode));
 
 AL_FUNC(bool, keypressed, (void));
-AL_FUNC(int, readkey, (void));
+AL_FUNC(Common::KeyState, readkey, (void));
 
 } // namespace AGS3
 


Commit: 6767689c067d606d70bcf465e9df783fd2d36fa7
    https://github.com/scummvm/scummvm/commit/6767689c067d606d70bcf465e9df783fd2d36fa7
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Simplifying passing of script method params to DLL class

The original had issues with the types of the method params
being 32 bits for ints, but 32 or 64 bits for string pointers.
This could easily result in a mismatch of passed params to
method definitions. To avoid this, I now pass the parameters
as a Common::Array, and a set of macros to simplify getting
the parameter values within the script method

Changed paths:
    engines/ags/engine/plugin/agsplugin.h
    engines/ags/engine/script/script_runtime.cpp
    engines/ags/plugins/agscreditz/agscreditz.cpp
    engines/ags/plugins/agscreditz/agscreditz.h
    engines/ags/plugins/dll.h


diff --git a/engines/ags/engine/plugin/agsplugin.h b/engines/ags/engine/plugin/agsplugin.h
index f38aca8c99..3f564c214c 100644
--- a/engines/ags/engine/plugin/agsplugin.h
+++ b/engines/ags/engine/plugin/agsplugin.h
@@ -31,8 +31,12 @@
 #ifndef AGS_ENGINE_PLUGIN_AGSPLUGIN_H
 #define AGS_ENGINE_PLUGIN_AGSPLUGIN_H
 
+#include "common/array.h"
+
 namespace AGS3 {
 
+typedef Common::Array<intptr_t> ScriptMethodParams;
+
 // If the plugin isn't using DDraw, don't require the headers
 #ifndef DIRECTDRAW_VERSION
 typedef void *LPDIRECTDRAW2;
diff --git a/engines/ags/engine/script/script_runtime.cpp b/engines/ags/engine/script/script_runtime.cpp
index f460eb5807..2c4a1e7569 100644
--- a/engines/ags/engine/script/script_runtime.cpp
+++ b/engines/ags/engine/script/script_runtime.cpp
@@ -34,15 +34,13 @@
 //
 //=============================================================================
 
-//include <stdlib.h>
-//include <stdarg.h>
-//include <string.h>
 #include "ags/engine/script/script_runtime.h"
 #include "ags/shared/script/script_common.h"
 #include "ags/shared/script/cc_error.h"
 #include "ags/shared/script/cc_options.h"
-#include "ags/engine/ac/dynobj/cc_dynamicarray.h"
 #include "ags/engine/script/systemimports.h"
+#include "ags/engine/plugin/agsplugin.h"
+#include "ags/engine/ac/dynobj/cc_dynamicarray.h"
 #include "ags/engine/ac/statobj/staticobject.h"
 
 namespace AGS3 {
@@ -172,109 +170,26 @@ int call_function(intptr_t addr, const RuntimeScriptValue *object, int numparm,
 		}
 	}
 
-	//
-	// AN IMPORTANT NOTE ON PARAM TYPE
-	// of 2012-11-10
-	//
-	//// NOTE of 2012-12-20:
-	//// Everything said below is applicable only for calling
-	//// exported plugin functions.
-	//
-	// Here we are sending parameters of type intptr_t to registered
-	// function of unknown kind. Intptr_t is 32-bit for x32 build and
-	// 64-bit for x64 build.
-	// The exported functions usually have two types of parameters:
-	// pointer and 'int' (32-bit). For x32 build those two have the
-	// same size, but for x64 build first has 64-bit size while the
-	// second remains 32-bit.
-	// In formal case that would cause 'overflow' - function will
-	// receive more data than needed (written to stack), with some
-	// values shifted further by 32 bits.
-	//
-	// Upon testing, however, it was revealed that AMD64 processor,
-	// the only platform we support x64 Linux AGS build on right now,
-	// treats all the function parameters pushed to stack as 64-bit
-	// values (few first parameters are sent via registers, and hence
-	// are least concern anyway). Therefore, no 'overflow' occurs,
-	// and 64-bit values are being effectively truncated to 32-bit
-	// integers in the callee.
-	//
-	// Since this is still quite unreliable, this should be
-	// reimplemented when there's enough free time available for
-	// developers both for coding & testing.
-	//
-	// Most basic idea is to pass array of RuntimeScriptValue
-	// objects (that hold type description) and get same RSV as a
-	// return result. Keep in mind, though, that this solution will
-	// require fixing ALL exported functions, so a good amount of
-	// time and energy should be allocated for this task.
-	//
+	// AN IMPORTANT NOTE ON PARAMS
+	// The original AGS interpreter did a bunch of dodgy function pointers with
+	// varying numbers of parameters, which were all int64_t. To simply matters
+	// now that we only supported plugins implemented in code, and not DLLs,
+	// we use a simplified Common::Array containing the parameters
 
-	switch (numparm) {
-	case 0:
-	{
-		int (*fparam)();
-		fparam = (int (*)())addr;
-		return fparam();
-	}
-	case 1:
-	{
-		int (*fparam)(intptr_t);
-		fparam = (int (*)(intptr_t))addr;
-		return fparam(parm_value[0]);
-	}
-	case 2:
-	{
-		int (*fparam)(intptr_t, intptr_t);
-		fparam = (int (*)(intptr_t, intptr_t))addr;
-		return fparam(parm_value[0], parm_value[1]);
-	}
-	case 3:
-	{
-		int (*fparam)(intptr_t, intptr_t, intptr_t);
-		fparam = (int (*)(intptr_t, intptr_t, intptr_t))addr;
-		return fparam(parm_value[0], parm_value[1], parm_value[2]);
-	}
-	case 4:
-	{
-		int (*fparam)(intptr_t, intptr_t, intptr_t, intptr_t);
-		fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t))addr;
-		return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3]);
-	}
-	case 5:
-	{
-		int (*fparam)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t);
-		fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr;
-		return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4]);
-	}
-	case 6:
-	{
-		int (*fparam)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t);
-		fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr;
-		return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4], parm_value[5]);
-	}
-	case 7:
-	{
-		int (*fparam)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t);
-		fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr;
-		return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4], parm_value[5], parm_value[6]);
-	}
-	case 8:
-	{
-		int (*fparam)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t);
-		fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr;
-		return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4], parm_value[5], parm_value[6], parm_value[7]);
-	}
-	case 9:
-	{
-		int (*fparam)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t);
-		fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr;
-		return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4], parm_value[5], parm_value[6], parm_value[7], parm_value[8]);
-	}
-	}
+	if (numparm > 9) {
+		cc_error("too many arguments in call to function");
+		return -1;
+	} else {
+		// Build the parameters
+		ScriptMethodParams params;
+		for (int i = 0; i < numparm; ++i)
+			params.push_back(parm_value[i]);
 
-	cc_error("too many arguments in call to function");
-	return -1;
+		// Call the method
+		typedef int (*ScriptMethod)(const ScriptMethodParams &params);
+		ScriptMethod fparam = (ScriptMethod)addr;
+		return fparam(params);
+	}
 }
 
 } // namespace AGS3
diff --git a/engines/ags/plugins/agscreditz/agscreditz.cpp b/engines/ags/plugins/agscreditz/agscreditz.cpp
index bae5322bc0..8f30b69f0f 100644
--- a/engines/ags/plugins/agscreditz/agscreditz.cpp
+++ b/engines/ags/plugins/agscreditz/agscreditz.cpp
@@ -59,74 +59,89 @@ void AgsCreditz::AGS_EngineStartup(IAGSEngine *engine) {
 	SCRIPT_METHOD(IsStaticCreditsFinished);
 }
 
-void AgsCreditz::SetCredit(int ID, string credit, int colour, int font, int center, int xpos, int generateoutline) {
+void AgsCreditz::SetCredit(const ScriptMethodParams &params) {
+	PARAMS7(int, ID, string, credit, int, colour, int, font, int, center, int, xpos, int, generateoutline);
 }
 
-void AgsCreditz::ScrollCredits(int onoff, int speed, int fromY, int toY, int isautom, int wait, int res) {
+void AgsCreditz::ScrollCredits(const ScriptMethodParams &params) {
+	PARAMS7(int, onoff, int, speed, int, fromY, int, toY, int, isautom, int, wait, int, res);
 }
 
-string AgsCreditz::GetCredit(int ID) {
-	return string();
+string AgsCreditz::GetCredit(const ScriptMethodParams &params) {
+	PARAMS1(int, ID);
+	return nullptr;
 }
 
-int AgsCreditz::IsCreditScrollingFinished() {
+int AgsCreditz::IsCreditScrollingFinished(const ScriptMethodParams &params) {
 	return true;
 }
 
-void AgsCreditz::SetCreditImage(int ID, int Slot, int center, int xpos, int pixtonext) {
+void AgsCreditz::SetCreditImage(const ScriptMethodParams &params) {
+	PARAMS5(int, ID, int, Slot, int, center, int, xpos, int, pixtonext);
 }
 
-void AgsCreditz::PauseScroll(int onoff) {
+void AgsCreditz::PauseScroll(const ScriptMethodParams &params) {
+	PARAMS1(int, onoff);
 }
 
-void AgsCreditz::ScrollReset() {
+void AgsCreditz::ScrollReset(const ScriptMethodParams &params) {
 }
 
-void AgsCreditz::SetEmptyLineHeight(int Height) {
+void AgsCreditz::SetEmptyLineHeight(const ScriptMethodParams &params) {
+	PARAMS1(int, Height);
 }
 
-int AgsCreditz::GetEmptyLineHeight() {
+int AgsCreditz::GetEmptyLineHeight(const ScriptMethodParams &params) {
 	return 0;
 }
 
-void AgsCreditz::SetStaticCredit(int ID, int x, int y, int creditfont, int creditcolour, int centered, int generateoutline, string credit) {
+void AgsCreditz::SetStaticCredit(const ScriptMethodParams &params) {
+	PARAMS8(int, ID, int, x, int, y, int, creditfont, int, creditcolour, int, centered, int, generateoutline, string, credit);
 
 }
 
-string AgsCreditz::GetStaticCredit(int ID) {
-	return string();
+string AgsCreditz::GetStaticCredit(const ScriptMethodParams &params) {
+	PARAMS1(int, ID);
+	return nullptr;
 }
 
-void AgsCreditz::StartEndStaticCredits(int onoff, int res) {
+void AgsCreditz::StartEndStaticCredits(const ScriptMethodParams &params) {
+	PARAMS2(int, onoff, int, res);
 }
 
-int AgsCreditz::GetCurrentStaticCredit() {
+int AgsCreditz::GetCurrentStaticCredit(const ScriptMethodParams &params) {
 	return 0;
 }
 
-void AgsCreditz::SetDefaultStaticDelay(int Cyclesperchar) {
+void AgsCreditz::SetDefaultStaticDelay(const ScriptMethodParams &params) {
+	PARAMS1(int, Cyclesperchar);
 }
 
-void AgsCreditz::SetStaticPause(int ID, int length) {
+void AgsCreditz::SetStaticPause(const ScriptMethodParams &params) {
+	PARAMS2(int, ID, int, length);
 }
 
-void AgsCreditz::SetStaticCreditTitle(int ID, int x, int y, int titlefont, int titlecolour, int centered, int generateoutline, string title) {
+void AgsCreditz::SetStaticCreditTitle(const ScriptMethodParams &params) {
+	PARAMS8(int, ID, int, x, int, y, int, titlefont, int, titlecolour, int, centered, int, generateoutline, string, title);
 }
 
-void AgsCreditz::ShowStaticCredit(int ID, int time, int style, int transtime, int sound, int resolution) {
+void AgsCreditz::ShowStaticCredit(const ScriptMethodParams &params) {
+	PARAMS6(int, ID, int, time, int, style, int, transtime, int, sound, int, resolution);
 }
 
-void AgsCreditz::StaticReset() {
+void AgsCreditz::StaticReset(const ScriptMethodParams &params) {
 }
 
-string AgsCreditz::GetStaticCreditTitle(int ID) {
-	return string();
+string AgsCreditz::GetStaticCreditTitle(const ScriptMethodParams &params) {
+	PARAMS1(int, ID);
+	return nullptr;
 }
 
-void AgsCreditz::SetStaticCreditImage(int ID, int x, int y, int Slot, int Hcentered, int Vcentered, int time) {
+void AgsCreditz::SetStaticCreditImage(const ScriptMethodParams &params) {
+//int ID, int x, int y, int Slot, int Hcentered, int Vcentered, int time) {
 }
 
-int AgsCreditz::IsStaticCreditsFinished() {
+int AgsCreditz::IsStaticCreditsFinished(const ScriptMethodParams &params) {
 	return true;
 }
 
diff --git a/engines/ags/plugins/agscreditz/agscreditz.h b/engines/ags/plugins/agscreditz/agscreditz.h
index 6096260218..d10c1a8893 100644
--- a/engines/ags/plugins/agscreditz/agscreditz.h
+++ b/engines/ags/plugins/agscreditz/agscreditz.h
@@ -34,27 +34,28 @@ private:
 	static const char *AGS_GetPluginName();
 	static void AGS_EngineStartup(IAGSEngine *engine);
 
-	static void SetCredit(int ID, string credit, int colour, int font, int center, int xpos, int generateoutline);
-	static void ScrollCredits(int onoff, int speed, int fromY, int toY, int isautom, int wait, int res);
-	static string GetCredit(int ID);
-	static int IsCreditScrollingFinished();
-	static void SetCreditImage(int ID, int Slot, int center, int xpos, int pixtonext);
-	static void PauseScroll(int onoff);
-	static void ScrollReset();
-	static void SetEmptyLineHeight(int Height);
-	static int GetEmptyLineHeight();
-	static void SetStaticCredit(int ID, int x, int y, int creditfont, int creditcolour, int centered, int generateoutline, string credit);
-	static string GetStaticCredit(int ID);
-	static void StartEndStaticCredits(int onoff, int res);
-	static int GetCurrentStaticCredit();
-	static void SetDefaultStaticDelay(int Cyclesperchar);
-	static void SetStaticPause(int ID, int length);
-	static void SetStaticCreditTitle(int ID, int x, int y, int titlefont, int titlecolour, int centered, int generateoutline, string title);
-	static void ShowStaticCredit(int ID, int time, int style, int transtime, int sound, int resolution);
-	static void StaticReset();
-	static string GetStaticCreditTitle(int ID);
-	static void SetStaticCreditImage(int ID, int x, int y, int Slot, int Hcentered, int Vcentered, int time);
-	static int IsStaticCreditsFinished();
+	// Script methods
+	static void SetCredit(const ScriptMethodParams &params);
+	static void ScrollCredits(const ScriptMethodParams &params);
+	static string GetCredit(const ScriptMethodParams &params);
+	static int IsCreditScrollingFinished(const ScriptMethodParams &params);
+	static void SetCreditImage(const ScriptMethodParams &params);
+	static void PauseScroll(const ScriptMethodParams &params);
+	static void ScrollReset(const ScriptMethodParams &params);
+	static void SetEmptyLineHeight(const ScriptMethodParams &params);
+	static int GetEmptyLineHeight(const ScriptMethodParams &params);
+	static void SetStaticCredit(const ScriptMethodParams &params);
+	static string GetStaticCredit(const ScriptMethodParams &params);
+	static void StartEndStaticCredits(const ScriptMethodParams &params);
+	static int GetCurrentStaticCredit(const ScriptMethodParams &params);
+	static void SetDefaultStaticDelay(const ScriptMethodParams &params);
+	static void SetStaticPause(const ScriptMethodParams &params);
+	static void SetStaticCreditTitle(const ScriptMethodParams &params);
+	static void ShowStaticCredit(const ScriptMethodParams &params);
+	static void StaticReset(const ScriptMethodParams &params);
+	static string GetStaticCreditTitle(const ScriptMethodParams &params);
+	static void SetStaticCreditImage(const ScriptMethodParams &params);
+	static int IsStaticCreditsFinished(const ScriptMethodParams &params);
 public:
 	AgsCreditz();
 };
diff --git a/engines/ags/plugins/dll.h b/engines/ags/plugins/dll.h
index e3fedacf88..2d653a4edc 100644
--- a/engines/ags/plugins/dll.h
+++ b/engines/ags/plugins/dll.h
@@ -34,8 +34,55 @@ namespace Plugins {
 #define DLL_METHOD(NAME) _methods[#NAME] = (void *)&NAME
 #define SCRIPT_METHOD(NAME) engine->RegisterScriptFunction(#NAME, (void *)&NAME)
 
+#define PARAMS1(T1, N1) \
+	T1 N1 = (T1)params[0]
+#define PARAMS2(T1, N1, T2, N2) \
+	T1 N1 = (T1)params[0]; \
+	T2 N2 = (T2)params[1]
+#define PARAMS3(T1, N1, T2, N2, T3, N3) \
+	T1 N1 = (T1)params[0]; \
+	T2 N2 = (T2)params[1]; \
+	T3 N3 = (T3)params[2]
+#define PARAMS4(T1, N1, T2, N2, T3, N3, T4, N4) \
+	T1 N1 = (T1)params[0]; \
+	T2 N2 = (T2)params[1]; \
+	T3 N3 = (T3)params[2]; \
+	T4 N4 = (T4)params[3]
+#define PARAMS5(T1, N1, T2, N2, T3, N3, T4, N4, T5, N5) \
+	T1 N1 = (T1)params[0]; \
+	T2 N2 = (T2)params[1]; \
+	T3 N3 = (T3)params[2]; \
+	T4 N4 = (T4)params[3]; \
+	T5 N5 = (T5)params[4]
+#define PARAMS6(T1, N1, T2, N2, T3, N3, T4, N4, T5, N5, T6, N6) \
+	T1 N1 = (T1)params[0]; \
+	T2 N2 = (T2)params[1]; \
+	T3 N3 = (T3)params[2]; \
+	T4 N4 = (T4)params[3]; \
+	T5 N5 = (T5)params[4]; \
+	T6 N6 = (T6)params[5]
+#define PARAMS7(T1, N1, T2, N2, T3, N3, T4, N4, T5, N5, T6, N6, T7, N7) \
+	T1 N1 = (T1)params[0]; \
+	T2 N2 = (T2)params[1]; \
+	T3 N3 = (T3)params[2]; \
+	T4 N4 = (T4)params[3]; \
+	T5 N5 = (T5)params[4]; \
+	T6 N6 = (T6)params[5]; \
+	T7 N7 = (T7)params[6]
+#define PARAMS8(T1, N1, T2, N2, T3, N3, T4, N4, T5, N5, T6, N6, T7, N7, T8, N8) \
+	T1 N1 = (T1)params[0]; \
+	T2 N2 = (T2)params[1]; \
+	T3 N3 = (T3)params[2]; \
+	T4 N4 = (T4)params[3]; \
+	T5 N5 = (T5)params[4]; \
+	T6 N6 = (T6)params[5]; \
+	T7 N7 = (T7)params[6]; \
+	T8 N8 = (T8)params[7]
+
+
 // TODO: Refactor string into core AGS namespace
-using string = ::AGS3::AGS::Shared::String;
+using string = const char *;
+using ScriptMethodParams = ::AGS3::ScriptMethodParams;
 
 using IAGSEngine = ::AGS3::IAGSEngine;
 using IAGSEditor = ::AGS3::IAGSEditor;


Commit: 0cf3a48ae498985148d8f904d024935851a43973
    https://github.com/scummvm/scummvm/commit/0cf3a48ae498985148d8f904d024935851a43973
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Saves now has dummy path for clarity, added MetaEngine listSaves

Changed paths:
    engines/ags/engine/ac/game.cpp
    engines/ags/engine/ac/richgamemedia.cpp
    engines/ags/engine/ac/richgamemedia.h
    engines/ags/engine/game/savegame.cpp
    engines/ags/metaengine.cpp
    engines/ags/metaengine.h
    engines/ags/shared/util/filestream.cpp
    engines/ags/shared/util/filestream.h


diff --git a/engines/ags/engine/ac/game.cpp b/engines/ags/engine/ac/game.cpp
index 1332850a67..26f275be26 100644
--- a/engines/ags/engine/ac/game.cpp
+++ b/engines/ags/engine/ac/game.cpp
@@ -361,7 +361,8 @@ void set_save_game_suffix(const String &suffix) {
 
 String get_save_game_path(int slotNum) {
 #if AGS_PLATFORM_SCUMMVM
-	return ::AGS::g_vm->getSaveStateName(slotNum);
+	return Common::String::format("%s%s", SAVE_FOLDER_PREFIX,
+		::AGS::g_vm->getSaveStateName(slotNum).c_str());
 #else
 	String filename;
 	filename.Format(sgnametemplate, slotNum);
diff --git a/engines/ags/engine/ac/richgamemedia.cpp b/engines/ags/engine/ac/richgamemedia.cpp
index 1c09739ddd..ae6852d3a3 100644
--- a/engines/ags/engine/ac/richgamemedia.cpp
+++ b/engines/ags/engine/ac/richgamemedia.cpp
@@ -55,4 +55,15 @@ void RICH_GAME_MEDIA_HEADER::WriteToFile(Stream *out) {
 	out->WriteArrayOfInt16((int16_t *)szComments, RM_MAXLENGTH);
 }
 
+void RICH_GAME_MEDIA_HEADER::setSaveName(const Common::String &saveName) {
+	uconvert<char, uint16>(saveName.c_str(), szSaveName, RM_MAXLENGTH);
+}
+
+Common::String RICH_GAME_MEDIA_HEADER::getSaveName() const {
+	char buf[RM_MAXLENGTH];
+	uconvert<uint16, char>(szSaveName, buf, RM_MAXLENGTH);
+
+	return Common::String(buf);
+}
+
 } // namespace AGS3
diff --git a/engines/ags/engine/ac/richgamemedia.h b/engines/ags/engine/ac/richgamemedia.h
index f28cd454ae..c66a46d835 100644
--- a/engines/ags/engine/ac/richgamemedia.h
+++ b/engines/ags/engine/ac/richgamemedia.h
@@ -23,12 +23,15 @@
 #ifndef AGS_ENGINE_AC_RICHGAMEMEDIA_H
 #define AGS_ENGINE_AC_RICHGAMEMEDIA_H
 
+#include "common/algorithm.h"
+#include "common/str.h"
+
 namespace AGS3 {
 
 // Windows Vista Rich Save Games, modified to be platform-agnostic
 
 #define RM_MAXLENGTH    1024
-#define RM_MAGICNUMBER  "RGMH"
+#define RM_MAGICNUMBER  MKTAG('R', 'G', 'M', 'H')
 
 // Forward declaration
 namespace AGS {
@@ -41,22 +44,35 @@ using namespace AGS; // FIXME later
 
 #pragma pack(push)
 #pragma pack(1)
-typedef struct _RICH_GAME_MEDIA_HEADER {
-	int       dwMagicNumber;
+struct RICH_GAME_MEDIA_HEADER {
+private:
+	template<class SRC, class DEST>
+	static void uconvert(const SRC *src, DEST *dest, size_t maxSize) {
+		do {
+			*dest++ = *src;
+		} while (*src++ != 0 && --maxSize > 1);
+
+		*dest = '\0';
+	}
+public:
+	uint32    dwMagicNumber;
 	int       dwHeaderVersion;
 	int       dwHeaderSize;
 	int       dwThumbnailOffsetLowerDword;
 	int       dwThumbnailOffsetHigherDword;
 	int       dwThumbnailSize;
-	unsigned char guidGameId[16];
-	unsigned short szGameName[RM_MAXLENGTH];
-	unsigned short szSaveName[RM_MAXLENGTH];
-	unsigned short szLevelName[RM_MAXLENGTH];
-	unsigned short szComments[RM_MAXLENGTH];
+	byte guidGameId[16];
+	uint16 szGameName[RM_MAXLENGTH];
+	uint16 szSaveName[RM_MAXLENGTH];
+	uint16 szLevelName[RM_MAXLENGTH];
+	uint16 szComments[RM_MAXLENGTH];
 
 	void ReadFromFile(Shared::Stream *in);
 	void WriteToFile(Shared::Stream *out);
-} RICH_GAME_MEDIA_HEADER;
+
+	void setSaveName(const Common::String &saveName);
+	Common::String getSaveName() const;
+};
 #pragma pack(pop)
 
 } // namespace AGS3
diff --git a/engines/ags/engine/game/savegame.cpp b/engines/ags/engine/game/savegame.cpp
index f9adcdb69f..89d746abdb 100644
--- a/engines/ags/engine/game/savegame.cpp
+++ b/engines/ags/engine/game/savegame.cpp
@@ -683,14 +683,6 @@ void WriteDescription(Stream *out, const String &user_text, const Bitmap *user_i
 	WriteSaveImage(out, user_image);
 }
 
-static void uconvert(const char *src, unsigned short *dest, int maxSize) {
-	do {
-		*dest++ = *src;
-	} while (*src++ != 0 && --maxSize > 1);
-
-	*dest = '\0';
-}
-
 PStream StartSavegame(const String &filename, const String &user_text, const Bitmap *user_image) {
 	Stream *out = Shared::File::CreateFile(filename);
 	if (!out)
@@ -699,7 +691,7 @@ PStream StartSavegame(const String &filename, const String &user_text, const Bit
 	// Initialize and write Vista header
 	RICH_GAME_MEDIA_HEADER vistaHeader;
 	memset(&vistaHeader, 0, sizeof(RICH_GAME_MEDIA_HEADER));
-	memcpy(&vistaHeader.dwMagicNumber, RM_MAGICNUMBER, sizeof(int));
+	vistaHeader.dwMagicNumber = RM_MAGICNUMBER;
 	vistaHeader.dwHeaderVersion = 1;
 	vistaHeader.dwHeaderSize = sizeof(RICH_GAME_MEDIA_HEADER);
 	vistaHeader.dwThumbnailOffsetHigherDword = 0;
@@ -708,8 +700,7 @@ PStream StartSavegame(const String &filename, const String &user_text, const Bit
 	convert_guid_from_text_to_binary(game.guid, &vistaHeader.guidGameId[0]);
 
 #if 1
-	Common::String name = Common::String::format("%s %s", game.gamename, user_text.GetNullableCStr());
-	uconvert(name.c_str(), vistaHeader.szSaveName, RM_MAXLENGTH);
+	vistaHeader.setSaveName(user_text);
 #else
 	uconvert(game.gamename, U_ASCII, (char *)&vistaHeader.szGameName[0], U_UNICODE, RM_MAXLENGTH);
 	uconvert(user_text, U_ASCII, (char *)&vistaHeader.szSaveName[0], U_UNICODE, RM_MAXLENGTH);
diff --git a/engines/ags/metaengine.cpp b/engines/ags/metaengine.cpp
index bb737c24f0..e210080f41 100644
--- a/engines/ags/metaengine.cpp
+++ b/engines/ags/metaengine.cpp
@@ -23,6 +23,10 @@
 #include "ags/metaengine.h"
 #include "ags/detection.h"
 #include "ags/ags.h"
+#include "ags/shared/util/filestream.h"
+#include "ags/engine/ac/richgamemedia.h"
+#include "ags/engine/game/savegame.h"
+#include "common/savefile.h"
 
 const char *AGSMetaEngine::getName() const {
 	return "ags";
@@ -35,6 +39,44 @@ Common::Error AGSMetaEngine::createInstance(OSystem *syst, Engine **engine, cons
 	return Common::kNoError;
 }
 
+SaveStateList AGSMetaEngine::listSaves(const char *target) const {
+	Common::SaveFileManager *saveFileMan = g_system->getSavefileManager();
+	Common::StringArray filenames;
+	Common::String pattern(getSavegameFilePattern(target));
+
+	filenames = saveFileMan->listSavefiles(pattern);
+
+	SaveStateList saveList;
+	for (Common::StringArray::const_iterator file = filenames.begin(); file != filenames.end(); ++file) {
+		Common::String filename = Common::String::format("%s%s",
+			::AGS3::AGS::Shared::SAVE_FOLDER_PREFIX, file->c_str());
+
+		::AGS3::AGS::Shared::FileStream saveFile(filename, ::AGS3::AGS::Shared::kFile_Open,
+			::AGS3::AGS::Shared::kFile_Read);
+		if (saveFile.IsValid()) {
+			AGS3::RICH_GAME_MEDIA_HEADER rich_media_header;
+			rich_media_header.ReadFromFile(&saveFile);
+
+			if (rich_media_header.dwMagicNumber == RM_MAGICNUMBER) {
+				int slotNum = atoi(file->c_str() + file->size() - 3);
+
+				SaveStateDescriptor desc;
+				desc.setSaveSlot(slotNum);
+				desc.setDescription(rich_media_header.getSaveName());
+
+				if (slotNum == getAutosaveSlot())
+					desc.setWriteProtectedFlag(true);
+
+				saveList.push_back(desc);
+			}
+		}
+	}
+
+	// Sort saves based on slot number.
+	Common::sort(saveList.begin(), saveList.end(), SaveStateDescriptorSlotComparator());
+	return saveList;
+}
+
 #if PLUGIN_ENABLED_DYNAMIC(AGS)
 REGISTER_PLUGIN_DYNAMIC(AGS, PLUGIN_TYPE_ENGINE, AGSMetaEngine);
 #else
diff --git a/engines/ags/metaengine.h b/engines/ags/metaengine.h
index b8a6cd8c84..aeccb8f447 100644
--- a/engines/ags/metaengine.h
+++ b/engines/ags/metaengine.h
@@ -31,7 +31,14 @@ class AGSMetaEngine : public AdvancedMetaEngine {
 public:
 	const char *getName() const override;
 
-	virtual Common::Error createInstance(OSystem *syst, Engine **engine, const ADGameDescription *desc) const;
+	Common::Error createInstance(OSystem *syst, Engine **engine, const ADGameDescription *desc) const override;
+
+	SaveStateList listSaves(const char *target) const override;
+
+	int getAutosaveSlot() const override {
+		return 999;
+	}
+
 };
 
 #endif
diff --git a/engines/ags/shared/util/filestream.cpp b/engines/ags/shared/util/filestream.cpp
index 44988fd5fc..620124a42f 100644
--- a/engines/ags/shared/util/filestream.cpp
+++ b/engines/ags/shared/util/filestream.cpp
@@ -31,6 +31,8 @@ namespace AGS3 {
 namespace AGS {
 namespace Shared {
 
+const char *SAVE_FOLDER_PREFIX = "/saves/";
+
 FileStream::FileStream(const String &file_name, FileOpenMode open_mode, FileWorkMode work_mode,
 	DataEndianess stream_endianess)
 		: DataStream(stream_endianess), _writeBuffer(DisposeAfterUse::YES),
@@ -174,31 +176,35 @@ bool FileStream::Seek(soff_t offset, StreamSeek origin) {
 
 void FileStream::Open(const String &file_name, FileOpenMode open_mode, FileWorkMode work_mode) {
 	if (open_mode == kFile_Open) {
-		// First try to open file in game folder
-		Common::File *f = new Common::File();
-		if (!file_name.CompareLeftNoCase("agssave.") || !f->open(getFSNode(file_name.GetNullableCStr()))) {
-			delete f;
-
-			// Fall back on any save file with the given name
-			String saveName = file_name;
-			if (!file_name.CompareLeftNoCase("agssave.")) {
-				int saveSlot = atoi(file_name.GetNullableCStr() + 8);
-				saveName = ::AGS::g_vm->getSaveStateName(saveSlot);
-			}
+		if (!file_name.CompareLeftNoCase(SAVE_FOLDER_PREFIX)) {
+			_file = g_system->getSavefileManager()->openForLoading(
+				file_name.GetNullableCStr() + strlen(SAVE_FOLDER_PREFIX));
 
-			_file = g_system->getSavefileManager()->openForLoading(saveName);
 		} else {
-			_file = f;
+			// First try to open file in game folder
+			Common::File *f = new Common::File();
+			if (!f->open(getFSNode(file_name.GetNullableCStr()))) {
+				delete f;
+				_file = nullptr;
+			} else {
+				_file = f;
+			}
 		}
 
 	} else {
-		// All newly created files are created as save files
-		_outSave = g_system->getSavefileManager()->openForSaving(file_name, false);
-		if (_outSave) {
+		if (!file_name.CompareLeftNoCase(SAVE_FOLDER_PREFIX)) {
+			_outSave = g_system->getSavefileManager()->openForSaving(
+				file_name + strlen(SAVE_FOLDER_PREFIX), false);
+		} else if (file_name == "warnings.log") {
+			_outSave = g_system->getSavefileManager()->openForSaving(file_name, false);
+		} else {
+			error("Creating files is only supported for savegames");
+		}
+
+		if (_outSave)
 			// Any data written has to first go through the memory stream buffer,
 			// since the savegame code uses Seeks, which OutSaveFile doesn't support
 			_file = &_writeBuffer;
-		}
 	}
 }
 
diff --git a/engines/ags/shared/util/filestream.h b/engines/ags/shared/util/filestream.h
index ff9994c111..491e552fad 100644
--- a/engines/ags/shared/util/filestream.h
+++ b/engines/ags/shared/util/filestream.h
@@ -33,6 +33,8 @@ namespace AGS3 {
 namespace AGS {
 namespace Shared {
 
+extern const char *SAVE_FOLDER_PREFIX;
+
 class FileStream : public DataStream {
 public:
 


Commit: 6f7c777a211c4219c3d93952c1ae1140fbb8aea9
    https://github.com/scummvm/scummvm/commit/6f7c777a211c4219c3d93952c1ae1140fbb8aea9
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Sound cleanup and hookup to ScummVM decoders

It isn't perfect.. some of the SOUNDCLIP variables don't do
anything yet. But it at least properly implements playback
of sound now

Changed paths:
    engines/ags/engine/ac/audiochannel.cpp
    engines/ags/engine/ac/audioclip.cpp
    engines/ags/engine/ac/global_audio.cpp
    engines/ags/engine/game/savegame.cpp
    engines/ags/engine/game/savegame_components.cpp
    engines/ags/engine/media/audio/audio.cpp
    engines/ags/engine/media/audio/clip_mydumbmod.cpp
    engines/ags/engine/media/audio/clip_mydumbmod.h
    engines/ags/engine/media/audio/clip_mymidi.cpp
    engines/ags/engine/media/audio/clip_mymidi.h
    engines/ags/engine/media/audio/clip_mymp3.cpp
    engines/ags/engine/media/audio/clip_mymp3.h
    engines/ags/engine/media/audio/clip_myogg.cpp
    engines/ags/engine/media/audio/clip_myogg.h
    engines/ags/engine/media/audio/clip_mystaticmp3.cpp
    engines/ags/engine/media/audio/clip_mystaticmp3.h
    engines/ags/engine/media/audio/clip_mystaticogg.cpp
    engines/ags/engine/media/audio/clip_mystaticogg.h
    engines/ags/engine/media/audio/clip_mywave.cpp
    engines/ags/engine/media/audio/clip_mywave.h
    engines/ags/engine/media/audio/sound.cpp
    engines/ags/engine/media/audio/sound.h
    engines/ags/engine/media/audio/soundcache.cpp
    engines/ags/engine/media/audio/soundcache.h
    engines/ags/engine/media/audio/soundclip.cpp
    engines/ags/engine/media/audio/soundclip.h
    engines/ags/lib/audio/midi.cpp
    engines/ags/lib/audio/midi.h
    engines/ags/lib/audio/ogg.cpp
    engines/ags/lib/audio/ogg.h
    engines/ags/music.cpp
    engines/ags/music.h


diff --git a/engines/ags/engine/ac/audiochannel.cpp b/engines/ags/engine/ac/audiochannel.cpp
index 31bb032c9a..5659ead8d6 100644
--- a/engines/ags/engine/ac/audiochannel.cpp
+++ b/engines/ags/engine/ac/audiochannel.cpp
@@ -58,7 +58,7 @@ int AudioChannel_GetPanning(ScriptAudioChannel *channel) {
 	auto *ch = lock.GetChannelIfPlaying(channel->id);
 
 	if (ch) {
-		return ch->panningAsPercentage;
+		return ch->_panningAsPercentage;
 	}
 	return 0;
 }
@@ -72,7 +72,7 @@ void AudioChannel_SetPanning(ScriptAudioChannel *channel, int newPanning) {
 
 	if (ch) {
 		ch->set_panning(((newPanning + 100) * 255) / 200);
-		ch->panningAsPercentage = newPanning;
+		ch->_panningAsPercentage = newPanning;
 	}
 }
 
@@ -81,7 +81,7 @@ ScriptAudioClip *AudioChannel_GetPlayingClip(ScriptAudioChannel *channel) {
 	auto *ch = lock.GetChannelIfPlaying(channel->id);
 
 	if (ch) {
-		return (ScriptAudioClip *)ch->sourceClip;
+		return (ScriptAudioClip *)ch->_sourceClip;
 	}
 	return nullptr;
 }
@@ -189,9 +189,9 @@ void AudioChannel_SetRoomLocation(ScriptAudioChannel *channel, int xPos, int yPo
 
 	if (ch) {
 		int maxDist = ((xPos > thisroom.Width / 2) ? xPos : (thisroom.Width - xPos)) - AMBIENCE_FULL_DIST;
-		ch->xSource = (xPos > 0) ? xPos : -1;
-		ch->ySource = yPos;
-		ch->maximumPossibleDistanceAway = maxDist;
+		ch->_xSource = (xPos > 0) ? xPos : -1;
+		ch->_ySource = yPos;
+		ch->_maximumPossibleDistanceAway = maxDist;
 		if (xPos > 0) {
 			update_directional_sound_vol();
 		} else {
diff --git a/engines/ags/engine/ac/audioclip.cpp b/engines/ags/engine/ac/audioclip.cpp
index cd40476752..19b4c41630 100644
--- a/engines/ags/engine/ac/audioclip.cpp
+++ b/engines/ags/engine/ac/audioclip.cpp
@@ -54,7 +54,7 @@ void AudioClip_Stop(ScriptAudioClip *clip) {
 	AudioChannelsLock lock;
 	for (int i = 0; i < MAX_SOUND_CHANNELS; i++) {
 		auto *ch = lock.GetChannelIfPlaying(i);
-		if ((ch != nullptr) && (ch->sourceClip == clip)) {
+		if ((ch != nullptr) && (ch->_sourceClip == clip)) {
 			AudioChannel_Stop(&scrAudioChannel[i]);
 		}
 	}
diff --git a/engines/ags/engine/ac/global_audio.cpp b/engines/ags/engine/ac/global_audio.cpp
index 1cf2aaf71e..78c535537d 100644
--- a/engines/ags/engine/ac/global_audio.cpp
+++ b/engines/ags/engine/ac/global_audio.cpp
@@ -86,7 +86,7 @@ void PlayAmbientSound(int channel, int sndnum, int vol, int x, int y) {
 
 		debug_script_log("Playing ambient sound %d on channel %d", sndnum, channel);
 		ambient[channel].channel = channel;
-		asound->priority = 15;  // ambient sound higher priority than normal sfx
+		asound->_priority = 15;  // ambient sound higher priority than normal sfx
 		set_clip_to_channel(channel, asound);
 	}
 	// calculate the maximum distance away the player can be, using X
@@ -161,7 +161,7 @@ int PlaySoundEx(int val1, int channel) {
 		return -1;
 	}
 
-	soundfx->priority = 10;
+	soundfx->_priority = 10;
 	soundfx->set_volume(play.sound_volume);
 	set_clip_to_channel(channel, soundfx);
 	return channel;
@@ -547,7 +547,7 @@ static bool play_voice_clip_on_channel(const String &voice_name) {
 	if (speechmp3 != nullptr) {
 		if (!speechmp3->play()) {
 			// not assigned to a channel, so clean up manually.
-			speechmp3->destroy();
+			//speechmp3->destroy();
 			delete speechmp3;
 			speechmp3 = nullptr;
 		}
diff --git a/engines/ags/engine/game/savegame.cpp b/engines/ags/engine/game/savegame.cpp
index 89d746abdb..a5823f2956 100644
--- a/engines/ags/engine/game/savegame.cpp
+++ b/engines/ags/engine/game/savegame.cpp
@@ -571,10 +571,10 @@ HSaveError DoAfterRestore(const PreservedParams &pp, const RestoredData &r_data)
 				ch->set_volume_direct(chan_info.VolAsPercent, chan_info.Vol);
 				ch->set_speed(chan_info.Speed);
 				ch->set_panning(chan_info.Pan);
-				ch->panningAsPercentage = chan_info.PanAsPercent;
-				ch->xSource = chan_info.XSource;
-				ch->ySource = chan_info.YSource;
-				ch->maximumPossibleDistanceAway = chan_info.MaxDist;
+				ch->_panningAsPercentage = chan_info.PanAsPercent;
+				ch->_xSource = chan_info.XSource;
+				ch->_ySource = chan_info.YSource;
+				ch->_maximumPossibleDistanceAway = chan_info.MaxDist;
 			}
 		}
 		if ((cf_in_chan > 0) && (lock.GetChannel(cf_in_chan) != nullptr))
diff --git a/engines/ags/engine/game/savegame_components.cpp b/engines/ags/engine/game/savegame_components.cpp
index 55c30b4417..f5fb62c0b4 100644
--- a/engines/ags/engine/game/savegame_components.cpp
+++ b/engines/ags/engine/game/savegame_components.cpp
@@ -361,20 +361,16 @@ HSaveError WriteAudio(PStream out) {
 	// Audio clips and crossfade
 	for (int i = 0; i <= MAX_SOUND_CHANNELS; i++) {
 		auto *ch = lock.GetChannelIfPlaying(i);
-		if ((ch != nullptr) && (ch->sourceClip != nullptr)) {
-			out->WriteInt32(((ScriptAudioClip *)ch->sourceClip)->id);
+		if ((ch != nullptr) && (ch->_sourceClip != nullptr)) {
+			out->WriteInt32(((ScriptAudioClip *)ch->_sourceClip)->id);
 			out->WriteInt32(ch->get_pos());
-			out->WriteInt32(ch->priority);
-			out->WriteInt32(ch->repeat ? 1 : 0);
-			out->WriteInt32(ch->vol);
-			out->WriteInt32(ch->panning);
-			out->WriteInt32(ch->volAsPercentage);
-			out->WriteInt32(ch->panningAsPercentage);
+			out->WriteInt32(ch->_priority);
+ 			out->WriteInt32(ch->_panningAsPercentage);
 			out->WriteInt32(ch->get_speed());
 			// since version 1
-			out->WriteInt32(ch->xSource);
-			out->WriteInt32(ch->ySource);
-			out->WriteInt32(ch->maximumPossibleDistanceAway);
+			out->WriteInt32(ch->_xSource);
+			out->WriteInt32(ch->_ySource);
+			out->WriteInt32(ch->_maximumPossibleDistanceAway);
 		} else {
 			out->WriteInt32(-1);
 		}
diff --git a/engines/ags/engine/media/audio/audio.cpp b/engines/ags/engine/media/audio/audio.cpp
index 954f229278..21e7aef891 100644
--- a/engines/ags/engine/media/audio/audio.cpp
+++ b/engines/ags/engine/media/audio/audio.cpp
@@ -202,9 +202,9 @@ static int find_free_audio_channel(ScriptAudioClip *clip, int priority, bool int
 			stop_and_destroy_channel(i);
 			break;
 		}
-		if ((ch->priority < lowestPrioritySoFar) &&
-			(ch->sourceClipType == clip->type)) {
-			lowestPrioritySoFar = ch->priority;
+		if ((ch->_priority < lowestPrioritySoFar) &&
+			(ch->_sourceClipType == clip->type)) {
+			lowestPrioritySoFar = ch->_priority;
 			lowestPriorityID = i;
 		}
 	}
@@ -259,8 +259,8 @@ SOUNDCLIP *load_sound_clip(ScriptAudioClip *audioClip, bool repeat) {
 	}
 	if (soundClip != nullptr) {
 		soundClip->set_volume_percent(audioClip->defaultVolume);
-		soundClip->sourceClip = audioClip;
-		soundClip->sourceClipType = audioClip->type;
+		soundClip->_sourceClip = audioClip;
+		soundClip->_sourceClipType = audioClip->type;
 	}
 	return soundClip;
 }
@@ -337,7 +337,7 @@ static void audio_update_polled_stuff() {
 
 // Applies a volume drop modifier to the clip, in accordance to its audio type
 static void apply_volume_drop_to_clip(SOUNDCLIP *clip) {
-	int audiotype = clip->sourceClipType;
+	int audiotype = clip->_sourceClipType;
 	clip->apply_volume_modifier(-(game.audioClipTypes[audiotype].volume_reduction_while_speech_playing * 255 / 100));
 }
 
@@ -370,7 +370,7 @@ ScriptAudioChannel *play_audio_clip_on_channel(int channel, ScriptAudioClip *cli
 		}
 		return nullptr;
 	}
-	soundfx->priority = priority;
+	soundfx->_priority = priority;
 
 	if (play.crossfading_in_channel == channel) {
 		soundfx->set_volume_percent(0);
@@ -573,13 +573,13 @@ void update_directional_sound_vol() {
 
 	for (int chnum = 1; chnum < MAX_SOUND_CHANNELS; chnum++) {
 		auto *ch = lock.GetChannelIfPlaying(chnum);
-		if ((ch != nullptr) && (ch->xSource >= 0)) {
+		if ((ch != nullptr) && (ch->_xSource >= 0)) {
 			ch->apply_directional_modifier(
-				get_volume_adjusted_for_distance(ch->vol,
-					ch->xSource,
-					ch->ySource,
-					ch->maximumPossibleDistanceAway) -
-				ch->vol);
+				get_volume_adjusted_for_distance(ch->_vol,
+					ch->_xSource,
+					ch->_ySource,
+					ch->_maximumPossibleDistanceAway) -
+				ch->_vol);
 		}
 	}
 }
@@ -685,11 +685,11 @@ static int play_sound_priority(int val1, int priority) {
 				assert(usechan == i);
 				auto *chan = lock.GetChannel(usechan);
 				if (chan)
-					chan->priority = priority;
+					chan->_priority = priority;
 			}
 			return usechan;
-		} else if (ch->priority < lowest_pri) {
-			lowest_pri = ch->priority;
+		} else if (ch->_priority < lowest_pri) {
+			lowest_pri = ch->_priority;
 			lowest_pri_id = i;
 		}
 
@@ -705,7 +705,7 @@ static int play_sound_priority(int val1, int priority) {
 			assert(usechan == lowest_pri_id);
 			auto *ch = lock.GetChannel(usechan);
 			if (ch)
-				ch->priority = priority;
+				ch->_priority = priority;
 			return usechan;
 		}
 	}
@@ -830,7 +830,7 @@ void apply_volume_drop_modifier(bool applyModifier) {
 
 	for (int i = 0; i < MAX_SOUND_CHANNELS; i++) {
 		auto *ch = lock.GetChannelIfPlaying(i);
-		if (ch && ch->sourceClip != nullptr) {
+		if (ch && ch->_sourceClip != nullptr) {
 			if (applyModifier)
 				apply_volume_drop_to_clip(ch);
 			else
diff --git a/engines/ags/engine/media/audio/clip_mydumbmod.cpp b/engines/ags/engine/media/audio/clip_mydumbmod.cpp
index d5c2262379..ae0921b1fa 100644
--- a/engines/ags/engine/media/audio/clip_mydumbmod.cpp
+++ b/engines/ags/engine/media/audio/clip_mydumbmod.cpp
@@ -28,6 +28,7 @@
 #include "ags/engine/media/audio/audiointernaldefs.h"
 
 namespace AGS3 {
+#ifdef DEPRECATED
 
 void al_duh_set_loop(AL_DUH_PLAYER *dp, int loop) {
 	DUH_SIGRENDERER *sr = al_duh_get_sigrenderer(dp);
@@ -178,6 +179,7 @@ MYMOD::MYMOD() : SOUNDCLIP() {
 	duhPlayer = nullptr;
 }
 
+#endif
 } // namespace AGS3
 
 #endif // DUMB_MOD_PLAYER
diff --git a/engines/ags/engine/media/audio/clip_mydumbmod.h b/engines/ags/engine/media/audio/clip_mydumbmod.h
index 370de3f344..ad98d49c2f 100644
--- a/engines/ags/engine/media/audio/clip_mydumbmod.h
+++ b/engines/ags/engine/media/audio/clip_mydumbmod.h
@@ -27,6 +27,7 @@
 #include "ags/engine/media/audio/soundclip.h"
 
 namespace AGS3 {
+#ifdef DEPRECATED
 
 #define VOLUME_TO_DUMB_VOL(vol) ((float)vol) / 256.0
 
@@ -74,7 +75,7 @@ protected:
 	// Returns real MOD/XM playing position
 	int get_real_mod_pos();
 };
-
+#endif
 } // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/media/audio/clip_mymidi.cpp b/engines/ags/engine/media/audio/clip_mymidi.cpp
index ff0a1fd481..01e0e3b4bc 100644
--- a/engines/ags/engine/media/audio/clip_mymidi.cpp
+++ b/engines/ags/engine/media/audio/clip_mymidi.cpp
@@ -27,103 +27,79 @@
 
 namespace AGS3 {
 
-void MYMIDI::poll() {
-	if (state_ != SoundClipPlaying) {
-		return;
-	}
-
-	if (midi_pos < 0)
-		state_ = SoundClipStopped;
-}
-
-void MYMIDI::adjust_volume() {
-	if (!is_playing()) {
-		return;
-	}
-	AGS3::set_volume(-1, get_final_volume());
-}
-
-void MYMIDI::set_volume(int newvol) {
-	vol = newvol;
-	adjust_volume();
+MYMIDI::MYMIDI(Common::SeekableReadStream *data, bool repeat) :
+		_data(data), _repeat(repeat), lengthInSeconds(0) {
 }
 
 void MYMIDI::destroy() {
-	stop_midi();
-
-	if (tune) {
-		destroy_midi(tune);
-	}
-	tune = nullptr;
-
-	state_ = SoundClipStopped;
+	stop();
+	delete _data;
+	_data = nullptr;
 }
 
 void MYMIDI::seek(int pos) {
-	if (!is_playing()) {
-		return;
-	}
-	midi_seek(pos);
+	warning("TODO: MYMIDI::seek");
 }
 
 int MYMIDI::get_pos() {
-	if (!is_playing()) {
-		return -1;
-	}
-	return midi_pos;
+	// We don't know ms with midi
+	return 0;
 }
 
 int MYMIDI::get_pos_ms() {
-	return 0;                   // we don't know ms with midi
+	// We don't know ms with midi
+	return 0;
 }
 
 int MYMIDI::get_length_ms() {
+	warning("TODO: MYMIDI::get_length_ms");
 	return lengthInSeconds * 1000;
 }
 
-int MYMIDI::get_voice() {
-	// voice is N/A for midi
-	return -1;
-}
-
 void MYMIDI::pause() {
-	if (state_ != SoundClipPlaying) {
-		return;
-	}
-	midi_pause();
-	state_ = SoundClipPaused;
+	::AGS::g_music->pause();
+	_state = SoundClipPaused;
 }
 
 void MYMIDI::resume() {
-	if (state_ != SoundClipPaused) {
+	if (_state != SoundClipPaused)
 		return;
-	}
-	midi_resume();
-	state_ = SoundClipPlaying;
-}
 
-int MYMIDI::get_sound_type() {
-	return MUS_MIDI;
+	::AGS::g_music->resume();
+	_state = SoundClipPlaying;
 }
 
 int MYMIDI::play() {
-	if (tune == nullptr) {
-		return 0;
-	}
+	::AGS::g_music->playMusic(_data, _repeat);
+	_state =  SoundClipPlaying;
+	return 1;
+}
 
-	lengthInSeconds = get_midi_length(tune);
-	if (AGS3::play_midi(tune, repeat)) {
-		lengthInSeconds = 0;
-		return 0;
-	}
+void MYMIDI::stop() {
+	::AGS::g_music->stop();
+}
 
-	state_ = SoundClipPlaying;
-	return 1;
+bool MYMIDI::is_playing() const {
+	return ::AGS::g_music->isPlaying();
+}
+
+int MYMIDI::get_volume() const {
+	return _mixer->getVolumeForSoundType(Audio::Mixer::kMusicSoundType);
 }
 
-MYMIDI::MYMIDI() : SOUNDCLIP() {
-	tune = nullptr;
-	lengthInSeconds = 0;
+void MYMIDI::set_volume(int volume) {
+	_mixer->setVolumeForSoundType(Audio::Mixer::kMusicSoundType, volume);
+}
+
+void MYMIDI::set_panning(int newPanning) {
+	// No implementation for MIDI
+}
+
+/*
+int MYMIDI::get_voice() {
+	// voice is N/A for midi
+	return -1;
 }
+*/
 
 } // namespace AGS3
diff --git a/engines/ags/engine/media/audio/clip_mymidi.h b/engines/ags/engine/media/audio/clip_mymidi.h
index 87e21d7704..78c7b4fea1 100644
--- a/engines/ags/engine/media/audio/clip_mymidi.h
+++ b/engines/ags/engine/media/audio/clip_mymidi.h
@@ -29,12 +29,12 @@ namespace AGS3 {
 
 // MIDI
 struct MYMIDI : public SOUNDCLIP {
-	MIDI *tune;
+	Common::SeekableReadStream *_data;
+	bool _repeat;
 	int lengthInSeconds;
 
-	void poll() override;
-
-	void set_volume(int newvol) override;
+	MYMIDI(Common::SeekableReadStream *data, bool repeat);
+	~MYMIDI() override {}
 
 	void destroy() override;
 
@@ -50,15 +50,16 @@ struct MYMIDI : public SOUNDCLIP {
 
 	void resume() override;
 
-	int get_sound_type() override;
+	int get_sound_type() const override {
+		return MUS_MIDI;
+	}
 
 	int play() override;
-
-	MYMIDI();
-
-protected:
-	int get_voice() override;
-	void adjust_volume() override;
+	void stop() override;
+	bool is_playing() const override;
+	int get_volume() const override;
+	void set_volume(int volume) override;
+	void set_panning(int newPanning) override;
 };
 
 } // namespace AGS3
diff --git a/engines/ags/engine/media/audio/clip_mymp3.cpp b/engines/ags/engine/media/audio/clip_mymp3.cpp
index ce87812b46..28d1e0e70a 100644
--- a/engines/ags/engine/media/audio/clip_mymp3.cpp
+++ b/engines/ags/engine/media/audio/clip_mymp3.cpp
@@ -33,6 +33,7 @@
 #include "ags/ags.h"
 
 namespace AGS3 {
+#ifdef DEPRECATED
 
 void MYMP3::poll() {
 	if (state_ != SoundClipPlaying) {
@@ -182,6 +183,7 @@ MYMP3::MYMP3() : SOUNDCLIP() {
 	chunksize = 0;
 }
 
+#endif
 } // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/media/audio/clip_mymp3.h b/engines/ags/engine/media/audio/clip_mymp3.h
index 148799b015..a8c283454e 100644
--- a/engines/ags/engine/media/audio/clip_mymp3.h
+++ b/engines/ags/engine/media/audio/clip_mymp3.h
@@ -28,6 +28,7 @@
 #include "ags/engine/media/audio/soundclip.h"
 
 namespace AGS3 {
+#ifdef  DEPRECATED
 
 struct MYMP3 : public SOUNDCLIP {
 	ALMP3_MP3STREAM *stream;
@@ -54,7 +55,7 @@ protected:
 private:
 	void adjust_stream();
 };
-
+#endif
 } // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/media/audio/clip_myogg.cpp b/engines/ags/engine/media/audio/clip_myogg.cpp
index c2c16a770d..cc52a6e223 100644
--- a/engines/ags/engine/media/audio/clip_myogg.cpp
+++ b/engines/ags/engine/media/audio/clip_myogg.cpp
@@ -31,7 +31,7 @@
 #include "ags/engine/platform/base/agsplatformdriver.h"
 
 namespace AGS3 {
-
+#ifdef DEPRECATED
 void MYOGG::poll() {
 	if (state_ != SoundClipPlaying) {
 		return;
@@ -202,5 +202,5 @@ MYOGG::MYOGG() : SOUNDCLIP() {
 	last_but_one = 0;
 	last_ms_offs = 0;
 }
-
+#endif
 } // namespace AGS3
diff --git a/engines/ags/engine/media/audio/clip_myogg.h b/engines/ags/engine/media/audio/clip_myogg.h
index 951ae336b3..f619ec5a90 100644
--- a/engines/ags/engine/media/audio/clip_myogg.h
+++ b/engines/ags/engine/media/audio/clip_myogg.h
@@ -28,7 +28,7 @@
 #include "ags/engine/media/audio/soundclip.h"
 
 namespace AGS3 {
-
+#ifdef DEPRECATED
 struct MYOGG : public SOUNDCLIP {
 	ALOGG_OGGSTREAM *stream;
 	PACKFILE *in;
@@ -67,6 +67,7 @@ private:
 	void adjust_stream();
 };
 
+#endif
 } // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/media/audio/clip_mystaticmp3.cpp b/engines/ags/engine/media/audio/clip_mystaticmp3.cpp
index 65ae8b3ef6..43c336d713 100644
--- a/engines/ags/engine/media/audio/clip_mystaticmp3.cpp
+++ b/engines/ags/engine/media/audio/clip_mystaticmp3.cpp
@@ -32,6 +32,7 @@
 #include "ags/ags.h"
 
 namespace AGS3 {
+#ifdef DEPRECATED
 
 extern int our_eip;
 
@@ -159,7 +160,7 @@ MYSTATICMP3::MYSTATICMP3() : SOUNDCLIP() {
 	tune = nullptr;
 	mp3buffer = nullptr;
 }
-
+#endif
 } // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/media/audio/clip_mystaticmp3.h b/engines/ags/engine/media/audio/clip_mystaticmp3.h
index 575df1583b..6592ae8c19 100644
--- a/engines/ags/engine/media/audio/clip_mystaticmp3.h
+++ b/engines/ags/engine/media/audio/clip_mystaticmp3.h
@@ -27,7 +27,7 @@
 #include "ags/engine/media/audio/soundclip.h"
 
 namespace AGS3 {
-
+#ifdef DEPRECATED
 // pre-loaded (non-streaming) MP3 file
 struct MYSTATICMP3 : public SOUNDCLIP {
 	ALMP3_MP3 *tune;
@@ -60,6 +60,7 @@ protected:
 private:
 	void adjust_stream();
 };
+#endif
 
 } // namespace AGS3
 
diff --git a/engines/ags/engine/media/audio/clip_mystaticogg.cpp b/engines/ags/engine/media/audio/clip_mystaticogg.cpp
index 84654620ce..363bfa5617 100644
--- a/engines/ags/engine/media/audio/clip_mystaticogg.cpp
+++ b/engines/ags/engine/media/audio/clip_mystaticogg.cpp
@@ -20,195 +20,12 @@
  *
  */
 
-#include "ags/engine/media/audio/audiodefines.h"
 #include "ags/engine/media/audio/clip_mystaticogg.h"
-#include "ags/engine/media/audio/audiointernaldefs.h"
-#include "ags/engine/media/audio/soundcache.h"
-#include "ags/engine/util/mutex_lock.h"
-
-#include "ags/engine/platform/base/agsplatformdriver.h"
-#include "ags/lib/audio/digi.h"
-#include "ags/lib/audio/ogg.h"
+#include "audio/decoders/vorbis.h"
+#include "common/memstream.h"
 
 namespace AGS3 {
 
 extern int use_extra_sound_offset;  // defined in ac.cpp
 
-void MYSTATICOGG::poll() {
-	if (state_ != SoundClipPlaying) {
-		return;
-	}
-
-	if (alogg_poll_ogg(tune) == ALOGG_POLL_PLAYJUSTFINISHED) {
-		if (!repeat) {
-			state_ = SoundClipStopped;
-		}
-	} else get_pos(); // call this to keep the last_but_one stuff up to date
-}
-
-void MYSTATICOGG::adjust_stream() {
-	if (!is_playing()) {
-		return;
-	}
-	alogg_adjust_ogg(tune, get_final_volume(), panning, speed, repeat);
-}
-
-void MYSTATICOGG::adjust_volume() {
-	adjust_stream();
-}
-
-void MYSTATICOGG::set_volume(int newvol) {
-	vol = newvol;
-	adjust_stream();
-}
-
-void MYSTATICOGG::set_speed(int new_speed) {
-	speed = new_speed;
-	adjust_stream();
-}
-
-void MYSTATICOGG::destroy() {
-	if (tune) {
-		alogg_stop_ogg(tune);
-		alogg_destroy_ogg(tune);
-	}
-	tune = nullptr;
-
-	if (mp3buffer) {
-		sound_cache_free(mp3buffer, false);
-	}
-	mp3buffer = nullptr;
-
-	state_ = SoundClipStopped;
-}
-
-void MYSTATICOGG::seek(int pos) {
-	if (!is_playing()) {
-		return;
-	}
-
-	// we stop and restart it because otherwise the buffer finishes
-	// playing first and the seek isn't quite accurate
-	alogg_stop_ogg(tune);
-	state_ = SoundClipInitial;
-	play_from(pos);
-}
-
-int MYSTATICOGG::get_pos() {
-	if (!is_playing()) {
-		return -1;
-	}
-	return get_pos_ms();
-}
-
-int MYSTATICOGG::get_pos_ms() {
-	if (!is_playing()) {
-		return -1;
-	}
-
-	// Unfortunately the alogg_get_pos_msecs function
-	// returns the ms offset that was last decoded, so it's always
-	// ahead of the actual playback. Therefore we have this
-	// hideous hack below to sort it out.
-	if (!alogg_is_playing_ogg(tune))
-		return 0;
-
-	AUDIOSTREAM *str = alogg_get_audiostream_ogg(tune);
-	long offs = (voice_get_position(str->voice) * 1000) / str->samp->freq;
-
-	if (last_ms_offs != alogg_get_pos_msecs_ogg(tune)) {
-		last_but_one_but_one = last_but_one;
-		last_but_one = last_ms_offs;
-		last_ms_offs = alogg_get_pos_msecs_ogg(tune);
-	}
-
-	// just about to switch buffers
-	if (offs < 0)
-		return last_but_one;
-
-	int end_of_stream = alogg_is_end_of_ogg(tune);
-
-	if ((str->active == 1) && (last_but_one_but_one > 0) && (str->locked == nullptr)) {
-		switch (end_of_stream) {
-		case 0:
-		case 2:
-			offs -= (last_but_one - last_but_one_but_one);
-			break;
-		case 1:
-			offs -= (last_but_one - last_but_one_but_one);
-			break;
-		}
-	}
-
-	if (end_of_stream == 1) {
-		return offs + last_but_one + extraOffset;
-	}
-
-	return offs + last_but_one_but_one + extraOffset;
-}
-
-int MYSTATICOGG::get_length_ms() {
-	if (tune == nullptr) {
-		return -1;
-	}
-	return alogg_get_length_msecs_ogg(tune);
-}
-
-int MYSTATICOGG::get_voice() {
-	if (!is_playing()) {
-		return -1;
-	}
-	AUDIOSTREAM *ast = alogg_get_audiostream_ogg(tune);
-	if (ast)
-		return ast->voice;
-	return -1;
-}
-
-int MYSTATICOGG::get_sound_type() {
-	return MUS_OGG;
-}
-
-int MYSTATICOGG::play_from(int position) {
-	if (tune == nullptr) {
-		return 0;
-	}
-
-	if (use_extra_sound_offset)
-		extraOffset = ((16384 / (alogg_get_wave_is_stereo_ogg(tune) ? 2 : 1)) * 1000) / alogg_get_wave_freq_ogg(tune);
-	else
-		extraOffset = 0;
-
-	if (alogg_play_ex_ogg(tune, 16384, vol, panning, 1000, repeat) != ALOGG_OK) {
-		return 0;
-	}
-
-	last_ms_offs = position;
-	last_but_one = position;
-	last_but_one_but_one = position;
-
-	if (position > 0)
-		alogg_seek_abs_msecs_ogg(tune, position);
-
-	state_ = SoundClipPlaying;
-
-	if (!psp_audio_multithreaded)
-		poll();
-
-	return 1;
-}
-
-int MYSTATICOGG::play() {
-	return play_from(0);
-}
-
-MYSTATICOGG::MYSTATICOGG() : SOUNDCLIP() {
-	tune = nullptr;
-	mp3buffer = nullptr;
-	mp3buffersize = 0;
-	extraOffset = 0;
-	last_but_one = 0;
-	last_ms_offs = 0;
-	last_but_one_but_one = 0;
-}
-
 } // namespace AGS3
diff --git a/engines/ags/engine/media/audio/clip_mystaticogg.h b/engines/ags/engine/media/audio/clip_mystaticogg.h
index cffe990090..56b2bb00d2 100644
--- a/engines/ags/engine/media/audio/clip_mystaticogg.h
+++ b/engines/ags/engine/media/audio/clip_mystaticogg.h
@@ -24,51 +24,20 @@
 #define AGS_ENGINE_MEDIA_AUDIO_CLIP_MYSTATICOGG_H
 
 #include "ags/lib/audio/ogg.h"
-#include "ags/engine/media/audio/soundclip.h"
 
 namespace AGS3 {
+#ifdef DEPRECATED
+/**
+ * Pre-loaded (non-streaming) OGG file
+ */
+struct MYSTATICOGG : public AUDIO_STREAM {
+	MYSTATICOGG(const byte *data, size_t len, bool repeat);
 
-// pre-loaded (non-streaming) OGG file
-struct MYSTATICOGG : public SOUNDCLIP {
-	ALOGG_OGG *tune;
-	char *mp3buffer;
-	int mp3buffersize;
-	int extraOffset;
-
-	int last_but_one_but_one;
-	int last_but_one;
-	int last_ms_offs;
-
-	void poll() override;
-
-	void set_volume(int newvol) override;
-	void set_speed(int new_speed) override;
-
-	void destroy() override;
-
-	void seek(int pos) override;
-
-	int get_pos() override;
-
-	int get_pos_ms() override;
-
-	int get_length_ms() override;
-
-	int get_sound_type() override;
-
-	int play_from(int position) override;
-
-	int play() override;
-
-	MYSTATICOGG();
-
-protected:
-	int get_voice() override;
-	void adjust_volume() override;
-private:
-	void adjust_stream();
+	int get_sound_type() override {
+		return MUS_OGG;
+	}
 };
-
+#endif
 } // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/media/audio/clip_mywave.cpp b/engines/ags/engine/media/audio/clip_mywave.cpp
index f11f1b22dd..6a6d02b6ba 100644
--- a/engines/ags/engine/media/audio/clip_mywave.cpp
+++ b/engines/ags/engine/media/audio/clip_mywave.cpp
@@ -31,6 +31,7 @@
 #include "ags/engine/platform/base/agsplatformdriver.h"
 
 namespace AGS3 {
+#ifdef  DEPRECATED
 
 void MYWAVE::poll() {
 	if (state_ != SoundClipPlaying) {
@@ -131,5 +132,5 @@ MYWAVE::MYWAVE() : SOUNDCLIP() {
 	wave = nullptr;
 	voice = -1;
 }
-
+#endif
 } // namespace AGS3
diff --git a/engines/ags/engine/media/audio/clip_mywave.h b/engines/ags/engine/media/audio/clip_mywave.h
index a9f75b8319..2e665d088d 100644
--- a/engines/ags/engine/media/audio/clip_mywave.h
+++ b/engines/ags/engine/media/audio/clip_mywave.h
@@ -26,6 +26,7 @@
 #include "ags/engine/media/audio/soundclip.h"
 
 namespace AGS3 {
+#ifdef DEPRECATED
 
 // My new MP3STREAM wrapper
 struct MYWAVE : public SOUNDCLIP {
@@ -55,7 +56,7 @@ protected:
 	int get_voice() override;
 	void adjust_volume() override;
 };
-
+#endif
 } // namespace AGS3
 
 #endif
diff --git a/engines/ags/engine/media/audio/sound.cpp b/engines/ags/engine/media/audio/sound.cpp
index 98134b9456..25dd52a428 100644
--- a/engines/ags/engine/media/audio/sound.cpp
+++ b/engines/ags/engine/media/audio/sound.cpp
@@ -26,8 +26,6 @@
 //
 //=============================================================================
 
-//include <ctype.h> // for toupper
-
 #include "ags/shared/core/platform.h"
 #include "ags/shared/util/wgt2allg.h"
 #include "ags/engine/ac/file.h"
@@ -35,22 +33,15 @@
 #include "ags/engine/media/audio/sound.h"
 #include "ags/engine/media/audio/audiointernaldefs.h"
 #include "ags/engine/media/audio/clip_mywave.h"
-#ifndef NO_MP3_PLAYER
-#include "ags/engine/media/audio/clip_mymp3.h"
-#include "ags/engine/media/audio/clip_mystaticmp3.h"
-#endif
-#include "ags/engine/media/audio/clip_myogg.h"
-#include "ags/engine/media/audio/clip_mystaticogg.h"
-#include "ags/engine/media/audio/clip_mymidi.h"
-#ifdef JGMOD_MOD_PLAYER
-#include "ags/engine/media/audio/clip_myjgmod.h"
-#endif
-#ifdef DUMB_MOD_PLAYER
-#include "ags/engine/media/audio/clip_mydumbmod.h"
-#endif
 #include "ags/engine/media/audio/soundcache.h"
+#include "ags/engine/media/audio/clip_mymidi.h"
 #include "ags/engine/util/mutex_lock.h"
 #include "ags/ags.h"
+#include "common/memstream.h"
+#include "audio/mods/mod_xm_s3m.h"
+#include "audio/decoders/mp3.h"
+#include "audio/decoders/vorbis.h"
+#include "audio/decoders/wave.h"
 
 namespace AGS3 {
 
@@ -62,294 +53,71 @@ namespace AGS3 {
 #error Either JGMOD_MOD_PLAYER or DUMB_MOD_PLAYER should be defined.
 #endif
 
-// Load MIDI from PACKFILE stream
-extern MIDI *load_midi_pf(PACKFILE *pf);
-
-
 int use_extra_sound_offset = 0;
 
 
-
-MYWAVE *thiswave;
 SOUNDCLIP *my_load_wave(const AssetPath &asset_name, int voll, int loop) {
-	// Load via soundcache.
-	size_t dummy;
-	SAMPLE *new_sample = (SAMPLE *)get_cached_sound(asset_name, true, dummy);
-
-	if (new_sample == nullptr)
-		return nullptr;
-
-	thiswave = new MYWAVE();
-	thiswave->wave = new_sample;
-	thiswave->vol = voll;
-	thiswave->repeat = (loop != 0);
-
-	return thiswave;
-}
-
-PACKFILE *mp3in;
-
-#ifndef NO_MP3_PLAYER
-
-MYMP3 *thistune;
-
-SOUNDCLIP *my_load_mp3(const AssetPath &asset_name, int voll) {
-	size_t asset_size;
-	mp3in = PackfileFromAsset(asset_name, asset_size);
-	if (mp3in == nullptr)
-		return nullptr;
-
-	char *tmpbuffer = (char *)malloc(MP3CHUNKSIZE);
-	if (tmpbuffer == nullptr) {
-		pack_fclose(mp3in);
+	Common::SeekableReadStream *data = get_cached_sound(asset_name);
+	if (data) {
+		Audio::AudioStream *audioStream = Audio::makeWAVStream(data, DisposeAfterUse::YES);
+		return new SoundClipWave<MUS_WAVE>(audioStream, voll, loop);
+	} else {
 		return nullptr;
 	}
-	thistune = new MYMP3();
-	thistune->in = mp3in;
-	thistune->chunksize = MP3CHUNKSIZE;
-	thistune->filesize = asset_size;
-	thistune->vol = voll;
-
-	if (thistune->chunksize > (int)thistune->filesize)
-		thistune->chunksize = thistune->filesize;
-
-	pack_fread(tmpbuffer, thistune->chunksize, mp3in);
-
-	thistune->buffer = (char *)tmpbuffer;
-
-	{
-		AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
-		thistune->stream = almp3_create_mp3stream(tmpbuffer, thistune->chunksize, (thistune->filesize < 1));
-	}
-
-	if (thistune->stream == nullptr) {
-		free(tmpbuffer);
-		pack_fclose(mp3in);
-		delete thistune;
-		return nullptr;
-	}
-
-	return thistune;
 }
 
-
-
-MYSTATICMP3 *thismp3;
 SOUNDCLIP *my_load_static_mp3(const AssetPath &asset_name, int voll, bool loop) {
-	// Load via soundcache.
-	size_t muslen = 0;
-	char *mp3buffer = get_cached_sound(asset_name, false, muslen);
-	if (mp3buffer == nullptr)
-		return nullptr;
-
-	// now, create an MP3 structure for it
-	thismp3 = new MYSTATICMP3();
-	if (thismp3 == nullptr) {
-		free(mp3buffer);
-		return nullptr;
-	}
-	thismp3->vol = voll;
-	thismp3->mp3buffer = nullptr;
-	thismp3->repeat = loop;
-
-	{
-		AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
-		thismp3->tune = almp3_create_mp3(mp3buffer, muslen);
-	}
-
-	if (thismp3->tune == nullptr) {
-		free(mp3buffer);
-		delete thismp3;
+	Common::SeekableReadStream *data = get_cached_sound(asset_name);
+	if (data) {
+		Audio::AudioStream *audioStream = Audio::makeMP3Stream(data, DisposeAfterUse::YES);
+		return new SoundClipWave<MUS_MP3>(audioStream, voll, false);
+	} else {
 		return nullptr;
 	}
-
-	thismp3->mp3buffer = mp3buffer;
-
-	return thismp3;
 }
 
-#else // NO_MP3_PLAYER
-
 SOUNDCLIP *my_load_mp3(const AssetPath &asset_name, int voll) {
-	return NULL;
-}
-
-SOUNDCLIP *my_load_static_mp3(const AssetPath &asset_name, int voll, bool loop) {
-	return NULL;
+	return my_load_static_mp3(asset_name, voll, false);
 }
 
-#endif // NO_MP3_PLAYER
-
-
-
-MYSTATICOGG *thissogg;
 SOUNDCLIP *my_load_static_ogg(const AssetPath &asset_name, int voll, bool loop) {
-	// Load via soundcache.
-	size_t muslen = 0;
-	char *mp3buffer = get_cached_sound(asset_name, false, muslen);
-	if (mp3buffer == nullptr)
-		return nullptr;
-
-	// now, create an OGG structure for it
-	thissogg = new MYSTATICOGG();
-	thissogg->vol = voll;
-	thissogg->repeat = loop;
-	thissogg->mp3buffer = mp3buffer;
-	thissogg->mp3buffersize = muslen;
-
-	thissogg->tune = alogg_create_ogg_from_buffer(mp3buffer, muslen);
-
-	if (thissogg->tune == nullptr) {
-		thissogg->destroy();
-		delete thissogg;
+	Common::SeekableReadStream *data = get_cached_sound(asset_name);
+	if (data) {
+		Audio::AudioStream *audioStream = Audio::makeVorbisStream(data, DisposeAfterUse::YES);
+		return new SoundClipWave<MUS_OGG>(audioStream, voll, loop);
+	} else {
 		return nullptr;
 	}
-
-	return thissogg;
 }
 
-MYOGG *thisogg;
 SOUNDCLIP *my_load_ogg(const AssetPath &asset_name, int voll) {
-	size_t asset_size;
-	mp3in = PackfileFromAsset(asset_name, asset_size);
-	if (mp3in == nullptr)
-		return nullptr;
-
-	char *tmpbuffer = (char *)malloc(MP3CHUNKSIZE);
-	if (tmpbuffer == nullptr) {
-		pack_fclose(mp3in);
-		return nullptr;
-	}
-
-	thisogg = new MYOGG();
-	thisogg->in = mp3in;
-	thisogg->vol = voll;
-	thisogg->chunksize = MP3CHUNKSIZE;
-	thisogg->last_but_one = 0;
-	thisogg->last_ms_offs = 0;
-	thisogg->last_but_one_but_one = 0;
-
-	if (thisogg->chunksize > (int)asset_size)
-		thisogg->chunksize = asset_size;
-
-	pack_fread(tmpbuffer, thisogg->chunksize, mp3in);
-
-	thisogg->buffer = (char *)tmpbuffer;
-	thisogg->stream = alogg_create_oggstream(tmpbuffer, thisogg->chunksize, (asset_size < 1));
-
-	if (thisogg->stream == nullptr) {
-		free(tmpbuffer);
-		pack_fclose(mp3in);
-		delete thisogg;
-		return nullptr;
-	}
-
-	return thisogg;
+	return my_load_static_ogg(asset_name, voll, false);
 }
 
-
-
-MYMIDI *thismidi;
-SOUNDCLIP *my_load_midi(const AssetPath &asset_name, int repet) {
-	// The first a midi is played, preload all patches.
-	if (!thismidi && psp_midi_preload_patches)
-		load_midi_patches();
-
-	size_t asset_size;
-	PACKFILE *pf = PackfileFromAsset(asset_name, asset_size);
-	if (!pf)
+SOUNDCLIP *my_load_midi(const AssetPath &asset_name, bool repeat) {
+	Common::SeekableReadStream *data = get_cached_sound(asset_name);
+	if (data) {
+		return new MYMIDI(data, repeat);
+	} else {
 		return nullptr;
-
-	MIDI *midiPtr = load_midi_pf(pf);
-	pack_fclose(pf);
-
-	if (midiPtr == nullptr)
-		return nullptr;
-
-	thismidi = new MYMIDI();
-	thismidi->tune = midiPtr;
-	thismidi->repeat = (repet != 0);
-
-	return thismidi;
-}
-
-
-#ifdef JGMOD_MOD_PLAYER
-
-MYMOD *thismod = NULL;
-SOUNDCLIP *my_load_mod(const char *filname, int repet) {
-
-	JGMOD *modPtr = load_mod((char *)filname);
-	if (modPtr == NULL)
-		return NULL;
-
-	thismod = new MYMOD();
-	thismod->tune = modPtr;
-	thismod->repeat = (repet != 0);
-
-	return thismod;
-}
-
-int init_mod_player(int numVoices) {
-	return install_mod(numVoices);
-}
-
-void remove_mod_player() {
-	remove_mod();
+	}
 }
 
-//#endif   // JGMOD_MOD_PLAYER
-#elif defined DUMB_MOD_PLAYER
-
-MYMOD *thismod = nullptr;
-SOUNDCLIP *my_load_mod(const AssetPath &asset_name, int repet) {
-	size_t asset_size;
-	DUMBFILE *df = DUMBfileFromAsset(asset_name, asset_size);
-	if (!df)
-		return nullptr;
-
-	DUH *modPtr = nullptr;
-	// determine the file extension
-	const char *lastDot = strrchr(asset_name.second, '.');
-	if (lastDot == nullptr) {
-		dumbfile_close(df);
+SOUNDCLIP *my_load_mod(const AssetPath &asset_name, bool repeat) {
+	Common::SeekableReadStream *data = get_cached_sound(asset_name);
+	if (data) {
+		Audio::AudioStream *audioStream = Audio::makeModXmS3mStream(data, DisposeAfterUse::YES);
+		return new SoundClipWave<MUS_OGG>(audioStream, 255, repeat);
+	} else {
 		return nullptr;
 	}
-	// get the first char of the extensin
-	int charAfterDot = toupper(lastDot[1]);
-
-	// use the appropriate loader
-	if (charAfterDot == 'I') {
-		modPtr = dumb_read_it(df);
-	} else if (charAfterDot == 'X') {
-		modPtr = dumb_read_xm(df);
-	} else if (charAfterDot == 'S') {
-		modPtr = dumb_read_s3m(df);
-	} else if (charAfterDot == 'M') {
-		modPtr = dumb_read_mod(df);
-	}
-
-	dumbfile_close(df);
-	if (modPtr == nullptr)
-		return nullptr;
-
-	thismod = new MYMOD();
-	thismod->tune = modPtr;
-	thismod->vol = 255;
-	thismod->repeat = (repet != 0);
-
-	return thismod;
 }
 
 int init_mod_player(int numVoices) {
-	dumb_register_packfiles();
 	return 0;
 }
 
 void remove_mod_player() {
-	dumb_exit();
 }
 
 } // namespace AGS3
-
-#endif
diff --git a/engines/ags/engine/media/audio/sound.h b/engines/ags/engine/media/audio/sound.h
index d5d5ea7e35..c8ccdde425 100644
--- a/engines/ags/engine/media/audio/sound.h
+++ b/engines/ags/engine/media/audio/sound.h
@@ -39,8 +39,8 @@ SOUNDCLIP *my_load_mp3(const AssetPath &asset_name, int voll);
 SOUNDCLIP *my_load_static_mp3(const AssetPath &asset_name, int voll, bool loop);
 SOUNDCLIP *my_load_static_ogg(const AssetPath &asset_name, int voll, bool loop);
 SOUNDCLIP *my_load_ogg(const AssetPath &asset_name, int voll);
-SOUNDCLIP *my_load_midi(const AssetPath &asset_name, int repet);
-SOUNDCLIP *my_load_mod(const AssetPath &asset_name, int repet);
+SOUNDCLIP *my_load_midi(const AssetPath &asset_name, bool repeat);
+SOUNDCLIP *my_load_mod(const AssetPath &asset_name, bool repeat);
 
 extern int use_extra_sound_offset;
 
diff --git a/engines/ags/engine/media/audio/soundcache.cpp b/engines/ags/engine/media/audio/soundcache.cpp
index 84865d61a3..45fce16f10 100644
--- a/engines/ags/engine/media/audio/soundcache.cpp
+++ b/engines/ags/engine/media/audio/soundcache.cpp
@@ -20,8 +20,6 @@
  *
  */
 
-//include <stdlib.h>
-//include <string.h>
 #include "ags/engine/ac/file.h"
 #include "ags/shared/util/wgt2allg.h"
 #include "ags/engine/media/audio/soundcache.h"
@@ -31,6 +29,7 @@
 #include "ags/shared/util/string.h"
 #include "ags/shared/debugging/out.h"
 #include "ags/ags.h"
+#include "common/memstream.h"
 
 namespace AGS3 {
 
@@ -208,7 +207,16 @@ char *get_cached_sound(const AssetPath &asset_name, bool is_wave, size_t &size)
 
 		return sound_cache_entries[i].data;
 	}
+}
+
+Common::SeekableReadStream *get_cached_sound(const AssetPath &asset_name) {
+	size_t muslen = 0;
+	const byte *data = (byte *)get_cached_sound(asset_name, false, muslen);
+	if (data == nullptr)
+		return nullptr;
 
+	// Create a read stream for the sound
+	return new Common::MemoryReadStream(data, muslen, DisposeAfterUse::YES);
 }
 
 } // namespace AGS3
diff --git a/engines/ags/engine/media/audio/soundcache.h b/engines/ags/engine/media/audio/soundcache.h
index 932c207b8c..fa872e3b65 100644
--- a/engines/ags/engine/media/audio/soundcache.h
+++ b/engines/ags/engine/media/audio/soundcache.h
@@ -24,6 +24,7 @@
 #define AGS_ENGINE_MEDIA_AUDIO_SOUNDCACHE_H
 
 #include "ags/engine/ac/asset_helper.h"
+#include "common/stream.h"
 
 namespace AGS3 {
 
@@ -52,6 +53,7 @@ extern int psp_midi_preload_patches;
 void clear_sound_cache();
 void sound_cache_free(char *buffer, bool is_wave);
 char *get_cached_sound(const AssetPath &asset_name, bool is_wave, size_t &size);
+Common::SeekableReadStream *get_cached_sound(const AssetPath &asset_name);
 
 } // namespace AGS3
 
diff --git a/engines/ags/engine/media/audio/soundclip.cpp b/engines/ags/engine/media/audio/soundclip.cpp
index c7b54cc83a..40a7b741f5 100644
--- a/engines/ags/engine/media/audio/soundclip.cpp
+++ b/engines/ags/engine/media/audio/soundclip.cpp
@@ -20,77 +20,121 @@
  *
  */
 
-#include "ags/shared/util/wgt2allg.h"
-#include "ags/engine/media/audio/audio.h"
-#include "ags/engine/media/audio/audiodefines.h"
 #include "ags/engine/media/audio/soundclip.h"
-#include "ags/engine/media/audio/audiointernaldefs.h"
+#include "ags/ags.h"
 
 namespace AGS3 {
 
+SOUNDCLIP::SOUNDCLIP() : _state(SoundClipInitial), _panning(128), _panningAsPercentage(0),
+		_sourceClip(nullptr), _sourceClipType(0), _speed(1000), _priority(50),
+		_xSource(-1), _ySource(-1), _maximumPossibleDistanceAway(0),
+		_volAsPercentage(100), _vol(0), _volModifier(0) {
+	_mixer = ::AGS::g_vm->_mixer;
+}
+
+void SOUNDCLIP::poll() {
+	bool playing = is_playing();
+	if (playing)
+		_state = SoundClipPlaying;
+	else if (_state == SoundClipPlaying)
+		_state = SoundClipStopped;
+}
+
+SOUNDCLIP::~SOUNDCLIP() {
+	destroy();
+}
+
+void SOUNDCLIP::set_speed(int new_speed) {
+	warning("TODO: SOUNDCLIP::set_speed");
+	_speed = new_speed;
+}
+
+void SOUNDCLIP::adjust_volume() {
+	// TODO: See if this method is needed
+}
+
 int SOUNDCLIP::play_from(int position) {
-	int retVal = play();
-	if ((retVal != 0) && (position > 0)) {
-		seek(position);
+	// TODO: Implement playing from arbitrary positions
+	if (position == 0) {
+		play();
+		return 1;
+	} else {
+		return 0;
 	}
-	return retVal;
 }
 
-void SOUNDCLIP::set_panning(int newPanning) {
-	if (!is_playing()) {
-		return;
-	}
 
-	int voice = get_voice();
-	if (voice >= 0) {
-		voice_set_pan(voice, newPanning);
-		panning = newPanning;
+/*------------------------------------------------------------------*/
+
+SoundClipWaveBase::SoundClipWaveBase(Audio::AudioStream *stream, int volume, bool repeat) :
+		SOUNDCLIP(), _stream(stream) {
+	_mixer = ::AGS::g_vm->_mixer;
+
+	if (repeat) {
+		Audio::SeekableAudioStream *str = dynamic_cast<Audio::SeekableAudioStream *>(stream);
+		assert(str);
+		_stream = new Audio::LoopingAudioStream(str, 0);
 	}
 }
 
-void SOUNDCLIP::pause() {
-	if (state_ != SoundClipPlaying) {
-		return;
-	}
+void SoundClipWaveBase::destroy() {
+	stop();
+	delete _stream;
+	_stream = nullptr;
+}
 
-	int voice = get_voice();
-	if (voice >= 0) {
-		voice_stop(voice);
-		state_ = SoundClipPaused;
-	}
+int SoundClipWaveBase::play() {
+	_mixer->playStream(Audio::Mixer::kSFXSoundType, &_soundHandle, _stream,
+		-1, 255, 0, DisposeAfterUse::NO);
+	return 1;
 }
 
-void SOUNDCLIP::resume() {
-	if (state_ != SoundClipPaused) {
-		return;
-	}
+void SoundClipWaveBase::stop() {
+	_mixer->stopHandle(_soundHandle);
+}
 
-	int voice = get_voice();
-	if (voice >= 0) {
-		voice_start(voice);
-		state_ = SoundClipPlaying;
-	}
+void SoundClipWaveBase::pause() {
+	_mixer->pauseHandle(_soundHandle, false);
+	_state = SoundClipPaused;
+}
+
+void SoundClipWaveBase::resume() {
+	_mixer->pauseHandle(_soundHandle, false);
+	_state = SoundClipPlaying;
+	poll();
+}
+
+bool SoundClipWaveBase::is_playing() const {
+	return _mixer->isSoundHandleActive(_soundHandle);
+}
+
+void SoundClipWaveBase::seek(int offset) {
+	warning("TODO: SoundClipWaveBase::seek");
+}
+
+int SoundClipWaveBase::get_pos() {
+	return _mixer->getSoundElapsedTime(_soundHandle) / 1000;
 }
 
-SOUNDCLIP::SOUNDCLIP() {
-	state_ = SoundClipInitial;
-	priority = 50;
-	panning = 128;
-	panningAsPercentage = 0;
-	speed = 1000;
-	sourceClipType = 0;
-	sourceClip = nullptr;
-	vol = 0;
-	volAsPercentage = 0;
-	volModifier = 0;
-	muted = false;
-	repeat = false;
-	xSource = -1;
-	ySource = -1;
-	maximumPossibleDistanceAway = 0;
-	directionalVolModifier = 0;
-}
-
-SOUNDCLIP::~SOUNDCLIP() = default;
+int SoundClipWaveBase::get_pos_ms() {
+	return _mixer->getSoundElapsedTime(_soundHandle);
+}
+
+int SoundClipWaveBase::get_length_ms() {
+	warning("TODO: SoundClipWaveBase::get_length_ms");
+	return 0;
+}
+
+int SoundClipWaveBase::get_volume() const {
+	return _mixer->getChannelVolume(_soundHandle);
+}
+
+void SoundClipWaveBase::set_volume(int volume) {
+	_mixer->setChannelVolume(_soundHandle, volume);
+}
+
+void SoundClipWaveBase::set_panning(int newPanning) {
+	_mixer->setChannelBalance(_soundHandle, newPanning);
+}
 
 } // namespace AGS3
diff --git a/engines/ags/engine/media/audio/soundclip.h b/engines/ags/engine/media/audio/soundclip.h
index d7d89767e7..3476a248c0 100644
--- a/engines/ags/engine/media/audio/soundclip.h
+++ b/engines/ags/engine/media/audio/soundclip.h
@@ -30,6 +30,9 @@
 #define AGS_ENGINE_MEDIA_AUDIO_SOUNDCLIP_H
 
 #include "ags/engine/util/mutex.h"
+#include "audio/mixer.h"
+#include "audio/audiostream.h"
+#include "common/stream.h"
 
 namespace AGS3 {
 
@@ -47,76 +50,66 @@ enum SoundClipState {
 };
 
 struct SOUNDCLIP {
-	int priority;
-	int sourceClipType;
-	// absolute volume, set by implementations only!
-	int vol;
-	// current relative volume, in percents
-	int volAsPercentage;
-	// volModifier is used when there's a need to temporarily change and
-	// the restore the clip's absolute volume (vol)
-	int volModifier;
-	int panning;
-	int panningAsPercentage;
-	int xSource, ySource;
-	int maximumPossibleDistanceAway;
-	int directionalVolModifier;
-	bool repeat;
-	void *sourceClip;
-
-	virtual void poll() = 0;
-	virtual void destroy() = 0;
-	// apply volume directly to playback; volume is given in units of 255
-	// NOTE: this completely ignores volAsPercentage and muted property
-	virtual void set_volume(int) = 0;
-	virtual void seek(int) = 0;
-	virtual int get_pos() = 0;    // return 0 to indicate seek not supported
-	virtual int get_pos_ms() = 0; // this must always return valid value if poss
-	virtual int get_length_ms() = 0; // return total track length in ms (or 0)
-	virtual int get_sound_type() = 0;
-	virtual int play() = 0;
-
-	virtual int play_from(int position);
-
-	virtual void set_panning(int newPanning);
-	virtual void set_speed(int new_speed) {
-		speed = new_speed;
-	}
-
-	virtual void pause();
-	virtual void resume();
-
-	inline bool is_playing() const {
-		return state_ == SoundClipPlaying || state_ == SoundClipPaused;
-	}
-
-	inline int get_speed() const {
-		return speed;
-	}
+	Audio::Mixer *_mixer;
+	SoundClipState _state;
+	int _panning;
+	int _panningAsPercentage;
+	void *_sourceClip;		// Pointer to source object that spawned the clip
+	int _sourceClipType;
+	int _speed;
+	int _xSource, _ySource;		// Used for positioning sounds in game rooms
+	int _maximumPossibleDistanceAway;
+	int _priority;
+	bool _muted;
+	int _volAsPercentage;
+	int _vol;
+	int _volModifier;
 
-	// Gets clip's volume property, as percentage (0 - 100);
-	// note this may not be the real volume of playback (which could e.g. be muted)
-	inline int get_volume() const {
-		return volAsPercentage;
-	}
-
-	inline bool is_muted() const {
-		return muted;
-	}
+	SOUNDCLIP();
+	virtual ~SOUNDCLIP();
 
+	virtual void destroy() {}
+	virtual int play() = 0;
+	virtual void stop() = 0;
+	virtual void pause() = 0;
+	virtual void resume() = 0;
+	virtual bool is_playing() const = 0;
+	virtual void seek(int offset) = 0;
+	virtual int get_pos() = 0;
+	virtual int get_pos_ms() = 0;
+	virtual int get_length_ms() = 0; // return total track length in ms (or 0)
+	virtual int get_sound_type() const = 0;
+	virtual int get_volume() const = 0;
+	virtual void set_volume(int volume) = 0;
+	virtual void set_panning(int newPanning) = 0;
+	inline int get_speed() const { return _speed; }
+	virtual void set_speed(int new_speed);
+
+	void poll();
 	// Sets the current volume property, as percentage (0 - 100).
 	inline void set_volume_percent(int volume) {
-		volAsPercentage = volume;
-		if (!muted)
-			set_volume((volume * 255) / 100);
+		set_volume((volume * 255) / 100);
+	}
+	void adjust_volume();
+	int play_from(int position);
+
+	/**
+	 * Apply permanent directional volume modifier, in absolute units (0 - 255)
+	 * this is distinct value that is used in conjunction with current volume
+	 * (can be both positive and negative).
+	 */
+	inline void apply_directional_modifier(int mod) {
+		warning("TODO: SOUNDCLIP::apply_directional_modifier");
 	}
 
-	// Explicitly defines both percentage and absolute volume value,
-	// without calculating it from given percentage.
-	// NOTE: this overrides the mute
+	/**
+	 * Explicitly defines both percentage and absolute volume value,
+	 * without calculating it from given percentage.
+	 * NOTE: this overrides the mute
+	 */
 	inline void set_volume_direct(int vol_percent, int vol_absolute) {
-		muted = false;
-		volAsPercentage = vol_percent;
+		_muted = false;
+		_volAsPercentage = vol_percent;
 		set_volume(vol_absolute);
 	}
 
@@ -124,27 +117,35 @@ struct SOUNDCLIP {
 	// for the future reference; when unmuted, that property is
 	// used to restart previous volume.
 	inline void set_mute(bool enable) {
-		muted = enable;
+		_muted = enable;
 		if (enable)
 			set_volume(0);
 		else
-			set_volume((volAsPercentage * 255) / 100);
+			set_volume((_volAsPercentage * 255) / 100);
 	}
 
 	// Apply arbitrary permanent volume modifier, in absolute units (0 - 255);
 	// this is distinct value that is used in conjunction with current volume
 	// (can be both positive and negative).
 	inline void apply_volume_modifier(int mod) {
-		volModifier = mod;
+		_volModifier = mod;
 		adjust_volume();
 	}
 
-	// Apply permanent directional volume modifier, in absolute units (0 - 255)
-	// this is distinct value that is used in conjunction with current volume
-	// (can be both positive and negative).
-	inline void apply_directional_modifier(int mod) {
-		directionalVolModifier = mod;
-		adjust_volume();
+	/*
+	inline bool is_playing() const {
+		return state_ == SoundClipPlaying || state_ == SoundClipPaused;
+	}
+
+
+	// Gets clip's volume property, as percentage (0 - 100);
+	// note this may not be the real volume of playback (which could e.g. be muted)
+	inline int get_volume() const {
+		return volAsPercentage;
+	}
+
+	inline bool is_muted() const {
+		return muted;
 	}
 
 	virtual void adjust_volume() = 0;
@@ -173,6 +174,36 @@ protected:
 		int final_vol = vol + volModifier + directionalVolModifier;
 		return final_vol >= 0 ? final_vol : 0;
 	}
+	*/
+};
+
+struct SoundClipWaveBase : public SOUNDCLIP {
+	Audio::AudioStream *_stream;
+	Audio::SoundHandle _soundHandle;
+
+	SoundClipWaveBase(Audio::AudioStream *stream, int volume, bool repeat = false);
+	~SoundClipWaveBase() override {}
+
+	void destroy() override;
+	int play() override;
+	void stop() override;
+	void pause() override;
+	void resume() override;
+	bool is_playing() const override;
+	void seek(int offset) override;
+	int get_pos() override;
+	int get_pos_ms() override;
+	int get_length_ms() override;
+	int get_volume() const override;
+	void set_volume(int volume) override;
+	void set_panning(int newPanning) override;
+};
+
+template<int SOUND_TYPE>
+struct SoundClipWave : public SoundClipWaveBase {
+	SoundClipWave(Audio::AudioStream *stream, int volume, bool repeat = false) :
+		SoundClipWaveBase(stream, volume, repeat) {}
+	int get_sound_type() const { return SOUND_TYPE; }
 };
 
 } // namespace AGS3
diff --git a/engines/ags/lib/audio/midi.cpp b/engines/ags/lib/audio/midi.cpp
index 503b3b14b7..ca475da20a 100644
--- a/engines/ags/lib/audio/midi.cpp
+++ b/engines/ags/lib/audio/midi.cpp
@@ -48,61 +48,9 @@ int detect_midi_driver(int driver_id) {
 	return 16;
 }
 
-
-void stop_midi() {
-	::AGS::g_music->stop();
-}
-
-void destroy_midi(MIDI *midi) {
-	delete midi;
-}
-
-int play_midi(MIDI *tune, bool repeat) {
-	::AGS::g_music->playMusic(tune, repeat);
-	return 0;
-}
-
-size_t get_midi_length(MIDI *tune) {
-	warning("TODO: get_midi_length");
-	return 0;
-}
-
-void midi_seek(int target) {
-	::AGS::g_music->seek(target);
-}
-
-void midi_pause() {
-	::AGS::g_music->pause();
-}
-
-void midi_resume() {
-	::AGS::g_music->resume();
-}
-
 int load_midi_patches() {
 	warning("TODO: load_midi_patches");
 	return 0;
 }
 
-#define MIDI_BLOCK_SIZE 32768
-
-MIDI *load_midi_pf(PACKFILE *fp) {
-	MIDI *midi = new MIDI();
-	int bytesRead;
-
-	// Iterate through loading blocks of MIDI data
-	for (;;) {
-		size_t priorSize = midi->size();
-		midi->resize(priorSize + MIDI_BLOCK_SIZE);
-		bytesRead = pack_fread(&(*midi)[priorSize], MIDI_BLOCK_SIZE, fp);
-
-		if (bytesRead < MIDI_BLOCK_SIZE) {
-			midi->resize(priorSize + bytesRead);
-			break;
-		}
-	}
-
-	return midi;
-}
-
 } // namespace AGS3
diff --git a/engines/ags/lib/audio/midi.h b/engines/ags/lib/audio/midi.h
index 376f8b919c..6bf59bedd0 100644
--- a/engines/ags/lib/audio/midi.h
+++ b/engines/ags/lib/audio/midi.h
@@ -37,8 +37,6 @@ namespace AGS3 {
 
 AL_ARRAY(_DRIVER_INFO, _midi_driver_list);
 
-using MIDI = ::AGS::MIDI;
-
 /* macros for constructing the driver lists */
 #define BEGIN_MIDI_DRIVER_LIST                                 \
 	_DRIVER_INFO _midi_driver_list[] =                          \
@@ -64,15 +62,7 @@ AL_VAR(long, midi_loop_end);           /* loop when we hit this position */
 
 
 AL_FUNC(int, detect_midi_driver, (int driver_id));
-
-extern void stop_midi();
-extern void destroy_midi(MIDI *tune);
-extern int play_midi(MIDI *tune, bool repeat);
-extern size_t get_midi_length(MIDI *tune);
-extern void midi_seek(int target);
-extern void midi_pause();
-extern void midi_resume();
-extern int load_midi_patches();
+AL_FUNC(int, load_midi_patches, ());
 
 } // namespace AGS3
 
diff --git a/engines/ags/lib/audio/ogg.cpp b/engines/ags/lib/audio/ogg.cpp
index 60860b3df9..3fd8dd0b38 100644
--- a/engines/ags/lib/audio/ogg.cpp
+++ b/engines/ags/lib/audio/ogg.cpp
@@ -25,7 +25,7 @@
 #include "ags/ags.h"
 
 namespace AGS3 {
-
+#ifdef DEPRECATED
 ALOGG_OGG *alogg_create_ogg_from_buffer(void *data, int data_len) {
 	warning("TODO: alogg_create_ogg_from_buffer");
 	return nullptr;
@@ -142,5 +142,5 @@ int alogg_get_pos_msecs_oggstream(ALOGG_OGGSTREAM *ogg) {
 	warning("TODO: alogg_get_pos_msecs_oggstream");
 	return 0;
 }
-
+#endif
 } // namespace AGS3
diff --git a/engines/ags/lib/audio/ogg.h b/engines/ags/lib/audio/ogg.h
index b967cb53f9..79142086ce 100644
--- a/engines/ags/lib/audio/ogg.h
+++ b/engines/ags/lib/audio/ogg.h
@@ -27,7 +27,7 @@
 #include "audio/mixer.h"
 
 namespace AGS3 {
-
+#ifdef DEPRECATED
 #define ALOGG_OK 0
 
 #define ALOGG_PLAY_BUFFERTOOSMALL    -1
@@ -70,7 +70,7 @@ extern bool alogg_is_playing_oggstream(ALOGG_OGGSTREAM *ogg);
 extern int alogg_is_end_of_oggstream(ALOGG_OGGSTREAM *ogg);
 extern AUDIOSTREAM *alogg_get_audiostream_oggstream(ALOGG_OGGSTREAM *ogg);
 extern int alogg_get_pos_msecs_oggstream(ALOGG_OGGSTREAM *ogg);
-
+#endif
 } // namespace AGS3
 
 #endif
diff --git a/engines/ags/music.cpp b/engines/ags/music.cpp
index 191335d1e7..c0f49644cf 100644
--- a/engines/ags/music.cpp
+++ b/engines/ags/music.cpp
@@ -21,6 +21,8 @@
  */
 
 #include "ags/music.h"
+#include "ags/engine/main/main.h"
+#include "ags/lib/audio/midi.h"
 #include "audio/midiparser.h"
 
 namespace AGS {
@@ -28,7 +30,7 @@ namespace AGS {
 Music *g_music;
 
 Music::Music(Audio::Mixer *mixer) :
-		Audio::MidiPlayer(), _mixer(mixer) {
+		Audio::MidiPlayer(), _mixer(mixer), _isFirstTime(true) {
 	g_music = this;
 	Audio::MidiPlayer::createDriver();
 
@@ -61,14 +63,20 @@ void Music::sendToChannel(byte channel, uint32 b) {
 		_channelsTable[channel]->send(b);
 }
 
-void Music::playMusic(const MIDI *midi, bool repeat) {
+void Music::playMusic(Common::SeekableReadStream *midi, bool repeat) {
+	if (_isFirstTime) {
+		if (::AGS3::psp_midi_preload_patches)
+			::AGS3::load_midi_patches();
+		_isFirstTime = false;
+	}
+
 	stop();
 
 	// Load MIDI resource data
 	int midiMusicSize = midi->size();
 
 	_midiData.resize(midi->size());
-	Common::copy(&(*midi)[0], &(*midi)[0] + midi->size(), &_midiData[0]);
+	midi->read(&_midiData[0], midi->size());
 
 	MidiParser *parser = MidiParser::createParser_SMF();
 	if (parser->loadMusic(&_midiData[0], midiMusicSize)) {
diff --git a/engines/ags/music.h b/engines/ags/music.h
index 6b6f09b569..2ea8f81662 100644
--- a/engines/ags/music.h
+++ b/engines/ags/music.h
@@ -30,14 +30,12 @@
 
 namespace AGS {
 
-// A MIDI file
-typedef Common::Array<byte> MIDI;
-
 class Music : public Audio::MidiPlayer {
 private:
 	Audio::Mixer *_mixer;
 	Audio::SoundHandle _soundHandle;
 	Common::Array<byte> _midiData;
+	bool _isFirstTime;
 protected:
 	// Overload Audio::MidiPlayer method
 	void sendToChannel(byte channel, uint32 b) override;
@@ -48,7 +46,7 @@ public:
 	/**
 	 * Play music
 	 */
-	void playMusic(const MIDI *midi, bool repeat = false);
+	void playMusic(Common::SeekableReadStream *midi, bool repeat = false);
 
 	/**
 	 * Seek within the MIDI


Commit: ce606cd25c73d63242ac663b05dfde0a4f958cd6
    https://github.com/scummvm/scummvm/commit/ce606cd25c73d63242ac663b05dfde0a4f958cd6
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Remove deprecated audio classes

Changed paths:
  R engines/ags/engine/media/audio/clip_mydumbmod.cpp
  R engines/ags/engine/media/audio/clip_mydumbmod.h
  R engines/ags/engine/media/audio/clip_mymp3.cpp
  R engines/ags/engine/media/audio/clip_mymp3.h
  R engines/ags/engine/media/audio/clip_myogg.cpp
  R engines/ags/engine/media/audio/clip_myogg.h
  R engines/ags/engine/media/audio/clip_mystaticmp3.cpp
  R engines/ags/engine/media/audio/clip_mystaticmp3.h
  R engines/ags/engine/media/audio/clip_mystaticogg.cpp
  R engines/ags/engine/media/audio/clip_mystaticogg.h
  R engines/ags/engine/media/audio/clip_mywave.cpp
  R engines/ags/engine/media/audio/clip_mywave.h
  R engines/ags/lib/audio/mp3.cpp
  R engines/ags/lib/audio/mp3.h
  R engines/ags/lib/audio/ogg.cpp
  R engines/ags/lib/audio/ogg.h
  R engines/ags/lib/audio/wav.cpp
  R engines/ags/lib/audio/wav.h
    engines/ags/engine/media/audio/sound.cpp
    engines/ags/engine/plugin/agsplugin.cpp
    engines/ags/lib/audio/midi.cpp
    engines/ags/lib/audio/midi.h
    engines/ags/module.mk


diff --git a/engines/ags/engine/media/audio/clip_mydumbmod.cpp b/engines/ags/engine/media/audio/clip_mydumbmod.cpp
deleted file mode 100644
index ae0921b1fa..0000000000
--- a/engines/ags/engine/media/audio/clip_mydumbmod.cpp
+++ /dev/null
@@ -1,185 +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 "ags/engine/media/audio/audiodefines.h"
-
-#ifdef DUMB_MOD_PLAYER
-
-#include "ags/engine/media/audio/clip_mydumbmod.h"
-#include "ags/engine/media/audio/audiointernaldefs.h"
-
-namespace AGS3 {
-#ifdef DEPRECATED
-
-void al_duh_set_loop(AL_DUH_PLAYER *dp, int loop) {
-	DUH_SIGRENDERER *sr = al_duh_get_sigrenderer(dp);
-	DUMB_IT_SIGRENDERER *itsr = duh_get_it_sigrenderer(sr);
-	if (itsr == nullptr)
-		return;
-
-	if (loop)
-		dumb_it_set_loop_callback(itsr, nullptr, nullptr);
-	else
-		dumb_it_set_loop_callback(itsr, dumb_it_callback_terminate, itsr);
-}
-
-void MYMOD::poll() {
-	if (state_ != SoundClipPlaying) {
-		return;
-	}
-
-	if (al_poll_duh(duhPlayer)) {
-		state_ = SoundClipStopped;
-	}
-}
-
-void MYMOD::adjust_volume() {
-	if (!is_playing()) {
-		return;
-	}
-	al_duh_set_volume(duhPlayer, VOLUME_TO_DUMB_VOL(get_final_volume()));
-}
-
-void MYMOD::set_volume(int newvol) {
-	vol = newvol;
-	adjust_volume();
-}
-
-void MYMOD::destroy() {
-	if (duhPlayer) {
-		al_stop_duh(duhPlayer);
-	}
-	duhPlayer = nullptr;
-
-	if (tune) {
-		unload_duh(tune);
-	}
-	tune = nullptr;
-
-	state_ = SoundClipStopped;
-}
-
-void MYMOD::seek(int patnum) {
-	if (!is_playing()) {
-		return;
-	}
-
-	al_stop_duh(duhPlayer);
-	state_ = SoundClipInitial;
-
-	DUH_SIGRENDERER *sr = dumb_it_start_at_order(tune, 2, patnum);
-	duhPlayer = al_duh_encapsulate_sigrenderer(sr, VOLUME_TO_DUMB_VOL(vol), 8192, 22050);
-	if (!duhPlayer) {
-		duh_end_sigrenderer(sr);
-		return;
-	}
-
-	al_duh_set_loop(duhPlayer, repeat);
-	state_ = SoundClipPlaying;
-}
-
-int MYMOD::get_pos() {
-	if (!is_playing()) {
-		return -1;
-	}
-
-	// determine the current track number (DUMB calls them 'orders')
-	DUH_SIGRENDERER *sr = al_duh_get_sigrenderer(duhPlayer);
-	DUMB_IT_SIGRENDERER *itsr = duh_get_it_sigrenderer(sr);
-	if (itsr == nullptr)
-		return -1;
-
-	return dumb_it_sr_get_current_order(itsr);
-}
-
-int MYMOD::get_real_mod_pos() {
-	if (!is_playing()) {
-		return -1;
-	}
-	return al_duh_get_position(duhPlayer);
-}
-
-int MYMOD::get_pos_ms() {
-	if (!is_playing()) {
-		return -1;
-	}
-	return (get_real_mod_pos() * 10) / 655;
-}
-
-int MYMOD::get_length_ms() {
-	if (tune == nullptr)
-		return 0;
-
-	// duh_get_length represents time as 65536ths of a second
-	return (duh_get_length(tune) * 10) / 655;
-}
-
-int MYMOD::get_voice() {
-	// MOD uses so many different voices it's not practical to keep track
-	return -1;
-}
-
-void MYMOD::pause() {
-	if (state_ != SoundClipPlaying) {
-		return;
-	}
-	al_pause_duh(duhPlayer);
-	state_ = SoundClipPaused;
-}
-
-void MYMOD::resume() {
-	if (state_ != SoundClipPaused) {
-		return;
-	}
-	al_resume_duh(duhPlayer);
-	state_ = SoundClipPlaying;
-}
-
-int MYMOD::get_sound_type() {
-	return MUS_MOD;
-}
-
-int MYMOD::play() {
-	if (tune == nullptr) {
-		return 0;
-	}
-
-	duhPlayer = al_start_duh(tune, 2, 0, 1.0, 8192, 22050);
-	if (!duhPlayer) {
-		return 0;
-	}
-	al_duh_set_loop(duhPlayer, repeat);
-	set_volume(vol);
-
-	state_ = SoundClipPlaying;
-	return 1;
-}
-
-MYMOD::MYMOD() : SOUNDCLIP() {
-	tune = nullptr;
-	duhPlayer = nullptr;
-}
-
-#endif
-} // namespace AGS3
-
-#endif // DUMB_MOD_PLAYER
diff --git a/engines/ags/engine/media/audio/clip_mydumbmod.h b/engines/ags/engine/media/audio/clip_mydumbmod.h
deleted file mode 100644
index ad98d49c2f..0000000000
--- a/engines/ags/engine/media/audio/clip_mydumbmod.h
+++ /dev/null
@@ -1,81 +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 AGS_ENGINE_MEDIA_AUDIO_CLIP_MYDUMBMOD_H
-#define AGS_ENGINE_MEDIA_AUDIO_CLIP_MYDUMBMOD_H
-
-#include "ags/lib/audio/aldumb.h"
-#include "ags/engine/media/audio/soundclip.h"
-
-namespace AGS3 {
-#ifdef DEPRECATED
-
-#define VOLUME_TO_DUMB_VOL(vol) ((float)vol) / 256.0
-
-extern void al_duh_set_loop(AL_DUH_PLAYER *dp, int loop);
-
-// MOD/XM (DUMB)
-struct MYMOD : public SOUNDCLIP {
-	DUH *tune;
-	AL_DUH_PLAYER *duhPlayer;
-
-	void poll() override;
-
-	void set_volume(int newvol) override;
-
-	void destroy() override;
-
-	void seek(int patnum) override;
-
-	// NOTE: this implementation of the virtual function returns a MOD/XM
-	// "order" index, not actual playing position;
-	// this does not make much sense in the context of the interface itself,
-	// and, as it seems, was implemented so solely for the purpose of emulating
-	// deprecated "GetMODPattern" script function.
-	// (see Game_GetMODPattern(), and documentation for AudioChannel.Position property)
-	// TODO: find a way to redesign this behavior
-	int get_pos() override;
-
-	int get_pos_ms() override;
-
-	int get_length_ms() override;
-
-	void pause() override;
-
-	void resume() override;
-
-	int get_sound_type() override;
-
-	int play() override;
-
-	MYMOD();
-
-protected:
-	int get_voice() override;
-	void adjust_volume() override;
-	// Returns real MOD/XM playing position
-	int get_real_mod_pos();
-};
-#endif
-} // namespace AGS3
-
-#endif
diff --git a/engines/ags/engine/media/audio/clip_mymp3.cpp b/engines/ags/engine/media/audio/clip_mymp3.cpp
deleted file mode 100644
index 28d1e0e70a..0000000000
--- a/engines/ags/engine/media/audio/clip_mymp3.cpp
+++ /dev/null
@@ -1,189 +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 "ags/engine/media/audio/audiodefines.h"
-
-#ifndef NO_MP3_PLAYER
-
-#include "ags/engine/media/audio/clip_mymp3.h"
-#include "ags/engine/media/audio/audiointernaldefs.h"
-#include "ags/shared/ac/common.h"               // quit()
-#include "ags/engine/ac/asset_helper.h"
-#include "ags/engine/util/mutex_lock.h"
-#include "ags/engine/platform/base/agsplatformdriver.h"
-#include "ags/ags.h"
-
-namespace AGS3 {
-#ifdef DEPRECATED
-
-void MYMP3::poll() {
-	if (state_ != SoundClipPlaying) {
-		return;
-	}
-#if !AGS_PLATFORM_SCUMMVM
-	// update the buffer
-	char *tempbuf = nullptr;
-	{
-		AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
-		tempbuf = (char *)almp3_get_mp3stream_buffer(stream);
-	}
-
-	if (tempbuf != nullptr) {
-		AGS_PACKFILE_OBJ *obj = (AGS_PACKFILE_OBJ *)in->userdata;
-		int free_val = -1;
-		if (chunksize >= obj->remains) {
-			chunksize = obj->remains;
-			free_val = chunksize;
-		}
-		pack_fread(tempbuf, chunksize, in);
-
-		{
-			AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
-			almp3_free_mp3stream_buffer(stream, free_val);
-		}
-	}
-#endif
-	{
-		AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
-		if (almp3_poll_mp3stream(stream) == ALMP3_POLL_PLAYJUSTFINISHED) {
-			state_ = SoundClipStopped;
-		}
-	}
-}
-
-void MYMP3::adjust_stream() {
-	if (!is_playing()) {
-		return;
-	}
-	AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
-	almp3_adjust_mp3stream(stream, get_final_volume(), panning, speed);
-}
-
-void MYMP3::adjust_volume() {
-	adjust_stream();
-}
-
-void MYMP3::set_volume(int newvol) {
-	// boost MP3 volume
-	newvol += 20;
-	if (newvol > 255)
-		newvol = 255;
-
-	vol = newvol;
-	adjust_stream();
-}
-
-void MYMP3::set_speed(int new_speed) {
-	speed = new_speed;
-	adjust_stream();
-}
-
-void MYMP3::destroy() {
-	if (stream) {
-		AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
-		almp3_stop_mp3stream(stream);
-		almp3_destroy_mp3stream(stream);
-	}
-	stream = nullptr;
-
-	if (buffer)
-		free(buffer);
-	buffer = nullptr;
-
-	pack_fclose(in);
-
-	state_ = SoundClipStopped;
-}
-
-void MYMP3::seek(int pos) {
-	if (!is_playing()) {
-		return;
-	}
-	quit("Tried to seek an mp3stream");
-}
-
-int MYMP3::get_pos() {
-	return 0; // Return 0 to signify that Seek is not supported
-	// return almp3_get_pos_msecs_mp3stream (stream);
-}
-
-int MYMP3::get_pos_ms() {
-	if (!is_playing()) {
-		return -1;
-	}
-	AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
-	return almp3_get_pos_msecs_mp3stream(stream);
-}
-
-int MYMP3::get_length_ms() {
-	if (!is_playing()) {
-		return -1;
-	}
-	AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
-	return almp3_get_length_msecs_mp3stream(stream, filesize);
-}
-
-int MYMP3::get_voice() {
-	if (!is_playing()) {
-		return -1;
-	}
-	AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
-	AUDIOSTREAM *ast = almp3_get_audiostream_mp3stream(stream);
-	return (ast != nullptr ? ast->voice : -1);
-}
-
-int MYMP3::get_sound_type() {
-	return MUS_MP3;
-}
-
-int MYMP3::play() {
-	if (in == nullptr) {
-		return 0;
-	}
-
-	{
-		AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
-		if (almp3_play_mp3stream(stream, chunksize, (vol > 230) ? vol : vol + 20, panning) != ALMP3_OK) {
-			return 0;
-		}
-	}
-
-	state_ = SoundClipPlaying;
-
-	if (!psp_audio_multithreaded)
-		poll();
-
-	return 1;
-}
-
-MYMP3::MYMP3() : SOUNDCLIP() {
-	stream = nullptr;
-	in = nullptr;
-	filesize = 0;
-	buffer = nullptr;
-	chunksize = 0;
-}
-
-#endif
-} // namespace AGS3
-
-#endif
diff --git a/engines/ags/engine/media/audio/clip_mymp3.h b/engines/ags/engine/media/audio/clip_mymp3.h
deleted file mode 100644
index a8c283454e..0000000000
--- a/engines/ags/engine/media/audio/clip_mymp3.h
+++ /dev/null
@@ -1,61 +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 AGS_ENGINE_MEDIA_AUDIO_CLIP_MYMP3_H
-#define AGS_ENGINE_MEDIA_AUDIO_CLIP_MYMP3_H
-
-#include "ags/lib/audio/mp3.h"
-#include "ags/lib/allegro/file.h"
-#include "ags/engine/media/audio/soundclip.h"
-
-namespace AGS3 {
-#ifdef  DEPRECATED
-
-struct MYMP3 : public SOUNDCLIP {
-	ALMP3_MP3STREAM *stream;
-	PACKFILE *in;
-	size_t filesize;
-	char *buffer;
-	int chunksize;
-
-	void poll() override;
-	void set_volume(int newvol) override;
-	void set_speed(int new_speed) override;
-	void destroy() override;
-	void seek(int pos) override;
-	int get_pos() override;
-	int get_pos_ms() override;
-	int get_length_ms() override;
-	int get_sound_type() override;
-	int play() override;
-	MYMP3();
-
-protected:
-	int get_voice() override;
-	void adjust_volume() override;
-private:
-	void adjust_stream();
-};
-#endif
-} // namespace AGS3
-
-#endif
diff --git a/engines/ags/engine/media/audio/clip_myogg.cpp b/engines/ags/engine/media/audio/clip_myogg.cpp
deleted file mode 100644
index cc52a6e223..0000000000
--- a/engines/ags/engine/media/audio/clip_myogg.cpp
+++ /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.
- *
- */
-
-#include "ags/lib/audio/digi.h"
-#include "ags/engine/media/audio/audiodefines.h"
-#include "ags/engine/media/audio/clip_myogg.h"
-#include "ags/engine/media/audio/audiointernaldefs.h"
-#include "ags/shared/ac/common.h"               // quit()
-#include "ags/engine/ac/asset_helper.h"
-#include "ags/engine/util/mutex_lock.h"
-
-#include "ags/engine/platform/base/agsplatformdriver.h"
-
-namespace AGS3 {
-#ifdef DEPRECATED
-void MYOGG::poll() {
-	if (state_ != SoundClipPlaying) {
-		return;
-	}
-#if !AGS_PLATFORM_SCUMMVM
-	AGS_PACKFILE_OBJ *obj = (AGS_PACKFILE_OBJ *)in->userdata;
-	if (obj->remains > 0) {
-		// update the buffer
-		char *tempbuf = (char *)alogg_get_oggstream_buffer(stream);
-		if (tempbuf != nullptr) {
-			int free_val = -1;
-			if (chunksize >= obj->remains) {
-				chunksize = obj->remains;
-				free_val = chunksize;
-			}
-			pack_fread(tempbuf, chunksize, in);
-			alogg_free_oggstream_buffer(stream, free_val);
-		}
-	}
-#endif
-	int ret = alogg_poll_oggstream(stream);
-	if (ret == ALOGG_OK || ret == ALOGG_POLL_BUFFERUNDERRUN)
-		get_pos_ms();  // call this to keep the last_but_one stuff up to date
-	else {
-		// finished playing or error
-		state_ = SoundClipStopped;
-	}
-}
-
-void MYOGG::adjust_stream() {
-	if (!is_playing()) {
-		return;
-	}
-	alogg_adjust_oggstream(stream, get_final_volume(), panning, speed);
-}
-
-void MYOGG::adjust_volume() {
-	adjust_stream();
-}
-
-void MYOGG::set_volume(int newvol) {
-	// boost MP3 volume
-	newvol += 20;
-	if (newvol > 255)
-		newvol = 255;
-	vol = newvol;
-	adjust_stream();
-}
-
-void MYOGG::set_speed(int new_speed) {
-	speed = new_speed;
-	adjust_stream();
-}
-
-void MYOGG::destroy() {
-	if (stream) {
-		alogg_stop_oggstream(stream);
-		alogg_destroy_oggstream(stream);
-	}
-	stream = nullptr;
-
-	if (buffer)
-		free(buffer);
-	buffer = nullptr;
-
-	pack_fclose(in);
-
-	state_ = SoundClipStopped;
-}
-
-void MYOGG::seek(int pos) {
-	if (!is_playing()) {
-		return;
-	}
-	quit("Attempted to seek an oggstream; operation not permitted");
-}
-
-int MYOGG::get_pos() {
-	return 0;
-}
-
-int MYOGG::get_pos_ms() {
-	// Unfortunately the alogg_get_pos_msecs_oggstream function
-	// returns the ms offset that was last decoded, so it's always
-	// ahead of the actual playback. Therefore we have this
-	// hideous hack below to sort it out.
-	if ((!is_playing()) || (!alogg_is_playing_oggstream(stream)))
-		return 0;
-
-	AUDIOSTREAM *str = alogg_get_audiostream_oggstream(stream);
-	long offs = (voice_get_position(str->voice) * 1000) / str->samp->freq;
-
-	if (last_ms_offs != alogg_get_pos_msecs_oggstream(stream)) {
-		last_but_one_but_one = last_but_one;
-		last_but_one = last_ms_offs;
-		last_ms_offs = alogg_get_pos_msecs_oggstream(stream);
-	}
-
-	// just about to switch buffers
-	if (offs < 0)
-		return last_but_one;
-
-	int end_of_stream = alogg_is_end_of_oggstream(stream);
-
-	if ((str->active == 1) && (last_but_one_but_one > 0) && (str->locked == nullptr)) {
-		switch (end_of_stream) {
-		case 0:
-		case 2:
-			offs -= (last_but_one - last_but_one_but_one);
-			break;
-		case 1:
-			offs -= (last_but_one - last_but_one_but_one);
-			break;
-		}
-	}
-
-	if (end_of_stream == 1) {
-
-		return offs + last_but_one;
-	}
-
-	return offs + last_but_one_but_one;
-}
-
-int MYOGG::get_length_ms() {
-	// streamed OGG is variable bitrate so we don't know
-	return 0;
-}
-
-int MYOGG::get_voice() {
-	if (!is_playing()) {
-		return -1;
-	}
-
-	AUDIOSTREAM *ast = alogg_get_audiostream_oggstream(stream);
-	if (ast)
-		return ast->voice;
-	return -1;
-}
-
-int MYOGG::get_sound_type() {
-	return MUS_OGG;
-}
-
-int MYOGG::play() {
-	if (in == nullptr) {
-		return 0;
-	}
-
-	if (alogg_play_oggstream(stream, MP3CHUNKSIZE, (vol > 230) ? vol : vol + 20, panning) != ALOGG_OK) {
-		return 0;
-	}
-
-	state_ = SoundClipPlaying;
-
-	if (!psp_audio_multithreaded)
-		poll();
-
-	return 1;
-}
-
-MYOGG::MYOGG() : SOUNDCLIP() {
-	stream = nullptr;
-	in = nullptr;
-	buffer = nullptr;
-	chunksize = 0;
-	last_but_one_but_one = 0;
-	last_but_one = 0;
-	last_ms_offs = 0;
-}
-#endif
-} // namespace AGS3
diff --git a/engines/ags/engine/media/audio/clip_myogg.h b/engines/ags/engine/media/audio/clip_myogg.h
deleted file mode 100644
index f619ec5a90..0000000000
--- a/engines/ags/engine/media/audio/clip_myogg.h
+++ /dev/null
@@ -1,73 +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 AGS_ENGINE_MEDIA_AUDIO_CLIP_MYOGG_H
-#define AGS_ENGINE_MEDIA_AUDIO_CLIP_MYOGG_H
-
-#include "ags/lib/audio/ogg.h"
-#include "ags/lib/allegro/file.h"
-#include "ags/engine/media/audio/soundclip.h"
-
-namespace AGS3 {
-#ifdef DEPRECATED
-struct MYOGG : public SOUNDCLIP {
-	ALOGG_OGGSTREAM *stream;
-	PACKFILE *in;
-	char *buffer;
-	int chunksize;
-
-	int last_but_one_but_one;
-	int last_but_one;
-	int last_ms_offs;
-
-	void poll() override;
-
-	void set_volume(int newvol) override;
-	void set_speed(int new_speed) override;
-
-	void destroy() override;
-
-	void seek(int pos) override;
-
-	int get_pos() override;
-
-	int get_pos_ms() override;
-
-	int get_length_ms() override;
-
-	int get_sound_type() override;
-
-	int play() override;
-
-	MYOGG();
-
-protected:
-	int get_voice() override;
-	void adjust_volume() override;
-private:
-	void adjust_stream();
-};
-
-#endif
-} // namespace AGS3
-
-#endif
diff --git a/engines/ags/engine/media/audio/clip_mystaticmp3.cpp b/engines/ags/engine/media/audio/clip_mystaticmp3.cpp
deleted file mode 100644
index 43c336d713..0000000000
--- a/engines/ags/engine/media/audio/clip_mystaticmp3.cpp
+++ /dev/null
@@ -1,166 +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 "ags/engine/media/audio/audiodefines.h"
-
-#ifndef NO_MP3_PLAYER
-
-#include "ags/engine/media/audio/clip_mystaticmp3.h"
-#include "ags/engine/media/audio/audiointernaldefs.h"
-#include "ags/engine/media/audio/soundcache.h"
-#include "ags/engine/util/mutex_lock.h"
-#include "ags/engine/platform/base/agsplatformdriver.h"
-#include "ags/ags.h"
-
-namespace AGS3 {
-#ifdef DEPRECATED
-
-extern int our_eip;
-
-void MYSTATICMP3::poll() {
-	if (state_ != SoundClipPlaying) {
-		return;
-	}
-
-	int oldeip = our_eip;
-	our_eip = 5997;
-
-	AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
-	int result = almp3_poll_mp3(tune);
-
-	if (result == ALMP3_POLL_PLAYJUSTFINISHED) {
-		if (!repeat) {
-			state_ = SoundClipStopped;
-		}
-	}
-	our_eip = oldeip;
-}
-
-void MYSTATICMP3::adjust_stream() {
-	if (!is_playing()) {
-		return;
-	}
-	AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
-	almp3_adjust_mp3(tune, get_final_volume(), panning, speed, repeat);
-}
-
-void MYSTATICMP3::adjust_volume() {
-	adjust_stream();
-}
-
-void MYSTATICMP3::set_volume(int newvol) {
-	vol = newvol;
-	adjust_stream();
-}
-
-void MYSTATICMP3::set_speed(int new_speed) {
-	speed = new_speed;
-	adjust_stream();
-}
-
-void MYSTATICMP3::destroy() {
-	if (tune) {
-		AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
-		almp3_stop_mp3(tune);
-		almp3_destroy_mp3(tune);
-	}
-	tune = nullptr;
-
-	if (mp3buffer) {
-		sound_cache_free(mp3buffer, false);
-	}
-	mp3buffer = nullptr;
-
-	state_ = SoundClipStopped;
-}
-
-void MYSTATICMP3::seek(int pos) {
-	if (!is_playing()) {
-		return;
-	}
-	AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
-	almp3_seek_abs_msecs_mp3(tune, pos);
-}
-
-int MYSTATICMP3::get_pos() {
-	if (!is_playing()) {
-		return -1;
-	}
-	AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
-	return almp3_get_pos_msecs_mp3(tune);
-}
-
-int MYSTATICMP3::get_pos_ms() {
-	int result = get_pos();
-	return result;
-}
-
-int MYSTATICMP3::get_length_ms() {
-	if (tune == nullptr) {
-		return -1;
-	}
-	AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
-	return almp3_get_length_msecs_mp3(tune);
-}
-
-int MYSTATICMP3::get_voice() {
-	if (!is_playing()) {
-		return -1;
-	}
-	AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
-	AUDIOSTREAM *ast = almp3_get_audiostream_mp3(tune);
-	return (ast != nullptr ? ast->voice : -1);
-}
-
-int MYSTATICMP3::get_sound_type() {
-	return MUS_MP3;
-}
-
-int MYSTATICMP3::play() {
-	if (tune == nullptr) {
-		return 0;
-	}
-
-	{
-		AGS::Engine::MutexLock _lockMp3(::AGS::g_vm->_mp3Mutex);
-		int result = almp3_play_ex_mp3(tune, 16384, vol, panning, 1000, repeat);
-		if (result != ALMP3_OK) {
-			return 0;
-		}
-	}
-
-	state_ = SoundClipPlaying;
-
-	if (!psp_audio_multithreaded)
-		poll();
-
-	return 1;
-}
-
-MYSTATICMP3::MYSTATICMP3() : SOUNDCLIP() {
-	tune = nullptr;
-	mp3buffer = nullptr;
-}
-#endif
-} // namespace AGS3
-
-#endif
diff --git a/engines/ags/engine/media/audio/clip_mystaticmp3.h b/engines/ags/engine/media/audio/clip_mystaticmp3.h
deleted file mode 100644
index 6592ae8c19..0000000000
--- a/engines/ags/engine/media/audio/clip_mystaticmp3.h
+++ /dev/null
@@ -1,67 +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 AGS_ENGINE_MEDIA_AUDIO_CLIP_MYSTATICMP3_H
-#define AGS_ENGINE_MEDIA_AUDIO_CLIP_MYSTATICMP3_H
-
-#include "ags/lib/audio/mp3.h"
-#include "ags/engine/media/audio/soundclip.h"
-
-namespace AGS3 {
-#ifdef DEPRECATED
-// pre-loaded (non-streaming) MP3 file
-struct MYSTATICMP3 : public SOUNDCLIP {
-	ALMP3_MP3 *tune;
-	char *mp3buffer;
-
-	void poll() override;
-
-	void set_volume(int newvol) override;
-	void set_speed(int new_speed) override;
-
-	void destroy() override;
-
-	void seek(int pos) override;
-
-	int get_pos() override;
-
-	int get_pos_ms() override;
-
-	int get_length_ms() override;
-
-	int get_sound_type() override;
-
-	int play() override;
-
-	MYSTATICMP3();
-
-protected:
-	int get_voice() override;
-	void adjust_volume() override;
-private:
-	void adjust_stream();
-};
-#endif
-
-} // namespace AGS3
-
-#endif
diff --git a/engines/ags/engine/media/audio/clip_mystaticogg.cpp b/engines/ags/engine/media/audio/clip_mystaticogg.cpp
deleted file mode 100644
index 363bfa5617..0000000000
--- a/engines/ags/engine/media/audio/clip_mystaticogg.cpp
+++ /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.
- *
- */
-
-#include "ags/engine/media/audio/clip_mystaticogg.h"
-#include "audio/decoders/vorbis.h"
-#include "common/memstream.h"
-
-namespace AGS3 {
-
-extern int use_extra_sound_offset;  // defined in ac.cpp
-
-} // namespace AGS3
diff --git a/engines/ags/engine/media/audio/clip_mystaticogg.h b/engines/ags/engine/media/audio/clip_mystaticogg.h
deleted file mode 100644
index 56b2bb00d2..0000000000
--- a/engines/ags/engine/media/audio/clip_mystaticogg.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 AGS_ENGINE_MEDIA_AUDIO_CLIP_MYSTATICOGG_H
-#define AGS_ENGINE_MEDIA_AUDIO_CLIP_MYSTATICOGG_H
-
-#include "ags/lib/audio/ogg.h"
-
-namespace AGS3 {
-#ifdef DEPRECATED
-/**
- * Pre-loaded (non-streaming) OGG file
- */
-struct MYSTATICOGG : public AUDIO_STREAM {
-	MYSTATICOGG(const byte *data, size_t len, bool repeat);
-
-	int get_sound_type() override {
-		return MUS_OGG;
-	}
-};
-#endif
-} // namespace AGS3
-
-#endif
diff --git a/engines/ags/engine/media/audio/clip_mywave.cpp b/engines/ags/engine/media/audio/clip_mywave.cpp
deleted file mode 100644
index 6a6d02b6ba..0000000000
--- a/engines/ags/engine/media/audio/clip_mywave.cpp
+++ /dev/null
@@ -1,136 +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 "ags/lib/audio/digi.h"
-#include "ags/shared/util/wgt2allg.h"
-#include "ags/engine/media/audio/audiodefines.h"
-#include "ags/engine/media/audio/clip_mywave.h"
-#include "ags/engine/media/audio/audiointernaldefs.h"
-#include "ags/engine/media/audio/soundcache.h"
-#include "ags/engine/util/mutex_lock.h"
-
-#include "ags/engine/platform/base/agsplatformdriver.h"
-
-namespace AGS3 {
-#ifdef  DEPRECATED
-
-void MYWAVE::poll() {
-	if (state_ != SoundClipPlaying) {
-		return;
-	}
-
-	if (voice_get_position(voice) < 0) {
-		state_ = SoundClipStopped;
-	}
-}
-
-void MYWAVE::adjust_volume() {
-	if (!is_playing()) {
-		return;
-	}
-	if (voice < 0) {
-		return;
-	}
-	voice_set_volume(voice, get_final_volume());
-}
-
-void MYWAVE::set_volume(int newvol) {
-	vol = newvol;
-	adjust_volume();
-}
-
-void MYWAVE::destroy() {
-	// Stop sound and decrease reference count.
-	if (wave) {
-		stop_sample(wave);
-		sound_cache_free((char *)wave, true);
-	}
-	wave = nullptr;
-
-	state_ = SoundClipStopped;
-}
-
-void MYWAVE::seek(int pos) {
-	if (!is_playing()) {
-		return;
-	}
-	voice_set_position(voice, pos);
-}
-
-int MYWAVE::get_pos() {
-	if (!is_playing()) {
-		return -1;
-	}
-	return voice_get_position(voice);
-}
-
-int MYWAVE::get_pos_ms() {
-	// convert the offset in samples into the offset in ms
-	//return ((1000000 / voice_get_frequency(voice)) * voice_get_position(voice)) / 1000;
-
-	if (voice_get_frequency(voice) < 100)
-		return 0;
-	// (number of samples / (samples per second / 100)) * 10 = ms
-	return (voice_get_position(voice) / (voice_get_frequency(voice) / 100)) * 10;
-}
-
-int MYWAVE::get_length_ms() {
-	if (wave == nullptr) {
-		return -1;
-	}
-	if (wave->freq < 100)
-		return 0;
-	return (wave->len / (wave->freq / 100)) * 10;
-}
-
-int MYWAVE::get_voice() {
-	if (!is_playing()) {
-		return -1;
-	}
-	return voice;
-}
-
-int MYWAVE::get_sound_type() {
-	return MUS_WAVE;
-}
-
-int MYWAVE::play() {
-	if (wave == nullptr) {
-		return 0;
-	}
-
-	voice = play_sample(wave, vol, panning, 1000, repeat);
-	if (voice < 0) {
-		return 0;
-	}
-
-	state_ = SoundClipPlaying;
-
-	return 1;
-}
-
-MYWAVE::MYWAVE() : SOUNDCLIP() {
-	wave = nullptr;
-	voice = -1;
-}
-#endif
-} // namespace AGS3
diff --git a/engines/ags/engine/media/audio/clip_mywave.h b/engines/ags/engine/media/audio/clip_mywave.h
deleted file mode 100644
index 2e665d088d..0000000000
--- a/engines/ags/engine/media/audio/clip_mywave.h
+++ /dev/null
@@ -1,62 +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 AGS_ENGINE_MEDIA_AUDIO_CLIP_MYWAVE_H
-#define AGS_ENGINE_MEDIA_AUDIO_CLIP_MYWAVE_H
-
-#include "ags/engine/media/audio/soundclip.h"
-
-namespace AGS3 {
-#ifdef DEPRECATED
-
-// My new MP3STREAM wrapper
-struct MYWAVE : public SOUNDCLIP {
-	SAMPLE *wave;
-	int voice;
-
-	void poll() override;
-
-	void set_volume(int new_speed) override;
-
-	void destroy() override;
-
-	void seek(int pos) override;
-
-	int get_pos() override;
-	int get_pos_ms() override;
-
-	int get_length_ms() override;
-
-	int get_sound_type() override;
-
-	int play() override;
-
-	MYWAVE();
-
-protected:
-	int get_voice() override;
-	void adjust_volume() override;
-};
-#endif
-} // namespace AGS3
-
-#endif
diff --git a/engines/ags/engine/media/audio/sound.cpp b/engines/ags/engine/media/audio/sound.cpp
index 25dd52a428..5051321ee1 100644
--- a/engines/ags/engine/media/audio/sound.cpp
+++ b/engines/ags/engine/media/audio/sound.cpp
@@ -32,7 +32,6 @@
 #include "ags/engine/media/audio/audiodefines.h"
 #include "ags/engine/media/audio/sound.h"
 #include "ags/engine/media/audio/audiointernaldefs.h"
-#include "ags/engine/media/audio/clip_mywave.h"
 #include "ags/engine/media/audio/soundcache.h"
 #include "ags/engine/media/audio/clip_mymidi.h"
 #include "ags/engine/util/mutex_lock.h"
diff --git a/engines/ags/engine/plugin/agsplugin.cpp b/engines/ags/engine/plugin/agsplugin.cpp
index 637330b9df..7844c2e24c 100644
--- a/engines/ags/engine/plugin/agsplugin.cpp
+++ b/engines/ags/engine/plugin/agsplugin.cpp
@@ -597,7 +597,7 @@ void IAGSEngine::PlaySoundChannel(int32 channel, int32 soundType, int32 volume,
 	else if (soundType == PSND_OGGSTATIC)
 		newcha = my_load_static_ogg(asset_name, volume, (loop != 0));
 	else if (soundType == PSND_MIDI) {
-		if (midi_pos >= 0)
+		if (::AGS::g_music->isPlaying())
 			quit("!IAGSEngine::PlaySoundChannel: MIDI already in use");
 		newcha = my_load_midi(asset_name, loop);
 		newcha->set_volume(volume);
diff --git a/engines/ags/lib/audio/midi.cpp b/engines/ags/lib/audio/midi.cpp
index ca475da20a..2b8056554d 100644
--- a/engines/ags/lib/audio/midi.cpp
+++ b/engines/ags/lib/audio/midi.cpp
@@ -34,16 +34,8 @@ BEGIN_MIDI_DRIVER_LIST
 END_MIDI_DRIVER_LIST
 
 int midi_card;
-
 int midi_input_card;
 
-volatile long midi_pos;       /* current position in the midi file, in beats */
-volatile long midi_time;      /* current position in the midi file, in seconds */
-
-long midi_loop_start;         /* where to loop back to at EOF */
-long midi_loop_end;           /* loop when we hit this position */
-
-
 int detect_midi_driver(int driver_id) {
 	return 16;
 }
diff --git a/engines/ags/lib/audio/midi.h b/engines/ags/lib/audio/midi.h
index 6bf59bedd0..ae24b041ce 100644
--- a/engines/ags/lib/audio/midi.h
+++ b/engines/ags/lib/audio/midi.h
@@ -54,9 +54,6 @@ AL_VAR(int, midi_card);
 
 AL_VAR(int, midi_input_card);
 
-AL_VAR(volatile long, midi_pos);       /* current position in the midi file, in beats */
-AL_VAR(volatile long, midi_time);      /* current position in the midi file, in seconds */
-
 AL_VAR(long, midi_loop_start);         /* where to loop back to at EOF */
 AL_VAR(long, midi_loop_end);           /* loop when we hit this position */
 
diff --git a/engines/ags/lib/audio/mp3.cpp b/engines/ags/lib/audio/mp3.cpp
deleted file mode 100644
index d6fd91ecfe..0000000000
--- a/engines/ags/lib/audio/mp3.cpp
+++ /dev/null
@@ -1,122 +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 "ags/lib/audio/mp3.h"
-#include "common/textconsole.h"
-#include "ags/ags.h"
-
-namespace AGS3 {
-
-ALMP3_MP3 *almp3_create_mp3(void *data, int data_len) {
-	warning("TODO: almp3_create_mp3");
-	return nullptr;
-}
-
-int almp3_play_mp3(ALMP3_MP3 *mp3, int buffer_len, int vol, int pan) {
-	warning("TODO: almp3_play_mp3");
-	return 0;
-}
-
-int almp3_play_ex_mp3(ALMP3_MP3 *mp3, int buffer_len, int vol, int pan, int speed, int loop) {
-	warning("TODO: almp3_play_ex_mp3");
-	return 0;
-}
-
-void almp3_stop_mp3(ALMP3_MP3 *mp3) {
-	::AGS::g_vm->_mixer->stopHandle(mp3->_handle);
-}
-
-void almp3_destroy_mp3(ALMP3_MP3 *mp3) {
-	delete mp3;
-}
-
-int almp3_poll_mp3(ALMP3_MP3 *mp3) {
-	return ::AGS::g_vm->_mixer->isSoundHandleActive(mp3->_handle) ? 0 : ALMP3_POLL_PLAYJUSTFINISHED;
-}
-
-void almp3_adjust_mp3(ALMP3_MP3 *mp3, int volume, int panning, int speed, bool repeat) {
-	warning("TODO: almp3_adjust_mp3");
-}
-
-void almp3_seek_abs_msecs_mp3(ALMP3_MP3 *mp3, int pos) {
-	warning("TODO: almp3_seek_abs_msecs_mp3");
-}
-
-int almp3_get_pos_msecs_mp3(ALMP3_MP3 *mp3) {
-	warning("TODO: almp3_get_pos_msecs_mp3");
-	return 0;
-}
-
-AUDIOSTREAM *almp3_get_audiostream_mp3(ALMP3_MP3 *mp3) {
-	warning("TODO: almp3_get_audiostream_mp3");
-	return nullptr;
-}
-
-int almp3_get_length_msecs_mp3(ALMP3_MP3 *mp3) {
-	warning("TODO: almp3_get_length_msecs_mp3");
-	return 0;
-}
-
-
-ALMP3_MP3STREAM *almp3_create_mp3stream(void *first_data_buffer, int data_buffer_len, int last_block) {
-	warning("TODO: almp3_create_mp3stream");
-	return nullptr;
-}
-
-int almp3_play_mp3stream(ALMP3_MP3STREAM *mp3, int buffer_len, int vol, int pan) {
-	warning("TODO: almp3_play_mp3stream");
-	return -1;
-}
-
-int almp3_poll_mp3stream(ALMP3_MP3STREAM *mp3) {
-	warning("TODO: almp3_poll_mp3stream");
-	return 0;
-}
-
-void almp3_adjust_mp3stream(ALMP3_MP3STREAM *mp3, int volume, int panning, int speed) {
-	warning("TODO: almp3_adjust_mp3stream");
-}
-
-void almp3_stop_mp3stream(ALMP3_MP3STREAM *mp3) {
-	warning("TODO: almp3_stop_mp3stream");
-}
-
-void almp3_destroy_mp3stream(ALMP3_MP3STREAM *mp3) {
-	warning("TODO: almp3_destroy_mp3stream");
-}
-
-int almp3_get_pos_msecs_mp3stream(ALMP3_MP3STREAM *mp3) {
-	warning("TODO: almp3_get_pos_msecs_mp3stream");
-	return 0;
-}
-
-AUDIOSTREAM *almp3_get_audiostream_mp3stream(ALMP3_MP3STREAM *mp3) {
-	warning("TODO: almp3_get_audiostream_mp3stream");
-	return nullptr;
-}
-
-int almp3_get_length_msecs_mp3stream(ALMP3_MP3STREAM *mp3, int total_size) {
-	warning("TODO: almp3_get_length_msecs_mp3stream");
-	return 0;
-}
-
-} // namespace AGS3
diff --git a/engines/ags/lib/audio/mp3.h b/engines/ags/lib/audio/mp3.h
deleted file mode 100644
index 2ac411aa75..0000000000
--- a/engines/ags/lib/audio/mp3.h
+++ /dev/null
@@ -1,64 +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 AGS_LIB_AUDIO_MP3_H
-#define AGS_LIB_AUDIO_MP3_H
-
-#include "ags/lib/audio/sound.h"
-#include "audio/mixer.h"
-
-namespace AGS3 {
-
-#define ALMP3_OK 0
-#define ALMP3_POLL_PLAYJUSTFINISHED 1
-
-typedef Audio::AudioStream ALMP3_MP3STREAM;
-struct ALMP3_MP3 {
-	ALMP3_MP3STREAM *_stream;
-	Audio::SoundHandle _handle;
-};
-
-extern ALMP3_MP3 *almp3_create_mp3(void *data, int data_len);
-extern void almp3_destroy_mp3(ALMP3_MP3 *mp3);
-extern int almp3_play_mp3(ALMP3_MP3 *mp3, int buffer_len, int vol, int pan);
-extern int almp3_play_ex_mp3(ALMP3_MP3 *mp3, int buffer_len, int vol, int pan, int speed, int loop);
-extern void almp3_stop_mp3(ALMP3_MP3 *mp3);
-extern int almp3_poll_mp3(ALMP3_MP3 *mp3);
-extern void almp3_adjust_mp3(ALMP3_MP3 *mp3, int volume, int panning, int speed, bool repeat);
-extern void almp3_seek_abs_msecs_mp3(ALMP3_MP3 *mp3, int pos);
-extern int almp3_get_pos_msecs_mp3(ALMP3_MP3 *mp3);
-extern AUDIOSTREAM *almp3_get_audiostream_mp3(ALMP3_MP3 *mp3);
-extern int almp3_get_length_msecs_mp3(ALMP3_MP3 *mp3);
-
-extern ALMP3_MP3STREAM *almp3_create_mp3stream(void *first_data_buffer, int data_buffer_len, int last_block);
-extern int almp3_play_mp3stream(ALMP3_MP3STREAM *mp3, int buffer_len, int vol, int pan);
-extern int almp3_poll_mp3stream(ALMP3_MP3STREAM *mp3);
-extern void almp3_adjust_mp3stream(ALMP3_MP3STREAM *mp3, int volume, int panning, int speed);
-extern void almp3_stop_mp3stream(ALMP3_MP3STREAM *mp3);
-extern void almp3_destroy_mp3stream(ALMP3_MP3STREAM *mp3);
-extern int almp3_get_pos_msecs_mp3stream(ALMP3_MP3STREAM *mp3);
-extern AUDIOSTREAM *almp3_get_audiostream_mp3stream(ALMP3_MP3STREAM *mp3);
-extern int almp3_get_length_msecs_mp3stream(ALMP3_MP3STREAM *mp3, int total_size);
-
-} // namespace AGS3
-
-#endif
diff --git a/engines/ags/lib/audio/ogg.cpp b/engines/ags/lib/audio/ogg.cpp
deleted file mode 100644
index 3fd8dd0b38..0000000000
--- a/engines/ags/lib/audio/ogg.cpp
+++ /dev/null
@@ -1,146 +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 "ags/lib/audio/ogg.h"
-#include "common/textconsole.h"
-#include "ags/ags.h"
-
-namespace AGS3 {
-#ifdef DEPRECATED
-ALOGG_OGG *alogg_create_ogg_from_buffer(void *data, int data_len) {
-	warning("TODO: alogg_create_ogg_from_buffer");
-	return nullptr;
-}
-
-void alogg_destroy_ogg(ALOGG_OGG *ogg) {
-	delete ogg;
-}
-
-int alogg_play_ogg(ALOGG_OGG *ogg, int buffer_len, int vol, int pan) {
-	warning("TODO: alogg_play_ogg");
-	return 0;
-}
-
-int alogg_play_ex_ogg(ALOGG_OGG *ogg, int buffer_len, int vol, int pan, int speed, int loop) {
-	warning("TODO: alogg_play_ex_ogg");
-	return 0;
-}
-
-void alogg_stop_ogg(ALOGG_OGG *ogg) {
-	warning("TODO: alogg_stop_ogg");
-}
-
-int alogg_poll_ogg(ALOGG_OGG *ogg) {
-	return ::AGS::g_vm->_mixer->isSoundHandleActive(ogg->_handle) ? 0 : ALOGG_POLL_PLAYJUSTFINISHED;
-}
-
-bool alogg_is_playing_ogg(ALOGG_OGG *ogg) {
-	warning("TODO: alogg_is_playing_ogg");
-	return false;
-}
-
-void alogg_adjust_ogg(ALOGG_OGG *ogg, int volume, int panning, int speed, bool repeat) {
-	warning("TODO: alogg_adjust_oggstream");
-}
-
-AUDIOSTREAM *alogg_get_audiostream_ogg(ALOGG_OGG *ogg) {
-	return ogg->_stream;
-}
-
-int alogg_get_pos_msecs_ogg(ALOGG_OGG *ogg) {
-	warning("TODO: alogg_get_pos_msecs_ogg");
-	return 0;
-}
-
-bool alogg_get_wave_is_stereo_ogg(ALOGG_OGG *ogg) {
-	warning("TODO: alogg_get_wave_is_stereo_ogg");
-	return true;
-}
-
-int alogg_get_length_msecs_ogg(ALOGG_OGG *ogg) {
-	warning("TODO: alogg_get_length_msecs_ogg");
-	return 0;
-}
-
-void alogg_seek_abs_msecs_ogg(ALOGG_OGG *ogg, int msecs) {
-	warning("TODO: alogg_seek_abs_msecs_ogg");
-}
-
-int alogg_get_wave_freq_ogg(ALOGG_OGG *ogg) {
-	warning("TODO: alogg_get_wave_freq_ogg");
-	return 0;
-}
-
-int alogg_is_end_of_ogg(ALOGG_OGG *ogg) {
-	warning("TODO: alogg_is_end_of_oggstream");
-	return 0;
-}
-
-
-ALOGG_OGGSTREAM *alogg_create_oggstream(void *first_data_buffer, int data_buffer_len, int last_block) {
-	warning("TODO: alogg_create_oggstream");
-	return nullptr;
-}
-
-void alogg_destroy_oggstream(ALOGG_OGGSTREAM *ogg) {
-	warning("TODO: alogg_destroy_oggstream");
-}
-
-int alogg_play_oggstream(ALOGG_OGGSTREAM *ogg, int buffer_len, int vol, int pan) {
-	warning("TODO: alogg_play_oggstream");
-	return 0;
-}
-
-void alogg_stop_oggstream(ALOGG_OGGSTREAM *ogg) {
-	warning("TODO: alogg_stop_oggstream");
-}
-
-int alogg_poll_oggstream(ALOGG_OGGSTREAM *ogg) {
-	warning("TODO: alogg_poll_oggstream");
-	return 0;
-}
-
-void alogg_adjust_oggstream(ALOGG_OGGSTREAM *ogg, int volume, int panning, int speed) {
-	warning("TODO: alogg_adjust_oggstream");
-}
-
-bool alogg_is_playing_oggstream(ALOGG_OGGSTREAM *ogg) {
-	warning("TODO: alogg_is_playing_oggstream");
-	return false;
-}
-
-int alogg_is_end_of_oggstream(ALOGG_OGGSTREAM *ogg) {
-	warning("TODO: alogg_is_end_of_oggstream");
-	return 0;
-}
-
-AUDIOSTREAM *alogg_get_audiostream_oggstream(ALOGG_OGGSTREAM *ogg) {
-	warning("TODO: alogg_get_audiostream_oggstream");
-	return nullptr;
-}
-
-int alogg_get_pos_msecs_oggstream(ALOGG_OGGSTREAM *ogg) {
-	warning("TODO: alogg_get_pos_msecs_oggstream");
-	return 0;
-}
-#endif
-} // namespace AGS3
diff --git a/engines/ags/lib/audio/ogg.h b/engines/ags/lib/audio/ogg.h
deleted file mode 100644
index 79142086ce..0000000000
--- a/engines/ags/lib/audio/ogg.h
+++ /dev/null
@@ -1,76 +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 AGS_LIB_AUDIO_OGG_H
-#define AGS_LIB_AUDIO_OGG_H
-
-#include "ags/lib/audio/sound.h"
-#include "audio/mixer.h"
-
-namespace AGS3 {
-#ifdef DEPRECATED
-#define ALOGG_OK 0
-
-#define ALOGG_PLAY_BUFFERTOOSMALL    -1
-
-#define ALOGG_POLL_PLAYJUSTFINISHED  1
-#define ALOGG_POLL_NOTPLAYING        -1
-#define ALOGG_POLL_FRAMECORRUPT      -2
-#define ALOGG_POLL_BUFFERUNDERRUN    -3
-#define ALOGG_POLL_INTERNALERROR     -4
-
-typedef AUDIOSTREAM ALOGG_OGGSTREAM;
-struct ALOGG_OGG {
-	ALOGG_OGGSTREAM *_stream;
-	Audio::SoundHandle _handle;
-};
-
-extern ALOGG_OGG *alogg_create_ogg_from_buffer(void *data, int data_len);
-extern void alogg_destroy_ogg(ALOGG_OGG *ogg);
-extern int alogg_play_ogg(ALOGG_OGG *ogg, int buffer_len, int vol, int pan);
-extern int alogg_play_ex_ogg(ALOGG_OGG *ogg, int buffer_len, int vol, int pan, int speed, int loop);
-extern void alogg_stop_ogg(ALOGG_OGG *ogg);
-extern int alogg_poll_ogg(ALOGG_OGG *ogg);
-extern bool alogg_is_playing_ogg(ALOGG_OGG *ogg);
-extern void alogg_adjust_ogg(ALOGG_OGG *ogg, int volume, int panning, int speed, bool repeat);
-extern AUDIOSTREAM *alogg_get_audiostream_ogg(ALOGG_OGG *ogg);
-extern int alogg_get_pos_msecs_ogg(ALOGG_OGG *ogg);
-extern bool alogg_get_wave_is_stereo_ogg(ALOGG_OGG *ogg);
-extern int alogg_get_length_msecs_ogg(ALOGG_OGG *ogg);
-extern void alogg_seek_abs_msecs_ogg(ALOGG_OGG *ogg, int msecs);
-extern int alogg_get_wave_freq_ogg(ALOGG_OGG *ogg);
-extern int alogg_is_end_of_ogg(ALOGG_OGG *ogg);
-
-ALOGG_OGGSTREAM *alogg_create_oggstream(void *first_data_buffer, int data_buffer_len, int last_block);
-extern int alogg_play_oggstream(ALOGG_OGGSTREAM *ogg, int buffer_len, int vol, int pan);
-extern void alogg_stop_oggstream(ALOGG_OGGSTREAM *ogg);
-extern void alogg_destroy_oggstream(ALOGG_OGGSTREAM *ogg);
-extern int alogg_poll_oggstream(ALOGG_OGGSTREAM *ogg);
-extern void alogg_adjust_oggstream(ALOGG_OGGSTREAM *ogg, int volume, int panning, int speed);
-extern bool alogg_is_playing_oggstream(ALOGG_OGGSTREAM *ogg);
-extern int alogg_is_end_of_oggstream(ALOGG_OGGSTREAM *ogg);
-extern AUDIOSTREAM *alogg_get_audiostream_oggstream(ALOGG_OGGSTREAM *ogg);
-extern int alogg_get_pos_msecs_oggstream(ALOGG_OGGSTREAM *ogg);
-#endif
-} // namespace AGS3
-
-#endif
diff --git a/engines/ags/lib/audio/wav.cpp b/engines/ags/lib/audio/wav.cpp
deleted file mode 100644
index 851877df46..0000000000
--- a/engines/ags/lib/audio/wav.cpp
+++ /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.
- *
- */
-
-#include "ags/lib/audio/wav.h"
-#include "common/textconsole.h"
-#include "ags/ags.h"
-
-namespace AGS3 {
-
-
-
-} // namespace AGS3
diff --git a/engines/ags/lib/audio/wav.h b/engines/ags/lib/audio/wav.h
deleted file mode 100644
index d550c03312..0000000000
--- a/engines/ags/lib/audio/wav.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 AGS_LIB_AUDIO_WAV_H
-#define AGS_LIB_AUDIO_WAV_H
-
-#include "audio/audiostream.h"
-#include "audio/mixer.h"
-
-namespace AGS3 {
-
-
-} // namespace AGS3
-
-#endif
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index e19feb3a3c..703367d4a2 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -28,10 +28,7 @@ MODULE_OBJS = \
 	lib/audio/aldumb.o \
 	lib/audio/digi.o \
 	lib/audio/midi.o \
-	lib/audio/mp3.o \
-	lib/audio/ogg.o \
 	lib/audio/sound.o \
-	lib/audio/wav.o \
 	lib/dumb-0.9.2/dumb.o \
 	lib/dumb-0.9.2/dumbfile.o \
 	lib/dumb-0.9.2/helpers/clickrem.o \
@@ -281,14 +278,7 @@ MODULE_OBJS = \
 	engine/main/update.o \
     engine/media/audio/ambientsound.o \
     engine/media/audio/audio.o \
-    engine/media/audio/clip_mydumbmod.o \
-    engine/media/audio/clip_myjgmod.o \
     engine/media/audio/clip_mymidi.o \
-    engine/media/audio/clip_mymp3.o \
-    engine/media/audio/clip_myogg.o \
-    engine/media/audio/clip_mystaticmp3.o \
-    engine/media/audio/clip_mystaticogg.o \
-    engine/media/audio/clip_mywave.o \
     engine/media/audio/queuedaudioitem.o \
     engine/media/audio/sound.o \
     engine/media/audio/soundcache.o \


Commit: aa21b7f73595a3e4192aacc2895064e770bbb0a4
    https://github.com/scummvm/scummvm/commit/aa21b7f73595a3e4192aacc2895064e770bbb0a4
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Change some TODO warnings to comments

Changed paths:
    engines/ags/lib/allegro/color.cpp


diff --git a/engines/ags/lib/allegro/color.cpp b/engines/ags/lib/allegro/color.cpp
index f66c1d19d7..eda663a680 100644
--- a/engines/ags/lib/allegro/color.cpp
+++ b/engines/ags/lib/allegro/color.cpp
@@ -240,71 +240,71 @@ int generate_optimized_palette(BITMAP *image, PALETTE pal, AL_CONST signed char
 }
 
 void set_blender_mode(BLENDER_FUNC b15, BLENDER_FUNC b16, BLENDER_FUNC b24, int r, int g, int b, int a) {
-	warning("TODO: set_blender_mode");
+	// TODO: set_blender_mode
 }
 
 void set_blender_mode_ex(BLENDER_FUNC b15, BLENDER_FUNC b16, BLENDER_FUNC b24, BLENDER_FUNC b32, BLENDER_FUNC b15x, BLENDER_FUNC b16x, BLENDER_FUNC b24x, int r, int g, int b, int a) {
-	warning("TODO: set_blender_mode_ex");
+	// TODO: set_blender_mode_ex
 }
 
 void set_alpha_blender(void) {
-	warning("TODO: set_alpha_blender");
+	// TODO: set_alpha_blender
 }
 
 void set_write_alpha_blender(void) {
-	warning("TODO: set_write_alpha_blender");
+	// TODO: set_write_alpha_blender
 }
 
 void set_trans_blender(int r, int g, int b, int a) {
-	warning("TODO: set_trans_blender");
+	// TODO: set_trans_blender
 }
 
 void set_add_blender(int r, int g, int b, int a) {
-	warning("TODO: set_add_blender");
+	// TODO: set_add_blender
 }
 
 void set_burn_blender(int r, int g, int b, int a) {
-	warning("TODO: set_burn_blender");
+	// TODO: set_burn_blender
 }
 
 void set_color_blender(int r, int g, int b, int a) {
-	warning("TODO: set_color_blender");
+	// TODO: set_color_blender
 }
 
 void set_difference_blender(int r, int g, int b, int a) {
-	warning("TODO: set_difference_blender");
+	// TODO: set_difference_blender
 }
 
 void set_dissolve_blender(int r, int g, int b, int a) {
-	warning("TODO: set_dissolve_blender");
+	// TODO: set_dissolve_blender
 }
 
 void set_dodge_blender(int r, int g, int b, int a) {
-	warning("TODO: set_dodge_blender");
+	// TODO: set_dodge_blender
 }
 
 void set_hue_blender(int r, int g, int b, int a) {
-	warning("TODO: set_hue_blender");
+	// TODO: set_hue_blender
 }
 
 void set_invert_blender(int r, int g, int b, int a) {
-	warning("TODO: set_invert_blender");
+	// TODO: set_invert_blender
 }
 
 void set_luminance_blender(int r, int g, int b, int a) {
-	warning("TODO: set_luminance_blender");
+	// TODO: set_luminance_blender
 }
 
 void set_multiply_blender(int r, int g, int b, int a) {
-	warning("TODO: set_multiply_blender");
+	// TODO: set_multiply_blender
 }
 
 void set_saturation_blender(int r, int g, int b, int a) {
-	warning("TODO: set_saturation_blender");
+	// TODO: set_saturation_blender
 }
 
 void set_screen_blender(int r, int g, int b, int a) {
-	warning("TODO: set_screen_blender");
+	// TODO: set_screen_blender
 }
 
 


Commit: 1416b860229c2a9d3940bcc0720c696b022f6891
    https://github.com/scummvm/scummvm/commit/1416b860229c2a9d3940bcc0720c696b022f6891
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Implement select_palette & unselect_palette

Changed paths:
    engines/ags/lib/allegro.cpp
    engines/ags/lib/allegro/color.cpp
    engines/ags/lib/allegro/color.h


diff --git a/engines/ags/lib/allegro.cpp b/engines/ags/lib/allegro.cpp
index bc1f5d24f2..ec92eb3f24 100644
--- a/engines/ags/lib/allegro.cpp
+++ b/engines/ags/lib/allegro.cpp
@@ -27,6 +27,7 @@ namespace AGS3 {
 /* default palette structures */
 PALETTE black_palette;
 PALETTE _current_palette;
+PALETTE _prev_current_palette;
 
 int _current_palette_changed = 0xFFFFFFFF;
 
diff --git a/engines/ags/lib/allegro/color.cpp b/engines/ags/lib/allegro/color.cpp
index eda663a680..0ae8c76b3f 100644
--- a/engines/ags/lib/allegro/color.cpp
+++ b/engines/ags/lib/allegro/color.cpp
@@ -223,11 +223,21 @@ void fade_out(int speed) {
 }
 
 void select_palette(AL_CONST PALETTE p) {
-	warning("TODO: select_palette");
+	int c;
+
+	for (c = 0; c < PAL_SIZE; c++) {
+		_prev_current_palette[c] = _current_palette[c];
+		_current_palette[c] = p[c];
+	}
+
+	// TODO: See if the remainder of Allegro's select_palette method is needed for AGS
 }
 
 void unselect_palette(void) {
-	warning("TODO: unselect_palette");
+	int c;
+
+	for (c = 0; c < PAL_SIZE; c++)
+		_current_palette[c] = _prev_current_palette[c];
 }
 
 void generate_332_palette(PALETTE pal) {
diff --git a/engines/ags/lib/allegro/color.h b/engines/ags/lib/allegro/color.h
index f0a25c0600..db793f2fad 100644
--- a/engines/ags/lib/allegro/color.h
+++ b/engines/ags/lib/allegro/color.h
@@ -50,6 +50,7 @@ typedef color RGB;
 typedef RGB PALETTE[PAL_SIZE];
 
 AL_VAR(PALETTE, _current_palette);
+AL_VAR(PALETTE, _prev_current_palette);
 
 #include "common/pack-end.h"    // END STRUCT PACKING
 


Commit: 2447e8b06ffad6b74da3cd53da852b3e19d4fb89
    https://github.com/scummvm/scummvm/commit/2447e8b06ffad6b74da3cd53da852b3e19d4fb89
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Corrections to saving games

Changed paths:
    engines/ags/engine/ac/file.cpp
    engines/ags/engine/ac/global_file.cpp
    engines/ags/engine/script/cc_instance.cpp
    engines/ags/lib/allegro/file.cpp
    engines/ags/metaengine.cpp
    engines/ags/shared/util/directory.cpp
    engines/ags/shared/util/directory.h
    engines/ags/shared/util/filestream.cpp
    engines/ags/shared/util/filestream.h


diff --git a/engines/ags/engine/ac/file.cpp b/engines/ags/engine/ac/file.cpp
index d20793aaea..263885359c 100644
--- a/engines/ags/engine/ac/file.cpp
+++ b/engines/ags/engine/ac/file.cpp
@@ -37,6 +37,7 @@
 #include "ags/shared/util/misc.h"
 #include "ags/engine/platform/base/agsplatformdriver.h"
 #include "ags/shared/util/stream.h"
+#include "ags/shared/util/filestream.h"
 #include "ags/shared/core/assetmanager.h"
 #include "ags/shared/core/asset.h"
 #include "ags/engine/main/engine.h"
@@ -271,12 +272,7 @@ String MakeSpecialSubDir(const String &sp_dir) {
 }
 
 String MakeAppDataPath() {
-	String app_data_path = usetup.shared_data_dir;
-	if (app_data_path.IsEmpty())
-		app_data_path = MakeSpecialSubDir(PathOrCurDir(platform->GetAllUsersDataDirectory()));
-	Directory::CreateDirectory(app_data_path);
-	app_data_path.AppendChar('/');
-	return app_data_path;
+	return AGS::Shared::SAVE_FOLDER_PREFIX;
 }
 
 bool ResolveScriptPath(const String &orig_sc_path, bool read_only, ResolvedPath &rp) {
diff --git a/engines/ags/engine/ac/global_file.cpp b/engines/ags/engine/ac/global_file.cpp
index 66fb05648e..0edc340598 100644
--- a/engines/ags/engine/ac/global_file.cpp
+++ b/engines/ags/engine/ac/global_file.cpp
@@ -29,6 +29,7 @@
 #include "ags/engine/ac/string.h"
 #include "ags/engine/debugging/debug_log.h"
 #include "ags/shared/util/directory.h"
+#include "ags/shared/util/filestream.h"
 #include "ags/shared/util/path.h"
 #include "ags/shared/util/stream.h"
 
@@ -81,8 +82,12 @@ int32_t FileOpen(const char *fnmm, Shared::FileOpenMode open_mode, Shared::FileW
 	}
 
 	Stream *s = File::OpenFile(rp.FullPath, open_mode, work_mode);
-	if (!s && !rp.AltPath.IsEmpty() && rp.AltPath.Compare(rp.FullPath) != 0)
-		s = File::OpenFile(rp.AltPath, open_mode, work_mode);
+	if (!s && !rp.AltPath.IsEmpty() && rp.AltPath.Compare(rp.FullPath) != 0) {
+		if (rp.FullPath.CompareLeft(AGS::Shared::SAVE_FOLDER_PREFIX))
+			// When file not found in main path, only check in AltPath if it's not a
+			// savegame file. Because ScummVM doesn't have any alt for saves
+			s = File::OpenFile(rp.AltPath, open_mode, work_mode);
+	}
 
 	valid_handles[useindx].stream = s;
 	if (valid_handles[useindx].stream == nullptr)
diff --git a/engines/ags/engine/script/cc_instance.cpp b/engines/ags/engine/script/cc_instance.cpp
index 5a4fd59f31..f239f12173 100644
--- a/engines/ags/engine/script/cc_instance.cpp
+++ b/engines/ags/engine/script/cc_instance.cpp
@@ -1024,7 +1024,8 @@ int ccInstance::Run(int32_t curpc) {
 					cc_error("invalid pointer type for object function call: %d", reg1.Type);
 				}
 			} else if (reg1.Type == kScValStaticFunction) {
-				return_value = reg1.SPfn(func_callstack.GetHead() + 1, num_args_to_func);
+				RuntimeScriptValue *head = func_callstack.GetHead();
+				return_value = reg1.SPfn(head + 1, num_args_to_func);
 			} else if (reg1.Type == kScValObjectFunction) {
 				cc_error("unexpected object function pointer on SCMD_CALLEXT");
 			} else {
diff --git a/engines/ags/lib/allegro/file.cpp b/engines/ags/lib/allegro/file.cpp
index 75f32935f6..e4dd654179 100644
--- a/engines/ags/lib/allegro/file.cpp
+++ b/engines/ags/lib/allegro/file.cpp
@@ -128,7 +128,7 @@ char *make_relative_filename(char *dest, const char *path, const char *filename,
 
 int is_relative_filename(const char *filename) {
 	Common::String fname(filename);
-	return !fname.contains('/') && !fname.contains('\\') ? 0 : -1;
+	return !fname.contains('/') && !fname.contains('\\') ? 1 : 0;
 }
 
 /*------------------------------------------------------------------*/
diff --git a/engines/ags/metaengine.cpp b/engines/ags/metaengine.cpp
index e210080f41..977c87d3e1 100644
--- a/engines/ags/metaengine.cpp
+++ b/engines/ags/metaengine.cpp
@@ -23,6 +23,7 @@
 #include "ags/metaengine.h"
 #include "ags/detection.h"
 #include "ags/ags.h"
+#include "ags/shared/util/directory.h"
 #include "ags/shared/util/filestream.h"
 #include "ags/engine/ac/richgamemedia.h"
 #include "ags/engine/game/savegame.h"
diff --git a/engines/ags/shared/util/directory.cpp b/engines/ags/shared/util/directory.cpp
index 5bbecdb074..798dd454df 100644
--- a/engines/ags/shared/util/directory.cpp
+++ b/engines/ags/shared/util/directory.cpp
@@ -31,6 +31,8 @@ namespace AGS3 {
 namespace AGS {
 namespace Shared {
 
+const char *SAVE_FOLDER_PREFIX = "/saves/";
+
 namespace Directory {
 
 bool CreateDirectory(const String &path) {
@@ -38,6 +40,10 @@ bool CreateDirectory(const String &path) {
 }
 
 bool CreateAllDirectories(const String &parent, const String &path) {
+	if (path == SAVE_FOLDER_PREFIX)
+		// ScummVM save folder doesn't need creating
+		return true;
+
 	if (!ags_directory_exists(parent.GetCStr()))
 		return false;
 	if (path.IsEmpty())
diff --git a/engines/ags/shared/util/directory.h b/engines/ags/shared/util/directory.h
index 754e6837bb..16a2e760b8 100644
--- a/engines/ags/shared/util/directory.h
+++ b/engines/ags/shared/util/directory.h
@@ -36,6 +36,8 @@ namespace AGS3 {
 namespace AGS {
 namespace Shared {
 
+extern const char *SAVE_FOLDER_PREFIX;
+
 namespace Directory {
 // Creates new directory (if it does not exist)
 bool   CreateDirectory(const String &path);
diff --git a/engines/ags/shared/util/filestream.cpp b/engines/ags/shared/util/filestream.cpp
index 620124a42f..d90c228a40 100644
--- a/engines/ags/shared/util/filestream.cpp
+++ b/engines/ags/shared/util/filestream.cpp
@@ -23,6 +23,7 @@
 #include "ags/shared/util/filestream.h"
 #include "ags/shared/util/stdio_compat.h"
 #include "ags/shared/util/string.h"
+#include "ags/shared/util/directory.h"
 #include "ags/ags.h"
 #include "common/file.h"
 #include "common/system.h"
@@ -31,8 +32,6 @@ namespace AGS3 {
 namespace AGS {
 namespace Shared {
 
-const char *SAVE_FOLDER_PREFIX = "/saves/";
-
 FileStream::FileStream(const String &file_name, FileOpenMode open_mode, FileWorkMode work_mode,
 	DataEndianess stream_endianess)
 		: DataStream(stream_endianess), _writeBuffer(DisposeAfterUse::YES),
diff --git a/engines/ags/shared/util/filestream.h b/engines/ags/shared/util/filestream.h
index 491e552fad..ff9994c111 100644
--- a/engines/ags/shared/util/filestream.h
+++ b/engines/ags/shared/util/filestream.h
@@ -33,8 +33,6 @@ namespace AGS3 {
 namespace AGS {
 namespace Shared {
 
-extern const char *SAVE_FOLDER_PREFIX;
-
 class FileStream : public DataStream {
 public:
 


Commit: cf99f28036d1608317e969fb358d7ab66c3ec9c6
    https://github.com/scummvm/scummvm/commit/cf99f28036d1608317e969fb358d7ab66c3ec9c6
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Show fatal errors in a GUI message dialog

Changed paths:
    engines/ags/ags.cpp
    engines/ags/detection_tables.h
    engines/ags/shared/ac/common.cpp


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index 374d67cf6b..822737d3b2 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -433,4 +433,8 @@ Common::Error AGSEngine::saveGameState(int slot, const Common::String &desc, boo
 	return Common::kNoError;
 }
 
+void AGSEngine::GUIError(const Common::String &msg) {
+	GUIErrorMessage(msg);
+}
+
 } // namespace AGS
diff --git a/engines/ags/detection_tables.h b/engines/ags/detection_tables.h
index ec98ce52e4..bf615503a4 100644
--- a/engines/ags/detection_tables.h
+++ b/engines/ags/detection_tables.h
@@ -47,7 +47,7 @@ static const PlainGameDescriptor GAME_NAMES[] = {
 static const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("bcremake", "bc.exe", "0710e2ec71042617f565c01824f0cf3c", 7683255),
 	ENGLISH_ENTRY("atotk", "atotk.exe", "37cf2d4d07842d45b59c6dd9387c1ee7", 42872046),
-	ENGLISH_ENTRY("kq2agdi", "kq2vga.exe", "40cfb7563df7dacf6530b19289a4745b", 12563246),
+	ENGLISH_ENTRY("kq2agdi", "kq2vga.exe", "40cfb7563df7dacf6530b19289a4745b", 12563246),	// 3.1
 
 	{ AD_TABLE_END_MARKER }
 };
diff --git a/engines/ags/shared/ac/common.cpp b/engines/ags/shared/ac/common.cpp
index 0990898673..d7dfc36b62 100644
--- a/engines/ags/shared/ac/common.cpp
+++ b/engines/ags/shared/ac/common.cpp
@@ -22,6 +22,7 @@
 
 #include "ags/shared/ac/common.h"
 #include "ags/shared/util/string.h"
+#include "ags/ags.h"
 
 namespace AGS3 {
 
@@ -34,6 +35,8 @@ void quitprintf(const char *fmt, ...) {
 	va_start(ap, fmt);
 	String text = String::FromFormatV(fmt, ap);
 	va_end(ap);
+
+	::AGS::g_vm->GUIError(text);
 	quit(text);
 }
 


Commit: 26adb0b229f3cfaccdd448cda4e5f78c03a10c75
    https://github.com/scummvm/scummvm/commit/26adb0b229f3cfaccdd448cda4e5f78c03a10c75
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix for writing audio to savegames

Changed paths:
    engines/ags/engine/game/savegame_components.cpp
    engines/ags/engine/media/audio/clip_mymidi.cpp
    engines/ags/engine/media/audio/clip_mymidi.h
    engines/ags/engine/media/audio/soundclip.cpp
    engines/ags/engine/media/audio/soundclip.h


diff --git a/engines/ags/engine/game/savegame_components.cpp b/engines/ags/engine/game/savegame_components.cpp
index f5fb62c0b4..4475b1fdb6 100644
--- a/engines/ags/engine/game/savegame_components.cpp
+++ b/engines/ags/engine/game/savegame_components.cpp
@@ -352,6 +352,7 @@ HSaveError WriteAudio(PStream out) {
 	// Game content assertion
 	out->WriteInt32(game.audioClipTypes.size());
 	out->WriteInt32(game.audioClips.size()); // [ivan-mogilko] not necessary, kept only to avoid changing save format
+
 	// Audio types
 	for (size_t i = 0; i < game.audioClipTypes.size(); ++i) {
 		game.audioClipTypes[i].WriteToSavegame(out.get());
@@ -365,6 +366,10 @@ HSaveError WriteAudio(PStream out) {
 			out->WriteInt32(((ScriptAudioClip *)ch->_sourceClip)->id);
 			out->WriteInt32(ch->get_pos());
 			out->WriteInt32(ch->_priority);
+			out->WriteInt32(ch->_repeat ? 1 : 0);
+			out->WriteInt32(ch->_vol);
+			out->WriteInt32(ch->_panning);
+			out->WriteInt32(ch->_volAsPercentage);
  			out->WriteInt32(ch->_panningAsPercentage);
 			out->WriteInt32(ch->get_speed());
 			// since version 1
@@ -375,6 +380,7 @@ HSaveError WriteAudio(PStream out) {
 			out->WriteInt32(-1);
 		}
 	}
+
 	out->WriteInt32(crossFading);
 	out->WriteInt32(crossFadeVolumePerStep);
 	out->WriteInt32(crossFadeStep);
@@ -385,18 +391,17 @@ HSaveError WriteAudio(PStream out) {
 	// Ambient sound
 	for (int i = 0; i < MAX_SOUND_CHANNELS; ++i)
 		ambient[i].WriteToFile(out.get());
+
 	return HSaveError::None();
 }
 
 HSaveError ReadAudio(PStream in, int32_t cmp_ver, const PreservedParams &pp, RestoredData &r_data) {
 	HSaveError err;
+
 	// Game content assertion
 	if (!AssertGameContent(err, in->ReadInt32(), game.audioClipTypes.size(), "Audio Clip Types"))
 		return err;
 	in->ReadInt32(); // audio clip count
-	/* [ivan-mogilko] looks like it's not necessary to assert, as there's no data serialized for clips
-	if (!AssertGameContent(err, in->ReadInt32(), game.audioClips.size(), "Audio Clips"))
-	    return err;*/
 
 	// Audio types
 	for (size_t i = 0; i < game.audioClipTypes.size(); ++i) {
@@ -428,6 +433,7 @@ HSaveError ReadAudio(PStream in, int32_t cmp_ver, const PreservedParams &pp, Res
 			}
 		}
 	}
+
 	crossFading = in->ReadInt32();
 	crossFadeVolumePerStep = in->ReadInt32();
 	crossFadeStep = in->ReadInt32();
@@ -438,6 +444,7 @@ HSaveError ReadAudio(PStream in, int32_t cmp_ver, const PreservedParams &pp, Res
 	// Ambient sound
 	for (int i = 0; i < MAX_SOUND_CHANNELS; ++i)
 		ambient[i].ReadFromFile(in.get());
+
 	for (int i = 1; i < MAX_SOUND_CHANNELS; ++i) {
 		if (ambient[i].channel == 0) {
 			r_data.DoAmbient[i] = 0;
diff --git a/engines/ags/engine/media/audio/clip_mymidi.cpp b/engines/ags/engine/media/audio/clip_mymidi.cpp
index 01e0e3b4bc..fc05ad53d6 100644
--- a/engines/ags/engine/media/audio/clip_mymidi.cpp
+++ b/engines/ags/engine/media/audio/clip_mymidi.cpp
@@ -28,7 +28,8 @@
 namespace AGS3 {
 
 MYMIDI::MYMIDI(Common::SeekableReadStream *data, bool repeat) :
-		_data(data), _repeat(repeat), lengthInSeconds(0) {
+		_data(data), lengthInSeconds(0) {
+	_repeat = repeat;
 }
 
 void MYMIDI::destroy() {
diff --git a/engines/ags/engine/media/audio/clip_mymidi.h b/engines/ags/engine/media/audio/clip_mymidi.h
index 78c7b4fea1..0fa224390e 100644
--- a/engines/ags/engine/media/audio/clip_mymidi.h
+++ b/engines/ags/engine/media/audio/clip_mymidi.h
@@ -30,7 +30,6 @@ namespace AGS3 {
 // MIDI
 struct MYMIDI : public SOUNDCLIP {
 	Common::SeekableReadStream *_data;
-	bool _repeat;
 	int lengthInSeconds;
 
 	MYMIDI(Common::SeekableReadStream *data, bool repeat);
diff --git a/engines/ags/engine/media/audio/soundclip.cpp b/engines/ags/engine/media/audio/soundclip.cpp
index 40a7b741f5..2c88f0b9aa 100644
--- a/engines/ags/engine/media/audio/soundclip.cpp
+++ b/engines/ags/engine/media/audio/soundclip.cpp
@@ -28,7 +28,7 @@ namespace AGS3 {
 SOUNDCLIP::SOUNDCLIP() : _state(SoundClipInitial), _panning(128), _panningAsPercentage(0),
 		_sourceClip(nullptr), _sourceClipType(0), _speed(1000), _priority(50),
 		_xSource(-1), _ySource(-1), _maximumPossibleDistanceAway(0),
-		_volAsPercentage(100), _vol(0), _volModifier(0) {
+		_volAsPercentage(100), _vol(0), _volModifier(0), _repeat(false) {
 	_mixer = ::AGS::g_vm->_mixer;
 }
 
@@ -69,6 +69,8 @@ int SOUNDCLIP::play_from(int position) {
 SoundClipWaveBase::SoundClipWaveBase(Audio::AudioStream *stream, int volume, bool repeat) :
 		SOUNDCLIP(), _stream(stream) {
 	_mixer = ::AGS::g_vm->_mixer;
+	_repeat = repeat;
+	_vol = volume;
 
 	if (repeat) {
 		Audio::SeekableAudioStream *str = dynamic_cast<Audio::SeekableAudioStream *>(stream);
diff --git a/engines/ags/engine/media/audio/soundclip.h b/engines/ags/engine/media/audio/soundclip.h
index 3476a248c0..6d520bfba1 100644
--- a/engines/ags/engine/media/audio/soundclip.h
+++ b/engines/ags/engine/media/audio/soundclip.h
@@ -64,6 +64,7 @@ struct SOUNDCLIP {
 	int _volAsPercentage;
 	int _vol;
 	int _volModifier;
+	bool _repeat;
 
 	SOUNDCLIP();
 	virtual ~SOUNDCLIP();


Commit: 406d7c51107d2152fe794d248c29cbcbf58b0d7e
    https://github.com/scummvm/scummvm/commit/406d7c51107d2152fe794d248c29cbcbf58b0d7e
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Don't allow audio streams to free cached sound data

Changed paths:
    engines/ags/engine/media/audio/soundcache.cpp


diff --git a/engines/ags/engine/media/audio/soundcache.cpp b/engines/ags/engine/media/audio/soundcache.cpp
index 45fce16f10..37e07e1c50 100644
--- a/engines/ags/engine/media/audio/soundcache.cpp
+++ b/engines/ags/engine/media/audio/soundcache.cpp
@@ -216,7 +216,7 @@ Common::SeekableReadStream *get_cached_sound(const AssetPath &asset_name) {
 		return nullptr;
 
 	// Create a read stream for the sound
-	return new Common::MemoryReadStream(data, muslen, DisposeAfterUse::YES);
+	return new Common::MemoryReadStream(data, muslen, DisposeAfterUse::NO);
 }
 
 } // namespace AGS3


Commit: e173527290274e608c37c1e6e185c1cfff721cdf
    https://github.com/scummvm/scummvm/commit/e173527290274e608c37c1e6e185c1cfff721cdf
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: gcc compilation fixes

Changed paths:
    engines/ags/lib/allegro/flood.cpp
    engines/ags/module.mk
    engines/ags/music.cpp
    engines/ags/shared/core/types.h
    engines/ags/shared/game/main_game_file.cpp


diff --git a/engines/ags/lib/allegro/flood.cpp b/engines/ags/lib/allegro/flood.cpp
index e5794ce29c..a618525f0c 100644
--- a/engines/ags/lib/allegro/flood.cpp
+++ b/engines/ags/lib/allegro/flood.cpp
@@ -22,6 +22,7 @@
 
 #include "ags/lib/allegro/flood.h"
 #include "ags/lib/allegro/gfx.h"
+#include "ags/shared/core/types.h"
 #include "common/array.h"
 
 namespace AGS3 {
@@ -183,8 +184,8 @@ void floodfill(BITMAP *bmp, int x, int y, int color) {
 	p = FLOOD_LINE(0);
 	for (c = 0; c < (int)scratchMem.size(); c++) {
 		p[c].flags = 0;
-		p[c].lpos = SHRT_MAX;
-		p[c].rpos = SHRT_MIN;
+		p[c].lpos = INT16_MAX;
+		p[c].rpos = INT16_MIN;
 		p[c].y = y;
 		p[c].next = 0;
 	}
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 703367d4a2..2520fbb6f1 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -300,7 +300,7 @@ MODULE_OBJS = \
 	engine/script/script_runtime.o \
 	engine/script/systemimports.o \
 	plugins/dll.o \
-	plugins/agscreditz\agscreditz.o
+	plugins/agscreditz/agscreditz.o
 
 ifdef ENABLE_AGS_TESTS
 MODULE_OBJS += \
diff --git a/engines/ags/music.cpp b/engines/ags/music.cpp
index c0f49644cf..5b78a24e7b 100644
--- a/engines/ags/music.cpp
+++ b/engines/ags/music.cpp
@@ -97,7 +97,7 @@ void Music::playMusic(Common::SeekableReadStream *midi, bool repeat) {
 }
 
 void Music::seek(size_t offset) {
-	warning("TODO: Music::seek to offset %u", offset);
+	warning("TODO: Music::seek to offset %u", (uint32)offset);
 }
 
 } // End of namespace AGS
diff --git a/engines/ags/shared/core/types.h b/engines/ags/shared/core/types.h
index b4209972a6..c77a9e6e20 100644
--- a/engines/ags/shared/core/types.h
+++ b/engines/ags/shared/core/types.h
@@ -74,6 +74,7 @@ typedef int64 intptr_t;
 #define fixed_t int32_t
 #define color_t int
 
+#undef INT16_MIN
 #undef INT16_MAX
 #undef INT32_MIN
 #undef INT32_MAX
@@ -81,6 +82,7 @@ typedef int64 intptr_t;
 #undef INT_MAX
 #undef UINT_MAX
 #undef SIZE_MAX
+#define INT16_MIN     -32768
 #define INT16_MAX     0x7fff
 #define INT32_MIN     (-2147483647 - 1)
 #define INT32_MAX       2147483647
diff --git a/engines/ags/shared/game/main_game_file.cpp b/engines/ags/shared/game/main_game_file.cpp
index ad42434759..6a41aa8380 100644
--- a/engines/ags/shared/game/main_game_file.cpp
+++ b/engines/ags/shared/game/main_game_file.cpp
@@ -622,7 +622,7 @@ void FixupSaveDirectory(GameSetupStruct &game) {
 	String s = Path::FixupSharedFilename(game.saveGameFolderName);
 	snprintf(game.saveGameFolderName, MAX_SG_FOLDER_LEN, "%s", s.GetCStr());
 #else
-	sprintf(game.saveGameFolderName, "");
+	strcpy(game.saveGameFolderName, SAVE_FOLDER_PREFIX);
 #endif
 }
 


Commit: ae7efc50022b33ee03995d5044382c989e08b30c
    https://github.com/scummvm/scummvm/commit/ae7efc50022b33ee03995d5044382c989e08b30c
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Properly handle transparent pixels in item z order

Previously, in cases where multiple items were layered
on top of each other, it wasn't properly tecognizing
transparent pixels as such to be ignored

Changed paths:
    engines/ags/lib/allegro/gfx.h


diff --git a/engines/ags/lib/allegro/gfx.h b/engines/ags/lib/allegro/gfx.h
index 2af30ede9f..5075bd9a9a 100644
--- a/engines/ags/lib/allegro/gfx.h
+++ b/engines/ags/lib/allegro/gfx.h
@@ -206,7 +206,7 @@ public:
 	}
 
 	uint getTransparentColor() const {
-		return _owner->getTransparentColor();
+		return format.RGBToColor(255, 0, 255);
 	}
 
 	int getpixel(int x, int y) const;


Commit: 9b893f160244c4b4400d7cd5143b6e5efdd5dd2d
    https://github.com/scummvm/scummvm/commit/9b893f160244c4b4400d7cd5143b6e5efdd5dd2d
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Add AGS credits section

Changed paths:
    devtools/credits.pl


diff --git a/devtools/credits.pl b/devtools/credits.pl
index d7b8449912..880113f08a 100755
--- a/devtools/credits.pl
+++ b/devtools/credits.pl
@@ -556,6 +556,11 @@ begin_credits("Credits");
 				add_person("Ludvig Strigeus", "ludde", "(retired)");
 			end_section();
 
+			begin_section("AGS");
+				add_person("Paul Gilbert", "dreammaster", "");
+				add_person("", "AGA", "AgsCreditz");
+			end_section();
+
 			begin_section("Avalanche");
 				add_person("Peter Bozsó", "uruk", "");
 				add_person("Arnaud Boutonné", "Strangerke", "");


Commit: 4a9d59e8a9c4070d5cbcbbae29f6120e6efd61b8
    https://github.com/scummvm/scummvm/commit/4a9d59e8a9c4070d5cbcbbae29f6120e6efd61b8
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Don't show GUI message on exit

Changed paths:
    engines/ags/shared/ac/common.cpp


diff --git a/engines/ags/shared/ac/common.cpp b/engines/ags/shared/ac/common.cpp
index d7dfc36b62..57caf4820e 100644
--- a/engines/ags/shared/ac/common.cpp
+++ b/engines/ags/shared/ac/common.cpp
@@ -29,6 +29,7 @@ namespace AGS3 {
 using namespace AGS::Shared;
 
 const char *game_file_sig = "Adventure Creator Game File v2";
+extern volatile char abort_engine;
 
 void quitprintf(const char *fmt, ...) {
 	va_list ap;
@@ -36,7 +37,8 @@ void quitprintf(const char *fmt, ...) {
 	String text = String::FromFormatV(fmt, ap);
 	va_end(ap);
 
-	::AGS::g_vm->GUIError(text);
+	if (!abort_engine)
+		::AGS::g_vm->GUIError(text);
 	quit(text);
 }
 


Commit: e0d73e9dc8506ec2d0cd2408cc671ebd3577ad10
    https://github.com/scummvm/scummvm/commit/e0d73e9dc8506ec2d0cd2408cc671ebd3577ad10
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Implement horizontally flipped sprite draw

Changed paths:
    engines/ags/lib/allegro/gfx.cpp


diff --git a/engines/ags/lib/allegro/gfx.cpp b/engines/ags/lib/allegro/gfx.cpp
index a98541c2bf..c35184d27b 100644
--- a/engines/ags/lib/allegro/gfx.cpp
+++ b/engines/ags/lib/allegro/gfx.cpp
@@ -294,7 +294,11 @@ void draw_lit_sprite(BITMAP *bmp, const BITMAP *sprite, int x, int y, int color)
 }
 
 void draw_sprite_h_flip(BITMAP *bmp, const BITMAP *sprite, int x, int y) {
-	error("TODO: draw_sprite_h_flip");
+	Graphics::ManagedSurface &bmpS = **bmp;
+	Graphics::ManagedSurface &spriteS = **sprite;
+
+	add_palette_if_needed(spriteS, bmpS);
+	bmpS.transBlitFrom(spriteS, Common::Point(x, y), (uint)-1, true);
 }
 
 void draw_sprite_v_flip(BITMAP *bmp, const BITMAP *sprite, int x, int y) {


Commit: 6da17f421bee7bb1acdb84e883cce723d3de5050
    https://github.com/scummvm/scummvm/commit/6da17f421bee7bb1acdb84e883cce723d3de5050
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Matching keycodes to Allegro in original

Changed paths:
    engines/ags/engine/ac/sys_events.cpp
    engines/ags/engine/ac/system.cpp
    engines/ags/engine/debugging/debug.cpp
    engines/ags/engine/main/game_run.cpp
    engines/ags/engine/platform/base/agsplatformdriver.cpp
    engines/ags/events.cpp
    engines/ags/events.h
    engines/ags/lib/allegro/keyboard.cpp
    engines/ags/lib/allegro/keyboard.h


diff --git a/engines/ags/engine/ac/sys_events.cpp b/engines/ags/engine/ac/sys_events.cpp
index 16acd3c0e8..2f8b9c9795 100644
--- a/engines/ags/engine/ac/sys_events.cpp
+++ b/engines/ags/engine/ac/sys_events.cpp
@@ -31,6 +31,7 @@
 #include "ags/engine/platform/base/agsplatformdriver.h"
 #include "ags/engine/ac/timer.h"
 #include "ags/ags.h"
+#include "ags/events.h"
 
 namespace AGS3 {
 
@@ -56,8 +57,8 @@ int ags_kbhit() {
 }
 
 int ags_iskeypressed(int keycode) {
-	if (keycode >= 0 && keycode < Common::KEYCODE_LAST) {
-		return key[keycode] != 0;
+	if (keycode >= 0 && keycode < __allegro_KEY_MAX) {
+		return ::AGS::g_events->isKeyPressed((AllegroKbdKeycode)keycode);
 	}
 	return 0;
 }
@@ -99,100 +100,87 @@ int ags_check_mouse_wheel() {
 }
 
 int ags_getch() {
-	const Common::KeyState keyState = readkey();
-	int gott;
-
-	// I believe we rely on a lot of keys being converted to ASCII, which is why
-	// the complete scan code list is not here.
-
-	switch (keyState.keycode) {
-	case Common::KEYCODE_F1:
-		gott = eAGSKeyCodeF1;
-		break;
-	case Common::KEYCODE_F2:
-		gott = eAGSKeyCodeF2;
-		break;
-	case Common::KEYCODE_F3:
-		gott = eAGSKeyCodeF3;
-		break;
-	case Common::KEYCODE_F4:
-		gott = eAGSKeyCodeF4;
-		break;
-	case Common::KEYCODE_F5:
-		gott = eAGSKeyCodeF5;
-		break;
-	case Common::KEYCODE_F6:
-		gott = eAGSKeyCodeF6;
-		break;
-	case Common::KEYCODE_F7:
-		gott = eAGSKeyCodeF7;
-		break;
-	case Common::KEYCODE_F8:
-		gott = eAGSKeyCodeF8;
-		break;
-	case Common::KEYCODE_F9:
-		gott = eAGSKeyCodeF9;
-		break;
-	case Common::KEYCODE_F10:
-		gott = eAGSKeyCodeF10;
-		break;
-	case Common::KEYCODE_F11:
-		gott = eAGSKeyCodeF11;
-		break;
-	case Common::KEYCODE_F12:
-		gott = eAGSKeyCodeF12;
-		break;
-
-	case Common::KEYCODE_INSERT:
-	case Common::KEYCODE_KP0:
-		gott = eAGSKeyCodeInsert;
-		break;
-	case Common::KEYCODE_DELETE:
-	case Common::KEYCODE_KP_PERIOD:
-		gott = eAGSKeyCodeDelete;
-		break;
-	case Common::KEYCODE_HOME:
-	case Common::KEYCODE_KP7:
-		gott = eAGSKeyCodeHome;
-		break;
-	case Common::KEYCODE_END:
-	case Common::KEYCODE_KP1:
-		gott = eAGSKeyCodeEnd;
-		break;
-	case Common::KEYCODE_PAGEUP:
-	case Common::KEYCODE_KP9:
-		gott = eAGSKeyCodePageUp;
-		break;
-	case Common::KEYCODE_PAGEDOWN:
-	case Common::KEYCODE_KP3:
-		gott = eAGSKeyCodePageDown;
-		break;
-	case Common::KEYCODE_LEFT:
-	case Common::KEYCODE_KP4:
-		gott = eAGSKeyCodeLeftArrow;
-		break;
-	case Common::KEYCODE_RIGHT:
-	case Common::KEYCODE_KP6:
-		gott = eAGSKeyCodeRightArrow;
-		break;
-	case Common::KEYCODE_UP:
-	case Common::KEYCODE_KP8:
-		gott = eAGSKeyCodeUpArrow;
-		break;
-	case Common::KEYCODE_DOWN:
-	case Common::KEYCODE_KP2:
-		gott = eAGSKeyCodeDownArrow;
-		break;
-
-	default:
-		if (keyState.flags & (Common::KBD_ALT | Common::KBD_CTRL) &&
-			keyState.keycode >= Common::KEYCODE_a && keyState.keycode <= Common::KEYCODE_z)
+	const int read_key_value = readkey();
+	int gott = read_key_value;
+	const int scancode = ((gott >> 8) & 0x00ff);
+	const int ascii = (gott & 0x00ff);
+
+	bool is_extended = (ascii == EXTENDED_KEY_CODE);
+	// On macos, the extended keycode is the ascii character '?' or '\0' if alt-key
+	// so check it's not actually the character '?'
+#if AGS_PLATFORM_OS_MACOS && ! AGS_PLATFORM_OS_IOS
+	is_extended = is_extended || ((ascii == EXTENDED_KEY_CODE_MACOS) && (scancode != __allegro_KEY_SLASH));
+#endif
+
+	/*  char message[200];
+	sprintf(message, "Scancode: %04X", gott);
+	Debug::Printf(message);*/
+
+	/*if ((scancode >= KEY_0_PAD) && (scancode <= KEY_9_PAD)) {
+	// fix numeric pad keys if numlock is off (allegro 4.2 changed this behaviour)
+	if ((key_shifts & KB_NUMLOCK_FLAG) == 0)
+	gott = (gott & 0xff00) | EXTENDED_KEY_CODE;
+	}*/
+
+	if (gott == READKEY_CODE_ALT_TAB) {
+		// Alt+Tab, it gets stuck down unless we do this
+		gott = AGS_KEYCODE_ALT_TAB;
+	}
+#if AGS_PLATFORM_OS_MACOS
+	else if (scancode == __allegro_KEY_BACKSPACE) {
+		gott = eAGSKeyCodeBackspace;
+	}
+#endif
+	else if (is_extended) {
+
+		// I believe we rely on a lot of keys being converted to ASCII, which is why
+		// the complete scan code list is not here.
+
+		switch (scancode) {
+		case __allegro_KEY_F1: gott = eAGSKeyCodeF1; break;
+		case __allegro_KEY_F2: gott = eAGSKeyCodeF2; break;
+		case __allegro_KEY_F3: gott = eAGSKeyCodeF3; break;
+		case __allegro_KEY_F4: gott = eAGSKeyCodeF4; break;
+		case __allegro_KEY_F5: gott = eAGSKeyCodeF5; break;
+		case __allegro_KEY_F6: gott = eAGSKeyCodeF6; break;
+		case __allegro_KEY_F7: gott = eAGSKeyCodeF7; break;
+		case __allegro_KEY_F8: gott = eAGSKeyCodeF8; break;
+		case __allegro_KEY_F9: gott = eAGSKeyCodeF9; break;
+		case __allegro_KEY_F10: gott = eAGSKeyCodeF10; break;
+		case __allegro_KEY_F11: gott = eAGSKeyCodeF11; break;
+		case __allegro_KEY_F12: gott = eAGSKeyCodeF12; break;
+
+		case __allegro_KEY_INSERT: gott = eAGSKeyCodeInsert; break;
+		case __allegro_KEY_DEL: gott = eAGSKeyCodeDelete; break;
+		case __allegro_KEY_HOME: gott = eAGSKeyCodeHome; break;
+		case __allegro_KEY_END: gott = eAGSKeyCodeEnd; break;
+		case __allegro_KEY_PGUP: gott = eAGSKeyCodePageUp; break;
+		case __allegro_KEY_PGDN: gott = eAGSKeyCodePageDown; break;
+		case __allegro_KEY_LEFT: gott = eAGSKeyCodeLeftArrow; break;
+		case __allegro_KEY_RIGHT: gott = eAGSKeyCodeRightArrow; break;
+		case __allegro_KEY_UP: gott = eAGSKeyCodeUpArrow; break;
+		case __allegro_KEY_DOWN: gott = eAGSKeyCodeDownArrow; break;
+
+		case __allegro_KEY_0_PAD: gott = eAGSKeyCodeInsert; break;
+		case __allegro_KEY_1_PAD: gott = eAGSKeyCodeEnd; break;
+		case __allegro_KEY_2_PAD: gott = eAGSKeyCodeDownArrow; break;
+		case __allegro_KEY_3_PAD: gott = eAGSKeyCodePageDown; break;
+		case __allegro_KEY_4_PAD: gott = eAGSKeyCodeLeftArrow; break;
+		case __allegro_KEY_5_PAD: gott = eAGSKeyCodeNumPad5; break;
+		case __allegro_KEY_6_PAD: gott = eAGSKeyCodeRightArrow; break;
+		case __allegro_KEY_7_PAD: gott = eAGSKeyCodeHome; break;
+		case __allegro_KEY_8_PAD: gott = eAGSKeyCodeUpArrow; break;
+		case __allegro_KEY_9_PAD: gott = eAGSKeyCodePageUp; break;
+		case __allegro_KEY_DEL_PAD: gott = eAGSKeyCodeDelete; break;
+
+		default:
 			// no meaningful mappings
 			// this is how we accidentally got the alt-key mappings
-			gott = AGS_EXT_KEY_SHIFT + (keyState.keycode - Common::KEYCODE_a) + 1;
-		else
-			gott = keyState.ascii;
-		break;
+			gott = scancode + AGS_EXT_KEY_SHIFT;
+		}
+	} else {
+		// this includes ascii characters and ctrl-A-Z
+		gott = ascii;
 	}
 
 	// Alt+X, abort (but only once game is loaded)
diff --git a/engines/ags/engine/ac/system.cpp b/engines/ags/engine/ac/system.cpp
index 02d4c0a2d7..0275ec1b6a 100644
--- a/engines/ags/engine/ac/system.cpp
+++ b/engines/ags/engine/ac/system.cpp
@@ -40,11 +40,11 @@
 #include "ags/engine/ac/global_translation.h"
 #include "ags/engine/media/audio/audio_system.h"
 #include "ags/shared/util/string_compat.h"
-
 #include "ags/shared/debugging/out.h"
 #include "ags/engine/script/script_api.h"
 #include "ags/engine/script/script_runtime.h"
 #include "ags/engine/ac/dynobj/scriptstring.h"
+#include "ags/events.h"
 
 namespace AGS3 {
 
@@ -118,15 +118,15 @@ int System_GetHardwareAcceleration() {
 }
 
 int System_GetNumLock() {
-	return (key_shifts & KB_NUMLOCK_FLAG) ? 1 : 0;
+	return (::AGS::g_events->getModifierFlags() & __allegro_KB_NUMLOCK_FLAG) ? 1 : 0;
 }
 
 int System_GetCapsLock() {
-	return (key_shifts & KB_CAPSLOCK_FLAG) ? 1 : 0;
+	return (::AGS::g_events->getModifierFlags() & __allegro_KB_CAPSLOCK_FLAG) ? 1 : 0;
 }
 
 int System_GetScrollLock() {
-	return (key_shifts & KB_SCROLOCK_FLAG) ? 1 : 0;
+	return (::AGS::g_events->getModifierFlags() & __allegro_KB_SCROLOCK_FLAG) ? 1 : 0;
 }
 
 void System_SetNumLock(int newValue) {
diff --git a/engines/ags/engine/debugging/debug.cpp b/engines/ags/engine/debugging/debug.cpp
index 921108c4b2..9fc93fbf7e 100644
--- a/engines/ags/engine/debugging/debug.cpp
+++ b/engines/ags/engine/debugging/debug.cpp
@@ -44,6 +44,7 @@
 #include "ags/shared/script/cc_error.h"
 #include "ags/shared/util/string_utils.h"
 #include "ags/shared/util/textstreamwriter.h"
+#include "ags/events.h"
 
 #if AGS_PLATFORM_OS_WINDOWS
 //include <winalleg.h>
@@ -564,14 +565,12 @@ void check_debug_keys() {
 	if (play.debug_mode) {
 		// do the run-time script debugging
 
-		if ((!key[KEY_SCRLOCK]) && (scrlockWasDown))
+		if (!::AGS::g_events->isKeyPressed(KEY_SCRLOCK) && scrlockWasDown)
 			scrlockWasDown = 0;
-		else if ((key[KEY_SCRLOCK]) && (!scrlockWasDown)) {
-
+		else if (::AGS::g_events->isKeyPressed(KEY_SCRLOCK) && !scrlockWasDown) {
 			break_on_next_script_step = 1;
 			scrlockWasDown = 1;
 		}
-
 	}
 }
 
diff --git a/engines/ags/engine/main/game_run.cpp b/engines/ags/engine/main/game_run.cpp
index c331315f41..4870b1c275 100644
--- a/engines/ags/engine/main/game_run.cpp
+++ b/engines/ags/engine/main/game_run.cpp
@@ -66,6 +66,7 @@
 #include "ags/engine/ac/timer.h"
 #include "ags/engine/ac/keycode.h"
 #include "ags/lib/allegro/keyboard.h"
+#include "ags/events.h"
 
 namespace AGS3 {
 
@@ -280,14 +281,7 @@ static void check_mouse_controls() {
 // situation: if first modifier gets pressed, 'key_shifts' will be zero,
 // when second modifier gets pressed it will only contain first one, and so on.
 static int get_active_shifts() {
-	int shifts = 0;
-	if (key[KEY_LSHIFT] || key[KEY_RSHIFT])
-		shifts |= KB_SHIFT_FLAG;
-	if (key[KEY_LCONTROL] || key[KEY_RCONTROL])
-		shifts |= KB_CTRL_FLAG;
-	if (key[KEY_ALT] || key[KEY_ALTGR])
-		shifts |= KB_ALT_FLAG;
-	return shifts;
+	return ::AGS::g_events->getModifierFlags();
 }
 
 // Special flags to OR saved shift flags with:
@@ -345,7 +339,10 @@ bool run_service_key_controls(int &kgn) {
 
 	// LAlt or RAlt + Enter
 	// NOTE: for some reason LAlt + Enter produces same code as F9
-	if (act_shifts == KB_ALT_FLAG && ((keycode == eAGSKeyCodeF9 && !key[KEY_F9]) || keycode == eAGSKeyCodeReturn)) {
+	if (act_shifts == KB_ALT_FLAG && (
+			(keycode == eAGSKeyCodeF9 && !::AGS::g_events->isKeyPressed(KEY_F9)) ||
+			keycode == eAGSKeyCodeReturn)
+	) {
 		engine_try_switch_windowed_gfxmode();
 		return false;
 	}
@@ -476,7 +473,8 @@ static void check_keyboard_controls() {
 	//     return;
 	// }
 
-	if ((kgn == eAGSKeyCodeAltV) && (key[KEY_LCONTROL] || key[KEY_RCONTROL]) && (play.wait_counter < 1) && (is_text_overlay == 0) && (restrict_until == 0)) {
+	if (kgn == eAGSKeyCodeAltV && (::AGS::g_events->getModifierFlags() & KB_CTRL_FLAG)
+			&& (play.wait_counter < 1) && (is_text_overlay == 0) && (restrict_until == 0)) {
 		// make sure we can't interrupt a Wait()
 		// and desync the music to cutscene
 		play.debug_mode++;
diff --git a/engines/ags/engine/platform/base/agsplatformdriver.cpp b/engines/ags/engine/platform/base/agsplatformdriver.cpp
index cfd02ea602..150a7f6418 100644
--- a/engines/ags/engine/platform/base/agsplatformdriver.cpp
+++ b/engines/ags/engine/platform/base/agsplatformdriver.cpp
@@ -159,7 +159,7 @@ void AGSPlatformDriver::SetGameWindowIcon() {
 }
 
 int AGSPlatformDriver::ConvertKeycodeToScanCode(int keycode) {
-	keycode -= ('A' - KEY_A);
+	keycode -= ('A' - Common::KEYCODE_a);
 	return keycode;
 }
 
diff --git a/engines/ags/events.cpp b/engines/ags/events.cpp
index 983dcee60f..8a6c7a2a61 100644
--- a/engines/ags/events.cpp
+++ b/engines/ags/events.cpp
@@ -32,8 +32,9 @@ namespace AGS {
 
 EventsManager *g_events;
 
-EventsManager::EventsManager() {
+EventsManager::EventsManager() : _keyFlags(0) {
 	g_events = this;
+	_keys.resize(AGS3::__allegro_KEY_MAX);
 }
 
 EventsManager::~EventsManager() {
@@ -50,10 +51,15 @@ void EventsManager::pollEvents() {
 			::AGS3::check_dynamic_sprites_at_exit = 0;
 
 		} else if (e.type == Common::EVENT_KEYDOWN) {
+			updateKeys(e.kbd.keycode, true);
+
 			if (!isModifierKey(e.kbd.keycode)) {
 				// Add keypresses to the pending key list
 				_pendingKeys.push(e.kbd);
 			}
+		} else if (e.type == Common::EVENT_KEYUP) {
+			updateKeys(e.kbd.keycode, false);
+
 		} else {
 			// Add other event types to the pending events queue. If the event is a
 			// mouse move and the prior one was also, then discard the prior one.
@@ -67,23 +73,23 @@ void EventsManager::pollEvents() {
 	}
 }
 
-bool EventsManager::isModifierKey(const Common::KeyCode &keycode) const {
-	return keycode == Common::KEYCODE_LCTRL || keycode == Common::KEYCODE_LALT
-		|| keycode == Common::KEYCODE_RCTRL || keycode == Common::KEYCODE_RALT
-		|| keycode == Common::KEYCODE_LSHIFT || keycode == Common::KEYCODE_RSHIFT
-		|| keycode == Common::KEYCODE_LSUPER || keycode == Common::KEYCODE_RSUPER
-		|| keycode == Common::KEYCODE_CAPSLOCK || keycode == Common::KEYCODE_NUMLOCK
-		|| keycode == Common::KEYCODE_SCROLLOCK;
-}
-
 bool EventsManager::keypressed() {
 	pollEvents();
 	return !_pendingKeys.empty();
 }
 
-Common::KeyState EventsManager::readKey() {
+int EventsManager::readKey() {
 	pollEvents();
-	return _pendingKeys.empty() ? Common::KeyState() : _pendingKeys.pop();
+	if (_pendingKeys.empty())
+		return 0;
+
+	Common::KeyState keyState = _pendingKeys.pop();
+
+	int code = getScancode(keyState.keycode) << 8;
+	if (keyState.ascii >= 0 && keyState.ascii <= 127)
+		code = keyState.ascii;
+
+	return code;
 }
 
 Common::Event EventsManager::readEvent() {
@@ -95,4 +101,100 @@ void EventsManager::warpMouse(const Common::Point &newPos) {
 	g_system->warpMouse(newPos.x, newPos.y);
 }
 
+bool EventsManager::isModifierKey(const Common::KeyCode &keycode) const {
+	return keycode == Common::KEYCODE_LCTRL || keycode == Common::KEYCODE_LALT
+		|| keycode == Common::KEYCODE_RCTRL || keycode == Common::KEYCODE_RALT
+		|| keycode == Common::KEYCODE_LSHIFT || keycode == Common::KEYCODE_RSHIFT
+		|| keycode == Common::KEYCODE_LSUPER || keycode == Common::KEYCODE_RSUPER
+		|| keycode == Common::KEYCODE_CAPSLOCK || keycode == Common::KEYCODE_NUMLOCK
+		|| keycode == Common::KEYCODE_SCROLLOCK;
+}
+
+int EventsManager::getScancode(Common::KeyCode keycode) const {
+	if (keycode >= Common::KEYCODE_a && keycode <= Common::KEYCODE_z)
+		return (int)keycode - Common::KEYCODE_a + AGS3::__allegro_KEY_A;
+	if (keycode >= Common::KEYCODE_0 && keycode <= Common::KEYCODE_9)
+		return (int)keycode - Common::KEYCODE_0 + AGS3::__allegro_KEY_0;
+	if (keycode >= Common::KEYCODE_KP0 && keycode <= Common::KEYCODE_KP9)
+		return (int)keycode - Common::KEYCODE_KP0 + AGS3::__allegro_KEY_0_PAD;
+	if (keycode >= Common::KEYCODE_F1 && keycode <= Common::KEYCODE_F12)
+		return (int)keycode - Common::KEYCODE_F1 + AGS3::__allegro_KEY_F1;
+
+	switch (keycode) {
+	case Common::KEYCODE_ESCAPE: return AGS3::__allegro_KEY_ESC;
+	case Common::KEYCODE_TILDE: return AGS3::__allegro_KEY_TILDE;
+	case Common::KEYCODE_MINUS: return AGS3::__allegro_KEY_MINUS;
+	case Common::KEYCODE_EQUALS: return AGS3::__allegro_KEY_EQUALS;
+	case Common::KEYCODE_BACKSPACE: return AGS3::__allegro_KEY_BACKSPACE;
+	case Common::KEYCODE_TAB: return AGS3::__allegro_KEY_TAB;
+	case Common::KEYCODE_LEFTBRACKET: return AGS3::__allegro_KEY_OPENBRACE;
+	case Common::KEYCODE_RIGHTBRACKET: return AGS3::__allegro_KEY_CLOSEBRACE;
+	case Common::KEYCODE_RETURN: return AGS3::__allegro_KEY_ENTER;
+	case Common::KEYCODE_COLON: return AGS3::__allegro_KEY_COLON;
+	case Common::KEYCODE_QUOTE: return AGS3::__allegro_KEY_QUOTE;
+	case Common::KEYCODE_BACKSLASH: return AGS3::__allegro_KEY_BACKSLASH;
+	case Common::KEYCODE_COMMA: return AGS3::__allegro_KEY_COMMA;
+	case Common::KEYCODE_SLASH: return AGS3::__allegro_KEY_SLASH;
+	case Common::KEYCODE_SPACE: return AGS3::__allegro_KEY_SPACE;
+	case Common::KEYCODE_INSERT: return AGS3::__allegro_KEY_INSERT;
+	case Common::KEYCODE_DELETE: return AGS3::__allegro_KEY_DEL;
+	case Common::KEYCODE_HOME: return AGS3::__allegro_KEY_HOME;
+	case Common::KEYCODE_END: return AGS3::__allegro_KEY_END;
+	case Common::KEYCODE_PAGEUP: return AGS3::__allegro_KEY_PGUP;
+	case Common::KEYCODE_PAGEDOWN: return AGS3::__allegro_KEY_PGDN;
+	case Common::KEYCODE_LEFT: return AGS3::__allegro_KEY_LEFT;
+	case Common::KEYCODE_RIGHT: return AGS3::__allegro_KEY_RIGHT;
+	case Common::KEYCODE_UP: return AGS3::__allegro_KEY_UP;
+	case Common::KEYCODE_DOWN: return AGS3::__allegro_KEY_DOWN;
+	case Common::KEYCODE_KP_DIVIDE: return AGS3::__allegro_KEY_SLASH_PAD;
+	case Common::KEYCODE_ASTERISK: return AGS3::__allegro_KEY_ASTERISK;
+	case Common::KEYCODE_KP_MINUS: return AGS3::__allegro_KEY_MINUS_PAD;
+	case Common::KEYCODE_KP_PLUS: return AGS3::__allegro_KEY_PLUS_PAD;
+	case Common::KEYCODE_KP_PERIOD: return AGS3::__allegro_KEY_DEL_PAD;
+	case Common::KEYCODE_KP_ENTER: return AGS3::__allegro_KEY_ENTER_PAD;
+	case Common::KEYCODE_PRINT: return AGS3::__allegro_KEY_PRTSCR;
+	case Common::KEYCODE_PAUSE: return AGS3::__allegro_KEY_PAUSE;
+	case Common::KEYCODE_SEMICOLON: return AGS3::__allegro_KEY_SEMICOLON;
+
+	case Common::KEYCODE_LSHIFT: return AGS3::__allegro_KEY_LSHIFT;
+	case Common::KEYCODE_RSHIFT: return AGS3::__allegro_KEY_RSHIFT;
+	case Common::KEYCODE_LCTRL: return AGS3::__allegro_KEY_LCONTROL;
+	case Common::KEYCODE_RCTRL: return AGS3::__allegro_KEY_RCONTROL;
+	case Common::KEYCODE_LALT: return AGS3::__allegro_KEY_ALT;
+	case Common::KEYCODE_RALT: return AGS3::__allegro_KEY_ALT;
+	case Common::KEYCODE_SCROLLOCK: return AGS3::__allegro_KEY_SCRLOCK;
+	case Common::KEYCODE_NUMLOCK: return AGS3::__allegro_KEY_NUMLOCK;
+	case Common::KEYCODE_CAPSLOCK: return AGS3::__allegro_KEY_CAPSLOCK;
+	default: return 0;
+	}
+}
+
+void EventsManager::updateKeys(const Common::KeyState &keyState, bool isDown) {
+	// Update the keys array with whether the key is pressed
+	int scancode = getScancode(keyState.keycode);
+	if (scancode != 0)
+		_keys[scancode] = isDown;
+
+	// Update shift flags
+	_keyFlags = 0;
+	if (keyState.flags & Common::KBD_SHIFT)
+		_keyFlags |= AGS3::__allegro_KB_SHIFT_FLAG;
+	if (keyState.flags & Common::KBD_CTRL)
+		_keyFlags |= AGS3::__allegro_KB_CTRL_FLAG;
+	if (keyState.flags & Common::KBD_ALT)
+		_keyFlags |= AGS3::__allegro_KB_ALT_FLAG;
+	if (keyState.flags & Common::KBD_META)
+		_keyFlags |= AGS3::__allegro_KB_COMMAND_FLAG;
+	if (keyState.flags & Common::KBD_SCRL)
+		_keyFlags |= AGS3::__allegro_KB_SCROLOCK_FLAG;
+	if (keyState.flags & Common::KBD_NUM)
+		_keyFlags |= AGS3::__allegro_KB_NUMLOCK_FLAG;
+	if (keyState.flags & Common::KBD_CAPS)
+		_keyFlags |= AGS3::__allegro_KB_CAPSLOCK_FLAG;
+}
+
+bool EventsManager::isKeyPressed(AGS3::AllegroKbdKeycode keycode) const {
+	return _keys[keycode];
+}
+
 } // namespace AGS
diff --git a/engines/ags/events.h b/engines/ags/events.h
index 5842bd9548..f291136c07 100644
--- a/engines/ags/events.h
+++ b/engines/ags/events.h
@@ -23,6 +23,8 @@
 #ifndef AGS_EVENTS_H
 #define AGS_EVENTS_H
 
+#include "lib/allegro/keyboard.h"
+#include "common/array.h"
 #include "common/queue.h"
 #include "common/events.h"
 
@@ -32,8 +34,14 @@ class EventsManager {
 private:
 	Common::Queue<Common::Event> _pendingEvents;
 	Common::Queue<Common::KeyState> _pendingKeys;
+	Common::Array<bool> _keys;
+	uint _keyFlags;
 
 	bool isModifierKey(const Common::KeyCode &keycode) const;
+
+	int getScancode(Common::KeyCode keycode) const;
+
+	void updateKeys(const Common::KeyState &keyState, bool isDown);
 public:
 	EventsManager();
 	~EventsManager();
@@ -51,7 +59,7 @@ public:
 	/**
 	 * Returns the next keypress, if any is pending
 	 */
-	Common::KeyState readKey();
+	int readKey();
 
 	/**
 	 * Returns the next event, if any
@@ -62,6 +70,18 @@ public:
 	 * Sets the mouse position
 	 */
 	void warpMouse(const Common::Point &newPos);
+
+	/**
+	 * Returns true if a given key is pressed
+	 */
+	bool isKeyPressed(AGS3::AllegroKbdKeycode keycode) const;
+
+	/**
+	 * Returns the bitset of currently pressed modifier keys
+	 */
+	uint getModifierFlags() const {
+		return _keyFlags;
+	}
 };
 
 extern EventsManager *g_events;
diff --git a/engines/ags/lib/allegro/keyboard.cpp b/engines/ags/lib/allegro/keyboard.cpp
index 7629e364e7..869ca1655a 100644
--- a/engines/ags/lib/allegro/keyboard.cpp
+++ b/engines/ags/lib/allegro/keyboard.cpp
@@ -72,7 +72,7 @@ bool keypressed() {
 	return ::AGS::g_events->keypressed();
 }
 
-Common::KeyState readkey() {
+int readkey() {
 	return ::AGS::g_events->readKey();
 }
 
diff --git a/engines/ags/lib/allegro/keyboard.h b/engines/ags/lib/allegro/keyboard.h
index 5f5b4ccc1f..873737e163 100644
--- a/engines/ags/lib/allegro/keyboard.h
+++ b/engines/ags/lib/allegro/keyboard.h
@@ -28,151 +28,305 @@
 
 namespace AGS3 {
 
-#define __allegro_KEY_MAX Common::KEYCODE_LAST
-
-#define KB_SHIFT_FLAG Common::KBD_SHIFT
-#define KB_CTRL_FLAG Common::KBD_CTRL
-#define KB_ALT_FLAG Common::KBD_ALT
-#define KB_NUMLOCK_FLAG Common::KBD_NUM
-#define KB_CAPSLOCK_FLAG Common::KBD_CAPS
-#define KB_SCROLOCK_FLAG Common::KBD_SCRL
-
-#define KEY_LSHIFT Common::KEYCODE_LSHIFT
-#define KEY_RSHIFT Common::KEYCODE_RSHIFT
-#define KEY_ALT Common::KEYCODE_LALT
-#define KEY_LCONTROL Common::KEYCODE_LCTRL
-#define KEY_RCONTROL Common::KEYCODE_RCTRL
-#define KEY_SCRLOCK Common::KEYCODE_SCROLLOCK
-#define KEY_ALTGR 0
-#define KEY_F9 Common::KEYCODE_F9
-#define KEY_A Common::KEYCODE_a
-
-#define __allegro_KEY_LSHIFT Common::KEYCODE_LSHIFT
-#define __allegro_KEY_RSHIFT Common::KEYCODE_RSHIFT
-#define __allegro_KEY_LCONTROL Common::KEYCODE_LCTRL
-#define __allegro_KEY_RCONTROL Common::KEYCODE_RCTRL
-#define __allegro_KEY_ALT Common::KEYCODE_LALT
-
-#define __allegro_KEY_F1 Common::KEYCODE_F1
-#define __allegro_KEY_F2 Common::KEYCODE_F2
-#define __allegro_KEY_F3 Common::KEYCODE_F3
-#define __allegro_KEY_F4 Common::KEYCODE_F4
-#define __allegro_KEY_F5 Common::KEYCODE_F5
-#define __allegro_KEY_F6 Common::KEYCODE_F6
-#define __allegro_KEY_F7 Common::KEYCODE_F7
-#define __allegro_KEY_F8 Common::KEYCODE_F8
-#define __allegro_KEY_F9 Common::KEYCODE_F9
-#define __allegro_KEY_F10 Common::KEYCODE_F10
-#define __allegro_KEY_F11 Common::KEYCODE_F11
-#define __allegro_KEY_F12 Common::KEYCODE_F12
-
-#define __allegro_KEY_HOME Common::KEYCODE_HOME
-#define __allegro_KEY_UP Common::KEYCODE_UP
-#define __allegro_KEY_PGUP Common::KEYCODE_PAGEUP
-#define __allegro_KEY_LEFT Common::KEYCODE_LEFT
-#define __allegro_KEY_RIGHT Common::KEYCODE_RIGHT
-#define __allegro_KEY_END Common::KEYCODE_END
-#define __allegro_KEY_DOWN Common::KEYCODE_DOWN
-#define __allegro_KEY_PGDN Common::KEYCODE_PAGEDOWN
-#define __allegro_KEY_INSERT Common::KEYCODE_INSERT
-#define __allegro_KEY_DEL Common::KEYCODE_DELETE
-
-#define __allegro_KEY_0_PAD Common::KEYCODE_KP0
-#define __allegro_KEY_1_PAD Common::KEYCODE_KP1
-#define __allegro_KEY_2_PAD Common::KEYCODE_KP2
-#define __allegro_KEY_3_PAD Common::KEYCODE_KP3
-#define __allegro_KEY_4_PAD Common::KEYCODE_KP4
-#define __allegro_KEY_5_PAD Common::KEYCODE_KP5
-#define __allegro_KEY_6_PAD Common::KEYCODE_KP6
-#define __allegro_KEY_7_PAD Common::KEYCODE_KP7
-#define __allegro_KEY_8_PAD Common::KEYCODE_KP8
-#define __allegro_KEY_9_PAD Common::KEYCODE_KP9
-#define __allegro_KEY_DEL_PAD Common::KEYCODE_KP_PERIOD
-
-#define __allegro_KEY_PRTSCR Common::KEYCODE_PRINT
-#define __allegro_KEY_PAUSE Common::KEYCODE_PAUSE
-#define __allegro_KEY_ABNT_C1 94
-#define __allegro_KEY_YEN 95
-#define __allegro_KEY_KANA 96
-#define __allegro_KEY_CONVERT 97
-#define __allegro_KEY_NOCONVERT 98
-#define __allegro_KEY_CIRCUMFLEX 100
-#define __allegro_KEY_KANJI 102
-#define __allegro_KEY_ALTGR 120
-#define __allegro_KEY_LWIN Common::KEYCODE_LMETA
-#define __allegro_KEY_RWIN Common::KEYCODE_RMETA
-#define __allegro_KEY_MENU 123
-#define __allegro_KEY_SCRLOCK Common::KEYCODE_SCROLLOCK
-#define __allegro_KEY_NUMLOCK Common::KEYCODE_NUMLOCK
-#define __allegro_KEY_CAPSLOCK Common::KEYCODE_CAPSLOCK
-
-#define __allegro_KEY_0 Common::KEYCODE_0
-#define __allegro_KEY_1 Common::KEYCODE_1
-#define __allegro_KEY_2 Common::KEYCODE_2
-#define __allegro_KEY_3 Common::KEYCODE_3
-#define __allegro_KEY_4 Common::KEYCODE_4
-#define __allegro_KEY_5 Common::KEYCODE_5
-#define __allegro_KEY_6 Common::KEYCODE_6
-#define __allegro_KEY_7 Common::KEYCODE_7
-#define __allegro_KEY_8 Common::KEYCODE_8
-#define __allegro_KEY_9 Common::KEYCODE_9
-
-#define __allegro_KEY_A Common::KEYCODE_a
-#define __allegro_KEY_B Common::KEYCODE_b
-#define __allegro_KEY_C Common::KEYCODE_c
-#define __allegro_KEY_D Common::KEYCODE_d
-#define __allegro_KEY_E Common::KEYCODE_e
-#define __allegro_KEY_F Common::KEYCODE_f
-#define __allegro_KEY_G Common::KEYCODE_g
-#define __allegro_KEY_H Common::KEYCODE_h
-#define __allegro_KEY_I Common::KEYCODE_i
-#define __allegro_KEY_J Common::KEYCODE_j
-#define __allegro_KEY_K Common::KEYCODE_k
-#define __allegro_KEY_L Common::KEYCODE_l
-#define __allegro_KEY_M Common::KEYCODE_m
-#define __allegro_KEY_N Common::KEYCODE_n
-#define __allegro_KEY_O Common::KEYCODE_o
-#define __allegro_KEY_P Common::KEYCODE_p
-#define __allegro_KEY_Q Common::KEYCODE_q
-#define __allegro_KEY_R Common::KEYCODE_r
-#define __allegro_KEY_S Common::KEYCODE_s
-#define __allegro_KEY_T Common::KEYCODE_t
-#define __allegro_KEY_U Common::KEYCODE_u
-#define __allegro_KEY_V Common::KEYCODE_v
-#define __allegro_KEY_W Common::KEYCODE_w
-#define __allegro_KEY_X Common::KEYCODE_x
-#define __allegro_KEY_Y Common::KEYCODE_y
-#define __allegro_KEY_Z Common::KEYCODE_z
-
-
-#define __allegro_KEY_BACKSPACE Common::KEYCODE_BACKSPACE
-#define __allegro_KEY_TAB Common::KEYCODE_TAB
-#define __allegro_KEY_ENTER Common::KEYCODE_RETURN
-#define __allegro_KEY_ENTER_PAD Common::KEYCODE_KP_ENTER
-#define __allegro_KEY_ESC Common::KEYCODE_ESCAPE
-#define __allegro_KEY_SPACE Common::KEYCODE_SPACE
-#define __allegro_KEY_QUOTE Common::KEYCODE_QUOTE
-#define __allegro_KEY_COMMA Common::KEYCODE_COMMA
-#define __allegro_KEY_STOP 0
-#define __allegro_KEY_SLASH Common::KEYCODE_SLASH
-#define __allegro_KEY_SLASH_PAD Common::KEYCODE_KP_DIVIDE
-#define __allegro_KEY_BACKSLASH Common::KEYCODE_BACKSLASH
-#define __allegro_KEY_BACKSLASH2 Common::KEYCODE_BACKSLASH
-#define __allegro_KEY_SEMICOLON Common::KEYCODE_SEMICOLON
-#define __allegro_KEY_EQUALS Common::KEYCODE_EQUALS
-#define __allegro_KEY_EQUALS_PAD Common::KEYCODE_KP_EQUALS
-#define __allegro_KEY_OPENBRACE 123
-#define __allegro_KEY_CLOSEBRACE 125
-#define __allegro_KEY_PLUS_PAD Common::KEYCODE_KP_PLUS
-#define __allegro_KEY_MINUS Common::KEYCODE_MINUS
-#define __allegro_KEY_MINUS_PAD Common::KEYCODE_KP_MINUS
-#define __allegro_KEY_COLON Common::KEYCODE_COLON
-#define __allegro_KEY_COLON2 Common::KEYCODE_COLON
-#define __allegro_KEY_ASTERISK Common::KEYCODE_ASTERISK
-#define __allegro_KEY_AT Common::KEYCODE_AT
-
-extern bool key[Common::KEYCODE_LAST];
-extern uint key_shifts;
+enum AllegroKbdFlag {
+   __allegro_KB_SHIFT_FLAG    = 0x0001,
+   __allegro_KB_CTRL_FLAG     = 0x0002,
+   __allegro_KB_ALT_FLAG      = 0x0004,
+   __allegro_KB_LWIN_FLAG     = 0x0008,
+   __allegro_KB_RWIN_FLAG     = 0x0010,
+   __allegro_KB_MENU_FLAG     = 0x0020,
+   __allegro_KB_COMMAND_FLAG  = 0x0040,
+   __allegro_KB_SCROLOCK_FLAG = 0x0100,
+   __allegro_KB_NUMLOCK_FLAG  = 0x0200,
+   __allegro_KB_CAPSLOCK_FLAG = 0x0400,
+   __allegro_KB_INALTSEQ_FLAG = 0x0800,
+   __allegro_KB_ACCENT1_FLAG  = 0x1000,
+   __allegro_KB_ACCENT2_FLAG  = 0x2000,
+   __allegro_KB_ACCENT3_FLAG  = 0x4000,
+   __allegro_KB_ACCENT4_FLAG  = 0x8000
+};
+
+enum AllegroKbdKeycode {
+   __allegro_KEY_A            = 1,
+   __allegro_KEY_B            = 2,
+   __allegro_KEY_C            = 3,
+   __allegro_KEY_D            = 4,
+   __allegro_KEY_E            = 5,
+   __allegro_KEY_F            = 6,
+   __allegro_KEY_G            = 7,
+   __allegro_KEY_H            = 8,
+   __allegro_KEY_I            = 9,
+   __allegro_KEY_J            = 10,
+   __allegro_KEY_K            = 11,
+   __allegro_KEY_L            = 12,
+   __allegro_KEY_M            = 13,
+   __allegro_KEY_N            = 14,
+   __allegro_KEY_O            = 15,
+   __allegro_KEY_P            = 16,
+   __allegro_KEY_Q            = 17,
+   __allegro_KEY_R            = 18,
+   __allegro_KEY_S            = 19,
+   __allegro_KEY_T            = 20,
+   __allegro_KEY_U            = 21,
+   __allegro_KEY_V            = 22,
+   __allegro_KEY_W            = 23,
+   __allegro_KEY_X            = 24,
+   __allegro_KEY_Y            = 25,
+   __allegro_KEY_Z            = 26,
+   __allegro_KEY_0            = 27,
+   __allegro_KEY_1            = 28,
+   __allegro_KEY_2            = 29,
+   __allegro_KEY_3            = 30,
+   __allegro_KEY_4            = 31,
+   __allegro_KEY_5            = 32,
+   __allegro_KEY_6            = 33,
+   __allegro_KEY_7            = 34,
+   __allegro_KEY_8            = 35,
+   __allegro_KEY_9            = 36,
+   __allegro_KEY_0_PAD        = 37,
+   __allegro_KEY_1_PAD        = 38,
+   __allegro_KEY_2_PAD        = 39,
+   __allegro_KEY_3_PAD        = 40,
+   __allegro_KEY_4_PAD        = 41,
+   __allegro_KEY_5_PAD        = 42,
+   __allegro_KEY_6_PAD        = 43,
+   __allegro_KEY_7_PAD        = 44,
+   __allegro_KEY_8_PAD        = 45,
+   __allegro_KEY_9_PAD        = 46,
+   __allegro_KEY_F1           = 47,
+   __allegro_KEY_F2           = 48,
+   __allegro_KEY_F3           = 49,
+   __allegro_KEY_F4           = 50,
+   __allegro_KEY_F5           = 51,
+   __allegro_KEY_F6           = 52,
+   __allegro_KEY_F7           = 53,
+   __allegro_KEY_F8           = 54,
+   __allegro_KEY_F9           = 55,
+   __allegro_KEY_F10          = 56,
+   __allegro_KEY_F11          = 57,
+   __allegro_KEY_F12          = 58,
+   __allegro_KEY_ESC          = 59,
+   __allegro_KEY_TILDE        = 60,
+   __allegro_KEY_MINUS        = 61,
+   __allegro_KEY_EQUALS       = 62,
+   __allegro_KEY_BACKSPACE    = 63,
+   __allegro_KEY_TAB          = 64,
+   __allegro_KEY_OPENBRACE    = 65,
+   __allegro_KEY_CLOSEBRACE   = 66,
+   __allegro_KEY_ENTER        = 67,
+   __allegro_KEY_COLON        = 68,
+   __allegro_KEY_QUOTE        = 69,
+   __allegro_KEY_BACKSLASH    = 70,
+   __allegro_KEY_BACKSLASH2   = 71,
+   __allegro_KEY_COMMA        = 72,
+   __allegro_KEY_STOP         = 73,
+   __allegro_KEY_SLASH        = 74,
+   __allegro_KEY_SPACE        = 75,
+   __allegro_KEY_INSERT       = 76,
+   __allegro_KEY_DEL          = 77,
+   __allegro_KEY_HOME         = 78,
+   __allegro_KEY_END          = 79,
+   __allegro_KEY_PGUP         = 80,
+   __allegro_KEY_PGDN         = 81,
+   __allegro_KEY_LEFT         = 82,
+   __allegro_KEY_RIGHT        = 83,
+   __allegro_KEY_UP           = 84,
+   __allegro_KEY_DOWN         = 85,
+   __allegro_KEY_SLASH_PAD    = 86,
+   __allegro_KEY_ASTERISK     = 87,
+   __allegro_KEY_MINUS_PAD    = 88,
+   __allegro_KEY_PLUS_PAD     = 89,
+   __allegro_KEY_DEL_PAD      = 90,
+   __allegro_KEY_ENTER_PAD    = 91,
+   __allegro_KEY_PRTSCR       = 92,
+   __allegro_KEY_PAUSE        = 93,
+   __allegro_KEY_ABNT_C1      = 94,
+   __allegro_KEY_YEN          = 95,
+   __allegro_KEY_KANA         = 96,
+   __allegro_KEY_CONVERT      = 97,
+   __allegro_KEY_NOCONVERT    = 98,
+   __allegro_KEY_AT           = 99,
+   __allegro_KEY_CIRCUMFLEX   = 100,
+   __allegro_KEY_COLON2       = 101,
+   __allegro_KEY_KANJI        = 102,
+   __allegro_KEY_EQUALS_PAD   = 103,  /* MacOS X */
+   __allegro_KEY_BACKQUOTE    = 104,  /* MacOS X */
+   __allegro_KEY_SEMICOLON    = 105,  /* MacOS X */
+   __allegro_KEY_COMMAND      = 106,  /* MacOS X */
+   __allegro_KEY_UNKNOWN1     = 107,
+   __allegro_KEY_UNKNOWN2     = 108,
+   __allegro_KEY_UNKNOWN3     = 109,
+   __allegro_KEY_UNKNOWN4     = 110,
+   __allegro_KEY_UNKNOWN5     = 111,
+   __allegro_KEY_UNKNOWN6     = 112,
+   __allegro_KEY_UNKNOWN7     = 113,
+   __allegro_KEY_UNKNOWN8     = 114,
+
+   __allegro_KEY_MODIFIERS    = 115,
+
+   __allegro_KEY_LSHIFT       = 115,
+   __allegro_KEY_RSHIFT       = 116,
+   __allegro_KEY_LCONTROL     = 117,
+   __allegro_KEY_RCONTROL     = 118,
+   __allegro_KEY_ALT          = 119,
+   __allegro_KEY_ALTGR        = 120,
+   __allegro_KEY_LWIN         = 121,
+   __allegro_KEY_RWIN         = 122,
+   __allegro_KEY_MENU         = 123,
+   __allegro_KEY_SCRLOCK      = 124,
+   __allegro_KEY_NUMLOCK      = 125,
+   __allegro_KEY_CAPSLOCK     = 126,
+
+   __allegro_KEY_MAX          = 127
+};
+
+#define KB_SHIFT_FLAG         __allegro_KB_SHIFT_FLAG
+#define KB_CTRL_FLAG          __allegro_KB_CTRL_FLAG
+#define KB_ALT_FLAG           __allegro_KB_ALT_FLAG
+#define KB_LWIN_FLAG          __allegro_KB_LWIN_FLAG
+#define KB_RWIN_FLAG          __allegro_KB_RWIN_FLAG
+#define KB_MENU_FLAG          __allegro_KB_MENU_FLAG
+#define KB_COMMAND_FLAG       __allegro_KB_COMMAND_FLAG
+#define KB_SCROLOCK_FLAG      __allegro_KB_SCROLOCK_FLAG
+#define KB_NUMLOCK_FLAG       __allegro_KB_NUMLOCK_FLAG
+#define KB_CAPSLOCK_FLAG      __allegro_KB_CAPSLOCK_FLAG
+#define KB_INALTSEQ_FLAG      __allegro_KB_INALTSEQ_FLAG
+#define KB_ACCENT1_FLAG       __allegro_KB_ACCENT1_FLAG
+#define KB_ACCENT2_FLAG       __allegro_KB_ACCENT2_FLAG
+#define KB_ACCENT3_FLAG       __allegro_KB_ACCENT3_FLAG
+#define KB_ACCENT4_FLAG       __allegro_KB_ACCENT4_FLAG
+
+#define KEY_A                 __allegro_KEY_A
+#define KEY_B                 __allegro_KEY_B
+#define KEY_C                 __allegro_KEY_C
+#define KEY_D                 __allegro_KEY_D
+#define KEY_E                 __allegro_KEY_E
+#define KEY_F                 __allegro_KEY_F
+#define KEY_G                 __allegro_KEY_G
+#define KEY_H                 __allegro_KEY_H
+#define KEY_I                 __allegro_KEY_I
+#define KEY_J                 __allegro_KEY_J
+#define KEY_K                 __allegro_KEY_K
+#define KEY_L                 __allegro_KEY_L
+#define KEY_M                 __allegro_KEY_M
+#define KEY_N                 __allegro_KEY_N
+#define KEY_O                 __allegro_KEY_O
+#define KEY_P                 __allegro_KEY_P
+#define KEY_Q                 __allegro_KEY_Q
+#define KEY_R                 __allegro_KEY_R
+#define KEY_S                 __allegro_KEY_S
+#define KEY_T                 __allegro_KEY_T
+#define KEY_U                 __allegro_KEY_U
+#define KEY_V                 __allegro_KEY_V
+#define KEY_W                 __allegro_KEY_W
+#define KEY_X                 __allegro_KEY_X
+#define KEY_Y                 __allegro_KEY_Y
+#define KEY_Z                 __allegro_KEY_Z
+#define KEY_0                 __allegro_KEY_0
+#define KEY_1                 __allegro_KEY_1
+#define KEY_2                 __allegro_KEY_2
+#define KEY_3                 __allegro_KEY_3
+#define KEY_4                 __allegro_KEY_4
+#define KEY_5                 __allegro_KEY_5
+#define KEY_6                 __allegro_KEY_6
+#define KEY_7                 __allegro_KEY_7
+#define KEY_8                 __allegro_KEY_8
+#define KEY_9                 __allegro_KEY_9
+#define KEY_0_PAD             __allegro_KEY_0_PAD
+#define KEY_1_PAD             __allegro_KEY_1_PAD
+#define KEY_2_PAD             __allegro_KEY_2_PAD
+#define KEY_3_PAD             __allegro_KEY_3_PAD
+#define KEY_4_PAD             __allegro_KEY_4_PAD
+#define KEY_5_PAD             __allegro_KEY_5_PAD
+#define KEY_6_PAD             __allegro_KEY_6_PAD
+#define KEY_7_PAD             __allegro_KEY_7_PAD
+#define KEY_8_PAD             __allegro_KEY_8_PAD
+#define KEY_9_PAD             __allegro_KEY_9_PAD
+#define KEY_F1                __allegro_KEY_F1
+#define KEY_F2                __allegro_KEY_F2
+#define KEY_F3                __allegro_KEY_F3
+#define KEY_F4                __allegro_KEY_F4
+#define KEY_F5                __allegro_KEY_F5
+#define KEY_F6                __allegro_KEY_F6
+#define KEY_F7                __allegro_KEY_F7
+#define KEY_F8                __allegro_KEY_F8
+#define KEY_F9                __allegro_KEY_F9
+#define KEY_F10               __allegro_KEY_F10
+#define KEY_F11               __allegro_KEY_F11
+#define KEY_F12               __allegro_KEY_F12
+#define KEY_ESC               __allegro_KEY_ESC
+#define KEY_TILDE             __allegro_KEY_TILDE
+#define KEY_MINUS             __allegro_KEY_MINUS
+#define KEY_EQUALS            __allegro_KEY_EQUALS
+#define KEY_BACKSPACE         __allegro_KEY_BACKSPACE
+#define KEY_TAB               __allegro_KEY_TAB
+#define KEY_OPENBRACE         __allegro_KEY_OPENBRACE
+#define KEY_CLOSEBRACE        __allegro_KEY_CLOSEBRACE
+#define KEY_ENTER             __allegro_KEY_ENTER
+#define KEY_COLON             __allegro_KEY_COLON
+#define KEY_QUOTE             __allegro_KEY_QUOTE
+#define KEY_BACKSLASH         __allegro_KEY_BACKSLASH
+#define KEY_BACKSLASH2        __allegro_KEY_BACKSLASH2
+#define KEY_COMMA             __allegro_KEY_COMMA
+#define KEY_STOP              __allegro_KEY_STOP
+#define KEY_SLASH             __allegro_KEY_SLASH
+#define KEY_SPACE             __allegro_KEY_SPACE
+#define KEY_INSERT            __allegro_KEY_INSERT
+#define KEY_DEL               __allegro_KEY_DEL
+#define KEY_HOME              __allegro_KEY_HOME
+#define KEY_END               __allegro_KEY_END
+#define KEY_PGUP              __allegro_KEY_PGUP
+#define KEY_PGDN              __allegro_KEY_PGDN
+#define KEY_LEFT              __allegro_KEY_LEFT
+#define KEY_RIGHT             __allegro_KEY_RIGHT
+#define KEY_UP                __allegro_KEY_UP
+#define KEY_DOWN              __allegro_KEY_DOWN
+#define KEY_SLASH_PAD         __allegro_KEY_SLASH_PAD
+#define KEY_ASTERISK          __allegro_KEY_ASTERISK
+#define KEY_MINUS_PAD         __allegro_KEY_MINUS_PAD
+#define KEY_PLUS_PAD          __allegro_KEY_PLUS_PAD
+#define KEY_DEL_PAD           __allegro_KEY_DEL_PAD
+#define KEY_ENTER_PAD         __allegro_KEY_ENTER_PAD
+#define KEY_PRTSCR            __allegro_KEY_PRTSCR
+#define KEY_PAUSE             __allegro_KEY_PAUSE
+#define KEY_ABNT_C1           __allegro_KEY_ABNT_C1
+#define KEY_YEN               __allegro_KEY_YEN
+#define KEY_KANA              __allegro_KEY_KANA
+#define KEY_CONVERT           __allegro_KEY_CONVERT
+#define KEY_NOCONVERT         __allegro_KEY_NOCONVERT
+#define KEY_AT                __allegro_KEY_AT
+#define KEY_CIRCUMFLEX        __allegro_KEY_CIRCUMFLEX
+#define KEY_COLON2            __allegro_KEY_COLON2
+#define KEY_KANJI             __allegro_KEY_KANJI
+#define KEY_EQUALS_PAD        __allegro_KEY_EQUALS_PAD
+#define KEY_BACKQUOTE         __allegro_KEY_BACKQUOTE
+#define KEY_SEMICOLON         __allegro_KEY_SEMICOLON
+#define KEY_COMMAND           __allegro_KEY_COMMAND
+#define KEY_UNKNOWN1          __allegro_KEY_UNKNOWN1
+#define KEY_UNKNOWN2          __allegro_KEY_UNKNOWN2
+#define KEY_UNKNOWN3          __allegro_KEY_UNKNOWN3
+#define KEY_UNKNOWN4          __allegro_KEY_UNKNOWN4
+#define KEY_UNKNOWN5          __allegro_KEY_UNKNOWN5
+#define KEY_UNKNOWN6          __allegro_KEY_UNKNOWN6
+#define KEY_UNKNOWN7          __allegro_KEY_UNKNOWN7
+#define KEY_UNKNOWN8          __allegro_KEY_UNKNOWN8
+
+#define KEY_MODIFIERS         __allegro_KEY_MODIFIERS
+
+#define KEY_LSHIFT            __allegro_KEY_LSHIFT
+#define KEY_RSHIFT            __allegro_KEY_RSHIFT
+#define KEY_LCONTROL          __allegro_KEY_LCONTROL
+#define KEY_RCONTROL          __allegro_KEY_RCONTROL
+#define KEY_ALT               __allegro_KEY_ALT
+#define KEY_ALTGR             __allegro_KEY_ALTGR
+#define KEY_LWIN              __allegro_KEY_LWIN
+#define KEY_RWIN              __allegro_KEY_RWIN
+#define KEY_MENU              __allegro_KEY_MENU
+#define KEY_SCRLOCK           __allegro_KEY_SCRLOCK
+#define KEY_NUMLOCK           __allegro_KEY_NUMLOCK
+#define KEY_CAPSLOCK          __allegro_KEY_CAPSLOCK
+
+#define KEY_MAX               __allegro_KEY_MAX
 
 AL_FUNC(bool, keyboard_needs_poll, (void));
 AL_FUNC(int, poll_keyboard, (void));
@@ -183,7 +337,7 @@ AL_FUNC(void, simulate_keypress, (int keycode));
 AL_FUNC(void, simulate_ukeypress, (int keycode, int scancode));
 
 AL_FUNC(bool, keypressed, (void));
-AL_FUNC(Common::KeyState, readkey, (void));
+AL_FUNC(int, readkey, (void));
 
 } // namespace AGS3
 


Commit: c2e502f771da38286aaf7e869d76ef6c1f8c1024
    https://github.com/scummvm/scummvm/commit/c2e502f771da38286aaf7e869d76ef6c1f8c1024
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix assert on ClearRect with invalid coordinates

Changed paths:
    engines/ags/engine/gfx/gfxfilter_allegro.cpp


diff --git a/engines/ags/engine/gfx/gfxfilter_allegro.cpp b/engines/ags/engine/gfx/gfxfilter_allegro.cpp
index aa24f8c3b4..0392f173fe 100644
--- a/engines/ags/engine/gfx/gfxfilter_allegro.cpp
+++ b/engines/ags/engine/gfx/gfxfilter_allegro.cpp
@@ -115,7 +115,8 @@ void AllegroGfxFilter::RenderScreenFlipped(Bitmap *toRender, int x, int y, Globa
 }
 
 void AllegroGfxFilter::ClearRect(int x1, int y1, int x2, int y2, int color) {
-	if (!realScreen) return;
+	if (!realScreen || x2 < x1 || y2 < y1)
+		return;
 	Rect r = _scaling.ScaleRange(Rect(x1, y1, x2, y2));
 	realScreen->FillRect(r, color);
 }


Commit: 35497da6249396d9c66b4635bb4bb2d99e608864
    https://github.com/scummvm/scummvm/commit/35497da6249396d9c66b4635bb4bb2d99e608864
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix unreachable code warnings

Changed paths:
    engines/ags/engine/ac/global_button.cpp
    engines/ags/lib/allegro/gfx.cpp


diff --git a/engines/ags/engine/ac/global_button.cpp b/engines/ags/engine/ac/global_button.cpp
index 77508d1f5e..db72fbebb2 100644
--- a/engines/ags/engine/ac/global_button.cpp
+++ b/engines/ags/engine/ac/global_button.cpp
@@ -81,8 +81,6 @@ int GetButtonPic(int guin, int objn, int ptype) {
 	} else { // pushed pic
 		return guil->PushedImage;
 	}
-
-	quit("internal error in getbuttonpic");
 }
 
 void SetButtonPic(int guin, int objn, int ptype, int slotn) {
diff --git a/engines/ags/lib/allegro/gfx.cpp b/engines/ags/lib/allegro/gfx.cpp
index c35184d27b..df0f0ea2e8 100644
--- a/engines/ags/lib/allegro/gfx.cpp
+++ b/engines/ags/lib/allegro/gfx.cpp
@@ -406,13 +406,10 @@ int getpixel(BITMAP *bmp, int x, int y) {
 	switch (surf.format.bytesPerPixel) {
 	case 1:
 		return *((uint8 *)p);
-		break;
 	case 2:
 		return *((uint16 *)p);
-		break;
 	case 4:
 		return *((uint32 *)p);
-		break;
 	default:
 		break;
 	}


Commit: 7097d33268292fdcb611caade331a0731974f190
    https://github.com/scummvm/scummvm/commit/7097d33268292fdcb611caade331a0731974f190
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix some overflow warnings

Changed paths:
    engines/ags/ags.cpp
    engines/ags/engine/script/cc_instance.cpp


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index 822737d3b2..1a0805f45d 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -193,8 +193,8 @@ static int main_process_cmdline(ConfigTree &cfg, int argc, const char *argv[]) {
 		}
 #endif
 		else if ((scumm_stricmp(arg, "--testre") == 0) && (ee < argc - 2)) {
-			strcpy(return_to_roomedit, argv[ee + 1]);
-			strcpy(return_to_room, argv[ee + 2]);
+			strncpy(return_to_roomedit, argv[ee + 1], 30);
+			strncpy(return_to_room, argv[ee + 2], 150);
 			ee += 2;
 		} else if (scumm_stricmp(arg, "-noexceptionhandler") == 0) usetup.disable_exception_handling = true;
 		else if (scumm_stricmp(arg, "--setup") == 0) {
diff --git a/engines/ags/engine/script/cc_instance.cpp b/engines/ags/engine/script/cc_instance.cpp
index f239f12173..3bf2d85569 100644
--- a/engines/ags/engine/script/cc_instance.cpp
+++ b/engines/ags/engine/script/cc_instance.cpp
@@ -301,7 +301,7 @@ int ccInstance::CallScriptFunction(const char *funcname, int32_t numargs, const
 	int32_t startat = -1;
 	int k;
 	char mangledName[200];
-	sprintf(mangledName, "%s$", funcname);
+	snprintf(mangledName, 200, "%s$", funcname);
 
 	for (k = 0; k < instanceof->numexports; k++) {
 		char *thisExportName = instanceof->exports[k];
@@ -1239,7 +1239,7 @@ void ccInstance::GetScriptPosition(ScriptPosition &script_pos) {
 RuntimeScriptValue ccInstance::GetSymbolAddress(const char *symname) {
 	int k;
 	char altName[200];
-	sprintf(altName, "%s$", symname);
+	snprintf(altName, 200, "%s$", symname);
 	RuntimeScriptValue rval_null;
 
 	for (k = 0; k < instanceof->numexports; k++) {


Commit: 3d84af6aeba642c8c2947f5d937b70399a5739ea
    https://github.com/scummvm/scummvm/commit/3d84af6aeba642c8c2947f5d937b70399a5739ea
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix more unreachable code warnings

Changed paths:
    engines/ags/ags.cpp
    engines/ags/engine/ac/global_game.cpp


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index 1a0805f45d..439e42e5a9 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -406,8 +406,6 @@ Common::Error AGSEngine::run() {
 		return initialize_engine_with_exception_handling(initialize_engine, startup_opts);
 	}
 #endif
-
-	return Common::kNoError;
 }
 
 SaveStateList AGSEngine::listSaves() const {
diff --git a/engines/ags/engine/ac/global_game.cpp b/engines/ags/engine/ac/global_game.cpp
index 1148456630..9235c76b69 100644
--- a/engines/ags/engine/ac/global_game.cpp
+++ b/engines/ags/engine/ac/global_game.cpp
@@ -603,329 +603,229 @@ void GetLocationName(int xxx, int yyy, char *tempo) {
 }
 
 int IsKeyPressed(int keycode) {
-#ifdef ALLEGRO_KEYBOARD_HANDLER
 	if (keyboard_needs_poll())
 		poll_keyboard();
 
 	switch (keycode) {
 	case eAGSKeyCodeBackspace:
 		return ags_iskeypressed(__allegro_KEY_BACKSPACE);
-		break;
 	case eAGSKeyCodeTab:
 		return ags_iskeypressed(__allegro_KEY_TAB);
-		break;
 	case eAGSKeyCodeReturn:
 		return ags_iskeypressed(__allegro_KEY_ENTER) || ags_iskeypressed(__allegro_KEY_ENTER_PAD);
-		break;
 	case eAGSKeyCodeEscape:
 		return ags_iskeypressed(__allegro_KEY_ESC);
-		break;
 	case eAGSKeyCodeSpace:
 		return ags_iskeypressed(__allegro_KEY_SPACE);
-		break;
 	case eAGSKeyCodeSingleQuote:
 		return ags_iskeypressed(__allegro_KEY_QUOTE);
-		break;
 	case eAGSKeyCodeComma:
 		return ags_iskeypressed(__allegro_KEY_COMMA);
-		break;
 	case eAGSKeyCodePeriod:
 		return ags_iskeypressed(__allegro_KEY_STOP);
-		break;
 	case eAGSKeyCodeForwardSlash:
 		return ags_iskeypressed(__allegro_KEY_SLASH) || ags_iskeypressed(__allegro_KEY_SLASH_PAD);
-		break;
 	case eAGSKeyCodeBackSlash:
 		return ags_iskeypressed(__allegro_KEY_BACKSLASH) || ags_iskeypressed(__allegro_KEY_BACKSLASH2);
-		break;
 	case eAGSKeyCodeSemiColon:
 		return ags_iskeypressed(__allegro_KEY_SEMICOLON);
-		break;
 	case eAGSKeyCodeEquals:
 		return ags_iskeypressed(__allegro_KEY_EQUALS) || ags_iskeypressed(__allegro_KEY_EQUALS_PAD);
-		break;
 	case eAGSKeyCodeOpenBracket:
 		return ags_iskeypressed(__allegro_KEY_OPENBRACE);
-		break;
 	case eAGSKeyCodeCloseBracket:
 		return ags_iskeypressed(__allegro_KEY_CLOSEBRACE);
-		break;
-		// NOTE: we're treating EQUALS like PLUS, even though it is only available shifted.
+	// NOTE: we're treating EQUALS like PLUS, even though it is only available shifted.
 	case eAGSKeyCodePlus:
 		return ags_iskeypressed(__allegro_KEY_EQUALS) || ags_iskeypressed(__allegro_KEY_PLUS_PAD);
-		break;
 	case eAGSKeyCodeHyphen:
 		return ags_iskeypressed(__allegro_KEY_MINUS) || ags_iskeypressed(__allegro_KEY_MINUS_PAD);
-		break;
 
-		// non-shifted versions of keys
+	// non-shifted versions of keys
 	case eAGSKeyCodeColon:
 		return ags_iskeypressed(__allegro_KEY_COLON) || ags_iskeypressed(__allegro_KEY_COLON2);
-		break;
 	case eAGSKeyCodeAsterisk:
 		return ags_iskeypressed(__allegro_KEY_ASTERISK);
-		break;
 	case eAGSKeyCodeAt:
 		return ags_iskeypressed(__allegro_KEY_AT);
-		break;
 
 	case eAGSKeyCode0:
 		return ags_iskeypressed(__allegro_KEY_0);
-		break;
 	case eAGSKeyCode1:
 		return ags_iskeypressed(__allegro_KEY_1);
-		break;
 	case eAGSKeyCode2:
 		return ags_iskeypressed(__allegro_KEY_2);
-		break;
 	case eAGSKeyCode3:
 		return ags_iskeypressed(__allegro_KEY_3);
-		break;
 	case eAGSKeyCode4:
 		return ags_iskeypressed(__allegro_KEY_4);
-		break;
 	case eAGSKeyCode5:
 		return ags_iskeypressed(__allegro_KEY_5);
-		break;
 	case eAGSKeyCode6:
 		return ags_iskeypressed(__allegro_KEY_6);
-		break;
 	case eAGSKeyCode7:
 		return ags_iskeypressed(__allegro_KEY_7);
-		break;
 	case eAGSKeyCode8:
 		return ags_iskeypressed(__allegro_KEY_8);
-		break;
 	case eAGSKeyCode9:
 		return ags_iskeypressed(__allegro_KEY_9);
-		break;
 
 	case eAGSKeyCodeA:
 		return ags_iskeypressed(platform->ConvertKeycodeToScanCode('A'));
-		break;
 	case eAGSKeyCodeB:
 		return ags_iskeypressed(platform->ConvertKeycodeToScanCode('B'));
-		break;
 	case eAGSKeyCodeC:
 		return ags_iskeypressed(platform->ConvertKeycodeToScanCode('C'));
-		break;
 	case eAGSKeyCodeD:
 		return ags_iskeypressed(platform->ConvertKeycodeToScanCode('D'));
-		break;
 	case eAGSKeyCodeE:
 		return ags_iskeypressed(platform->ConvertKeycodeToScanCode('E'));
-		break;
 	case eAGSKeyCodeF:
 		return ags_iskeypressed(platform->ConvertKeycodeToScanCode('F'));
-		break;
 	case eAGSKeyCodeG:
 		return ags_iskeypressed(platform->ConvertKeycodeToScanCode('G'));
-		break;
 	case eAGSKeyCodeH:
 		return ags_iskeypressed(platform->ConvertKeycodeToScanCode('H'));
-		break;
 	case eAGSKeyCodeI:
 		return ags_iskeypressed(platform->ConvertKeycodeToScanCode('I'));
-		break;
 	case eAGSKeyCodeJ:
 		return ags_iskeypressed(platform->ConvertKeycodeToScanCode('J'));
-		break;
 	case eAGSKeyCodeK:
 		return ags_iskeypressed(platform->ConvertKeycodeToScanCode('K'));
-		break;
 	case eAGSKeyCodeL:
 		return ags_iskeypressed(platform->ConvertKeycodeToScanCode('L'));
-		break;
 	case eAGSKeyCodeM:
 		return ags_iskeypressed(platform->ConvertKeycodeToScanCode('M'));
-		break;
 	case eAGSKeyCodeN:
 		return ags_iskeypressed(platform->ConvertKeycodeToScanCode('N'));
-		break;
 	case eAGSKeyCodeO:
 		return ags_iskeypressed(platform->ConvertKeycodeToScanCode('O'));
-		break;
 	case eAGSKeyCodeP:
 		return ags_iskeypressed(platform->ConvertKeycodeToScanCode('P'));
-		break;
 	case eAGSKeyCodeQ:
 		return ags_iskeypressed(platform->ConvertKeycodeToScanCode('Q'));
-		break;
 	case eAGSKeyCodeR:
 		return ags_iskeypressed(platform->ConvertKeycodeToScanCode('R'));
-		break;
 	case eAGSKeyCodeS:
 		return ags_iskeypressed(platform->ConvertKeycodeToScanCode('S'));
-		break;
 	case eAGSKeyCodeT:
 		return ags_iskeypressed(platform->ConvertKeycodeToScanCode('T'));
-		break;
 	case eAGSKeyCodeU:
 		return ags_iskeypressed(platform->ConvertKeycodeToScanCode('U'));
-		break;
 	case eAGSKeyCodeV:
 		return ags_iskeypressed(platform->ConvertKeycodeToScanCode('V'));
-		break;
 	case eAGSKeyCodeW:
 		return ags_iskeypressed(platform->ConvertKeycodeToScanCode('W'));
-		break;
 	case eAGSKeyCodeX:
 		return ags_iskeypressed(platform->ConvertKeycodeToScanCode('X'));
-		break;
 	case eAGSKeyCodeY:
 		return ags_iskeypressed(platform->ConvertKeycodeToScanCode('Y'));
-		break;
 	case eAGSKeyCodeZ:
 		return ags_iskeypressed(platform->ConvertKeycodeToScanCode('Z'));
-		break;
 
 	case eAGSKeyCodeF1:
 		return ags_iskeypressed(__allegro_KEY_F1);
-		break;
 	case eAGSKeyCodeF2:
 		return ags_iskeypressed(__allegro_KEY_F2);
-		break;
 	case eAGSKeyCodeF3:
 		return ags_iskeypressed(__allegro_KEY_F3);
-		break;
 	case eAGSKeyCodeF4:
 		return ags_iskeypressed(__allegro_KEY_F4);
-		break;
 	case eAGSKeyCodeF5:
 		return ags_iskeypressed(__allegro_KEY_F5);
-		break;
 	case eAGSKeyCodeF6:
 		return ags_iskeypressed(__allegro_KEY_F6);
-		break;
 	case eAGSKeyCodeF7:
 		return ags_iskeypressed(__allegro_KEY_F7);
-		break;
 	case eAGSKeyCodeF8:
 		return ags_iskeypressed(__allegro_KEY_F8);
-		break;
 	case eAGSKeyCodeF9:
 		return ags_iskeypressed(__allegro_KEY_F9);
-		break;
 	case eAGSKeyCodeF10:
 		return ags_iskeypressed(__allegro_KEY_F10);
-		break;
 	case eAGSKeyCodeF11:
 		return ags_iskeypressed(__allegro_KEY_F11);
-		break;
 	case eAGSKeyCodeF12:
 		return ags_iskeypressed(__allegro_KEY_F12);
-		break;
 
 	case eAGSKeyCodeHome:
 		return ags_iskeypressed(__allegro_KEY_HOME) || ags_iskeypressed(__allegro_KEY_7_PAD);
-		break;
 	case eAGSKeyCodeUpArrow:
 		return ags_iskeypressed(__allegro_KEY_UP) || ags_iskeypressed(__allegro_KEY_8_PAD);
-		break;
 	case eAGSKeyCodePageUp:
 		return ags_iskeypressed(__allegro_KEY_PGUP) || ags_iskeypressed(__allegro_KEY_9_PAD);
-		break;
 	case eAGSKeyCodeLeftArrow:
 		return ags_iskeypressed(__allegro_KEY_LEFT) || ags_iskeypressed(__allegro_KEY_4_PAD);
-		break;
 	case eAGSKeyCodeNumPad5:
 		return ags_iskeypressed(__allegro_KEY_5_PAD);
-		break;
 	case eAGSKeyCodeRightArrow:
 		return ags_iskeypressed(__allegro_KEY_RIGHT) || ags_iskeypressed(__allegro_KEY_6_PAD);
-		break;
 	case eAGSKeyCodeEnd:
 		return ags_iskeypressed(__allegro_KEY_END) || ags_iskeypressed(__allegro_KEY_1_PAD);
-		break;
 	case eAGSKeyCodeDownArrow:
 		return ags_iskeypressed(__allegro_KEY_DOWN) || ags_iskeypressed(__allegro_KEY_2_PAD);
-		break;
 	case eAGSKeyCodePageDown:
 		return ags_iskeypressed(__allegro_KEY_PGDN) || ags_iskeypressed(__allegro_KEY_3_PAD);
-		break;
 	case eAGSKeyCodeInsert:
 		return ags_iskeypressed(__allegro_KEY_INSERT) || ags_iskeypressed(__allegro_KEY_0_PAD);
-		break;
 	case eAGSKeyCodeDelete:
 		return ags_iskeypressed(__allegro_KEY_DEL) || ags_iskeypressed(__allegro_KEY_DEL_PAD);
-		break;
 
-		// These keys are not defined in the eAGSKey enum but are in the manual
-		// https://adventuregamestudio.github.io/ags-manual/ASCIIcodes.html
+	// These keys are not defined in the eAGSKey enum but are in the manual
+	// https://adventuregamestudio.github.io/ags-manual/ASCIIcodes.html
 
 	case 403:
 		return ags_iskeypressed(__allegro_KEY_LSHIFT);
-		break;
 	case 404:
 		return ags_iskeypressed(__allegro_KEY_RSHIFT);
-		break;
 	case 405:
 		return ags_iskeypressed(__allegro_KEY_LCONTROL);
-		break;
 	case 406:
 		return ags_iskeypressed(__allegro_KEY_RCONTROL);
-		break;
 	case 407:
 		return ags_iskeypressed(__allegro_KEY_ALT);
-		break;
 
-		// (noted here for interest)
-		// The following are the AGS_EXT_KEY_SHIFT, derived from applying arithmetic to the original keycodes.
-		// These do not have a corresponding ags key enum, do not appear in the manual and may not be accessible because of OS contraints.
+	// (noted here for interest)
+	// The following are the AGS_EXT_KEY_SHIFT, derived from applying arithmetic to the original keycodes.
+	// These do not have a corresponding ags key enum, do not appear in the manual and may not be accessible because of OS contraints.
 
 	case 392:
 		return ags_iskeypressed(__allegro_KEY_PRTSCR);
-		break;
 	case 393:
 		return ags_iskeypressed(__allegro_KEY_PAUSE);
-		break;
 	case 394:
 		return ags_iskeypressed(__allegro_KEY_ABNT_C1);
-		break;  // The ABNT_C1 (Brazilian) key
 	case 395:
 		return ags_iskeypressed(__allegro_KEY_YEN);
-		break;
 	case 396:
 		return ags_iskeypressed(__allegro_KEY_KANA);
-		break;
 	case 397:
 		return ags_iskeypressed(__allegro_KEY_CONVERT);
-		break;
 	case 398:
 		return ags_iskeypressed(__allegro_KEY_NOCONVERT);
-		break;
 	case 400:
 		return ags_iskeypressed(__allegro_KEY_CIRCUMFLEX);
-		break;
 	case 402:
 		return ags_iskeypressed(__allegro_KEY_KANJI);
-		break;
 	case 420:
 		return ags_iskeypressed(__allegro_KEY_ALTGR);
-		break;
 	case 421:
 		return ags_iskeypressed(__allegro_KEY_LWIN);
-		break;
 	case 422:
 		return ags_iskeypressed(__allegro_KEY_RWIN);
-		break;
 	case 423:
 		return ags_iskeypressed(__allegro_KEY_MENU);
-		break;
 	case 424:
 		return ags_iskeypressed(__allegro_KEY_SCRLOCK);
-		break;
 	case 425:
 		return ags_iskeypressed(__allegro_KEY_NUMLOCK);
-		break;
 	case 426:
 		return ags_iskeypressed(__allegro_KEY_CAPSLOCK);
-		break;
 
-		// Allegro4 keys that were never supported:
-		// __allegro_KEY_COMMAND
-		// __allegro_KEY_TILDE
-		// __allegro_KEY_BACKQUOTE
+	// Allegro4 keys that were never supported:
+	// __allegro_KEY_COMMAND
+	// __allegro_KEY_TILDE
+	// __allegro_KEY_BACKQUOTE
 
 	default:
 		// Remaining Allegro4 keycodes are offset by AGS_EXT_KEY_SHIFT
@@ -937,10 +837,6 @@ int IsKeyPressed(int keycode) {
 		debug_script_log("IsKeyPressed: unsupported keycode %d", keycode);
 		return 0;
 	}
-#else
-	// old allegro version
-	quit("allegro keyboard handler not in use??");
-#endif
 }
 
 int SaveScreenShot(const char *namm) {


Commit: cf9bbb2bb21554278e9460f87c69f76d5f3b573a
    https://github.com/scummvm/scummvm/commit/cf9bbb2bb21554278e9460f87c69f76d5f3b573a
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Beginnings of new Globals class

Changed paths:
  A engines/ags/engine/globals.cpp
  A engines/ags/engine/globals.h
    engines/ags/ags.cpp
    engines/ags/ags.h
    engines/ags/engine/ac/game.cpp
    engines/ags/engine/debugging/debug.cpp
    engines/ags/engine/main/engine.cpp
    engines/ags/engine/main/game_run.cpp
    engines/ags/engine/main/game_start.cpp
    engines/ags/engine/main/quit.cpp
    engines/ags/engine/media/audio/audio.cpp
    engines/ags/engine/script/cc_instance.cpp
    engines/ags/events.cpp
    engines/ags/module.mk
    engines/ags/shared/ac/common.cpp


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index 439e42e5a9..f0f01d6fd3 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -37,6 +37,7 @@
 #include "ags/lib/std/set.h"
 #include "ags/shared/ac/common.h"
 #include "ags/engine/ac/game.h"
+#include "ags/engine/globals.h"
 #include "ags/engine/ac/gamesetup.h"
 #include "ags/engine/ac/gamestate.h"
 #include "ags/shared/core/def_version.h"
@@ -328,13 +329,15 @@ AGSEngine *g_vm;
 
 AGSEngine::AGSEngine(OSystem *syst, const AGSGameDescription *gameDesc) : Engine(syst),
 		_gameDescription(gameDesc), _randomSource("AGS"), _events(nullptr), _music(nullptr),
-		_rawScreen(nullptr), _screen(nullptr), _gfxDriver(nullptr) {
+		_rawScreen(nullptr), _screen(nullptr), _gfxDriver(nullptr),
+		_globals(nullptr) {
 	g_vm = this;
 	DebugMan.addDebugChannel(kDebugPath, "Path", "Pathfinding debug level");
 	DebugMan.addDebugChannel(kDebugGraphics, "Graphics", "Graphics debug level");
 
 	_events = new EventsManager();
 	_music = new Music(_mixer);
+	_globals = new ::AGS3::Globals();
 }
 
 AGSEngine::~AGSEngine() {
@@ -342,6 +345,7 @@ AGSEngine::~AGSEngine() {
 	delete _rawScreen;
 	delete _events;
 	delete _music;
+	delete _globals;
 }
 
 uint32 AGSEngine::getFeatures() const {
diff --git a/engines/ags/ags.h b/engines/ags/ags.h
index 982bf66d54..2c6b3b1ffd 100644
--- a/engines/ags/ags.h
+++ b/engines/ags/ags.h
@@ -37,6 +37,10 @@
 #include "ags/lib/allegro/system.h"
 #include "ags/engine/util/mutex_std.h"
 
+namespace AGS3 {
+class Globals;
+}
+
 namespace AGS {
 
 #define SCREEN_WIDTH 320
@@ -64,6 +68,7 @@ public:
 	::AGS3::AGS::Engine::Mutex _sMutex;
 	::AGS3::AGS::Engine::Mutex _soundCacheMutex;
 	::AGS3::AGS::Engine::Mutex _mp3Mutex;
+	::AGS3::Globals *_globals;
 protected:
 	// Engine APIs
 	virtual Common::Error run();
diff --git a/engines/ags/engine/ac/game.cpp b/engines/ags/engine/ac/game.cpp
index 26f275be26..9b61c47468 100644
--- a/engines/ags/engine/ac/game.cpp
+++ b/engines/ags/engine/ac/game.cpp
@@ -158,7 +158,6 @@ RoomStruct thisroom;
 
 volatile int switching_away_from_game = 0;
 volatile bool switched_away = false;
-volatile char want_exit = 0, abort_engine = 0;
 GameDataVersion loaded_game_file_version = kGameVersion_Undefined;
 int frames_per_second = 40;
 int displayed_room = -10, starting_room = -1;
diff --git a/engines/ags/engine/debugging/debug.cpp b/engines/ags/engine/debugging/debug.cpp
index 9fc93fbf7e..c2454a27fd 100644
--- a/engines/ags/engine/debugging/debug.cpp
+++ b/engines/ags/engine/debugging/debug.cpp
@@ -44,6 +44,7 @@
 #include "ags/shared/script/cc_error.h"
 #include "ags/shared/util/string_utils.h"
 #include "ags/shared/util/textstreamwriter.h"
+#include "ags/engine/globals.h"
 #include "ags/events.h"
 
 #if AGS_PLATFORM_OS_WINDOWS
@@ -59,7 +60,6 @@ extern char check_dynamic_sprites_at_exit;
 extern int displayed_room;
 extern RoomStruct thisroom;
 extern char pexbuf[STD_BUFFER_SIZE];
-extern volatile char want_exit, abort_engine;
 extern GameSetupStruct game;
 
 
@@ -471,8 +471,8 @@ int check_for_messages_from_editor() {
 			game_paused_in_debugger = 0;
 			break_on_next_script_step = 1;
 		} else if (strncmp(msgPtr, "EXIT", 4) == 0) {
-			want_exit = 1;
-			abort_engine = 1;
+			_G(want_exit) = 1;
+			_G(abort_engine) = 1;
 			check_dynamic_sprites_at_exit = 0;
 		}
 
@@ -488,7 +488,7 @@ int check_for_messages_from_editor() {
 
 bool send_exception_to_editor(const char *qmsg) {
 #if AGS_PLATFORM_OS_WINDOWS
-	want_exit = 0;
+	_G(want_exit) = 0;
 	// allow the editor to break with the error message
 	if (editor_window_handle != NULL)
 		SetForegroundWindow(editor_window_handle);
@@ -496,7 +496,7 @@ bool send_exception_to_editor(const char *qmsg) {
 	if (!send_message_to_editor("ERROR", qmsg))
 		return false;
 
-	while ((check_for_messages_from_editor() == 0) && (want_exit == 0)) {
+	while ((check_for_messages_from_editor() == 0) && (_G(want_exit) == 0)) {
 		update_polled_mp3();
 		platform->Delay(10);
 	}
diff --git a/engines/ags/engine/globals.cpp b/engines/ags/engine/globals.cpp
new file mode 100644
index 0000000000..af4b56a69d
--- /dev/null
+++ b/engines/ags/engine/globals.cpp
@@ -0,0 +1,37 @@
+/* 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 "ags/engine/globals.h"
+
+namespace AGS3 {
+
+Globals *g_globals;
+
+Globals::Globals() : _want_exit(false), _abort_engine(false) {
+	g_globals = this;
+}
+
+Globals::~Globals() {
+	g_globals = nullptr;
+}
+
+} // namespace AGS3
diff --git a/engines/ags/engine/globals.h b/engines/ags/engine/globals.h
new file mode 100644
index 0000000000..6de237a01c
--- /dev/null
+++ b/engines/ags/engine/globals.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 AGS_ENGINE_GLOBALS_H
+#define AGS_ENGINE_GLOBALS_H
+
+namespace AGS3 {
+
+class Globals {
+public:
+	bool _want_exit;
+	bool _abort_engine;
+
+public:
+	Globals();
+	~Globals();
+};
+
+extern Globals *g_globals;
+
+#define _G(FIELD) (::AGS3::g_globals->_##FIELD)
+
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/engine/main/engine.cpp b/engines/ags/engine/main/engine.cpp
index 7d128c19a1..41192bc72f 100644
--- a/engines/ags/engine/main/engine.cpp
+++ b/engines/ags/engine/main/engine.cpp
@@ -89,7 +89,6 @@ using namespace AGS::Engine;
 
 extern char check_dynamic_sprites_at_exit;
 extern int our_eip;
-extern volatile char want_exit, abort_engine;
 extern bool justRunSetup;
 extern GameSetup usetup;
 extern GameSetupStruct game;
diff --git a/engines/ags/engine/main/game_run.cpp b/engines/ags/engine/main/game_run.cpp
index 4870b1c275..173e3dd998 100644
--- a/engines/ags/engine/main/game_run.cpp
+++ b/engines/ags/engine/main/game_run.cpp
@@ -66,6 +66,7 @@
 #include "ags/engine/ac/timer.h"
 #include "ags/engine/ac/keycode.h"
 #include "ags/lib/allegro/keyboard.h"
+#include "ags/engine/globals.h"
 #include "ags/events.h"
 
 namespace AGS3 {
@@ -77,7 +78,6 @@ extern int numAnimButs;
 extern int mouse_on_iface;   // mouse cursor is over this interface
 extern int ifacepopped;
 extern int is_text_overlay;
-extern volatile char want_exit, abort_engine;
 extern int proper_exit, our_eip;
 extern int displayed_room, starting_room, in_new_room, new_room_was;
 extern GameSetupStruct game;
@@ -124,7 +124,7 @@ unsigned int loopcounter = 0;
 static unsigned int lastcounter = 0;
 
 static void ProperExit() {
-	want_exit = 0;
+	_G(want_exit) = 0;
 	proper_exit = 1;
 	quit("||exit!");
 }
@@ -737,7 +737,7 @@ void UpdateGameOnce(bool checkControls, IDriverDependantBitmap *extraBitmap, int
 
 	numEventsAtStartOfFunction = numevents;
 
-	if (want_exit) {
+	if (_G(want_exit)) {
 		ProperExit();
 	}
 
@@ -944,7 +944,7 @@ static void GameLoopUntilEvent(int untilwhat, const void *daaa) {
 	auto cached_user_disabled_for = user_disabled_for;
 
 	SetupLoopParameters(untilwhat, daaa);
-	while (GameTick() == 0 && !abort_engine) {
+	while (GameTick() == 0 && !_G(abort_engine)) {
 	}
 
 	our_eip = 78;
@@ -992,7 +992,7 @@ void RunGameUntilAborted() {
 	// skip ticks to account for time spent starting game.
 	skipMissedTicks();
 
-	while (!abort_engine) {
+	while (!_G(abort_engine)) {
 		GameTick();
 
 		if (load_new_game) {
@@ -1003,8 +1003,8 @@ void RunGameUntilAborted() {
 }
 
 void update_polled_stuff_if_runtime() {
-	if (want_exit) {
-		want_exit = 0;
+	if (_G(want_exit)) {
+		_G(want_exit) = 0;
 		quit("||exit!");
 	}
 
diff --git a/engines/ags/engine/main/game_start.cpp b/engines/ags/engine/main/game_start.cpp
index 681ee8f858..47fe112aac 100644
--- a/engines/ags/engine/main/game_start.cpp
+++ b/engines/ags/engine/main/game_start.cpp
@@ -51,7 +51,6 @@ using namespace AGS::Shared;
 using namespace AGS::Engine;
 
 extern int our_eip, displayed_room;
-extern volatile char want_exit, abort_engine;
 extern GameSetupStruct game;
 extern GameState play;
 extern const char *loadSaveGameOnStartup;
diff --git a/engines/ags/engine/main/quit.cpp b/engines/ags/engine/main/quit.cpp
index f8fa75c215..45a1edcc86 100644
--- a/engines/ags/engine/main/quit.cpp
+++ b/engines/ags/engine/main/quit.cpp
@@ -46,6 +46,7 @@
 #include "ags/shared/core/assetmanager.h"
 #include "ags/engine/plugin/plugin_engine.h"
 #include "ags/engine/media/audio/audio_system.h"
+#include "ags/engine/globals.h"
 #include "ags/ags.h"
 
 namespace AGS3 {
@@ -67,7 +68,6 @@ extern IAGSEditorDebugger *editor_debugger;
 extern int need_to_stop_cd;
 extern int use_cdplayer;
 extern IGraphicsDriver *gfxDriver;
-extern volatile char abort_engine;
 
 bool handledErrorInEditor;
 
@@ -233,7 +233,7 @@ char quit_message[256] = "\0";
 // "!|" is a special code used to mean that the player has aborted (Alt+X)
 void quit(const char *quitmsg) {
 	strncpy(quit_message, quitmsg, 256);
-	abort_engine = true;
+	_G(abort_engine) = true;
 }
 
 void quit_free() {
diff --git a/engines/ags/engine/media/audio/audio.cpp b/engines/ags/engine/media/audio/audio.cpp
index 21e7aef891..90b4a96829 100644
--- a/engines/ags/engine/media/audio/audio.cpp
+++ b/engines/ags/engine/media/audio/audio.cpp
@@ -844,8 +844,6 @@ void update_volume_drop_if_voiceover() {
 	apply_volume_drop_modifier(play.speech_has_voice);
 }
 
-extern volatile char want_exit;
-
 void update_mp3_thread() {
 	if (switching_away_from_game) {
 		return;
diff --git a/engines/ags/engine/script/cc_instance.cpp b/engines/ags/engine/script/cc_instance.cpp
index 3bf2d85569..53ea6aa4f7 100644
--- a/engines/ags/engine/script/cc_instance.cpp
+++ b/engines/ags/engine/script/cc_instance.cpp
@@ -20,8 +20,6 @@
  *
  */
 
-//include <cstdio>
-//include <string.h>
 #include "ags/shared/ac/common.h"
 #include "ags/engine/ac/dynobj/cc_dynamicarray.h"
 #include "ags/engine/ac/dynobj/managedobjectpool.h"
@@ -45,6 +43,7 @@
 #include "ags/engine/ac/dynobj/cc_dynamicobject_addr_and_manager.h"
 #include "ags/shared/util/memory.h"
 #include "ags/shared/util/string_utils.h" // linux strnicmp definition
+#include "ags/engine/globals.h"
 
 namespace AGS3 {
 
@@ -58,7 +57,6 @@ extern int maxWhileLoops;
 extern new_line_hook_type new_line_hook;
 
 extern ScriptString myScriptStringImpl;
-extern volatile char abort_engine;
 
 enum ScriptOpArgIsReg {
 	kScOpNoArgIsReg     = 0,
@@ -435,7 +433,7 @@ int ccInstance::Run(int32_t curpc) {
 	FunctionCallStack func_callstack;
 
 	while (1) {
-		if (abort_engine)
+		if (_G(abort_engine))
 			return -1;
 
 		/*
diff --git a/engines/ags/events.cpp b/engines/ags/events.cpp
index 8a6c7a2a61..3bff16c296 100644
--- a/engines/ags/events.cpp
+++ b/engines/ags/events.cpp
@@ -22,9 +22,9 @@
 
 #include "ags/events.h"
 #include "common/system.h"
+#include "ags/engine/globals.h"
 
 namespace AGS3 {
-extern volatile char want_exit, abort_engine;
 extern char check_dynamic_sprites_at_exit;
 }
 
@@ -46,8 +46,8 @@ void EventsManager::pollEvents() {
 
 	while (g_system->getEventManager()->pollEvent(e)) {
 		if (e.type == Common::EVENT_QUIT) {
-			::AGS3::want_exit = 1;
-			::AGS3::abort_engine = 1;
+			_G(want_exit) = true;
+			_G(abort_engine) = true;
 			::AGS3::check_dynamic_sprites_at_exit = 0;
 
 		} else if (e.type == Common::EVENT_KEYDOWN) {
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 2520fbb6f1..e31bfb8938 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -102,6 +102,7 @@ MODULE_OBJS = \
 	shared/util/textstreamwriter.o \
 	shared/util/version.o \
 	shared/util/wgt2allg.o \
+	engine/globals.o \
 	engine/ac/dynobj/cc_agsdynamicobject.o \
 	engine/ac/dynobj/cc_audiochannel.o \
 	engine/ac/dynobj/cc_audioclip.o \
diff --git a/engines/ags/shared/ac/common.cpp b/engines/ags/shared/ac/common.cpp
index 57caf4820e..310fe52028 100644
--- a/engines/ags/shared/ac/common.cpp
+++ b/engines/ags/shared/ac/common.cpp
@@ -22,6 +22,7 @@
 
 #include "ags/shared/ac/common.h"
 #include "ags/shared/util/string.h"
+#include "ags/engine/globals.h"
 #include "ags/ags.h"
 
 namespace AGS3 {
@@ -29,7 +30,6 @@ namespace AGS3 {
 using namespace AGS::Shared;
 
 const char *game_file_sig = "Adventure Creator Game File v2";
-extern volatile char abort_engine;
 
 void quitprintf(const char *fmt, ...) {
 	va_list ap;
@@ -37,7 +37,7 @@ void quitprintf(const char *fmt, ...) {
 	String text = String::FromFormatV(fmt, ap);
 	va_end(ap);
 
-	if (!abort_engine)
+	if (!_G(abort_engine))
 		::AGS::g_vm->GUIError(text);
 	quit(text);
 }


Commit: daaa9ab6c66f917f6dd883b3221c41517a21b991
    https://github.com/scummvm/scummvm/commit/daaa9ab6c66f917f6dd883b3221c41517a21b991
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Mark engine with 16bit requirement

Changed paths:
    engines/ags/configure.engine


diff --git a/engines/ags/configure.engine b/engines/ags/configure.engine
index 0fb88d9de1..18e126e167 100644
--- a/engines/ags/configure.engine
+++ b/engines/ags/configure.engine
@@ -1,4 +1,4 @@
 # This file is included from the main "configure" script
 # add_engine [name] [desc] [build-by-default] [subengines] [base games] [deps]
-add_engine ags "Adventure Game Studio" no "ags_tests" "" "cxx11"
+add_engine ags "Adventure Game Studio" no "ags_tests" "" "cxx11 16bit"
 add_engine ags_tests "AGS Tests" no "" "" ""


Commit: e2469a8cfa0e2f9103d4ce2f547ca1b738823da3
    https://github.com/scummvm/scummvm/commit/e2469a8cfa0e2f9103d4ce2f547ca1b738823da3
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Move globals from ags.cpp to Globals

Changed paths:
  R engines/ags/engine/main/main.cpp
    engines/ags/ags.cpp
    engines/ags/engine/ac/game.cpp
    engines/ags/engine/ac/global_debug.cpp
    engines/ags/engine/ac/global_game.cpp
    engines/ags/engine/ac/room.cpp
    engines/ags/engine/ac/system.cpp
    engines/ags/engine/game/savegame.cpp
    engines/ags/engine/gfx/gfx_util.cpp
    engines/ags/engine/globals.cpp
    engines/ags/engine/globals.h
    engines/ags/engine/main/config.cpp
    engines/ags/engine/main/engine.cpp
    engines/ags/engine/main/game_start.cpp
    engines/ags/engine/main/main.h
    engines/ags/engine/main/quit.cpp
    engines/ags/engine/media/audio/soundcache.cpp
    engines/ags/engine/media/audio/soundcache.h
    engines/ags/engine/util/library_posix.h
    engines/ags/music.cpp


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index f0f01d6fd3..aca6d6e165 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -69,12 +69,6 @@ using namespace Engine;
 
 extern HSaveError load_game(const String &path, int slotNumber, bool &data_overwritten);
 
-String appDirectory; // Needed for library loading
-String cmdGameDataPath;
-
-const char **global_argv = nullptr;
-int    global_argc = 0;
-
 extern GameSetup usetup;
 extern GameState play;
 extern int our_eip;
@@ -84,38 +78,6 @@ extern int editor_debugging_enabled;
 extern int editor_debugging_initialized;
 extern char editor_debugger_instance_token[100];
 
-
-// Startup flags, set from parameters to engine
-int force_window = 0;
-int override_start_room = 0;
-bool justDisplayHelp = false;
-bool justDisplayVersion = false;
-bool justRunSetup = false;
-bool justRegisterGame = false;
-bool justUnRegisterGame = false;
-bool justTellInfo = false;
-std::set<String> tellInfoKeys;
-const char *loadSaveGameOnStartup = nullptr;
-
-#if ! AGS_PLATFORM_DEFINES_PSP_VARS
-int psp_video_framedrop = 1;
-int psp_audio_enabled = 1;
-int psp_midi_enabled = 1;
-int psp_ignore_acsetup_cfg_file = 0;
-int psp_clear_cache_on_room_change = 0;
-
-int psp_midi_preload_patches = 0;
-int psp_audio_cachesize = 10;
-char psp_game_file_name[] = "";
-char psp_translation[] = "default";
-
-int psp_gfx_renderer = 0;
-int psp_gfx_scaling = 1;
-int psp_gfx_smoothing = 0;
-int psp_gfx_super_sampling = 1;
-int psp_gfx_smooth_sprites = 0;
-#endif
-
 // this needs to be updated if the "play" struct changes
 #define SVG_VERSION_BWCOMPAT_MAJOR      3
 #define SVG_VERSION_BWCOMPAT_MINOR      2
@@ -128,13 +90,6 @@ int psp_gfx_smooth_sprites = 0;
 #define SVG_VERSION_FWCOMPAT_RELEASE    1
 #define SVG_VERSION_FWCOMPAT_REVISION   1111
 
-// Current engine version
-Version EngineVersion;
-// Lowest savedgame version, accepted by this engine
-Version SavedgameLowestBackwardCompatVersion;
-// Lowest engine version, which would accept current savedgames
-Version SavedgameLowestForwardCompatVersion;
-
 extern void quit_free();
 
 void main_pre_init() {
@@ -148,23 +103,23 @@ void main_create_platform_driver() {
 }
 
 void main_init(int argc, const char *argv[]) {
-	EngineVersion = Version(ACI_VERSION_STR " " SPECIAL_VERSION);
+	_G(EngineVersion) = Version(ACI_VERSION_STR " " SPECIAL_VERSION);
 
-	SavedgameLowestBackwardCompatVersion = Version(SVG_VERSION_BWCOMPAT_MAJOR, SVG_VERSION_BWCOMPAT_MINOR, SVG_VERSION_BWCOMPAT_RELEASE, SVG_VERSION_BWCOMPAT_REVISION);
-	SavedgameLowestForwardCompatVersion = Version(SVG_VERSION_FWCOMPAT_MAJOR, SVG_VERSION_FWCOMPAT_MINOR, SVG_VERSION_FWCOMPAT_RELEASE, SVG_VERSION_FWCOMPAT_REVISION);
+	_G(SavedgameLowestBackwardCompatVersion) = Version(SVG_VERSION_BWCOMPAT_MAJOR, SVG_VERSION_BWCOMPAT_MINOR, SVG_VERSION_BWCOMPAT_RELEASE, SVG_VERSION_BWCOMPAT_REVISION);
+	_G(SavedgameLowestForwardCompatVersion) = Version(SVG_VERSION_FWCOMPAT_MAJOR, SVG_VERSION_FWCOMPAT_MINOR, SVG_VERSION_FWCOMPAT_RELEASE, SVG_VERSION_FWCOMPAT_REVISION);
 
 	Shared::AssetManager::CreateInstance();
 	main_pre_init();
 	main_create_platform_driver();
 
-	global_argv = argv;
-	global_argc = argc;
+	_G(global_argv) = argv;
+	_G(global_argc) = argc;
 }
 
 String get_engine_string() {
 	return String::FromFormat("Adventure Game Studio v%s Interpreter\n"
 		"Copyright (c) 1999-2011 Chris Jones and " ACI_COPYRIGHT_YEARS " others\n"
-		"ACI version %s\n", EngineVersion.ShortString.GetCStr(), EngineVersion.LongString.GetCStr());
+		"ACI version %s\n", _G(EngineVersion).ShortString.GetCStr(), _G(EngineVersion).LongString.GetCStr());
 }
 
 void main_print_help() {
@@ -179,17 +134,17 @@ static int main_process_cmdline(ConfigTree &cfg, int argc, const char *argv[]) {
 		// Startup options
 		//
 		if (scumm_stricmp(arg, "--help") == 0 || scumm_stricmp(arg, "/?") == 0 || scumm_stricmp(arg, "-?") == 0) {
-			justDisplayHelp = true;
+			_G(justDisplayHelp) = true;
 			return 0;
 		}
 		if (scumm_stricmp(arg, "-v") == 0 || scumm_stricmp(arg, "--version") == 0) {
-			justDisplayVersion = true;
+			_G(justDisplayVersion) = true;
 			return 0;
 		} else if (scumm_stricmp(arg, "-updatereg") == 0)
 			debug_flags |= DBG_REGONLY;
 #if AGS_PLATFORM_DEBUG
 		else if ((scumm_stricmp(arg, "--startr") == 0) && (ee < argc - 1)) {
-			override_start_room = atoi(argv[ee + 1]);
+			_G(override_start_room) = atoi(argv[ee + 1]);
 			ee++;
 		}
 #endif
@@ -199,18 +154,18 @@ static int main_process_cmdline(ConfigTree &cfg, int argc, const char *argv[]) {
 			ee += 2;
 		} else if (scumm_stricmp(arg, "-noexceptionhandler") == 0) usetup.disable_exception_handling = true;
 		else if (scumm_stricmp(arg, "--setup") == 0) {
-			justRunSetup = true;
+			_G(justRunSetup) = true;
 		} else if (scumm_stricmp(arg, "-registergame") == 0) {
-			justRegisterGame = true;
+			_G(justRegisterGame) = true;
 		} else if (scumm_stricmp(arg, "-unregistergame") == 0) {
-			justUnRegisterGame = true;
+			_G(justUnRegisterGame) = true;
 		} else if ((scumm_stricmp(arg, "-loadsavedgame") == 0) && (argc > ee + 1)) {
-			loadSaveGameOnStartup = argv[ee + 1];
+			_G(loadSaveGameOnStartup) = argv[ee + 1];
 			ee++;
 		} else if ((scumm_stricmp(arg, "--enabledebugger") == 0) && (argc > ee + 1)) {
 			strcpy(editor_debugger_instance_token, argv[ee + 1]);
 			editor_debugging_enabled = 1;
-			force_window = 1;
+			_G(force_window) = 1;
 			ee++;
 		} else if (scumm_stricmp(arg, "--runfromide") == 0 && (argc > ee + 3)) {
 			usetup.install_dir = argv[ee + 1];
@@ -226,17 +181,17 @@ static int main_process_cmdline(ConfigTree &cfg, int argc, const char *argv[]) {
 			ee += 2;
 		} else if (scumm_strnicmp(arg, "--tell", 6) == 0) {
 			if (arg[6] == 0)
-				tellInfoKeys.insert(String("all"));
+				_G(tellInfoKeys).insert(String("all"));
 			else if (arg[6] == '-' && arg[7] != 0)
-				tellInfoKeys.insert(String(arg + 7));
+				_G(tellInfoKeys).insert(String(arg + 7));
 		}
 		//
 		// Config overrides
 		//
 		else if (scumm_stricmp(arg, "-windowed") == 0 || scumm_stricmp(arg, "--windowed") == 0)
-			force_window = 1;
+			_G(force_window) = 1;
 		else if (scumm_stricmp(arg, "-fullscreen") == 0 || scumm_stricmp(arg, "--fullscreen") == 0)
-			force_window = 2;
+			_G(force_window) = 2;
 		else if ((scumm_stricmp(arg, "-gfxdriver") == 0 || scumm_stricmp(arg, "--gfxdriver") == 0) && (argc > ee + 1)) {
 			INIwritestring(cfg, "graphics", "driver", argv[++ee]);
 		} else if ((scumm_stricmp(arg, "-gfxfilter") == 0 || scumm_stricmp(arg, "--gfxfilter") == 0) && (argc > ee + 1)) {
@@ -267,25 +222,25 @@ static int main_process_cmdline(ConfigTree &cfg, int argc, const char *argv[]) {
 	}
 
 	if (datafile_argv > 0) {
-		cmdGameDataPath = argv[datafile_argv];
+		_G(cmdGameDataPath) = argv[datafile_argv];
 	} else {
 		// assign standard path for mobile/consoles (defined in their own platform implementation)
-		cmdGameDataPath = psp_game_file_name;
+		_G(cmdGameDataPath) = _G(psp_game_file_name);
 	}
 
-	if (!tellInfoKeys.empty())
-		justTellInfo = true;
+	if (!_G(tellInfoKeys).empty())
+		_G(justTellInfo) = true;
 
 	return 0;
 }
 
 void main_set_gamedir(int argc, const char *argv[]) {
-	appDirectory = Path::GetDirectoryPath("./");
+	_G(appDirectory) = Path::GetDirectoryPath("./");
 #ifdef DEPRECATED
-	if ((loadSaveGameOnStartup != nullptr) && (argv[0] != nullptr)) {
+	if ((_G(loadSaveGameOnStartup) != nullptr) && (argv[0] != nullptr)) {
 		// When launched by double-clicking a save game file, the curdir will
 		// be the save game folder unless we correct it
-		Directory::SetCurrentDirectory(appDirectory);
+		Directory::SetCurrentDirectory(_G(appDirectory));
 	} else {
 		// It looks like Allegro library does not like ANSI (ACP) paths.
 		// When *not* working in U_UNICODE filepath mode, whenever it gets
@@ -373,19 +328,19 @@ Common::Error AGSEngine::run() {
 	if (res != 0)
 		return Common::kUnknownError;
 
-	if (AGS3::justDisplayVersion) {
+	if (_G(justDisplayVersion)) {
 		AGS3::platform->WriteStdOut(AGS3::get_engine_string());
 		return Common::kNoError;
 	}
 
-	if (AGS3::justDisplayHelp) {
+	if (_G(justDisplayHelp)) {
 		AGS3::main_print_help();
 		return Common::kNoError;
 	}
 
-	if (!AGS3::justTellInfo)
+	if (!_G(justTellInfo))
 		AGS3::platform->SetGUIMode(true);
-	AGS3::init_debug(startup_opts, AGS3::justTellInfo);
+	AGS3::init_debug(startup_opts, _G(justTellInfo));
 	AGS3::Debug::Printf("%s", AGS3::get_engine_string().GetNullableCStr());
 
 	AGS3::main_set_gamedir(ARGC, ARGV);
diff --git a/engines/ags/engine/ac/game.cpp b/engines/ags/engine/ac/game.cpp
index 9b61c47468..4526adb9ab 100644
--- a/engines/ags/engine/ac/game.cpp
+++ b/engines/ags/engine/ac/game.cpp
@@ -126,7 +126,7 @@ extern int numAnimButs;
 extern int is_complete_overlay, is_text_overlay;
 
 #if AGS_PLATFORM_OS_IOS || AGS_PLATFORM_OS_ANDROID
-extern int psp_gfx_renderer;
+extern int _G(psp_gfx_renderer);
 #endif
 
 extern int obj_lowest_yp, char_lowest_yp;
diff --git a/engines/ags/engine/ac/global_debug.cpp b/engines/ags/engine/ac/global_debug.cpp
index e1a4aefece..35ae916ad8 100644
--- a/engines/ags/engine/ac/global_debug.cpp
+++ b/engines/ags/engine/ac/global_debug.cpp
@@ -46,6 +46,7 @@
 #include "ags/shared/gfx/bitmap.h"
 #include "ags/engine/gfx/graphicsdriver.h"
 #include "ags/engine/main/graphics_mode.h"
+#include "ags/engine/globals.h"
 
 namespace AGS3 {
 
@@ -75,7 +76,7 @@ String GetRuntimeInfo() {
 		"[Game resolution %d x %d (%d-bit)"
 		"[Running %d x %d at %d-bit%s%s[GFX: %s; %s[Draw frame %d x %d["
 		"Sprite cache size: %d KB (limit %d KB; %d locked)",
-		EngineVersion.LongString.GetCStr(), game.GetGameRes().Width, game.GetGameRes().Height, game.GetColorDepth(),
+		_G(EngineVersion).LongString.GetCStr(), game.GetGameRes().Width, game.GetGameRes().Height, game.GetColorDepth(),
 		mode.Width, mode.Height, mode.ColorDepth, (convert_16bit_bgr) ? " BGR" : "",
 		mode.Windowed ? " W" : "",
 		gfxDriver->GetDriverName(), filter->GetInfo().Name.GetCStr(),
diff --git a/engines/ags/engine/ac/global_game.cpp b/engines/ags/engine/ac/global_game.cpp
index 9235c76b69..dd195561d8 100644
--- a/engines/ags/engine/ac/global_game.cpp
+++ b/engines/ags/engine/ac/global_game.cpp
@@ -95,7 +95,7 @@ extern IGraphicsDriver *gfxDriver;
 extern color palette[256];
 
 #if AGS_PLATFORM_OS_IOS || AGS_PLATFORM_OS_ANDROID
-extern int psp_gfx_renderer;
+extern int _G(psp_gfx_renderer);
 #endif
 
 void GiveScore(int amnt) {
diff --git a/engines/ags/engine/ac/room.cpp b/engines/ags/engine/ac/room.cpp
index 6fa660d393..d6c04b6a02 100644
--- a/engines/ags/engine/ac/room.cpp
+++ b/engines/ags/engine/ac/room.cpp
@@ -20,8 +20,6 @@
  *
  */
 
-//include <ctype.h> // for toupper
-
 #include "ags/shared/core/platform.h"
 #include "ags/shared/util/string_utils.h" //strlwr()
 #include "ags/shared/ac/common.h"
@@ -81,6 +79,7 @@
 #include "ags/engine/script/script_api.h"
 #include "ags/engine/script/script_runtime.h"
 #include "ags/engine/ac/dynobj/scriptstring.h"
+#include "ags/engine/globals.h"
 
 namespace AGS3 {
 
@@ -914,8 +913,6 @@ void load_new_room(int newnum, CharacterInfo *forchar) {
 	//  MSS_CHECK_ALL_BLOCKS;
 }
 
-extern int psp_clear_cache_on_room_change;
-
 // new_room: changes the current room number, and loads the new room from disk
 void new_room(int newnum, CharacterInfo *forchar) {
 	EndSkippingUntilCharStops();
@@ -949,7 +946,7 @@ void new_room(int newnum, CharacterInfo *forchar) {
 	// change rooms
 	unload_old_room();
 
-	if (psp_clear_cache_on_room_change) {
+	if (_G(psp_clear_cache_on_room_change)) {
 		// Delete all cached sprites
 		spriteset.DisposeAll();
 
diff --git a/engines/ags/engine/ac/system.cpp b/engines/ags/engine/ac/system.cpp
index 0275ec1b6a..abeb62a4dd 100644
--- a/engines/ags/engine/ac/system.cpp
+++ b/engines/ags/engine/ac/system.cpp
@@ -44,6 +44,7 @@
 #include "ags/engine/script/script_api.h"
 #include "ags/engine/script/script_runtime.h"
 #include "ags/engine/ac/dynobj/scriptstring.h"
+#include "ags/engine/globals.h"
 #include "ags/events.h"
 
 namespace AGS3 {
@@ -110,7 +111,7 @@ int System_GetViewportWidth() {
 }
 
 const char *System_GetVersion() {
-	return CreateNewScriptString(EngineVersion.LongString);
+	return CreateNewScriptString(_G(EngineVersion).LongString);
 }
 
 int System_GetHardwareAcceleration() {
diff --git a/engines/ags/engine/game/savegame.cpp b/engines/ags/engine/game/savegame.cpp
index a5823f2956..d2deb79b9d 100644
--- a/engines/ags/engine/game/savegame.cpp
+++ b/engines/ags/engine/game/savegame.cpp
@@ -61,6 +61,7 @@
 #include "ags/shared/util/stream.h"
 #include "ags/shared/util/string_utils.h"
 #include "ags/engine/media/audio/audio_system.h"
+#include "ags/engine/globals.h"
 #include "ags/ags.h"
 
 namespace AGS3 {
@@ -240,11 +241,11 @@ HSaveError ReadDescription_v321(Stream *in, SavegameVersion &svg_ver, SavegameDe
 
 	String version_str = String::FromStream(in);
 	Version eng_version(version_str);
-	if (eng_version > EngineVersion ||
-		eng_version < SavedgameLowestBackwardCompatVersion) {
+	if (eng_version > _G(EngineVersion) ||
+		eng_version < _G(SavedgameLowestBackwardCompatVersion)) {
 		// Engine version is either non-forward or non-backward compatible
 		return new SavegameError(kSvgErr_IncompatibleEngine,
-			String::FromFormat("Required: %s, supported: %s - %s.", eng_version.LongString.GetCStr(), SavedgameLowestBackwardCompatVersion.LongString.GetCStr(), EngineVersion.LongString.GetCStr()));
+			String::FromFormat("Required: %s, supported: %s - %s.", eng_version.LongString.GetCStr(), _G(SavedgameLowestBackwardCompatVersion).LongString.GetCStr(), _G(EngineVersion).LongString.GetCStr()));
 	}
 	if (elems & kSvgDesc_EnvInfo) {
 		desc.MainDataFilename.Read(in);
@@ -672,7 +673,7 @@ void WriteDescription(Stream *out, const String &user_text, const Bitmap *user_i
 	out->WriteInt32(kSvgVersion_Current);
 	// Enviroment information
 	StrUtil::WriteString("Adventure Game Studio run-time engine", out);
-	StrUtil::WriteString(EngineVersion.LongString, out);
+	StrUtil::WriteString(_G(EngineVersion).LongString, out);
 	StrUtil::WriteString(game.guid, out);
 	StrUtil::WriteString(game.gamename, out);
 	StrUtil::WriteString(ResPaths.GamePak.Name, out);
diff --git a/engines/ags/engine/gfx/gfx_util.cpp b/engines/ags/engine/gfx/gfx_util.cpp
index d6ff6d19ae..b1ad9e20d2 100644
--- a/engines/ags/engine/gfx/gfx_util.cpp
+++ b/engines/ags/engine/gfx/gfx_util.cpp
@@ -28,7 +28,7 @@ namespace AGS3 {
 
 // CHECKME: is this hack still relevant?
 #if AGS_PLATFORM_OS_IOS || AGS_PLATFORM_OS_ANDROID
-extern int psp_gfx_renderer;
+extern int _G(psp_gfx_renderer);
 #endif
 
 namespace AGS {
@@ -117,7 +117,7 @@ void DrawSpriteWithTransparency(Bitmap *ds, Bitmap *sprite, int x, int y, int al
 	if (sprite_depth < surface_depth
 		// CHECKME: what is the purpose of this hack and is this still relevant?
 #if AGS_PLATFORM_OS_IOS || AGS_PLATFORM_OS_ANDROID
-		|| (ds->GetBPP() < surface_depth && psp_gfx_renderer > 0) // Fix for corrupted speechbox outlines with the OGL driver
+		|| (ds->GetBPP() < surface_depth && _G(psp_gfx_renderer) > 0) // Fix for corrupted speechbox outlines with the OGL driver
 #endif
 		) {
 		// If sprite is lower color depth than destination surface, e.g.
diff --git a/engines/ags/engine/globals.cpp b/engines/ags/engine/globals.cpp
index af4b56a69d..cd161a794e 100644
--- a/engines/ags/engine/globals.cpp
+++ b/engines/ags/engine/globals.cpp
@@ -26,7 +26,7 @@ namespace AGS3 {
 
 Globals *g_globals;
 
-Globals::Globals() : _want_exit(false), _abort_engine(false) {
+Globals::Globals() {
 	g_globals = this;
 }
 
diff --git a/engines/ags/engine/globals.h b/engines/ags/engine/globals.h
index 6de237a01c..b312519049 100644
--- a/engines/ags/engine/globals.h
+++ b/engines/ags/engine/globals.h
@@ -23,12 +23,78 @@
 #ifndef AGS_ENGINE_GLOBALS_H
 #define AGS_ENGINE_GLOBALS_H
 
+#include "ags/shared/util/string.h"
+#include "ags/shared/util/version.h"
+#include "ags/lib/std/set.h"
+
 namespace AGS3 {
 
+using String = AGS::Shared::String;
+using Version = AGS::Shared::Version;
+
 class Globals {
 public:
-	bool _want_exit;
-	bool _abort_engine;
+	/**
+	 * \defgroup Overall flags
+	 * @{
+	 */
+
+	// Major overall flags
+	bool _want_exit = false;
+	bool _abort_engine = false;
+
+	/**@}*/
+
+	/**
+	 * \defgroup main globals
+	 * @{
+	 */
+
+	String _appDirectory; // Needed for library loading
+	String _cmdGameDataPath;
+
+	const char **_global_argv = nullptr;
+	int _global_argc = 0;
+
+	// Startup flags, set from parameters to engine
+	int _force_window = 0;
+	int _override_start_room = 0;
+	bool _justDisplayHelp = false;
+	bool _justDisplayVersion = false;
+	bool _justRunSetup = false;
+	bool _justRegisterGame = false;
+	bool _justUnRegisterGame = false;
+	bool _justTellInfo = false;
+	std::set<String> _tellInfoKeys;
+	const char *_loadSaveGameOnStartup = nullptr;
+
+#if ! AGS_PLATFORM_DEFINES_PSP_VARS
+	int _psp_video_framedrop = 1;
+	int _psp_audio_enabled = 1;
+	int _psp_midi_enabled = 1;
+	int _psp_ignore_acsetup_cfg_file = 0;
+	int _psp_clear_cache_on_room_change = 0;
+
+	int _psp_midi_preload_patches = 0;
+	int _psp_audio_cachesize = 10;
+	const char *_psp_game_file_name = "";
+	const char *_psp_translation = "default";
+
+	int _psp_gfx_renderer = 0;
+	int _psp_gfx_scaling = 1;
+	int _psp_gfx_smoothing = 0;
+	int _psp_gfx_super_sampling = 1;
+	int _psp_gfx_smooth_sprites = 0;
+#endif
+
+	// Current engine version
+	Version _EngineVersion;
+	// Lowest savedgame version, accepted by this engine
+	Version _SavedgameLowestBackwardCompatVersion;
+	// Lowest engine version, which would accept current savedgames
+	Version _SavedgameLowestForwardCompatVersion;
+
+	/**@}*/
 
 public:
 	Globals();
diff --git a/engines/ags/engine/main/config.cpp b/engines/ags/engine/main/config.cpp
index 7f5d52e193..93b11d64e1 100644
--- a/engines/ags/engine/main/config.cpp
+++ b/engines/ags/engine/main/config.cpp
@@ -23,7 +23,6 @@
 //
 // Game configuration
 //
-//include <ctype.h> // toupper
 
 #include "ags/shared/core/platform.h"
 #include "ags/engine/ac/gamesetup.h"
@@ -44,6 +43,7 @@
 #include "ags/shared/util/path.h"
 #include "ags/shared/util/string_utils.h"
 #include "ags/engine/media/audio/audio_system.h"
+#include "ags/engine/globals.h"
 
 namespace AGS3 {
 
@@ -53,7 +53,6 @@ using namespace AGS::Engine;
 extern GameSetupStruct game;
 extern GameSetup usetup;
 extern SpriteCache spriteset;
-extern int force_window;
 extern GameState play;
 
 // Filename of the default config file, the one found in the game installation
@@ -385,16 +384,6 @@ void read_legacy_graphics_config(const ConfigTree &cfg) {
 	usetup.Screen.DisplayMode.RefreshRate = INIreadint(cfg, "misc", "refresh");
 }
 
-// Variables used for mobile port configs
-extern int psp_gfx_renderer;
-extern int psp_gfx_scaling;
-extern int psp_gfx_super_sampling;
-extern int psp_gfx_smoothing;
-extern int psp_gfx_smooth_sprites;
-extern int psp_audio_enabled;
-extern int psp_midi_enabled;
-extern char psp_translation[];
-
 void override_config_ext(ConfigTree &cfg) {
 	// Mobile ports always run in fullscreen mode
 #if AGS_PLATFORM_OS_ANDROID || AGS_PLATFORM_OS_IOS
@@ -404,35 +393,35 @@ void override_config_ext(ConfigTree &cfg) {
 	INIwritestring(cfg, "graphics", "driver", "ScummVM");
 	INIwriteint(cfg, "graphics", "render_at_screenres", 1);
 
-	// psp_gfx_scaling - scaling style:
+	// _G(psp_gfx_scaling) - scaling style:
 	//    * 0 - no scaling
 	//    * 1 - stretch and preserve aspect ratio
 	//    * 2 - stretch to whole screen
-	if (psp_gfx_scaling == 0)
+	if (_G(psp_gfx_scaling) == 0)
 		INIwritestring(cfg, "graphics", "game_scale_fs", "1");
-	else if (psp_gfx_scaling == 1)
+	else if (_G(psp_gfx_scaling) == 1)
 		INIwritestring(cfg, "graphics", "game_scale_fs", "proportional");
 	else
 		INIwritestring(cfg, "graphics", "game_scale_fs", "stretch");
 
-	// psp_gfx_smoothing - scaling filter:
+	// _G(psp_gfx_smoothing) - scaling filter:
 	//    * 0 - nearest-neighbour
 	//    * 1 - linear
-	if (psp_gfx_smoothing == 0)
+	if (_G(psp_gfx_smoothing) == 0)
 		INIwritestring(cfg, "graphics", "filter", "StdScale");
 	else
 		INIwritestring(cfg, "graphics", "filter", "Linear");
 
-	// psp_gfx_super_sampling - enable super sampling
+	// _G(psp_gfx_super_sampling) - enable super sampling
 	//    * 0 - x1
 	//    * 1 - x2
-	if (psp_gfx_renderer == 2)
-		INIwriteint(cfg, "graphics", "supersampling", psp_gfx_super_sampling + 1);
+	if (_G(psp_gfx_renderer) == 2)
+		INIwriteint(cfg, "graphics", "supersampling", _G(psp_gfx_super_sampling) + 1);
 	else
 		INIwriteint(cfg, "graphics", "supersampling", 0);
 
-	INIwriteint(cfg, "misc", "antialias", psp_gfx_smooth_sprites != 0);
-	INIwritestring(cfg, "language", "translation", psp_translation);
+	INIwriteint(cfg, "misc", "antialias", _G(psp_gfx_smooth_sprites) != 0);
+	INIwritestring(cfg, "language", "translation", _G(psp_translation));
 }
 
 void apply_config(const ConfigTree &cfg) {
@@ -440,9 +429,9 @@ void apply_config(const ConfigTree &cfg) {
 		// Legacy settings has to be translated into new options;
 		// they must be read first, to let newer options override them, if ones are present
 		read_legacy_audio_config(cfg);
-		if (psp_audio_enabled) {
+		if (_G(psp_audio_enabled)) {
 			usetup.digicard = read_driverid(cfg, "sound", "digiid", usetup.digicard);
-			if (psp_midi_enabled)
+			if (_G(psp_midi_enabled))
 				usetup.midicard = read_driverid(cfg, "sound", "midiid", usetup.midicard);
 			else
 				usetup.midicard = MIDI_NONE;
@@ -573,8 +562,8 @@ void save_config_file() {
 	ConfigTree cfg;
 
 	// Last display mode
-	// TODO: force_window check is a temporary workaround (see comment below)
-	if (force_window == 0) {
+	// TODO: _G(force_window) check is a temporary workaround (see comment below)
+	if (_G(force_window) == 0) {
 		bool is_windowed = System_GetWindowed() != 0;
 		cfg["graphics"]["windowed"] = String::FromFormat("%d", is_windowed ? 1 : 0);
 		// TODO: this is a hack, necessary because the original config system was designed when
diff --git a/engines/ags/engine/main/engine.cpp b/engines/ags/engine/main/engine.cpp
index 41192bc72f..7e0df18447 100644
--- a/engines/ags/engine/main/engine.cpp
+++ b/engines/ags/engine/main/engine.cpp
@@ -25,6 +25,7 @@
 //
 
 #include "ags/shared/core/platform.h"
+#include "ags/engine/globals.h"
 
 //include <errno.h>
 #if AGS_PLATFORM_OS_WINDOWS
@@ -89,7 +90,6 @@ using namespace AGS::Engine;
 
 extern char check_dynamic_sprites_at_exit;
 extern int our_eip;
-extern bool justRunSetup;
 extern GameSetup usetup;
 extern GameSetupStruct game;
 extern int proper_exit;
@@ -193,10 +193,10 @@ bool engine_run_setup(const String &exe_path, ConfigTree &cfg, int &app_res) {
 void engine_force_window() {
 	// Force to run in a window, override the config file
 	// TODO: actually overwrite config tree instead
-	if (force_window == 1) {
+	if (_G(force_window) == 1) {
 		usetup.Screen.DisplayMode.Windowed = true;
 		usetup.Screen.DisplayMode.ScreenSize.SizeDef = kScreenDef_ByGameScaling;
-	} else if (force_window == 2) {
+	} else if (_G(force_window) == 2) {
 		usetup.Screen.DisplayMode.Windowed = false;
 		usetup.Screen.DisplayMode.ScreenSize.SizeDef = kScreenDef_MaxDisplay;
 	}
@@ -247,9 +247,9 @@ String find_game_data_in_directory(const String &path) {
 bool search_for_game_data_file(String &filename, String &search_path) {
 	Debug::Printf("Looking for the game data file");
 	// 1. From command line argument, treated as a directory
-	if (!cmdGameDataPath.IsEmpty()) {
+	if (!_G(cmdGameDataPath).IsEmpty()) {
 		// set from cmd arg (do any conversions if needed)
-		filename = cmdGameDataPath;
+		filename = _G(cmdGameDataPath);
 		if (!filename.IsEmpty() && Path::IsDirectory(filename)) {
 			search_path = filename;
 			filename = find_game_data_in_directory(search_path);
@@ -273,8 +273,8 @@ bool search_for_game_data_file(String &filename, String &search_path) {
 			filename = find_game_data_in_directory(search_path);
 			if (filename.IsEmpty()) {
 				// 3.3 Look in executable's directory (if it's different from current dir)
-				if (Path::ComparePaths(appDirectory, search_path)) {
-					search_path = appDirectory;
+				if (Path::ComparePaths(_G(appDirectory), search_path)) {
+					search_path = _G(appDirectory);
 					filename = find_game_data_in_directory(search_path);
 				}
 			}
@@ -559,7 +559,7 @@ void atexit_handler() {
 		                       "Program pointer: %+03d  (write this number down), ACI version %s\n"
 		                       "If you see a list of numbers above, please write them down and contact\n"
 		                       "developers. Otherwise, note down any other information displayed.",
-		                       our_eip, EngineVersion.LongString.GetCStr());
+		                       our_eip, _G(EngineVersion).LongString.GetCStr());
 	}
 }
 
@@ -598,13 +598,13 @@ int engine_load_game_data() {
 }
 
 int engine_check_register_game() {
-	if (justRegisterGame) {
+	if (_G(justRegisterGame)) {
 		platform->RegisterGameWithGameExplorer();
 		proper_exit = 1;
 		return EXIT_NORMAL;
 	}
 
-	if (justUnRegisterGame) {
+	if (_G(justUnRegisterGame)) {
 		platform->UnRegisterGameWithGameExplorer();
 		proper_exit = 1;
 		return EXIT_NORMAL;
@@ -1052,7 +1052,7 @@ void engine_init_game_settings() {
 
 void engine_setup_scsystem_auxiliary() {
 	// ScriptSystem::aci_version is only 10 chars long
-	strncpy(scsystem.aci_version, EngineVersion.LongString, 10);
+	strncpy(scsystem.aci_version, _G(EngineVersion).LongString, 10);
 	if (usetup.override_script_os >= 0) {
 		scsystem.os = usetup.override_script_os;
 	} else {
@@ -1114,15 +1114,15 @@ void allegro_bitmap_test_init() {
 // for the available resource packs in common locations
 HError define_gamedata_location_checkall(const String &exe_path) {
 	// First try if they provided a startup option
-	if (!cmdGameDataPath.IsEmpty()) {
+	if (!_G(cmdGameDataPath).IsEmpty()) {
 		// If not a valid path - bail out
-		if (!Path::IsFileOrDir(cmdGameDataPath))
-			return new Error(String::FromFormat("Defined game location is not a valid path.\nPath: '%s'", cmdGameDataPath.GetCStr()));
+		if (!Path::IsFileOrDir(_G(cmdGameDataPath)))
+			return new Error(String::FromFormat("Defined game location is not a valid path.\nPath: '%s'", _G(cmdGameDataPath).GetCStr()));
 		// Switch working dir to this path to be able to look for config and other assets there
-		Directory::SetCurrentDirectory(Path::GetDirectoryPath(cmdGameDataPath));
+		Directory::SetCurrentDirectory(Path::GetDirectoryPath(_G(cmdGameDataPath)));
 		// If it's a file, then keep it and proceed
-		if (Path::IsFile(cmdGameDataPath)) {
-			usetup.main_data_filepath = cmdGameDataPath;
+		if (Path::IsFile(_G(cmdGameDataPath))) {
+			usetup.main_data_filepath = _G(cmdGameDataPath);
 			return HError::None();
 		}
 	}
@@ -1219,7 +1219,7 @@ void engine_read_config(const String &exe_path, ConfigTree &cfg) {
 	// Apply overriding options from mobile port settings
 	// TODO: normally, those should be instead stored in the same config file in a uniform way
 	// NOTE: the variable is historically called "ignore" but we use it in "override" meaning here
-	if (psp_ignore_acsetup_cfg_file)
+	if (_G(psp_ignore_acsetup_cfg_file))
 		override_config_ext(cfg);
 }
 
@@ -1257,7 +1257,7 @@ void engine_set_config(const ConfigTree cfg) {
 //
 // --tell command support: printing engine/game info by request
 //
-extern std::set<String> tellInfoKeys;
+
 static bool print_info_needs_game(const std::set<String> &keys) {
 	return keys.count("all") > 0 || keys.count("config") > 0 || keys.count("configpath") > 0 ||
 	       keys.count("data") > 0;
@@ -1329,9 +1329,9 @@ int initialize_engine(const ConfigTree &startup_opts) {
 
 	//-----------------------------------------------------
 	// Locate game data and assemble game config
-	const String exe_path = global_argv[0];
-	if (justTellInfo && !print_info_needs_game(tellInfoKeys)) {
-		engine_print_info(tellInfoKeys, exe_path, nullptr);
+	const String exe_path = _G(global_argv)[0];
+	if (_G(justTellInfo) && !print_info_needs_game(_G(tellInfoKeys))) {
+		engine_print_info(_G(tellInfoKeys), exe_path, nullptr);
 		return EXIT_NORMAL;
 	}
 
@@ -1339,12 +1339,12 @@ int initialize_engine(const ConfigTree &startup_opts) {
 		return EXIT_ERROR;
 	ConfigTree cfg;
 	engine_prepare_config(cfg, exe_path, startup_opts);
-	if (justTellInfo) {
-		engine_print_info(tellInfoKeys, exe_path, &cfg);
+	if (_G(justTellInfo)) {
+		engine_print_info(_G(tellInfoKeys), exe_path, &cfg);
 		return EXIT_NORMAL;
 	}
 	// Test if need to run built-in setup program (where available)
-	if (justRunSetup) {
+	if (_G(justRunSetup)) {
 		int res;
 		if (!engine_run_setup(exe_path, cfg, res))
 			return res;
@@ -1465,7 +1465,7 @@ int initialize_engine(const ConfigTree &startup_opts) {
 
 	allegro_bitmap_test_init();
 
-	initialize_start_and_play_game(override_start_room, loadSaveGameOnStartup);
+	initialize_start_and_play_game(_G(override_start_room), _G(loadSaveGameOnStartup));
 
 	return EXIT_NORMAL;
 }
@@ -1545,7 +1545,7 @@ const char *get_engine_name() {
 }
 
 const char *get_engine_version() {
-	return EngineVersion.LongString.GetCStr();
+	return _G(EngineVersion).LongString.GetCStr();
 }
 
 void engine_set_pre_init_callback(t_engine_pre_init_callback callback) {
diff --git a/engines/ags/engine/main/game_start.cpp b/engines/ags/engine/main/game_start.cpp
index 47fe112aac..11143a035f 100644
--- a/engines/ags/engine/main/game_start.cpp
+++ b/engines/ags/engine/main/game_start.cpp
@@ -43,6 +43,7 @@
 #include "ags/engine/script/script.h"
 #include "ags/engine/media/audio/audio_system.h"
 #include "ags/engine/ac/timer.h"
+#include "ags/engine/globals.h"
 #include "ags/ags.h"
 
 namespace AGS3 {
@@ -53,7 +54,6 @@ using namespace AGS::Engine;
 extern int our_eip, displayed_room;
 extern GameSetupStruct game;
 extern GameState play;
-extern const char *loadSaveGameOnStartup;
 extern std::vector<ccInstance *> moduleInst;
 extern int numScriptModules;
 extern CharacterInfo *playerchar;
@@ -75,14 +75,14 @@ void start_game_init_editor_debugging() {
 }
 
 void start_game_load_savegame_on_startup() {
-	if (loadSaveGameOnStartup != nullptr) {
+	if (_G(loadSaveGameOnStartup) != nullptr) {
 		int saveGameNumber = 1000;
-		const char *sgName = strstr(loadSaveGameOnStartup, "agssave.");
+		const char *sgName = strstr(_G(loadSaveGameOnStartup), "agssave.");
 		if (sgName != nullptr) {
 			sscanf(sgName, "agssave.%03d", &saveGameNumber);
 		}
 		current_fade_out_effect();
-		try_restore_save(loadSaveGameOnStartup, saveGameNumber);
+		try_restore_save(_G(loadSaveGameOnStartup), saveGameNumber);
 	}
 }
 
diff --git a/engines/ags/engine/main/main.cpp b/engines/ags/engine/main/main.cpp
deleted file mode 100644
index de0b2b72ea..0000000000
--- a/engines/ags/engine/main/main.cpp
+++ /dev/null
@@ -1,465 +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.
- *
- */
-
-//
-// Entry point of the application here.
-//
-//
-// For Windows main() function is really called _mangled_main and is called
-// not by system, but from insides of allegro library.
-// (See allegro\platform\alwin.h)
-// What about other platforms?
-//
-
-#include "ags/shared/core/platform.h"
-#define AGS_PLATFORM_DEFINES_PSP_VARS (AGS_PLATFORM_OS_IOS || AGS_PLATFORM_OS_ANDROID)
-
-//include <set>
-#include "ags/shared/ac/common.h"
-#include "ags/shared/ac/gamesetup.h"
-#include "ags/shared/ac/gamestate.h"
-#include "ags/shared/core/def_version.h"
-#include "ags/shared/debugging/debugger.h"
-#include "ags/shared/debugging/debug_log.h"
-#include "ags/shared/debugging/out.h"
-#include "ags/shared/main/config.h"
-#include "ags/shared/main/engine.h"
-#include "ags/shared/main/mainheader.h"
-#include "ags/shared/main/main.h"
-#include "ags/shared/platform/base/agsplatformdriver.h"
-#include "ags/shared/ac/route_finder.h"
-#include "ags/shared/core/assetmanager.h"
-#include "ags/shared/util/directory.h"
-#include "ags/shared/util/path.h"
-#include "ags/shared/util/string_compat.h"
-
-#if AGS_PLATFORM_OS_WINDOWS
-#include "ags/shared/platform/windows/win_ex_handling.h"
-#endif
-#if AGS_PLATFORM_DEBUG
-#include "ags/shared/test/test_all.h"
-#endif
-
-#if AGS_PLATFORM_OS_WINDOWS && !AGS_PLATFORM_DEBUG
-#define USE_CUSTOM_EXCEPTION_HANDLER
-#endif
-
-namespace AGS3 {
-
-using namespace AGS::Shared;
-using namespace AGS::Engine;
-
-String appDirectory; // Needed for library loading
-String cmdGameDataPath;
-
-char **global_argv = nullptr;
-int    global_argc = 0;
-
-
-extern GameSetup usetup;
-extern GameState play;
-extern int our_eip;
-extern AGSPlatformDriver *platform;
-extern int convert_16bit_bgr;
-extern int editor_debugging_enabled;
-extern int editor_debugging_initialized;
-extern char editor_debugger_instance_token[100];
-
-
-// Startup flags, set from parameters to engine
-int force_window = 0;
-int override_start_room = 0;
-bool justDisplayHelp = false;
-bool justDisplayVersion = false;
-bool justRunSetup = false;
-bool justRegisterGame = false;
-bool justUnRegisterGame = false;
-bool justTellInfo = false;
-bool attachToParentConsole = false;
-bool hideMessageBoxes = false;
-std::set<String> tellInfoKeys;
-const char *loadSaveGameOnStartup = nullptr;
-
-#if ! AGS_PLATFORM_DEFINES_PSP_VARS
-int psp_video_framedrop = 1;
-int psp_audio_enabled = 1;
-int psp_midi_enabled = 1;
-int psp_ignore_acsetup_cfg_file = 0;
-int psp_clear_cache_on_room_change = 0;
-
-int psp_midi_preload_patches = 0;
-int psp_audio_cachesize = 10;
-char psp_game_file_name[] = "";
-char psp_translation[] = "default";
-
-int psp_gfx_renderer = 0;
-int psp_gfx_scaling = 1;
-int psp_gfx_smoothing = 0;
-int psp_gfx_super_sampling = 1;
-int psp_gfx_smooth_sprites = 0;
-#endif
-
-
-void main_pre_init() {
-	our_eip = -999;
-	Common::AssetManager::SetSearchPriority(Common::kAssetPriorityDir);
-	play.takeover_data = 0;
-}
-
-void main_create_platform_driver() {
-	platform = AGSPlatformDriver::GetDriver();
-}
-
-// this needs to be updated if the "play" struct changes
-#define SVG_VERSION_BWCOMPAT_MAJOR      3
-#define SVG_VERSION_BWCOMPAT_MINOR      2
-#define SVG_VERSION_BWCOMPAT_RELEASE    0
-#define SVG_VERSION_BWCOMPAT_REVISION   1103
-// CHECKME: we may lower this down, if we find that earlier versions may still
-// load new savedgames
-#define SVG_VERSION_FWCOMPAT_MAJOR      3
-#define SVG_VERSION_FWCOMPAT_MINOR      2
-#define SVG_VERSION_FWCOMPAT_RELEASE    1
-#define SVG_VERSION_FWCOMPAT_REVISION   1111
-
-// Current engine version
-AGS::Shared::Version EngineVersion;
-// Lowest savedgame version, accepted by this engine
-AGS::Shared::Version SavedgameLowestBackwardCompatVersion;
-// Lowest engine version, which would accept current savedgames
-AGS::Shared::Version SavedgameLowestForwardCompatVersion;
-
-void main_init(int argc, char *argv[]) {
-	EngineVersion = Version(ACI_VERSION_STR " " SPECIAL_VERSION);
-#if defined (BUILD_STR)
-	EngineVersion.BuildInfo = BUILD_STR;
-#endif
-	SavedgameLowestBackwardCompatVersion = Version(SVG_VERSION_BWCOMPAT_MAJOR, SVG_VERSION_BWCOMPAT_MINOR, SVG_VERSION_BWCOMPAT_RELEASE, SVG_VERSION_BWCOMPAT_REVISION);
-	SavedgameLowestForwardCompatVersion = Version(SVG_VERSION_FWCOMPAT_MAJOR, SVG_VERSION_FWCOMPAT_MINOR, SVG_VERSION_FWCOMPAT_RELEASE, SVG_VERSION_FWCOMPAT_REVISION);
-
-	Common::AssetManager::CreateInstance();
-	main_pre_init();
-	main_create_platform_driver();
-
-	global_argv = argv;
-	global_argc = argc;
-}
-
-String get_engine_string() {
-	return String::FromFormat("Adventure Game Studio v%s Interpreter\n"
-		"Copyright (c) 1999-2011 Chris Jones and " ACI_COPYRIGHT_YEARS " others\n"
-#ifdef BUILD_STR
-		"ACI version %s (Build: %s)\n",
-		EngineVersion.ShortString.GetCStr(), EngineVersion.LongString.GetCStr(), EngineVersion.BuildInfo.GetCStr());
-#else
-		"ACI version %s\n", EngineVersion.ShortString.GetCStr(), EngineVersion.LongString.GetCStr());
-#endif
-}
-
-extern char return_to_roomedit[30];
-extern char return_to_room[150];
-
-void main_print_help() {
-	platform->WriteStdOut(
-		"Usage: ags [OPTIONS] [GAMEFILE or DIRECTORY]\n\n"
-		//--------------------------------------------------------------------------------|
-		"Options:\n"
-#if AGS_PLATFORM_OS_WINDOWS
-		"  --console-attach             Write output to the parent process's console\n"
-#endif
-		"  --fps                        Display fps counter\n"
-		"  --fullscreen                 Force display mode to fullscreen\n"
-		"  --gfxdriver <id>             Request graphics driver. Available options:\n"
-#if AGS_PLATFORM_OS_WINDOWS
-		"                                 d3d9, ogl, software\n"
-#else
-		"                                 ogl, software\n"
-#endif
-		"  --gfxfilter FILTER [SCALING]\n"
-		"                               Request graphics filter. Available options:\n"
-		"                                 hqx, linear, none, stdscale\n"
-		"                                 (support differs between graphic drivers);\n"
-		"                                 scaling is specified by integer number\n"
-		"  --help                       Print this help message and stop\n"
-		"  --log-OUTPUT=GROUP[:LEVEL][,GROUP[:LEVEL]][,...]\n"
-		"  --log-OUTPUT=+GROUPLIST[:LEVEL]\n"
-		"                               Setup logging to the chosen OUTPUT with given\n"
-		"                               log groups and verbosity levels. Groups may\n"
-		"                               be also defined by a LIST of one-letter IDs,\n"
-		"                               preceded by '+', e.g. +ABCD:LEVEL. Verbosity may\n"
-		"                               be also defined by a numberic ID.\n"
-		"                               OUTPUTs are\n"
-		"                                 stdout, file, console\n"
-		"                               (where \"console\" is internal engine's console)\n"
-		"                               GROUPs are:\n"
-		"                                 all, main (m), game (g), manobj (o),\n"
-		"                                 script (s), sprcache (c)\n"
-		"                               LEVELs are:\n"
-		"                                 all, alert (1), fatal (2), error (3), warn (4),\n"
-		"                                 info (5), debug (6)\n"
-		"                               Examples:\n"
-		"                                 --log-stdout=+mgs:debug\n"
-		"                                 --log-file=all:warn\n"
-		"  --log-file-path=PATH         Define custom path for the log file\n"
-		//--------------------------------------------------------------------------------|
-#if AGS_PLATFORM_OS_WINDOWS
-		"  --no-message-box             Disable reporting of alerts to message boxes\n"
-		"  --setup                      Run setup application\n"
-#endif
-		"  --tell                       Print various information concerning engine\n"
-		"                                 and the game; for selected output use:\n"
-		"  --tell-config                Print contents of merged game config\n"
-		"  --tell-configpath            Print paths to available config files\n"
-		"  --tell-data                  Print information on game data and its location\n"
-		"  --tell-engine                Print engine name and version\n"
-		"  --tell-graphicdriver         Print list of supported graphic drivers\n"
-		"\n"
-		"  --version                    Print engine's version and stop\n"
-		"  --windowed                   Force display mode to windowed\n"
-		"\n"
-		"Gamefile options:\n"
-		"  /dir/path/game/              Launch the game in specified directory\n"
-		"  /dir/path/game/penguin.exe   Launch penguin.exe\n"
-		"  [nothing]                    Launch the game in the current directory\n"
-		//--------------------------------------------------------------------------------|
-	);
-}
-
-static int main_process_cmdline(ConfigTree &cfg, int argc, char *argv[]) {
-	int datafile_argv = 0;
-	for (int ee = 1; ee < argc; ++ee) {
-		const char *arg = argv[ee];
-		//
-		// Startup options
-		//
-		if (ags_stricmp(arg, "--help") == 0 || ags_stricmp(arg, "/?") == 0 || ags_stricmp(arg, "-?") == 0) {
-			justDisplayHelp = true;
-			return 0;
-		}
-		if (ags_stricmp(arg, "-v") == 0 || ags_stricmp(arg, "--version") == 0) {
-			justDisplayVersion = true;
-			return 0;
-		} else if (ags_stricmp(arg, "-updatereg") == 0)
-			debug_flags |= DBG_REGONLY;
-#if AGS_PLATFORM_DEBUG
-		else if ((ags_stricmp(arg, "--startr") == 0) && (ee < argc - 1)) {
-			override_start_room = atoi(argv[ee + 1]);
-			ee++;
-		}
-#endif
-		else if ((ags_stricmp(arg, "--testre") == 0) && (ee < argc - 2)) {
-			strcpy(return_to_roomedit, argv[ee + 1]);
-			strcpy(return_to_room, argv[ee + 2]);
-			ee += 2;
-		} else if (ags_stricmp(arg, "-noexceptionhandler") == 0) usetup.disable_exception_handling = true;
-		else if (ags_stricmp(arg, "--setup") == 0) {
-			justRunSetup = true;
-		} else if (ags_stricmp(arg, "-registergame") == 0) {
-			justRegisterGame = true;
-		} else if (ags_stricmp(arg, "-unregistergame") == 0) {
-			justUnRegisterGame = true;
-		} else if ((ags_stricmp(arg, "-loadsavedgame") == 0) && (argc > ee + 1)) {
-			loadSaveGameOnStartup = argv[ee + 1];
-			ee++;
-		} else if ((ags_stricmp(arg, "--enabledebugger") == 0) && (argc > ee + 1)) {
-			strcpy(editor_debugger_instance_token, argv[ee + 1]);
-			editor_debugging_enabled = 1;
-			force_window = 1;
-			ee++;
-		} else if (ags_stricmp(arg, "--runfromide") == 0 && (argc > ee + 3)) {
-			usetup.install_dir = argv[ee + 1];
-			usetup.install_audio_dir = argv[ee + 2];
-			usetup.install_voice_dir = argv[ee + 3];
-			ee += 3;
-		} else if (ags_stricmp(arg, "--takeover") == 0) {
-			if (argc < ee + 2)
-				break;
-			play.takeover_data = atoi(argv[ee + 1]);
-			strncpy(play.takeover_from, argv[ee + 2], 49);
-			play.takeover_from[49] = 0;
-			ee += 2;
-		} else if (ags_strnicmp(arg, "--tell", 6) == 0) {
-			if (arg[6] == 0)
-				tellInfoKeys.insert(String("all"));
-			else if (arg[6] == '-' && arg[7] != 0)
-				tellInfoKeys.insert(String(arg + 7));
-		}
-		//
-		// Config overrides
-		//
-		else if (ags_stricmp(arg, "-windowed") == 0 || ags_stricmp(arg, "--windowed") == 0)
-			force_window = 1;
-		else if (ags_stricmp(arg, "-fullscreen") == 0 || ags_stricmp(arg, "--fullscreen") == 0)
-			force_window = 2;
-		else if ((ags_stricmp(arg, "-gfxdriver") == 0 || ags_stricmp(arg, "--gfxdriver") == 0) && (argc > ee + 1)) {
-			INIwritestring(cfg, "graphics", "driver", argv[++ee]);
-		} else if ((ags_stricmp(arg, "-gfxfilter") == 0 || ags_stricmp(arg, "--gfxfilter") == 0) && (argc > ee + 1)) {
-			// NOTE: we make an assumption here that if user provides scaling factor,
-			// this factor means to be applied to windowed mode only.
-			INIwritestring(cfg, "graphics", "filter", argv[++ee]);
-			if (argc > ee + 1 && argv[ee + 1][0] != '-')
-				INIwritestring(cfg, "graphics", "game_scale_win", argv[++ee]);
-			else
-				INIwritestring(cfg, "graphics", "game_scale_win", "max_round");
-		} else if (ags_stricmp(arg, "--fps") == 0) display_fps = kFPS_Forced;
-		else if (ags_stricmp(arg, "--test") == 0) debug_flags |= DBG_DEBUGMODE;
-		else if (ags_stricmp(arg, "-noiface") == 0) debug_flags |= DBG_NOIFACE;
-		else if (ags_stricmp(arg, "-nosprdisp") == 0) debug_flags |= DBG_NODRAWSPRITES;
-		else if (ags_stricmp(arg, "-nospr") == 0) debug_flags |= DBG_NOOBJECTS;
-		else if (ags_stricmp(arg, "-noupdate") == 0) debug_flags |= DBG_NOUPDATE;
-		else if (ags_stricmp(arg, "-nosound") == 0) debug_flags |= DBG_NOSFX;
-		else if (ags_stricmp(arg, "-nomusic") == 0) debug_flags |= DBG_NOMUSIC;
-		else if (ags_stricmp(arg, "-noscript") == 0) debug_flags |= DBG_NOSCRIPT;
-		else if (ags_stricmp(arg, "-novideo") == 0) debug_flags |= DBG_NOVIDEO;
-		else if (ags_stricmp(arg, "-dbgscript") == 0) debug_flags |= DBG_DBGSCRIPT;
-		else if (ags_strnicmp(arg, "--log-", 6) == 0 && arg[6] != 0) {
-			String logarg = arg + 6;
-			size_t split_at = logarg.FindChar('=');
-			if (split_at >= 0)
-				cfg["log"][logarg.Left(split_at)] = logarg.Mid(split_at + 1);
-			else
-				cfg["log"][logarg] = "";
-		} else if (ags_stricmp(arg, "--console-attach") == 0) attachToParentConsole = true;
-		else if (ags_stricmp(arg, "--no-message-box") == 0) hideMessageBoxes = true;
-		//
-		// Special case: data file location
-		//
-		else if (arg[0] != '-') datafile_argv = ee;
-	}
-
-	if (datafile_argv > 0) {
-		cmdGameDataPath = GetPathFromCmdArg(datafile_argv);
-	} else {
-		// assign standard path for mobile/consoles (defined in their own platform implementation)
-		cmdGameDataPath = psp_game_file_name;
-	}
-
-	if (tellInfoKeys.size() > 0)
-		justTellInfo = true;
-
-	return 0;
-}
-
-void main_set_gamedir(int argc, char *argv[]) {
-	appDirectory = Path::GetDirectoryPath(GetPathFromCmdArg(0));
-
-	if ((loadSaveGameOnStartup != nullptr) && (argv[0] != nullptr)) {
-		// When launched by double-clicking a save game file, the curdir will
-		// be the save game folder unless we correct it
-		Directory::SetCurrentDirectory(appDirectory);
-	} else {
-		// It looks like Allegro library does not like ANSI (ACP) paths.
-		// When *not* working in U_UNICODE filepath mode, whenever it gets
-		// current directory for its own operations, it "fixes" it by
-		// substituting non-ASCII symbols with '^'.
-		// Here we explicitly set current directory to ASCII path.
-		String cur_dir = Directory::GetCurrentDirectory();
-		String path = Path::GetPathInASCII(cur_dir);
-		if (!path.IsEmpty())
-			Directory::SetCurrentDirectory(Path::MakeAbsolutePath(path));
-		else
-			Debug::Printf(kDbgMsg_Error, "Unable to determine current directory: GetPathInASCII failed.\nArg: %s", cur_dir.GetCStr());
-	}
-}
-
-String GetPathFromCmdArg(int arg_index) {
-	if (arg_index < 0 || arg_index >= global_argc)
-		return "";
-	String path = Path::GetCmdLinePathInASCII(global_argv[arg_index], arg_index);
-	if (!path.IsEmpty())
-		return Path::MakeAbsolutePath(path);
-	Debug::Printf(kDbgMsg_Error, "Unable to determine path: GetCmdLinePathInASCII failed.\nCommand line argument %i: %s", arg_index, global_argv[arg_index]);
-	return global_argv[arg_index];
-}
-
-const char *get_allegro_error() {
-	return allegro_error;
-}
-
-const char *set_allegro_error(const char *format, ...) {
-	va_list argptr;
-	va_start(argptr, format);
-	uvszprintf(allegro_error, ALLEGRO_ERROR_SIZE, get_config_text(format), argptr);
-	va_end(argptr);
-	return allegro_error;
-}
-
-int ags_entry_point(int argc, char *argv[]) {
-
-#ifdef AGS_RUN_TESTS
-	Test_DoAllTests();
-#endif
-	main_init(argc, argv);
-
-#if AGS_PLATFORM_OS_WINDOWS
-	setup_malloc_handling();
-#endif
-	debug_flags = 0;
-
-	ConfigTree startup_opts;
-	int res = main_process_cmdline(startup_opts, argc, argv);
-	if (res != 0)
-		return res;
-
-	if (attachToParentConsole)
-		platform->AttachToParentConsole();
-
-	if (justDisplayVersion) {
-		platform->WriteStdOut(get_engine_string());
-		return EXIT_NORMAL;
-	}
-
-	if (justDisplayHelp) {
-		main_print_help();
-		return EXIT_NORMAL;
-	}
-
-	if (!justTellInfo && !hideMessageBoxes)
-		platform->SetGUIMode(true);
-
-	init_debug(startup_opts, justTellInfo);
-	Debug::Printf(kDbgMsg_Alert, get_engine_string());
-
-	main_set_gamedir(argc, argv);
-
-	// Update shell associations and exit
-	if (debug_flags & DBG_REGONLY)
-		exit(EXIT_NORMAL);
-
-#ifdef USE_CUSTOM_EXCEPTION_HANDLER
-	if (usetup.disable_exception_handling)
-#endif
-	{
-		int result = initialize_engine(startup_opts);
-		// TODO: refactor engine shutdown routine (must shutdown and delete everything started and created)
-		allegro_exit();
-		platform->PostAllegroExit();
-		return result;
-	}
-#ifdef USE_CUSTOM_EXCEPTION_HANDLER
-	else {
-		return initialize_engine_with_exception_handling(initialize_engine, startup_opts);
-	}
-#endif
-}
-
-} // namespace AGS3
diff --git a/engines/ags/engine/main/main.h b/engines/ags/engine/main/main.h
index fdc9da0b6a..29e4e44765 100644
--- a/engines/ags/engine/main/main.h
+++ b/engines/ags/engine/main/main.h
@@ -28,41 +28,8 @@
 
 namespace AGS3 {
 
-// Current engine version
-extern AGS::Shared::Version EngineVersion;
-// Lowest savedgame version, accepted by this engine
-extern AGS::Shared::Version SavedgameLowestBackwardCompatVersion;
-// Lowest engine version, which would accept current savedgames
-extern AGS::Shared::Version SavedgameLowestForwardCompatVersion;
-
 //=============================================================================
 
-extern const char **global_argv;
-
-// Location of the engine executable
-extern AGS::Shared::String appDirectory;
-// Game path from the startup options (before reading config)
-extern AGS::Shared::String cmdGameDataPath;
-
-// Startup flags, set from parameters to engine
-extern int force_window;
-extern int override_start_room;
-extern bool justRegisterGame;
-extern bool justUnRegisterGame;
-extern bool justTellInfo;
-extern const char *loadSaveGameOnStartup;
-
-extern int psp_video_framedrop;
-extern int psp_audio_enabled;
-extern int psp_midi_enabled;
-extern int psp_ignore_acsetup_cfg_file;
-extern int psp_clear_cache_on_room_change;
-
-extern int psp_midi_preload_patches;
-extern int psp_audio_cachesize;
-extern char psp_game_file_name[];
-extern char psp_translation[];
-
 void main_print_help();
 
 int ags_entry_point(int argc, char *argv[]);
diff --git a/engines/ags/engine/main/quit.cpp b/engines/ags/engine/main/quit.cpp
index 45a1edcc86..12660e525d 100644
--- a/engines/ags/engine/main/quit.cpp
+++ b/engines/ags/engine/main/quit.cpp
@@ -151,7 +151,7 @@ QuitReason quit_check_for_error_state(const char *&qmsg, String &alertis) {
 			qreason = kQuit_GameError;
 			alertis.Format("An error has occurred. Please contact the game author for support, as this "
 				"is likely to be a scripting error and not a bug in AGS.\n"
-				"(ACI version %s)\n\n", EngineVersion.LongString.GetCStr());
+				"(ACI version %s)\n\n", _G(EngineVersion).LongString.GetCStr());
 		}
 
 		alertis.Append(get_cur_script(5));
@@ -165,13 +165,13 @@ QuitReason quit_check_for_error_state(const char *&qmsg, String &alertis) {
 		qmsg++;
 		alertis.Format("A warning has been generated. This is not normally fatal, but you have selected "
 			"to treat warnings as errors.\n"
-			"(ACI version %s)\n\n%s\n", EngineVersion.LongString.GetCStr(), get_cur_script(5).GetCStr());
+			"(ACI version %s)\n\n%s\n", _G(EngineVersion).LongString.GetCStr(), get_cur_script(5).GetCStr());
 		return kQuit_GameWarning;
 	} else {
 		alertis.Format("An internal error has occurred. Please note down the following information.\n"
 			"If the problem persists, post the details on the AGS Technical Forum.\n"
 			"(ACI version %s)\n"
-			"\nError: ", EngineVersion.LongString.GetCStr());
+			"\nError: ", _G(EngineVersion).LongString.GetCStr());
 		return kQuit_FatalError;
 	}
 }
diff --git a/engines/ags/engine/media/audio/soundcache.cpp b/engines/ags/engine/media/audio/soundcache.cpp
index 37e07e1c50..adf41fa9cd 100644
--- a/engines/ags/engine/media/audio/soundcache.cpp
+++ b/engines/ags/engine/media/audio/soundcache.cpp
@@ -28,6 +28,7 @@
 #include "ags/engine/util/mutex_lock.h"
 #include "ags/shared/util/string.h"
 #include "ags/shared/debugging/out.h"
+#include "ags/engine/globals.h"
 #include "ags/ags.h"
 #include "common/memstream.h"
 
@@ -43,7 +44,7 @@ void clear_sound_cache() {
 
 	if (sound_cache_entries) {
 		int i;
-		for (i = 0; i < psp_audio_cachesize; i++) {
+		for (i = 0; i < _G(psp_audio_cachesize); i++) {
 			if (sound_cache_entries[i].data) {
 				free(sound_cache_entries[i].data);
 				sound_cache_entries[i].data = nullptr;
@@ -53,8 +54,8 @@ void clear_sound_cache() {
 			}
 		}
 	} else {
-		sound_cache_entries = (sound_cache_entry_t *)malloc(psp_audio_cachesize * sizeof(sound_cache_entry_t));
-		memset(sound_cache_entries, 0, psp_audio_cachesize * sizeof(sound_cache_entry_t));
+		sound_cache_entries = (sound_cache_entry_t *)malloc(_G(psp_audio_cachesize) * sizeof(sound_cache_entry_t));
+		memset(sound_cache_entries, 0, _G(psp_audio_cachesize) * sizeof(sound_cache_entry_t));
 	}
 }
 
@@ -65,7 +66,7 @@ void sound_cache_free(char *buffer, bool is_wave) {
 	Debug::Printf("sound_cache_free(%p %d)\n", buffer, (unsigned int)is_wave);
 #endif
 	int i;
-	for (i = 0; i < psp_audio_cachesize; i++) {
+	for (i = 0; i < _G(psp_audio_cachesize); i++) {
 		if (sound_cache_entries[i].data == buffer) {
 			if (sound_cache_entries[i].reference > 0)
 				sound_cache_entries[i].reference--;
@@ -82,7 +83,7 @@ void sound_cache_free(char *buffer, bool is_wave) {
 #endif
 
 	// Sound is uncached
-	if (i == psp_audio_cachesize) {
+	if (i == _G(psp_audio_cachesize)) {
 		if (is_wave)
 			destroy_sample((SAMPLE *)buffer);
 		else
@@ -101,7 +102,7 @@ char *get_cached_sound(const AssetPath &asset_name, bool is_wave, size_t &size)
 	size = 0;
 
 	int i;
-	for (i = 0; i < psp_audio_cachesize; i++) {
+	for (i = 0; i < _G(psp_audio_cachesize); i++) {
 		if (sound_cache_entries[i].data == nullptr)
 			continue;
 
@@ -135,17 +136,17 @@ char *get_cached_sound(const AssetPath &asset_name, bool is_wave, size_t &size)
 	}
 
 	// Find free slot
-	for (i = 0; i < psp_audio_cachesize; i++) {
+	for (i = 0; i < _G(psp_audio_cachesize); i++) {
 		if (sound_cache_entries[i].data == nullptr)
 			break;
 	}
 
 	// No free slot?
-	if (i == psp_audio_cachesize) {
+	if (i == _G(psp_audio_cachesize)) {
 		unsigned int oldest = sound_cache_counter;
 		int index = -1;
 
-		for (i = 0; i < psp_audio_cachesize; i++) {
+		for (i = 0; i < _G(psp_audio_cachesize); i++) {
 			if (sound_cache_entries[i].reference == 0) {
 				if (sound_cache_entries[i].last_used < oldest) {
 					oldest = sound_cache_entries[i].last_used;
diff --git a/engines/ags/engine/media/audio/soundcache.h b/engines/ags/engine/media/audio/soundcache.h
index fa872e3b65..8020d417ce 100644
--- a/engines/ags/engine/media/audio/soundcache.h
+++ b/engines/ags/engine/media/audio/soundcache.h
@@ -45,11 +45,6 @@ typedef struct {
 	bool is_wave;
 } sound_cache_entry_t;
 
-extern int psp_use_sound_cache;
-extern int psp_sound_cache_max_size;
-extern int psp_audio_cachesize;
-extern int psp_midi_preload_patches;
-
 void clear_sound_cache();
 void sound_cache_free(char *buffer, bool is_wave);
 char *get_cached_sound(const AssetPath &asset_name, bool is_wave, size_t &size);
diff --git a/engines/ags/engine/util/library_posix.h b/engines/ags/engine/util/library_posix.h
index a966281fa9..04ab952340 100644
--- a/engines/ags/engine/util/library_posix.h
+++ b/engines/ags/engine/util/library_posix.h
@@ -28,14 +28,13 @@
 #include "ags/shared/util/string.h"
 #include "ags/shared/debugging/out.h"
 #include "ags/engine/plugin/library.h"
+#include "ags/engine/globals.h"
 
 namespace AGS3 {
 
 // FIXME: Replace with a unified way to get the directory which contains the engine binary
 #if AGS_PLATFORM_OS_ANDROID
 extern char android_app_directory[256];
-#else
-extern AGS::Shared::String appDirectory;
 #endif
 
 
@@ -102,7 +101,7 @@ public:
 			sprintf(buffer, "%s%s", android_app_directory, "/lib");
 			_library = dlopen(BuildPath(buffer, libraryName).GetCStr(), RTLD_LAZY);
 #else
-			_library = dlopen(BuildPath(appDirectory, libraryName).GetCStr(), RTLD_LAZY);
+			_library = dlopen(BuildPath(_G(appDirectory), libraryName).GetCStr(), RTLD_LAZY);
 #endif
 
 			AGS::Shared::Debug::Printf("dlopen returned: %s", dlerror());
diff --git a/engines/ags/music.cpp b/engines/ags/music.cpp
index 5b78a24e7b..a3142d8023 100644
--- a/engines/ags/music.cpp
+++ b/engines/ags/music.cpp
@@ -23,6 +23,7 @@
 #include "ags/music.h"
 #include "ags/engine/main/main.h"
 #include "ags/lib/audio/midi.h"
+#include "ags/engine/globals.h"
 #include "audio/midiparser.h"
 
 namespace AGS {
@@ -65,7 +66,7 @@ void Music::sendToChannel(byte channel, uint32 b) {
 
 void Music::playMusic(Common::SeekableReadStream *midi, bool repeat) {
 	if (_isFirstTime) {
-		if (::AGS3::psp_midi_preload_patches)
+		if (_G(psp_midi_preload_patches))
 			::AGS3::load_midi_patches();
 		_isFirstTime = false;
 	}


Commit: f432dc29c2911f68c748e0940af259b44f78764a
    https://github.com/scummvm/scummvm/commit/f432dc29c2911f68c748e0940af259b44f78764a
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Move quit globals into Globals

Changed paths:
    engines/ags/ags.cpp
    engines/ags/engine/globals.h
    engines/ags/engine/main/quit.cpp


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index aca6d6e165..e282601452 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -55,15 +55,13 @@
 #include "ags/shared/util/directory.h"
 #include "ags/shared/util/path.h"
 
+
 #ifdef ENABLE_AGS_TESTS
 #include "ags/tests/test_all.h"
 #endif
 
 namespace AGS3 {
 
-extern char return_to_roomedit[30];
-extern char return_to_room[150];
-
 using namespace Shared;
 using namespace Engine;
 
@@ -149,8 +147,8 @@ static int main_process_cmdline(ConfigTree &cfg, int argc, const char *argv[]) {
 		}
 #endif
 		else if ((scumm_stricmp(arg, "--testre") == 0) && (ee < argc - 2)) {
-			strncpy(return_to_roomedit, argv[ee + 1], 30);
-			strncpy(return_to_room, argv[ee + 2], 150);
+			strncpy(_G(return_to_roomedit), argv[ee + 1], 30);
+			strncpy(_G(return_to_room), argv[ee + 2], 150);
 			ee += 2;
 		} else if (scumm_stricmp(arg, "-noexceptionhandler") == 0) usetup.disable_exception_handling = true;
 		else if (scumm_stricmp(arg, "--setup") == 0) {
diff --git a/engines/ags/engine/globals.h b/engines/ags/engine/globals.h
index b312519049..e8b8b908ea 100644
--- a/engines/ags/engine/globals.h
+++ b/engines/ags/engine/globals.h
@@ -96,6 +96,18 @@ public:
 
 	/**@}*/
 
+	/**
+	 * \defgroup quit globals
+	 * @{
+	 */
+
+	bool _handledErrorInEditor = false;
+	char _return_to_roomedit[30] = "\0";
+	char _return_to_room[150] = "\0";
+	char _quit_message[256] = "\0";
+
+	 /**@}*/
+
 public:
 	Globals();
 	~Globals();
@@ -103,7 +115,12 @@ public:
 
 extern Globals *g_globals;
 
+// Macro for accessing a globals member
 #define _G(FIELD) (::AGS3::g_globals->_##FIELD)
+// Macro for accessing a globals member that was an object in the original,
+// but is a pointer to the object in ScummVM, so that we don't need to
+// provide the full class/struct definition here in the header file
+#define _GP(FIELD) (*::AGS3::g_globals->_##FIELD)
 
 } // namespace AGS3
 
diff --git a/engines/ags/engine/main/quit.cpp b/engines/ags/engine/main/quit.cpp
index 12660e525d..9b33146a00 100644
--- a/engines/ags/engine/main/quit.cpp
+++ b/engines/ags/engine/main/quit.cpp
@@ -69,12 +69,14 @@ extern int need_to_stop_cd;
 extern int use_cdplayer;
 extern IGraphicsDriver *gfxDriver;
 
-bool handledErrorInEditor;
+// TODO: move to test unit
+extern Bitmap *test_allegro_bitmap;
+extern IDriverDependantBitmap *test_allegro_ddb;
 
 void quit_tell_editor_debugger(const String &qmsg, QuitReason qreason) {
 	if (editor_debugging_initialized) {
 		if (qreason & kQuitKind_GameException)
-			handledErrorInEditor = send_exception_to_editor(qmsg);
+			_G(handledErrorInEditor) = send_exception_to_editor(qmsg);
 		send_message_to_editor("EXIT");
 		editor_debugger->Shutdown();
 	}
@@ -179,7 +181,7 @@ QuitReason quit_check_for_error_state(const char *&qmsg, String &alertis) {
 void quit_message_on_exit(const char *qmsg, String &alertis, QuitReason qreason) {
 	// successful exit displays no messages (because Windoze closes the dos-box
 	// if it is empty).
-	if ((qreason & kQuitKind_NormalExit) == 0 && !handledErrorInEditor) {
+	if ((qreason & kQuitKind_NormalExit) == 0 && !_G(handledErrorInEditor)) {
 		// Display the message (at this point the window still exists)
 		sprintf(pexbuf, "%s\n", qmsg);
 		alertis.Append(pexbuf);
@@ -212,18 +214,12 @@ void quit_delete_temp_files() {
 }
 
 // TODO: move to test unit
-extern Bitmap *test_allegro_bitmap;
-extern IDriverDependantBitmap *test_allegro_ddb;
 void allegro_bitmap_test_release() {
 	delete test_allegro_bitmap;
 	if (test_allegro_ddb)
 		gfxDriver->DestroyDDB(test_allegro_ddb);
 }
 
-char return_to_roomedit[30] = "\0";
-char return_to_room[150] = "\0";
-char quit_message[256] = "\0";
-
 // quit - exits the engine, shutting down everything gracefully
 // The parameter is the message to print. If this message begins with
 // an '!' character, then it is printed as a "contact game author" error.
@@ -232,16 +228,16 @@ char quit_message[256] = "\0";
 // error.
 // "!|" is a special code used to mean that the player has aborted (Alt+X)
 void quit(const char *quitmsg) {
-	strncpy(quit_message, quitmsg, 256);
+	strncpy(_G(quit_message), quitmsg, 256);
 	_G(abort_engine) = true;
 }
 
 void quit_free() {
 	String alertis;
-	if (strlen(quit_message) == 0)
-		strcpy(quit_message, "|bye!");
+	if (strlen(_G(quit_message)) == 0)
+		strcpy(_G(quit_message), "|bye!");
 
-	const char *quitmsg = quit_message;
+	const char *quitmsg = _G(quit_message);
 	QuitReason qreason = quit_check_for_error_state(quitmsg, alertis);
 
 	if (qreason & kQuitKind_NormalExit)
@@ -249,9 +245,9 @@ void quit_free() {
 
 	allegro_bitmap_test_release();
 
-	handledErrorInEditor = false;
+	_G(handledErrorInEditor) = false;
 
-	quit_tell_editor_debugger(quit_message, qreason);
+	quit_tell_editor_debugger(_G(quit_message), qreason);
 
 	our_eip = 9900;
 


Commit: 4b40b09ce062fc218a63626b0241976242788856
    https://github.com/scummvm/scummvm/commit/4b40b09ce062fc218a63626b0241976242788856
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Move mouse globals to Globals

Changed paths:
    engines/ags/engine/ac/dialog.cpp
    engines/ags/engine/ac/draw.cpp
    engines/ags/engine/ac/global_game.cpp
    engines/ags/engine/ac/global_inventoryitem.cpp
    engines/ags/engine/ac/gui.cpp
    engines/ags/engine/ac/guicontrol.cpp
    engines/ags/engine/ac/invwindow.cpp
    engines/ags/engine/ac/mouse.cpp
    engines/ags/engine/ac/route_finder_impl_legacy.cpp
    engines/ags/engine/device/mousew32.cpp
    engines/ags/engine/device/mousew32.h
    engines/ags/engine/globals.cpp
    engines/ags/engine/globals.h
    engines/ags/engine/gui/cscidialog.cpp
    engines/ags/engine/gui/mylistbox.cpp
    engines/ags/engine/gui/mypushbutton.cpp
    engines/ags/engine/gui/newcontrol.cpp
    engines/ags/engine/main/engine.cpp
    engines/ags/engine/main/game_run.cpp
    engines/ags/engine/plugin/agsplugin.cpp
    engines/ags/shared/ac/interfaceelement.h
    engines/ags/shared/ac/mousecursor.cpp
    engines/ags/shared/gui/guimain.cpp
    engines/ags/shared/gui/guimain.h


diff --git a/engines/ags/engine/ac/dialog.cpp b/engines/ags/engine/ac/dialog.cpp
index 92c3e0fb45..1bf4e468e9 100644
--- a/engines/ags/engine/ac/dialog.cpp
+++ b/engines/ags/engine/ac/dialog.cpp
@@ -59,11 +59,11 @@
 #include "ags/engine/gfx/graphicsdriver.h"
 #include "ags/engine/ac/mouse.h"
 #include "ags/engine/media/audio/audio_system.h"
-
 #include "ags/shared/debugging/out.h"
 #include "ags/engine/script/script_api.h"
 #include "ags/engine/script/script_runtime.h"
 #include "ags/engine/ac/dynobj/scriptstring.h"
+#include "ags/engine/globals.h"
 
 namespace AGS3 {
 
@@ -872,9 +872,9 @@ bool DialogOptions::Run() {
 	mouseison = -1;
 	if (new_custom_render); // do not automatically detect option under mouse
 	else if (usingCustomRendering) {
-		if ((mousex >= dirtyx) && (mousey >= dirtyy) &&
-		        (mousex < dirtyx + tempScrn->GetWidth()) &&
-		        (mousey < dirtyy + tempScrn->GetHeight())) {
+		if ((_G(mousex) >= dirtyx) && (_G(mousey) >= dirtyy) &&
+		        (_G(mousex) < dirtyx + tempScrn->GetWidth()) &&
+		        (_G(mousey) < dirtyy + tempScrn->GetHeight())) {
 			getDialogOptionUnderCursorFunc.params[0].SetDynamicObject(&ccDialogOptionsRendering, &ccDialogOptionsRendering);
 			run_function_on_non_blocking_thread(&getDialogOptionUnderCursorFunc);
 
@@ -885,11 +885,11 @@ bool DialogOptions::Run() {
 		} else {
 			ccDialogOptionsRendering.activeOptionID = -1;
 		}
-	} else if (mousex >= dialog_abs_x && mousex < (dialog_abs_x + areawid) &&
-	           mousey >= dlgyp && mousey < curyp) {
+	} else if (_G(mousex) >= dialog_abs_x && _G(mousex) < (dialog_abs_x + areawid) &&
+	           _G(mousey) >= dlgyp && _G(mousey) < curyp) {
 		mouseison = numdisp - 1;
 		for (int i = 0; i < numdisp; ++i) {
-			if (mousey < dispyp[i]) {
+			if (_G(mousey) < dispyp[i]) {
 				mouseison = i - 1;
 				break;
 			}
@@ -898,7 +898,7 @@ bool DialogOptions::Run() {
 	}
 
 	if (parserInput != nullptr) {
-		int relativeMousey = mousey;
+		int relativeMousey = _G(mousey);
 		if (usingCustomRendering)
 			relativeMousey -= dirtyy;
 
diff --git a/engines/ags/engine/ac/draw.cpp b/engines/ags/engine/ac/draw.cpp
index d74095bdee..c559768d73 100644
--- a/engines/ags/engine/ac/draw.cpp
+++ b/engines/ags/engine/ac/draw.cpp
@@ -70,6 +70,7 @@
 #include "ags/engine/gfx/blender.h"
 #include "ags/engine/media/audio/audio_system.h"
 #include "ags/engine/ac/game.h"
+#include "ags/engine/globals.h"
 
 namespace AGS3 {
 
@@ -121,7 +122,6 @@ extern int cur_mode, cur_cursor;
 extern int mouse_frame, mouse_delay;
 extern int lastmx, lastmy;
 extern IDriverDependantBitmap *mouseCursor;
-extern int hotx, hoty;
 extern int bg_just_changed;
 
 color palette[256];
@@ -2207,10 +2207,10 @@ void construct_game_screen_overlay(bool draw_mouse) {
 		ags_domouse(DOMOUSE_NOCURSOR);
 		// only on mousemove, and it's not moving
 		if (((game.mcurs[cur_cursor].flags & MCF_ANIMMOVE) != 0) &&
-		        (mousex == lastmx) && (mousey == lastmy));
+		        (_G(mousex) == lastmx) && (_G(mousey) == lastmy));
 		// only on hotspot, and it's not on one
 		else if (((game.mcurs[cur_cursor].flags & MCF_HOTSPOT) != 0) &&
-		         (GetLocationType(game_to_data_coord(mousex), game_to_data_coord(mousey)) == 0))
+		         (GetLocationType(game_to_data_coord(_G(mousex)), game_to_data_coord(_G(mousey))) == 0))
 			set_new_cursor_graphic(game.mcurs[cur_cursor].pic);
 		else if (mouse_delay > 0) mouse_delay--;
 		else {
@@ -2228,16 +2228,16 @@ void construct_game_screen_overlay(bool draw_mouse) {
 			mouse_delay = views[viewnum].loops[loopnum].frames[mouse_frame].speed + 5;
 			CheckViewFrame(viewnum, loopnum, mouse_frame);
 		}
-		lastmx = mousex;
-		lastmy = mousey;
+		lastmx = _G(mousex);
+		lastmy = _G(mousey);
 	}
 
 	ags_domouse(DOMOUSE_NOCURSOR);
 
 	// Stage: mouse cursor
 	if (draw_mouse && !play.mouse_cursor_hidden && play.screen_is_faded_out == 0) {
-		gfxDriver->DrawSprite(mousex - hotx, mousey - hoty, mouseCursor);
-		invalidate_sprite(mousex - hotx, mousey - hoty, mouseCursor, false);
+		gfxDriver->DrawSprite(_G(mousex) - _G(hotx), _G(mousey) - _G(hoty), mouseCursor);
+		invalidate_sprite(_G(mousex) - _G(hotx), _G(mousey) - _G(hoty), mouseCursor, false);
 	}
 
 	if (play.screen_is_faded_out == 0) {
diff --git a/engines/ags/engine/ac/global_game.cpp b/engines/ags/engine/ac/global_game.cpp
index dd195561d8..d1c2fbeb83 100644
--- a/engines/ags/engine/ac/global_game.cpp
+++ b/engines/ags/engine/ac/global_game.cpp
@@ -69,6 +69,7 @@
 #include "ags/engine/main/game_file.h"
 #include "ags/shared/util/string_utils.h"
 #include "ags/engine/media/audio/audio_system.h"
+#include "ags/engine/globals.h"
 
 namespace AGS3 {
 
@@ -520,7 +521,7 @@ int GetLocationType(int xxx, int yyy) {
 void SaveCursorForLocationChange() {
 	// update the current location name
 	char tempo[100];
-	GetLocationName(game_to_data_coord(mousex), game_to_data_coord(mousey), tempo);
+	GetLocationName(game_to_data_coord(_G(mousex)), game_to_data_coord(_G(mousey)), tempo);
 
 	if (play.get_loc_name_save_cursor != play.get_loc_name_last_time) {
 		play.get_loc_name_save_cursor = play.get_loc_name_last_time;
diff --git a/engines/ags/engine/ac/global_inventoryitem.cpp b/engines/ags/engine/ac/global_inventoryitem.cpp
index 4bd15c1eee..baf99555e1 100644
--- a/engines/ags/engine/ac/global_inventoryitem.cpp
+++ b/engines/ags/engine/ac/global_inventoryitem.cpp
@@ -33,6 +33,7 @@
 #include "ags/shared/gui/guiinv.h"
 #include "ags/engine/ac/event.h"
 #include "ags/engine/ac/gamestate.h"
+#include "ags/engine/globals.h"
 
 namespace AGS3 {
 
@@ -40,7 +41,6 @@ using namespace AGS::Shared;
 
 extern GameSetupStruct game;
 extern GameState play;
-extern int mousex, mousey;
 extern int mouse_ifacebut_xoffs, mouse_ifacebut_yoffs;
 extern const char *evblockbasename;
 extern int evblocknum;
@@ -79,17 +79,17 @@ void SetInvItemName(int invi, const char *newName) {
 int GetInvAt(int xxx, int yyy) {
 	int ongui = GetGUIAt(xxx, yyy);
 	if (ongui >= 0) {
-		int mxwas = mousex, mywas = mousey;
-		mousex = data_to_game_coord(xxx) - guis[ongui].X;
-		mousey = data_to_game_coord(yyy) - guis[ongui].Y;
+		int mxwas = _G(mousex), mywas = _G(mousey);
+		_G(mousex) = data_to_game_coord(xxx) - guis[ongui].X;
+		_G(mousey) = data_to_game_coord(yyy) - guis[ongui].Y;
 		int onobj = guis[ongui].FindControlUnderMouse();
 		GUIObject *guio = guis[ongui].GetControl(onobj);
 		if (guio) {
-			mouse_ifacebut_xoffs = mousex - (guio->X);
-			mouse_ifacebut_yoffs = mousey - (guio->Y);
+			mouse_ifacebut_xoffs = _G(mousex) - (guio->X);
+			mouse_ifacebut_yoffs = _G(mousey) - (guio->Y);
 		}
-		mousex = mxwas;
-		mousey = mywas;
+		_G(mousex) = mxwas;
+		_G(mousey) = mywas;
 		if (guio && (guis[ongui].GetControlType(onobj) == kGUIInvWindow))
 			return offset_over_inv((GUIInvWindow *)guio);
 	}
diff --git a/engines/ags/engine/ac/gui.cpp b/engines/ags/engine/ac/gui.cpp
index d52d7cbc82..d76d399ca6 100644
--- a/engines/ags/engine/ac/gui.cpp
+++ b/engines/ags/engine/ac/gui.cpp
@@ -54,10 +54,10 @@
 #include "ags/engine/ac/dynobj/cc_guiobject.h"
 #include "ags/engine/script/runtimescriptvalue.h"
 #include "ags/shared/util/string_compat.h"
-
 #include "ags/shared/debugging/out.h"
 #include "ags/engine/script/script_api.h"
 #include "ags/engine/script/script_runtime.h"
+#include "ags/engine/globals.h"
 
 namespace AGS3 {
 
@@ -304,15 +304,15 @@ void GUI_Click(ScriptGUI *scgui, int mbut) {
 void GUI_ProcessClick(int x, int y, int mbut) {
 	int guiid = gui_get_interactable(x, y);
 	if (guiid >= 0) {
-		const int real_mousex = mousex;
-		const int real_mousey = mousey;
-		mousex = x;
-		mousey = y;
+		const int real_mousex = _G(mousex);
+		const int real_mousey = _G(mousey);
+		_G(mousex) = x;
+		_G(mousey) = y;
 		guis[guiid].Poll();
 		gui_on_mouse_down(guiid, mbut);
 		gui_on_mouse_up(guiid, mbut);
-		mousex = real_mousex;
-		mousey = real_mousey;
+		_G(mousex) = real_mousex;
+		_G(mousey) = real_mousey;
 	}
 }
 
@@ -323,8 +323,8 @@ void remove_popup_interface(int ifacenum) {
 	ifacepopped = -1;
 	UnPauseGame();
 	guis[ifacenum].SetConceal(true);
-	if (mousey <= guis[ifacenum].PopupAtMouseY)
-		Mouse::SetPosition(Point(mousex, guis[ifacenum].PopupAtMouseY + 2));
+	if (_G(mousey) <= guis[ifacenum].PopupAtMouseY)
+		Mouse::SetPosition(Point(_G(mousex), guis[ifacenum].PopupAtMouseY + 2));
 	if ((!IsInterfaceEnabled()) && (cur_cursor == cur_mode))
 		// Only change the mouse cursor if it hasn't been specifically changed first
 		set_mouse_cursor(CURS_WAIT);
@@ -422,7 +422,7 @@ void replace_macro_tokens(const char *text, String &fixed_text) {
 				if (!IsInterfaceEnabled())
 					tempo[0] = 0;
 				else
-					GetLocationName(game_to_data_coord(mousex), game_to_data_coord(mousey), tempo);
+					GetLocationName(game_to_data_coord(_G(mousex)), game_to_data_coord(_G(mousey)), tempo);
 			} else { // not a macro, there's just a @ in the message
 				curptr = curptrWasAt + 1;
 				strcpy(tempo, "@");
@@ -598,7 +598,7 @@ int gui_on_mouse_move() {
 		int ll;
 		for (ll = 0; ll < game.numgui; ll++) {
 			const int guin = play.gui_draw_order[ll];
-			if (guis[guin].IsInteractableAt(mousex, mousey)) mouse_over_gui = guin;
+			if (guis[guin].IsInteractableAt(_G(mousex), _G(mousey))) mouse_over_gui = guin;
 
 			if (guis[guin].PopupStyle != kGUIPopupMouseY) continue;
 			if (is_complete_overlay > 0) break; // interfaces disabled
@@ -608,7 +608,7 @@ int gui_on_mouse_move() {
 			// Don't allow it to be popped up while skipping cutscene
 			if (play.fast_forward) continue;
 
-			if (mousey < guis[guin].PopupAtMouseY) {
+			if (_G(mousey) < guis[guin].PopupAtMouseY) {
 				set_mouse_cursor(CURS_ARROW);
 				guis[guin].SetConceal(false);
 				guis_need_update = 1;
@@ -646,8 +646,8 @@ void gui_on_mouse_up(const int wasongui, const int wasbutdown) {
 		if ((cttype == kGUIButton) || (cttype == kGUISlider) || (cttype == kGUIListBox)) {
 			force_event(EV_IFACECLICK, wasongui, i, wasbutdown);
 		} else if (cttype == kGUIInvWindow) {
-			mouse_ifacebut_xoffs = mousex - (guio->X) - guis[wasongui].X;
-			mouse_ifacebut_yoffs = mousey - (guio->Y) - guis[wasongui].Y;
+			mouse_ifacebut_xoffs = _G(mousex) - (guio->X) - guis[wasongui].X;
+			mouse_ifacebut_yoffs = _G(mousey) - (guio->Y) - guis[wasongui].Y;
 			int iit = offset_over_inv((GUIInvWindow *)guio);
 			if (iit >= 0) {
 				evblocknum = iit;
diff --git a/engines/ags/engine/ac/guicontrol.cpp b/engines/ags/engine/ac/guicontrol.cpp
index eb089b3de4..e198f72c7d 100644
--- a/engines/ags/engine/ac/guicontrol.cpp
+++ b/engines/ags/engine/ac/guicontrol.cpp
@@ -34,10 +34,10 @@
 #include "ags/engine/script/runtimescriptvalue.h"
 #include "ags/engine/ac/dynobj/cc_gui.h"
 #include "ags/engine/ac/dynobj/cc_guiobject.h"
-
 #include "ags/shared/debugging/out.h"
 #include "ags/engine/script/script_api.h"
 #include "ags/engine/script/script_runtime.h"
+#include "ags/engine/globals.h"
 
 namespace AGS3 {
 
@@ -54,12 +54,12 @@ GUIObject *GetGUIControlAtLocation(int xx, int yy) {
 
 	data_to_game_coords(&xx, &yy);
 
-	int oldmousex = mousex, oldmousey = mousey;
-	mousex = xx - guis[guinum].X;
-	mousey = yy - guis[guinum].Y;
+	int oldmousex = _G(mousex), oldmousey = _G(mousey);
+	_G(mousex) = xx - guis[guinum].X;
+	_G(mousey) = yy - guis[guinum].Y;
 	int toret = guis[guinum].FindControlUnderMouse(0, false);
-	mousex = oldmousex;
-	mousey = oldmousey;
+	_G(mousex) = oldmousex;
+	_G(mousey) = oldmousey;
 	if (toret < 0)
 		return nullptr;
 
diff --git a/engines/ags/engine/ac/invwindow.cpp b/engines/ags/engine/ac/invwindow.cpp
index 208666888d..a0a336d2e3 100644
--- a/engines/ags/engine/ac/invwindow.cpp
+++ b/engines/ags/engine/ac/invwindow.cpp
@@ -44,10 +44,10 @@
 #include "ags/shared/util/math.h"
 #include "ags/engine/media/audio/audio_system.h"
 #include "ags/engine/ac/timer.h"
-
 #include "ags/shared/debugging/out.h"
 #include "ags/engine/script/script_api.h"
 #include "ags/engine/script/script_runtime.h"
+#include "ags/engine/globals.h"
 
 namespace AGS3 {
 
@@ -59,7 +59,6 @@ extern CharacterExtras *charextra;
 extern ScriptInvItem scrInv[MAX_INV];
 extern int mouse_ifacebut_xoffs, mouse_ifacebut_yoffs;
 extern SpriteCache spriteset;
-extern int mousex, mousey;
 extern int evblocknum;
 extern CharacterInfo *playerchar;
 extern AGSPlatformDriver *platform;
@@ -366,8 +365,8 @@ bool InventoryScreen::Run() {
 	refresh_gui_screen();
 
 	// NOTE: this is because old code was working with full game screen
-	const int mouseX = AGS3::mousex - windowxp;
-	const int mouseY = AGS3::mousey - windowyp;
+	const int mouseX = _G(mousex) - windowxp;
+	const int mouseY = _G(mousey) - windowyp;
 
 	int isonitem = ((mouseY - bartop) / highest) * ICONSPERLINE + (mouseX - barxp) / widest;
 	if (mouseY <= bartop) isonitem = -1;
diff --git a/engines/ags/engine/ac/mouse.cpp b/engines/ags/engine/ac/mouse.cpp
index c6780c73d3..8d12af0650 100644
--- a/engines/ags/engine/ac/mouse.cpp
+++ b/engines/ags/engine/ac/mouse.cpp
@@ -41,11 +41,11 @@
 #include "ags/shared/ac/spritecache.h"
 #include "ags/engine/gfx/graphicsdriver.h"
 #include "ags/engine/gfx/gfxfilter.h"
-
 #include "ags/shared/debugging/out.h"
 #include "ags/engine/script/script_api.h"
 #include "ags/engine/script/script_runtime.h"
 #include "ags/engine/ac/global_game.h"
+#include "ags/engine/globals.h"
 
 namespace AGS3 {
 
@@ -55,7 +55,6 @@ using namespace AGS::Engine;
 extern GameSetupStruct game;
 extern GameState play;
 extern ScriptSystem scsystem;
-extern Bitmap *mousecurs[MAXCURSORS];
 extern SpriteCache spriteset;
 extern CharacterInfo *playerchar;
 extern IGraphicsDriver *gfxDriver;
@@ -143,7 +142,7 @@ void set_mouse_cursor(int newcurs) {
 		((game.hotdot > 0) || (game.invhotdotsprite > 0))) {
 		// If necessary, create a copy of the cursor and put the hotspot
 		// dot onto it
-		dotted_mouse_cursor = BitmapHelper::CreateBitmapCopy(mousecurs[0]);
+		dotted_mouse_cursor = BitmapHelper::CreateBitmapCopy(_G(mousecurs)[0]);
 
 		if (game.invhotdotsprite > 0) {
 			draw_sprite_slot_support_alpha(dotted_mouse_cursor,
@@ -163,7 +162,7 @@ void set_mouse_cursor(int newcurs) {
 				putpixel_compensate(dotted_mouse_cursor, hotspotx, hotspoty - get_fixed_pixel_size(1), outercol);
 			}
 		}
-		mousecurs[0] = dotted_mouse_cursor;
+		_G(mousecurs)[0] = dotted_mouse_cursor;
 		update_cached_mouse_cursor();
 	}
 }
@@ -287,8 +286,8 @@ void disable_cursor_mode(int modd) {
 
 void RefreshMouse() {
 	ags_domouse(DOMOUSE_NOCURSOR);
-	scmouse.x = game_to_data_coord(mousex);
-	scmouse.y = game_to_data_coord(mousey);
+	scmouse.x = game_to_data_coord(_G(mousex));
+	scmouse.y = game_to_data_coord(_G(mousey));
 }
 
 void SetMousePosition(int newx, int newy) {
@@ -353,8 +352,8 @@ int GetMouseCursor() {
 }
 
 void update_script_mouse_coords() {
-	scmouse.x = game_to_data_coord(mousex);
-	scmouse.y = game_to_data_coord(mousey);
+	scmouse.x = game_to_data_coord(_G(mousex));
+	scmouse.y = game_to_data_coord(_G(mousey));
 }
 
 void update_inv_cursor(int invnum) {
@@ -384,19 +383,19 @@ void update_inv_cursor(int invnum) {
 void update_cached_mouse_cursor() {
 	if (mouseCursor != nullptr)
 		gfxDriver->DestroyDDB(mouseCursor);
-	mouseCursor = gfxDriver->CreateDDBFromBitmap(mousecurs[0], alpha_blend_cursor != 0);
+	mouseCursor = gfxDriver->CreateDDBFromBitmap(_G(mousecurs)[0], alpha_blend_cursor != 0);
 }
 
 void set_new_cursor_graphic(int spriteslot) {
-	mousecurs[0] = spriteset[spriteslot];
+	_G(mousecurs)[0] = spriteset[spriteslot];
 
 	// It looks like spriteslot 0 can be used in games with version 2.72 and lower.
 	// The NULL check should ensure that the sprite is valid anyway.
-	if (((spriteslot < 1) && (loaded_game_file_version > kGameVersion_272)) || (mousecurs[0] == nullptr)) {
+	if (((spriteslot < 1) && (loaded_game_file_version > kGameVersion_272)) || (_G(mousecurs)[0] == nullptr)) {
 		if (blank_mouse_cursor == nullptr) {
 			blank_mouse_cursor = BitmapHelper::CreateTransparentBitmap(1, 1, game.GetColorDepth());
 		}
-		mousecurs[0] = blank_mouse_cursor;
+		_G(mousecurs)[0] = blank_mouse_cursor;
 	}
 
 	if (game.SpriteInfos[spriteslot].Flags & SPF_ALPHACHANNEL)
diff --git a/engines/ags/engine/ac/route_finder_impl_legacy.cpp b/engines/ags/engine/ac/route_finder_impl_legacy.cpp
index b0d6782ffd..9b662526e3 100644
--- a/engines/ags/engine/ac/route_finder_impl_legacy.cpp
+++ b/engines/ags/engine/ac/route_finder_impl_legacy.cpp
@@ -51,7 +51,7 @@ namespace BitmapHelper = AGS::Shared::BitmapHelper;
 // #define DEBUG_PATHFINDER
 
 #ifdef DEBUG_PATHFINDER
-// extern Bitmap *mousecurs[10];
+// extern Bitmap *_G(mousecurs)[10];
 #endif
 
 namespace AGS {
@@ -294,7 +294,7 @@ static int try_this_square(int srcx, int srcy, int tox, int toy) {
 	}
 
 #ifdef DEBUG_PATHFINDER
-	// wputblock(lastcx, lastcy, mousecurs[C_CROSS], 1);
+	// wputblock(lastcx, lastcy, _G(mousecurs)[C_CROSS], 1);
 #endif
 
 	int trydir = DIR_UP;
diff --git a/engines/ags/engine/device/mousew32.cpp b/engines/ags/engine/device/mousew32.cpp
index 16e65d813b..ed4497d51d 100644
--- a/engines/ags/engine/device/mousew32.cpp
+++ b/engines/ags/engine/device/mousew32.cpp
@@ -56,6 +56,7 @@
 #include "ags/engine/main/graphics_mode.h"
 #include "ags/engine/platform/base/agsplatformdriver.h"
 #include "ags/shared/util/math.h"
+#include "ags/engine/globals.h"
 #if AGS_SIMULATE_RIGHT_CLICK
 #include "ags/shared/ac/sys_events.h" // j for ags_iskeypressed
 #endif
@@ -65,25 +66,15 @@ namespace AGS3 {
 using namespace AGS::Shared;
 using namespace AGS::Engine;
 
+const int NONE = -1, LEFT = 0, RIGHT = 1, MIDDLE = 2;
 
 extern char lib_file_name[13];
-
-const char *mouselibcopyr = "MouseLib32 (c) 1994, 1998 Chris Jones";
-const int NONE = -1, LEFT = 0, RIGHT = 1, MIDDLE = 2;
-char currentcursor = 0;
-// virtual mouse cursor coordinates
-int mousex = 0, mousey = 0, numcurso = -1, hotx = 0, hoty = 0;
-// real mouse coordinates and bounds
-int real_mouse_x = 0, real_mouse_y = 0;
-int boundx1 = 0, boundx2 = 99999, boundy1 = 0, boundy2 = 99999;
-int disable_mgetgraphpos = 0;
-char ignore_bounds = 0;
 extern char alpha_blend_cursor;
-Bitmap *mousecurs[MAXCURSORS];
 extern color palette[256];
 extern volatile bool switched_away;
 
 namespace Mouse {
+
 // Tells whether mouse was locked to the game window
 bool LockedToWindow = false;
 
@@ -114,14 +105,14 @@ void mgraphconfine(int x1, int y1, int x2, int y2) {
 
 void mgetgraphpos() {
 	poll_mouse();
-	if (disable_mgetgraphpos) {
+	if (_G(disable_mgetgraphpos)) {
 		// The cursor coordinates are provided from alternate source;
 		// in this case we completely ignore actual cursor movement.
-		if (!ignore_bounds &&
-			(mousex < boundx1 || mousey < boundy1 || mousex > boundx2 || mousey > boundy2)) {
-			mousex = Math::Clamp(mousex, boundx1, boundx2);
-			mousey = Math::Clamp(mousey, boundy1, boundy2);
-			msetgraphpos(mousex, mousey);
+		if (!_G(ignore_bounds) &&
+			(_G(mousex) < _G(boundx1) || _G(mousey) < _G(boundy1) || _G(mousex) > _G(boundx2) || _G(mousey) > _G(boundy2))) {
+			_G(mousex) = Math::Clamp(_G(mousex), _G(boundx1), _G(boundx2));
+			_G(mousey) = Math::Clamp(_G(mousey), _G(boundy1), _G(boundy2));
+			msetgraphpos(_G(mousex), _G(mousey));
 		}
 		return;
 	}
@@ -141,55 +132,55 @@ void mgetgraphpos() {
 		//---------------------------------------------------------------------
 		// If the real cursor is inside the control rectangle (read - game window),
 		// then apply sensitivity factors and adjust real cursor position
-		if (Mouse::ControlRect.IsInside(real_mouse_x + dx, real_mouse_y + dy)) {
-			real_mouse_x += dx;
-			real_mouse_y += dy;
-			position_mouse(real_mouse_x, real_mouse_y);
+		if (Mouse::ControlRect.IsInside(_G(real_mouse_x) + dx, _G(real_mouse_y) + dy)) {
+			_G(real_mouse_x) += dx;
+			_G(real_mouse_y) += dy;
+			position_mouse(_G(real_mouse_x), _G(real_mouse_y));
 		}
 		// Otherwise, if real cursor was moved outside the control rect, yet we
 		// are required to confine cursor inside one, then adjust cursor position
 		// to stay inside the rect's bounds.
 		else if (Mouse::ConfineInCtrlRect) {
-			real_mouse_x = Math::Clamp(real_mouse_x + dx, Mouse::ControlRect.Left, Mouse::ControlRect.Right);
-			real_mouse_y = Math::Clamp(real_mouse_y + dy, Mouse::ControlRect.Top, Mouse::ControlRect.Bottom);
-			position_mouse(real_mouse_x, real_mouse_y);
+			_G(real_mouse_x) = Math::Clamp(_G(real_mouse_x) + dx, Mouse::ControlRect.Left, Mouse::ControlRect.Right);
+			_G(real_mouse_y) = Math::Clamp(_G(real_mouse_y) + dy, Mouse::ControlRect.Top, Mouse::ControlRect.Bottom);
+			position_mouse(_G(real_mouse_x), _G(real_mouse_y));
 		}
 		// Lastly, if the real cursor is out of the control rect, simply add
 		// actual movement to keep up with the system cursor coordinates.
 		else {
-			real_mouse_x += mickey_x;
-			real_mouse_y += mickey_y;
+			_G(real_mouse_x) += mickey_x;
+			_G(real_mouse_y) += mickey_y;
 		}
 
 		// Do not update the game cursor if the real cursor is beyond the control rect
-		if (!Mouse::ControlRect.IsInside(real_mouse_x, real_mouse_y))
+		if (!Mouse::ControlRect.IsInside(_G(real_mouse_x), _G(real_mouse_y)))
 			return;
 	} else {
 		// Save real cursor coordinates provided by system
-		real_mouse_x = mouse_x;
-		real_mouse_y = mouse_y;
+		_G(real_mouse_x) = mouse_x;
+		_G(real_mouse_y) = mouse_y;
 	}
 
 	// Set new in-game cursor position
-	mousex = real_mouse_x;
-	mousey = real_mouse_y;
-
-	if (!ignore_bounds &&
-		(mousex < boundx1 || mousey < boundy1 || mousex > boundx2 || mousey > boundy2)) {
-		mousex = Math::Clamp(mousex, boundx1, boundx2);
-		mousey = Math::Clamp(mousey, boundy1, boundy2);
-		msetgraphpos(mousex, mousey);
+	_G(mousex) = _G(real_mouse_x);
+	_G(mousey) = _G(real_mouse_y);
+
+	if (!_G(ignore_bounds) &&
+		(_G(mousex) < _G(boundx1) || _G(mousey) < _G(boundy1) || _G(mousex) > _G(boundx2) || _G(mousey) > _G(boundy2))) {
+		_G(mousex) = Math::Clamp(_G(mousex), _G(boundx1), _G(boundx2));
+		_G(mousey) = Math::Clamp(_G(mousey), _G(boundy1), _G(boundy2));
+		msetgraphpos(_G(mousex), _G(mousey));
 	}
 
 	// Convert to virtual coordinates
-	Mouse::AdjustPosition(mousex, mousey);
+	Mouse::AdjustPosition(_G(mousex), _G(mousey));
 }
 
 void msetcursorlimit(int x1, int y1, int x2, int y2) {
-	boundx1 = x1;
-	boundy1 = y1;
-	boundx2 = x2;
-	boundy2 = y2;
+	_G(boundx1) = x1;
+	_G(boundy1) = y1;
+	_G(boundx2) = x2;
+	_G(boundy2) = y2;
 }
 
 int hotxwas = 0, hotywas = 0;
@@ -198,37 +189,37 @@ void domouse(int str) {
 	   TO USE THIS ROUTINE YOU MUST LOAD A MOUSE CURSOR USING mloadcursor.
 	   YOU MUST ALSO REMEMBER TO CALL mfreemem AT THE END OF THE PROGRAM.
 	*/
-	int poow = mousecurs[(int)currentcursor]->GetWidth();
-	int pooh = mousecurs[(int)currentcursor]->GetHeight();
-	//int smx = mousex - hotxwas, smy = mousey - hotywas;
+	int poow = _G(mousecurs)[(int)_G(currentcursor)]->GetWidth();
+	int pooh = _G(mousecurs)[(int)_G(currentcursor)]->GetHeight();
+	//int smx = _G(mousex) - hotxwas, smy = _G(mousey) - hotywas;
 	const Rect &viewport = play.GetMainViewport();
 
 	mgetgraphpos();
-	mousex -= hotx;
-	mousey -= hoty;
+	_G(mousex) -= _G(hotx);
+	_G(mousey) -= _G(hoty);
 
-	if (mousex + poow >= viewport.GetWidth())
-		poow = viewport.GetWidth() - mousex;
+	if (_G(mousex) + poow >= viewport.GetWidth())
+		poow = viewport.GetWidth() - _G(mousex);
 
-	if (mousey + pooh >= viewport.GetHeight())
-		pooh = viewport.GetHeight() - mousey;
+	if (_G(mousey) + pooh >= viewport.GetHeight())
+		pooh = viewport.GetHeight() - _G(mousey);
 
-	mousex += hotx;
-	mousey += hoty;
-	hotxwas = hotx;
-	hotywas = hoty;
+	_G(mousex) += _G(hotx);
+	_G(mousey) += _G(hoty);
+	hotxwas = _G(hotx);
+	hotywas = _G(hoty);
 }
 
 int ismouseinbox(int lf, int tp, int rt, int bt) {
-	if ((mousex >= lf) & (mousex <= rt) & (mousey >= tp) & (mousey <= bt))
+	if ((_G(mousex) >= lf) & (_G(mousex) <= rt) & (_G(mousey) >= tp) & (_G(mousey) <= bt))
 		return TRUE;
 	else
 		return FALSE;
 }
 
 void mfreemem() {
-	for (int re = 0; re < numcurso; re++) {
-		delete mousecurs[re];
+	for (int re = 0; re < _G(numcurso); re++) {
+		delete _G(mousecurs)[re];
 	}
 }
 
@@ -237,7 +228,7 @@ void mfreemem() {
 
 void mloadwcursor(char *namm) {
 	color dummypal[256];
-	if (wloadsprites(&dummypal[0], namm, mousecurs, 0, MAXCURSORS)) {
+	if (wloadsprites(&dummypal[0], namm, _G(mousecurs), 0, MAXCURSORS)) {
 		error("mloadwcursor: Error reading mouse cursor file");
 	}
 }
@@ -277,14 +268,14 @@ int misbuttondown(int buno) {
 }
 
 void msetgraphpos(int xa, int ya) {
-	real_mouse_x = xa;
-	real_mouse_y = ya;
-	position_mouse(real_mouse_x, real_mouse_y);
+	_G(real_mouse_x) = xa;
+	_G(real_mouse_y) = ya;
+	position_mouse(_G(real_mouse_x), _G(real_mouse_y));
 }
 
 void msethotspot(int xx, int yy) {
-	hotx = xx;  // mousex -= hotx; mousey -= hoty;
-	hoty = yy;  // mousex += hotx; mousey += hoty;
+	_G(hotx) = xx;  // _G(mousex) -= _G(hotx); _G(mousey) -= _G(hoty);
+	_G(hoty) = yy;  // _G(mousex) += _G(hotx); _G(mousey) += _G(hoty);
 }
 
 int minstalled() {
diff --git a/engines/ags/engine/device/mousew32.h b/engines/ags/engine/device/mousew32.h
index 87185517de..4cee33c6fb 100644
--- a/engines/ags/engine/device/mousew32.h
+++ b/engines/ags/engine/device/mousew32.h
@@ -32,9 +32,6 @@
 //=============================================================================
 
 #include "ags/shared/util/geometry.h"
-
-#define MAXCURSORS 20
-
 #include "ags/shared/util/geometry.h"
 
 namespace AGS3 {
@@ -98,13 +95,4 @@ void SetMoveLimit(const Rect &r);
 void SetPosition(const Point p);
 
 } // namespace Mouse
-
-
-extern int mousex, mousey;
-extern int hotx, hoty;
-extern int disable_mgetgraphpos;
-extern char currentcursor;
-
-extern Shared::Bitmap *mousecurs[MAXCURSORS];
-
 } // namespace AGS3
diff --git a/engines/ags/engine/globals.cpp b/engines/ags/engine/globals.cpp
index cd161a794e..88b516c91a 100644
--- a/engines/ags/engine/globals.cpp
+++ b/engines/ags/engine/globals.cpp
@@ -28,6 +28,8 @@ Globals *g_globals;
 
 Globals::Globals() {
 	g_globals = this;
+
+	Common::fill(&_mousecurs[0], &_mousecurs[MAXCURSORS], nullptr);
 }
 
 Globals::~Globals() {
diff --git a/engines/ags/engine/globals.h b/engines/ags/engine/globals.h
index e8b8b908ea..b13038e84f 100644
--- a/engines/ags/engine/globals.h
+++ b/engines/ags/engine/globals.h
@@ -29,9 +29,17 @@
 
 namespace AGS3 {
 
+#define MAXCURSORS 20
+
 using String = AGS::Shared::String;
 using Version = AGS::Shared::Version;
 
+namespace AGS {
+namespace Shared {
+class Bitmap;
+} // namespace Shared
+} // namespace AGS
+
 class Globals {
 public:
 	/**
@@ -96,6 +104,23 @@ public:
 
 	/**@}*/
 
+	/**
+	 * \defgroup mouse globals
+	 * @{
+	 */
+
+	char _currentcursor = 0;
+	// virtual mouse cursor coordinates
+	int _mousex = 0, _mousey = 0, _numcurso = -1, _hotx = 0, _hoty = 0;
+	// real mouse coordinates and bounds
+	int _real_mouse_x = 0, _real_mouse_y = 0;
+	int _boundx1 = 0, _boundx2 = 99999, _boundy1 = 0, _boundy2 = 99999;
+	int _disable_mgetgraphpos = 0;
+	char _ignore_bounds = 0;
+	AGS::Shared::Bitmap *_mousecurs[MAXCURSORS];
+
+	/**@}*/
+
 	/**
 	 * \defgroup quit globals
 	 * @{
diff --git a/engines/ags/engine/gui/cscidialog.cpp b/engines/ags/engine/gui/cscidialog.cpp
index 25f4c7db18..5f26837c58 100644
--- a/engines/ags/engine/gui/cscidialog.cpp
+++ b/engines/ags/engine/gui/cscidialog.cpp
@@ -42,13 +42,13 @@
 #include "ags/engine/media/audio/audio_system.h"
 #include "ags/engine/platform/base/agsplatformdriver.h"
 #include "ags/engine/ac/timer.h"
+#include "ags/engine/globals.h"
 
 namespace AGS3 {
 
 using AGS::Shared::Bitmap;
 namespace BitmapHelper = AGS::Shared::BitmapHelper;
 
-extern char ignore_bounds; // from mousew32
 extern IGraphicsDriver *gfxDriver;
 extern GameSetup usetup;
 
@@ -97,7 +97,7 @@ int CSCIGetVersion() {
 int windowcount = 0, curswas = 0;
 int win_x = 0, win_y = 0, win_width = 0, win_height = 0;
 int CSCIDrawWindow(int xx, int yy, int wid, int hit) {
-	ignore_bounds++;
+	_G(ignore_bounds)++;
 	multiply_up(&xx, &yy, &wid, &hit);
 	int drawit = -1;
 	for (int aa = 0; aa < MAXSCREENWINDOWS; aa++) {
@@ -133,7 +133,7 @@ int CSCIDrawWindow(int xx, int yy, int wid, int hit) {
 
 void CSCIEraseWindow(int handl) {
 	//  ags_domouse(DOMOUSE_DISABLE);
-	ignore_bounds--;
+	_G(ignore_bounds)--;
 	topwindowhandle = oswi[handl].oldtop;
 	oswi[handl].handle = -1;
 	//  ags_domouse(DOMOUSE_ENABLE);
@@ -275,8 +275,8 @@ void multiply_up(int *x1, int *y1, int *x2, int *y2) {
 
 int checkcontrols() {
 	// NOTE: this is because old code was working with full game screen
-	const int mouseX = AGS3::mousex - win_x;
-	const int mouseY = AGS3::mousey - win_y;
+	const int mouseX = _G(mousex) - win_x;
+	const int mouseY = _G(mousey) - win_y;
 
 	smcode = 0;
 	for (int kk = 0; kk < MAXCONTROLS; kk++) {
diff --git a/engines/ags/engine/gui/mylistbox.cpp b/engines/ags/engine/gui/mylistbox.cpp
index 339cabce10..c0e77e92da 100644
--- a/engines/ags/engine/gui/mylistbox.cpp
+++ b/engines/ags/engine/gui/mylistbox.cpp
@@ -29,14 +29,13 @@
 #include "ags/engine/gui/guidialog.h"
 #include "ags/engine/gui/guidialoginternaldefs.h"
 #include "ags/engine/gui/mylistbox.h"
+#include "ags/engine/globals.h"
 
 namespace AGS3 {
 
 using AGS::Shared::Bitmap;
 
 extern GameSetup usetup;
-extern int numcurso, hotx, hoty;
-
 extern int windowbackgroundcolor;
 extern int cbuttfont;
 extern int smcode;
@@ -111,14 +110,14 @@ void MyListBox::draw(Bitmap *ds) {
 }
 
 int MyListBox::pressedon(int mousex, int mousey) {
-	if (mousex > x + wid - ARROWWIDTH) {
-		if ((mousey - y < hit / 2) & (topitem > 0))
+	if (_G(mousex) > x + wid - ARROWWIDTH) {
+		if ((_G(mousey) - y < hit / 2) & (topitem > 0))
 			topitem--;
-		else if ((mousey - y > hit / 2) &(topitem + numonscreen < items))
+		else if ((_G(mousey) - y > hit / 2) &(topitem + numonscreen < items))
 			topitem++;
 
 	} else {
-		selected = ((mousey - y) - 2) / TEXT_HT + topitem;
+		selected = ((_G(mousey) - y) - 2) / TEXT_HT + topitem;
 		if (selected >= items)
 			selected = items - 1;
 
diff --git a/engines/ags/engine/gui/mypushbutton.cpp b/engines/ags/engine/gui/mypushbutton.cpp
index b5bb5a5da7..f4dcc4c86b 100644
--- a/engines/ags/engine/gui/mypushbutton.cpp
+++ b/engines/ags/engine/gui/mypushbutton.cpp
@@ -32,6 +32,7 @@
 #include "ags/shared/gfx/bitmap.h"
 #include "ags/engine/platform/base/agsplatformdriver.h"
 #include "ags/engine/ac/timer.h"
+#include "ags/engine/globals.h"
 
 namespace AGS3 {
 
@@ -85,7 +86,7 @@ int MyPushButton::pressedon(int mousex, int mousey) {
 	while (mbutrelease(LEFT) == 0) {
 
 		wasstat = state;
-		state = mouseisinarea(mousex, mousey);
+		state = mouseisinarea(_G(mousex), _G(mousey));
 		// stop mp3 skipping if button held down
 		update_polled_stuff_if_runtime();
 		if (wasstat != state) {
diff --git a/engines/ags/engine/gui/newcontrol.cpp b/engines/ags/engine/gui/newcontrol.cpp
index f17d444ed4..d709adf82b 100644
--- a/engines/ags/engine/gui/newcontrol.cpp
+++ b/engines/ags/engine/gui/newcontrol.cpp
@@ -23,6 +23,7 @@
 #include "ags/engine/gui/newcontrol.h"
 #include "ags/engine/gui/guidialog.h"
 #include "ags/engine/gui/guidialoginternaldefs.h"
+#include "ags/engine/globals.h"
 
 namespace AGS3 {
 
@@ -55,7 +56,7 @@ int NewControl::mouseisinarea(int mousex, int mousey) {
 	if (topwindowhandle != wlevel)
 		return 0;
 
-	if ((mousex > x) &(mousex < x + wid) &(mousey > y) &(mousey < y + hit))
+	if ((_G(mousex) > x) &(_G(mousex) < x + wid) &(_G(mousey) > y) &(_G(mousey) < y + hit))
 		return 1;
 
 	return 0;
diff --git a/engines/ags/engine/main/engine.cpp b/engines/ags/engine/main/engine.cpp
index 7e0df18447..fb157b5fa4 100644
--- a/engines/ags/engine/main/engine.cpp
+++ b/engines/ags/engine/main/engine.cpp
@@ -810,7 +810,7 @@ void engine_init_game_settings() {
 	}
 
 	for (ee = 0; ee < game.numcursors; ee++) {
-		// The cursor graphics are assigned to mousecurs[] and so cannot
+		// The cursor graphics are assigned to _G(mousecurs)[] and so cannot
 		// be removed from memory
 		if (game.mcurs[ee].pic >= 0)
 			spriteset.Precache(game.mcurs[ee].pic);
@@ -1039,9 +1039,9 @@ void engine_init_game_settings() {
 	update_invorder();
 	displayed_room = -10;
 
-	currentcursor = 0;
+	_G(currentcursor) = 0;
 	our_eip = -4;
-	mousey = 100; // stop icon bar popping up
+	_G(mousey) = 100; // stop icon bar popping up
 
 	// We use same variable to read config and be used at runtime for now,
 	// so update it here with regards to game design option
diff --git a/engines/ags/engine/main/game_run.cpp b/engines/ags/engine/main/game_run.cpp
index 173e3dd998..3441ed99d1 100644
--- a/engines/ags/engine/main/game_run.cpp
+++ b/engines/ags/engine/main/game_run.cpp
@@ -227,7 +227,7 @@ static void check_mouse_controls() {
 	mongu = gui_on_mouse_move();
 
 	mouse_on_iface = mongu;
-	if ((ifacepopped >= 0) && (mousey >= guis[ifacepopped].Y + guis[ifacepopped].Height))
+	if ((ifacepopped >= 0) && (_G(mousey) >= guis[ifacepopped].Y + guis[ifacepopped].Height))
 		remove_popup_interface(ifacepopped);
 
 	// check mouse clicks on GUIs
@@ -621,7 +621,7 @@ static void game_loop_update_animated_buttons() {
 
 static void game_loop_do_render_and_check_mouse(IDriverDependantBitmap *extraBitmap, int extraX, int extraY) {
 	if (!play.fast_forward) {
-		int mwasatx = mousex, mwasaty = mousey;
+		int mwasatx = _G(mousex), mwasaty = _G(mousey);
 
 		// Only do this if we are not skipping a cutscene
 		render_graphics(extraBitmap, extraX, extraY);
@@ -632,7 +632,7 @@ static void game_loop_do_render_and_check_mouse(IDriverDependantBitmap *extraBit
 		// TODO: if we support rotation then we also need to compare full transform!
 		if (displayed_room < 0)
 			return;
-		auto view = play.GetRoomViewportAt(mousex, mousey);
+		auto view = play.GetRoomViewportAt(_G(mousex), _G(mousey));
 		auto cam = view ? view->GetCamera() : nullptr;
 		if (cam) {
 			// NOTE: all cameras are in same room right now, so their positions are in same coordinate system;
@@ -641,10 +641,10 @@ static void game_loop_do_render_and_check_mouse(IDriverDependantBitmap *extraBit
 			int offsetx = cam->GetRect().Left;
 			int offsety = cam->GetRect().Top;
 
-			if (((mwasatx != mousex) || (mwasaty != mousey) ||
+			if (((mwasatx != _G(mousex)) || (mwasaty != _G(mousey)) ||
 				(offsetxWas != offsetx) || (offsetyWas != offsety))) {
 				// mouse moves over hotspot
-				if (__GetLocationType(game_to_data_coord(mousex), game_to_data_coord(mousey), 1) == LOCTYPE_HOTSPOT) {
+				if (__GetLocationType(game_to_data_coord(_G(mousex)), game_to_data_coord(_G(mousey)), 1) == LOCTYPE_HOTSPOT) {
 					int onhs = getloctype_index;
 
 					setevent(EV_RUNEVBLOCK, EVB_HOTSPOT, onhs, 6);
@@ -813,7 +813,7 @@ static void UpdateMouseOverLocation() {
 	// Call GetLocationName - it will internally force a GUI refresh
 	// if the result it returns has changed from last time
 	char tempo[STD_BUFFER_SIZE];
-	GetLocationName(game_to_data_coord(mousex), game_to_data_coord(mousey), tempo);
+	GetLocationName(game_to_data_coord(_G(mousex)), game_to_data_coord(_G(mousey)), tempo);
 
 	if ((play.get_loc_name_save_cursor >= 0) &&
 		(play.get_loc_name_save_cursor != play.get_loc_name_last_time) &&
diff --git a/engines/ags/engine/plugin/agsplugin.cpp b/engines/ags/engine/plugin/agsplugin.cpp
index 7844c2e24c..9ef1f677cc 100644
--- a/engines/ags/engine/plugin/agsplugin.cpp
+++ b/engines/ags/engine/plugin/agsplugin.cpp
@@ -74,6 +74,7 @@
 #include "ags/shared/util/filestream.h"
 #include "ags/engine/media/audio/audio_system.h"
 #include "ags/engine/util/library.h"
+#include "ags/engine/globals.h"
 
 #if defined(BUILTIN_PLUGINS)
 #include "ags/shared/../Plugins/AGSflashlight/agsflashlight.h"
@@ -93,7 +94,6 @@ using namespace AGS::Shared::Memory;
 using namespace AGS::Engine;
 
 extern IGraphicsDriver *gfxDriver;
-extern int mousex, mousey;
 extern int displayed_room;
 extern RoomStruct thisroom;
 extern GameSetupStruct game;
@@ -290,8 +290,8 @@ void IAGSEngine::ReleaseBitmapSurface(BITMAP *bmp) {
 }
 
 void IAGSEngine::GetMousePosition(int32 *x, int32 *y) {
-	if (x) x[0] = mousex;
-	if (y) y[0] = mousey;
+	if (x) x[0] = _G(mousex);
+	if (y) y[0] = _G(mousey);
 }
 int IAGSEngine::GetCurrentRoom() {
 	return displayed_room;
diff --git a/engines/ags/shared/ac/interfaceelement.h b/engines/ags/shared/ac/interfaceelement.h
index 69f8fcaa02..a07a316cbf 100644
--- a/engines/ags/shared/ac/interfaceelement.h
+++ b/engines/ags/shared/ac/interfaceelement.h
@@ -37,7 +37,7 @@ struct InterfaceElement {
 	InterfaceButton button[MAXBUTTON];
 	int             flags;
 	int             reserved_for_future;
-	int             popupyp;   // pops up when mousey < this
+	int             popupyp;   // pops up when _G(mousey) < this
 	char            popup;     // does it pop up? (like sierra icon bar)
 	char            on;
 	InterfaceElement();
diff --git a/engines/ags/shared/ac/mousecursor.cpp b/engines/ags/shared/ac/mousecursor.cpp
index 8acbf41b41..cde072b207 100644
--- a/engines/ags/shared/ac/mousecursor.cpp
+++ b/engines/ags/shared/ac/mousecursor.cpp
@@ -22,6 +22,7 @@
 
 #include "ags/shared/ac/mousecursor.h"
 #include "ags/shared/util/stream.h"
+#include "ags/engine/globals.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/shared/gui/guimain.cpp b/engines/ags/shared/gui/guimain.cpp
index 889bf289f7..9481df5d6a 100644
--- a/engines/ags/shared/gui/guimain.cpp
+++ b/engines/ags/shared/gui/guimain.cpp
@@ -34,6 +34,7 @@
 #include "ags/shared/util/stream.h"
 #include "ags/shared/util/string_utils.h"
 #include "ags/lib/std/algorithm.h"
+#include "ags/engine/globals.h"
 
 namespace AGS3 {
 
@@ -98,7 +99,7 @@ int GUIMain::FindControlUnderMouse(int leeway, bool must_be_clickable) const {
 				continue;
 			if (!_controls[i]->IsClickable() && must_be_clickable)
 				continue;
-			if (_controls[i]->IsOverControl(mousex, mousey, leeway))
+			if (_controls[i]->IsOverControl(_G(mousex), _G(mousey), leeway))
 				return i;
 		}
 	} else {
@@ -108,7 +109,7 @@ int GUIMain::FindControlUnderMouse(int leeway, bool must_be_clickable) const {
 				continue;
 			if (!_controls[ctrl_index]->IsClickable() && must_be_clickable)
 				continue;
-			if (_controls[ctrl_index]->IsOverControl(mousex, mousey, leeway))
+			if (_controls[ctrl_index]->IsOverControl(_G(mousex), _G(mousey), leeway))
 				return ctrl_index;
 		}
 	}
@@ -279,15 +280,15 @@ void GUIMain::DrawBlob(Bitmap *ds, int x, int y, color_t draw_color) {
 }
 
 void GUIMain::Poll() {
-	int mxwas = mousex, mywas = mousey;
+	int mxwas = _G(mousex), mywas = _G(mousey);
 
-	mousex -= X;
-	mousey -= Y;
-	if (mousex != MouseWasAt.X || mousey != MouseWasAt.Y) {
+	_G(mousex) -= X;
+	_G(mousey) -= Y;
+	if (_G(mousex) != MouseWasAt.X || _G(mousey) != MouseWasAt.Y) {
 		int ctrl_index = FindControlUnderMouse();
 
 		if (MouseOverCtrl == MOVER_MOUSEDOWNLOCKED)
-			_controls[MouseDownCtrl]->OnMouseMove(mousex, mousey);
+			_controls[MouseDownCtrl]->OnMouseMove(_G(mousex), _G(mousey));
 		else if (ctrl_index != MouseOverCtrl) {
 			if (MouseOverCtrl >= 0)
 				_controls[MouseOverCtrl]->OnMouseLeave();
@@ -303,18 +304,18 @@ void GUIMain::Poll() {
 				MouseOverCtrl = ctrl_index;
 				if (MouseOverCtrl >= 0) {
 					_controls[MouseOverCtrl]->OnMouseEnter();
-					_controls[MouseOverCtrl]->OnMouseMove(mousex, mousey);
+					_controls[MouseOverCtrl]->OnMouseMove(_G(mousex), _G(mousey));
 				}
 			}
 			guis_need_update = 1;
 		} else if (MouseOverCtrl >= 0)
-			_controls[MouseOverCtrl]->OnMouseMove(mousex, mousey);
+			_controls[MouseOverCtrl]->OnMouseMove(_G(mousex), _G(mousey));
 	}
 
-	MouseWasAt.X = mousex;
-	MouseWasAt.Y = mousey;
-	mousex = mxwas;
-	mousey = mywas;
+	MouseWasAt.X = _G(mousex);
+	MouseWasAt.Y = _G(mousey);
+	_G(mousex) = mxwas;
+	_G(mousey) = mywas;
 }
 
 HError GUIMain::RebuildArray() {
@@ -449,7 +450,7 @@ void GUIMain::OnMouseButtonDown() {
 	MouseDownCtrl = MouseOverCtrl;
 	if (_controls[MouseOverCtrl]->OnMouseDown())
 		MouseOverCtrl = MOVER_MOUSEDOWNLOCKED;
-	_controls[MouseDownCtrl]->OnMouseMove(mousex - X, mousey - Y);
+	_controls[MouseDownCtrl]->OnMouseMove(_G(mousex) - X, _G(mousey) - Y);
 	guis_need_update = 1;
 }
 
diff --git a/engines/ags/shared/gui/guimain.h b/engines/ags/shared/gui/guimain.h
index 3e72bbae29..670f52a980 100644
--- a/engines/ags/shared/gui/guimain.h
+++ b/engines/ags/shared/gui/guimain.h
@@ -171,7 +171,7 @@ public:
 	// and text color in text windows)
 	int32_t Padding;        // padding surrounding a GUI text window
 	GUIPopupStyle PopupStyle; // GUI popup behavior
-	int32_t PopupAtMouseY;  // popup when mousey < this
+	int32_t PopupAtMouseY;  // popup when _G(mousey) < this
 	int32_t Transparency;   // "incorrect" alpha (in legacy 255-range units)
 	int32_t ZOrder;
 
@@ -222,8 +222,6 @@ extern std::vector<Shared::GUIMain> guis;
 extern int all_buttons_disabled, gui_inv_pic;
 extern int gui_disabled_style;
 
-extern int mousex, mousey;
-
 extern int get_adjusted_spritewidth(int spr);
 extern int get_adjusted_spriteheight(int spr);
 extern bool is_sprite_alpha(int spr);


Commit: ec02e1a118864f46803ab7d776ec3ad5a846831e
    https://github.com/scummvm/scummvm/commit/ec02e1a118864f46803ab7d776ec3ad5a846831e
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Move debugger globals to Globals

Changed paths:
    engines/ags/ags.cpp
    engines/ags/engine/ac/global_game.cpp
    engines/ags/engine/debugging/debug.cpp
    engines/ags/engine/debugging/debugger.h
    engines/ags/engine/globals.h
    engines/ags/engine/main/game_run.cpp
    engines/ags/engine/main/game_start.cpp
    engines/ags/engine/main/graphics_mode.cpp
    engines/ags/engine/main/quit.cpp
    engines/ags/engine/plugin/agsplugin.cpp


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index e282601452..09a58e539d 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -72,9 +72,6 @@ extern GameState play;
 extern int our_eip;
 extern AGSPlatformDriver *platform;
 extern int convert_16bit_bgr;
-extern int editor_debugging_enabled;
-extern int editor_debugging_initialized;
-extern char editor_debugger_instance_token[100];
 
 // this needs to be updated if the "play" struct changes
 #define SVG_VERSION_BWCOMPAT_MAJOR      3
@@ -161,8 +158,8 @@ static int main_process_cmdline(ConfigTree &cfg, int argc, const char *argv[]) {
 			_G(loadSaveGameOnStartup) = argv[ee + 1];
 			ee++;
 		} else if ((scumm_stricmp(arg, "--enabledebugger") == 0) && (argc > ee + 1)) {
-			strcpy(editor_debugger_instance_token, argv[ee + 1]);
-			editor_debugging_enabled = 1;
+			strcpy(_G(editor_debugger_instance_token), argv[ee + 1]);
+			_G(editor_debugging_enabled) = 1;
 			_G(force_window) = 1;
 			ee++;
 		} else if (scumm_stricmp(arg, "--runfromide") == 0 && (argc > ee + 3)) {
diff --git a/engines/ags/engine/ac/global_game.cpp b/engines/ags/engine/ac/global_game.cpp
index d1c2fbeb83..37684f36b8 100644
--- a/engines/ags/engine/ac/global_game.cpp
+++ b/engines/ags/engine/ac/global_game.cpp
@@ -246,7 +246,7 @@ int RunAGSGame(const char *newgame, unsigned int mode, int data) {
 	if ((mode & (~AllowedModes)) != 0)
 		quit("!RunAGSGame: mode value unknown");
 
-	if (editor_debugging_enabled) {
+	if (_G(editor_debugging_enabled)) {
 		quit("!RunAGSGame cannot be used while running the game from within the AGS Editor. You must build the game EXE and run it from there to use this function.");
 	}
 
diff --git a/engines/ags/engine/debugging/debug.cpp b/engines/ags/engine/debugging/debug.cpp
index c2454a27fd..016f2b471c 100644
--- a/engines/ags/engine/debugging/debug.cpp
+++ b/engines/ags/engine/debugging/debug.cpp
@@ -62,14 +62,6 @@ extern RoomStruct thisroom;
 extern char pexbuf[STD_BUFFER_SIZE];
 extern GameSetupStruct game;
 
-
-int editor_debugging_enabled = 0;
-int editor_debugging_initialized = 0;
-char editor_debugger_instance_token[100];
-IAGSEditorDebugger *editor_debugger = nullptr;
-int break_on_next_script_step = 0;
-volatile int game_paused_in_debugger = 0;
-
 #if AGS_PLATFORM_OS_WINDOWS
 
 #include "ags/shared/platform/windows/debug/namedpipesagsdebugger.h"
@@ -373,7 +365,7 @@ bool send_message_to_editor(const char *msg, const char *errorMsg) {
 	}
 	strcat(messageToSend, "</Debugger>");
 
-	editor_debugger->SendMessageToEditor(messageToSend);
+	_G(editor_debugger)->SendMessageToEditor(messageToSend);
 
 	return true;
 }
@@ -384,17 +376,17 @@ bool send_message_to_editor(const char *msg) {
 
 bool init_editor_debugging() {
 #if AGS_PLATFORM_OS_WINDOWS
-	editor_debugger = GetEditorDebugger(editor_debugger_instance_token);
+	_G(editor_debugger) = GetEditorDebugger(_G(editor_debugger_instance_token));
 #else
 	// Editor isn't ported yet
-	editor_debugger = nullptr;
+	_G(editor_debugger) = nullptr;
 #endif
 
-	if (editor_debugger == nullptr)
-		quit("editor_debugger is NULL but debugger enabled");
+	if (_G(editor_debugger) == nullptr)
+		quit("_G(editor_debugger) is NULL but debugger enabled");
 
-	if (editor_debugger->Initialize()) {
-		editor_debugging_initialized = 1;
+	if (_G(editor_debugger)->Initialize()) {
+		_G(editor_debugging_initialized) = 1;
 
 		// Wait for the editor to send the initial breakpoints
 		// and then its READY message
@@ -410,8 +402,8 @@ bool init_editor_debugging() {
 }
 
 int check_for_messages_from_editor() {
-	if (editor_debugger->IsMessageAvailable()) {
-		char *msg = editor_debugger->GetNextMessage();
+	if (_G(editor_debugger)->IsMessageAvailable()) {
+		char *msg = _G(editor_debugger)->GetNextMessage();
 		if (msg == nullptr) {
 			return 0;
 		}
@@ -466,10 +458,10 @@ int check_for_messages_from_editor() {
 				numBreakpoints++;
 			}
 		} else if (strncmp(msgPtr, "RESUME", 6) == 0) {
-			game_paused_in_debugger = 0;
+			_G(game_paused_in_debugger) = 0;
 		} else if (strncmp(msgPtr, "STEP", 4) == 0) {
-			game_paused_in_debugger = 0;
-			break_on_next_script_step = 1;
+			_G(game_paused_in_debugger) = 0;
+			_G(break_on_next_script_step) = 1;
 		} else if (strncmp(msgPtr, "EXIT", 4) == 0) {
 			_G(want_exit) = 1;
 			_G(abort_engine) = 1;
@@ -512,9 +504,9 @@ void break_into_debugger() {
 		SetForegroundWindow(editor_window_handle);
 
 	send_message_to_editor("BREAK");
-	game_paused_in_debugger = 1;
+	_G(game_paused_in_debugger) = 1;
 
-	while (game_paused_in_debugger) {
+	while (_G(game_paused_in_debugger)) {
 		update_polled_stuff_if_runtime();
 		platform->YieldCPU();
 	}
@@ -542,8 +534,8 @@ void scriptDebugHook(ccInstance *ccinst, int linenum) {
 		return;
 	}
 
-	if (break_on_next_script_step) {
-		break_on_next_script_step = 0;
+	if (_G(break_on_next_script_step)) {
+		_G(break_on_next_script_step) = 0;
 		break_into_debugger();
 		return;
 	}
@@ -568,7 +560,7 @@ void check_debug_keys() {
 		if (!::AGS::g_events->isKeyPressed(KEY_SCRLOCK) && scrlockWasDown)
 			scrlockWasDown = 0;
 		else if (::AGS::g_events->isKeyPressed(KEY_SCRLOCK) && !scrlockWasDown) {
-			break_on_next_script_step = 1;
+			_G(break_on_next_script_step) = 1;
 			scrlockWasDown = 1;
 		}
 	}
diff --git a/engines/ags/engine/debugging/debugger.h b/engines/ags/engine/debugging/debugger.h
index 8e87d71f22..7e4b070413 100644
--- a/engines/ags/engine/debugging/debugger.h
+++ b/engines/ags/engine/debugging/debugger.h
@@ -30,12 +30,6 @@ namespace AGS3 {
 struct IAGSEditorDebugger;
 struct ScriptPosition;
 
-extern int editor_debugging_enabled;
-extern int editor_debugging_initialized;
-extern char editor_debugger_instance_token[100];
-extern IAGSEditorDebugger *editor_debugger;
-extern int break_on_next_script_step;
-
 int check_for_messages_from_editor();
 bool send_message_to_editor(const char *msg);
 bool send_exception_to_editor(const char *qmsg);
diff --git a/engines/ags/engine/globals.h b/engines/ags/engine/globals.h
index b13038e84f..6cca2e29d3 100644
--- a/engines/ags/engine/globals.h
+++ b/engines/ags/engine/globals.h
@@ -40,6 +40,8 @@ class Bitmap;
 } // namespace Shared
 } // namespace AGS
 
+struct IAGSEditorDebugger;
+
 class Globals {
 public:
 	/**
@@ -53,6 +55,20 @@ public:
 
 	/**@}*/
 
+	/**
+	 * \defgroup debug globals
+	 * @{
+	 */
+
+	int _editor_debugging_enabled = 0;
+	int _editor_debugging_initialized = 0;
+	char _editor_debugger_instance_token[100];
+	IAGSEditorDebugger *_editor_debugger = nullptr;
+	int _break_on_next_script_step = 0;
+	volatile int _game_paused_in_debugger = 0;
+
+	/**@}*/
+
 	/**
 	 * \defgroup main globals
 	 * @{
diff --git a/engines/ags/engine/main/game_run.cpp b/engines/ags/engine/main/game_run.cpp
index 3441ed99d1..68a830ee83 100644
--- a/engines/ags/engine/main/game_run.cpp
+++ b/engines/ags/engine/main/game_run.cpp
@@ -1010,7 +1010,7 @@ void update_polled_stuff_if_runtime() {
 
 	update_polled_mp3();
 
-	if (editor_debugging_initialized)
+	if (_G(editor_debugging_initialized))
 		check_for_messages_from_editor();
 }
 
diff --git a/engines/ags/engine/main/game_start.cpp b/engines/ags/engine/main/game_start.cpp
index 11143a035f..5ea5356fe3 100644
--- a/engines/ags/engine/main/game_start.cpp
+++ b/engines/ags/engine/main/game_start.cpp
@@ -60,7 +60,7 @@ extern CharacterInfo *playerchar;
 extern int convert_16bit_bgr;
 
 void start_game_init_editor_debugging() {
-	if (editor_debugging_enabled) {
+	if (_G(editor_debugging_enabled)) {
 		SetMultitasking(1);
 		if (init_editor_debugging()) {
 			auto waitUntil = AGS_Clock::now() + std::chrono::milliseconds(500);
diff --git a/engines/ags/engine/main/graphics_mode.cpp b/engines/ags/engine/main/graphics_mode.cpp
index 63490180e9..9fbdb6aa6b 100644
--- a/engines/ags/engine/main/graphics_mode.cpp
+++ b/engines/ags/engine/main/graphics_mode.cpp
@@ -24,7 +24,6 @@
 // Graphics initialization
 //
 
-//include <algorithm>
 #include "ags/shared/core/platform.h"
 #include "ags/engine/ac/draw.h"
 #include "ags/engine/debugging/debugger.h"
@@ -39,6 +38,7 @@
 #include "ags/engine/main/graphics_mode.h"
 #include "ags/engine/main/main_allegro.h"
 #include "ags/engine/platform/base/agsplatformdriver.h"
+#include "ags/engine/globals.h"
 
 namespace AGS3 {
 
@@ -378,7 +378,7 @@ bool create_gfx_driver_and_init_mode_any(const String &gfx_driver_id, const Size
 
 	bool result = try_init_mode_using_setup(game_size, dm_setup, use_col_depth, frame_setup, filter_setup);
 	// Try windowed mode if fullscreen failed, and vice versa
-	if (!result && editor_debugging_enabled == 0) {
+	if (!result && _G(editor_debugging_enabled) == 0) {
 		// we need to clone from initial config, because not every parameter is set by graphics_mode_get_defaults()
 		DisplayModeSetup dm_setup_alt = dm_setup;
 		dm_setup_alt.Windowed = !dm_setup.Windowed;
diff --git a/engines/ags/engine/main/quit.cpp b/engines/ags/engine/main/quit.cpp
index 9b33146a00..822b273717 100644
--- a/engines/ags/engine/main/quit.cpp
+++ b/engines/ags/engine/main/quit.cpp
@@ -63,8 +63,6 @@ extern GameSetup usetup;
 extern char pexbuf[STD_BUFFER_SIZE];
 extern int proper_exit;
 extern char check_dynamic_sprites_at_exit;
-extern int editor_debugging_initialized;
-extern IAGSEditorDebugger *editor_debugger;
 extern int need_to_stop_cd;
 extern int use_cdplayer;
 extern IGraphicsDriver *gfxDriver;
@@ -74,11 +72,11 @@ extern Bitmap *test_allegro_bitmap;
 extern IDriverDependantBitmap *test_allegro_ddb;
 
 void quit_tell_editor_debugger(const String &qmsg, QuitReason qreason) {
-	if (editor_debugging_initialized) {
+	if (_G(editor_debugging_initialized)) {
 		if (qreason & kQuitKind_GameException)
 			_G(handledErrorInEditor) = send_exception_to_editor(qmsg);
 		send_message_to_editor("EXIT");
-		editor_debugger->Shutdown();
+		_G(editor_debugger)->Shutdown();
 	}
 }
 
diff --git a/engines/ags/engine/plugin/agsplugin.cpp b/engines/ags/engine/plugin/agsplugin.cpp
index 9ef1f677cc..626ced045a 100644
--- a/engines/ags/engine/plugin/agsplugin.cpp
+++ b/engines/ags/engine/plugin/agsplugin.cpp
@@ -833,7 +833,7 @@ void IAGSEngine::GetMovementPathWaypointSpeed(int32 pathId, int32 waypoint, int3
 }
 
 int IAGSEngine::IsRunningUnderDebugger() {
-	return (editor_debugging_enabled != 0) ? 1 : 0;
+	return (_G(editor_debugging_enabled) != 0) ? 1 : 0;
 }
 
 void IAGSEngine::GetPathToFileInCompiledFolder(const char *fileName, char *buffer) {
@@ -841,7 +841,7 @@ void IAGSEngine::GetPathToFileInCompiledFolder(const char *fileName, char *buffe
 }
 
 void IAGSEngine::BreakIntoDebugger() {
-	break_on_next_script_step = 1;
+	_G(break_on_next_script_step) = 1;
 }
 
 IAGSFontRenderer *IAGSEngine::ReplaceFontRenderer(int fontNumber, IAGSFontRenderer *newRenderer) {


Commit: 94add31198633539b2c409a75fea607b0fa30446
    https://github.com/scummvm/scummvm/commit/94add31198633539b2c409a75fea607b0fa30446
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix spurious bool comparisons

Changed paths:
    engines/ags/engine/ac/dialog.cpp
    engines/ags/engine/ac/global_game.cpp
    engines/ags/engine/debugging/filebasedagsdebugger.cpp
    engines/ags/shared/gui/guiobject.cpp


diff --git a/engines/ags/engine/ac/dialog.cpp b/engines/ags/engine/ac/dialog.cpp
index 1bf4e468e9..cd7f1b294e 100644
--- a/engines/ags/engine/ac/dialog.cpp
+++ b/engines/ags/engine/ac/dialog.cpp
@@ -959,7 +959,7 @@ bool DialogOptions::Run() {
 
 	if (parserActivated) {
 		// They have selected a custom parser-based option
-		if (!parserInput->Text.IsEmpty() != 0) {
+		if (!parserInput->Text.IsEmpty()) {
 			chose = DLG_OPTION_PARSER;
 			return false; // end dialog options running loop
 		} else {
diff --git a/engines/ags/engine/ac/global_game.cpp b/engines/ags/engine/ac/global_game.cpp
index 37684f36b8..64603bafa3 100644
--- a/engines/ags/engine/ac/global_game.cpp
+++ b/engines/ags/engine/ac/global_game.cpp
@@ -850,7 +850,7 @@ int SaveScreenShot(const char *namm) {
 		fileName.Format("%s%s", svg_dir.GetCStr(), namm);
 
 	Bitmap *buffer = CopyScreenIntoBitmap(play.GetMainViewport().GetWidth(), play.GetMainViewport().GetHeight());
-	if (!buffer->SaveToFile(fileName, palette) != 0) {
+	if (!buffer->SaveToFile(fileName, palette)) {
 		delete buffer;
 		return 0;
 	}
diff --git a/engines/ags/engine/debugging/filebasedagsdebugger.cpp b/engines/ags/engine/debugging/filebasedagsdebugger.cpp
index c8e6b42022..3975ffd3ab 100644
--- a/engines/ags/engine/debugging/filebasedagsdebugger.cpp
+++ b/engines/ags/engine/debugging/filebasedagsdebugger.cpp
@@ -74,7 +74,7 @@ bool FileBasedAGSDebugger::SendMessageToEditor(const char *message) {
 }
 
 bool FileBasedAGSDebugger::IsMessageAvailable() {
-	return (exists("dbgsend.tmp") != 0);
+	return exists("dbgsend.tmp");
 }
 
 char *FileBasedAGSDebugger::GetNextMessage() {
diff --git a/engines/ags/shared/gui/guiobject.cpp b/engines/ags/shared/gui/guiobject.cpp
index 81387b1c2a..6ba23826e5 100644
--- a/engines/ags/shared/gui/guiobject.cpp
+++ b/engines/ags/shared/gui/guiobject.cpp
@@ -167,7 +167,7 @@ void GUIObject::ReadFromSavegame(Stream *in, GuiSvgVersion svg_ver) {
 	Height = in->ReadInt32();
 	ZOrder = in->ReadInt32();
 	// Dynamic state
-	IsActivated = in->ReadBool() ? 1 : 0;
+	IsActivated = in->ReadBool();
 }
 
 void GUIObject::WriteToSavegame(Stream *out) const {
@@ -179,7 +179,7 @@ void GUIObject::WriteToSavegame(Stream *out) const {
 	out->WriteInt32(Height);
 	out->WriteInt32(ZOrder);
 	// Dynamic state
-	out->WriteBool(IsActivated != 0);
+	out->WriteBool(IsActivated);
 }
 
 


Commit: 2732f63a84a20e397f441091b24b1abbf47fe28e
    https://github.com/scummvm/scummvm/commit/2732f63a84a20e397f441091b24b1abbf47fe28e
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Use empty() rather than size() == 0

Changed paths:
    engines/ags/engine/ac/draw_software.cpp
    engines/ags/engine/ac/scriptcontainers.cpp


diff --git a/engines/ags/engine/ac/draw_software.cpp b/engines/ags/engine/ac/draw_software.cpp
index e6af2262bc..67eb7450db 100644
--- a/engines/ags/engine/ac/draw_software.cpp
+++ b/engines/ags/engine/ac/draw_software.cpp
@@ -440,7 +440,7 @@ void update_black_invreg_and_reset(Bitmap *ds) {
 }
 
 void update_room_invreg_and_reset(int view_index, Bitmap *ds, Bitmap *src, bool no_transform) {
-	if (view_index < 0 || RoomCamRects.size() == 0)
+	if (view_index < 0 || RoomCamRects.empty())
 		return;
 
 	update_invalid_region(ds, src, RoomCamRects[view_index], no_transform);
diff --git a/engines/ags/engine/ac/scriptcontainers.cpp b/engines/ags/engine/ac/scriptcontainers.cpp
index 10700dca70..0baa5ea971 100644
--- a/engines/ags/engine/ac/scriptcontainers.cpp
+++ b/engines/ags/engine/ac/scriptcontainers.cpp
@@ -119,7 +119,7 @@ int Dict_GetItemCount(ScriptDictBase *dic) {
 void *Dict_GetKeysAsArray(ScriptDictBase *dic) {
 	std::vector<const char *> items;
 	dic->GetKeys(items);
-	if (items.size() == 0)
+	if (items.empty())
 		return nullptr;
 	DynObjectRef arr = DynamicArrayHelpers::CreateStringArray(items);
 	return arr.second;


Commit: 2bbf6d1110de5b869b5ec339afd6e97ef9c1def9
    https://github.com/scummvm/scummvm/commit/2bbf6d1110de5b869b5ec339afd6e97ef9c1def9
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Compilation fix when tests are enabled

Changed paths:
    engines/ags/tests/test_inifile.cpp


diff --git a/engines/ags/tests/test_inifile.cpp b/engines/ags/tests/test_inifile.cpp
index 75781c427a..ec0399e83f 100644
--- a/engines/ags/tests/test_inifile.cpp
+++ b/engines/ags/tests/test_inifile.cpp
@@ -75,6 +75,35 @@ const char *IniFileText2 = ""
 "item5_2=value5_2" ENDL
 "item5_3=value5_3" ENDL;
 
+bool operator==(const StringOrderMap &lhs, const StringOrderMap &rhs) {
+	if (lhs.size() != rhs.size())
+		return false;
+
+	StringOrderMap::const_iterator it1 = lhs.begin();
+	StringOrderMap::const_iterator it2 = rhs.begin();
+
+	for (; it1 != lhs.end(); ++it1, ++it2) {
+		if (it1->_key || it2->_key || it1->_value != it2->_value)
+			return false;
+	}
+
+	return true;
+}
+
+bool operator==(const ConfigTree &lhs, const ConfigTree &rhs) {
+	if (lhs.size() != rhs.size())
+		return false;
+
+	ConfigTree::const_iterator it1 = lhs.begin();
+	ConfigTree::const_iterator it2 = rhs.begin();
+
+	for (; it1 != lhs.end(); ++it1, ++it2) {
+		if (it1->_key || it2->_key || !(it1->_value == it2->_value))
+			return false;
+	}
+
+	return true;
+}
 
 void Test_IniFile() {
 	Stream *fs = File::CreateFile("test.ini");


Commit: 77171310143fa25c3529ecf188f1cd0d31deee41
    https://github.com/scummvm/scummvm/commit/77171310143fa25c3529ecf188f1cd0d31deee41
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix games that write to files in the game folder

This fixes a crash at the very startup of The Blackwell Legacy,
which reads from a file prog.bwl in the game folder, and then
writes out a new version. In the new scheme, all data files
will try to be accessed from the save folder first, and then
fall back on the game folder. So this allows Blackwell to first
read from the game folder prog.bwl, then create it's own

Changed paths:
    engines/ags/detection_tables.h
    engines/ags/engine/ac/file.cpp
    engines/ags/engine/ac/global_file.cpp


diff --git a/engines/ags/detection_tables.h b/engines/ags/detection_tables.h
index bf615503a4..af315a8bdb 100644
--- a/engines/ags/detection_tables.h
+++ b/engines/ags/detection_tables.h
@@ -27,6 +27,7 @@ static const PlainGameDescriptor GAME_NAMES[] = {
 
 	{ "atotk", "A Tale Of Two Kingdoms" },
 	{ "bcremake", "Black Cauldron Remake" },
+	{ "blackwelllegacy", "The Blackwell Legacy" },
 	{ "kq2agdi", "Kings Quest II - Romancing The Stones" },
 
 	{ 0, 0 }
@@ -47,6 +48,7 @@ static const PlainGameDescriptor GAME_NAMES[] = {
 static const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("bcremake", "bc.exe", "0710e2ec71042617f565c01824f0cf3c", 7683255),
 	ENGLISH_ENTRY("atotk", "atotk.exe", "37cf2d4d07842d45b59c6dd9387c1ee7", 42872046),
+	ENGLISH_ENTRY("blackwelllegacy", "blackwell1.exe", "605e124cb7e0b56841c471e2d641c224", 18822697),
 	ENGLISH_ENTRY("kq2agdi", "kq2vga.exe", "40cfb7563df7dacf6530b19289a4745b", 12563246),	// 3.1
 
 	{ AD_TABLE_END_MARKER }
diff --git a/engines/ags/engine/ac/file.cpp b/engines/ags/engine/ac/file.cpp
index 263885359c..a0b5f7cc4d 100644
--- a/engines/ags/engine/ac/file.cpp
+++ b/engines/ags/engine/ac/file.cpp
@@ -272,7 +272,7 @@ String MakeSpecialSubDir(const String &sp_dir) {
 }
 
 String MakeAppDataPath() {
-	return AGS::Shared::SAVE_FOLDER_PREFIX;
+	return "./";
 }
 
 bool ResolveScriptPath(const String &orig_sc_path, bool read_only, ResolvedPath &rp) {
@@ -289,6 +289,23 @@ bool ResolveScriptPath(const String &orig_sc_path, bool read_only, ResolvedPath
 		return true;
 	}
 
+#if AGS_PLATFORM_SCUMMVM
+	if (read_only) {
+		// For reading files, first try as a save file, then fall back
+		// in the game folder. This handles cases where some games like
+		// The Blackwell Legacy write to files in the game folder
+		rp.BaseDir = SAVE_FOLDER_PREFIX;
+		rp.FullPath = String::FromFormat("%s%s", SAVE_FOLDER_PREFIX,
+			orig_sc_path.GetNullableCStr());
+		rp.AltPath = orig_sc_path;
+	} else {
+		// For writing files, always use as save files
+		rp.BaseDir = SAVE_FOLDER_PREFIX;
+		rp.FullPath = String::FromFormat("%s%s", SAVE_FOLDER_PREFIX,
+			orig_sc_path.GetNullableCStr());
+	}
+
+#else
 	String sc_path = FixSlashAfterToken(orig_sc_path);
 	String parent_dir;
 	String child_path;
@@ -348,6 +365,7 @@ bool ResolveScriptPath(const String &orig_sc_path, bool read_only, ResolvedPath
 	rp.BaseDir = parent_dir;
 	rp.FullPath = full_path;
 	rp.AltPath = alt_path;
+#endif
 	return true;
 }
 
diff --git a/engines/ags/engine/ac/global_file.cpp b/engines/ags/engine/ac/global_file.cpp
index 0edc340598..56eb016c02 100644
--- a/engines/ags/engine/ac/global_file.cpp
+++ b/engines/ags/engine/ac/global_file.cpp
@@ -83,10 +83,7 @@ int32_t FileOpen(const char *fnmm, Shared::FileOpenMode open_mode, Shared::FileW
 
 	Stream *s = File::OpenFile(rp.FullPath, open_mode, work_mode);
 	if (!s && !rp.AltPath.IsEmpty() && rp.AltPath.Compare(rp.FullPath) != 0) {
-		if (rp.FullPath.CompareLeft(AGS::Shared::SAVE_FOLDER_PREFIX))
-			// When file not found in main path, only check in AltPath if it's not a
-			// savegame file. Because ScummVM doesn't have any alt for saves
-			s = File::OpenFile(rp.AltPath, open_mode, work_mode);
+		s = File::OpenFile(rp.AltPath, open_mode, work_mode);
 	}
 
 	valid_handles[useindx].stream = s;


Commit: 5c97a5427391f9e23ec6f60c41861fee19cba3ef
    https://github.com/scummvm/scummvm/commit/5c97a5427391f9e23ec6f60c41861fee19cba3ef
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Implement bitmap saving code needed by KQ2

Changed paths:
    engines/ags/engine/ac/game.cpp
    engines/ags/shared/gfx/allegrobitmap.cpp
    engines/ags/shared/gfx/allegrobitmap.h
    engines/ags/shared/gfx/image.cpp
    engines/ags/shared/gfx/image.h


diff --git a/engines/ags/engine/ac/game.cpp b/engines/ags/engine/ac/game.cpp
index 4526adb9ab..9899af8973 100644
--- a/engines/ags/engine/ac/game.cpp
+++ b/engines/ags/engine/ac/game.cpp
@@ -97,11 +97,11 @@
 #include "ags/shared/util/path.h"
 #include "ags/shared/util/string_utils.h"
 #include "ags/engine/ac/keycode.h"
-
 #include "ags/shared/debugging/out.h"
 #include "ags/engine/script/script_api.h"
 #include "ags/engine/script/script_runtime.h"
 #include "ags/ags.h"
+#include "common/memstream.h"
 
 namespace AGS3 {
 
@@ -997,30 +997,16 @@ void skip_serialized_bitmap(Stream *in) {
 }
 
 long write_screen_shot_for_vista(Stream *out, Bitmap *screenshot) {
-#ifdef TODO
-	long fileSize = 0;
-	String tempFileName = String::FromFormat("%s""_tmpscht.bmp", saveGameDirectory.GetCStr());
-
-	screenshot->SaveToFile(tempFileName, palette);
+	// Save the screenshot to a memory stream so we can access the raw data
+	Common::MemoryWriteStreamDynamic bitmap(DisposeAfterUse::YES);
+	screenshot->SaveToFile(bitmap, palette);
 
 	update_polled_stuff_if_runtime();
 
-	if (exists(tempFileName)) {
-		fileSize = file_size_ex(tempFileName);
-		char *buffer = (char *)malloc(fileSize);
-
-		Stream *temp_in = Shared::File::OpenFileRead(tempFileName);
-		temp_in->Read(buffer, fileSize);
-		delete temp_in;
-		::remove(tempFileName);
+	// Write the bitmap to the output stream
+	out->Write(bitmap.getData(), bitmap.size());
 
-		out->Write(buffer, fileSize);
-		free(buffer);
-	}
-	return fileSize;
-#else
-	error("TODO: write_screen_shot_for_vista");
-#endif
+	return bitmap.size();
 }
 
 void WriteGameSetupStructBase_Aligned(Stream *out) {
diff --git a/engines/ags/shared/gfx/allegrobitmap.cpp b/engines/ags/shared/gfx/allegrobitmap.cpp
index f627868d7e..6f1dc56fc4 100644
--- a/engines/ags/shared/gfx/allegrobitmap.cpp
+++ b/engines/ags/shared/gfx/allegrobitmap.cpp
@@ -24,6 +24,8 @@
 #include "ags/shared/gfx/image.h"
 #include "ags/shared/debugging/assert.h"
 #include "ags/lib/aastr-0.1.1/aastr.h"
+#include "common/savefile.h"
+#include "common/system.h"
 
 namespace AGS3 {
 
@@ -123,8 +125,18 @@ bool Bitmap::LoadFromFile(const char *filename) {
 	return _alBitmap != nullptr;
 }
 
+bool Bitmap::SaveToFile(Common::WriteStream &out, const void *palette) {
+	return save_bitmap(out, _alBitmap, (const RGB *)palette) == 0;
+}
+
 bool Bitmap::SaveToFile(const char *filename, const void *palette) {
-	return save_bitmap(filename, _alBitmap, (const RGB *)palette) == 0;
+	Common::OutSaveFile *out = g_system->getSavefileManager()->openForSaving(filename, false);
+	assert(out);
+	bool result = SaveToFile(*out, palette);
+	out->finalize();
+	delete out;
+
+	return result;
 }
 
 void Bitmap::SetMaskColor(color_t color) {
diff --git a/engines/ags/shared/gfx/allegrobitmap.h b/engines/ags/shared/gfx/allegrobitmap.h
index 76ba4ec596..4e70adf1f6 100644
--- a/engines/ags/shared/gfx/allegrobitmap.h
+++ b/engines/ags/shared/gfx/allegrobitmap.h
@@ -66,6 +66,7 @@ public:
 	void    Destroy();
 
 	bool    LoadFromFile(const char *filename);
+	bool    SaveToFile(Common::WriteStream &out, const void *palette);
 	bool    SaveToFile(const char *filename, const void *palette);
 
 	// TODO: This is temporary solution for cases when we cannot replace
diff --git a/engines/ags/shared/gfx/image.cpp b/engines/ags/shared/gfx/image.cpp
index 914c4d84bf..055dcba4e0 100644
--- a/engines/ags/shared/gfx/image.cpp
+++ b/engines/ags/shared/gfx/image.cpp
@@ -24,6 +24,7 @@
 #include "ags/lib/allegro.h"
 #include "common/file.h"
 #include "common/str.h"
+#include "common/stream.h"
 #include "common/textconsole.h"
 #include "image/pcx.h"
 
@@ -103,8 +104,56 @@ BITMAP *load_bitmap(const char *filename, color *pal) {
 		error("Unknown image file - %s", filename);
 }
 
-int save_bitmap(const char *filename, BITMAP *bmp, const RGB *pal) {
-	error("TODO: save_bitmap");
+int save_bitmap(Common::WriteStream &out, BITMAP *bmp, const RGB *pal) {
+#ifdef SCUMM_LITTLE_ENDIAN
+	const Graphics::PixelFormat requiredFormat_3byte(3, 8, 8, 8, 0, 16, 8, 0, 0);
+#else
+	const Graphics::PixelFormat requiredFormat_3byte(3, 8, 8, 8, 0, 0, 8, 16, 0);
+#endif
+
+	Graphics::ManagedSurface &src = bmp->getSurface();
+	Graphics::Surface *tmp = nullptr;
+	const Graphics::Surface *surface;
+
+	if (bmp->format == requiredFormat_3byte) {
+		surface = &src.rawSurface();
+	} else {
+		surface = tmp = src.rawSurface().convertTo(requiredFormat_3byte);
+	}
+
+	int dstPitch = surface->w * 3;
+	int extraDataLength = (dstPitch % 4) ? 4 - (dstPitch % 4) : 0;
+	int padding = 0;
+
+	out.writeByte('B');
+	out.writeByte('M');
+	out.writeUint32LE(surface->h * dstPitch + 54);
+	out.writeUint32LE(0);
+	out.writeUint32LE(54);
+	out.writeUint32LE(40);
+	out.writeUint32LE(surface->w);
+	out.writeUint32LE(surface->h);
+	out.writeUint16LE(1);
+	out.writeUint16LE(24);
+	out.writeUint32LE(0);
+	out.writeUint32LE(0);
+	out.writeUint32LE(0);
+	out.writeUint32LE(0);
+	out.writeUint32LE(0);
+	out.writeUint32LE(0);
+
+	for (uint y = surface->h; y-- > 0;) {
+		out.write((const void *)surface->getBasePtr(0, y), dstPitch);
+		out.write(&padding, extraDataLength);
+	}
+
+	// free tmp surface
+	if (tmp) {
+		tmp->free();
+		delete tmp;
+	}
+
+	return true;
 }
 
 } // namespace AGS
diff --git a/engines/ags/shared/gfx/image.h b/engines/ags/shared/gfx/image.h
index 592009ec01..8af013a19d 100644
--- a/engines/ags/shared/gfx/image.h
+++ b/engines/ags/shared/gfx/image.h
@@ -36,7 +36,7 @@ BITMAP *load_pcx_pf(PACKFILE *f, color *pal);
 BITMAP *load_tga(const char *filename, color *pal);
 BITMAP *load_tga_pf(PACKFILE *f, color *pal);
 
-int save_bitmap(const char *filename, BITMAP *bmp, const RGB *pal);
+int save_bitmap(Common::WriteStream &out, BITMAP *bmp, const RGB *pal);
 
 } // namespace AGS3
 


Commit: 9d2c67f738a327f4cbbc5b92f0b9000f56829b1a
    https://github.com/scummvm/scummvm/commit/9d2c67f738a327f4cbbc5b92f0b9000f56829b1a
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix black box & gfx issues in ATOTK

Changed paths:
    engines/ags/lib/allegro/gfx.cpp


diff --git a/engines/ags/lib/allegro/gfx.cpp b/engines/ags/lib/allegro/gfx.cpp
index df0f0ea2e8..6b973c993c 100644
--- a/engines/ags/lib/allegro/gfx.cpp
+++ b/engines/ags/lib/allegro/gfx.cpp
@@ -211,8 +211,8 @@ int bitmap_color_depth(BITMAP *bmp) {
 }
 
 int bitmap_mask_color(BITMAP *bmp) {
-	Graphics::ManagedSurface &surf = **bmp;
-	return surf.getTransparentColor();
+	assert(bmp->format.bytesPerPixel > 1);
+	return bmp->format.RGBToColor(255, 0, 255);
 }
 
 void add_palette_if_needed(Graphics::ManagedSurface &src, Graphics::ManagedSurface &dest) {


Commit: 9ef8af4427e6804b5dfb80cecdb744ffa2a70d41
    https://github.com/scummvm/scummvm/commit/9ef8af4427e6804b5dfb80cecdb744ffa2a70d41
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Implemented Theora video player

Changed paths:
    engines/ags/engine/media/video/video.cpp
    engines/ags/shared/util/stream.h


diff --git a/engines/ags/engine/media/video/video.cpp b/engines/ags/engine/media/video/video.cpp
index d5a14bc821..998b29fee0 100644
--- a/engines/ags/engine/media/video/video.cpp
+++ b/engines/ags/engine/media/video/video.cpp
@@ -20,13 +20,9 @@
  *
  */
 
-#include "ags/engine/media/video/video.h"
-
-//include "apeg.h"
+#include "video/theora_decoder.h"
 #include "ags/shared/core/platform.h"
-#define AGS_FLI_FROM_PACK_FILE ((ALLEGRO_DATE >= 20190303) || \
-	AGS_PLATFORM_OS_WINDOWS || AGS_PLATFORM_OS_ANDROID || AGS_PLATFORM_OS_MACOS)
-
+#include "ags/shared/core/types.h"
 #include "ags/engine/debugging/debug_log.h"
 #include "ags/shared/debugging/out.h"
 #include "ags/engine/ac/asset_helper.h"
@@ -47,361 +43,84 @@
 #include "ags/engine/main/game_run.h"
 #include "ags/shared/util/stream.h"
 #include "ags/engine/media/audio/audio_system.h"
+#include "ags/ags.h"
+#include "ags/events.h"
+#include "ags/engine/media/video/video.h"
 
 namespace AGS3 {
 
-// TODO: Enable video playback
-#define AGS_NO_VIDEO_PLAYER
-
-#ifndef AGS_NO_VIDEO_PLAYER
-
-using namespace AGS::Shared;
-using namespace AGS::Engine;
-
-
-extern GameSetupStruct game;
-extern IGraphicsDriver *gfxDriver;
-extern int psp_video_framedrop;
-
-enum VideoPlaybackType {
-	kVideoNone,
-	kVideoFlic,
-	kVideoTheora
-};
-
-VideoPlaybackType video_type = kVideoNone;
-
-// FLIC player start
-Bitmap *fli_buffer = nullptr;
-short fliwidth, fliheight;
-int canabort = 0, stretch_flc = 1;
-Bitmap *hicol_buf = nullptr;
-IDriverDependantBitmap *fli_ddb = nullptr;
-Bitmap *fli_target = nullptr;
-int fliTargetWidth, fliTargetHeight;
-int check_if_user_input_should_cancel_video() {
-	int key, mbut, mwheelz;
-	if (run_service_key_controls(key)) {
-		if ((key == 27) && (canabort == 1))
-			return 1;
-		if (canabort >= 2)
-			return 1;  // skip on any key
-	}
-	if (run_service_mb_controls(mbut, mwheelz) && mbut >= 0 && canabort == 3) {
-		return 1; // skip on mouse click
-	}
-	return 0;
-}
-
-#if AGS_PLATFORM_OS_WINDOWS
-int __cdecl fli_callback() {
-#else
-extern "C" int fli_callback() {
-#endif
-	Bitmap *usebuf = fli_buffer;
-
-	update_audio_system_on_game_loop();
-
-	if (game.color_depth > 1) {
-		hicol_buf->Blit(fli_buffer, 0, 0, 0, 0, fliwidth, fliheight);
-		usebuf = hicol_buf;
-	}
-
-	const Rect &view = play.GetMainViewport();
-	if (stretch_flc == 0)
-		fli_target->Blit(usebuf, 0, 0, view.GetWidth() / 2 - fliwidth / 2, view.GetHeight() / 2 - fliheight / 2, view.GetWidth(), view.GetHeight());
-	else
-		fli_target->StretchBlt(usebuf, RectWH(0, 0, fliwidth, fliheight), RectWH(0, 0, view.GetWidth(), view.GetHeight()));
-
-	gfxDriver->UpdateDDBFromBitmap(fli_ddb, fli_target, false);
-	gfxDriver->DrawSprite(0, 0, fli_ddb);
-	render_to_screen();
-
-	return check_if_user_input_should_cancel_video();
-}
-
-void play_flc_file(int numb, int playflags) {
-	color oldpal[256];
-
-	// AGS 2.x: If the screen is faded out, fade in again when playing a movie.
-	if (loaded_game_file_version <= kGameVersion_272)
-		play.screen_is_faded_out = 0;
-
-	if (play.fast_forward)
-		return;
-
-	get_palette_range(oldpal, 0, 255);
-
-	int clearScreenAtStart = 1;
-	canabort = playflags % 10;
-	playflags -= canabort;
-
-	if (canabort == 2) // convert to PlayVideo-compatible setting
-		canabort = 3;
-
-	if (playflags % 100 == 0)
-		stretch_flc = 1;
-	else
-		stretch_flc = 0;
-
-	if (playflags / 100)
-		clearScreenAtStart = 0;
-
-	String flicname = String::FromFormat("flic%d.flc", numb);
-	Stream *in = AssetManager::OpenAsset(flicname);
-	if (!in) {
-		flicname.Format("flic%d.fli", numb);
-		in = AssetManager::OpenAsset(flicname);
-	}
-	if (!in) {
-		debug_script_warn("FLIC animation flic%d.flc nor flic%d.fli not found", numb, numb);
-		return;
-	}
-
-	in->Seek(8);
-	fliwidth = in->ReadInt16();
-	fliheight = in->ReadInt16();
-	delete in;
-
-	if (game.color_depth > 1) {
-		hicol_buf = BitmapHelper::CreateBitmap(fliwidth, fliheight, game.GetColorDepth());
-		hicol_buf->Clear();
-	}
-	// override the stretch option if necessary
-	const Rect &view = play.GetMainViewport();
-	if ((fliwidth == view.GetWidth()) && (fliheight == view.GetHeight()))
-		stretch_flc = 0;
-	else if ((fliwidth > view.GetWidth()) || (fliheight > view.GetHeight()))
-		stretch_flc = 1;
-	fli_buffer = BitmapHelper::CreateBitmap(fliwidth, fliheight, 8);
-	if (fli_buffer == nullptr) quit("Not enough memory to play animation");
-	fli_buffer->Clear();
-
-	if (clearScreenAtStart) {
-		if (gfxDriver->UsesMemoryBackBuffer()) {
-			Bitmap *screen_bmp = gfxDriver->GetMemoryBackBuffer();
-			screen_bmp->Clear();
-		}
-		render_to_screen();
-	}
-
-	video_type = kVideoFlic;
-	fli_target = BitmapHelper::CreateBitmap(view.GetWidth(), view.GetHeight(), game.GetColorDepth());
-	fli_ddb = gfxDriver->CreateDDBFromBitmap(fli_target, false, true);
-
-	// TODO: find a better solution.
-	// Make only certain versions of the engineuse play_fli_pf from the patched version of Allegro for now.
-	// Add more versions as their Allegro lib becomes patched too, or they use newer version of Allegro 4.
-	// Ports can still play FLI if separate file is put into game's directory.
-#if AGS_FLI_FROM_PACK_FILE
-	size_t asset_size;
-	PACKFILE *pf = PackfileFromAsset(AssetPath("", flicname), asset_size);
-	if (play_fli_pf(pf, (BITMAP *)fli_buffer->GetAllegroBitmap(), fli_callback) == FLI_ERROR)
-#else
-	if (play_fli(flicname, (BITMAP *)fli_buffer->GetAllegroBitmap(), 0, fli_callback) == FLI_ERROR)
-#endif
-	{
-		// This is not a fatal error that should prevent the game from continuing
-		Debug::Printf("FLI/FLC animation play error");
-	}
-#if AGS_FLI_FROM_PACK_FILE
-	pack_fclose(pf);
-#endif
-
-	video_type = kVideoNone;
-	delete fli_buffer;
-	fli_buffer = nullptr;
-	// NOTE: the screen bitmap could change in the meanwhile, if the display mode has changed
-	if (gfxDriver->UsesMemoryBackBuffer()) {
-		Bitmap *screen_bmp = gfxDriver->GetMemoryBackBuffer();
-		screen_bmp->Clear();
-	}
-	set_palette_range(oldpal, 0, 255, 0);
-	render_to_screen();
-
-	delete fli_target;
-	gfxDriver->DestroyDDB(fli_ddb);
-	fli_target = nullptr;
-	fli_ddb = nullptr;
-
-
-	delete hicol_buf;
-	hicol_buf = nullptr;
-	//  SetVirtualScreen(screen); wputblock(0,0,backbuffer,0);
-	while (ags_mgetbutton() != NONE) {
-	} // clear any queued mouse events.
-	invalidate_screen();
-}
-
-// FLIC player end
-
-// Theora player begin
-// TODO: find a way to take Bitmap here?
-Bitmap gl_TheoraBuffer;
-int theora_playing_callback(BITMAP * theoraBuffer) {
-	if (theoraBuffer == nullptr) {
-		// No video, only sound
-		return check_if_user_input_should_cancel_video();
-	}
-
-	gl_TheoraBuffer.WrapAllegroBitmap(theoraBuffer, true);
-
-	int drawAtX = 0, drawAtY = 0;
-	const Rect &viewport = play.GetMainViewport();
-	if (fli_ddb == nullptr) {
-		fli_ddb = gfxDriver->CreateDDBFromBitmap(&gl_TheoraBuffer, false, true);
-	}
-	if (stretch_flc) {
-		drawAtX = viewport.GetWidth() / 2 - fliTargetWidth / 2;
-		drawAtY = viewport.GetHeight() / 2 - fliTargetHeight / 2;
-		if (!gfxDriver->HasAcceleratedTransform()) {
-			fli_target->StretchBlt(&gl_TheoraBuffer, RectWH(0, 0, gl_TheoraBuffer.GetWidth(), gl_TheoraBuffer.GetHeight()),
-				RectWH(drawAtX, drawAtY, fliTargetWidth, fliTargetHeight));
-			gfxDriver->UpdateDDBFromBitmap(fli_ddb, fli_target, false);
-			drawAtX = 0;
-			drawAtY = 0;
-		} else {
-			gfxDriver->UpdateDDBFromBitmap(fli_ddb, &gl_TheoraBuffer, false);
-			fli_ddb->SetStretch(fliTargetWidth, fliTargetHeight, false);
-		}
-	} else {
-		gfxDriver->UpdateDDBFromBitmap(fli_ddb, &gl_TheoraBuffer, false);
-		drawAtX = viewport.GetWidth() / 2 - gl_TheoraBuffer.GetWidth() / 2;
-		drawAtY = viewport.GetHeight() / 2 - gl_TheoraBuffer.GetHeight() / 2;
-	}
-
-	gfxDriver->DrawSprite(drawAtX, drawAtY, fli_ddb);
-	update_audio_system_on_game_loop();
-	render_to_screen();
-
-	return check_if_user_input_should_cancel_video();
-}
-
-//
-// Theora stream reader callbacks. We need these because APEG library does not
-// provide means to supply user's PACKFILE directly.
-//
-// Open stream for reading (return suggested cache buffer size).
-int apeg_stream_init(void *ptr) {
-	return ptr != nullptr ? F_BUF_SIZE : 0;
-}
-// Read requested number of bytes into provided buffer,
-// return actual number of bytes managed to read.
-int apeg_stream_read(void *buffer, int bytes, void *ptr) {
-	return ((Stream *)ptr)->Read(buffer, bytes);
-}
-// Skip requested number of bytes
-void apeg_stream_skip(int bytes, void *ptr) {
-	((Stream *)ptr)->Seek(bytes);
-}
-//
-
-APEG_STREAM *get_theora_size(Stream * video_stream, int *width, int *height) {
-	APEG_STREAM *oggVid = apeg_open_stream_ex(video_stream);
-	if (oggVid != nullptr) {
-		apeg_get_video_size(oggVid, width, height);
-	} else {
-		*width = 0;
-		*height = 0;
-	}
-	return oggVid;
-}
-
-// TODO: use shared utility function for placing rect in rect
-void calculate_destination_size_maintain_aspect_ratio(int vidWidth, int vidHeight, int *targetWidth, int *targetHeight) {
-	const Rect &viewport = play.GetMainViewport();
-	float aspectRatioVideo = (float)vidWidth / (float)vidHeight;
-	float aspectRatioScreen = (float)viewport.GetWidth() / (float)viewport.GetHeight();
-
-	if (aspectRatioVideo == aspectRatioScreen) {
-		*targetWidth = viewport.GetWidth();
-		*targetHeight = viewport.GetHeight();
-	} else if (aspectRatioVideo > aspectRatioScreen) {
-		*targetWidth = viewport.GetWidth();
-		*targetHeight = (int)(((float)viewport.GetWidth() / aspectRatioVideo) + 0.5f);
-	} else {
-		*targetHeight = viewport.GetHeight();
-		*targetWidth = (float)viewport.GetHeight() * aspectRatioVideo;
-	}
-
-}
+using AGS::Shared::AssetManager;
 
 void play_theora_video(const char *name, int skip, int flags) {
 	std::unique_ptr<Stream> video_stream(AssetManager::OpenAsset(name));
-	apeg_set_stream_reader(apeg_stream_init, apeg_stream_read, apeg_stream_skip);
-	apeg_set_display_depth(game.GetColorDepth());
-	// we must disable length detection, otherwise it takes ages to start
-	// playing if the file is large because it seeks through the whole thing
-	apeg_disable_length_detection(TRUE);
-	// Disable framedrop because it can lead to the PSP not playing the video at all.
-	apeg_enable_framedrop(psp_video_framedrop);
-	update_polled_stuff_if_runtime();
-
-	stretch_flc = (flags % 10);
-	canabort = skip;
-	apeg_ignore_audio((flags >= 10) ? 1 : 0);
-
-	int videoWidth, videoHeight;
-	APEG_STREAM *oggVid = get_theora_size(video_stream.get(), &videoWidth, &videoHeight);
-
-	if (videoWidth == 0) {
+	if (!video_stream) {
 		Display("Unable to load theora video '%s'", name);
 		return;
 	}
 
-	if (flags < 10) {
-		stop_all_sound_and_music();
-	}
+	update_polled_stuff_if_runtime();
 
-	//fli_buffer = BitmapHelper::CreateBitmap_(scsystem.coldepth, videoWidth, videoHeight);
-	calculate_destination_size_maintain_aspect_ratio(videoWidth, videoHeight, &fliTargetWidth, &fliTargetHeight);
+	Graphics::Screen &scr = *::AGS::g_vm->_rawScreen;
+	bool stretchVideo = (flags % 10) != 0;
+	int canAbort = skip;
+	bool ignoreAudio = (flags >= 10);
 
-	if ((fliTargetWidth == videoWidth) && (fliTargetHeight == videoHeight) && (stretch_flc)) {
-		// don't need to stretch after all
-		stretch_flc = 0;
+	if (!ignoreAudio) {
+		stop_all_sound_and_music();
 	}
 
-	if ((stretch_flc) && (!gfxDriver->HasAcceleratedTransform())) {
-		fli_target = BitmapHelper::CreateBitmap(play.GetMainViewport().GetWidth(), play.GetMainViewport().GetHeight(), game.GetColorDepth());
-		fli_target->Clear();
-		fli_ddb = gfxDriver->CreateDDBFromBitmap(fli_target, false, true);
-	} else {
-		fli_ddb = nullptr;
+	Video::TheoraDecoder decoder;
+	AGS::Shared::ScummVMReadStream *stream = new AGS::Shared::ScummVMReadStream(video_stream.get(), DisposeAfterUse::NO);
+
+	if (!decoder.loadStream(stream)) {
+		delete stream;
+		Display("Unable to decode theora video '%s'", name);
+		return;
 	}
 
 	update_polled_stuff_if_runtime();
 
-	if (gfxDriver->UsesMemoryBackBuffer())
-		gfxDriver->GetMemoryBackBuffer()->Clear();
+	decoder.start();
+	while (!SHOULD_QUIT && !decoder.endOfVideo()) {
+		if (decoder.needsUpdate()) {
+			// Get the next video frame and draw onto the screen
+			const Graphics::Surface *frame = decoder.decodeNextFrame();
+
+			if (stretchVideo && frame->w == scr.w && frame->h == scr.h)
+				// Don't need to stretch video after all
+				stretchVideo = false;
+
+			if (stretchVideo) {
+				scr.transBlitFrom(*frame, Common::Rect(0, 0, frame->w, frame->h),
+					Common::Rect(0, 0, scr.w, scr.h));
+			} else {
+				scr.blitFrom(*frame, Common::Point((scr.w - frame->w) / 2,
+					(scr.h - frame->h) / 2));
+			}
+
+			scr.update();
+		}
 
-	video_type = kVideoTheora;
-	if (apeg_play_apeg_stream(oggVid, nullptr, 0, theora_playing_callback) == APEG_ERROR) {
-		Display("Error playing theora video '%s'", name);
+		g_system->delayMillis(10);
+		::AGS::g_events->pollEvents();
+
+		if (canAbort) {
+			// Check for whether user aborted video
+			int key, mbut, mwheelz;
+			if (run_service_key_controls(key)) {
+				if (key == 27 && canAbort)
+					return;
+				if (canAbort >= 2)
+					return;  // skip on any key
+			}
+			if (run_service_mb_controls(mbut, mwheelz) && mbut >= 0 && canAbort == 3) {
+				return; // skip on mouse click
+			}
+		}
 	}
-	apeg_close_stream(oggVid);
-	video_type = kVideoNone;
 
-	//destroy_bitmap(fli_buffer);
-	delete fli_target;
-	gfxDriver->DestroyDDB(fli_ddb);
-	fli_target = nullptr;
-	fli_ddb = nullptr;
 	invalidate_screen();
 }
-// Theora player end
-
-void video_on_gfxmode_changed() {
-	if (video_type == kVideoFlic) {
-		// If the FLIC video is playing, restore its palette
-		set_palette_range(fli_palette, 0, 255, 0);
-	}
-}
-
-#else
-
-void play_theora_video(const char *name, int skip, int flags) {
-	warning("TODO: play_theora_video");
-}
 void play_flc_file(int numb, int playflags) {
 	warning("TODO: play_flc_file");
 }
@@ -410,6 +129,4 @@ void video_on_gfxmode_changed() {
 	warning("TODO: video_on_gfxmode_changed");
 }
 
-#endif
-
 } // namespace AGS3
diff --git a/engines/ags/shared/util/stream.h b/engines/ags/shared/util/stream.h
index 9940e96695..4b42de45e7 100644
--- a/engines/ags/shared/util/stream.h
+++ b/engines/ags/shared/util/stream.h
@@ -36,6 +36,8 @@
 #define AGS_SHARED_UTIL_STREAM_H
 
 #include "ags/shared/api/stream_api.h"
+#include "common/stream.h"
+#include "common/types.h"
 
 namespace AGS3 {
 namespace AGS {
@@ -83,6 +85,46 @@ public:
 	size_t WriteByteCount(uint8_t b, size_t count);
 };
 
+class ScummVMReadStream : public Common::SeekableReadStream {
+private:
+	IAGSStream *_stream;
+	DisposeAfterUse::Flag _disposeAfterUse;
+public:
+	ScummVMReadStream(IAGSStream *src, DisposeAfterUse::Flag disposeAfterUse =
+			DisposeAfterUse::YES) : _stream(src), _disposeAfterUse(disposeAfterUse) {
+	}
+	~ScummVMReadStream() override {
+		if (_disposeAfterUse == DisposeAfterUse::YES)
+			delete _stream;
+	}
+
+	bool eos() const override {
+		return _stream->EOS();
+	}
+
+	uint32 read(void *dataPtr, uint32 dataSize) override {
+		return _stream->Read(dataPtr, dataSize);
+	}
+
+	int32 pos() const override {
+		return _stream->GetPosition();
+	}
+
+	int32 size() const override {
+		return _stream->GetLength();
+	}
+
+	bool seek(int32 offset, int whence = SEEK_SET) override {
+		StreamSeek origin = kSeekBegin;
+		if (whence == SEEK_CUR)
+			origin = kSeekCurrent;
+		if (whence == SEEK_END)
+			origin = kSeekEnd;
+
+		return _stream->Seek(offset, origin);
+	}
+};
+
 } // namespace Shared
 } // namespace AGS
 } // namespace AGS3


Commit: a9c456c7788f726c80ceef14d34fe6f607bda639
    https://github.com/scummvm/scummvm/commit/a9c456c7788f726c80ceef14d34fe6f607bda639
Author: Thierry Crozat (criezy at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Add some more detection entries

Changed paths:
    engines/ags/detection_tables.h


diff --git a/engines/ags/detection_tables.h b/engines/ags/detection_tables.h
index af315a8bdb..45c4e1634a 100644
--- a/engines/ags/detection_tables.h
+++ b/engines/ags/detection_tables.h
@@ -27,8 +27,24 @@ static const PlainGameDescriptor GAME_NAMES[] = {
 
 	{ "atotk", "A Tale Of Two Kingdoms" },
 	{ "bcremake", "Black Cauldron Remake" },
-	{ "blackwelllegacy", "The Blackwell Legacy" },
+	{ "blackwell1", "The Blackwell Legacy"},
+	{ "blackwell2", "Blackwell Unbound"},
+	{ "blackwell3", "The Blackwell Convergence"},
+	{ "blackwell4", "The Blackwell Deception"},
+	{ "blackwell5", "The Blackwell Epiphany"},
 	{ "kq2agdi", "Kings Quest II - Romancing The Stones" },
+	{ "kq1agdi", "King's Quest I: Quest for the Crown Remake" },
+	{ "kq2agdi", "King's Quest II: Romancing The Stones" },
+	{ "kq3agdi", "King's Quest III Redux: To Heir is Human" },
+	{ "geminirue", "Gemini Rue"},
+	{ "goldenwake", "A Golden Wake"},
+	{ "kathyrain", "Kathy Rain"},
+	{ "qfi", "Quest for Infamy"},
+	{ "oott", "Order of the Thorne: The King's Challenge"},
+	{ "primordia", "Primordia"},
+	{ "resonance", "Resonance"},
+	{ "mage", "Mage's Initiation: Reign of the Elements"},
+	{ "unavowed", "Unavowed"},
 
 	{ 0, 0 }
 };
@@ -48,8 +64,26 @@ static const PlainGameDescriptor GAME_NAMES[] = {
 static const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("bcremake", "bc.exe", "0710e2ec71042617f565c01824f0cf3c", 7683255),
 	ENGLISH_ENTRY("atotk", "atotk.exe", "37cf2d4d07842d45b59c6dd9387c1ee7", 42872046),
-	ENGLISH_ENTRY("blackwelllegacy", "blackwell1.exe", "605e124cb7e0b56841c471e2d641c224", 18822697),
+	ENGLISH_ENTRY("atotk", "atotk.exe", "37cf2d4d07842d45b59c6dd9387c1ee7", 42740200),
+	ENGLISH_ENTRY("blackwell1", "blackwell1.exe", "605e124cb7e0b56841c471e2d641c224", 18822697), // GOG
+	ENGLISH_ENTRY("blackwell2", "unbound.exe", "5c3a940514d91431e8e1c372018851ca", 14493753), // GOG
+	ENGLISH_ENTRY("blackwell3", "convergence.exe", "2260c1a21aba7ac00baf0100d4ca54f1", 172575801), // GOG
+	ENGLISH_ENTRY("blackwell4", "deception.exe", "b3b192cf20a2f7666ddea3410dbd87cc", 303459336), // GOG
+	ENGLISH_ENTRY("blackwell5", "epiphany.exe", "c1cddd6fcdbcd030beda9f10d4e4270a", 281849897), // GOG
+	ENGLISH_ENTRY("kq1agdi", "kq1vga.exe", "688f1807c9d8df26fc0f174dc756054e", 8278611),  // 4.1c
 	ENGLISH_ENTRY("kq2agdi", "kq2vga.exe", "40cfb7563df7dacf6530b19289a4745b", 12563246),	// 3.1
+	ENGLISH_ENTRY("kq2agdi", "kq2vga.exe", "40cfb7563df7dacf6530b19289a4745b", 12574643),  // 3.1c
+	ENGLISH_ENTRY("kq3agdi", "kq3redux.exe", "e569fb2ceabdc4a1609348c23ebc0821", 11986266),  // 1.1
+	ENGLISH_ENTRY("geminirue", "gemini rue.exe", "f3c0c7d3892bdd8963e8ce017f73de08", 61986506), // GOG
+	ENGLISH_ENTRY("goldenwake", "a-golden-wake.exe", "dbe281d93c914899886e77c09c3c65ec", 130844360), // Steam
+	ENGLISH_ENTRY("kathyrain", "kathyrain.exe", "434e24a12ba3cfb07d7b4b2f0e0bb1bf", 197487159), // Steam
+	ENGLISH_ENTRY("qfi", "qfi.exe", "0702df6e67ef87fd3c51d09303803126", 534847265), // GOG
+	ENGLISH_ENTRY("oott", "OotT-TKC.exe", "11c2421258465cba4bd773c49d918ee3", 467834855), // GOG
+	ENGLISH_ENTRY("primordia", "primordia.exe", "22313e59c3233001488c26f18c80cc08", 973495830), // GOG
+	ENGLISH_ENTRY("resonance", "resonance.exe", "2e635c22bcbf0ed3d46f1bcde71812d4", 849404957), // GOG
+	// For some macOS and iOS releases the executable was renamed to ac2game.dat
+	ENGLISH_ENTRY("mage", "ac2game.dat", "2e822f554994f36e0c62da2acda874da", 30492258), // GOG, Mac
+	ENGLISH_ENTRY("unavowed", "ac2game.dat", "b1ff7d96667707daf4266975cea2bf90", 1755457364), // Steam, Mac
 
 	{ AD_TABLE_END_MARKER }
 };


Commit: dbf63c63dbfeacbd8df60b42756ff0ff44dd05a6
    https://github.com/scummvm/scummvm/commit/dbf63c63dbfeacbd8df60b42756ff0ff44dd05a6
Author: Thierry Crozat (criezy at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Add override keyword

Changed paths:
    engines/ags/ags.h
    engines/ags/detection.h


diff --git a/engines/ags/ags.h b/engines/ags/ags.h
index 2c6b3b1ffd..3c3d8d2e82 100644
--- a/engines/ags/ags.h
+++ b/engines/ags/ags.h
@@ -71,10 +71,10 @@ public:
 	::AGS3::Globals *_globals;
 protected:
 	// Engine APIs
-	virtual Common::Error run();
+	virtual Common::Error run() override;
 public:
 	AGSEngine(OSystem *syst, const AGSGameDescription *gameDesc);
-	virtual ~AGSEngine();
+	virtual ~AGSEngine() override;
 	void GUIError(const Common::String &msg);
 
 	void set_window_title(const char *str) {
diff --git a/engines/ags/detection.h b/engines/ags/detection.h
index f916f2f2a1..e58dffd202 100644
--- a/engines/ags/detection.h
+++ b/engines/ags/detection.h
@@ -38,15 +38,15 @@ public:
 	AGSMetaEngineDetection();
 	~AGSMetaEngineDetection() override {}
 
-	virtual const char *getEngineId() const {
+	virtual const char *getEngineId() const override {
 		return "ags";
 	}
 
-	virtual const char *getName() const {
+	virtual const char *getName() const override {
 		return "Adventure Game Studio";
 	}
 
-	virtual const char *getOriginalCopyright() const {
+	virtual const char *getOriginalCopyright() const override {
 		return "";
 	}
 };


Commit: 05e1af053b7b7183123e36a705456891926d13a0
    https://github.com/scummvm/scummvm/commit/05e1af053b7b7183123e36a705456891926d13a0
Author: Thierry Crozat (criezy at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Use ScummVM endian macros

Changed paths:
    engines/ags/shared/core/platform.h
    engines/ags/shared/util/bbop.h


diff --git a/engines/ags/shared/core/platform.h b/engines/ags/shared/core/platform.h
index bcac2025a1..93479a49d5 100644
--- a/engines/ags/shared/core/platform.h
+++ b/engines/ags/shared/core/platform.h
@@ -23,6 +23,8 @@
 #ifndef AGS_SHARED_CORE_PLATFORM_H
 #define AGS_SHARED_CORE_PLATFORM_H
 
+#include <common/scummsys.h>
+
 namespace AGS3 {
 
 // platform definitions. Not intended for replacing types or checking for libraries.
@@ -117,17 +119,14 @@ namespace AGS3 {
 #define AGS_PLATFORM_64BIT (0)
 #endif
 
-#if defined(_WIN32)
-#define AGS_PLATFORM_ENDIAN_LITTLE  (1)
-#define AGS_PLATFORM_ENDIAN_BIG     (0)
-#elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
+#if defined(SCUMM_LITTLE_ENDIAN)
 #define AGS_PLATFORM_ENDIAN_LITTLE  (1)
 #define AGS_PLATFORM_ENDIAN_BIG     (0)
-#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
+#elif defined(SCUMM_BIG_ENDIAN)
 #define AGS_PLATFORM_ENDIAN_LITTLE  (0)
 #define AGS_PLATFORM_ENDIAN_BIG     (1)
 #else
-#error "Unknown platform"
+#error "No endianness defined"
 #endif
 
 #if defined(_DEBUG)
diff --git a/engines/ags/shared/util/bbop.h b/engines/ags/shared/util/bbop.h
index 48764722f8..0eb32a13a6 100644
--- a/engines/ags/shared/util/bbop.h
+++ b/engines/ags/shared/util/bbop.h
@@ -29,6 +29,7 @@
 #ifndef AGS_SHARED_UTIL_BBOP_H
 #define AGS_SHARED_UTIL_BBOP_H
 
+#include <common/endian.h>
 #include "ags/shared/core/platform.h"
 #include "ags/shared/core/types.h"
 
@@ -52,17 +53,15 @@ enum DataEndianess {
 
 namespace BitByteOperations {
 inline int16_t SwapBytesInt16(const int16_t val) {
-	return ((val >> 8) & 0xFF) | ((val << 8) & 0xFF00);
+	return (int16_t)SWAP_CONSTANT_16(val);
 }
 
 inline int32_t SwapBytesInt32(const int32_t val) {
-	return ((val >> 24) & 0xFF) | ((val >> 8) & 0xFF00) | ((val << 8) & 0xFF0000) | ((val << 24) & 0xFF000000);
+	return (int32_t)SWAP_CONSTANT_32(val);
 }
 
 inline int64_t SwapBytesInt64(const int64_t val) {
-	return ((val >> 56) & 0xFF) | ((val >> 40) & 0xFF00) | ((val >> 24) & 0xFF0000) |
-		((val >> 8) & 0xFF000000) | ((val << 8) & 0xFF00000000LL) |
-		((val << 24) & 0xFF0000000000LL) | ((val << 40) & 0xFF000000000000LL) | ((val << 56) & 0xFF00000000000000LL);
+	return (int64_t)SWAP_CONSTANT_64(val);
 }
 
 inline float SwapBytesFloat(const float val) {
@@ -77,27 +76,15 @@ inline float SwapBytesFloat(const float val) {
 }
 
 inline int16_t Int16FromLE(const int16_t val) {
-#if defined (BITBYTE_BIG_ENDIAN)
-	return SwapBytesInt16(val);
-#else
-	return val;
-#endif
+	return (int16_t)FROM_LE_16(val);
 }
 
 inline int32_t Int32FromLE(const int32_t val) {
-#if defined (BITBYTE_BIG_ENDIAN)
-	return SwapBytesInt32(val);
-#else
-	return val;
-#endif
+	return (int32_t)FROM_LE_32(val);
 }
 
 inline int64_t Int64FromLE(const int64_t val) {
-#if defined (BITBYTE_BIG_ENDIAN)
-	return SwapBytesInt64(val);
-#else
-	return val;
-#endif
+	return (int64_t)FROM_LE_64(val);
 }
 
 inline float FloatFromLE(const float val) {
@@ -109,27 +96,15 @@ inline float FloatFromLE(const float val) {
 }
 
 inline int16_t Int16FromBE(const int16_t val) {
-#if defined (BITBYTE_BIG_ENDIAN)
-	return val;
-#else
-	return SwapBytesInt16(val);
-#endif
+	return (int16_t)FROM_BE_16(val);
 }
 
 inline int32_t Int32FromBE(const int32_t val) {
-#if defined (BITBYTE_BIG_ENDIAN)
-	return val;
-#else
-	return SwapBytesInt32(val);
-#endif
+	return (int32_t)FROM_BE_32(val);
 }
 
 inline int64_t Int64FromBE(const int64_t val) {
-#if defined (BITBYTE_BIG_ENDIAN)
-	return val;
-#else
-	return SwapBytesInt64(val);
-#endif
+	return (int64_t)FROM_BE_64(val);
 }
 
 inline float FloatFromBE(const float val) {


Commit: 712c151498973b196007cb86f8596a41c5dfd4cf
    https://github.com/scummvm/scummvm/commit/712c151498973b196007cb86f8596a41c5dfd4cf
Author: Thierry Crozat (criezy at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix ReadDialogs for some AGS versions on 64 bit systems

Changed paths:
    engines/ags/shared/game/main_game_file.cpp


diff --git a/engines/ags/shared/game/main_game_file.cpp b/engines/ags/shared/game/main_game_file.cpp
index 6a41aa8380..08d55da666 100644
--- a/engines/ags/shared/game/main_game_file.cpp
+++ b/engines/ags/shared/game/main_game_file.cpp
@@ -310,13 +310,13 @@ void ReadDialogs(DialogTopic *&dialog,
 	} else {
 		// Encrypted text on > 2.60
 		while (1) {
-			size_t newlen = (size_t)in->ReadInt32();
+			uint32_t newlen = (uint32_t)in->ReadInt32();
 			if (newlen == 0xCAFEBEEF) { // GUI magic
 				in->Seek(-4);
 				break;
 			}
 
-			newlen = Math::Min(newlen, sizeof(buffer) - 1);
+			newlen = Math::Min(newlen, (uint32_t)sizeof(buffer) - 1);
 			in->Read(buffer, newlen);
 			buffer[newlen] = 0;
 			decrypt_text(buffer);


Commit: e0d5aab8051d7952641f7ff98f38b02b1bb26188
    https://github.com/scummvm/scummvm/commit/e0d5aab8051d7952641f7ff98f38b02b1bb26188
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Remove redundant virtual keywords when override is present

Changed paths:
    engines/ags/ags.h
    engines/ags/detection.h


diff --git a/engines/ags/ags.h b/engines/ags/ags.h
index 3c3d8d2e82..10bcf431fb 100644
--- a/engines/ags/ags.h
+++ b/engines/ags/ags.h
@@ -71,10 +71,10 @@ public:
 	::AGS3::Globals *_globals;
 protected:
 	// Engine APIs
-	virtual Common::Error run() override;
+	Common::Error run() override;
 public:
 	AGSEngine(OSystem *syst, const AGSGameDescription *gameDesc);
-	virtual ~AGSEngine() override;
+	~AGSEngine() override;
 	void GUIError(const Common::String &msg);
 
 	void set_window_title(const char *str) {
diff --git a/engines/ags/detection.h b/engines/ags/detection.h
index e58dffd202..3667582516 100644
--- a/engines/ags/detection.h
+++ b/engines/ags/detection.h
@@ -38,15 +38,15 @@ public:
 	AGSMetaEngineDetection();
 	~AGSMetaEngineDetection() override {}
 
-	virtual const char *getEngineId() const override {
+	const char *getEngineId() const override {
 		return "ags";
 	}
 
-	virtual const char *getName() const override {
+	const char *getName() const override {
 		return "Adventure Game Studio";
 	}
 
-	virtual const char *getOriginalCopyright() const override {
+	const char *getOriginalCopyright() const override {
 		return "";
 	}
 };


Commit: 911c54c7e26c0878933c6b4d538a176261607051
    https://github.com/scummvm/scummvm/commit/911c54c7e26c0878933c6b4d538a176261607051
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Match the 32-bit PixelFormat to decoded bitmaps

The 32-bit bitmap resources encoded by AGS had ARGB rather
than RGBA (or is it the other way around?). Anyway, this
was what was causing the KQ2 title screen to be all red.

Changed paths:
    engines/ags/ags.cpp
    engines/ags/lib/allegro/gfx.cpp


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index 09a58e539d..d3a54972d5 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -367,7 +367,7 @@ SaveStateList AGSEngine::listSaves() const {
 }
 
 void AGSEngine::setGraphicsMode(size_t w, size_t h) {
-	Graphics::PixelFormat FORMAT(4, 8, 8, 8, 8, 24, 16, 8, 0);
+	Graphics::PixelFormat FORMAT(4, 8, 8, 8, 8, 0, 8, 16, 24);
 	initGraphics(w, h, &FORMAT);
 
 	_rawScreen = new Graphics::Screen();
diff --git a/engines/ags/lib/allegro/gfx.cpp b/engines/ags/lib/allegro/gfx.cpp
index 6b973c993c..fc855550b2 100644
--- a/engines/ags/lib/allegro/gfx.cpp
+++ b/engines/ags/lib/allegro/gfx.cpp
@@ -142,7 +142,7 @@ BITMAP *create_bitmap_ex(int color_depth, int width, int height) {
 		format = Graphics::PixelFormat(2, 5, 6, 5, 0, 11, 5, 0, 0);
 		break;
 	case 32:
-		format = Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0);
+		format = Graphics::PixelFormat(4, 8, 8, 8, 8, 0, 8, 16, 24);
 		break;
 	default:
 		error("Invalid color depth");


Commit: 982a708f0f697fd4bb5275781f04b366258b0a5b
    https://github.com/scummvm/scummvm/commit/982a708f0f697fd4bb5275781f04b366258b0a5b
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Move plugins/ folder into AGS3 namespace

Changed paths:
    engines/ags/engine/plugin/library.cpp
    engines/ags/plugins/agscreditz/agscreditz.cpp
    engines/ags/plugins/agscreditz/agscreditz.h
    engines/ags/plugins/dll.cpp
    engines/ags/plugins/dll.h


diff --git a/engines/ags/engine/plugin/library.cpp b/engines/ags/engine/plugin/library.cpp
index 7b64088194..814fab68dc 100644
--- a/engines/ags/engine/plugin/library.cpp
+++ b/engines/ags/engine/plugin/library.cpp
@@ -26,19 +26,19 @@
 namespace AGS3 {
 
 void *dlopen(const char *filename, bool) {
-	return ::AGS::Plugins::dlopen(filename);
+	return Plugins::dlopen(filename);
 }
 
 int dlclose(void *lib) {
-	return ::AGS::Plugins::dlclose(lib);
+	return Plugins::dlclose(lib);
 }
 
 void *dlsym(void *lib, const char *method) {
-	return ::AGS::Plugins::dlsym(lib, method);
+	return Plugins::dlsym(lib, method);
 }
 
 const char *dlerror() {
-	return ::AGS::Plugins::dlerror();
+	return Plugins::dlerror();
 }
 
 } // namespace AGS3
diff --git a/engines/ags/plugins/agscreditz/agscreditz.cpp b/engines/ags/plugins/agscreditz/agscreditz.cpp
index 8f30b69f0f..21a0ce3ecb 100644
--- a/engines/ags/plugins/agscreditz/agscreditz.cpp
+++ b/engines/ags/plugins/agscreditz/agscreditz.cpp
@@ -22,7 +22,7 @@
 
 #include "ags/plugins/agscreditz/agscreditz.h"
 
-namespace AGS {
+namespace AGS3 {
 namespace Plugins {
 namespace AgsCreditz {
 
@@ -147,4 +147,4 @@ int AgsCreditz::IsStaticCreditsFinished(const ScriptMethodParams &params) {
 
 } // namespace AgsCreditz
 } // namespace Plugins
-} // namespace AGS
+} // namespace AGS3
diff --git a/engines/ags/plugins/agscreditz/agscreditz.h b/engines/ags/plugins/agscreditz/agscreditz.h
index d10c1a8893..a19a867035 100644
--- a/engines/ags/plugins/agscreditz/agscreditz.h
+++ b/engines/ags/plugins/agscreditz/agscreditz.h
@@ -25,7 +25,7 @@
 
 #include "ags/plugins/dll.h"
 
-namespace AGS {
+namespace AGS3 {
 namespace Plugins {
 namespace AgsCreditz {
 
@@ -62,6 +62,6 @@ public:
 
 } // namespace AgsCreditz
 } // namespace Plugins
-} // namespace AGS
+} // namespace AGS3
 
 #endif
diff --git a/engines/ags/plugins/dll.cpp b/engines/ags/plugins/dll.cpp
index a964949027..c9a1d9e915 100644
--- a/engines/ags/plugins/dll.cpp
+++ b/engines/ags/plugins/dll.cpp
@@ -24,7 +24,7 @@
 #include "ags/plugins/agscreditz/agscreditz.h"
 #include "common/str.h"
 
-namespace AGS {
+namespace AGS3 {
 namespace Plugins {
 
 void *dlopen(const char *filename) {
@@ -103,4 +103,4 @@ void DLL::AGS_EngineInitGfx(const char *driverID, void *data) {
 }
 
 } // namespace Plugins
-} // namespace AGS
+} // namespace AGS3
diff --git a/engines/ags/plugins/dll.h b/engines/ags/plugins/dll.h
index 2d653a4edc..c198add1f6 100644
--- a/engines/ags/plugins/dll.h
+++ b/engines/ags/plugins/dll.h
@@ -28,7 +28,7 @@
 #include "common/hashmap.h"
 #include "common/hash-str.h"
 
-namespace AGS {
+namespace AGS3 {
 namespace Plugins {
 
 #define DLL_METHOD(NAME) _methods[#NAME] = (void *)&NAME
@@ -80,12 +80,7 @@ namespace Plugins {
 	T8 N8 = (T8)params[7]
 
 
-// TODO: Refactor string into core AGS namespace
 using string = const char *;
-using ScriptMethodParams = ::AGS3::ScriptMethodParams;
-
-using IAGSEngine = ::AGS3::IAGSEngine;
-using IAGSEditor = ::AGS3::IAGSEditor;
 typedef uint32 HWND;
 
 /**
@@ -123,6 +118,6 @@ extern void *dlsym(void *lib, const char *method);
 extern const char *dlerror();
 
 } // namespace Plugins
-} // namespace AGS
+} // namespace AGS3
 
 #endif


Commit: 03c7491e1867e2a824705eb9378695719710224b
    https://github.com/scummvm/scummvm/commit/03c7491e1867e2a824705eb9378695719710224b
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix compilation of VS 64-bit builds

Changed paths:
    engines/ags/engine/ac/string.cpp
    engines/ags/engine/ac/string.h
    engines/ags/engine/gui/cscidialog.cpp
    engines/ags/engine/gui/cscidialog.h
    engines/ags/engine/gui/guidialog.cpp
    engines/ags/engine/gui/mylabel.cpp
    engines/ags/engine/gui/mylabel.h
    engines/ags/engine/gui/mylistbox.cpp
    engines/ags/engine/gui/mylistbox.h
    engines/ags/engine/gui/mypushbutton.cpp
    engines/ags/engine/gui/mypushbutton.h
    engines/ags/engine/gui/mytextbox.cpp
    engines/ags/engine/gui/mytextbox.h
    engines/ags/engine/gui/newcontrol.h
    engines/ags/lib/aastr-0.1.1/aarot.cpp
    engines/ags/lib/aastr-0.1.1/aastr.cpp
    engines/ags/lib/aastr-0.1.1/aautil.cpp
    engines/ags/lib/aastr-0.1.1/aautil.h
    engines/ags/lib/allegro/gfx.cpp
    engines/ags/lib/allegro/gfx.h
    engines/ags/shared/core/types.h


diff --git a/engines/ags/engine/ac/string.cpp b/engines/ags/engine/ac/string.cpp
index 305629a497..d679db77ad 100644
--- a/engines/ags/engine/ac/string.cpp
+++ b/engines/ags/engine/ac/string.cpp
@@ -273,9 +273,9 @@ size_t break_up_text_into_lines(const char *todis, SplitLines &lines, int wii, i
 int MAXSTRLEN = MAX_MAXSTRLEN;
 void check_strlen(char *ptt) {
 	MAXSTRLEN = MAX_MAXSTRLEN;
-	long charstart = (long)&game.chars[0];
-	long charend = charstart + sizeof(CharacterInfo) * game.numcharacters;
-	if (((long)&ptt[0] >= charstart) && ((long)&ptt[0] <= charend))
+	const byte *charstart = (const byte *)&game.chars[0];
+	const byte *charend = charstart + sizeof(CharacterInfo) * game.numcharacters;
+	if (((const byte *)&ptt[0] >= charstart) && ((const byte *)&ptt[0] <= charend))
 		MAXSTRLEN = 30;
 }
 
diff --git a/engines/ags/engine/ac/string.h b/engines/ags/engine/ac/string.h
index 1d606e9a2d..df911864a1 100644
--- a/engines/ags/engine/ac/string.h
+++ b/engines/ags/engine/ac/string.h
@@ -29,7 +29,7 @@
 namespace AGS3 {
 
 // Check that a supplied buffer from a text script function was not null
-#define VALIDATE_STRING(strin) if ((unsigned long)strin <= 4096) quit("!String argument was null: make sure you pass a string, not an int, as a buffer")
+#define VALIDATE_STRING(strin) if (reinterpret_cast<intptr_t>(strin) <= 4096) quit("!String argument was null: make sure you pass a string, not an int, as a buffer")
 
 int String_IsNullOrEmpty(const char *thisString);
 const char *String_Copy(const char *srcString);
diff --git a/engines/ags/engine/gui/cscidialog.cpp b/engines/ags/engine/gui/cscidialog.cpp
index 5f26837c58..48da261d1f 100644
--- a/engines/ags/engine/gui/cscidialog.cpp
+++ b/engines/ags/engine/gui/cscidialog.cpp
@@ -243,7 +243,7 @@ void CSCIDeleteControl(int haa) {
 	vobjs[haa] = nullptr;
 }
 
-int CSCISendControlMessage(int haa, int mess, int wPar, long lPar) {
+int CSCISendControlMessage(int haa, int mess, int wPar, NumberPtr lPar) {
 	if (vobjs[haa] == nullptr)
 		return -1;
 	return vobjs[haa]->processmessage(mess, wPar, lPar);
diff --git a/engines/ags/engine/gui/cscidialog.h b/engines/ags/engine/gui/cscidialog.h
index 5a360b1faa..5afe6ca286 100644
--- a/engines/ags/engine/gui/cscidialog.h
+++ b/engines/ags/engine/gui/cscidialog.h
@@ -39,7 +39,7 @@ void CSCIEraseWindow(int handl);
 int  CSCIWaitMessage(CSCIMessage *cscim);
 int  CSCICreateControl(int typeandflags, int xx, int yy, int wii, int hii, const char *title);
 void CSCIDeleteControl(int haa);
-int  CSCISendControlMessage(int haa, int mess, int wPar, long lPar);
+int  CSCISendControlMessage(int haa, int mess, int wPar, NumberPtr lPar);
 void multiply_up_to_game_res(int *x, int *y);
 void multiply_up(int *x1, int *y1, int *x2, int *y2);
 int  checkcontrols();
diff --git a/engines/ags/engine/gui/guidialog.cpp b/engines/ags/engine/gui/guidialog.cpp
index 56002f6bb1..d80f2429b3 100644
--- a/engines/ags/engine/gui/guidialog.cpp
+++ b/engines/ags/engine/gui/guidialog.cpp
@@ -192,11 +192,11 @@ int savegamedialog() {
 
 	lpTemp = nullptr;
 	if (numsaves > 0)
-		CSCISendControlMessage(ctrllist, CLB_GETTEXT, 0, (long)&buffer2[0]);
+		CSCISendControlMessage(ctrllist, CLB_GETTEXT, 0,  &buffer2[0]);
 	else
 		buffer2[0] = 0;
 
-	CSCISendControlMessage(ctrltbox, CTB_SETTEXT, 0, (long)&buffer2[0]);
+	CSCISendControlMessage(ctrltbox, CTB_SETTEXT, 0, &buffer2[0]);
 
 	int toret = -1;
 	while (1) {
@@ -204,10 +204,10 @@ int savegamedialog() {
 		if (mes.code == CM_COMMAND) {
 			if (mes.id == ctrlok) {
 				int cursell = CSCISendControlMessage(ctrllist, CLB_GETCURSEL, 0, 0);
-				CSCISendControlMessage(ctrltbox, CTB_GETTEXT, 0, (long)&buffer2[0]);
+				CSCISendControlMessage(ctrltbox, CTB_GETTEXT, 0, &buffer2[0]);
 
 				if (numsaves > 0)
-					CSCISendControlMessage(ctrllist, CLB_GETTEXT, cursell, (long)&bufTemp[0]);
+					CSCISendControlMessage(ctrllist, CLB_GETTEXT, cursell, &bufTemp[0]);
 				else
 					strcpy(bufTemp, "_NOSAVEGAMENAME");
 
@@ -231,7 +231,7 @@ int savegamedialog() {
 						CSCIWaitMessage(&cmes);
 					} while (cmes.code != CM_COMMAND);
 
-					CSCISendControlMessage(txt1, CTB_GETTEXT, 0, (long)&buffer2[0]);
+					CSCISendControlMessage(txt1, CTB_GETTEXT, 0, &buffer2[0]);
 					CSCIDeleteControl(btnCancel);
 					CSCIDeleteControl(btnOk);
 					CSCIDeleteControl(txt1);
@@ -279,8 +279,8 @@ int savegamedialog() {
 		} else if (mes.code == CM_SELCHANGE) {
 			int cursel = CSCISendControlMessage(ctrllist, CLB_GETCURSEL, 0, 0);
 			if (cursel >= 0) {
-				CSCISendControlMessage(ctrllist, CLB_GETTEXT, cursel, (long)&buffer2[0]);
-				CSCISendControlMessage(ctrltbox, CTB_SETTEXT, 0, (long)&buffer2[0]);
+				CSCISendControlMessage(ctrllist, CLB_GETTEXT, cursel, &buffer2[0]);
+				CSCISendControlMessage(ctrltbox, CTB_SETTEXT, 0, &buffer2[0]);
 			}
 		}
 	}
@@ -305,7 +305,8 @@ void preparesavegamelist(int ctrllist) {
 		Common::String desc = it->getDescription();
 
 		// TODO: Casting pointer to long is nasty
-		CSCISendControlMessage(ctrllist, CLB_ADDITEM, 0, (long)desc.c_str());
+		CSCISendControlMessage(ctrllist, CLB_ADDITEM, 0,
+			const_cast<char *>(desc.c_str()));
 
 		// Select the first item
 		CSCISendControlMessage(ctrllist, CLB_SETCURSEL, 0, 0);
@@ -321,10 +322,10 @@ void preparesavegamelist(int ctrllist) {
 	for (int nn = 0; nn < numsaves - 1; nn++) {
 		for (int kk = 0; kk < numsaves - 1; kk++) { // Date order the games
 			if (filedates[kk] < filedates[kk + 1]) {  // swap them round
-				CSCISendControlMessage(ctrllist, CLB_GETTEXT, kk, (long)&buff[0]);
-				CSCISendControlMessage(ctrllist, CLB_GETTEXT, kk + 1, (long)&buffer2[0]);
-				CSCISendControlMessage(ctrllist, CLB_SETTEXT, kk + 1, (long)&buff[0]);
-				CSCISendControlMessage(ctrllist, CLB_SETTEXT, kk, (long)&buffer2[0]);
+				CSCISendControlMessage(ctrllist, CLB_GETTEXT, kk, &buff[0]);
+				CSCISendControlMessage(ctrllist, CLB_GETTEXT, kk + 1, &buffer2[0]);
+				CSCISendControlMessage(ctrllist, CLB_SETTEXT, kk + 1, &buff[0]);
+				CSCISendControlMessage(ctrllist, CLB_SETTEXT, kk, &buffer2[0]);
 				int numtem = filenumbers[kk];
 				filenumbers[kk] = filenumbers[kk + 1];
 				filenumbers[kk + 1] = numtem;
@@ -361,7 +362,7 @@ void enterstringwindow(const char *prompttext, char *stouse) {
 			if (mes.id == ctrlcancel)
 				buffer2[0] = 0;
 			else
-				CSCISendControlMessage(ctrltbox, CTB_GETTEXT, 0, (long)&buffer2[0]);
+				CSCISendControlMessage(ctrltbox, CTB_GETTEXT, 0, &buffer2[0]);
 			break;
 		}
 	}
@@ -400,7 +401,7 @@ int roomSelectorWindow(int currentRoom, int numRooms, int *roomNumbers, char **r
 	CSCISendControlMessage(ctrllist, CLB_CLEAR, 0, 0);    // clear the list box
 	for (int aa = 0; aa < numRooms; aa++) {
 		sprintf(buff, "%3d %s", roomNumbers[aa], roomNames[aa]);
-		CSCISendControlMessage(ctrllist, CLB_ADDITEM, 0, (long)&buff[0]);
+		CSCISendControlMessage(ctrllist, CLB_ADDITEM, 0, &buff[0]);
 		if (roomNumbers[aa] == currentRoom) {
 			CSCISendControlMessage(ctrllist, CLB_SETCURSEL, aa, 0);
 		}
@@ -414,14 +415,14 @@ int roomSelectorWindow(int currentRoom, int numRooms, int *roomNumbers, char **r
 	buffer2[0] = 0;
 
 	int ctrltbox = CSCICreateControl(CNT_TEXTBOX, 10, 29, 120, 0, nullptr);
-	CSCISendControlMessage(ctrltbox, CTB_SETTEXT, 0, (long)&buffer2[0]);
+	CSCISendControlMessage(ctrltbox, CTB_SETTEXT, 0, &buffer2[0]);
 
 	int toret = -1;
 	while (1) {
 		CSCIWaitMessage(&mes);      //printf("mess: %d, id %d ",mes.code,mes.id);
 		if (mes.code == CM_COMMAND) {
 			if (mes.id == ctrlok) {
-				CSCISendControlMessage(ctrltbox, CTB_GETTEXT, 0, (long)&buffer2[0]);
+				CSCISendControlMessage(ctrltbox, CTB_GETTEXT, 0, &buffer2[0]);
 				if (Common::isDigit(buffer2[0])) {
 					toret = atoi(buffer2);
 				}
@@ -432,7 +433,7 @@ int roomSelectorWindow(int currentRoom, int numRooms, int *roomNumbers, char **r
 			int cursel = CSCISendControlMessage(ctrllist, CLB_GETCURSEL, 0, 0);
 			if (cursel >= 0) {
 				sprintf(buffer2, "%d", roomNumbers[cursel]);
-				CSCISendControlMessage(ctrltbox, CTB_SETTEXT, 0, (long)&buffer2[0]);
+				CSCISendControlMessage(ctrltbox, CTB_SETTEXT, 0, &buffer2[0]);
 			}
 		}
 	}
diff --git a/engines/ags/engine/gui/mylabel.cpp b/engines/ags/engine/gui/mylabel.cpp
index 69a330b984..817d643d76 100644
--- a/engines/ags/engine/gui/mylabel.cpp
+++ b/engines/ags/engine/gui/mylabel.cpp
@@ -63,7 +63,7 @@ int MyLabel::pressedon(int mouseX, int mouseY) {
 	return 0;
 }
 
-int MyLabel::processmessage(int mcode, int wParam, long lParam) {
+int MyLabel::processmessage(int mcode, int wParam, NumberPtr lParam) {
 	return -1;                  // doesn't support messages
 }
 
diff --git a/engines/ags/engine/gui/mylabel.h b/engines/ags/engine/gui/mylabel.h
index 67cdc55082..43722cfee9 100644
--- a/engines/ags/engine/gui/mylabel.h
+++ b/engines/ags/engine/gui/mylabel.h
@@ -35,7 +35,7 @@ struct MyLabel : public NewControl {
 
 	int pressedon(int mouseX, int mouseY) override;
 
-	int processmessage(int mcode, int wParam, long lParam) override;
+	int processmessage(int mcode, int wParam, NumberPtr lParam) override;
 };
 
 } // namespace AGS3
diff --git a/engines/ags/engine/gui/mylistbox.cpp b/engines/ags/engine/gui/mylistbox.cpp
index c0e77e92da..2579767a1e 100644
--- a/engines/ags/engine/gui/mylistbox.cpp
+++ b/engines/ags/engine/gui/mylistbox.cpp
@@ -139,9 +139,9 @@ void MyListBox::additem(char *texx) {
 	needredraw = 1;
 }
 
-int MyListBox::processmessage(int mcode, int wParam, long lParam) {
+int MyListBox::processmessage(int mcode, int wParam, NumberPtr lParam) {
 	if (mcode == CLB_ADDITEM) {
-		additem((char *)lParam);
+		additem((char *)lParam._ptr);
 	} else if (mcode == CLB_CLEAR)
 		clearlist();
 	else if (mcode == CLB_GETCURSEL)
@@ -155,12 +155,12 @@ int MyListBox::processmessage(int mcode, int wParam, long lParam) {
 		if (topitem + numonscreen <= selected)
 			topitem = (selected + 1) - numonscreen;
 	} else if (mcode == CLB_GETTEXT)
-		strcpy((char *)lParam, itemnames[wParam]);
+		strcpy((char *)lParam._ptr, itemnames[wParam]);
 	else if (mcode == CLB_SETTEXT) {
 		if (wParam < items)
 			free(itemnames[wParam]);
 
-		char *newstri = (char *)lParam;
+		char *newstri = (char *)lParam._ptr;
 		itemnames[wParam] = (char *)malloc(strlen(newstri) + 2);
 		strcpy(itemnames[wParam], newstri);
 
diff --git a/engines/ags/engine/gui/mylistbox.h b/engines/ags/engine/gui/mylistbox.h
index b70b45ee4f..a817029d8a 100644
--- a/engines/ags/engine/gui/mylistbox.h
+++ b/engines/ags/engine/gui/mylistbox.h
@@ -40,7 +40,7 @@ struct MyListBox : public NewControl {
 	void draw(Shared::Bitmap *ds) override;
 	int pressedon(int mousex, int mousey) override;
 	void additem(char *texx);
-	int processmessage(int mcode, int wParam, long lParam) override;
+	int processmessage(int mcode, int wParam, NumberPtr lParam) override;
 };
 
 } // namespace AGS3
diff --git a/engines/ags/engine/gui/mypushbutton.cpp b/engines/ags/engine/gui/mypushbutton.cpp
index f4dcc4c86b..7fbc5c7f10 100644
--- a/engines/ags/engine/gui/mypushbutton.cpp
+++ b/engines/ags/engine/gui/mypushbutton.cpp
@@ -109,7 +109,7 @@ int MyPushButton::pressedon(int mousex, int mousey) {
 	return wasstat;
 }
 
-int MyPushButton::processmessage(int mcode, int wParam, long lParam) {
+int MyPushButton::processmessage(int mcode, int wParam, NumberPtr lParam) {
 	return -1;                  // doesn't support messages
 }
 
diff --git a/engines/ags/engine/gui/mypushbutton.h b/engines/ags/engine/gui/mypushbutton.h
index 2ba6ca11ca..3fc69782fd 100644
--- a/engines/ags/engine/gui/mypushbutton.h
+++ b/engines/ags/engine/gui/mypushbutton.h
@@ -32,7 +32,7 @@ struct MyPushButton : public NewControl {
 	MyPushButton(int xx, int yy, int wi, int hi, const char *tex);
 	void draw(Shared::Bitmap *ds) override;
 	int pressedon(int mousex, int mousey) override;
-	int processmessage(int mcode, int wParam, long lParam) override;
+	int processmessage(int mcode, int wParam, NumberPtr lParam) override;
 };
 
 } // namespace AGS3
diff --git a/engines/ags/engine/gui/mytextbox.cpp b/engines/ags/engine/gui/mytextbox.cpp
index b0d45b0218..48507fb7de 100644
--- a/engines/ags/engine/gui/mytextbox.cpp
+++ b/engines/ags/engine/gui/mytextbox.cpp
@@ -64,12 +64,12 @@ int MyTextBox::pressedon(int mousex, int mousey) {
 	return 0;
 }
 
-int MyTextBox::processmessage(int mcode, int wParam, long lParam) {
+int MyTextBox::processmessage(int mcode, int wParam, NumberPtr lParam) {
 	if (mcode == CTB_SETTEXT) {
-		strcpy(text, (char *)lParam);
+		strcpy(text, (char *)lParam._ptr);
 		needredraw = 1;
 	} else if (mcode == CTB_GETTEXT)
-		strcpy((char *)lParam, text);
+		strcpy((char *)lParam._ptr, text);
 	else if (mcode == CTB_KEYPRESS) {
 		if (wParam == 8) {
 			if (text[0] != 0)
diff --git a/engines/ags/engine/gui/mytextbox.h b/engines/ags/engine/gui/mytextbox.h
index a2a3e7d166..db7602c1eb 100644
--- a/engines/ags/engine/gui/mytextbox.h
+++ b/engines/ags/engine/gui/mytextbox.h
@@ -33,7 +33,7 @@ struct MyTextBox : public NewControl {
 	MyTextBox(int xx, int yy, int wii, const char *tee);
 	void draw(Shared::Bitmap *ds) override;
 	int pressedon(int mousex, int mousey) override;
-	int processmessage(int mcode, int wParam, long lParam) override;
+	int processmessage(int mcode, int wParam, NumberPtr lParam) override;
 };
 
 } // namespace AGS3
diff --git a/engines/ags/engine/gui/newcontrol.h b/engines/ags/engine/gui/newcontrol.h
index cfb19f128c..43232819fd 100644
--- a/engines/ags/engine/gui/newcontrol.h
+++ b/engines/ags/engine/gui/newcontrol.h
@@ -35,7 +35,7 @@ struct NewControl {
 	char needredraw;
 	virtual void draw(Shared::Bitmap *ds) = 0;
 	virtual int pressedon(int mousex, int mousey) = 0;
-	virtual int processmessage(int, int, long) = 0;
+	virtual int processmessage(int, int, NumberPtr) = 0;
 
 	NewControl(int xx, int yy, int wi, int hi);
 	NewControl();
diff --git a/engines/ags/lib/aastr-0.1.1/aarot.cpp b/engines/ags/lib/aastr-0.1.1/aarot.cpp
index 0c9a364da9..2f4b65a7de 100644
--- a/engines/ags/lib/aastr-0.1.1/aarot.cpp
+++ b/engines/ags/lib/aastr-0.1.1/aarot.cpp
@@ -66,7 +66,7 @@ _aa_rotate_bitmap(BITMAP *_src, BITMAP *_dst, int _x, int _y, fixed _angle,
 	int syinc, sydd, syi1, syi2;
 	unsigned long num;
 	void (*add) (BITMAP * _src, int _sx1, int _sx2, int _sy1, int _sy2, unsigned long _num);
-	void (*put) (unsigned long _addr, int _x);
+	void (*put) (byte *_addr, int _x);
 
 	if (_dst->clip) {
 		xbeg = _dst->cl;
@@ -449,7 +449,7 @@ _aa_rotate_bitmap(BITMAP *_src, BITMAP *_dst, int _x, int _y, fixed _angle,
 
 	/* Stretch lines.  */
 	while (dy < yend) {
-		unsigned long daddr = bmp_write_line(_dst, dy);
+		byte *daddr = bmp_write_line(_dst, dy);
 
 		if ((ldx < xend) && (rdx >= xbeg)) {
 			int curxend;
diff --git a/engines/ags/lib/aastr-0.1.1/aastr.cpp b/engines/ags/lib/aastr-0.1.1/aastr.cpp
index b753d9e5f2..3cc53b647a 100644
--- a/engines/ags/lib/aastr-0.1.1/aastr.cpp
+++ b/engines/ags/lib/aastr-0.1.1/aastr.cpp
@@ -53,8 +53,8 @@ _aa_stretch_blit(BITMAP *_src, BITMAP *_dst,
 	int yi1, yi2, ydd;
 	int dxbeg, dxend, dybeg, dyend;
 	unsigned long num;
-	void (*add) (BITMAP * _src, int _sx1, int _sx2, int _sy1, int _sy2, unsigned long _num);
-	void (*put) (unsigned long _addr, int _x);
+	void (*add)(BITMAP * _src, int _sx1, int _sx2, int _sy1, int _sy2, unsigned long _num);
+	void (*put)(byte *_addr, int _x);
 
 	if ((_dw <= 0) || (_dh <= 0) || (_sw <= 0) || (_sh <= 0))
 		return;
@@ -188,7 +188,7 @@ _aa_stretch_blit(BITMAP *_src, BITMAP *_dst,
 
 	/* Stretch all non-clipped lines.  */
 	for (; dy < dyend; dy++) {
-		unsigned long daddr = bmp_write_line(_dst, dy);
+		byte *daddr = bmp_write_line(_dst, dy);
 
 		for (dx = ydx, sx = ysx, xdd = yxdd; dx < dxend; dx++) {
 			(*add) (_src, sx, sx + dsx, sy, sy + dsy, num);
diff --git a/engines/ags/lib/aastr-0.1.1/aautil.cpp b/engines/ags/lib/aastr-0.1.1/aautil.cpp
index ebd0889cf3..98e50e9882 100644
--- a/engines/ags/lib/aastr-0.1.1/aautil.cpp
+++ b/engines/ags/lib/aastr-0.1.1/aautil.cpp
@@ -722,44 +722,33 @@ _aa_add_rgb32 (BITMAP *_src, int _sx1, int _sx2, int _sy1, int _sy2, unsigned lo
 /*
  * Putting pixel to destination bitmap.
  */
-void
-_aa_put_rgb8 (unsigned long _addr, int _x)
-{
-  bmp_write8 (_addr + _x, makecol8(_aa.r, _aa.g, _aa.b));
+void _aa_put_rgb8(byte *addr, int _x) {
+  bmp_write8(addr + _x, makecol8(_aa.r, _aa.g, _aa.b));
 }
 #ifdef ALLEGRO_COLOR16
-void
-_aa_put_rgb15 (unsigned long _addr, int _x)
-{
-  bmp_write15 (_addr + sizeof (short) * _x, makecol15 (_aa.r, _aa.g, _aa.b));
+void _aa_put_rgb15 (byte *addr, int _x) {
+  bmp_write15 (addr + sizeof (short) * _x, makecol15 (_aa.r, _aa.g, _aa.b));
 }
-void
-_aa_put_rgb16 (unsigned long _addr, int _x)
-{
-  bmp_write16 (_addr + sizeof (short) * _x, makecol16 (_aa.r, _aa.g, _aa.b));
+
+void _aa_put_rgb16 (byte *addr, int _x) {
+  bmp_write16 (addr + sizeof (short) * _x, makecol16 (_aa.r, _aa.g, _aa.b));
 }
 #endif
 #ifdef ALLEGRO_COLOR24
-void
-_aa_put_rgb24 (unsigned long _addr, int _x)
-{
-  bmp_write24 (_addr + 3 * _x, makecol24 (_aa.r, _aa.g, _aa.g));
+void _aa_put_rgb24 (byte *addr, int _x) {
+  bmp_write24 (addr + 3 * _x, makecol24 (_aa.r, _aa.g, _aa.g));
 }
 #endif
 #ifdef ALLEGRO_COLOR32
-void
-_aa_put_rgb32 (unsigned long _addr, int _x)
-{
-  bmp_write32 (_addr + sizeof (int) * _x, makecol32 (_aa.r, _aa.g, _aa.b));
+void _aa_put_rgb32 (byte *addr, int _x) {
+  bmp_write32 (addr + sizeof (int) * _x, makecol32 (_aa.r, _aa.g, _aa.b));
 }
 #endif
 
 /*
  * Add masked r, g, b values of pixels.
  */
-void
-_aa_masked_add_rgb8 (BITMAP *_src, int _sx1, int _sx2, int _sy1, int _sy2, unsigned long _num)
-{
+void _aa_masked_add_rgb8 (BITMAP *_src, int _sx1, int _sx2, int _sy1, int _sy2, unsigned long _num) {
   unsigned char *sline;
   int sx, sx1i, sx1f, sx2i, sx2f;
   int sy, sy1i, sy1f, sy2i, sy2f;
@@ -1796,39 +1785,39 @@ _aa_masked_add_rgb32 (BITMAP *_src, int _sx1, int _sx2, int _sy1, int _sy2, unsi
  * Putting pixel to destination bitmap.
  */
 void
-_aa_masked_put_rgb8 (unsigned long _addr, int _x)
+_aa_masked_put_rgb8(byte *addr, int _x)
 {
   if (!_aa.transparent)
-    bmp_write8 (_addr + _x, makecol8 (_aa.r, _aa.g, _aa.b));
+    bmp_write8(addr + _x, makecol8 (_aa.r, _aa.g, _aa.b));
 }
 #ifdef ALLEGRO_COLOR16
 void
-_aa_masked_put_rgb15 (unsigned long _addr, int _x)
+_aa_masked_put_rgb15 (byte *addr, int _x)
 {
   if (!_aa.transparent)
-    bmp_write15 (_addr + sizeof (short) * _x, makecol15 (_aa.r, _aa.g, _aa.b));
+    bmp_write15 (addr + sizeof (short) * _x, makecol15 (_aa.r, _aa.g, _aa.b));
 }
 void
-_aa_masked_put_rgb16 (unsigned long _addr, int _x)
+_aa_masked_put_rgb16 (byte *addr, int _x)
 {
   if (!_aa.transparent)
-    bmp_write16 (_addr + sizeof (short) * _x, makecol16 (_aa.r, _aa.g, _aa.b));
+    bmp_write16 (addr + sizeof (short) * _x, makecol16 (_aa.r, _aa.g, _aa.b));
 }
 #endif
 #ifdef ALLEGRO_COLOR24
 void
-_aa_masked_put_rgb24 (unsigned long _addr, int _x)
+_aa_masked_put_rgb24 (byte *addr, int _x)
 {
   if (!_aa.transparent)
-    bmp_write24 (_addr + 3 * _x, makecol24 (_aa.r, _aa.g, _aa.b));
+    bmp_write24 (addr + 3 * _x, makecol24 (_aa.r, _aa.g, _aa.b));
 }
 #endif
 #ifdef ALLEGRO_COLOR32
 void
-_aa_masked_put_rgb32 (unsigned long _addr, int _x)
+_aa_masked_put_rgb32 (byte *addr, int _x)
 {
   if (!_aa.transparent)
-    bmp_write32 (_addr + sizeof (int) * _x, makecol32 (_aa.r, _aa.g, _aa.b));
+    bmp_write32 (addr + sizeof (int) * _x, makecol32 (_aa.r, _aa.g, _aa.b));
 }
 
 #endif
diff --git a/engines/ags/lib/aastr-0.1.1/aautil.h b/engines/ags/lib/aastr-0.1.1/aautil.h
index 8616f8c286..7dce41fe14 100644
--- a/engines/ags/lib/aastr-0.1.1/aautil.h
+++ b/engines/ags/lib/aastr-0.1.1/aautil.h
@@ -114,16 +114,16 @@ extern "C" {
 #endif
 
 	/* Put pixel to destination bitmap.  */
-	void _aa_put_rgb8(unsigned long _addr, int _x);
+	void _aa_put_rgb8(byte *addr, int _x);
 #ifdef ALLEGRO_COLOR16
-	void _aa_put_rgb15(unsigned long _addr, int _x);
-	void _aa_put_rgb16(unsigned long _addr, int _x);
+	void _aa_put_rgb15(byte *addr, int _x);
+	void _aa_put_rgb16(byte *addr, int _x);
 #endif
 #ifdef ALLEGRO_COLOR24
-	void _aa_put_rgb24(unsigned long _addr, int _x);
+	void _aa_put_rgb24(byte *addr, int _x);
 #endif
 #ifdef ALLEGRO_COLOR32
-	void _aa_put_rgb32(unsigned long _addr, int _x);
+	void _aa_put_rgb32(byte *addr, int _x);
 #endif
 
 	/* Add r,g,b and transparency values from source bitmap.  */
@@ -145,16 +145,16 @@ extern "C" {
 #endif
 
 	/* Put masked pixel to destination bitmap.  */
-	void _aa_masked_put_rgb8(unsigned long _addr, int _x);
+	void _aa_masked_put_rgb8(byte *addr, int _x);
 #ifdef ALLEGRO_COLOR16
-	void _aa_masked_put_rgb15(unsigned long _addr, int _x);
-	void _aa_masked_put_rgb16(unsigned long _addr, int _x);
+	void _aa_masked_put_rgb15(byte *addr, int _x);
+	void _aa_masked_put_rgb16(byte *addr, int _x);
 #endif
 #ifdef ALLEGRO_COLOR24
-	void _aa_masked_put_rgb24(unsigned long _addr, int _x);
+	void _aa_masked_put_rgb24(byte *addr, int _x);
 #endif
 #ifdef ALLEGRO_COLOR32
-	void _aa_masked_put_rgb32(unsigned long _addr, int _x);
+	void _aa_masked_put_rgb32(byte *addr, int _x);
 #endif
 
 #ifdef __cplusplus
diff --git a/engines/ags/lib/allegro/gfx.cpp b/engines/ags/lib/allegro/gfx.cpp
index fc855550b2..065e5738fa 100644
--- a/engines/ags/lib/allegro/gfx.cpp
+++ b/engines/ags/lib/allegro/gfx.cpp
@@ -338,16 +338,16 @@ void bmp_select(BITMAP *bmp) {
 	// No implementation needed
 }
 
-long bmp_write_line(BITMAP *bmp, int line) {
-	return (long)bmp->line[line];
+byte *bmp_write_line(BITMAP *bmp, int line) {
+	return bmp->line[line];
 }
 
 void bmp_unwrite_line(BITMAP *bmp) {
 	// No implementation needed
 }
 
-void bmp_write8(unsigned long addr, int color) {
-	*((byte *)addr) = color;
+void bmp_write8(byte *addr, int color) {
+	*addr = color;
 }
 
 void memory_putpixel(BITMAP *bmp, int x, int y, int color) {
diff --git a/engines/ags/lib/allegro/gfx.h b/engines/ags/lib/allegro/gfx.h
index 5075bd9a9a..b5006e55af 100644
--- a/engines/ags/lib/allegro/gfx.h
+++ b/engines/ags/lib/allegro/gfx.h
@@ -310,9 +310,9 @@ extern bool is_video_bitmap(BITMAP *bmp);
 extern bool is_linear_bitmap(BITMAP *bmp);
 extern bool is_planar_bitmap(BITMAP *bmp);
 extern void bmp_select(BITMAP *bmp);
-extern long bmp_write_line(BITMAP *bmp, int line);
+extern byte *bmp_write_line(BITMAP *bmp, int line);
 extern void bmp_unwrite_line(BITMAP *bmp);
-extern void bmp_write8(unsigned long addr, int color);
+extern void bmp_write8(byte *addr, int color);
 extern void memory_putpixel(BITMAP *bmp, int x, int y, int color);
 extern void putpixel(BITMAP *bmp, int x, int y, int color);
 extern void _putpixel(BITMAP *bmp, int x, int y, int color);
diff --git a/engines/ags/shared/core/types.h b/engines/ags/shared/core/types.h
index c77a9e6e20..0aa1fd3e63 100644
--- a/engines/ags/shared/core/types.h
+++ b/engines/ags/shared/core/types.h
@@ -102,6 +102,19 @@ enum {
 	kUnit = 1 << kShift
 };
 
+/**
+ * Basic union that can be either a number or a pointer. Helps avoid some
+ * of the more nasty casts the codebase does, which was causing issues
+ * on 64-bit systems
+ */
+union NumberPtr {
+	int32 _value;
+	void *_ptr;
+
+	NumberPtr(int value) : _value(value) {}
+	NumberPtr(void *ptr) : _ptr(ptr) {}
+};
+
 } // namespace AGS3
 
 #endif


Commit: ef4d87b28ae7908eba73ced93df609837d2f1eb6
    https://github.com/scummvm/scummvm/commit/ef4d87b28ae7908eba73ced93df609837d2f1eb6
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Allow plugins onEvent 64-bit pointers

Changed paths:
    engines/ags/engine/ac/global_game.cpp
    engines/ags/engine/ac/global_translation.cpp
    engines/ags/engine/plugin/agsplugin.cpp
    engines/ags/engine/plugin/plugin_builtin.h
    engines/ags/engine/plugin/plugin_engine.h
    engines/ags/plugins/dll.cpp
    engines/ags/plugins/dll.h
    engines/ags/shared/core/types.h


diff --git a/engines/ags/engine/ac/global_game.cpp b/engines/ags/engine/ac/global_game.cpp
index 64603bafa3..14f70c0faa 100644
--- a/engines/ags/engine/ac/global_game.cpp
+++ b/engines/ags/engine/ac/global_game.cpp
@@ -597,7 +597,8 @@ void GetLocationName(int xxx, int yyy, char *tempo) {
 		return;
 	}
 	onhs = getloctype_index;
-	if (onhs > 0) strcpy(tempo, get_translation(thisroom.Hotspots[onhs].Name));
+	if (onhs > 0)
+		strcpy(tempo, get_translation(thisroom.Hotspots[onhs].Name));
 	if (play.get_loc_name_last_time != onhs)
 		guis_need_update = 1;
 	play.get_loc_name_last_time = onhs;
diff --git a/engines/ags/engine/ac/global_translation.cpp b/engines/ags/engine/ac/global_translation.cpp
index 07c2771752..6ee31b312e 100644
--- a/engines/ags/engine/ac/global_translation.cpp
+++ b/engines/ags/engine/ac/global_translation.cpp
@@ -50,8 +50,8 @@ const char *get_translation(const char *text) {
 
 #if AGS_PLATFORM_64BIT
 	// check if a plugin wants to translate it - if so, return that
-	// TODO: plugin API is currently strictly 32-bit, so this may break on 64-bit systems
-	char *plResult = Int32ToPtr<char>(pl_run_plugin_hooks(AGSE_TRANSLATETEXT, PtrToInt32(text)));
+	char *plResult = (char *)(pl_run_plugin_hooks(AGSE_TRANSLATETEXT,
+		const_cast<char *>(text)))._ptr;
 	if (plResult) {
 		return plResult;
 	}
diff --git a/engines/ags/engine/plugin/agsplugin.cpp b/engines/ags/engine/plugin/agsplugin.cpp
index 626ced045a..7c18d3f358 100644
--- a/engines/ags/engine/plugin/agsplugin.cpp
+++ b/engines/ags/engine/plugin/agsplugin.cpp
@@ -128,7 +128,7 @@ struct EnginePlugin {
 	int         invalidatedRegion;
 	void (*engineStartup)(IAGSEngine *) = nullptr;
 	void (*engineShutdown)() = nullptr;
-	int (*onEvent)(int, int) = nullptr;
+	NumberPtr (*onEvent)(int, NumberPtr) = nullptr;
 	void (*initGfxHook)(const char *driverName, void *data) = nullptr;
 	int (*debugHook)(const char *whichscript, int lineNumber, int reserved) = nullptr;
 	IAGSEngine  eiface;
@@ -880,8 +880,9 @@ void pl_startup_plugins() {
 	}
 }
 
-int pl_run_plugin_hooks(int event, int data) {
-	int i, retval = 0;
+NumberPtr pl_run_plugin_hooks(int event, NumberPtr data) {
+	int i;
+	NumberPtr retval = 0;
 	for (i = 0; i < numPlugins; i++) {
 		if (plugins[i].wantHook & event) {
 			retval = plugins[i].onEvent(event, data);
@@ -1040,7 +1041,7 @@ Engine::GameInitError pl_register_plugins(const std::vector<Shared::PluginInfo>
 			if (apl->engineStartup == nullptr) {
 				quitprintf("Plugin '%s' is not a valid AGS plugin (no engine startup entry point)", apl->filename);
 			}
-			apl->onEvent = (int(*)(int, int))apl->library.GetFunctionAddress("AGS_EngineOnEvent");
+			apl->onEvent = (NumberPtr(*)(int, NumberPtr))apl->library.GetFunctionAddress("AGS_EngineOnEvent");
 			apl->debugHook = (int(*)(const char *, int, int))apl->library.GetFunctionAddress("AGS_EngineDebugHook");
 			apl->initGfxHook = (void(*)(const char *, void *))apl->library.GetFunctionAddress("AGS_EngineInitGfx");
 		} else {
diff --git a/engines/ags/engine/plugin/plugin_builtin.h b/engines/ags/engine/plugin/plugin_builtin.h
index 3db0f06e60..ed698989a7 100644
--- a/engines/ags/engine/plugin/plugin_builtin.h
+++ b/engines/ags/engine/plugin/plugin_builtin.h
@@ -41,7 +41,7 @@ struct InbuiltPluginDetails {
 	char      filename[PLUGIN_FILENAME_MAX + 1];
 	void (*engineStartup)(IAGSEngine *);
 	void (*engineShutdown)();
-	int (*onEvent)(int, int);
+	NumberPtr (*onEvent)(int, NumberPtr);
 	void (*initGfxHook)(const char *driverName, void *data);
 	int (*debugHook)(const char *whichscript, int lineNumber, int reserved);
 };
diff --git a/engines/ags/engine/plugin/plugin_engine.h b/engines/ags/engine/plugin/plugin_engine.h
index 430d3c5d7e..7ae9343c65 100644
--- a/engines/ags/engine/plugin/plugin_engine.h
+++ b/engines/ags/engine/plugin/plugin_engine.h
@@ -48,7 +48,7 @@ using namespace AGS; // FIXME later
 
 void pl_stop_plugins();
 void pl_startup_plugins();
-int  pl_run_plugin_hooks(int event, int data);
+NumberPtr pl_run_plugin_hooks(int event, NumberPtr data);
 void pl_run_plugin_init_gfx_hooks(const char *driverName, void *data);
 int  pl_run_plugin_debug_hooks(const char *scriptfile, int linenum);
 // Tries to register plugins, either by loading dynamic libraries, or getting any kind of replacement
diff --git a/engines/ags/plugins/dll.cpp b/engines/ags/plugins/dll.cpp
index c9a1d9e915..a4d0b10028 100644
--- a/engines/ags/plugins/dll.cpp
+++ b/engines/ags/plugins/dll.cpp
@@ -90,7 +90,7 @@ void DLL::AGS_EngineStartup(IAGSEngine *) {
 void DLL::AGS_EngineShutdown() {
 }
 
-int DLL::AGS_EngineOnEvent(int, int) {
+NumberPtr DLL::AGS_EngineOnEvent(int, NumberPtr) {
 	return 0;
 }
 
diff --git a/engines/ags/plugins/dll.h b/engines/ags/plugins/dll.h
index c198add1f6..8aa7f90499 100644
--- a/engines/ags/plugins/dll.h
+++ b/engines/ags/plugins/dll.h
@@ -98,7 +98,7 @@ protected:
 	static void   AGS_EditorLoadGame(char *, int);
 	static void   AGS_EngineStartup(IAGSEngine *);
 	static void   AGS_EngineShutdown();
-	static int    AGS_EngineOnEvent(int, int);
+	static NumberPtr AGS_EngineOnEvent(int, NumberPtr);
 	static int    AGS_EngineDebugHook(const char *, int, int);
 	static void   AGS_EngineInitGfx(const char *driverID, void *data);
 public:
diff --git a/engines/ags/shared/core/types.h b/engines/ags/shared/core/types.h
index 0aa1fd3e63..35f839fb37 100644
--- a/engines/ags/shared/core/types.h
+++ b/engines/ags/shared/core/types.h
@@ -111,8 +111,9 @@ union NumberPtr {
 	int32 _value;
 	void *_ptr;
 
-	NumberPtr(int value) : _value(value) {}
+	NumberPtr(int value) { _ptr = nullptr; _value = value; }
 	NumberPtr(void *ptr) : _ptr(ptr) {}
+	operator bool() const { return _ptr != nullptr; }
 };
 
 } // namespace AGS3


Commit: 440a14e5655622e0081664e5877a4bc5a3fc0277
    https://github.com/scummvm/scummvm/commit/440a14e5655622e0081664e5877a4bc5a3fc0277
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Tentative draw_lit_sprite implementation

Changed paths:
    engines/ags/lib/allegro/gfx.cpp


diff --git a/engines/ags/lib/allegro/gfx.cpp b/engines/ags/lib/allegro/gfx.cpp
index 065e5738fa..8353437a61 100644
--- a/engines/ags/lib/allegro/gfx.cpp
+++ b/engines/ags/lib/allegro/gfx.cpp
@@ -290,7 +290,39 @@ void draw_trans_sprite(BITMAP *bmp, const BITMAP *sprite, int x, int y) {
 }
 
 void draw_lit_sprite(BITMAP *bmp, const BITMAP *sprite, int x, int y, int color) {
-	error("TODO: draw_lit_sprite");
+	// TODO: For now, only 32-bit bitmaps
+	assert(sprite->format.bytesPerPixel == 4 && bmp->format.bytesPerPixel == 4);
+	byte rSrc, gSrc, bSrc, aSrc;
+	byte rDest, gDest, bDest;
+	double alpha = (double)color / 255.0;
+
+	for (int yCtr = 0, yp = y; yCtr < sprite->h && yp < bmp->h; ++yCtr, ++yp) {
+		if (yp < 0)
+			continue;
+
+		const uint32 *srcP = (const uint32 *)sprite->getBasePtr(0, yCtr);
+		uint32 *destP = (uint32 *)bmp->getBasePtr(x, yp);
+
+		for (int xCtr = 0, xp = x; xCtr < sprite->w && xp < bmp->w; ++xCtr, ++xp, ++destP) {
+			if (x < 0 || x >= bmp->w)
+				continue;
+
+			// Get the source and dest pixels
+			sprite->format.colorToARGB(*srcP, aSrc, rSrc, gSrc, bSrc);
+			bmp->format.colorToRGB(*destP, rDest, gDest, bDest);
+
+			if (rSrc == 255 && gSrc == 0 && bSrc == 255)
+				// Skip transparent pixels
+				continue;
+
+			// Blend the two
+			rDest = static_cast<byte>((rSrc * alpha) + (rDest * (1.0 - alpha)));
+			gDest = static_cast<byte>((gSrc * alpha) + (gDest * (1.0 - alpha)));
+			bDest = static_cast<byte>((bSrc * alpha) + (bDest * (1.0 - alpha)));
+
+			*destP = bmp->format.RGBToColor(rDest, gDest, bDest);
+		}
+	}
 }
 
 void draw_sprite_h_flip(BITMAP *bmp, const BITMAP *sprite, int x, int y) {


Commit: 57e6e684c993dd30c45359ea0ebef023380443a6
    https://github.com/scummvm/scummvm/commit/57e6e684c993dd30c45359ea0ebef023380443a6
Author: Thierry Crozat (criezy at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix compilation when theoradec is disabled

Changed paths:
    engines/ags/engine/media/video/video.cpp


diff --git a/engines/ags/engine/media/video/video.cpp b/engines/ags/engine/media/video/video.cpp
index 998b29fee0..b4c385a68e 100644
--- a/engines/ags/engine/media/video/video.cpp
+++ b/engines/ags/engine/media/video/video.cpp
@@ -52,6 +52,9 @@ namespace AGS3 {
 using AGS::Shared::AssetManager;
 
 void play_theora_video(const char *name, int skip, int flags) {
+#if !defined (USE_THEORADEC)
+	Display("This games uses Theora videos but ScummVM has been compiled without Theora support");
+#else
 	std::unique_ptr<Stream> video_stream(AssetManager::OpenAsset(name));
 	if (!video_stream) {
 		Display("Unable to load theora video '%s'", name);
@@ -120,7 +123,9 @@ void play_theora_video(const char *name, int skip, int flags) {
 	}
 
 	invalidate_screen();
+#endif
 }
+
 void play_flc_file(int numb, int playflags) {
 	warning("TODO: play_flc_file");
 }


Commit: 304ba31e4b3ab53097ecbe9494f83ed61e4829e0
    https://github.com/scummvm/scummvm/commit/304ba31e4b3ab53097ecbe9494f83ed61e4829e0
Author: Thierry Crozat (criezy at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix out of bound crossfade volume

The code was trying to pass a volume defined between 0 and 255
to a function expecting a volume between 0 and 100, causing an
assert.

Changed paths:
    engines/ags/engine/media/audio/audio.cpp
    engines/ags/engine/media/audio/soundclip.h


diff --git a/engines/ags/engine/media/audio/audio.cpp b/engines/ags/engine/media/audio/audio.cpp
index 90b4a96829..342fc3aac7 100644
--- a/engines/ags/engine/media/audio/audio.cpp
+++ b/engines/ags/engine/media/audio/audio.cpp
@@ -277,7 +277,7 @@ static void audio_update_polled_stuff() {
 
 	if (play.crossfading_out_channel > 0) {
 		SOUNDCLIP *ch = lock.GetChannel(play.crossfading_out_channel);
-		int newVolume = ch ? ch->get_volume() - play.crossfade_out_volume_per_step : 0;
+		int newVolume = ch ? ch->get_volume_percent() - play.crossfade_out_volume_per_step : 0;
 		if (newVolume > 0) {
 			AudioChannel_SetVolume(&scrAudioChannel[play.crossfading_out_channel], newVolume);
 		} else {
@@ -291,7 +291,7 @@ static void audio_update_polled_stuff() {
 
 	if (play.crossfading_in_channel > 0) {
 		SOUNDCLIP *ch = lock.GetChannel(play.crossfading_in_channel);
-		int newVolume = ch ? ch->get_volume() + play.crossfade_in_volume_per_step : 0;
+		int newVolume = ch ? ch->get_volume_percent() + play.crossfade_in_volume_per_step : 0;
 		if (newVolume > play.crossfade_final_volume_in) {
 			newVolume = play.crossfade_final_volume_in;
 		}
diff --git a/engines/ags/engine/media/audio/soundclip.h b/engines/ags/engine/media/audio/soundclip.h
index 6d520bfba1..ccd071cd21 100644
--- a/engines/ags/engine/media/audio/soundclip.h
+++ b/engines/ags/engine/media/audio/soundclip.h
@@ -91,6 +91,9 @@ struct SOUNDCLIP {
 	inline void set_volume_percent(int volume) {
 		set_volume((volume * 255) / 100);
 	}
+	inline int get_volume_percent() const {
+		return get_volume() * 100 / 255;
+	}
 	void adjust_volume();
 	int play_from(int position);
 


Commit: e9dd4d963f2aa87782ed22e218016047424697b0
    https://github.com/scummvm/scummvm/commit/e9dd4d963f2aa87782ed22e218016047424697b0
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Change game folder consts from String to const char *

Changed paths:
    engines/ags/engine/ac/file.cpp
    engines/ags/engine/ac/game.cpp
    engines/ags/engine/ac/path_helper.h
    engines/ags/engine/main/engine.cpp


diff --git a/engines/ags/engine/ac/file.cpp b/engines/ags/engine/ac/file.cpp
index a0b5f7cc4d..06110570ab 100644
--- a/engines/ags/engine/ac/file.cpp
+++ b/engines/ags/engine/ac/file.cpp
@@ -218,10 +218,10 @@ int File_GetPosition(sc_File *fil) {
 //=============================================================================
 
 
-const String GameInstallRootToken = "$INSTALLDIR$";
-const String UserSavedgamesRootToken = "$MYDOCS$";
-const String GameSavedgamesDirToken = "$SAVEGAMEDIR$";
-const String GameDataDirToken = "$APPDATADIR$";
+const char *GameInstallRootToken = "$INSTALLDIR$";
+const char *UserSavedgamesRootToken = "$MYDOCS$";
+const char *GameSavedgamesDirToken = "$SAVEGAMEDIR$";
+const char *GameDataDirToken = "$APPDATADIR$";
 
 void FixupFilename(char *filename) {
 	const char *illegal = platform->GetIllegalFileChars();
diff --git a/engines/ags/engine/ac/game.cpp b/engines/ags/engine/ac/game.cpp
index 9899af8973..0cba7e1f1e 100644
--- a/engines/ags/engine/ac/game.cpp
+++ b/engines/ags/engine/ac/game.cpp
@@ -382,10 +382,10 @@ bool MakeSaveGameDir(const String &newFolder, ResolvedPath &rp) {
 	String base_dir;
 	String newSaveGameDir = FixSlashAfterToken(newFolder);
 
-	if (newSaveGameDir.CompareLeft(UserSavedgamesRootToken, UserSavedgamesRootToken.GetLength()) == 0) {
+	if (newSaveGameDir.CompareLeft(UserSavedgamesRootToken, strlen(UserSavedgamesRootToken)) == 0) {
 		if (saveGameParent.IsEmpty()) {
 			base_dir = PathOrCurDir(platform->GetUserSavedgamesDirectory());
-			newSaveGameDir.ReplaceMid(0, UserSavedgamesRootToken.GetLength(), base_dir);
+			newSaveGameDir.ReplaceMid(0, strlen(UserSavedgamesRootToken), base_dir);
 		} else {
 			// If there is a custom save parent directory, then replace
 			// not only root token, but also first subdirectory
diff --git a/engines/ags/engine/ac/path_helper.h b/engines/ags/engine/ac/path_helper.h
index 46349386ac..41d12fc570 100644
--- a/engines/ags/engine/ac/path_helper.h
+++ b/engines/ags/engine/ac/path_helper.h
@@ -36,9 +36,9 @@ namespace AGS3 {
 using AGS::Shared::String;
 
 // Filepath tokens, which are replaced by platform-specific directory names
-extern const String UserSavedgamesRootToken;
-extern const String GameSavedgamesDirToken;
-extern const String GameDataDirToken;
+extern const char *UserSavedgamesRootToken;
+extern const char *GameSavedgamesDirToken;
+extern const char *GameDataDirToken;
 
 inline const char *PathOrCurDir(const char *path) {
 	return path ? path : ".";
diff --git a/engines/ags/engine/main/engine.cpp b/engines/ags/engine/main/engine.cpp
index fb157b5fa4..cd1940f046 100644
--- a/engines/ags/engine/main/engine.cpp
+++ b/engines/ags/engine/main/engine.cpp
@@ -655,7 +655,7 @@ void engine_init_directories() {
 	// if there is no custom path, or if custom path failed, use default system path
 	if (!res) {
 		char newDirBuffer[MAX_PATH];
-		sprintf(newDirBuffer, "%s/%s", UserSavedgamesRootToken.GetCStr(), game.saveGameFolderName);
+		sprintf(newDirBuffer, "%s/%s", UserSavedgamesRootToken, game.saveGameFolderName);
 		SetSaveGameDirectoryPath(newDirBuffer);
 	}
 }


Commit: 2d128fffcd7c16be8f0784b3713e39a23af72683
    https://github.com/scummvm/scummvm/commit/2d128fffcd7c16be8f0784b3713e39a23af72683
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix mapping folder macros like $

Changed paths:
    engines/ags/detection_tables.h
    engines/ags/engine/ac/file.cpp
    engines/ags/engine/ac/game.cpp
    engines/ags/lib/allegro/file.cpp


diff --git a/engines/ags/detection_tables.h b/engines/ags/detection_tables.h
index 45c4e1634a..e0f1149b1c 100644
--- a/engines/ags/detection_tables.h
+++ b/engines/ags/detection_tables.h
@@ -80,6 +80,7 @@ static const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("qfi", "qfi.exe", "0702df6e67ef87fd3c51d09303803126", 534847265), // GOG
 	ENGLISH_ENTRY("oott", "OotT-TKC.exe", "11c2421258465cba4bd773c49d918ee3", 467834855), // GOG
 	ENGLISH_ENTRY("primordia", "primordia.exe", "22313e59c3233001488c26f18c80cc08", 973495830), // GOG
+	ENGLISH_ENTRY("primordia", "primordia.exe", "f2edc9c3161f1f538df9b4c59fc89e24", 978377890), // GOG
 	ENGLISH_ENTRY("resonance", "resonance.exe", "2e635c22bcbf0ed3d46f1bcde71812d4", 849404957), // GOG
 	// For some macOS and iOS releases the executable was renamed to ac2game.dat
 	ENGLISH_ENTRY("mage", "ac2game.dat", "2e822f554994f36e0c62da2acda874da", 30492258), // GOG, Mac
diff --git a/engines/ags/engine/ac/file.cpp b/engines/ags/engine/ac/file.cpp
index 06110570ab..28b0814d61 100644
--- a/engines/ags/engine/ac/file.cpp
+++ b/engines/ags/engine/ac/file.cpp
@@ -288,8 +288,7 @@ bool ResolveScriptPath(const String &orig_sc_path, bool read_only, ResolvedPath
 		rp.FullPath = orig_sc_path;
 		return true;
 	}
-
-#if AGS_PLATFORM_SCUMMVM
+	/*
 	if (read_only) {
 		// For reading files, first try as a save file, then fall back
 		// in the game folder. This handles cases where some games like
@@ -304,13 +303,12 @@ bool ResolveScriptPath(const String &orig_sc_path, bool read_only, ResolvedPath
 		rp.FullPath = String::FromFormat("%s%s", SAVE_FOLDER_PREFIX,
 			orig_sc_path.GetNullableCStr());
 	}
-
-#else
+	*/
 	String sc_path = FixSlashAfterToken(orig_sc_path);
 	String parent_dir;
 	String child_path;
 	String alt_path;
-	if (sc_path.CompareLeft(GameInstallRootToken, GameInstallRootToken.GetLength()) == 0) {
+	if (sc_path.CompareLeft(GameInstallRootToken) == 0) {
 		if (!read_only) {
 			debug_script_warn("Attempt to access file '%s' denied (cannot write to game installation directory)",
 				sc_path.GetCStr());
@@ -318,36 +316,26 @@ bool ResolveScriptPath(const String &orig_sc_path, bool read_only, ResolvedPath
 		}
 		parent_dir = get_install_dir();
 		parent_dir.AppendChar('/');
-		child_path = sc_path.Mid(GameInstallRootToken.GetLength());
-	} else if (sc_path.CompareLeft(GameSavedgamesDirToken, GameSavedgamesDirToken.GetLength()) == 0) {
+		child_path = sc_path.Mid(strlen(GameInstallRootToken));
+	} else if (sc_path.CompareLeft(GameSavedgamesDirToken) == 0) {
 		parent_dir = get_save_game_directory();
-		child_path = sc_path.Mid(GameSavedgamesDirToken.GetLength());
-	} else if (sc_path.CompareLeft(GameDataDirToken, GameDataDirToken.GetLength()) == 0) {
+		child_path = sc_path.Mid(strlen(GameSavedgamesDirToken));
+	} else if (sc_path.CompareLeft(GameDataDirToken) == 0) {
 		parent_dir = MakeAppDataPath();
-		child_path = sc_path.Mid(GameDataDirToken.GetLength());
+		child_path = sc_path.Mid(strlen(GameDataDirToken));
 	} else {
 		child_path = sc_path;
 
-		// For games which were made without having safe paths in mind,
-		// provide two paths: a path to the local directory and a path to
-		// AppData directory.
-		// This is done in case game writes a file by local path, and would
-		// like to read it back later. Since AppData path has higher priority,
-		// game will first check the AppData location and find a previously
-		// written file.
-		// If no file was written yet, but game is trying to read a pre-created
-		// file in the installation directory, then such file will be found
-		// following the 'alt_path'.
-		parent_dir = MakeAppDataPath();
-		// Set alternate non-remapped "unsafe" path for read-only operations
-		if (read_only)
-			alt_path = String::FromFormat("%s/%s", get_install_dir().GetCStr(), sc_path.GetCStr());
-
-		// For games made in the safe-path-aware versions of AGS, report a warning
-		// if the unsafe path is used for write operation
-		if (!read_only && game.options[OPT_SAFEFILEPATHS]) {
-			debug_script_warn("Attempt to access file '%s' denied (cannot write to game installation directory);\nPath will be remapped to the app data directory: '%s'",
-				sc_path.GetCStr(), parent_dir.GetCStr());
+		// For cases where a file is trying to write to a game path, always remap
+		// it to write to a savefile. For normal reading, we thus need to give
+		// preference to any save file with a given name before looking in the
+		// game folder. This for example fixes an issue with The Blackwell Legacy,
+		// which wants to create a new prog.bwl in the game folder
+		parent_dir = SAVE_FOLDER_PREFIX;
+
+		if (read_only) {
+			alt_path = String::FromFormat("%s/%s", get_install_dir().GetCStr(),
+				sc_path.GetCStr());
 		}
 	}
 
@@ -365,7 +353,7 @@ bool ResolveScriptPath(const String &orig_sc_path, bool read_only, ResolvedPath
 	rp.BaseDir = parent_dir;
 	rp.FullPath = full_path;
 	rp.AltPath = alt_path;
-#endif
+
 	return true;
 }
 
diff --git a/engines/ags/engine/ac/game.cpp b/engines/ags/engine/ac/game.cpp
index 0cba7e1f1e..f7788186da 100644
--- a/engines/ags/engine/ac/game.cpp
+++ b/engines/ags/engine/ac/game.cpp
@@ -204,7 +204,7 @@ MoveList *mls = nullptr;
 
 //=============================================================================
 
-String saveGameDirectory = "./";
+String saveGameDirectory = SAVE_FOLDER_PREFIX;
 // Custom save game parent directory
 String saveGameParent;
 
diff --git a/engines/ags/lib/allegro/file.cpp b/engines/ags/lib/allegro/file.cpp
index e4dd654179..b8c02fba76 100644
--- a/engines/ags/lib/allegro/file.cpp
+++ b/engines/ags/lib/allegro/file.cpp
@@ -127,8 +127,8 @@ char *make_relative_filename(char *dest, const char *path, const char *filename,
 }
 
 int is_relative_filename(const char *filename) {
-	Common::String fname(filename);
-	return !fname.contains('/') && !fname.contains('\\') ? 1 : 0;
+	// ScummVM doesn't have absolute paths
+	return true;
 }
 
 /*------------------------------------------------------------------*/


Commit: ecf601dbb35c25677ea7eae0c181cf6edf0aaaf6
    https://github.com/scummvm/scummvm/commit/ecf601dbb35c25677ea7eae0c181cf6edf0aaaf6
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Framework for specifying a specific plugin version a game needs

Black Cauldron uses the AGSCreditz 1.1 plugin, but in the 2.0
version I was given the source for, there are differences in the
method declarations. So this new framework allows me to explicitly
specify that the game needs 1.1

Changed paths:
    engines/ags/ags.cpp
    engines/ags/ags.h
    engines/ags/detection.h
    engines/ags/detection_tables.h
    engines/ags/plugins/agscreditz/agscreditz.cpp
    engines/ags/plugins/agscreditz/agscreditz.h
    engines/ags/plugins/dll.cpp
    engines/ags/plugins/dll.h


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index d3a54972d5..bf61c62120 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -302,6 +302,10 @@ uint32 AGSEngine::getFeatures() const {
 	return _gameDescription->desc.flags;
 }
 
+const PluginVersion *AGSEngine::getNeededPlugins() const {
+	return _gameDescription->_plugins;
+}
+
 Common::Error AGSEngine::run() {
 	const char *filename = _gameDescription->desc.filesDescriptions[0].fileName;
 	const char *ARGV[] = { "scummvm.exe", filename };
diff --git a/engines/ags/ags.h b/engines/ags/ags.h
index 10bcf431fb..f1004110f1 100644
--- a/engines/ags/ags.h
+++ b/engines/ags/ags.h
@@ -52,6 +52,7 @@ enum AGSDebugChannels {
 };
 
 struct AGSGameDescription;
+struct PluginVersion;
 class EventsManager;
 class Music;
 
@@ -83,6 +84,8 @@ public:
 
 	uint32 getFeatures() const;
 
+	const PluginVersion *getNeededPlugins() const;
+
 	/**
 	 * Returns the current list of savegames
 	 */
diff --git a/engines/ags/detection.h b/engines/ags/detection.h
index 3667582516..9ac3d6ae35 100644
--- a/engines/ags/detection.h
+++ b/engines/ags/detection.h
@@ -27,8 +27,14 @@
 
 namespace AGS {
 
+struct PluginVersion {
+	const char *_plugin;
+	int _version;
+};
+
 struct AGSGameDescription {
 	ADGameDescription desc;
+	const PluginVersion *_plugins;
 };
 
 } // namespace AGS
diff --git a/engines/ags/detection_tables.h b/engines/ags/detection_tables.h
index e0f1149b1c..267f99bf61 100644
--- a/engines/ags/detection_tables.h
+++ b/engines/ags/detection_tables.h
@@ -56,13 +56,29 @@ static const PlainGameDescriptor GAME_NAMES[] = {
 			AD_ENTRY1s(FILENAME, MD5, SIZE), \
 			Common::EN_ANY, \
 			Common::kPlatformUnknown, \
-			ADGF_NO_FLAGS, \
+			ADGF_UNSTABLE, \
 			GUIO1(GUIO_NOSPEECH) \
-		} \
+		}, \
+		nullptr \
 	}
 
+#define ENGLISH_PLUGIN(ID, FILENAME, MD5, SIZE, PLUGIN_ARR) { \
+		{ \
+			ID, \
+			nullptr, \
+			AD_ENTRY1s(FILENAME, MD5, SIZE), \
+			Common::EN_ANY, \
+			Common::kPlatformUnknown, \
+			ADGF_UNSTABLE, \
+			GUIO1(GUIO_NOSPEECH) \
+		}, \
+		PLUGIN_ARR \
+	}
+
+static const PluginVersion AGSCREDITZ_11[] = { { "agscreditz", 11 }, { nullptr, 0 } };
+
 static const AGSGameDescription GAME_DESCRIPTIONS[] = {
-	ENGLISH_ENTRY("bcremake", "bc.exe", "0710e2ec71042617f565c01824f0cf3c", 7683255),
+	ENGLISH_PLUGIN("bcremake", "bc.exe", "0710e2ec71042617f565c01824f0cf3c", 7683255, AGSCREDITZ_11),
 	ENGLISH_ENTRY("atotk", "atotk.exe", "37cf2d4d07842d45b59c6dd9387c1ee7", 42872046),
 	ENGLISH_ENTRY("atotk", "atotk.exe", "37cf2d4d07842d45b59c6dd9387c1ee7", 42740200),
 	ENGLISH_ENTRY("blackwell1", "blackwell1.exe", "605e124cb7e0b56841c471e2d641c224", 18822697), // GOG
diff --git a/engines/ags/plugins/agscreditz/agscreditz.cpp b/engines/ags/plugins/agscreditz/agscreditz.cpp
index 21a0ce3ecb..d77763ae80 100644
--- a/engines/ags/plugins/agscreditz/agscreditz.cpp
+++ b/engines/ags/plugins/agscreditz/agscreditz.cpp
@@ -20,23 +20,34 @@
  *
  */
 
-#include "ags/plugins/agscreditz/agscreditz.h"
+#include "ags/plugins/AGSCreditz/AGSCreditz.h"
 
 namespace AGS3 {
 namespace Plugins {
-namespace AgsCreditz {
+namespace AGSCreditz {
+
+AGSCreditz::Version AGSCreditz::_version;
+State *AGSCreditz::_state;
+
+AGSCreditz::AGSCreditz() {
+	_state = new State();
 
-AgsCreditz::AgsCreditz() {
 	DLL_METHOD(AGS_GetPluginName);
-	DLL_METHOD(AGS_EngineStartup);
 }
 
-const char *AgsCreditz::AGS_GetPluginName() {
-	return "agsCreditz v1.1 by AJA";
+AGSCreditz::~AGSCreditz() {
+	delete _state;
 }
 
-void AgsCreditz::AGS_EngineStartup(IAGSEngine *engine) {
-	SCRIPT_METHOD(SetCredit);
+
+const char *AGSCreditz::AGS_GetPluginName() {
+	if (_version == VERSION_11)
+		return "AGSCreditz v1.1 by AJA";
+	else
+		return "AGSCreditz 2.0 (by Dima Software: AJA)";
+}
+
+void AGSCreditz::AGS_EngineStartup(IAGSEngine *engine) {
 	SCRIPT_METHOD(ScrollCredits);
 	SCRIPT_METHOD(GetCredit);
 	SCRIPT_METHOD(IsCreditScrollingFinished);
@@ -59,92 +70,138 @@ void AgsCreditz::AGS_EngineStartup(IAGSEngine *engine) {
 	SCRIPT_METHOD(IsStaticCreditsFinished);
 }
 
-void AgsCreditz::SetCredit(const ScriptMethodParams &params) {
-	PARAMS7(int, ID, string, credit, int, colour, int, font, int, center, int, xpos, int, generateoutline);
-}
-
-void AgsCreditz::ScrollCredits(const ScriptMethodParams &params) {
+void AGSCreditz::ScrollCredits(const ScriptMethodParams &params) {
 	PARAMS7(int, onoff, int, speed, int, fromY, int, toY, int, isautom, int, wait, int, res);
 }
 
-string AgsCreditz::GetCredit(const ScriptMethodParams &params) {
+string AGSCreditz::GetCredit(const ScriptMethodParams &params) {
 	PARAMS1(int, ID);
 	return nullptr;
 }
 
-int AgsCreditz::IsCreditScrollingFinished(const ScriptMethodParams &params) {
+int AGSCreditz::IsCreditScrollingFinished(const ScriptMethodParams &params) {
 	return true;
 }
 
-void AgsCreditz::SetCreditImage(const ScriptMethodParams &params) {
+void AGSCreditz::SetCreditImage(const ScriptMethodParams &params) {
 	PARAMS5(int, ID, int, Slot, int, center, int, xpos, int, pixtonext);
 }
 
-void AgsCreditz::PauseScroll(const ScriptMethodParams &params) {
+void AGSCreditz::PauseScroll(const ScriptMethodParams &params) {
 	PARAMS1(int, onoff);
 }
 
-void AgsCreditz::ScrollReset(const ScriptMethodParams &params) {
+void AGSCreditz::ScrollReset(const ScriptMethodParams &params) {
 }
 
-void AgsCreditz::SetEmptyLineHeight(const ScriptMethodParams &params) {
+void AGSCreditz::SetEmptyLineHeight(const ScriptMethodParams &params) {
 	PARAMS1(int, Height);
 }
 
-int AgsCreditz::GetEmptyLineHeight(const ScriptMethodParams &params) {
+int AGSCreditz::GetEmptyLineHeight(const ScriptMethodParams &params) {
 	return 0;
 }
 
-void AgsCreditz::SetStaticCredit(const ScriptMethodParams &params) {
+void AGSCreditz::SetStaticCredit(const ScriptMethodParams &params) {
 	PARAMS8(int, ID, int, x, int, y, int, creditfont, int, creditcolour, int, centered, int, generateoutline, string, credit);
 
 }
 
-string AgsCreditz::GetStaticCredit(const ScriptMethodParams &params) {
+string AGSCreditz::GetStaticCredit(const ScriptMethodParams &params) {
 	PARAMS1(int, ID);
 	return nullptr;
 }
 
-void AgsCreditz::StartEndStaticCredits(const ScriptMethodParams &params) {
+void AGSCreditz::StartEndStaticCredits(const ScriptMethodParams &params) {
 	PARAMS2(int, onoff, int, res);
 }
 
-int AgsCreditz::GetCurrentStaticCredit(const ScriptMethodParams &params) {
+int AGSCreditz::GetCurrentStaticCredit(const ScriptMethodParams &params) {
 	return 0;
 }
 
-void AgsCreditz::SetDefaultStaticDelay(const ScriptMethodParams &params) {
+void AGSCreditz::SetDefaultStaticDelay(const ScriptMethodParams &params) {
 	PARAMS1(int, Cyclesperchar);
 }
 
-void AgsCreditz::SetStaticPause(const ScriptMethodParams &params) {
+void AGSCreditz::SetStaticPause(const ScriptMethodParams &params) {
 	PARAMS2(int, ID, int, length);
 }
 
-void AgsCreditz::SetStaticCreditTitle(const ScriptMethodParams &params) {
+void AGSCreditz::SetStaticCreditTitle(const ScriptMethodParams &params) {
 	PARAMS8(int, ID, int, x, int, y, int, titlefont, int, titlecolour, int, centered, int, generateoutline, string, title);
 }
 
-void AgsCreditz::ShowStaticCredit(const ScriptMethodParams &params) {
+void AGSCreditz::ShowStaticCredit(const ScriptMethodParams &params) {
 	PARAMS6(int, ID, int, time, int, style, int, transtime, int, sound, int, resolution);
 }
 
-void AgsCreditz::StaticReset(const ScriptMethodParams &params) {
+void AGSCreditz::StaticReset(const ScriptMethodParams &params) {
 }
 
-string AgsCreditz::GetStaticCreditTitle(const ScriptMethodParams &params) {
+string AGSCreditz::GetStaticCreditTitle(const ScriptMethodParams &params) {
 	PARAMS1(int, ID);
 	return nullptr;
 }
 
-void AgsCreditz::SetStaticCreditImage(const ScriptMethodParams &params) {
+void AGSCreditz::SetStaticCreditImage(const ScriptMethodParams &params) {
 //int ID, int x, int y, int Slot, int Hcentered, int Vcentered, int time) {
 }
 
-int AgsCreditz::IsStaticCreditsFinished(const ScriptMethodParams &params) {
+int AGSCreditz::IsStaticCreditsFinished(const ScriptMethodParams &params) {
 	return true;
 }
 
-} // namespace AgsCreditz
+/*------------------------------------------------------------------*/
+
+AGSCreditz11::AGSCreditz11() {
+	_version = VERSION_11;
+
+	DLL_METHOD(AGS_EngineStartup);
+}
+
+void AGSCreditz11::AGS_EngineStartup(IAGSEngine *engine) {
+	AGSCreditz::AGS_EngineStartup(engine);
+	SCRIPT_METHOD(SetCredit);
+}
+
+void AGSCreditz11::SetCredit(const ScriptMethodParams &params) {
+	PARAMS7(int, ID, string, credit, int, colour, int, font, int, center, int, xpos, int, generateoutline);
+
+}
+
+/*------------------------------------------------------------------*/
+
+AGSCreditz20::AGSCreditz20() {
+	_version = VERSION_20;
+
+	DLL_METHOD(AGS_EngineStartup);
+}
+
+void AGSCreditz20::AGS_EngineStartup(IAGSEngine *engine) {
+	AGSCreditz::AGS_EngineStartup(engine);
+	SCRIPT_METHOD(SetCredit);
+}
+
+void AGSCreditz20::SetCredit(const ScriptMethodParams &params) {
+	PARAMS7(int, sequence, int, line, string, credit, int, x_pos, int, font, int, color, int, gen_outline);
+
+	assert(sequence >= 0 && sequence <= 10);
+	if (line >= (int)_state->_credits[sequence].size())
+		_state->_credits[sequence].resize(line + 1);
+
+	Credit &c = _state->_credits[sequence][line];
+	c._credit = credit;
+	c._fontSlot = font;
+	c._colorHeight = color;
+	c._x = x_pos;
+	c._isSet = true;
+	if (gen_outline > 0)
+		c._outline = true;
+}
+
+
+
+} // namespace AGSCreditz
 } // namespace Plugins
 } // namespace AGS3
diff --git a/engines/ags/plugins/agscreditz/agscreditz.h b/engines/ags/plugins/agscreditz/agscreditz.h
index a19a867035..ab93f88a13 100644
--- a/engines/ags/plugins/agscreditz/agscreditz.h
+++ b/engines/ags/plugins/agscreditz/agscreditz.h
@@ -24,18 +24,102 @@
 #define AGS_PLUGINS_AGSCREDITZ_AGSCREDITZ_H
 
 #include "ags/plugins/dll.h"
+#include "common/array.h"
+#include "common/rect.h"
+#include "common/str.h"
 
 namespace AGS3 {
 namespace Plugins {
-namespace AgsCreditz {
+namespace AGSCreditz {
 
-class AgsCreditz : public DLL {
-private:
+struct Credit {
+	Common::String _credit;
+	int _x = 0;
+	int _y = 0;
+	int _fontSlot = 0;
+	int _colorHeight = 0;
+	bool _isSet = false;
+	bool _image = false;
+	bool _outline = false;
+};
+
+struct SequenceSettings {
+	int startpoint = 0;
+	int endpoint = 0;
+	int speed = 0;
+	bool finished = false;
+	int automatic = 0;
+	int endwait = 0;
+	int topmask = 0;
+	int bottommask = 0;
+};
+
+struct StCredit {
+	Common::String credit;
+	Common::String title;
+	int x = 0;
+	int y = 0;
+	int font = 0;
+	int color = 0;
+	int title_x = 0;
+	int title_y = 0;
+	int title_font = 0;
+	int title_color = 0;
+	int pause = 0;
+	bool image = false;
+	int image_slot = 0;
+	int image_time = 0;
+	bool outline = false;
+	bool title_outline = false;
+};
+
+struct StSequenceSettings {
+	int speed = 0;
+	bool finished = false;
+};
+
+struct SingleStatic {
+	int id = 0;
+	int time = 0;
+	int style = 0;
+	int settings = 01;
+	int settings2 = 0;
+	bool bool_ = false;
+};
+
+typedef Common::Array<Credit> CreditArray;
+typedef Common::Array<StCredit> StCreditArray;
+
+struct State {
+	CreditArray _credits[10];
+	StCreditArray _stCredits[10];
+	bool _creditsRunning = 0, _paused = 0, _staticCredits = 0;
+	int _creditSequence = 0, _yPos = 0, _sequenceHeight = 0, _speedPoint = 0;
+	int _calculatedSequenceHeight = 0, _timer = 0, _currentStatic = 0;
+	int _numChars = 0, _timer2 = 0;
+	int _emptyLineHeight = 10;
+	int _strCredit[10];
+	SequenceSettings _seqSettings[10];
+	StSequenceSettings _stSeqSettings[10];
+	SingleStatic _singleStatic;
+	void *_maskScreen = nullptr;
+	void *_maski = nullptr;
+	void *_creditScreen = nullptr;
+};
+
+class AGSCreditz : public DLL {
+protected:
+	enum Version {
+		VERSION_11 = 11, VERSION_20 = 20
+	};
+
+	static Version _version;
+	static State *_state;
+protected:
 	static const char *AGS_GetPluginName();
 	static void AGS_EngineStartup(IAGSEngine *engine);
 
-	// Script methods
-	static void SetCredit(const ScriptMethodParams &params);
+	// Shared Script methods 
 	static void ScrollCredits(const ScriptMethodParams &params);
 	static string GetCredit(const ScriptMethodParams &params);
 	static int IsCreditScrollingFinished(const ScriptMethodParams &params);
@@ -57,10 +141,29 @@ private:
 	static void SetStaticCreditImage(const ScriptMethodParams &params);
 	static int IsStaticCreditsFinished(const ScriptMethodParams &params);
 public:
-	AgsCreditz();
+	AGSCreditz();
+	~AGSCreditz();
+};
+
+class AGSCreditz11 : public AGSCreditz {
+private:
+	static void AGS_EngineStartup(IAGSEngine *engine);
+
+	static void SetCredit(const ScriptMethodParams &params);
+public:
+	AGSCreditz11();
+};
+
+class AGSCreditz20 : public AGSCreditz {
+private:
+	static void AGS_EngineStartup(IAGSEngine *engine);
+
+	static void SetCredit(const ScriptMethodParams &params);
+public:
+	AGSCreditz20();
 };
 
-} // namespace AgsCreditz
+} // namespace AGSCreditz
 } // namespace Plugins
 } // namespace AGS3
 
diff --git a/engines/ags/plugins/dll.cpp b/engines/ags/plugins/dll.cpp
index a4d0b10028..76dcb86a23 100644
--- a/engines/ags/plugins/dll.cpp
+++ b/engines/ags/plugins/dll.cpp
@@ -20,8 +20,11 @@
  *
  */
 
+#include "ags/lib/allegro.h"
 #include "ags/plugins/dll.h"
 #include "ags/plugins/agscreditz/agscreditz.h"
+#include "ags/ags.h"
+#include "ags/detection.h"
 #include "common/str.h"
 
 namespace AGS3 {
@@ -30,8 +33,22 @@ namespace Plugins {
 void *dlopen(const char *filename) {
 	Common::String fname(filename);
 
-	if (fname.equalsIgnoreCase("libagsCreditz.so"))
-		return new AgsCreditz::AgsCreditz();
+	// Check for if the game specifies a specific plugin version for this game
+	int version = 0;
+	for (const ::AGS::PluginVersion *v = ::AGS::g_vm->getNeededPlugins();
+			v->_plugin; ++v) {
+		if (Common::String::format("lib%s.so", v->_plugin).equalsIgnoreCase(filename)) {
+			version = v->_version;
+			break;
+		}
+	}
+
+	if (fname.equalsIgnoreCase("libagsCreditz.so")) {
+		if (version == 20)
+			return new AGSCreditz::AGSCreditz20();
+		else
+			return new AGSCreditz::AGSCreditz11();
+	}
 
 	return nullptr;
 }
diff --git a/engines/ags/plugins/dll.h b/engines/ags/plugins/dll.h
index 8aa7f90499..d1e9c768a3 100644
--- a/engines/ags/plugins/dll.h
+++ b/engines/ags/plugins/dll.h
@@ -33,6 +33,7 @@ namespace Plugins {
 
 #define DLL_METHOD(NAME) _methods[#NAME] = (void *)&NAME
 #define SCRIPT_METHOD(NAME) engine->RegisterScriptFunction(#NAME, (void *)&NAME)
+#define SCRIPT_METHOD_EXT(NAME, PROC) engine->RegisterScriptFunction(#NAME, (void *)&(PROC))
 
 #define PARAMS1(T1, N1) \
 	T1 N1 = (T1)params[0]


Commit: 58acb3579e6ffeb8c3bf369d4f0eb044292b08de
    https://github.com/scummvm/scummvm/commit/58acb3579e6ffeb8c3bf369d4f0eb044292b08de
Author: dreammaster (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Initial import of unmodified other plugins source

the AGS codebase comes with the option to build with several
built-in plugins that code is provided for. These will still
need to be cleaned up for the ScummVM DLL implementation

Changed paths:
  A engines/ags/plugins/ags_blend/ags_blend.cpp
  A engines/ags/plugins/ags_blend/ags_blend.h
  A engines/ags/plugins/ags_creditz/ags_creditz.cpp
  A engines/ags/plugins/ags_creditz/ags_creditz.h
  A engines/ags/plugins/ags_flashlight/ags_flashlight.cpp
  A engines/ags/plugins/ags_flashlight/ags_flashlight.h
  A engines/ags/plugins/ags_pal_render/ags_pal_render.cpp
  A engines/ags/plugins/ags_pal_render/ags_pal_render.h
  A engines/ags/plugins/ags_pal_render/agsplugin.h
  A engines/ags/plugins/ags_pal_render/pal_render.h
  A engines/ags/plugins/ags_pal_render/raycast.cpp
  A engines/ags/plugins/ags_pal_render/raycast.h
  A engines/ags/plugins/ags_parallax/ags_parallax.cpp
  A engines/ags/plugins/ags_parallax/ags_parallax.h
  A engines/ags/plugins/ags_snow_rain/ags_snow_rain.cpp
  A engines/ags/plugins/ags_snow_rain/ags_snow_rain.h
  A engines/ags/plugins/ags_sprite_font/ags_sprite_font.cpp
  A engines/ags/plugins/ags_sprite_font/character_entry.cpp
  A engines/ags/plugins/ags_sprite_font/character_entry.h
  A engines/ags/plugins/ags_sprite_font/color.cpp
  A engines/ags/plugins/ags_sprite_font/color.h
  A engines/ags/plugins/ags_sprite_font/sprite_font.cpp
  A engines/ags/plugins/ags_sprite_font/sprite_font.h
  A engines/ags/plugins/ags_sprite_font/sprite_font_renderer.cpp
  A engines/ags/plugins/ags_sprite_font/sprite_font_renderer.h
  A engines/ags/plugins/ags_sprite_font/variable_width_font.cpp
  A engines/ags/plugins/ags_sprite_font/variable_width_font.h
  A engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.cpp
  A engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.h
  R engines/ags/plugins/agscreditz/agscreditz.cpp
  R engines/ags/plugins/agscreditz/agscreditz.h
    engines/ags/module.mk
    engines/ags/plugins/dll.cpp
    engines/ags/plugins/dll.h


diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index e31bfb8938..ad2657cdcd 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -301,7 +301,7 @@ MODULE_OBJS = \
 	engine/script/script_runtime.o \
 	engine/script/systemimports.o \
 	plugins/dll.o \
-	plugins/agscreditz/agscreditz.o
+	plugins/ags_creditz/ags_creditz.o
 
 ifdef ENABLE_AGS_TESTS
 MODULE_OBJS += \
diff --git a/engines/ags/plugins/ags_blend/ags_blend.cpp b/engines/ags/plugins/ags_blend/ags_blend.cpp
new file mode 100644
index 0000000000..eeb3584a50
--- /dev/null
+++ b/engines/ags/plugins/ags_blend/ags_blend.cpp
@@ -0,0 +1,1042 @@
+/***********************************************************
+ * AGSBlend                                                *
+ *                                                         *
+ * Author: Steven Poulton                                  *
+ *                                                         *
+ * Date: 09/01/2011                                        *
+ *                                                         *
+ * Description: An AGS Plugin to allow true Alpha Blending *
+ *                                                         *
+ ***********************************************************/
+
+#pragma region Defines_and_Includes
+
+#include "core/platform.h"
+
+#define MIN_EDITOR_VERSION 1
+#define MIN_ENGINE_VERSION 3
+
+#if AGS_PLATFORM_OS_WINDOWS
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#endif
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <math.h>
+
+#if !defined(BUILTIN_PLUGINS)
+#define THIS_IS_THE_PLUGIN
+#endif
+
+#include "plugin/agsplugin.h"
+
+#if defined(BUILTIN_PLUGINS)
+namespace agsblend {
+#endif
+
+typedef unsigned char uint8;
+
+#define DEFAULT_RGB_R_SHIFT_32  16
+#define DEFAULT_RGB_G_SHIFT_32  8
+#define DEFAULT_RGB_B_SHIFT_32  0
+#define DEFAULT_RGB_A_SHIFT_32  24
+
+#if !AGS_PLATFORM_OS_WINDOWS
+#define min(x,y) (((x) < (y)) ? (x) : (y))
+#define max(x,y) (((x) > (y)) ? (x) : (y))
+#endif
+
+#define abs(a)                       ((a)<0 ? -(a) : (a))
+#define ChannelBlend_Normal(B,L)     ((uint8)(B))
+#define ChannelBlend_Lighten(B,L)    ((uint8)((L > B) ? L:B))
+#define ChannelBlend_Darken(B,L)     ((uint8)((L > B) ? B:L))
+#define ChannelBlend_Multiply(B,L)   ((uint8)((B * L) / 255))
+#define ChannelBlend_Average(B,L)    ((uint8)((B + L) / 2))
+#define ChannelBlend_Add(B,L)        ((uint8)(min(255, (B + L))))
+#define ChannelBlend_Subtract(B,L)   ((uint8)((B + L < 255) ? 0:(B + L - 255)))
+#define ChannelBlend_Difference(B,L) ((uint8)(abs(B - L)))
+#define ChannelBlend_Negation(B,L)   ((uint8)(255 - abs(255 - B - L)))
+#define ChannelBlend_Screen(B,L)     ((uint8)(255 - (((255 - B) * (255 - L)) >> 8)))
+#define ChannelBlend_Exclusion(B,L)  ((uint8)(B + L - 2 * B * L / 255))
+#define ChannelBlend_Overlay(B,L)    ((uint8)((L < 128) ? (2 * B * L / 255):(255 - 2 * (255 - B) * (255 - L) / 255)))
+#define ChannelBlend_SoftLight(B,L)  ((uint8)((L < 128)?(2*((B>>1)+64))*((float)L/255):(255-(2*(255-((B>>1)+64))*(float)(255-L)/255))))
+#define ChannelBlend_HardLight(B,L)  (ChannelBlend_Overlay(L,B))
+#define ChannelBlend_ColorDodge(B,L) ((uint8)((L == 255) ? L:min(255, ((B << 8 ) / (255 - L)))))
+#define ChannelBlend_ColorBurn(B,L)  ((uint8)((L == 0) ? L:max(0, (255 - ((255 - B) << 8 ) / L))))
+#define ChannelBlend_LinearDodge(B,L)(ChannelBlend_Add(B,L))
+#define ChannelBlend_LinearBurn(B,L) (ChannelBlend_Subtract(B,L))
+#define ChannelBlend_LinearLight(B,L)((uint8)(L < 128)?ChannelBlend_LinearBurn(B,(2 * L)):ChannelBlend_LinearDodge(B,(2 * (L - 128))))
+#define ChannelBlend_VividLight(B,L) ((uint8)(L < 128)?ChannelBlend_ColorBurn(B,(2 * L)):ChannelBlend_ColorDodge(B,(2 * (L - 128))))
+#define ChannelBlend_PinLight(B,L)   ((uint8)(L < 128)?ChannelBlend_Darken(B,(2 * L)):ChannelBlend_Lighten(B,(2 * (L - 128))))
+#define ChannelBlend_HardMix(B,L)    ((uint8)((ChannelBlend_VividLight(B,L) < 128) ? 0:255))
+#define ChannelBlend_Reflect(B,L)    ((uint8)((L == 255) ? L:min(255, (B * B / (255 - L)))))
+#define ChannelBlend_Glow(B,L)       (ChannelBlend_Reflect(L,B))
+#define ChannelBlend_Phoenix(B,L)    ((uint8)(min(B,L) - max(B,L) + 255))
+#define ChannelBlend_Alpha(B,L,O)    ((uint8)(O * B + (1 - O) * L))
+#define ChannelBlend_AlphaF(B,L,F,O) (ChannelBlend_Alpha(F(B,L),B,O))
+
+
+#pragma endregion
+
+#if AGS_PLATFORM_OS_WINDOWS
+// The standard Windows DLL entry point
+
+BOOL APIENTRY DllMain(HANDLE hModule,
+                      DWORD  ul_reason_for_call,
+                      LPVOID lpReserved) {
+
+	switch (ul_reason_for_call)   {
+	case DLL_PROCESS_ATTACH:
+	case DLL_THREAD_ATTACH:
+	case DLL_THREAD_DETACH:
+	case DLL_PROCESS_DETACH:
+		break;
+	}
+	return TRUE;
+}
+#endif
+
+//define engine
+
+IAGSEngine *engine;
+
+
+#pragma region Color_Functions
+
+
+int getr32(int c) {
+	return ((c >> DEFAULT_RGB_R_SHIFT_32) & 0xFF);
+}
+
+
+int getg32(int c) {
+	return ((c >> DEFAULT_RGB_G_SHIFT_32) & 0xFF);
+}
+
+
+int getb32(int c) {
+	return ((c >> DEFAULT_RGB_B_SHIFT_32) & 0xFF);
+}
+
+
+int geta32(int c) {
+	return ((c >> DEFAULT_RGB_A_SHIFT_32) & 0xFF);
+}
+
+
+int makeacol32(int r, int g, int b, int a) {
+	return ((r << DEFAULT_RGB_R_SHIFT_32) |
+	        (g << DEFAULT_RGB_G_SHIFT_32) |
+	        (b << DEFAULT_RGB_B_SHIFT_32) |
+	        (a << DEFAULT_RGB_A_SHIFT_32));
+}
+
+#pragma endregion
+
+#pragma region Pixel32_Definition
+
+struct Pixel32 {
+
+public:
+	Pixel32();
+	~Pixel32() = default;
+	int GetColorAsInt();
+	int Red;
+	int Green;
+	int Blue;
+	int Alpha;
+
+};
+
+Pixel32::Pixel32() {
+	Red = 0;
+	Blue = 0;
+	Green = 0;
+	Alpha = 0;
+}
+
+int Pixel32::GetColorAsInt() {
+
+	return makeacol32(Red, Green, Blue, Alpha);
+
+}
+
+#pragma endregion
+
+/// <summary>
+/// Gets the alpha value at coords x,y
+/// </summary>
+int GetAlpha(int sprite, int x, int y) {
+
+
+	BITMAP *engineSprite = engine->GetSpriteGraphic(sprite);
+
+	unsigned char **charbuffer = engine->GetRawBitmapSurface(engineSprite);
+	unsigned int **longbuffer = (unsigned int **)charbuffer;
+
+	int alpha = geta32(longbuffer[y][x]);
+
+	engine->ReleaseBitmapSurface(engineSprite);
+
+	return alpha;
+
+}
+
+/// <summary>
+/// Sets the alpha value at coords x,y
+/// </summary>
+int PutAlpha(int sprite, int x, int y, int alpha) {
+
+	BITMAP *engineSprite = engine->GetSpriteGraphic(sprite);
+
+	unsigned char **charbuffer = engine->GetRawBitmapSurface(engineSprite);
+	unsigned int **longbuffer = (unsigned int **)charbuffer;
+
+
+	int r = getr32(longbuffer[y][x]);
+	int g = getg32(longbuffer[y][x]);
+	int b = getb32(longbuffer[y][x]);
+	longbuffer[y][x] = makeacol32(r, g, b, alpha);
+
+	engine->ReleaseBitmapSurface(engineSprite);
+
+	return alpha;
+
+}
+
+
+/// <summary>
+///  Translates index from a 2D array to a 1D array
+/// </summary>
+int xytolocale(int x, int y, int width) {
+
+	return (y * width + x);
+
+
+}
+
+int HighPass(int sprite, int threshold) {
+
+	BITMAP *src = engine->GetSpriteGraphic(sprite);
+	int srcWidth, srcHeight;
+
+	engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, nullptr);
+
+	unsigned char **srccharbuffer = engine->GetRawBitmapSurface(src);
+	unsigned int **srclongbuffer = (unsigned int **)srccharbuffer;
+
+	for (int y = 0; y < srcHeight; y++) {
+
+		for (int x = 0; x < srcWidth; x++) {
+
+			int srcr = getb32(srclongbuffer[y][x]);
+			int srcg = getg32(srclongbuffer[y][x]);
+			int srcb = getr32(srclongbuffer[y][x]);
+			int tempmaxim = max(srcr, srcg);
+			int maxim = max(tempmaxim, srcb);
+			int tempmin = min(srcr, srcg);
+			int minim = min(srcb, tempmin);
+			int light = (maxim + minim) / 2 ;
+			if (light < threshold) srclongbuffer[y][x] = makeacol32(0, 0, 0, 0);
+
+		}
+
+	}
+
+	return 0;
+
+}
+
+
+int Blur(int sprite, int radius) {
+
+	BITMAP *src = engine->GetSpriteGraphic(sprite);
+
+	int srcWidth, srcHeight;
+	engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, nullptr);
+
+	unsigned char **srccharbuffer = engine->GetRawBitmapSurface(src);
+	unsigned int **srclongbuffer = (unsigned int **)srccharbuffer;
+	int negrad = -1 * radius;
+
+	//use a 1Dimensional array since the array is on the free store, not the stack
+	Pixel32 *Pixels = new Pixel32[(srcWidth + (radius * 2)) * (srcHeight + (radius * 2))];  // this defines a copy of the individual channels in class form.
+	Pixel32 *Dest = new Pixel32[(srcWidth + (radius * 2)) * (srcHeight + (radius * 2))];  // this is the destination sprite. both have a border all the way round equal to the radius for the blurring.
+	Pixel32 *Temp = new Pixel32[(srcWidth + (radius * 2)) * (srcHeight + (radius * 2))];
+
+
+	int arraywidth = srcWidth + (radius * 2); //define the array width since its used many times in the algorithm
+
+
+	for (int y = 0; y < srcHeight; y++) { //copy the sprite to the Pixels class array
+
+		for (int x = 0; x < srcWidth; x++) {
+
+			int locale = xytolocale(x + radius, y + radius, arraywidth);
+
+			Pixels[locale].Red = getr32(srclongbuffer[y][x]);
+			Pixels[locale].Green = getg32(srclongbuffer[y][x]);
+			Pixels[locale].Blue = getb32(srclongbuffer[y][x]);
+			Pixels[locale].Alpha = geta32(srclongbuffer[y][x]);
+
+
+
+		}
+
+	}
+
+
+	int  numofpixels = (radius * 2 + 1);
+	for (int y = 0; y < srcHeight; y++) {
+
+		int totalr = 0;
+		int totalg = 0;
+		int totalb = 0;
+		int totala = 0;
+
+		// Process entire window for first pixel
+		for (int kx = negrad; kx <= radius; kx++) {
+			int locale = xytolocale(kx + radius, y + radius, arraywidth);
+			totala += Pixels[locale].Alpha;
+			totalr += (Pixels[locale].Red * Pixels[locale].Alpha) / 255;
+			totalg += (Pixels[locale].Green * Pixels[locale].Alpha) / 255;
+			totalb += (Pixels[locale].Blue * Pixels[locale].Alpha) / 255;
+		}
+
+		int locale = xytolocale(radius, y + radius, arraywidth);
+		Temp[locale].Red = totalr / numofpixels; // take an average and assign it to the destination array
+		Temp[locale].Green = totalg / numofpixels;
+		Temp[locale].Blue = totalb / numofpixels;
+		Temp[locale].Alpha = totala / numofpixels;
+
+
+		// Subsequent pixels just update window total
+		for (int x = 1; x < srcWidth; x++) {
+			// Subtract pixel leaving window
+			int locale = xytolocale(x - 1, y + radius, arraywidth);
+			totala -= Pixels[locale].Alpha;
+			totalr -= (Pixels[locale].Red * Pixels[locale].Alpha) / 255;
+			totalg -= (Pixels[locale].Green * Pixels[locale].Alpha) / 255;
+			totalb -= (Pixels[locale].Blue * Pixels[locale].Alpha) / 255;
+
+
+			// Add pixel entering window
+
+			locale = xytolocale(x + radius + radius, y + radius, arraywidth);
+			totala += Pixels[locale].Alpha;
+			totalr += (Pixels[locale].Red * Pixels[locale].Alpha) / 255;
+			totalg += (Pixels[locale].Green * Pixels[locale].Alpha) / 255;
+			totalb += (Pixels[locale].Blue * Pixels[locale].Alpha) / 255;
+
+
+			locale = xytolocale(x + radius, y + radius, arraywidth);
+			Temp[locale].Red = totalr / numofpixels; // take an average and assign it to the destination array
+			Temp[locale].Green = totalg / numofpixels;
+			Temp[locale].Blue = totalb / numofpixels;
+			Temp[locale].Alpha = totala / numofpixels;
+
+		}
+	}
+
+
+
+
+	for (int x = 0; x < srcWidth; x++) {
+
+		int totalr = 0;
+		int totalg = 0;
+		int totalb = 0;
+		int totala = 0;
+
+		// Process entire window for first pixel
+		for (int ky = negrad; ky <= radius; ky++) {
+			int locale = xytolocale(x + radius, ky + radius, arraywidth);
+			totala += Temp[locale].Alpha;
+			totalr += (Temp[locale].Red * Temp[locale].Alpha) / 255;
+			totalg += (Temp[locale].Green * Temp[locale].Alpha) / 255;
+			totalb += (Temp[locale].Blue * Temp[locale].Alpha) / 255;
+		}
+
+		int locale = xytolocale(x + radius, radius, arraywidth);
+		Dest[locale].Red = totalr / numofpixels; // take an average and assign it to the destination array
+		Dest[locale].Green = totalg / numofpixels;
+		Dest[locale].Blue = totalb / numofpixels;
+		Dest[locale].Alpha = totala / numofpixels;
+
+
+		// Subsequent pixels just update window total
+		for (int y = 1; y < srcHeight; y++) {
+			// Subtract pixel leaving window
+			int locale = xytolocale(x + radius, y - 1, arraywidth);
+			totala -= Temp[locale].Alpha;
+			totalr -= (Temp[locale].Red * Temp[locale].Alpha) / 255;
+			totalg -= (Temp[locale].Green * Temp[locale].Alpha) / 255;
+			totalb -= (Temp[locale].Blue * Temp[locale].Alpha) / 255;
+
+
+			// Add pixel entering window
+
+			locale = xytolocale(x + radius, y + radius + radius, arraywidth);
+			totala += Temp[locale].Alpha;
+			totalr += (Temp[locale].Red * Temp[locale].Alpha) / 255;
+			totalg += (Temp[locale].Green * Temp[locale].Alpha) / 255;
+			totalb += (Temp[locale].Blue * Temp[locale].Alpha) / 255;
+
+
+			locale = xytolocale(x + radius, y + radius, arraywidth);
+			Dest[locale].Red = totalr / numofpixels; // take an average and assign it to the destination array
+			Dest[locale].Green = totalg / numofpixels;
+			Dest[locale].Blue = totalb / numofpixels;
+			Dest[locale].Alpha = totala / numofpixels;
+
+		}
+	}
+
+
+
+	for (int y = 0; y < srcHeight; y++) {
+
+		for (int x = 0; x < srcWidth; x++) {
+			int locale = xytolocale(x + radius, y + radius, arraywidth);
+			srclongbuffer[y][x] = Dest[locale].GetColorAsInt(); //write the destination array to the main buffer
+
+		}
+
+	}
+	delete [] Pixels;
+	delete [] Dest;
+	delete [] Temp;
+	engine->ReleaseBitmapSurface(src);
+	delete srclongbuffer;
+	delete srccharbuffer;
+	return 0;
+}
+
+int Clamp(int val, int min, int max) {
+
+	if (val < min) return min;
+	else if (val > max) return max;
+	else return val;
+
+}
+
+int DrawSprite(int destination, int sprite, int x, int y, int DrawMode, int trans) {
+
+	trans = 100 - trans;
+	int srcWidth, srcHeight, destWidth, destHeight;
+
+	BITMAP *src = engine->GetSpriteGraphic(sprite);
+	BITMAP *dest = engine->GetSpriteGraphic(destination);
+
+	engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, nullptr);
+	engine->GetBitmapDimensions(dest, &destWidth, &destHeight, nullptr);
+
+	if (x > destWidth || y > destHeight || x + srcWidth < 0 || y + srcHeight < 0) return 1; // offscreen
+
+	unsigned char **srccharbuffer = engine->GetRawBitmapSurface(src);
+	unsigned int **srclongbuffer = (unsigned int **)srccharbuffer;
+
+	unsigned char **destcharbuffer = engine->GetRawBitmapSurface(dest);
+	unsigned int **destlongbuffer = (unsigned int **)destcharbuffer;
+
+
+
+	if (srcWidth + x > destWidth) srcWidth = destWidth - x - 1;
+	if (srcHeight + y > destHeight) srcHeight = destHeight - y - 1;
+
+	int destx, desty;
+	int srcr, srcg, srcb, srca, destr, destg, destb, desta, finalr, finalg, finalb, finala;
+	unsigned int col;
+	int starty = 0;
+	int startx = 0;
+
+	if (x < 0) startx = -1 * x;
+	if (y < 0) starty = -1 * y;
+
+	int ycount = 0;
+	int xcount = 0;
+	for (ycount = starty; ycount < srcHeight; ycount ++) {
+
+		for (xcount = startx; xcount < srcWidth; xcount ++) {
+
+			destx = xcount + x;
+			desty = ycount + y;
+
+			srca = (geta32(srclongbuffer[ycount][xcount]));
+
+			if (srca != 0) {
+				srca = srca * trans / 100;
+				srcr =  getr32(srclongbuffer[ycount][xcount]);
+				srcg =  getg32(srclongbuffer[ycount][xcount]);
+				srcb =  getb32(srclongbuffer[ycount][xcount]);
+
+				destr =  getr32(destlongbuffer[desty][destx]);
+				destg =  getg32(destlongbuffer[desty][destx]);
+				destb =  getb32(destlongbuffer[desty][destx]);
+				desta =  geta32(destlongbuffer[desty][destx]);
+
+
+
+
+				switch (DrawMode) {
+
+				case 0:
+
+					finalr = srcr;
+					finalg = srcg;
+					finalb = srcb;
+					break;
+
+				case 1:
+
+					finalr = ChannelBlend_Lighten(srcr, destr);
+					finalg = ChannelBlend_Lighten(srcg, destg);
+					finalb = ChannelBlend_Lighten(srcb, destb);
+					break;
+
+				case 2:
+
+
+					finalr = ChannelBlend_Darken(srcr, destr);
+					finalg = ChannelBlend_Darken(srcg, destg);
+					finalb = ChannelBlend_Darken(srcb, destb);
+					break;
+
+				case 3:
+
+
+					finalr = ChannelBlend_Multiply(srcr, destr);
+					finalg = ChannelBlend_Multiply(srcg, destg);
+					finalb = ChannelBlend_Multiply(srcb, destb);
+					break;
+
+				case 4:
+
+
+					finalr = ChannelBlend_Add(srcr, destr);
+					finalg = ChannelBlend_Add(srcg, destg);
+					finalb = ChannelBlend_Add(srcb, destb);
+					break;
+
+				case 5:
+
+
+					finalr = ChannelBlend_Subtract(srcr, destr);
+					finalg = ChannelBlend_Subtract(srcg, destg);
+					finalb = ChannelBlend_Subtract(srcb, destb);
+					break;
+
+				case 6:
+
+
+					finalr = ChannelBlend_Difference(srcr, destr);
+					finalg = ChannelBlend_Difference(srcg, destg);
+					finalb = ChannelBlend_Difference(srcb, destb);
+					break;
+
+				case 7:
+
+
+					finalr = ChannelBlend_Negation(srcr, destr);
+					finalg = ChannelBlend_Negation(srcg, destg);
+					finalb = ChannelBlend_Negation(srcb, destb);
+					break;
+
+				case 8:
+
+
+					finalr = ChannelBlend_Screen(srcr, destr);
+					finalg = ChannelBlend_Screen(srcg, destg);
+					finalb = ChannelBlend_Screen(srcb, destb);
+					break;
+
+
+				case 9:
+
+
+					finalr = ChannelBlend_Exclusion(srcr, destr);
+					finalg = ChannelBlend_Exclusion(srcg, destg);
+					finalb = ChannelBlend_Exclusion(srcb, destb);
+					break;
+
+
+				case 10:
+
+
+					finalr = ChannelBlend_Overlay(srcr, destr);
+					finalg = ChannelBlend_Overlay(srcg, destg);
+					finalb = ChannelBlend_Overlay(srcb, destb);
+					break;
+
+
+				case 11:
+
+
+					finalr = ChannelBlend_SoftLight(srcr, destr);
+					finalg = ChannelBlend_SoftLight(srcg, destg);
+					finalb = ChannelBlend_SoftLight(srcb, destb);
+					break;
+
+				case 12:
+
+
+					finalr = ChannelBlend_HardLight(srcr, destr);
+					finalg = ChannelBlend_HardLight(srcg, destg);
+					finalb = ChannelBlend_HardLight(srcb, destb);
+					break;
+
+				case 13:
+
+
+					finalr = ChannelBlend_ColorDodge(srcr, destr);
+					finalg = ChannelBlend_ColorDodge(srcg, destg);
+					finalb = ChannelBlend_ColorDodge(srcb, destb);
+					break;
+
+				case 14:
+
+
+					finalr = ChannelBlend_ColorBurn(srcr, destr);
+					finalg = ChannelBlend_ColorBurn(srcg, destg);
+					finalb = ChannelBlend_ColorBurn(srcb, destb);
+					break;
+
+				case 15:
+
+
+					finalr = ChannelBlend_LinearDodge(srcr, destr);
+					finalg = ChannelBlend_LinearDodge(srcg, destg);
+					finalb = ChannelBlend_LinearDodge(srcb, destb);
+					break;
+
+				case 16:
+
+
+					finalr = ChannelBlend_LinearBurn(srcr, destr);
+					finalg = ChannelBlend_LinearBurn(srcg, destg);
+					finalb = ChannelBlend_LinearBurn(srcb, destb);
+					break;
+
+
+
+				case 17:
+
+
+					finalr = ChannelBlend_LinearLight(srcr, destr);
+					finalg = ChannelBlend_LinearLight(srcg, destg);
+					finalb = ChannelBlend_LinearLight(srcb, destb);
+					break;
+
+
+
+				case 18:
+
+
+					finalr = ChannelBlend_VividLight(srcr, destr);
+					finalg = ChannelBlend_VividLight(srcg, destg);
+					finalb = ChannelBlend_VividLight(srcb, destb);
+					break;
+
+				case 19:
+
+
+					finalr = ChannelBlend_PinLight(srcr, destr);
+					finalg = ChannelBlend_PinLight(srcg, destg);
+					finalb = ChannelBlend_PinLight(srcb, destb);
+					break;
+
+				case 20:
+
+
+					finalr = ChannelBlend_HardMix(srcr, destr);
+					finalg = ChannelBlend_HardMix(srcg, destg);
+					finalb = ChannelBlend_HardMix(srcb, destb);
+					break;
+
+				case 21:
+
+
+					finalr = ChannelBlend_Reflect(srcr, destr);
+					finalg = ChannelBlend_Reflect(srcg, destg);
+					finalb = ChannelBlend_Reflect(srcb, destb);
+					break;
+
+				case 22:
+
+
+					finalr = ChannelBlend_Glow(srcr, destr);
+					finalg = ChannelBlend_Glow(srcg, destg);
+					finalb = ChannelBlend_Glow(srcb, destb);
+					break;
+
+				case 23:
+
+
+					finalr = ChannelBlend_Phoenix(srcr, destr);
+					finalg = ChannelBlend_Phoenix(srcg, destg);
+					finalb = ChannelBlend_Phoenix(srcb, destb);
+					break;
+
+				}
+
+				finala = 255 - (255 - srca) * (255 - desta) / 255;
+				finalr = srca * finalr / finala + desta * destr * (255 - srca) / finala / 255;
+				finalg = srca * finalg / finala + desta * destg * (255 - srca) / finala / 255;
+				finalb = srca * finalb / finala + desta * destb * (255 - srca) / finala / 255;
+				col = makeacol32(finalr, finalg, finalb, finala);
+				destlongbuffer[desty][destx] = col;
+
+			}
+
+
+		}
+
+	}
+
+	engine->ReleaseBitmapSurface(src);
+	engine->ReleaseBitmapSurface(dest);
+	engine->NotifySpriteUpdated(destination);
+	return 0;
+
+}
+
+
+int DrawAdd(int destination, int sprite, int x, int y, float scale) {
+
+
+	int srcWidth, srcHeight, destWidth, destHeight;
+
+	BITMAP *src = engine->GetSpriteGraphic(sprite);
+	BITMAP *dest = engine->GetSpriteGraphic(destination);
+
+	engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, nullptr);
+	engine->GetBitmapDimensions(dest, &destWidth, &destHeight, nullptr);
+
+	if (x > destWidth || y > destHeight) return 1; // offscreen
+
+	unsigned char **srccharbuffer = engine->GetRawBitmapSurface(src);
+	unsigned int **srclongbuffer = (unsigned int **)srccharbuffer;
+
+	unsigned char **destcharbuffer = engine->GetRawBitmapSurface(dest);
+	unsigned int **destlongbuffer = (unsigned int **)destcharbuffer;
+
+	if (srcWidth + x > destWidth) srcWidth = destWidth - x - 1;
+	if (srcHeight + y > destHeight) srcHeight = destHeight - y - 1;
+
+	int destx, desty;
+	int srcr, srcg, srcb, srca, destr, destg, destb, desta, finalr, finalg, finalb, finala;
+	unsigned int col;
+	int ycount = 0;
+	int xcount = 0;
+
+	int starty = 0;
+	int startx = 0;
+
+	if (x < 0) startx = -1 * x;
+	if (y < 0) starty = -1 * y;
+
+
+
+	for (ycount = starty; ycount < srcHeight; ycount ++) {
+
+		for (xcount = startx; xcount < srcWidth; xcount ++) {
+
+			destx = xcount + x;
+			desty = ycount + y;
+
+			srca = (geta32(srclongbuffer[ycount][xcount]));
+
+			if (srca != 0) {
+
+
+				srcr =  getr32(srclongbuffer[ycount][xcount]) * srca / 255 * scale;
+				srcg =  getg32(srclongbuffer[ycount][xcount]) * srca / 255 * scale;
+				srcb =  getb32(srclongbuffer[ycount][xcount]) * srca / 255 * scale;
+				desta =  geta32(destlongbuffer[desty][destx]);
+
+				if (desta == 0) {
+					destr = 0;
+					destg = 0;
+					destb = 0;
+
+				} else {
+					destr =  getr32(destlongbuffer[desty][destx]);
+					destg =  getg32(destlongbuffer[desty][destx]);
+					destb =  getb32(destlongbuffer[desty][destx]);
+				}
+
+				finala = 255 - (255 - srca) * (255 - desta) / 255;
+				finalr = Clamp(srcr + destr, 0, 255);
+				finalg = Clamp(srcg + destg, 0, 255);
+				finalb = Clamp(srcb + destb, 0, 255);
+				col = makeacol32(finalr, finalg, finalb, finala);
+				destlongbuffer[desty][destx] = col;
+
+			}
+
+		}
+
+	}
+
+	engine->ReleaseBitmapSurface(src);
+	engine->ReleaseBitmapSurface(dest);
+	engine->NotifySpriteUpdated(destination);
+	return 0;
+
+
+
+}
+
+
+
+int DrawAlpha(int destination, int sprite, int x, int y, int trans) {
+
+	trans = 100 - trans;
+
+	int srcWidth, srcHeight, destWidth, destHeight;
+
+	BITMAP *src = engine->GetSpriteGraphic(sprite);
+	BITMAP *dest = engine->GetSpriteGraphic(destination);
+
+	engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, nullptr);
+	engine->GetBitmapDimensions(dest, &destWidth, &destHeight, nullptr);
+
+	if (x > destWidth || y > destHeight) return 1; // offscreen
+
+	unsigned char **srccharbuffer = engine->GetRawBitmapSurface(src);
+	unsigned int **srclongbuffer = (unsigned int **)srccharbuffer;
+
+	unsigned char **destcharbuffer = engine->GetRawBitmapSurface(dest);
+	unsigned int **destlongbuffer = (unsigned int **)destcharbuffer;
+
+	if (srcWidth + x > destWidth) srcWidth = destWidth - x - 1;
+	if (srcHeight + y > destHeight) srcHeight = destHeight - y - 1;
+
+	int destx, desty;
+	int srcr, srcg, srcb, srca, destr, destg, destb, desta, finalr, finalg, finalb, finala;
+
+	int ycount = 0;
+	int xcount = 0;
+
+	int starty = 0;
+	int startx = 0;
+
+	if (x < 0) startx = -1 * x;
+	if (y < 0) starty = -1 * y;
+
+
+	for (ycount = starty; ycount < srcHeight; ycount ++) {
+
+		for (xcount = startx; xcount < srcWidth; xcount ++) {
+
+			destx = xcount + x;
+			desty = ycount + y;
+
+			srca = (geta32(srclongbuffer[ycount][xcount])) * trans / 100;
+
+			if (srca != 0) {
+
+				srcr =  getr32(srclongbuffer[ycount][xcount]);
+				srcg =  getg32(srclongbuffer[ycount][xcount]);
+				srcb =  getb32(srclongbuffer[ycount][xcount]);
+
+				destr =  getr32(destlongbuffer[desty][destx]);
+				destg =  getg32(destlongbuffer[desty][destx]);
+				destb =  getb32(destlongbuffer[desty][destx]);
+				desta =  geta32(destlongbuffer[desty][destx]);
+
+				finala = 255 - (255 - srca) * (255 - desta) / 255;
+				finalr = srca * srcr / finala + desta * destr * (255 - srca) / finala / 255;
+				finalg = srca * srcg / finala + desta * destg * (255 - srca) / finala / 255;
+				finalb = srca * srcb / finala + desta * destb * (255 - srca) / finala / 255;
+
+				destlongbuffer[desty][destx] = makeacol32(finalr, finalg, finalb, finala);
+
+			}
+
+		}
+
+	}
+
+	engine->ReleaseBitmapSurface(src);
+	engine->ReleaseBitmapSurface(dest);
+	engine->NotifySpriteUpdated(destination);
+
+	return 0;
+}
+
+
+#if AGS_PLATFORM_OS_WINDOWS
+
+//==============================================================================
+
+// ***** Design time *****
+
+IAGSEditor *editor; // Editor interface
+
+const char *ourScriptHeader =
+    "import int DrawAlpha(int destination, int sprite, int x, int y, int transparency);\r\n"
+    "import int GetAlpha(int sprite, int x, int y);\r\n"
+    "import int PutAlpha(int sprite, int x, int y, int alpha);\r\n"
+    "import int Blur(int sprite, int radius);\r\n"
+    "import int HighPass(int sprite, int threshold);\r\n"
+    "import int DrawAdd(int destination, int sprite, int x, int y, float scale);\r\n"
+    "import int DrawSprite(int destination, int sprite, int x, int y, int DrawMode, int trans);";
+
+
+
+
+//------------------------------------------------------------------------------
+
+LPCSTR AGS_GetPluginName() {
+	return ("AGSBlend");
+}
+
+//------------------------------------------------------------------------------
+
+int AGS_EditorStartup(IAGSEditor *lpEditor) {
+	// User has checked the plugin to use it in their game
+
+	// If it's an earlier version than what we need, abort.
+	if (lpEditor->version < MIN_EDITOR_VERSION)
+		return (-1);
+
+	editor = lpEditor;
+	editor->RegisterScriptHeader(ourScriptHeader);
+
+	// Return 0 to indicate success
+	return (0);
+}
+
+//------------------------------------------------------------------------------
+
+void AGS_EditorShutdown() {
+	// User has un-checked the plugin from their game
+	editor->UnregisterScriptHeader(ourScriptHeader);
+}
+
+//------------------------------------------------------------------------------
+
+void AGS_EditorProperties(HWND parent) {                      //*** optional ***
+	// User has chosen to view the Properties of the plugin
+	// We could load up an options dialog or something here instead
+	/*  MessageBox(parent,
+	               L"AGSBlend v1.0 By Calin Leafshade",
+	               L"About",
+	               MB_OK | MB_ICONINFORMATION);
+	         */
+}
+
+//------------------------------------------------------------------------------
+
+int AGS_EditorSaveGame(char *buffer, int bufsize) {           //*** optional ***
+	// Called by the editor when the current game is saved to disk.
+	// Plugin configuration can be stored in [buffer] (max [bufsize] bytes)
+	// Return the amount of bytes written in the buffer
+	return (0);
+}
+
+//------------------------------------------------------------------------------
+
+void AGS_EditorLoadGame(char *buffer, int bufsize) {          //*** optional ***
+	// Called by the editor when a game is loaded from disk
+	// Previous written data can be read from [buffer] (size [bufsize]).
+	// Make a copy of the data, the buffer is freed after this function call.
+}
+
+//==============================================================================
+
+#endif
+
+// ***** Run time *****
+
+// Engine interface
+
+//------------------------------------------------------------------------------
+
+#define REGISTER(x) engine->RegisterScriptFunction(#x, (void *) (x));
+#define STRINGIFY(s) STRINGIFY_X(s)
+#define STRINGIFY_X(s) #s
+
+void AGS_EngineStartup(IAGSEngine *lpEngine) {
+	engine = lpEngine;
+
+	// Make sure it's got the version with the features we need
+	if (engine->version < MIN_ENGINE_VERSION)
+		engine->AbortGame("Plugin needs engine version " STRINGIFY(MIN_ENGINE_VERSION) " or newer.");
+
+	//register functions
+
+	REGISTER(GetAlpha)
+	REGISTER(PutAlpha)
+	REGISTER(DrawAlpha)
+	REGISTER(Blur)
+	REGISTER(HighPass)
+	REGISTER(DrawAdd)
+	REGISTER(DrawSprite)
+
+
+}
+
+//------------------------------------------------------------------------------
+
+void AGS_EngineShutdown() {
+	// Called by the game engine just before it exits.
+	// This gives you a chance to free any memory and do any cleanup
+	// that you need to do before the engine shuts down.
+}
+
+//------------------------------------------------------------------------------
+
+int AGS_EngineOnEvent(int event, int data) {                  //*** optional ***
+	switch (event) {
+	/*
+	        case AGSE_KEYPRESS:
+	        case AGSE_MOUSECLICK:
+	        case AGSE_POSTSCREENDRAW:
+	        case AGSE_PRESCREENDRAW:
+	        case AGSE_SAVEGAME:
+	        case AGSE_RESTOREGAME:
+	        case AGSE_PREGUIDRAW:
+	        case AGSE_LEAVEROOM:
+	        case AGSE_ENTERROOM:
+	        case AGSE_TRANSITIONIN:
+	        case AGSE_TRANSITIONOUT:
+	        case AGSE_FINALSCREENDRAW:
+	        case AGSE_TRANSLATETEXT:
+	        case AGSE_SCRIPTDEBUG:
+	        case AGSE_SPRITELOAD:
+	        case AGSE_PRERENDER:
+	        case AGSE_PRESAVEGAME:
+	        case AGSE_POSTRESTOREGAME:
+	*/
+	default:
+		break;
+	}
+
+	// Return 1 to stop event from processing further (when needed)
+	return (0);
+}
+
+//------------------------------------------------------------------------------
+
+int AGS_EngineDebugHook(const char *scriptName,
+                        int lineNum, int reserved) {          //*** optional ***
+	// Can be used to debug scripts, see documentation
+	return 0;
+}
+
+//------------------------------------------------------------------------------
+
+void AGS_EngineInitGfx(const char *driverID, void *data) {    //*** optional ***
+	// This allows you to make changes to how the graphics driver starts up.
+	// See documentation
+}
+
+//..............................................................................
+
+
+#if defined(BUILTIN_PLUGINS)
+}
+#endif
diff --git a/engines/ags/plugins/ags_blend/ags_blend.h b/engines/ags/plugins/ags_blend/ags_blend.h
new file mode 100644
index 0000000000..c09349c9f1
--- /dev/null
+++ b/engines/ags/plugins/ags_blend/ags_blend.h
@@ -0,0 +1,14 @@
+#ifndef AGS_BLEND_H
+#define AGS_BLEND_H
+
+#include "plugin/agsplugin.h"
+
+namespace agsblend {
+void AGS_EngineStartup(IAGSEngine *lpEngine);
+void AGS_EngineShutdown();
+int AGS_EngineOnEvent(int event, int data);
+int AGS_EngineDebugHook(const char *scriptName, int lineNum, int reserved);
+void AGS_EngineInitGfx(const char *driverID, void *data);
+}
+
+#endif
\ No newline at end of file
diff --git a/engines/ags/plugins/agscreditz/agscreditz.cpp b/engines/ags/plugins/ags_creditz/ags_creditz.cpp
similarity index 99%
rename from engines/ags/plugins/agscreditz/agscreditz.cpp
rename to engines/ags/plugins/ags_creditz/ags_creditz.cpp
index d77763ae80..3e350d820b 100644
--- a/engines/ags/plugins/agscreditz/agscreditz.cpp
+++ b/engines/ags/plugins/ags_creditz/ags_creditz.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/plugins/AGSCreditz/AGSCreditz.h"
+#include "ags/plugins/ags_creditz/ags_creditz.h"
 
 namespace AGS3 {
 namespace Plugins {
diff --git a/engines/ags/plugins/agscreditz/agscreditz.h b/engines/ags/plugins/ags_creditz/ags_creditz.h
similarity index 99%
rename from engines/ags/plugins/agscreditz/agscreditz.h
rename to engines/ags/plugins/ags_creditz/ags_creditz.h
index ab93f88a13..14f7ed67ba 100644
--- a/engines/ags/plugins/agscreditz/agscreditz.h
+++ b/engines/ags/plugins/ags_creditz/ags_creditz.h
@@ -119,7 +119,7 @@ protected:
 	static const char *AGS_GetPluginName();
 	static void AGS_EngineStartup(IAGSEngine *engine);
 
-	// Shared Script methods 
+	// Shared Script methods
 	static void ScrollCredits(const ScriptMethodParams &params);
 	static string GetCredit(const ScriptMethodParams &params);
 	static int IsCreditScrollingFinished(const ScriptMethodParams &params);
diff --git a/engines/ags/plugins/ags_flashlight/ags_flashlight.cpp b/engines/ags/plugins/ags_flashlight/ags_flashlight.cpp
new file mode 100644
index 0000000000..663e81c1b1
--- /dev/null
+++ b/engines/ags/plugins/ags_flashlight/ags_flashlight.cpp
@@ -0,0 +1,829 @@
+/*
+
+This is not the AGS Flashlight plugin,
+but a workalike plugin created by JJS for the AGS engine PSP port.
+
+*/
+
+#include "core/platform.h"
+
+#if AGS_PLATFORM_OS_WINDOWS
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#pragma warning(disable : 4244)
+#endif
+
+#if !defined(BUILTIN_PLUGINS)
+#define THIS_IS_THE_PLUGIN
+#endif
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <math.h>
+
+#if defined(PSP_VERSION)
+#include <pspsdk.h>
+#include <pspmath.h>
+#include <pspdisplay.h>
+#define sin(x) vfpu_sinf(x)
+#endif
+
+#include "plugin/agsplugin.h"
+
+#if defined(BUILTIN_PLUGINS)
+namespace agsflashlight {
+#endif
+
+#if defined(__GNUC__)
+inline unsigned long _blender_alpha16_bgr(unsigned long y) __attribute__((always_inline));
+inline void calc_x_n(unsigned long bla) __attribute__((always_inline));
+#endif
+
+const unsigned int Magic = 0xBABE0000;
+const unsigned int Version = 2;
+const unsigned int SaveMagic = Magic + Version;
+const float PI = 3.14159265f;
+
+int screen_width = 320;
+int screen_height = 200;
+int screen_color_depth = 16;
+
+IAGSEngine *engine;
+
+bool g_BitmapMustBeUpdated = true;
+
+int g_RedTint = 0;
+int g_GreenTint = 0;
+int g_BlueTint = 0;
+
+int g_DarknessLightLevel = 100;
+int g_BrightnessLightLevel = 100;
+int g_DarknessSize = 0;
+int g_DarknessDiameter = 0;
+int g_BrightnessSize = 0;
+
+int g_FlashlightX = 0;
+int g_FlashlightY = 0;
+int g_FlashlightDrawAtX = 0;
+int g_FlashlightDrawAtY = 0;
+
+bool g_FlashlightFollowMouse = false;
+
+int g_FollowCharacterId = 0;
+int g_FollowCharacterDx = 0;
+int g_FollowCharacterDy = 0;
+int g_FollowCharacterHorz = 0;
+int g_FollowCharacterVert = 0;
+
+AGSCharacter *g_FollowCharacter = nullptr;
+
+BITMAP *g_LightBitmap = nullptr;
+
+
+// This function is from Allegro, split for more performance.
+
+/* _blender_alpha16_bgr
+ *  Combines a 32 bit RGBA sprite with a 16 bit RGB destination, optimised
+ *  for when one pixel is in an RGB layout and the other is BGR.
+ */
+
+unsigned long x, n;
+
+inline void calc_x_n(unsigned long _x) {
+	x = _x;
+
+	n = x >> 24;
+
+	if (n)
+		n = (n + 1) / 8;
+
+	x = ((x >> 19) & 0x001F) | ((x >> 5) & 0x07E0) | ((x << 8) & 0xF800);
+
+	x = (x | (x << 16)) & 0x7E0F81F;
+}
+
+
+inline unsigned long _blender_alpha16_bgr(unsigned long y) {
+	unsigned long result;
+
+	y = ((y & 0xFFFF) | (y << 16)) & 0x7E0F81F;
+
+	result = ((x - y) * n / 32 + y) & 0x7E0F81F;
+
+	return ((result & 0xFFFF) | (result >> 16));
+}
+
+
+
+inline void setPixel(int x, int y, int color, unsigned int *pixel) {
+	if ((x >= g_DarknessDiameter) || (y >= g_DarknessDiameter) || (x < 0) || (y < 0))
+		return;
+
+	*(pixel + (y * g_DarknessDiameter) + x) = color;
+}
+
+
+void plotCircle(int xm, int ym, int r, unsigned int color) {
+	unsigned int *pixel = *(unsigned int **)engine->GetRawBitmapSurface(g_LightBitmap);
+
+	int x = -r;
+	int y = 0;
+	int err = 2 - 2 * r;
+
+	do {
+		setPixel(xm - x, ym + y, color, pixel); //   I. Quadrant
+		setPixel(xm - x - 1, ym + y, color, pixel);
+
+		setPixel(xm - y, ym - x, color, pixel); // II. Quadrant
+		setPixel(xm - y, ym - x - 1, color, pixel);
+
+		setPixel(xm + x, ym - y, color, pixel); // III. Quadrant
+		setPixel(xm + x + 1, ym - y, color, pixel);
+
+		setPixel(xm + y, ym + x, color, pixel); //  IV. Quadrant
+		setPixel(xm + y, ym + x + 1, color, pixel);
+
+		r = err;
+		if (r > x)
+			err +=  ++x * 2 + 1;
+
+		if (r <= y)
+			err +=  ++y * 2 + 1;
+	} while (x < 0);
+
+	engine->ReleaseBitmapSurface(g_LightBitmap);
+}
+
+
+void ClipToRange(int &variable, int min, int max) {
+	if (variable < min)
+		variable = min;
+
+	if (variable > max)
+		variable = max;
+}
+
+
+void AlphaBlendBitmap() {
+	unsigned short *destpixel = *(unsigned short **)engine->GetRawBitmapSurface(engine->GetVirtualScreen());
+	unsigned int *sourcepixel = *(unsigned int **)engine->GetRawBitmapSurface(g_LightBitmap);
+
+	unsigned short *currentdestpixel = destpixel;
+	unsigned int *currentsourcepixel = sourcepixel;
+
+	int x, y;
+
+	int targetX = (g_FlashlightDrawAtX > -1) ? g_FlashlightDrawAtX : 0;
+	int targetY = (g_FlashlightDrawAtY > -1) ? g_FlashlightDrawAtY : 0;
+
+	int startX = (g_FlashlightDrawAtX < 0) ? -1 * g_FlashlightDrawAtX : 0;
+	int endX = (g_FlashlightDrawAtX + g_DarknessDiameter < screen_width) ? g_DarknessDiameter : g_DarknessDiameter - ((g_FlashlightDrawAtX + g_DarknessDiameter) - screen_width);
+
+	int startY = (g_FlashlightDrawAtY < 0) ? -1 * g_FlashlightDrawAtY : 0;
+	int endY = (g_FlashlightDrawAtY + g_DarknessDiameter < screen_height) ? g_DarknessDiameter :  g_DarknessDiameter - ((g_FlashlightDrawAtY + g_DarknessDiameter) - screen_height);
+
+	for (y = 0; y < endY - startY; y++) {
+		currentdestpixel = destpixel + (y + targetY) * screen_width + targetX;
+		currentsourcepixel = sourcepixel + (y + startY) * g_DarknessDiameter + startX;
+
+		for (x = 0; x < endX - startX; x++) {
+			calc_x_n(*currentsourcepixel);
+			*currentdestpixel = (unsigned short)_blender_alpha16_bgr(*currentdestpixel);
+
+			currentdestpixel++;
+			currentsourcepixel++;
+		}
+	}
+
+	engine->ReleaseBitmapSurface(engine->GetVirtualScreen());
+	engine->ReleaseBitmapSurface(g_LightBitmap);
+}
+
+
+void DrawTint() {
+	int x, y;
+	BITMAP *screen = engine->GetVirtualScreen();
+	unsigned short *destpixel = *(unsigned short **)engine->GetRawBitmapSurface(screen);
+
+	int32 red, blue, green, alpha;
+
+	for (y = 0; y < screen_height; y++) {
+		for (x = 0; x < screen_width; x++) {
+			engine->GetRawColorComponents(16, *destpixel, &red, &green, &blue, &alpha);
+
+			if (g_RedTint != 0) {
+				red += g_RedTint * 8;
+				if (red > 255)
+					red = 255;
+				else if (red < 0)
+					red = 0;
+			}
+
+			if (g_BlueTint != 0) {
+				blue += g_BlueTint * 8;
+				if (blue > 255)
+					blue = 255;
+				else if (blue < 0)
+					blue = 0;
+			}
+
+			if (g_GreenTint != 0) {
+				green += g_GreenTint * 8;
+				if (green > 255)
+					green = 255;
+				else if (green < 0)
+					green = 0;
+			}
+
+			*destpixel = engine->MakeRawColorPixel(16, red, green, blue, alpha);
+			destpixel++;
+		}
+	}
+
+	engine->ReleaseBitmapSurface(screen);
+}
+
+
+void DrawDarkness() {
+	int x, y;
+	unsigned int color = (255 - (int)((float)g_DarknessLightLevel * 2.55f)) << 24;
+	BITMAP *screen = engine->GetVirtualScreen();
+	unsigned short *destpixel = *(unsigned short **)engine->GetRawBitmapSurface(screen);
+	unsigned short *currentpixel;
+
+	calc_x_n(color);
+
+	if (g_DarknessSize == 0) {
+		// Whole screen.
+		for (x = 0; x < screen_width * screen_height; x++) {
+			*destpixel = (unsigned short)_blender_alpha16_bgr(*destpixel);
+			destpixel++;
+		}
+	} else {
+		// Top.
+		if (g_FlashlightDrawAtY > -1) {
+			currentpixel = destpixel;
+			for (y = 0; y < g_FlashlightDrawAtY; y++) {
+				for (x = 0; x < screen_width; x++) {
+					*currentpixel = (unsigned short)_blender_alpha16_bgr(*currentpixel);
+					currentpixel++;
+				}
+			}
+		}
+
+		// Bottom.
+		if (g_FlashlightDrawAtY + g_DarknessDiameter < screen_height) {
+			currentpixel = destpixel + (g_FlashlightDrawAtY + g_DarknessDiameter) * screen_width;
+			for (y = g_FlashlightDrawAtY + g_DarknessDiameter; y < screen_height; y++) {
+				for (x = 0; x < screen_width; x++) {
+					*currentpixel = (unsigned short)_blender_alpha16_bgr(*currentpixel);
+					currentpixel++;
+				}
+			}
+		}
+
+		// Left.
+		if (g_FlashlightDrawAtX > 0) {
+			currentpixel = destpixel;
+			int startpoint = (g_FlashlightDrawAtY > 0) ? g_FlashlightDrawAtY : 0;
+			int endpoint = (g_FlashlightDrawAtY + g_DarknessDiameter >= screen_height) ? screen_height + 1 : g_FlashlightDrawAtY + g_DarknessDiameter + 1;
+			for (y = startpoint; y < endpoint; y++) {
+				for (x = 0; x < g_FlashlightDrawAtX; x++) {
+					*currentpixel = (unsigned short)_blender_alpha16_bgr(*currentpixel);
+					currentpixel++;
+				}
+
+				currentpixel = destpixel + screen_width * y;
+			}
+		}
+
+		// Right.
+		if (g_FlashlightDrawAtX + g_DarknessDiameter < screen_width) {
+			currentpixel = destpixel + (g_FlashlightDrawAtX + g_DarknessDiameter);
+			int startpoint = (g_FlashlightDrawAtY > 0) ? g_FlashlightDrawAtY : 0;
+			int endpoint = (g_FlashlightDrawAtY + g_DarknessDiameter >= screen_height) ? screen_height + 1 : g_FlashlightDrawAtY + g_DarknessDiameter + 1;
+			for (y = startpoint; y < endpoint; y++) {
+				for (x = g_FlashlightDrawAtX + g_DarknessDiameter; x < screen_width; x++) {
+					*currentpixel = (unsigned short)_blender_alpha16_bgr(*currentpixel);
+					currentpixel++;
+				}
+
+				currentpixel = destpixel + screen_width * y + (g_FlashlightDrawAtX + g_DarknessDiameter);
+			}
+		}
+	}
+
+	engine->ReleaseBitmapSurface(screen);
+}
+
+
+void CreateLightBitmap() {
+	if (g_DarknessSize == 0)
+		return;
+
+	if (g_LightBitmap)
+		engine->FreeBitmap(g_LightBitmap);
+
+	g_LightBitmap = engine->CreateBlankBitmap(g_DarknessDiameter, g_DarknessDiameter, 32);
+
+	// Fill with darkness color.
+	unsigned int color = (255 - (int)((float)g_DarknessLightLevel * 2.55f)) << 24;
+	unsigned int *pixel = *(unsigned int **)engine->GetRawBitmapSurface(g_LightBitmap);
+
+	int i;
+	for (i = 0; i < g_DarknessDiameter * g_DarknessDiameter; i++)
+		*pixel++ = (unsigned int)color;
+
+	// Draw light circle if wanted.
+	if (g_DarknessSize > 0) {
+		int current_value = 0;
+		color = (255 - (int)((float)g_BrightnessLightLevel * 2.55f));
+		unsigned int targetcolor = ((255 - (int)((float)g_DarknessLightLevel * 2.55f)));
+
+		int increment = (targetcolor - color) / (g_DarknessSize - g_BrightnessSize);
+		float perfect_increment = (float)(targetcolor - color) / (float)(g_DarknessSize - g_BrightnessSize);
+
+		float error_term;
+
+		for (i = g_BrightnessSize; i < g_DarknessSize; i++) {
+			error_term = (perfect_increment * (i - g_BrightnessSize)) - current_value;
+
+			if (error_term >= 1.0f)
+				increment++;
+			else if (error_term <= -1.0f)
+				increment--;
+
+			current_value += increment;
+
+			if (current_value > targetcolor)
+				current_value = targetcolor;
+
+			plotCircle(g_DarknessSize, g_DarknessSize, i, (current_value << 24) + color);
+		}
+	}
+
+	// Draw inner fully lit circle.
+	if (g_BrightnessSize > 0) {
+		color = (255 - (int)((float)g_BrightnessLightLevel * 2.55f)) << 24;
+
+		for (i = 0; i < g_BrightnessSize; i++)
+			plotCircle(g_DarknessSize, g_DarknessSize, i, color);
+	}
+
+	engine->ReleaseBitmapSurface(g_LightBitmap);
+}
+
+
+void Update() {
+	if (g_BitmapMustBeUpdated) {
+		CreateLightBitmap();
+		g_BitmapMustBeUpdated = false;
+	}
+
+	if (g_FlashlightFollowMouse) {
+		engine->GetMousePosition(&g_FlashlightX, &g_FlashlightY);
+	} else if (g_FollowCharacter != nullptr) {
+		g_FlashlightX = g_FollowCharacter->x + g_FollowCharacterDx;
+		g_FlashlightY = g_FollowCharacter->y + g_FollowCharacterDy;
+
+		if ((g_FollowCharacterHorz != 0) || (g_FollowCharacterVert != 0)) {
+			switch (g_FollowCharacter->loop) {
+			// Down
+			case 0:
+			case 4:
+			case 6:
+				g_FlashlightY += g_FollowCharacterVert;
+				break;
+
+			// Up
+			case 3:
+			case 5:
+			case 7:
+				g_FlashlightY -= g_FollowCharacterVert;
+				break;
+
+			// Left
+			case 1:
+				g_FlashlightX -= g_FollowCharacterHorz;
+				break;
+
+			// Right:
+			case 2:
+				g_FlashlightX += g_FollowCharacterHorz;
+				break;
+			}
+		}
+	}
+
+	g_FlashlightDrawAtX = g_FlashlightX - g_DarknessSize;
+	g_FlashlightDrawAtY = g_FlashlightY - g_DarknessSize;
+
+
+	if ((g_GreenTint != 0) || (g_RedTint != 0) || (g_BlueTint != 0))
+		DrawTint();
+
+	if (g_DarknessSize > 0)
+		AlphaBlendBitmap();
+
+	if (g_DarknessLightLevel != 100)
+		DrawDarkness();
+
+	engine->MarkRegionDirty(0, 0, screen_width, screen_height);
+}
+
+static size_t engineFileRead(void *ptr, size_t size, size_t count, long fileHandle) {
+	auto totalBytes = engine->FRead(ptr, size * count, fileHandle);
+	return totalBytes / size;
+}
+
+static size_t engineFileWrite(const void *ptr, size_t size, size_t count, long fileHandle) {
+	auto totalBytes = engine->FWrite(const_cast<void *>(ptr), size * count, fileHandle);
+	return totalBytes / size;
+}
+
+void RestoreGame(long file) {
+	unsigned int SaveVersion = 0;
+	engineFileRead(&SaveVersion, sizeof(SaveVersion), 1, file);
+
+	if (SaveVersion != SaveMagic) {
+		engine->AbortGame("agsflashlight: bad save.");
+	}
+
+	// Current version
+	engineFileRead(&g_RedTint, 4, 1, file);
+	engineFileRead(&g_GreenTint, 4, 1, file);
+	engineFileRead(&g_BlueTint, 4, 1, file);
+
+	engineFileRead(&g_DarknessLightLevel, 4, 1, file);
+	engineFileRead(&g_BrightnessLightLevel, 4, 1, file);
+	engineFileRead(&g_DarknessSize, 4, 1, file);
+	engineFileRead(&g_DarknessDiameter, 4, 1, file);
+	engineFileRead(&g_BrightnessSize, 4, 1, file);
+
+	engineFileRead(&g_FlashlightX, 4, 1, file);
+	engineFileRead(&g_FlashlightY, 4, 1, file);
+
+	engineFileRead(&g_FlashlightFollowMouse, 4, 1, file);
+
+	engineFileRead(&g_FollowCharacterId, 4, 1, file);
+	engineFileRead(&g_FollowCharacterDx, 4, 1, file);
+	engineFileRead(&g_FollowCharacterDy, 4, 1, file);
+	engineFileRead(&g_FollowCharacterHorz, 4, 1, file);
+	engineFileRead(&g_FollowCharacterVert, 4, 1, file);
+
+	if (g_FollowCharacterId != 0)
+		g_FollowCharacter = engine->GetCharacter(g_FollowCharacterId);
+
+	g_BitmapMustBeUpdated = true;
+}
+
+
+void SaveGame(long file) {
+	engineFileWrite(&SaveMagic, sizeof(SaveMagic), 1, file);
+
+	engineFileWrite(&g_RedTint, 4, 1, file);
+	engineFileWrite(&g_GreenTint, 4, 1, file);
+	engineFileWrite(&g_BlueTint, 4, 1, file);
+
+	engineFileWrite(&g_DarknessLightLevel, 4, 1, file);
+	engineFileWrite(&g_BrightnessLightLevel, 4, 1, file);
+	engineFileWrite(&g_DarknessSize, 4, 1, file);
+	engineFileWrite(&g_DarknessDiameter, 4, 1, file);
+	engineFileWrite(&g_BrightnessSize, 4, 1, file);
+
+	engineFileWrite(&g_FlashlightX, 4, 1, file);
+	engineFileWrite(&g_FlashlightY, 4, 1, file);
+
+	engineFileWrite(&g_FlashlightFollowMouse, 4, 1, file);
+
+	engineFileWrite(&g_FollowCharacterId, 4, 1, file);
+	engineFileWrite(&g_FollowCharacterDx, 4, 1, file);
+	engineFileWrite(&g_FollowCharacterDy, 4, 1, file);
+	engineFileWrite(&g_FollowCharacterHorz, 4, 1, file);
+	engineFileWrite(&g_FollowCharacterVert, 4, 1, file);
+}
+
+
+// ********************************************
+// ************  AGS Interface  ***************
+// ********************************************
+
+
+
+// tint screen
+void SetFlashlightTint(int RedTint, int GreenTint, int BlueTint) {
+	ClipToRange(RedTint, -31, 31);
+	ClipToRange(GreenTint, -31, 31);
+	ClipToRange(BlueTint, -31, 31);
+
+	if ((RedTint != g_RedTint) || (GreenTint != g_GreenTint) || (BlueTint != g_BlueTint))
+		g_BitmapMustBeUpdated = true;
+
+	g_RedTint = RedTint;
+	g_GreenTint = GreenTint;
+	g_BlueTint = BlueTint;
+}
+
+int GetFlashlightTintRed() {
+	return g_RedTint;
+}
+
+int GetFlashlightTintGreen() {
+	return g_GreenTint;
+}
+
+int GetFlashlightTintBlue() {
+	return g_BlueTint;
+}
+
+int GetFlashlightMinLightLevel() {
+	return 0;
+}
+
+int GetFlashlightMaxLightLevel() {
+	return 100;
+}
+
+void SetFlashlightDarkness(int LightLevel) {
+	ClipToRange(LightLevel, 0, 100);
+
+	if (LightLevel != g_DarknessLightLevel) {
+		g_BitmapMustBeUpdated = true;
+		g_DarknessLightLevel = LightLevel;
+
+		if (g_DarknessLightLevel > g_BrightnessLightLevel)
+			g_BrightnessLightLevel = g_DarknessLightLevel;
+	}
+}
+
+int GetFlashlightDarkness() {
+	return g_DarknessLightLevel;
+}
+
+void SetFlashlightDarknessSize(int Size) {
+	if (Size != g_DarknessSize) {
+		g_BitmapMustBeUpdated = true;
+		g_DarknessSize = Size;
+		g_DarknessDiameter = g_DarknessSize * 2;
+	}
+}
+
+int GetFlashlightDarknessSize() {
+	return g_DarknessSize;
+}
+
+
+void SetFlashlightBrightness(int LightLevel) {
+	ClipToRange(LightLevel, 0, 100);
+
+	if (LightLevel != g_BrightnessLightLevel) {
+		g_BitmapMustBeUpdated = true;
+		g_BrightnessLightLevel = LightLevel;
+
+		if (g_BrightnessLightLevel < g_DarknessLightLevel)
+			g_DarknessLightLevel = g_BrightnessLightLevel;
+	}
+}
+
+int GetFlashlightBrightness() {
+	return g_BrightnessLightLevel;
+}
+
+void SetFlashlightBrightnessSize(int Size) {
+	if (Size != g_BrightnessSize) {
+		g_BitmapMustBeUpdated = true;
+		g_BrightnessSize = Size;
+	}
+}
+
+int GetFlashlightBrightnessSize() {
+	return g_BrightnessSize;
+}
+
+void SetFlashlightPosition(int X, int Y) {
+	g_FlashlightX = X;
+	g_FlashlightY = Y;
+}
+
+int GetFlashlightPositionX() {
+	return g_FlashlightX;
+}
+
+int GetFlashlightPositionY() {
+	return g_FlashlightY;
+}
+
+void SetFlashlightFollowMouse(int OnOff) {
+	g_FlashlightFollowMouse = (OnOff != 0);
+}
+
+int GetFlashlightFollowMouse() {
+	return g_FlashlightFollowMouse ? 1 : 0;
+}
+
+void SetFlashlightFollowCharacter(int CharacterId, int dx, int dy, int horz, int vert) {
+	g_FollowCharacterId = CharacterId;
+	g_FollowCharacterDx = dx;
+	g_FollowCharacterDy = dy;
+	g_FollowCharacterHorz = horz;
+	g_FollowCharacterVert = vert;
+
+	g_FollowCharacter = engine->GetCharacter(CharacterId);
+}
+
+int GetFlashlightFollowCharacter() {
+	return g_FollowCharacterId;
+}
+
+int GetFlashlightCharacterDX() {
+	return g_FollowCharacterDx;
+}
+
+int GetFlashlightCharacterDY() {
+	return g_FollowCharacterDy;
+}
+
+int GetFlashlightCharacterHorz() {
+	return g_FollowCharacterHorz;
+}
+
+int GetFlashlightCharacterVert() {
+	return g_FollowCharacterVert;
+}
+
+void SetFlashlightMask(int SpriteSlot) {
+	// Not implemented.
+}
+
+int GetFlashlightMask() {
+	return 0;
+}
+
+void AGS_EngineStartup(IAGSEngine *lpEngine) {
+	engine = lpEngine;
+
+	if (engine->version < 13)
+		engine->AbortGame("Engine interface is too old, need newer version of AGS.");
+
+	engine->RegisterScriptFunction("SetFlashlightTint", (void *)&SetFlashlightTint);
+	engine->RegisterScriptFunction("GetFlashlightTintRed", (void *)&GetFlashlightTintRed);
+	engine->RegisterScriptFunction("GetFlashlightTintGreen", (void *)&GetFlashlightTintGreen);
+	engine->RegisterScriptFunction("GetFlashlightTintBlue", (void *)&GetFlashlightTintBlue);
+
+	engine->RegisterScriptFunction("GetFlashlightMinLightLevel", (void *)&GetFlashlightMinLightLevel);
+	engine->RegisterScriptFunction("GetFlashlightMaxLightLevel", (void *)&GetFlashlightMaxLightLevel);
+
+	engine->RegisterScriptFunction("SetFlashlightDarkness", (void *)&SetFlashlightDarkness);
+	engine->RegisterScriptFunction("GetFlashlightDarkness", (void *)&GetFlashlightDarkness);
+	engine->RegisterScriptFunction("SetFlashlightDarknessSize", (void *)&SetFlashlightDarknessSize);
+	engine->RegisterScriptFunction("GetFlashlightDarknessSize", (void *)&GetFlashlightDarknessSize);
+
+	engine->RegisterScriptFunction("SetFlashlightBrightness", (void *)&SetFlashlightBrightness);
+	engine->RegisterScriptFunction("GetFlashlightBrightness", (void *)&GetFlashlightBrightness);
+	engine->RegisterScriptFunction("SetFlashlightBrightnessSize", (void *)&SetFlashlightBrightnessSize);
+	engine->RegisterScriptFunction("GetFlashlightBrightnessSize", (void *)&GetFlashlightBrightnessSize);
+
+	engine->RegisterScriptFunction("SetFlashlightPosition", (void *)&SetFlashlightPosition);
+	engine->RegisterScriptFunction("GetFlashlightPositionX", (void *)&GetFlashlightPositionX);
+	engine->RegisterScriptFunction("GetFlashlightPositionY", (void *)&GetFlashlightPositionY);
+
+
+	engine->RegisterScriptFunction("SetFlashlightFollowMouse", (void *)&SetFlashlightFollowMouse);
+	engine->RegisterScriptFunction("GetFlashlightFollowMouse", (void *)&GetFlashlightFollowMouse);
+
+	engine->RegisterScriptFunction("SetFlashlightFollowCharacter", (void *)&SetFlashlightFollowCharacter);
+	engine->RegisterScriptFunction("GetFlashlightFollowCharacter", (void *)&GetFlashlightFollowCharacter);
+	engine->RegisterScriptFunction("GetFlashlightCharacterDX", (void *)&GetFlashlightCharacterDX);
+	engine->RegisterScriptFunction("GetFlashlightCharacterDY", (void *)&GetFlashlightCharacterDY);
+	engine->RegisterScriptFunction("GetFlashlightCharacterHorz", (void *)&GetFlashlightCharacterHorz);
+	engine->RegisterScriptFunction("GetFlashlightCharacterVert", (void *)&GetFlashlightCharacterVert);
+
+	engine->RegisterScriptFunction("SetFlashlightMask", (void *)&SetFlashlightMask);
+	engine->RegisterScriptFunction("GetFlashlightMask", (void *)&GetFlashlightMask);
+
+	engine->RequestEventHook(AGSE_PREGUIDRAW);
+	engine->RequestEventHook(AGSE_PRESCREENDRAW);
+	engine->RequestEventHook(AGSE_SAVEGAME);
+	engine->RequestEventHook(AGSE_RESTOREGAME);
+}
+
+void AGS_EngineShutdown() {
+
+}
+
+int AGS_EngineOnEvent(int event, int data) {
+	if (event == AGSE_PREGUIDRAW) {
+		Update();
+	} else if (event == AGSE_RESTOREGAME) {
+		RestoreGame(data);
+	} else if (event == AGSE_SAVEGAME) {
+		SaveGame(data);
+	} else if (event == AGSE_PRESCREENDRAW) {
+		// Get screen size once here.
+		engine->GetScreenDimensions(&screen_width, &screen_height, &screen_color_depth);
+		engine->UnrequestEventHook(AGSE_PRESCREENDRAW);
+
+		// Only 16 bit color depth is supported.
+		if (screen_color_depth != 16) {
+			engine->UnrequestEventHook(AGSE_PREGUIDRAW);
+			engine->UnrequestEventHook(AGSE_PRESCREENDRAW);
+			engine->UnrequestEventHook(AGSE_SAVEGAME);
+			engine->UnrequestEventHook(AGSE_RESTOREGAME);
+		}
+	}
+
+	return 0;
+}
+
+int AGS_EngineDebugHook(const char *scriptName, int lineNum, int reserved) {
+	return 0;
+}
+
+void AGS_EngineInitGfx(const char *driverID, void *data) {
+}
+
+
+
+#if AGS_PLATFORM_OS_WINDOWS && !defined(BUILTIN_PLUGINS)
+
+// ********************************************
+// ***********  Editor Interface  *************
+// ********************************************
+
+const char *scriptHeader =
+    "import void SetFlashlightTint(int RedTint, int GreenTint, int BlueTint);\r\n"
+    "import int GetFlashlightTintRed();\r\n"
+    "import int GetFlashlightTintGreen();\r\n"
+    "import int GetFlashlightTintBlue();\r\n"
+    "import int GetFlashlightMinLightLevel();\r\n"
+    "import int GetFlashlightMaxLightLevel();\r\n"
+    "import void SetFlashlightDarkness(int LightLevel);\r\n"
+    "import int GetFlashlightDarkness();\r\n"
+    "import void SetFlashlightDarknessSize(int Size);\r\n"
+    "import int GetFlashlightDarknessSize();\r\n"
+    "import void SetFlashlightBrightness(int LightLevel);\r\n"
+    "import int GetFlashlightBrightness();\r\n"
+    "import void SetFlashlightBrightnessSize(int Size);\r\n"
+    "import int GetFlashlightBrightnessSize();\r\n"
+    "import void SetFlashlightPosition(int X, int Y);\r\n"
+    "import int GetFlashlightPositionX();\r\n"
+    "import int GetFlashlightPositionY();\r\n"
+    "import void SetFlashlightFollowMouse(int OnOff);\r\n"
+    "import int GetFlashlightFollowMouse ();\r\n"
+    "import void SetFlashlightFollowCharacter(int CharacterId, int dx, int dy, int horz, int vert);\r\n"
+    "import int GetFlashlightFollowCharacter();\r\n"
+    "import int GetFlashlightCharacterDX();\r\n"
+    "import int GetFlashlightCharacterDY();\r\n"
+    "import int GetFlashlightCharacterHorz();\r\n"
+    "import int GetFlashlightCharacterVert();\r\n";
+
+
+IAGSEditor *editor;
+
+
+LPCSTR AGS_GetPluginName(void) {
+	// Return the plugin description
+	return "Flashlight plugin recreation";
+}
+
+int  AGS_EditorStartup(IAGSEditor *lpEditor) {
+	// User has checked the plugin to use it in their game
+
+	// If it's an earlier version than what we need, abort.
+	if (lpEditor->version < 1)
+		return -1;
+
+	editor = lpEditor;
+	editor->RegisterScriptHeader(scriptHeader);
+
+	// Return 0 to indicate success
+	return 0;
+}
+
+void AGS_EditorShutdown() {
+	// User has un-checked the plugin from their game
+	editor->UnregisterScriptHeader(scriptHeader);
+}
+
+void AGS_EditorProperties(HWND parent) {
+	// User has chosen to view the Properties of the plugin
+	// We could load up an options dialog or something here instead
+	MessageBoxA(parent, "Flashlight plugin recreation by JJS", "About", MB_OK | MB_ICONINFORMATION);
+}
+
+int AGS_EditorSaveGame(char *buffer, int bufsize) {
+	// We don't want to save any persistent data
+	return 0;
+}
+
+void AGS_EditorLoadGame(char *buffer, int bufsize) {
+	// Nothing to load for this plugin
+}
+
+#endif
+
+
+#if defined(BUILTIN_PLUGINS)
+} // namespace agsflashlight
+#endif
diff --git a/engines/ags/plugins/ags_flashlight/ags_flashlight.h b/engines/ags/plugins/ags_flashlight/ags_flashlight.h
new file mode 100644
index 0000000000..cd01110630
--- /dev/null
+++ b/engines/ags/plugins/ags_flashlight/ags_flashlight.h
@@ -0,0 +1,14 @@
+#ifndef AGS_FLASHLIGHT_H
+#define AGS_FLASHLIGHT_H
+
+#include "plugin/agsplugin.h"
+
+namespace agsflashlight {
+void AGS_EngineStartup(IAGSEngine *lpEngine);
+void AGS_EngineShutdown();
+int AGS_EngineOnEvent(int event, int data);
+int AGS_EngineDebugHook(const char *scriptName, int lineNum, int reserved);
+void AGS_EngineInitGfx(const char *driverID, void *data);
+}
+
+#endif
\ No newline at end of file
diff --git a/engines/ags/plugins/ags_pal_render/ags_pal_render.cpp b/engines/ags/plugins/ags_pal_render/ags_pal_render.cpp
new file mode 100644
index 0000000000..7275320213
--- /dev/null
+++ b/engines/ags/plugins/ags_pal_render/ags_pal_render.cpp
@@ -0,0 +1,2164 @@
+//
+// ags_template.cpp : Example AGS plugin file
+// See the online API reference for details of how this works.
+// Copyright (c) 2002 Chris Jones
+//
+
+#include "core/platform.h"
+
+#if AGS_PLATFORM_OS_WINDOWS
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#endif
+
+#if !defined(BUILTIN_PLUGINS)
+#define THIS_IS_THE_PLUGIN
+#endif
+
+#include <algorithm>
+#include <cmath>
+#include <string>
+#include <vector>
+#include <iostream>
+#include <math.h>
+#include <time.h>
+#include <stdlib.h>
+#include <string>
+#include <stdio.h>
+
+
+
+#include "plugin/agsplugin.h"
+#include "palrender.h"
+#include "raycast.h"
+
+#define MAX_OVERLAYS 128
+#define MAX_STARS 1024
+#define MAX_DEPTH 64
+
+#define PI         (3.1415926535f)
+#define HALF_PI    (0.5f * PI)
+#define TWO_PI     (2.0f * PI)
+#define TWO_PI_INV (1.0f / TWO_PI)
+// DllMain - standard Windows DLL entry point.
+// The AGS editor will cause this to get called when the editor first
+// starts up, and when it shuts down at the end.
+
+#if AGS_PLATFORM_OS_WINDOWS
+bool APIENTRY DllMain(HANDLE hModule,
+                      DWORD  ul_reason_for_call,
+                      LPVOID lpReserved) {
+
+	switch (ul_reason_for_call)   {
+	case DLL_PROCESS_ATTACH:
+	case DLL_THREAD_ATTACH:
+	case DLL_THREAD_DETACH:
+	case DLL_PROCESS_DETACH:
+		break;
+	}
+	return TRUE;
+}
+#endif
+
+
+
+#if defined(BUILTIN_PLUGINS)
+namespace agspalrender {
+#endif
+
+const float halfpi = (0.5f * PI);
+const float twopi  = (2.0f * PI);
+const float twopi_inv = (1.0f / TWO_PI);
+const float pisquared = PI * PI;
+const float picubed = PI * PI * PI;
+
+//unsigned char clut[256][256];
+unsigned char clut[65536];
+
+struct transoverlaytype {
+	int sprite;
+	int spritemask;
+	int blendtype;
+	int x;
+	int y;
+	int trans;
+	int level;
+	bool enabled;
+} overlay[MAX_OVERLAYS];
+
+int clutslot;
+int drawreflections;
+unsigned char cycle_remap [256];
+
+struct starstype {
+	float x;
+	float y;
+	float z;
+	unsigned char color;
+	long sprite;
+	int maxrad;
+	int scaleboost;
+};
+starstype *stars;
+
+struct starsoptions {
+	float speed;
+	int maxstars;
+	int depthmultiplier;
+	int originx;
+	int originy;
+	int overscan;
+} Starfield;
+long *reflectionmap;
+BITMAP *rcolormap;
+BITMAP *ralphamap;
+
+struct charrefopt {
+	char reflect;
+	int replaceview;
+};
+
+struct objrefopt {
+	char reflect;
+	char ignorescaling;
+};
+
+struct reflectionopt {
+	charrefopt *Characters;
+	objrefopt *Objects;
+	int blendslot;
+	int blendamount;
+} Reflection;
+
+int dummy;
+
+#define LENS_WIDTH 150
+
+struct LensDistort {
+	int xoffset;
+	int yoffset;
+};
+
+LensDistort *lens;
+struct LensOpt {
+	bool draw;
+	int lenswidth;
+	int lenszoom;
+	int level;
+	int x;
+	int y;
+	int clampoffset;
+} LensOption;
+
+const int alphamultiply [4096] = {
+//#include "alphamultiply.txt"
+};
+float rot_sine_LUT[360];
+float rot_cos_LUT[360];
+
+BITMAP *backgroundimage;
+
+PALSTRUCT objectivepal[256];
+int bgimgspr;
+
+// ***** DESIGN TIME CALLS *******
+#if AGS_PLATFORM_OS_WINDOWS && !defined(BUILTIN_PLUGINS)
+
+IAGSEditor *editor;
+const char *ourScriptHeader =
+    "enum BlendingMode {																	\r\n"
+    "eBlendAlpha = 0,																		\r\n"
+    "eBlendAdditive = 1																	\r\n"
+    "};																					\r\n"
+    "enum ObjectiveMode {																	\r\n"
+    "eUseStandardPal = 0,																	\r\n"
+    "eUseObjectivePal = 1																	\r\n"
+    "};																					\r\n"
+    "enum PlasmaMixMode {																	\r\n"
+    "ePlasmaNone = 0,																		\r\n"
+    "ePlasmaHorzBars = 1,																    \r\n"
+    "ePlasmaVertBars = 2,																    \r\n"
+    "ePlasmaCircle   = 3,																    \r\n"
+    "ePlasmaDiagBars = 4																    \r\n"
+    "};																					\r\n"
+    "enum PlasmaRootType {																\r\n"
+    "ePlasmaSlowRoot = 1,																	\r\n"
+    "ePlasmaFastRoot = 0																    \r\n"
+    "};																					\r\n"
+    "enum TransOverlayLevel {																\r\n"
+    "eTOBackground = 0,																	\r\n"
+    "eTOPreGUI     = 1,																	\r\n"
+    "eTOPostGUI    = 2																	\r\n"
+    "};																					\r\n"
+    "enum LensLevel {																		\r\n"
+    "eLensBackgroundPreTO = 0,															\r\n"
+    "eLensBackgroundPostTO = 1,															\r\n"
+    "eLensPreGUIPreTO     = 2,															\r\n"
+    "eLensPreGUIPostTO     = 3,															\r\n"
+    "eLensPostGUIPreTO     = 4,															\r\n"
+    "eLensPostGUIPostTO     = 5															\r\n"
+    "};																					\r\n"
+
+    "struct Raycast {																					   \r\n"
+    "import static void Render (int slot);															   \r\n"
+    "import static void UnloadEngine ();	//$AUTOCOMPLETEIGNORE$										   \r\n"
+    "import static void MoveForward ();																   \r\n"
+    "import static void MoveBackward ();																   \r\n"
+    "import static void RotateLeft ();																   \r\n"
+    "import static void RotateRight ();																   \r\n"
+    "import static void MakeTextures (int slot);														   \r\n"
+    "import static void Initialize (); 																   \r\n"
+    "import static void LoadMap (int worldmapSlot,int lightmapSlot,int ceilingmapSlot,int floormapSlot); \r\n"
+    "import static void SetCameraPosition (float x,float y);				 						   \r\n"
+    "import static float GetCameraX (); 														       \r\n"
+    "import static float GetCameraY (); 															   \r\n"
+    "import static int GetCameraAngle (); 														   \r\n"
+    "import static void SetCameraAngle (int angle); 												   \r\n"
+    "import static void InitSprite (int id, float x, float y, int slot, char alpha=255, BlendingMode blendmode=0, float scale_x=0, float scale_y=0, float vMove=0);\r\n"
+    "import static int GetHotspotAtXY (int x,int y); 												   \r\n"
+    "import static int GetObjectAtXY (int x,int y); 												   \r\n"
+
+    "import static void SetSpriteInteractObj (int id,int obj); 									   \r\n"
+    "import static int  GetSpriteInteractObj (int id);		 									   \r\n"
+    "import static void SetSpritePosition (int id, float x, float y); 							   \r\n"
+    "import static void SetSpriteVertOffset (int id, float vMove); 								   \r\n"
+    "import static float GetSpriteVertOffset (int id);	 										   \r\n"
+    "import static float GetSpriteX (int id); 													   \r\n"
+    "import static float GetSpriteY (int id);														   \r\n"
+    "import static int GetSpriteAngle (int id);													   \r\n"
+    "import static void SetSpriteAngle (int id,int angle);										   \r\n"
+    "import static void SetSpriteView (int id,int view);											   \r\n"
+    "import static int GetSpriteView (int id);													   \r\n"
+    "import static void SetSpriteFrame (int id,int frame);										   \r\n"
+    "import static int GetSpriteFrame (int id);													   \r\n"
+    "import static float GetSpriteScaleX (int id);											       \r\n"
+    "import static void SetSpriteScaleX (int id,float scale);									       \r\n"
+    "import static float GetSpriteScaleY (int id);												   \r\n"
+    "import static void SetSpriteScaleY (int id,float scale);										   \r\n"
+
+
+    "import static void SetWallHotspot (int id,char hotsp);	 									   \r\n"
+    "import static void SetWallTextures (int id,int n,int s,int w,int e);							   \r\n"
+    "import static void SetWallSolid (int id,int n,int s,int w,int e); 							   \r\n"
+    "import static void SetWallIgnoreLighting (int id,int n,int s,int w,int e);					   \r\n"
+    "import static void SetWallAlpha (int id,int n,int s,int w,int e); 							   \r\n"
+    "import static void SetWallBlendType (int id,BlendingMode n,BlendingMode s,BlendingMode w,BlendingMode e);\r\n"
+
+    "import static float GetMoveSpeed ();															   \r\n"
+    "import static void SetMoveSpeed (float speed);												   \r\n"
+    "import static float GetRotSpeed ();															   \r\n"
+    "import static void SetRotSpeed (float speed); 												   \r\n"
+    "import static int GetWallAt (int x,int y); 													   \r\n"
+    "import static int GetLightAt (int x,int y); 													   \r\n"
+    "import static void SetLightAt (int x,int y, int light); 										   \r\n"
+    "import static void SetWallAt (int x,int y,int id);											   \r\n"
+    "import static void SetPlaneY (float y);	 													   \r\n"
+    "import static float GetDistanceAt (int x,int y);					  							   \r\n"
+    "import static void SetSkyBox (int slot);						  							   	   \r\n"
+    "import static int GetSkyBox (int slot);						  							       \r\n"
+    "import static void SetAmbientLight (int value);				  							       \r\n"
+    "import static int GetAmbientLight ();						  							       \r\n"
+    "import static void SetFloorAt (int x,int y,int tex);										       \r\n"
+    "import static void SetCeilingAt (int x,int y,int tex);									       \r\n"
+    "import static int GetCeilingAt (int x,int y);											       \r\n"
+    "import static int GetFloorAt (int x,int y);						  						       \r\n"
+    "import static int GetLightingAt (int x,int y);						 					       \r\n"
+    "import static void SetLightingAt (int x,int y,char lighting);						 		   \r\n"
+    "import static int GetAmbientWeight ();														   \r\n"
+    "import static int GetTileX_At (int x,int y);													   \r\n"
+    "import static int GetTileY_At (int x,int y);													   \r\n"
+    "///Draws a loaded tile onto a sprite (make sure it's 64x64 pixels).							   \r\n"
+    "import static void DrawTile (int spr,int tile);												   \r\n"
+    "///Draws a sprite onto a tile (make sure it's 64x64 pixels).									   \r\n"
+    "import static void DrawOntoTile (int spr,int tile);											   \r\n"
+    "import static int GetWallHotspot (int id);													   \r\n"
+    "import static int GetWallTexture (int id,int dir);											   \r\n"
+    "import static int GetWallSolid (int id,int dir);												   \r\n"
+    "import static int GetWallIgnoreLighting (int id,int dir);									   \r\n"
+    "import static int GetWallAlpha (int id, int dir);											   \r\n"
+    "import static int GetWallBlendType (int id,int dir);											   \r\n"
+    "import static void SelectTile (int x,int y, char color);										   \r\n"
+    "import static void SetNoClip (int value);													   \r\n"
+    "import static int GetNoClip ();																   \r\n"
+    "import static int HasSeenTile (int x,int y);													   \r\n"
+    "import static int GetSpriteAlpha (int id);													   \r\n"
+    "import static void SetSpriteAlpha (int id,int alpha);										   \r\n"
+    "import static int GetSpritePic (int id);														   \r\n"
+    "import static void SetSpritePic (int id,int slot);											   \r\n"
+    "import static void SetSpriteBlendType (int id,BlendingMode type);							   \r\n"
+    "import static int GetSpriteBlendType (int id);												   \r\n"
+    "import static void SetAmbientColor (int color,int amount);									   \r\n"
+    "int dummy; //$AUTOCOMPLETEIGNORE$															   \r\n"
+    "};																							   \r\n"
+
+    "struct PALInternal {																	\r\n"
+    "///Loads the colour lookup table for translucency effects. Used by module.			\r\n"
+    "import static int LoadCLUT (int slot);// $AUTOCOMPLETESTATICONLY$					\r\n"
+    "///Cycles the internal palette structure of the plugin. Internal use only.			\r\n"
+    "import static void CycleRemap (int start, int end);// $AUTOCOMPLETESTATICONLY$		\r\n"
+    "///Resets the remap array.															\r\n"
+    "import static void ResetRemapping ();				// $AUTOCOMPLETESTATICONLY$		\r\n"
+    "///Gets the closest palette slot from 16 bit colour space.							\r\n"
+    "import static char GetColor565 (char r,char g,char b);// $AUTOCOMPLETESTATICONLY$	\r\n"
+    "///Returns the true location of a remapped colour.									\r\n"
+    "import static char GetRemappedSlot (char slot);//$AUTOCOMPLETESTATICONLY$			\r\n"
+    "///Gets the luminosity of the palette slot.											\r\n"
+    "import static int GetLuminosityFromPalette (int slot);// $AUTOCOMPLETESTATICONLY$	\r\n"
+    "///Polynomial Sine Approximation.													\r\n"
+    "import static float FastSin (float x);// $AUTOCOMPLETESTATICONLY$					\r\n"
+    "///Polynomial Cosine Approximation.													\r\n"
+    "import static float FastCos (float x);// $AUTOCOMPLETESTATICONLY$					\r\n"
+    "///Ludicrously Fast Integer Root (0-0xFFFF)											\r\n"
+    "import static int FastRoot(int x);	 // $AUTOCOMPLETESTATICONLY$					\r\n"
+    "import static int GetModifiedBackgroundImage ();	//$AUTOCOMPLETEIGNORE$				\r\n"
+    "import static void WriteObjectivePalette (char index,char r,char b, char g);			\r\n"
+    "import static int ReadObjectivePaletteR (char index);								\r\n"
+    "import static int ReadObjectivePaletteB (char index);								\r\n"
+    "import static int ReadObjectivePaletteG (char index);								\r\n"
+    "int dummy; //$AUTOCOMPLETEIGNORE$													\r\n"
+    "};																					\r\n"
+
+    "struct Translucence {																																	 \r\n"
+    "///Creates a translucent overlay. level=0: Background,level=1: Below GUIs,level=2:Above GUIs. blendmode=0: Alpha, blendmode=1: Additive			 		 \r\n"
+    "import static int CreateOverlay (int id, int sprite, int alpha, int level, int ox, int oy,int mask=0,BlendingMode blendmode=0);// $AUTOCOMPLETESTATICONLY$\r\n"
+    "///Deletes translucent overlay.																															 \r\n"
+    "import static int DeleteOverlay (int id);// $AUTOCOMPLETESTATICONLY$																						 \r\n"
+    "///Moves Translucent Overlay to OX,OY.																													 \r\n"
+    "import static int Move (int id, int ox, int oy);// $AUTOCOMPLETESTATICONLY$																				 \r\n"
+    "///Get X coordinate of translucent overlay.																												 \r\n"
+    "import static int GetOverlayX (int id);// $AUTOCOMPLETESTATICONLY$																						 \r\n"
+    "///Get Y coordinate of translucent overlay.																												 \r\n"
+    "import static int GetOverlayY (int id);// $AUTOCOMPLETESTATICONLY$																						 \r\n"
+    "///Get the sprite slot for translucent overlay id																										 \r\n"
+    "import static int GetOverlaySprite (int id);// $AUTOCOMPLETESTATICONLY$																					 \r\n"
+    "///Get the level the overlay is drawn on currently.																										 \r\n"
+    "import static int GetOverlayLevel (int id);// $AUTOCOMPLETESTATICONLY$																					 \r\n"
+    "///Get whether Translucent Overlay is currently being drawn.																								 \r\n"
+    "import static int GetOverlayEnabled (int id);// $AUTOCOMPLETESTATICONLY$																					 \r\n"
+    "///Get the alpha channel for translucent overlay id. (0-255)																								 \r\n"
+    "import static int GetOverlayAlpha (int id);// $AUTOCOMPLETESTATICONLY$																					 \r\n"
+    "///Set translucent overlay id's alpha. (0-255)																											 \r\n"
+    "import static int SetOverlayAlpha (int id, int alpha);// $AUTOCOMPLETESTATICONLY$																		 \r\n"
+    "///Turn overlay on or off.																																 \r\n"
+    "import static int SetOverlayEnabled (int id, int toggle);// $AUTOCOMPLETESTATICONLY$																		 \r\n"
+    "///Blend bg with fg (fg is changed) together at alpha translevel.																						 \r\n"
+    "import static int DrawTransSprite (int sprite, int bg, int translevel,int mask=0,BlendingMode blendmode=0,ObjectiveMode use_objpal=0);// $AUTOCOMPLETESTATICONLY$ \r\n"
+    "int dummy; //$AUTOCOMPLETEIGNORE$																														 \r\n"
+    "};																																						 \r\n"
+
+    "struct Reflections {																																\r\n"
+    "///Turn reflective floors off or on.																												\r\n"
+    "import static int Set (int toggle);// $AUTOCOMPLETESTATICONLY$																					\r\n"
+    "///Check if reflections are turned on.																											\r\n"
+    "import static int IsReflecting ();// $AUTOCOMPLETESTATICONLY$																					\r\n"
+    "import static void SetCharacterReflected (int id,int refl);// $AUTOCOMPLETESTATICONLY$															\r\n"
+    "import static void SetObjectReflected (int id,int refl);// $AUTOCOMPLETESTATICONLY$																\r\n"
+    "import static int GetCharacterReflected (int id);// $AUTOCOMPLETESTATICONLY$																		\r\n"
+    "import static int GetObjectReflected (int id);// $AUTOCOMPLETESTATICONLY$																		\r\n"
+    "import static void ReplaceCharacterReflectionView (int id,int view);// $AUTOCOMPLETESTATICONLY$													\r\n"
+    "import static void SetObjectReflectionIgnoreScaling (int id,int wb);// $AUTOCOMPLETESTATICONLY$													\r\n"
+    "int dummy; //$AUTOCOMPLETEIGNORE$																												\r\n"
+    "};																																				\r\n"
+
+
+    "struct LensDistort {																																\r\n"
+    "import static void SetPos (int x,int y);															// $AUTOCOMPLETESTATICONLY$						\r\n"
+    "import static int GetX ();																		// $AUTOCOMPLETESTATICONLY$						\r\n"
+    "import static int GetY ();																		// $AUTOCOMPLETESTATICONLY$						\r\n"
+    "import static void Set (int toggle);																// $AUTOCOMPLETESTATICONLY$						\r\n"
+    "import static int IsDrawn ();																	// $AUTOCOMPLETESTATICONLY$						\r\n"
+    "import static void SetOffsetClamp (int clamp);													//$AUTOCOMPLETEIGNORE$							\r\n"
+    "import static int GetOffsetClamp ();																//$AUTOCOMPLETEIGNORE$							\r\n"
+    "import static int GetLevel ();																	// $AUTOCOMPLETESTATICONLY$						\r\n"
+    "import static void SetLevel (int level);															// $AUTOCOMPLETESTATICONLY$						\r\n"
+    "import static void Initialize (int width, int zoom, int lensx,int lensy,LensLevel level,int clamp=-1);	// $AUTOCOMPLETESTATICONLY$				\r\n"
+    "int dummy; //$AUTOCOMPLETEIGNORE$																												\r\n"
+    "};																																				\r\n"
+
+    "struct Plasma {																																	\r\n"
+    "///Set options for plasma generation. 0 = None. 1 = Horizontal Bars (data=width). 2 = Vertical Bars (data=width). 3 = Circle (data=x,data2=y,data3=width). 4 = Diagonal Bars (data=width) \r\n"
+    "import static void SetPlasmaType (int component, PlasmaMixMode type, int data=0, int data2=0, int data3=0);// $AUTOCOMPLETESTATICONLY$						\r\n"
+    "///Set all plasma settings to 0.																													\r\n"
+    "import static void ResetPlasmaSettings ();// $AUTOCOMPLETESTATICONLY$\r\n"
+    "///Draw Plasma into dynamic sprite slot using range palstart-palend. Remember to use SetPlasmaType first!										\r\n"
+    "import static void DrawPlasma (int slot, int palstart, int palend);// $AUTOCOMPLETESTATICONLY$													\r\n"
+    "///Draw fire effect into sprite, and alpha channel into masksprite.																				\r\n"
+    "import static void DoFire (int sprite, int masksprite, int palstart,int palend, int strength, int seed=0,int cutoff=0,int windspeed=0);// $AUTOCOMPLETESTATICONLY$\r\n"
+    "int dummy; //$AUTOCOMPLETEIGNORE$																												\r\n"
+    "import static void SetRootType (PlasmaRootType real);// $AUTOCOMPLETESTATICONLY$															\r\n"
+    "import static int GetRootType ();// $AUTOCOMPLETESTATICONLY$																				\r\n"
+    "};																																				\r\n"
+
+    "struct Starfield {																																\r\n"
+    "import static void Draw (int slot, int maskslot);																								\r\n"
+    "import static void RotateStar (int star, int angle,int px,int py);																				\r\n"
+    "import static void Iterate (int slot);																											\r\n"
+    "import static void Initialize (int slot,int maxstars);																							\r\n"
+    "import static void SetOriginPoint (int x,int y);																									\r\n"
+    "import static float GetStarX (int i);																											\r\n"
+    "import static float GetStarY (int i);																											\r\n"
+    "import static float GetStarZ (int i);																											\r\n"
+    "import static void SetStarPosition (int star,float x,float y,float z);																			\r\n"
+    "import static void SetStarColor (int star, char color);																							\r\n"
+    "import static char GetStarColor (int star);																										\r\n"
+    "import static void SetStarSprite (int star, int slot);																							\r\n"
+    "import static int GetStarSprite (int star);																										\r\n"
+    "import static void SetStarSpriteRange (int start, int end, int slot);																			\r\n"
+    "import static int GetOverscan ();																												\r\n"
+    "import static void SetOverscan (int overscan);																									\r\n"
+    "import static int GetOriginX ();																													\r\n"
+    "import static int GetOriginY ();																													\r\n"
+    "import static void SetDepthMultiplier (int multi);																								\r\n"
+    "import static int GetDepthMultiplier ();																											\r\n"
+    "import static int GetMaxStars ();																												\r\n"
+    "import static void SetStarSpriteScaleBoost (int star,int boost);																					\r\n"
+    "import static int GetStarSpriteScaleBoost (int star);																							\r\n"
+    "import static void SetStarMaxRadius (int star,int radius);																						\r\n"
+    "import static int GetStarMaxRadius (int star);																									\r\n"
+    "int dummy; //$AUTOCOMPLETEIGNORE$																												\r\n"
+    "};																																				\r\n";
+
+const char *AGS_GetPluginName(void) {
+	// Return the plugin description
+	return "PALgorithms Translucent Overlay Renderer";
+}
+
+int  AGS_EditorStartup(IAGSEditor *lpEditor) {
+	// User has checked the plugin to use it in their game
+
+	// If it's an earlier version than what we need, abort.
+	if (lpEditor->version < 1)
+		return -1;
+
+	editor = lpEditor;
+	editor->RegisterScriptHeader(ourScriptHeader);
+
+	// Return 0 to indicate success
+	return 0;
+}
+
+void AGS_EditorShutdown() {
+	// User has un-checked the plugin from their game
+	editor->UnregisterScriptHeader(ourScriptHeader);
+}
+
+#if AGS_PLATFORM_OS_WINDOWS
+void AGS_EditorProperties(HWND parent) {
+	// User has chosen to view the Properties of the plugin
+	// We could load up an options dialog or something here instead
+	MessageBox(parent, "PALgorithms Translucent Overlay Renderer & Other Demo Effects (c) 2015 Scavenger", "About", MB_OK | MB_ICONINFORMATION);
+}
+
+#endif
+
+int AGS_EditorSaveGame(char *buffer, int bufsize) {
+	// We don't want to save any persistent data
+	return 0;
+}
+
+void AGS_EditorLoadGame(char *buffer, int bufsize) {
+	// Nothing to load for this dummy plugin
+}
+
+#endif // #if AGS_PLATFORM_OS_WINDOWS && !defined(BUILTIN_PLUGINS)
+// ******* END DESIGN TIME  *******
+
+
+// ****** RUN TIME ********
+
+IAGSEngine *engine;
+
+void WriteObjectivePalette(unsigned char index, unsigned char r, unsigned char b, unsigned char g) {
+	objectivepal[index].r = r;
+	objectivepal[index].b = b;
+	objectivepal[index].g = g;
+}
+
+int ReadObjectivePaletteR(unsigned char index) {
+	return objectivepal[index].r;
+}
+
+int ReadObjectivePaletteB(unsigned char index) {
+	return objectivepal[index].b;
+}
+int ReadObjectivePaletteG(unsigned char index) {
+	return objectivepal[index].g;
+}
+
+
+#define SQRT_MAGIC_F 0x5f3759df
+float  q3sqrt(const float x) {
+	const float xhalf = 0.5f * x;
+
+	union { // get bits for floating value
+		float x;
+		int i;
+	} u;
+	u.x = x;
+	u.i = SQRT_MAGIC_F - (u.i >> 1);  // gives initial guess y0
+	return x * u.x * (1.5f - xhalf * u.x * u.x); // Newton step, repeating increases accuracy
+}
+
+void Make_Sin_Lut() {
+	for (int angle = 0; angle < 360; angle++) {
+		double rad = (angle * PI) / 180.0;
+		rot_sine_LUT [angle] = static_cast<float>(sin(rad));
+		rot_cos_LUT [angle]  = static_cast<float>(cos(rad));
+	}
+}
+
+/*
+void PreMultiply_Alphas () //Ha ha, this isn't the kind of premultiplcation you're thinking of.
+{
+    for (int y=0;y<64;y++)
+        for (int x=0;x<64;x++)
+            alphamultiply [y*64+x] = y*x;
+}
+*/
+
+int GetModifiedBackgroundImage() {
+	return bgimgspr;
+}
+
+unsigned short root(unsigned short x) {
+	unsigned short a, b;
+	b = x;
+	a = x = 0x3f;
+	x = b / x;
+	a = x = (x + a) >> 1;
+	x = b / x;
+	a = x = (x + a) >> 1;
+	x = b / x;
+	x = (x + a) >> 1;
+	return (x);
+}
+
+
+inline float Hill(float x) {
+	const float a0 = 1.0f;
+	const float a2 = 2.0f / PI - 12.0f / (pisquared);
+	const float a3 = 16.0f / (picubed) - 4.0f / (pisquared);
+	const float xx = x * x;
+	const float xxx = xx * x;
+
+	return a0 + a2 * xx + a3 * xxx;
+}
+
+float FastSin(float x) {
+	// wrap x within [0, TWO_PI)
+	const float a = x * twopi_inv;
+	x -= static_cast<int>(a) * twopi;
+	if (x < 0.0f)
+		x += twopi;
+
+	// 4 pieces of hills
+	if (x < halfpi)
+		return Hill(halfpi - x);
+	else if (x < PI)
+		return Hill(x - halfpi);
+	else if (x < 3.0f * halfpi)
+		return -Hill(3.0f * halfpi - x);
+	else
+		return -Hill(x - 3.0f * halfpi);
+}
+
+float FastCos(float x) {
+	return FastSin(x + halfpi);
+}
+
+FLOAT_RETURN_TYPE AGSFastSin(SCRIPT_FLOAT(x)) {
+	INIT_SCRIPT_FLOAT(x);
+	x = FastSin(x);
+	RETURN_FLOAT(x);
+}
+
+FLOAT_RETURN_TYPE AGSFastCos(SCRIPT_FLOAT(x)) {
+	INIT_SCRIPT_FLOAT(x);
+	x = FastSin(x + halfpi);
+	RETURN_FLOAT(x);
+}
+
+
+void DrawLens(int ox, int oy) {
+	int32 sh, sw = 0;
+	engine->GetScreenDimensions(&sw, &sh, nullptr);
+	BITMAP *virtsc = engine->GetVirtualScreen();
+	if (!virtsc) engine->AbortGame("DrawLens: Cannot get virtual screen.");
+	BITMAP *lenswrite = engine->CreateBlankBitmap(LensOption.lenswidth, LensOption.lenswidth, 8);
+	unsigned char **screen = engine->GetRawBitmapSurface(virtsc);
+	unsigned char **lensarray = engine->GetRawBitmapSurface(lenswrite);
+	int radius = LensOption.lenswidth >> 1;
+	for (int y = 0; y < LensOption.lenswidth; y++) {
+		int ypos = y * LensOption.lenswidth;
+		for (int x = 0; x < LensOption.lenswidth; x++) {
+			int lenspos = ypos + x;
+			int coffx = lens[lenspos].xoffset;
+			int coffy = lens[lenspos].yoffset;
+			if (oy + coffy > 0 && oy + coffy < sh && ox + coffx > 0 && ox + coffx < sw) {
+				lensarray[y][x] = screen[oy + coffy][ox + coffx];
+				//screen[oy+coffy][ox+coffx] = abs(coffy);
+			}
+		}
+	}
+	/*
+	for (int y=0;y<LensOption.lenswidth;y++)
+	{
+	    int ypos = y*LensOption.lenswidth;
+	    for (int x=0;x<LensOption.lenswidth;x++)
+	    {
+	        if (oy+y > 0 && oy+y < sh && ox+x > 0 && ox+x < sw)
+	        {
+	            screen[oy+y][ox+x] = lensarray[y][x];
+	        }
+	    }
+	}
+	*/
+	int radsq = radius * radius;
+	for (int cy = -radius; cy <= radius; cy++) { //Draw a circle around the point, for the mask.
+		int cysq = cy * cy;
+		for (int cx = -radius; cx <= radius; cx++) {
+			int cxsq = cx * cx;
+			int dx = cx + ox;
+			int dy = cy + oy;
+			if ((cxsq + cysq <= radsq) && dx < sw && dx >= 0 && dy < sh && dy >= 0 && cy + radius < LensOption.lenswidth - 1 && cx + radius < LensOption.lenswidth - 1) {
+				//if (cy+radius < 0 || cx+radius < 0) engine->AbortGame ("I did something wrong");
+				screen[dy][dx] = lensarray[cy + radius][cx + radius];
+			}
+		}
+	}
+
+	engine->ReleaseBitmapSurface(lenswrite);
+	engine->ReleaseBitmapSurface(virtsc);
+	engine->FreeBitmap(lenswrite);
+}
+
+void SetLensPos(int x, int y) {
+	LensOption.x = x;
+	LensOption.y = y;
+}
+
+int GetLensX() {
+	return LensOption.x;
+}
+
+int GetLensY() {
+	return LensOption.y;
+}
+
+void SetLensDrawn(int toggle) {
+	if (toggle > 0) LensOption.draw = 1;
+	else LensOption.draw = 0;
+}
+
+int GetLensDrawn() {
+	return LensOption.draw;
+}
+
+void SetLensOffsetClamp(int clamp) {
+	if (clamp < 0) LensOption.clampoffset = LensOption.lenswidth;
+	else LensOption.clampoffset = clamp;
+}
+
+int GetLensOffsetClamp() {
+	return LensOption.clampoffset;
+}
+
+int GetLensLevel() {
+	return LensOption.level;
+}
+
+void SetLensLevel(int level) {
+	if (level < 0 || level > 4) engine->AbortGame("SetLensLevel: Invalid level.");
+	else LensOption.level = level;
+}
+
+void LensInitialize(int width, int zoom, int lensx, int lensy, int level, int clamp = -1) {
+	int32 sw, sh, radius;
+	if (width < 1) engine->AbortGame("Invalid lens dimension!");
+	radius = width >> 1;
+	lens = new LensDistort [width * width]();
+	engine->GetScreenDimensions(&sw, &sh, nullptr);
+	int radsq = radius * radius;
+	int zoomsq = zoom * zoom;
+	for (int y = 0; y < radius; y++) {
+		int ysq = y * y;
+		for (int x = 0; x < radius; x++) {
+			int lx, ly;
+			int xsq = x * x;
+			if ((xsq + ysq) < (radsq)) {
+				float shift = zoom / sqrt((float)(zoomsq - (xsq + ysq - radsq)));
+				lx = (int)(x * shift - x);
+				ly = (int)(y * shift - y);
+			} else {
+				lx = 0;
+				ly = 0;
+			}
+			lens[(radius - y)*width + (radius - x)].xoffset =  lx;
+			lens[(radius - y)*width + (radius - x)].yoffset =  ly;
+			lens[(radius + y)*width + (radius + x)].xoffset = -lx;
+			lens[(radius + y)*width + (radius + x)].yoffset = -ly;
+			lens[(radius + y)*width + (radius - x)].xoffset =  lx;
+			lens[(radius + y)*width + (radius - x)].yoffset = -ly;
+			lens[(radius - y)*width + (radius + x)].xoffset = -lx;
+			lens[(radius - y)*width + (radius + x)].yoffset =  ly;
+		}
+	}
+	LensOption.lenswidth = width;
+	LensOption.lenszoom = zoom;
+	if (clamp < 0) LensOption.clampoffset = width;
+	else LensOption.clampoffset = clamp;
+	LensOption.x = lensx;
+	LensOption.y = lensy;
+	if (level < 0 || level > 4) engine->AbortGame("SetLensLevel: Invalid level.");
+	else LensOption.level = level;
+}
+
+void ResetRemapping() {
+	for (int j = 0; j < 256; ++j) {
+		cycle_remap [j] = j;
+	}
+}
+
+#define MAX_PLASMA_COMPLEXITY 4
+int plasmatype[MAX_PLASMA_COMPLEXITY];
+int plasmadata [MAX_PLASMA_COMPLEXITY];
+int plasmadata2 [MAX_PLASMA_COMPLEXITY];
+int plasmadata3 [MAX_PLASMA_COMPLEXITY];
+int plasmaroottype;
+
+
+void SetPlasmaRootType(int real) {
+	if (real) plasmaroottype = 1;
+	else plasmaroottype = 0;
+}
+
+int GetPlasmaRootType() {
+	return plasmaroottype;
+}
+
+void SetPlasmaType(int component, int type, int data, int data2, int data3) {
+	if (component >= MAX_PLASMA_COMPLEXITY) engine->AbortGame("Plasma too complex!");
+	else {
+		plasmatype [component] = type;
+		plasmadata [component] = data;
+		plasmadata2[component] = data2;
+		plasmadata3[component] = data3;
+	}
+
+	//0 = None.
+	//1 = Horizontal Bars (data=width)
+	//2 = Vertical Bars (data=width)
+	//3 = Circle (data=x,data2=y,data3=width)
+	//4 = Diagonal Bars (data=width)
+}
+
+void ResetPlasmaSettings() {
+	int i = 0;
+	while (i < MAX_PLASMA_COMPLEXITY) {
+		plasmatype [i] = 0;
+		plasmadata [i] = 0;
+		plasmadata2[i] = 0;
+		plasmadata3[i] = 0;
+		i++;
+	}
+}
+
+void DrawPlasma(int slot, int palstart, int palend) {
+	BITMAP *plasmaspr = engine->GetSpriteGraphic(slot);
+	if (!plasmaspr) engine->AbortGame("Plasma: Not a sprite I can load.");
+	int32 w, h, basecol, range = 0;
+	if (palend > palstart) {
+		range = palend - palstart;
+		basecol = palstart;
+	} else {
+		range = palstart - palend;
+		basecol = palend;
+	}
+	engine->GetBitmapDimensions(plasmaspr, &w, &h, nullptr);
+	unsigned char **plasmarray = engine->GetRawBitmapSurface(plasmaspr);
+	double frange = range / 2.0;
+	int complex = 0;
+	int color = 0;
+	int i = 0;
+	while (i < MAX_PLASMA_COMPLEXITY) {
+		if (plasmatype[i] > 0) complex++;
+		i++;
+	}
+	for (int x = 0; x < w; x++) {
+		for (int y = 0; y < h; y++) {
+			color = 0;
+			for (int p = 0; p < MAX_PLASMA_COMPLEXITY; p++) {
+				if (plasmatype[p] == 1) { //1 = Horizontal Bars (data=width)
+					color += int(frange + (frange * FastSin(y / (float)plasmadata[p])));
+				} else if (plasmatype[p] == 2) { //2 = Vertical Bars (data=width)
+					color += int(frange + (frange * FastSin(x / (float)plasmadata[p])));
+				} else if (plasmatype[p] == 3) { //3 = Circle (data=x,data2=y,data3=width)
+					int cx, cy = 0;
+					cx = plasmadata [p];
+					cy = plasmadata2 [p];
+					if (plasmaroottype == 1) color += int(frange + (frange * FastSin(q3sqrt((float)((x - cx) * (x - cx) + (y - cy) * (y - cy)) / plasmadata3[p]))));
+					else color += int(frange + (frange * FastSin(root(((x - cx) * (x - cx) + (y - cy) * (y - cy)) / plasmadata3[p]))));
+				} else if (plasmatype[p] == 4) { //4 = Diagonal Bars (data=width)
+					color += int(frange + (frange * FastSin((x + y) / (float)plasmadata[p])));
+				}
+			}
+			if (color > 0 && complex > 0) color = color / complex;
+			plasmarray[y][x] = static_cast<unsigned char>(basecol + color);
+		}
+	}
+	engine->ReleaseBitmapSurface(plasmaspr);
+	engine->NotifySpriteUpdated(slot);
+}
+
+void DoFire(int sprite, int masksprite, int palstart, int palend, int strength, int seed, int cutoff, int windspeed) {
+	BITMAP *firespr = engine->GetSpriteGraphic(masksprite);
+	BITMAP *firecolorspr = engine->GetSpriteGraphic(sprite);
+	BITMAP *seedspr;
+	int32 w, h = 0;
+	int range, basecol, dir = 0;
+	if (palend > palstart) {
+		range = palend - palstart;
+		basecol = palstart;
+		dir = 1;
+	} else {
+		range = palstart - palend;
+		basecol = palend;
+		dir = -1;
+	}
+	int divider = 256 / range;
+	engine->GetBitmapDimensions(firespr, &w, &h, nullptr);
+	unsigned char **fire = engine->GetRawBitmapSurface(firespr);
+	unsigned char **color = engine->GetRawBitmapSurface(firecolorspr);
+	int sparky = 0;
+	//srand(time(NULL));
+	for (int y = 0; y < h - 1; y++) {
+		if (rand() % 10 > 7 - windspeed) { //Wind right
+			for (int x = w - 1; x > 1; x--) {
+				fire[y][x] = fire[y][x - 1];
+			}
+		} else if (rand() % 10 > 7 + windspeed) { // wind left
+			for (int x = 0; x < w - 1; x++) {
+				fire[y][x] = fire[y][x + 1];
+			}
+		}
+	}
+	for (int x = 0; x < w; x++) {
+		sparky = abs(rand() % (h - 2));
+		if (sparky < h && sparky > 0 && fire[h - sparky][x] > cutoff && abs(rand() % 10) > 7) fire[h - sparky][x] = 255;
+		sparky = abs(rand() % (h - 2));
+		if (sparky < h && sparky > 0 && fire[h - sparky][x] > cutoff && abs(rand() % 10) > 7) fire[h - sparky][x] = 0;
+	}
+	if (seed == 0) {
+		for (int x = 0; x < w; x++) fire[h - 1][x] = 255;
+		for (int x = 0; x < w; x++) fire[h - 2][x] = abs(32768 + rand()) % 256;
+	} else if (seed > 0) {
+		seedspr = engine->GetSpriteGraphic(seed);
+		BITMAP *virtsc = engine->GetVirtualScreen();
+		engine->SetVirtualScreen(firespr);
+		engine->BlitBitmap(0, 0, seedspr, 1);
+		engine->SetVirtualScreen(virtsc);
+		engine->ReleaseBitmapSurface(virtsc);
+		engine->ReleaseBitmapSurface(seedspr);
+		engine->NotifySpriteUpdated(sprite);
+		engine->NotifySpriteUpdated(masksprite);
+	}
+
+	for (int y = 0; y < h - 1; y++) {
+		for (int x = 0; x < w; x++) {
+			fire[y][x] =
+			    ((fire[(y + 1) % h][(x - 1 + w) % w]
+			      + fire[(y + 1) % h][(x) % w]
+			      + fire[(y + 1) % h][(x + 1) % w]
+			      + fire[(y + 2) % h][(x) % w])
+			     * 100) / (400 + (100 - strength));
+			if (fire[y][x] < cutoff) fire[y][x] = 0;
+			//if (fire[y][x] ==255) color [y][x] = palend;
+			else color [y][x] = static_cast<unsigned char>(basecol + (fire[y][x] / divider) * dir);
+		}
+	}
+	engine->ReleaseBitmapSurface(firespr);
+	engine->ReleaseBitmapSurface(firecolorspr);
+	engine->NotifySpriteUpdated(sprite);
+	engine->NotifySpriteUpdated(masksprite);
+}
+
+/*
+unsigned char MixColorAlpha (unsigned char fg,unsigned char bg,unsigned char alpha)
+{
+    //unsigned char rfg = cycle_remap [fg]; //Automatic remapping of palette slots.
+    //unsigned char rbg = cycle_remap [bg]; //Saves on typing elsewhere.
+    //BITMAP *clutspr = engine->GetSpriteGraphic (clutslot);
+    //if (!clutspr) engine->AbortGame ("MixColorAlpha: Can't load CLUT sprite into memory.");
+    //unsigned char **clutarray = engine->GetRawBitmapSurface (clutspr);
+    AGSColor *palette = engine->GetPalette ();
+    int i=0;
+    int out_r = (palette[fg].r>>1) * alpha + (palette[bg].r>>1) * (255 - alpha);
+    int out_g = palette[fg].g * alpha + palette[bg].g * (255 - alpha);
+    int out_b = (palette[fg].b>>1) * alpha + (palette[bg].b>>1) * (255 - alpha);
+    //unsigned char ralpha = alpha>>2;
+    //unsigned char invralpha = 64-ralpha;
+    //if (ralpha > alpha) engine->AbortGame ("wtf");
+    //int out_r = alphamultiply[(palette[fg].r>>1)][ralpha] + alphamultiply[(palette[bg].r>>1)][(invralpha)];
+    //int out_g = alphamultiply[(palette[fg].g)][ralpha] + alphamultiply[(palette[bg].g)][(invralpha)];
+    //int out_b = alphamultiply[(palette[fg].b>>1)][ralpha] + alphamultiply[(palette[bg].b>>1)][(invralpha)];
+    out_r = (out_r + 1 + (out_r >> 8)) >> 8;
+    out_g = (out_g + 1 + (out_g >> 8)) >> 8;
+    out_b = (out_b + 1 + (out_b >> 8)) >> 8;
+    i = ((out_r << 11) | (out_g << 5) | out_b);
+    unsigned char (*clutp) = clut;
+    //unsigned char result = cycle_remap [clut[i>>8][i%256]]; //Once again, to make sure that the palette slot used is the right one.
+    unsigned char result = cycle_remap [*(clutp+i)]; //Once again, to make sure that the palette slot used is the right one.
+    //engine->ReleaseBitmapSurface (clutspr);
+    return result;
+}
+
+unsigned char MixColorAdditive (unsigned char fg,unsigned char bg,unsigned char alpha)
+{
+    //unsigned char rfg = cycle_remap [fg]; //Automatic remapping of palette slots.
+    //unsigned char rbg = cycle_remap [bg]; //Saves on typing elsewhere.
+    //BITMAP *clutspr = engine->GetSpriteGraphic (clutslot);
+    //if (!clutspr) engine->AbortGame ("MixColorAlpha: Can't load CLUT sprite into memory.");
+    //unsigned char **clutarray = engine->GetRawBitmapSurface (clutspr);
+    AGSColor *palette = engine->GetPalette ();
+    int i=0;
+    int add_r,add_b,add_g = 0;
+    char ralpha = alpha>>2;
+    //if (ralpha > alpha) engine->AbortGame ("wtf");
+    //add_r = (((palette[fg].r>>1) * (alpha))>>8);
+    //add_b = (((palette[fg].b>>1) * (alpha))>>8);
+    //add_g = (((palette[fg].g)    * (alpha))>>8);
+    add_r = ((alphamultiply[(palette[fg].r>>1)*64+ralpha])>>6);
+    add_b = ((alphamultiply[(palette[fg].b>>1)*64+ralpha])>>6);
+    add_g = ((alphamultiply[(palette[fg].g   )*64+ralpha])>>6);
+    int out_r = min(31,(palette[bg].r>>1) + add_r);
+    int out_g = min(63, palette[bg].g     + add_g);
+    int out_b = min(31,(palette[bg].b>>1) + add_b);
+    i = ((out_r << 11) | (out_g << 5) | out_b);
+    unsigned char (*clutp) = clut;
+    unsigned char result = cycle_remap [*(clutp+i)]; //Once again, to make sure that the palette slot used is the right one.
+    //unsigned char result = cycle_remap [clut[i>>8][i%256]]; //Once again, to make sure that the palette slot used is the right one.
+    //engine->ReleaseBitmapSurface (clutspr);
+    return result;
+}
+*/
+unsigned char GetColor565(unsigned char r, unsigned char g, unsigned char b) {
+	//BITMAP *clutspr = engine->GetSpriteGraphic (clutslot);
+	//if (!clutspr) engine->AbortGame ("MixColorAlpha: Can't load CLUT sprite into memory.");
+	//unsigned char **clutarray = engine->GetRawBitmapSurface (clutspr);
+	int i = ((r << 11) | (g << 5) | b);
+	unsigned char (*clutp) = clut;
+	unsigned char result = *(clutp + i);
+	result = cycle_remap [result]; //Once again, to make sure that the palette slot used is the right one.
+	//engine->ReleaseBitmapSurface (clutspr);
+	return result;
+}
+
+void CycleRemap(int start, int end) {
+	if (end > start) {
+		// Rotate left
+		int wraparound = cycle_remap [start];
+		for (; start < end; ++start) {
+			cycle_remap [start] = cycle_remap [start + 1];
+		}
+		cycle_remap [end] = wraparound;
+	} else if (end < start) {
+		// Rotate right
+		int wraparound = cycle_remap [start];
+		for (; start > end; --start) {
+			cycle_remap [start] = cycle_remap [start - 1];
+		}
+		cycle_remap [end] = wraparound;
+
+	}
+}
+
+unsigned char GetRemappedSlot(unsigned char slot) {
+	return cycle_remap [slot];
+}
+
+int LoadCLUT(int slot) {
+	if (engine->GetSpriteWidth(slot) != 256 || engine->GetSpriteHeight(slot) != 256) return 1;
+	BITMAP *clutimage = engine->GetSpriteGraphic(slot);
+	unsigned char **clutarray = engine->GetRawBitmapSurface(clutimage);
+	for (int y = 0; y < 256; y++) {
+		for (int x = 0; x < 256; x++) {
+			clut[y * 256 + x] = clutarray[y][x];
+		}
+	}
+	clutslot = slot;
+	engine->ReleaseBitmapSurface(clutimage);
+	return 0;
+}
+
+void SetReflections(int toggle) {
+	drawreflections = toggle;
+}
+
+int IsReflectionsOn() {
+	return drawreflections;
+}
+
+int GetLuminosityFromPalette(int slot) {
+	AGSColor *pal = engine->GetPalette();
+	int lum = (pal[slot].r +
+	           pal[slot].r +
+	           pal[slot].r +
+	           pal[slot].g +
+	           pal[slot].g +
+	           pal[slot].g +
+	           pal[slot].g +
+	           pal[slot].b) >> 3;
+	return lum;
+}
+
+
+
+void SetStarsOriginPoint(int x, int y) {
+	Starfield.originx = x;
+	Starfield.originy = y;
+}
+void InitializeStars(int slot, int maxstars) {
+	int32 sw, sh = 0;
+	BITMAP *canvas = engine->GetSpriteGraphic(slot);
+	engine->GetBitmapDimensions(canvas, &sw, &sh, nullptr);
+	Starfield.maxstars = maxstars;
+	Starfield.overscan = 20;
+	stars = new starstype [Starfield.maxstars];
+	for (int i = 0; i < Starfield.maxstars; i++) {
+		stars[i].x = (float)((rand() % sw) << 1) - sw;
+		if (stars[i].x < 1.0 && stars[i].x > -1.0) stars[i].x = (float)sw;
+		stars[i].y = (float)((rand() % sh) << 1) - sh;
+		if (stars[i].y < 1.0 && stars[i].y > -1.0) stars[i].y = (float)sh;
+		stars[i].z = (float)(MAX_DEPTH);
+		stars[i].color = (rand() % 240);
+		stars[i].sprite = 0;
+		stars[i].maxrad = (rand() % 5);
+	}
+}
+
+void IterateStars(int slot) {
+	long sw, sh = 0;
+	sw = engine->GetSpriteWidth(slot);
+	sh = engine->GetSpriteHeight(slot);
+	for (int i = 0; i < Starfield.maxstars; i++) {
+		stars[i].z -= Starfield.speed;
+		//if (stars[i].z < 1.0) stars[i].z = (double)MAX_DEPTH;
+		float k = Starfield.depthmultiplier / stars[i].z;
+		int px = static_cast<int>(stars[i].x * k + Starfield.originx);
+		int py = static_cast<int>(stars[i].y * k + Starfield.originy);
+		if (px >= sw + Starfield.overscan || px < 0 - Starfield.overscan || py >= sh + Starfield.overscan || py < 0 - Starfield.overscan) {
+			stars[i].x = (float)((rand() % sw) << 1) - sw;
+			if (stars[i].x < 1.0 && stars[i].x > -1.0) stars[i].x = (float)sw;
+			stars[i].y = (float)((rand() % sh) << 1) - sh;
+			if (stars[i].y < 1.0 && stars[i].y > 1.0) stars[i].y = (float)sh;
+			stars[i].z = (float)MAX_DEPTH;
+			//stars[i].color = (rand () %240);
+		}
+	}
+}
+int GetStarfieldOverscan() {
+	return Starfield.overscan;
+}
+void SetStarfieldOverscan(int overscan) {
+	Starfield.overscan = overscan;
+}
+
+int GetStarfieldOriginX() {
+	return Starfield.originx;
+}
+
+int GetStarfieldOriginY() {
+	return Starfield.originy;
+}
+
+void SetStarfieldDepthMultiplier(int multi) {
+	Starfield.depthmultiplier = multi;
+}
+
+int GetStarfieldDepthMultiplier() {
+	return Starfield.depthmultiplier;
+}
+
+int GetStarfieldMaxStars() {
+	return Starfield.maxstars;
+}
+
+void SetStarSpriteScaleBoost(int star, int boost) {
+	stars[star].scaleboost = boost;
+}
+
+int GetStarSpriteScaleBoost(int star) {
+	return stars[star].scaleboost;
+}
+
+void SetStarMaxRadius(int star, int radius) {
+	stars[star].maxrad = radius;
+}
+
+int GetStarMaxRadius(int star) {
+	return stars[star].maxrad;
+}
+
+void RotateStar(int star, int angle, int px, int py) {
+	float rsin = rot_sine_LUT[angle];
+	float rcos = rot_cos_LUT[angle];
+	float fPx = (float)px;
+	float fPy = (float)py;
+	float x1 = 0, y1 = 0, xRot = 0, yRot = 0;
+	int i = star;
+	x1 = stars[i].x;
+	y1 = stars[i].y;
+	xRot = fPx + rcos * (x1 - fPx) - rsin * (y1 - fPy);
+	yRot = fPy + rsin * (x1 - fPx) + rcos * (y1 - fPy);
+	stars[i].x = xRot;
+	stars[i].y = yRot;
+	i++;
+}
+
+FLOAT_RETURN_TYPE GetStarX(int i) {
+	float starx = (float)stars[i].x;
+	RETURN_FLOAT(starx);
+}
+
+FLOAT_RETURN_TYPE GetStarY(int i) {
+	float stary = (float)stars[i].y;
+	RETURN_FLOAT(stary);
+}
+
+FLOAT_RETURN_TYPE GetStarZ(int i) {
+	float starz = (float)stars[i].z;
+	RETURN_FLOAT(starz);
+}
+
+void SetStarPosition(int star, SCRIPT_FLOAT(x), SCRIPT_FLOAT(y), SCRIPT_FLOAT(z)) {
+	INIT_SCRIPT_FLOAT(x);
+	INIT_SCRIPT_FLOAT(y);
+	INIT_SCRIPT_FLOAT(z);
+	stars[star].x = x;
+	stars[star].y = y;
+	stars[star].z = z;
+}
+
+void SetStarColor(int star, unsigned char color) {
+	stars[star].color = color;
+}
+
+unsigned char GetStarColor(int star) {
+	return stars[star].color;
+}
+
+void SetStarSprite(int star, int slot) {
+	stars[star].sprite = slot;
+}
+
+int GetStarSprite(int star) {
+	return stars[star].sprite;
+}
+
+void SetStarSpriteRange(int start, int end, int slot) {
+	int sfix = start;
+	int efix = end;
+	if (start > Starfield.maxstars) sfix = Starfield.maxstars - 1;
+	if (end > Starfield.maxstars) efix = Starfield.maxstars;
+	for (int i = sfix; i < efix; i++)
+		stars[i].sprite = slot;
+}
+
+void DrawStars(int slot, int maskslot) {
+	int32 sw, sh = 0;
+	BITMAP *canvas = engine->GetSpriteGraphic(slot);
+	if (!canvas) engine->AbortGame("DrawStars: Can't load sprite slot.");
+	BITMAP *maskcanvas = engine->GetSpriteGraphic(maskslot);
+	if (!maskcanvas) engine->AbortGame("DrawStars: Can't load mask slot.");
+	engine->GetBitmapDimensions(canvas, &sw, &sh, nullptr);
+	unsigned char **screenarray = engine->GetRawBitmapSurface(canvas);
+	unsigned char **maskarray = engine->GetRawBitmapSurface(maskcanvas);
+	for (int i = 0; i < Starfield.maxstars; i++) {
+		//stars[i].z-= 0.5;
+		//if (stars[i].z < 1.0) stars[i].z = (double)MAX_DEPTH;
+		float k = (float)Starfield.depthmultiplier / stars[i].z;
+		int px = static_cast<int>(stars[i].x * k + Starfield.originx);
+		int py = static_cast<int>(stars[i].y * k + Starfield.originy);
+		if (px >= sw + Starfield.overscan || px < 0 - Starfield.overscan || py >= sh + Starfield.overscan || py < 0 - Starfield.overscan) {
+			stars[i].x = (float)((rand() % sw) << 1) - sw;
+			if (stars[i].x < 1.0 && stars[i].x > -1.0) stars[i].x = (float)sw;
+			stars[i].y = (float)((rand() % sh) << 1) - sh;
+			if (stars[i].y < 1.0 && stars[i].y > 1.0) stars[i].y = (float)sh;
+			stars[i].z = (float)MAX_DEPTH;
+			//stars[i].color = (rand () %240);
+		} else if (stars[i].z > 0) {
+			int ivalue = (63 - (int)stars[i].z);
+			if (ivalue > 63) ivalue = 63;
+			else if (ivalue < 0) ivalue = 0;
+			unsigned char value = (unsigned char)(ivalue);
+			unsigned char maskcolor = value << 2;
+			if (stars[i].sprite > 0) {
+				BITMAP *origspr = engine->GetSpriteGraphic(stars[i].sprite);
+				int scale = (ivalue + 1) * 100 >> 6;
+				//int scale = 50;
+				if (scale < 1) scale = 1;
+				/*
+				if (scale != 100)
+				{
+				unsigned char** orig = engine->GetRawBitmapSurface (origspr);
+				int32 h1,h2,w1,w2=0;
+				double fw2,fh2;
+				engine->GetBitmapDimensions (origspr,&w1,&h1,NULL);
+				fh2 = h1 * (scale / 100.0);
+				fw2 = w1 * (scale / 100.0);
+				h2 = static_cast<int>(fh2);
+				w2 = static_cast<int>(fw2);
+				if (w2 < 1) w2 = 1;
+				if (h2 < 1) h2 = 1;
+				resizspr = engine->CreateBlankBitmap (w2,h2,8);
+				unsigned char** resized = engine->GetRawBitmapSurface (resizspr);
+				int x_ratio = (int)((w1<<16)/w2) +1;
+				int y_ratio = (int)((h1<<16)/h2) +1;
+				int x2, y2 ;
+				for (int i=0;i<h2;i++)
+				{
+				    for (int j=0;j<w2;j++)
+				   {
+				       x2 = ((j*x_ratio)>>16) ;
+				       y2 = ((i*y_ratio)>>16) ;
+				       resized [i][j] = orig [y2][x2];
+				 }
+				}
+				engine->ReleaseBitmapSurface (resizspr);
+				}
+				//resizspr = origspr;
+				int32 w,h=0;
+				engine->GetBitmapDimensions (resizspr,&w,&h,NULL);
+				unsigned char **imagemap = engine->GetRawBitmapSurface (resizspr);
+				int ox = px - (w>>1);
+				int oy = py - (h>>1);
+				for (int dy=0;dy<h;dy++)
+				{
+				for (int dx=0;dx<w;dx++)
+				{
+				   int ex = ox+dx;
+				   int ey = oy+dy;
+				   if (ex < sw && ex >= 0 && ey < sh && ey >= 0)
+				   {
+				       if (maskcolor > maskarray [ey][ex] && imagemap[dy][dx] > 0)
+				       {
+				           maskarray [ey][ex] = maskcolor;
+				           screenarray [ey][ex] = imagemap[dy][dx];
+				       }
+				   }
+				}
+				}
+				*/
+
+				unsigned char **orig = engine->GetRawBitmapSurface(origspr);
+				int32 h1, h2, w1, w2 = 0;
+				double fw2, fh2;
+				engine->GetBitmapDimensions(origspr, &w1, &h1, nullptr);
+				fh2 = h1 * (scale / 100.0);
+				fw2 = w1 * (scale / 100.0);
+				h2 = static_cast<int>(fh2);
+				w2 = static_cast<int>(fw2);
+				if (w2 < 1) w2 = 1;
+				if (h2 < 1) h2 = 1;
+				int x_ratio = (int)((w1 << 16) / w2) + 1;
+				int y_ratio = (int)((h1 << 16) / h2) + 1;
+				int x2, y2 ;
+				int ox = px - (w2 >> 1);
+				int oy = py - (h2 >> 1);
+				for (int i = 0; i < h2; i++) {
+					int temprzy = i * y_ratio;
+					int ey = oy + i;
+					for (int j = 0; j < w2; j++) {
+						x2 = ((j * x_ratio) >> 16);
+						y2 = ((temprzy) >> 16);
+						int ex = ox + j;
+						if (ex < sw && ex >= 0 && ey < sh && ey >= 0) {
+							if (maskcolor > maskarray [ey][ex] && orig[y2][x2] > 0) {
+								maskarray [ey][ex] = maskcolor;
+								screenarray [ey][ex] = orig[y2][x2];
+							}
+						}
+						//resized [i][j] = orig [y2][x2];
+					}
+				}
+				engine->ReleaseBitmapSurface(origspr);
+			} else if (stars[i].sprite == 0) {
+				if (stars[i].maxrad == 1) {
+					if (px < sw && px >= 0 && py < sh && py >= 0) {
+						if (maskcolor > maskarray[py][px]) {
+							maskarray[py][px] = maskcolor;
+							screenarray[py][px] = stars[i].color;
+						}
+					}
+				} else {
+					int scale = ((((int)stars[i].z) * 100) / 63);
+					if (scale < 1) scale = 1;
+					int radius = (stars[i].maxrad * (100 - scale) / 100);
+					int radsq = radius * radius;
+					//unsigned char color = GetColor565 (value>>1,value,value>>1);
+					unsigned char color = stars[i].color;
+					for (int cy = -radius; cy <= radius; cy++) { //Draw a circle around the point, for the mask.
+						int cysq = cy * cy;
+						for (int cx = -radius; cx <= radius; cx++) {
+							int cxsq = cx * cx;
+							int dx = cx + px;
+							int dy = cy + py;
+							if ((cxsq + cysq <= radsq) && dx < sw && dx >= 0 && dy < sh && dy >= 0) {
+								if (maskcolor > maskarray [dy][dx]) {
+									maskarray [dy][dx] = maskcolor;
+									screenarray [dy][dx] = color;
+								}
+							}
+						}
+					}
+					/*
+					for(int cy=-radius; cy<=radius; cy++) //Draw a circle around the point, for the color.
+					{
+					   int cysq = cy*cy;
+					for(int cx=-radius; cx<=radius; cx++)
+					   {
+					       int cxsq = cx*cx;
+					       int dx = cx+px;
+					       int dy = cy+py;
+					       if((cxsq+cysq <= radsq) && dx < sw && dx >= 0 && dy < sh && dy >= 0)
+					       {
+					           if (maskarray [dy][dx] == maskcolor)screenarray [dy][dx] = color;
+					       }
+					   }
+					}
+					*/
+				}
+			}
+		}
+	}
+	engine->ReleaseBitmapSurface(canvas);
+	engine->ReleaseBitmapSurface(maskcanvas);
+	engine->NotifySpriteUpdated(slot);
+	engine->NotifySpriteUpdated(maskslot);
+}
+
+
+int CreateTranslucentOverlay(int id, int sprite, int alpha, int level, int ox, int oy, int mask = 0, int blendmode = 0) {
+
+	BITMAP *testspr = engine->GetSpriteGraphic(sprite);
+	if (testspr) overlay[id].sprite = sprite;
+	else engine->AbortGame("CreateTranslucentOverlay: Invalid sprite.");
+	engine->ReleaseBitmapSurface(testspr);
+	overlay[id].level = std::max(0, std::min(level, 4));
+	overlay[id].trans = std::max(0, std::min(alpha, 255));
+	overlay[id].spritemask = mask;
+	overlay[id].x = ox;
+	overlay[id].y = oy;
+	overlay[id].enabled = true;
+	overlay[id].blendtype = blendmode;
+	return 0;
+}
+
+int DeleteTranslucentOverlay(int id) {
+	overlay[id].enabled = false;
+	overlay[id].sprite = 0;
+	overlay[id].x = 0;
+	overlay[id].y = 0;
+	overlay[id].level = 0;
+	overlay[id].trans = 0;
+	return 0;
+}
+
+int MoveTranslucentOverlay(int id, int ox, int oy) {
+	overlay[id].x = ox;
+	overlay[id].y = oy;
+	return 0;
+}
+
+int GetTranslucentOverlayX(int id) {
+	return overlay[id].x;
+}
+
+int GetTranslucentOverlayY(int id) {
+	return overlay[id].y;
+}
+
+int GetTranslucentOverlaySprite(int id) {
+	return overlay[id].sprite;
+}
+
+int GetTranslucentOverlayLevel(int id) {
+	return overlay[id].level;
+}
+
+int GetTranslucentOverlayEnabled(int id) {
+	return overlay[id].enabled;
+}
+
+int GetTranslucentOverlayAlpha(int id) {
+	return overlay[id].trans;
+}
+
+int SetTranslucentOverlayAlpha(int id, int alpha) {
+	if (alpha >= 0 && alpha < 256) overlay[id].trans = alpha;
+	else engine->AbortGame("CreateTranslucentOverlay: Invalid alpha selected.");
+	return 0;
+}
+
+int SetTranslucentOverlayEnabled(int id, int toggle) {
+	if (toggle > 0) overlay[id].enabled = true;
+	else overlay[id].enabled = false;
+	return 0;
+}
+
+void SetCharacterReflected(int id, int refl) {
+	if (refl > 0) Reflection.Characters[id].reflect = 1;
+	else Reflection.Characters[id].reflect = 0;
+}
+
+void SetObjectReflected(int id, int refl) {
+	if (refl > 0) Reflection.Objects[id].reflect = 1;
+	else Reflection.Objects[id].reflect = 0;
+}
+
+int GetCharacterReflected(int id) {
+	return Reflection.Characters[id].reflect;
+}
+
+void GetObjectReflected(int id) {
+	Reflection.Objects[id].reflect;
+}
+
+void ReplaceCharacterReflectionView(int id, int view) {
+	Reflection.Characters[id].replaceview = view - 1;
+}
+
+void SetObjectReflectionIgnoreScaling(int id, int wb) {
+	if (wb) Reflection.Objects[id].ignorescaling = 1;
+	else    Reflection.Objects[id].ignorescaling = 0;
+}
+
+int DrawReflections(int id, int charobj = 0) {
+	int32 screenw, screenh;
+	int32 bgw, bgh;
+	engine->GetScreenDimensions(&screenw, &screenh, nullptr);
+	BITMAP *bgmask = engine->GetBackgroundScene(1);
+	if (bgmask == nullptr) return 1;
+	//BITMAP *virtsc = engine->GetVirtualScreen();
+	BITMAP *walkbehind = engine->GetRoomMask(MASK_WALKBEHIND);
+	//if (!virtsc) engine->AbortGame ("Can't load virtual screen.");
+	if (!walkbehind) engine->AbortGame("DrawRelfections: Can't load Walkbehind into memory.");
+	engine->GetBitmapDimensions(walkbehind, &bgw, &bgh, nullptr);
+	if (!bgmask) engine->AbortGame("DrawReflections: Can't load reflection mask.");
+	//unsigned char **charbuffer = engine->GetRawBitmapSurface (virtsc);
+	unsigned char **wbarray = engine->GetRawBitmapSurface(walkbehind);
+	unsigned char **maskarray = engine->GetRawBitmapSurface(bgmask);
+	//Initialize stuff
+	BITMAP *charsprite = nullptr;
+	BITMAP *charsprite2 = nullptr;
+	AGSCharacter *currchar;
+	AGSObject *currobj;
+	int cox, coy, coz = 0;
+	int scale = 0;
+	//Get character, and their sprite.
+	if (charobj == 0) {
+		currchar = engine->GetCharacter(id);
+		int view = 0;
+		if (Reflection.Characters[id].replaceview == 0) view = currchar->view + 1;
+		else view = Reflection.Characters[id].replaceview;
+		AGSViewFrame *vf = engine->GetViewFrame(currchar->view + 1, currchar->loop, currchar->frame);
+		charsprite = engine->GetSpriteGraphic(vf->pic);
+		long scaling = currchar->flags & CHF_NOSCALING;
+		if (!scaling)scale = engine->GetAreaScaling(currchar->x, currchar->y);
+		else scale = 100;
+		cox = currchar->x;
+		coy = currchar->y;
+		coz = currchar->z;
+	} else if (charobj == 1) {
+		currobj = engine->GetObject(id);
+
+		charsprite = engine->GetSpriteGraphic(currobj->num);
+		if (Reflection.Objects[id].ignorescaling) scale = 100;
+		else scale = engine->GetAreaScaling(currobj->x, currobj->y);
+		cox = currobj->x;
+		if (currobj->baseline < 0) coy = currobj->y;
+		else coy = currobj->baseline;
+		coz = 0;
+	}
+	bool scaled = false;
+	int32 w, h;
+	engine->GetBitmapDimensions(charsprite, &w, &h, nullptr);
+	if (scale != 100) {
+		unsigned char **orig = engine->GetRawBitmapSurface(charsprite);
+		int h1, h2, w1, w2;
+		double fw2, fh2;
+		h1 = h;
+		w1 = w;
+		fh2 = h1 * ((double)scale / 100.0);
+		fw2 = w1 * ((double)scale / 100.0);
+		h2 = static_cast<int>(fh2);
+		w2 = static_cast<int>(fw2);
+		charsprite2 = engine->CreateBlankBitmap(w2, h2, 8);
+		unsigned char **resized = engine->GetRawBitmapSurface(charsprite2);
+		int x_ratio = (int)((w1 << 16) / w2) + 1;
+		int y_ratio = (int)((h1 << 16) / h2) + 1;
+		int x2, y2 ;
+		for (int i = 0; i < h2; i++) {
+			for (int j = 0; j < w2; j++) {
+				x2 = ((j * x_ratio) >> 16) ;
+				y2 = ((i * y_ratio) >> 16) ;
+				resized [i][j] = orig [y2][x2];
+			}
+		}
+		engine->ReleaseBitmapSurface(charsprite2);
+		scaled = true;
+		w = w2;
+		h = h2;
+	} else {
+		charsprite2 = charsprite;
+	}
+	int transamount = 0;
+	unsigned char **spritearray = engine->GetRawBitmapSurface(charsprite2);
+	unsigned char **charbuffer = engine->GetRawBitmapSurface(rcolormap);
+	unsigned char **alphaarray = engine->GetRawBitmapSurface(ralphamap);
+	int i = h - 1, j = 0;
+	int32 ox = cox;
+	if (charobj == 0) ox = ox - (w / 2);
+	int32 oy = coy + coz - 1;
+	engine->RoomToViewport(&ox, &oy);
+	int yoffset = 0;
+	int translevel = 7;
+	bool dither = false;
+	bool dodither = false;
+	int counter = 0;
+	int rowcount = 101 - (int)(50.0 * ((double)(scale) / 100.0));
+	int delay = screenh / rowcount;
+	int *obst;
+	int flipped = 0;
+	if (charobj == 0) {
+		int (*sfGetGameParameter)(int, int, int, int);
+		sfGetGameParameter = ((int(*)(int, int, int, int)) engine->GetScriptFunctionAddress("GetGameParameter"));
+		flipped = sfGetGameParameter(13, currchar->view + 1, currchar->loop, currchar->frame);
+	} else flipped = 0;
+	obst = new int [w];
+	for (int k = 0; k < w; k++) {
+		obst[k] = 0;
+	}
+	while (i > 0) {
+		//if ((counter == delay/2-1 || counter == delay-1) && yoffset < 36) dodither = (!dodither);
+		if (counter == delay) {
+			counter = 0;
+			if (translevel > 0) translevel--;
+		} else counter++;
+		yoffset++;
+		while (j < w) {
+			int xoffset;
+			if (flipped == 1) xoffset = w - j - 1;
+			else xoffset = j;
+			int32 rx = ox + xoffset, ry = oy + yoffset;
+			int wbb = 0;
+			engine->ViewportToRoom(&rx, &ry);
+			if (ry > 0 && ry < bgh && rx > 0 && rx < bgw) {
+				if (wbarray [ry][rx] > 0) {
+					wbb = engine->GetWalkbehindBaseline(wbarray[ry][rx]);
+				}
+				if (maskarray[ry][rx] == 21) obst[j] = 1;
+			}
+
+			//dither = (!dither);
+			transamount = 32 * translevel;
+			if (spritearray [i][j] != 0 && oy + yoffset < screenh && ox + xoffset < screenw && oy + yoffset >= 0 && ox + xoffset >= 0) { // If the sprite isn't transparent, and isn't drawn off the edge of the bg.
+				if (wbb < ry && obst[j] == 0 && (oy > reflectionmap[(ox + xoffset) + (screenw * (oy + yoffset))])) {
+					//charbuffer[oy+yoffset][ox+xoffset] = MixColorAlpha (spritearray [i][j],charbuffer[oy+yoffset][ox+xoffset],transamount);
+					charbuffer [oy + yoffset][ox + xoffset] = spritearray [i][j];
+					alphaarray [oy + yoffset][ox + xoffset] = transamount;
+					reflectionmap[(ox + xoffset) + (screenw * (oy + yoffset))] = oy;
+				}
+			}
+			j++;
+		}
+		//if (w % 2 == 0) dither = (!dither);
+		i--;
+		j = 0;
+	}
+
+	delete [] obst;
+	if (scaled == true)engine->FreeBitmap(charsprite2);
+	engine->ReleaseBitmapSurface(charsprite);
+	//engine->ReleaseBitmapSurface (virtsc);
+	//engine->ReleaseBitmapSurface (clutspr);
+	engine->ReleaseBitmapSurface(bgmask);
+	engine->ReleaseBitmapSurface(walkbehind);
+	engine->ReleaseBitmapSurface(rcolormap);
+	engine->ReleaseBitmapSurface(ralphamap);
+	engine->MarkRegionDirty(ox, oy, ox + w, oy + h);
+	return 0;
+}
+
+
+int DrawTransSprite(int sprite, int bg, int translevel, int mask = 0, int blendmode = 0, int use_objpal = 0) {
+	BITMAP *maskspr = nullptr;
+	unsigned char **maskarray;
+	if (mask > 0) maskspr = engine->GetSpriteGraphic(mask);
+	if (!maskspr && mask > 0) {
+		char maskerr [100];
+		int cx;
+		cx = snprintf(maskerr, 100, "DrawTransSprite: Can't load mask from slot %d.", mask);
+		engine->AbortGame(maskerr);
+	}
+	// Get a reference to the screen we'll draw onto
+	BITMAP *bgspr = engine->GetSpriteGraphic(bg);
+	//BITMAP *clutspr = engine->GetSpriteGraphic (clutslot);
+	BITMAP *spritespr = engine->GetSpriteGraphic(sprite);
+	if (!bgspr) engine->AbortGame("DrawTransSprite: Can't load background");
+	//if (!clutspr) engine->AbortGame ("Can't load CLUT sprite into memory.");
+	if (!spritespr) engine->AbortGame("DrawTransSprite: Can't load overlay sprite into memory.");
+	// Get its surface
+	int32 sprw, sprh, coldepth;
+	int32 bgw, bgh;
+	engine->GetBitmapDimensions(bgspr, &bgw, &bgh, &coldepth);
+	engine->GetBitmapDimensions(spritespr, &sprw, &sprh, &coldepth);
+
+	unsigned char **bgarray = engine->GetRawBitmapSurface(bgspr);
+	//unsigned char **clutarray = engine->GetRawBitmapSurface (clutspr);
+	unsigned char **spritearray = engine->GetRawBitmapSurface(spritespr);
+	if (mask > 0) maskarray = engine->GetRawBitmapSurface(maskspr);
+	int tloffset = 255 - translevel;
+	int x = 0;
+	int y = 0;
+	//int transamount = 256 * translevel; //old
+	while (y < sprh) {
+		while (x < sprw) {
+			if (spritearray [y][x] != 0 && y < bgh && x < bgw && y >= 0 && x >= 0) { // If the sprite isn't transparent, and isn't drawn off the edge of the bg.
+				if (mask > 0) {
+					translevel = std::max(maskarray [y][x] - tloffset, 0);
+				}
+				//spritearray[y][x] = cycle_remap[clutarray [cycle_remap[bgarray[y][x]]+transamount][cycle_remap[spritearray [y][x]]]]; //old
+				if (blendmode == 0) spritearray[y][x] = Mix::MixColorAlpha(spritearray [y][x], bgarray[y][x], translevel, use_objpal);
+				else if (blendmode == 1) spritearray[y][x] = Mix::MixColorAdditive(spritearray [y][x], bgarray[y][x], translevel, use_objpal);
+			}
+			x++;
+		}
+		x = 0;
+		y++;
+	}
+
+	// Release the screen so that the engine can continue
+	engine->ReleaseBitmapSurface(bgspr);
+	//engine->ReleaseBitmapSurface (clutspr);
+	engine->ReleaseBitmapSurface(spritespr);
+	engine->NotifySpriteUpdated(sprite);
+	return 0;
+}
+
+int DrawTranslucentOverlay(int sprite, int translevel, int ox, int oy, int mask = 0, int blendmode = 0) {
+	if (translevel == 0) return 0;
+	BITMAP *maskspr;
+	unsigned char **maskarray;
+	// Get a reference to the screen we'll draw onto
+	BITMAP *virtsc = engine->GetVirtualScreen();
+	//BITMAP *clutspr = engine->GetSpriteGraphic (clutslot);
+	BITMAP *spritespr = engine->GetSpriteGraphic(sprite);
+	if (mask > 0) maskspr = engine->GetSpriteGraphic(mask);
+	if (!virtsc) engine->AbortGame("DrawTranslucentOverlay: Can't load virtual screen.");
+	//if (!clutspr) engine->AbortGame ("Can't load CLUT sprite into memory.");
+	if (!spritespr) engine->AbortGame("DrawTranslucentOverlay: Can't load overlay sprite into memory.");
+	// Get its surface
+	int32 sprw, sprh, coldepth;
+	int32 screenw, screenh;
+	engine->GetScreenDimensions(&screenw, &screenh, &coldepth);
+	engine->GetBitmapDimensions(spritespr, &sprw, &sprh, &coldepth);
+	unsigned char **charbuffer = engine->GetRawBitmapSurface(virtsc);
+	unsigned char **spritearray = engine->GetRawBitmapSurface(spritespr);
+	if (mask > 0) {
+		if (!maskspr && mask > 0) {
+			char maskerr [100];
+			snprintf(maskerr, 100, "DrawTransSprite: Can't load mask from slot %d.", mask);
+			engine->AbortGame(maskerr);
+		}
+		maskarray = engine->GetRawBitmapSurface(maskspr);
+	}
+	int tloffset = 255 - translevel;
+	int x = 0;
+	int y = 0;
+	//int transamount = 256 * translevel; //old
+	while (y < sprh) {
+		while (x < sprw) {
+			if (spritearray [y][x] != 0 && y + oy < screenh && x + ox < screenw && y + oy >= 0 && x + ox >= 0) { // If the sprite isn't transparent, and isn't drawn off the edge of the screen.
+				//charbuffer[y+oy][x+ox] = cycle_remap[clutarray [cycle_remap[charbuffer[y+oy][x+ox]]+transamount][cycle_remap[spritearray [y][x]]]]; //old
+				if (mask > 0) {
+					translevel = std::max(maskarray [y][x] - tloffset, 0);
+				}
+				if (blendmode == 0) {
+					if (translevel == 255) {
+						charbuffer[y + oy][x + ox] = spritearray [y][x];
+					} else charbuffer[y + oy][x + ox] = Mix::MixColorAlpha(spritearray [y][x], charbuffer[y + oy][x + ox], translevel);
+				} else if (blendmode == 1) charbuffer[y + oy][x + ox] = Mix::MixColorAdditive(spritearray [y][x], charbuffer[y + oy][x + ox], translevel);
+			}
+			x++;
+		}
+		x = 0;
+		y++;
+	}
+
+	// Release the screen so that the engine can continue
+	long dirtywidth = ox + sprw;
+	if (dirtywidth > screenw) dirtywidth = screenw - 1;
+	long dirtyheight = oy + sprh;
+	if (dirtyheight > screenh) dirtywidth = screenh - 1;
+	engine->ReleaseBitmapSurface(virtsc);
+	//engine->ReleaseBitmapSurface (clutspr);
+	engine->ReleaseBitmapSurface(spritespr);
+	if (mask > 0) engine->ReleaseBitmapSurface(maskspr);
+	engine->MarkRegionDirty(ox, oy, dirtywidth, dirtyheight);
+	return 0;
+}
+
+void AGS_EngineStartup(IAGSEngine *lpEngine) {
+	engine = lpEngine;
+
+	// Make sure it's got the version with the features we need
+	if (engine->version < 3) {
+		engine->AbortGame("Engine interface is too old, need newer version of AGS.");
+	}
+	engine->RegisterScriptFunction("PALInternal::LoadCLUT^1", (void *)LoadCLUT);
+	engine->RegisterScriptFunction("PALInternal::CycleRemap^2", (void *)CycleRemap);
+	engine->RegisterScriptFunction("PALInternal::GetColor565^3", (void *)GetColor565);
+	engine->RegisterScriptFunction("PALInternal::GetLuminosityFromPalette^1", (void *)GetLuminosityFromPalette);
+	engine->RegisterScriptFunction("PALInternal::FastSin^1", (void *)AGSFastSin);
+	engine->RegisterScriptFunction("PALInternal::FastCos^1", (void *)AGSFastCos);
+	engine->RegisterScriptFunction("PALInternal::FastRoot^1", (void *)root);
+	engine->RegisterScriptFunction("PALInternal::GetRemappedSlot^1", (void *)GetRemappedSlot);
+	engine->RegisterScriptFunction("PALInternal::ResetRemapping^0", (void *)ResetRemapping);
+	engine->RegisterScriptFunction("PALInternal::GetModifiedBackgroundImage", (void *)GetModifiedBackgroundImage);
+	engine->RegisterScriptFunction("PALInternal::WriteObjectivePalette^4", (void *)WriteObjectivePalette);
+	engine->RegisterScriptFunction("PALInternal::ReadObjectivePaletteR^1", (void *)ReadObjectivePaletteR);
+	engine->RegisterScriptFunction("PALInternal::ReadObjectivePaletteB^1", (void *)ReadObjectivePaletteB);
+	engine->RegisterScriptFunction("PALInternal::ReadObjectivePaletteG^1", (void *)ReadObjectivePaletteG);
+
+	engine->RegisterScriptFunction("Raycast::Render^1", (void *)Raycast_Render);
+	engine->RegisterScriptFunction("Raycast::LoadMap^4", (void *)LoadMap);
+	engine->RegisterScriptFunction("Raycast::Initialize", (void *)Init_Raycaster);
+	engine->RegisterScriptFunction("Raycast::MakeTextures^1", (void *)MakeTextures);
+	engine->RegisterScriptFunction("Raycast::MoveForward^0", (void *)MoveForward);
+	engine->RegisterScriptFunction("Raycast::MoveBackward^0", (void *)MoveBackward);
+	engine->RegisterScriptFunction("Raycast::RotateLeft^0", (void *)RotateLeft);
+	engine->RegisterScriptFunction("Raycast::RotateRight^0", (void *)RotateRight);
+	engine->RegisterScriptFunction("Raycast::SetCameraPosition^2", (void *)Ray_SetPlayerPosition);
+	engine->RegisterScriptFunction("Raycast::GetCameraX^0", (void *)Ray_GetPlayerX);
+	engine->RegisterScriptFunction("Raycast::GetCameraY^0", (void *)Ray_GetPlayerY);
+	engine->RegisterScriptFunction("Raycast::GetCameraAngle^0", (void *)Ray_GetPlayerAngle);
+	engine->RegisterScriptFunction("Raycast::SetCameraAngle^1", (void *)Ray_SetPlayerAngle);
+	engine->RegisterScriptFunction("Raycast::InitSprite^9", (void *)Ray_InitSprite);
+	engine->RegisterScriptFunction("Raycast::UnloadEngine^0", (void *)QuitCleanup);
+	engine->RegisterScriptFunction("Raycast::GetHotspotAtXY^2", (void *)Ray_GetHotspotAt);
+	engine->RegisterScriptFunction("Raycast::GetObjectAtXY^2", (void *)Ray_GetObjectAt);
+	engine->RegisterScriptFunction("Raycast::SetSpriteInteractObj^2", (void *)Ray_SetSpriteInteractObj);
+	engine->RegisterScriptFunction("Raycast::GetSpriteInteractObj^1", (void *)Ray_GetSpriteInteractObj);
+	engine->RegisterScriptFunction("Raycast::SetSpritePosition^3", (void *)Ray_SetSpritePosition);
+	engine->RegisterScriptFunction("Raycast::SetSpriteVertOffset^2", (void *)Ray_SetSpriteVertOffset);
+	engine->RegisterScriptFunction("Raycast::GetSpriteVertOffset^1", (void *)Ray_GetSpriteVertOffset);
+	engine->RegisterScriptFunction("Raycast::GetSpriteX^1", (void *)Ray_GetSpriteX);
+	engine->RegisterScriptFunction("Raycast::GetSpriteY^1", (void *)Ray_GetSpriteY);
+	engine->RegisterScriptFunction("Raycast::SetWallHotspot^2", (void *)Ray_SetWallHotspot);
+	engine->RegisterScriptFunction("Raycast::SetWallTextures^5", (void *)Ray_SetWallTextures);
+	engine->RegisterScriptFunction("Raycast::SetWallSolid^5", (void *)Ray_SetWallSolid);
+	engine->RegisterScriptFunction("Raycast::SetWallIgnoreLighting^5", (void *)Ray_SetWallIgnoreLighting);
+	engine->RegisterScriptFunction("Raycast::SetWallAlpha^5", (void *)Ray_SetWallAlpha);
+	engine->RegisterScriptFunction("Raycast::SetWallBlendType^5", (void *)Ray_SetWallBlendType);
+	engine->RegisterScriptFunction("Raycast::GetMoveSpeed^0", (void *)Ray_GetMoveSpeed);
+	engine->RegisterScriptFunction("Raycast::SetMoveSpeed^1", (void *)Ray_SetMoveSpeed);
+	engine->RegisterScriptFunction("Raycast::GetRotSpeed^0", (void *)Ray_GetRotSpeed);
+	engine->RegisterScriptFunction("Raycast::SetRotSpeed^1", (void *)Ray_SetRotSpeed);
+	engine->RegisterScriptFunction("Raycast::GetWallAt^2", (void *)Ray_GetWallAt);
+	engine->RegisterScriptFunction("Raycast::GetLightAt^2", (void *)Ray_GetLightAt);
+	engine->RegisterScriptFunction("Raycast::SetLightAt^3", (void *)Ray_SetLightAt);
+	engine->RegisterScriptFunction("Raycast::SetWallAt^3", (void *)Ray_SetWallAt);
+	engine->RegisterScriptFunction("Raycast::SetPlaneY^1", (void *)Ray_SetPlaneY);
+	engine->RegisterScriptFunction("Raycast::GetDistanceAt^2", (void *)Ray_GetDistanceAt);
+	engine->RegisterScriptFunction("Raycast::GetSpriteAngle^1", (void *)Ray_GetSpriteAngle);
+	engine->RegisterScriptFunction("Raycast::SetSpriteAngle^2", (void *)Ray_SetSpriteAngle);
+	engine->RegisterScriptFunction("Raycast::SetSpriteView^2", (void *)Ray_SetSpriteView);
+	engine->RegisterScriptFunction("Raycast::GetSpriteView^1", (void *)Ray_GetSpriteView);
+	engine->RegisterScriptFunction("Raycast::SetSpriteFrame^2", (void *)Ray_SetSpriteFrame);
+	engine->RegisterScriptFunction("Raycast::GetSpriteFrame^1", (void *)Ray_GetSpriteFrame);
+	engine->RegisterScriptFunction("Raycast::SetSpritePic^2", (void *)Ray_SetSpritePic);
+	engine->RegisterScriptFunction("Raycast::GetSpritePic^1", (void *)Ray_GetSpritePic);
+	engine->RegisterScriptFunction("Raycast::SetSkyBox^1", (void *)Ray_SetSkyBox);
+	engine->RegisterScriptFunction("Raycast::SetSpriteAlpha^2", (void *)Ray_SetSpriteAlpha);
+	engine->RegisterScriptFunction("Raycast::GetSpriteAlpha^1", (void *)Ray_GetSpriteAlpha);
+	engine->RegisterScriptFunction("Raycast::GetSkyBox^1", (void *)Ray_GetSkyBox);
+	engine->RegisterScriptFunction("Raycast::SetAmbientLight^1", (void *)Ray_SetAmbientLight);
+	engine->RegisterScriptFunction("Raycast::SetAmbientColor^2", (void *)Ray_SetAmbientColor);
+	engine->RegisterScriptFunction("Raycast::GetAmbientLight^0", (void *)Ray_GetAmbientLight);
+	engine->RegisterScriptFunction("Raycast::GetAmbientWeight^0", (void *)Ray_GetAmbientWeight);
+	engine->RegisterScriptFunction("Raycast::GetTileX_At^2", (void *)Ray_GetTileX_At);
+	engine->RegisterScriptFunction("Raycast::GetTileY_At^2", (void *)Ray_GetTileY_At);
+	engine->RegisterScriptFunction("Raycast::DrawTile^2", (void *)Ray_DrawTile);
+	engine->RegisterScriptFunction("Raycast::DrawOntoTile^2", (void *)Ray_DrawOntoTile);
+	engine->RegisterScriptFunction("Raycast::SetNoClip^1", (void *)Ray_SetNoClip);
+	engine->RegisterScriptFunction("Raycast::GetNoClip^0", (void *)Ray_GetNoClip);
+	engine->RegisterScriptFunction("Raycast::GetSpriteScaleX^1", (void *)Ray_GetSpriteScaleX);
+	engine->RegisterScriptFunction("Raycast::SetSpriteScaleX^2", (void *)Ray_SetSpriteScaleX);
+	engine->RegisterScriptFunction("Raycast::GetSpriteScaleY^1", (void *)Ray_GetSpriteScaleY);
+	engine->RegisterScriptFunction("Raycast::SetSpriteScaleY^2", (void *)Ray_SetSpriteScaleY);
+	engine->RegisterScriptFunction("Raycast::GetSpriteBlendType^1", (void *)Ray_GetSpriteBlendType);
+	engine->RegisterScriptFunction("Raycast::SetSpriteBlendType^2", (void *)Ray_SetSpriteBlendType);
+
+
+	engine->RegisterScriptFunction("Raycast::SetFloorAt^3", (void *)Ray_SetFloorAt);
+	engine->RegisterScriptFunction("Raycast::SetCeilingAt^3", (void *)Ray_SetCeilingAt);
+	engine->RegisterScriptFunction("Raycast::GetCeilingAt^2", (void *)Ray_GetCeilingAt);
+	engine->RegisterScriptFunction("Raycast::GetFloorAt^2", (void *)Ray_GetFloorAt);
+	engine->RegisterScriptFunction("Raycast::GetLightingAt^2", (void *)Ray_GetLightingAt);
+	engine->RegisterScriptFunction("Raycast::SetLightingAt^3", (void *)Ray_SetLightingAt);
+	engine->RegisterScriptFunction("Raycast::GetWallHotspot^1", (void *)Ray_GetWallHotspot);
+	engine->RegisterScriptFunction("Raycast::GetWallTexture^2", (void *)Ray_GetWallTexture);
+	engine->RegisterScriptFunction("Raycast::GetWallSolid^2", (void *)Ray_GetWallSolid);
+	engine->RegisterScriptFunction("Raycast::GetWallIgnoreLighting^2", (void *)Ray_GetWallIgnoreLighting);
+	engine->RegisterScriptFunction("Raycast::GetWallAlpha^2", (void *)Ray_GetWallAlpha);
+	engine->RegisterScriptFunction("Raycast::GetWallBlendType^2", (void *)Ray_GetWallBlendType);
+	engine->RegisterScriptFunction("Raycast::SelectTile^3", (void *)Ray_SelectTile);
+	engine->RegisterScriptFunction("Raycast::HasSeenTile^2", (void *)Ray_HasSeenTile);
+
+	engine->RegisterScriptFunction("LensDistort::SetPos^2", (void *)SetLensPos);
+	engine->RegisterScriptFunction("LensDistort::GetX^0", (void *)GetLensX);
+	engine->RegisterScriptFunction("LensDistort::GetY^0", (void *)GetLensY);
+	engine->RegisterScriptFunction("LensDistort::Set^1", (void *)SetLensDrawn);
+	engine->RegisterScriptFunction("LensDistort::IsDrawn^0", (void *)GetLensDrawn);
+	engine->RegisterScriptFunction("LensDistort::SetOffsetClamp^1", (void *)SetLensOffsetClamp);
+	engine->RegisterScriptFunction("LensDistort::GetOffsetClamp^0", (void *)GetLensOffsetClamp);
+	engine->RegisterScriptFunction("LensDistort::GetLevel^0", (void *)GetLensLevel);
+	engine->RegisterScriptFunction("LensDistort::SetLevel^1", (void *)GetLensLevel);
+	engine->RegisterScriptFunction("LensDistort::Initialize^6", (void *)LensInitialize);
+
+	engine->RegisterScriptFunction("Translucence::CreateOverlay^8", (void *)CreateTranslucentOverlay);
+	engine->RegisterScriptFunction("Translucence::DeleteOverlay^1", (void *)DeleteTranslucentOverlay);
+	engine->RegisterScriptFunction("Translucence::Move^3", (void *)MoveTranslucentOverlay);
+	engine->RegisterScriptFunction("Translucence::GetOverlayX^1", (void *)GetTranslucentOverlayX);
+	engine->RegisterScriptFunction("Translucence::GetOverlayY^1", (void *)GetTranslucentOverlayY);
+	engine->RegisterScriptFunction("Translucence::GetOverlaySprite^1", (void *)GetTranslucentOverlaySprite);
+	engine->RegisterScriptFunction("Translucence::GetOverlayLevel^1", (void *)GetTranslucentOverlayLevel);
+	engine->RegisterScriptFunction("Translucence::GetOverlayEnabled^1", (void *)GetTranslucentOverlayEnabled);
+	engine->RegisterScriptFunction("Translucence::GetOverlayAlpha^1", (void *)GetTranslucentOverlayAlpha);
+	engine->RegisterScriptFunction("Translucence::SetOverlayAlpha^2", (void *)SetTranslucentOverlayAlpha);
+	engine->RegisterScriptFunction("Translucence::SetOverlayEnabled^2", (void *)SetTranslucentOverlayEnabled);
+	engine->RegisterScriptFunction("Translucence::DrawTransSprite^6", (void *)DrawTransSprite);
+
+	engine->RegisterScriptFunction("Starfield::GetOverscan^0", (void *)GetStarfieldOverscan);
+	engine->RegisterScriptFunction("Starfield::SetOverscan^1", (void *)SetStarfieldOverscan);
+	engine->RegisterScriptFunction("Starfield::GetOriginX^0", (void *)GetStarfieldOriginX);
+	engine->RegisterScriptFunction("Starfield::GetOriginY^0", (void *)GetStarfieldOriginY);
+	engine->RegisterScriptFunction("Starfield::SetDepthMultiplier^1", (void *)SetStarfieldDepthMultiplier);
+	engine->RegisterScriptFunction("Starfield::GetDepthMultiplier^0", (void *)GetStarfieldDepthMultiplier);
+	engine->RegisterScriptFunction("Starfield::GetMaxStars^0", (void *)GetStarfieldMaxStars);
+	engine->RegisterScriptFunction("Starfield::SetStarSpriteScaleBoost^1", (void *)SetStarSpriteScaleBoost);
+	engine->RegisterScriptFunction("Starfield::GetStarSpriteScaleBoost^0", (void *)GetStarSpriteScaleBoost);
+	engine->RegisterScriptFunction("Starfield::SetStarMaxRadius^2", (void *)SetStarMaxRadius);
+	engine->RegisterScriptFunction("Starfield::GetStarMaxRadius^0", (void *)GetStarMaxRadius);
+	engine->RegisterScriptFunction("Starfield::GetStarX^1", (void *)GetStarX);
+	engine->RegisterScriptFunction("Starfield::GetStarY^1", (void *)GetStarY);
+	engine->RegisterScriptFunction("Starfield::GetStarZ^1", (void *)GetStarZ);
+	engine->RegisterScriptFunction("Starfield::SetStarPosition^4", (void *)SetStarPosition);
+	engine->RegisterScriptFunction("Starfield::RotateStar^4", (void *)RotateStar);
+	engine->RegisterScriptFunction("Starfield::SetStarColor^2", (void *)SetStarColor);
+	engine->RegisterScriptFunction("Starfield::GetStarColor^1", (void *)GetStarColor);
+	engine->RegisterScriptFunction("Starfield::SetStarSprite^2", (void *)SetStarSprite);
+	engine->RegisterScriptFunction("Starfield::GetStarSprite^1", (void *)GetStarSprite);
+	engine->RegisterScriptFunction("Starfield::SetStarSpriteRange^3", (void *)SetStarSpriteRange);
+	engine->RegisterScriptFunction("Starfield::Initialize^2", (void *)InitializeStars);
+	engine->RegisterScriptFunction("Starfield::Iterate^1", (void *)IterateStars);
+	engine->RegisterScriptFunction("Starfield::Draw^2", (void *)DrawStars);
+	engine->RegisterScriptFunction("Starfield::SetOriginPoint^2", (void *)SetStarsOriginPoint);
+
+	engine->RegisterScriptFunction("Plasma::DoFire^8", (void *)DoFire);
+	engine->RegisterScriptFunction("Plasma::SetPlasmaType^5", (void *)SetPlasmaType);
+	engine->RegisterScriptFunction("Plasma::ResetPlasmaSettings^0", (void *)ResetPlasmaSettings);
+	engine->RegisterScriptFunction("Plasma::DrawPlasma^3", (void *)DrawPlasma);
+	engine->RegisterScriptFunction("Plasma::SetRootType^1", (void *)SetPlasmaRootType);
+	engine->RegisterScriptFunction("Plasma::GetRootType^0", (void *)GetPlasmaRootType);
+
+	engine->RegisterScriptFunction("Reflections::Set^1", (void *)SetReflections);
+	engine->RegisterScriptFunction("Reflections::IsReflecting^0", (void *)IsReflectionsOn);
+	engine->RegisterScriptFunction("Reflections::SetCharacterReflected^2", (void *)SetCharacterReflected);
+	engine->RegisterScriptFunction("Reflections::GetCharacterReflected^1", (void *)GetCharacterReflected);
+	engine->RegisterScriptFunction("Reflections::SetObjectReflected^2", (void *)SetObjectReflected);
+	engine->RegisterScriptFunction("Reflections::GetObjectReflected^1", (void *)GetObjectReflected);
+	engine->RegisterScriptFunction("Reflections::ReplaceCharacterReflectionView^2", (void *)ReplaceCharacterReflectionView);
+	engine->RegisterScriptFunction("Reflections::SetObjectReflectionIgnoreScaling^2", (void *)SetObjectReflectionIgnoreScaling);
+	engine->RequestEventHook(AGSE_PRESCREENDRAW);
+	engine->RequestEventHook(AGSE_PREGUIDRAW);
+	engine->RequestEventHook(AGSE_POSTSCREENDRAW);
+	engine->RequestEventHook(AGSE_SAVEGAME);
+	engine->RequestEventHook(AGSE_RESTOREGAME);
+	engine->RequestEventHook(AGSE_ENTERROOM);
+	stars = new starstype [MAX_STARS];
+	Starfield.maxstars = MAX_STARS;
+	Starfield.depthmultiplier = 256;
+	Starfield.speed = 0.5;
+	Starfield.originx = 160;
+	Starfield.originy = 100;
+	Reflection.Characters = new charrefopt [engine->GetNumCharacters()]();
+	lens = new LensDistort [LENS_WIDTH * LENS_WIDTH]();
+	//PreMultiply_Alphas ();
+	plasmaroottype = 0;
+	Make_Sin_Lut();
+	Init_Raycaster();
+}
+
+void AGS_EngineShutdown() {
+	// no work to do here - but if we had created any dynamic sprites,
+	// we should delete them here
+	delete [] Reflection.Characters;
+	delete [] Reflection.Objects;
+	//QuitCleanup ();
+}
+
+
+int AGS_EngineOnEvent(int event, int data) {
+	if (event == AGSE_PRESCREENDRAW && clutslot > 0) {
+		if (drawreflections) {
+			int32 sh, sw = 0;
+			engine->GetScreenDimensions(&sw, &sh, nullptr);
+			reflectionmap = new long[sw * sh]();
+			rcolormap = engine->CreateBlankBitmap(sw, sh, 8);
+			ralphamap = engine->CreateBlankBitmap(sw, sh, 8);
+			for (int i = 0; i < engine->GetNumCharacters(); i++) {
+				if (Reflection.Characters[i].reflect == 0) continue;
+				AGSCharacter *tempchar = engine->GetCharacter(i);
+				if (tempchar->room != engine->GetCurrentRoom()) continue;  //if character isn't even in the room, go to next iteration.
+				int32 vx = tempchar->x;
+				int32 vy = tempchar->y;
+				engine->RoomToViewport(&vx, &vy);
+				AGSViewFrame *vf = engine->GetViewFrame(tempchar->view + 1, tempchar->loop, tempchar->frame);
+				int w = engine->GetSpriteWidth(vf->pic);
+				int h = engine->GetSpriteHeight(vf->pic);
+				vx = vx - (w / 2);
+				int32 vxmax = vx + w;
+				int32 vymax = vy + h;
+				if (vxmax < 0 || vy > sh || vx > sw || vymax < 0) continue; //if all of the sprite is off screen in any direction, go to next iteration
+				DrawReflections(i, 0);
+			}
+			for (int i = 0; i < engine->GetNumObjects(); i++) {
+				if (Reflection.Objects[i].reflect == 0) continue;
+				AGSObject *tempobj = engine->GetObject(i);
+				if (!tempobj->on) continue;
+				int32 vx = tempobj->x;
+				int32 vy = tempobj->baseline - tempobj->y;
+				engine->RoomToViewport(&vx, &vy);
+				int32 w = engine->GetSpriteWidth(tempobj->num);
+				int32 h = engine->GetSpriteHeight(tempobj->num);
+				int32 vxmax = vx + w;
+				int32 vymax = vy + h;
+				if (vxmax < 0 || vy > sh || vx > sw || vymax < 0) continue; //if all of the sprite is off screen in any direction, go to next iteration
+				DrawReflections(i, 1);
+			}
+			BITMAP *virtsc = engine->GetVirtualScreen();
+			unsigned char **screenbuffer = engine->GetRawBitmapSurface(virtsc);
+			unsigned char **colorbuffer = engine->GetRawBitmapSurface(rcolormap);
+			unsigned char **alphabuffer = engine->GetRawBitmapSurface(ralphamap);
+			for (int y = 0; y < sh; y++)
+				for (int x = 0; x < sw; x++)
+					screenbuffer[y][x] = Mix::MixColorAlpha(colorbuffer[y][x], screenbuffer[y][x], alphabuffer[y][x]);
+			engine->ReleaseBitmapSurface(rcolormap);
+			engine->ReleaseBitmapSurface(ralphamap);
+			engine->ReleaseBitmapSurface(virtsc);
+			engine->FreeBitmap(rcolormap);
+			engine->FreeBitmap(ralphamap);
+			delete [] reflectionmap;
+		}
+		int i = 0;
+		if (LensOption.draw == 1 && LensOption.level == 0) DrawLens(LensOption.x, LensOption.y);
+		while (i < MAX_OVERLAYS) {
+			if (overlay[i].enabled && overlay[i].level == 0) {
+				DrawTranslucentOverlay(overlay[i].sprite, overlay[i].trans, overlay[i].x, overlay[i].y, overlay[i].spritemask, overlay[i].blendtype);
+			}
+			i++;
+		}
+		if (LensOption.draw == 1 && LensOption.level == 1) DrawLens(LensOption.x, LensOption.y);
+	}
+	if (event == AGSE_PREGUIDRAW && clutslot > 0) {
+		int i = 0;
+		if (LensOption.draw == 1 && LensOption.level == 1) DrawLens(LensOption.x, LensOption.y);
+		while (i < MAX_OVERLAYS) {
+			if (overlay[i].enabled && overlay[i].level == 1) {
+				DrawTranslucentOverlay(overlay[i].sprite, overlay[i].trans, overlay[i].x, overlay[i].y, overlay[i].spritemask, overlay[i].blendtype);
+			}
+			i++;
+		}
+		if (LensOption.draw == 1 && LensOption.level == 2) DrawLens(LensOption.x, LensOption.y);
+	}
+	if (event == AGSE_POSTSCREENDRAW && clutslot > 0) {
+		int i = 0;
+		if (LensOption.draw == 1 && LensOption.level == 3) DrawLens(LensOption.x, LensOption.y);
+		while (i < MAX_OVERLAYS) {
+			if (overlay[i].enabled && overlay[i].level == 2) {
+				DrawTranslucentOverlay(overlay[i].sprite, overlay[i].trans, overlay[i].x, overlay[i].y, overlay[i].spritemask, overlay[i].blendtype);
+			}
+			i++;
+		}
+		if (LensOption.draw == 1 && LensOption.level == 4) DrawLens(LensOption.x, LensOption.y);
+	}
+	if (event == AGSE_SAVEGAME) {
+		for (int i = 0; i < MAX_OVERLAYS; ++i) {
+			engine->FWrite(&overlay[i].sprite, sizeof(int), data);
+			engine->FWrite(&overlay[i].spritemask, sizeof(int), data);
+			engine->FWrite(&overlay[i].x, sizeof(int), data);
+			engine->FWrite(&overlay[i].y, sizeof(int), data);
+			engine->FWrite(&overlay[i].level, sizeof(int), data);
+			engine->FWrite(&overlay[i].trans, sizeof(int), data);
+			engine->FWrite(&overlay[i].blendtype, sizeof(int), data);
+			engine->FWrite(&overlay[i].enabled, sizeof(bool), data);
+		}
+		engine->FWrite(&clutslot, sizeof(int), data);
+		engine->FWrite(&drawreflections, sizeof(int), data);
+		for (int j = 0; j < 256; ++j) {
+			engine->FWrite(&cycle_remap[j], sizeof(unsigned char), data);
+		}
+		for (int j = 0; j < 256; ++j) {
+			engine->FWrite(&objectivepal[j].r, sizeof(unsigned char), data);
+			engine->FWrite(&objectivepal[j].b, sizeof(unsigned char), data);
+			engine->FWrite(&objectivepal[j].g, sizeof(unsigned char), data);
+		}
+		for (int j = 0; j < 256; ++j) {
+			engine->FWrite(&sprite[j].x, sizeof(double), data);
+			engine->FWrite(&sprite[j].y, sizeof(double), data);
+			engine->FWrite(&sprite[j].texture, sizeof(int), data);
+			engine->FWrite(&sprite[j].alpha, sizeof(unsigned char), data);
+			engine->FWrite(&sprite[j].uDivW, sizeof(double), data);
+			engine->FWrite(&sprite[j].uDivH, sizeof(double), data);
+			engine->FWrite(&sprite[j].vMove, sizeof(double), data);
+			engine->FWrite(&sprite[j].hMove, sizeof(double), data);
+			engine->FWrite(&sprite[j].objectinteract, sizeof(char), data);
+			engine->FWrite(&sprite[j].view, sizeof(int), data);
+			engine->FWrite(&sprite[j].frame, sizeof(int), data);
+			engine->FWrite(&sprite[j].angle, sizeof(int), data);
+		}
+		for (int j = 0; j < 256; ++j) {
+			for (int k = 0; k < 4; ++k) {
+				engine->FWrite(&wallData[j].texture[k], sizeof(int), data);
+				engine->FWrite(&wallData[j].solid[k], sizeof(int), data);
+				engine->FWrite(&wallData[j].ignorelighting[k], sizeof(int), data);
+				engine->FWrite(&wallData[j].alpha[k], sizeof(int), data);
+				engine->FWrite(&wallData[j].blendtype[k], sizeof(int), data);
+				engine->FWrite(&wallData[j].mask[k], sizeof(int), data);
+			}
+			engine->FWrite(&wallData[j].hotspotinteract, sizeof(char), data);
+		}
+		engine->FWrite(&raycastOn, sizeof(bool), data);
+		engine->FWrite(&heightmapOn, sizeof(bool), data);
+		engine->FWrite(&posX, sizeof(double), data);
+		engine->FWrite(&posY, sizeof(double), data);
+		engine->FWrite(&dirX, sizeof(double), data);
+		engine->FWrite(&dirY, sizeof(double), data);
+		engine->FWrite(&planeX, sizeof(double), data);
+		engine->FWrite(&planeY, sizeof(double), data);
+		engine->FWrite(&moveSpeed, sizeof(double), data);
+		engine->FWrite(&rotSpeed, sizeof(double), data);
+		if (raycastOn) { //If the raycaster is active, we have additional data to save.
+			for (int i = 0; i < mapWidth; ++i)
+				for (int j = 0; j < mapHeight; ++j) {
+					engine->FWrite(&worldMap [i][j], sizeof(unsigned char), data);
+					engine->FWrite(&lightMap [i][j], sizeof(unsigned char), data);
+					engine->FWrite(&ceilingMap [i][j], sizeof(int), data);
+					engine->FWrite(&floorMap [i][j], sizeof(int), data);
+					engine->FWrite(&heightMap [i][j], sizeof(int), data);
+				}
+		}
+		engine->FWrite(&textureSlot, sizeof(int), data);
+		engine->FWrite(&skybox, sizeof(int), data);
+		engine->FWrite(&ambientlight, sizeof(int), data);
+	}
+	if (event == AGSE_RESTOREGAME) {
+
+
+		for (int i = 0; i < MAX_OVERLAYS; ++i) {
+			engine->FRead(&overlay[i].sprite, sizeof(int), data);
+			engine->FRead(&overlay[i].spritemask, sizeof(int), data);
+			engine->FRead(&overlay[i].x, sizeof(int), data);
+			engine->FRead(&overlay[i].y, sizeof(int), data);
+			engine->FRead(&overlay[i].level, sizeof(int), data);
+			engine->FRead(&overlay[i].trans, sizeof(int), data);
+			engine->FRead(&overlay[i].blendtype, sizeof(int), data);
+			engine->FRead(&overlay[i].enabled, sizeof(bool), data);
+		}
+		engine->FRead(&clutslot, sizeof(int), data);
+		engine->FRead(&drawreflections, sizeof(int), data);
+		for (int j = 0; j < 256; ++j) {
+			engine->FRead(&cycle_remap[j], sizeof(unsigned char), data);
+		}
+		for (int j = 0; j < 256; ++j) { //Save Objective Palette, for palette mixing.
+			engine->FRead(&objectivepal[j].r, sizeof(unsigned char), data);
+			engine->FRead(&objectivepal[j].b, sizeof(unsigned char), data);
+			engine->FRead(&objectivepal[j].g, sizeof(unsigned char), data);
+		}
+		for (int j = 0; j < 256; ++j) { //Save Raycaster Sprite struct, 256 instances.
+			engine->FRead(&sprite[j].x, sizeof(double), data);
+			engine->FRead(&sprite[j].y, sizeof(double), data);
+			engine->FRead(&sprite[j].texture, sizeof(int), data);
+			engine->FRead(&sprite[j].alpha, sizeof(unsigned char), data);
+			engine->FRead(&sprite[j].uDivW, sizeof(double), data);
+			engine->FRead(&sprite[j].uDivH, sizeof(double), data);
+			engine->FRead(&sprite[j].vMove, sizeof(double), data);
+			engine->FRead(&sprite[j].hMove, sizeof(double), data);
+			engine->FRead(&sprite[j].objectinteract, sizeof(char), data);
+			engine->FRead(&sprite[j].view, sizeof(int), data);
+			engine->FRead(&sprite[j].frame, sizeof(int), data);
+			engine->FRead(&sprite[j].angle, sizeof(int), data);
+		}
+		for (int j = 0; j < 256; ++j) { //Save Raycaster wall type data.
+			for (int k = 0; k < 4; ++k) {
+				engine->FRead(&wallData[j].texture[k], sizeof(int), data);
+				engine->FRead(&wallData[j].solid[k], sizeof(int), data);
+				engine->FRead(&wallData[j].ignorelighting[k], sizeof(int), data);
+				engine->FRead(&wallData[j].alpha[k], sizeof(int), data);
+				engine->FRead(&wallData[j].blendtype[k], sizeof(int), data);
+				engine->FRead(&wallData[j].mask[k], sizeof(int), data);
+			}
+			engine->FRead(&wallData[j].hotspotinteract, sizeof(char), data);
+		}
+		//Delete worldmap data if it exists.
+		engine->FRead(&raycastOn, sizeof(bool), data);
+		engine->FRead(&heightmapOn, sizeof(bool), data);
+		engine->FRead(&posX, sizeof(double), data);
+		engine->FRead(&posY, sizeof(double), data);
+		engine->FRead(&dirX, sizeof(double), data);
+		engine->FRead(&dirY, sizeof(double), data);
+		engine->FRead(&planeX, sizeof(double), data);
+		engine->FRead(&planeY, sizeof(double), data);
+		engine->FRead(&moveSpeed, sizeof(double), data);
+		engine->FRead(&rotSpeed, sizeof(double), data);
+		if (raycastOn) { //If the raycaster is currently running, we have additional data to load.
+			for (int i = 0; i < mapWidth; ++i) {
+				for (int j = 0; j < mapHeight; ++j) {
+					engine->FRead(&worldMap [i][j], sizeof(unsigned char), data);
+					engine->FRead(&lightMap [i][j], sizeof(unsigned char), data);
+					engine->FRead(&ceilingMap [i][j], sizeof(int), data);
+					engine->FRead(&floorMap [i][j], sizeof(int), data);
+					engine->FRead(&heightMap [i][j], sizeof(int), data);
+					seenMap [i][j] = 0;
+				}
+			}
+
+			//Reinitialize all the buffers and stuff.
+
+		}
+		engine->FRead(&textureSlot, sizeof(int), data);
+		if (textureSlot) MakeTextures(textureSlot);
+		engine->FRead(&skybox, sizeof(int), data);
+		engine->FRead(&ambientlight, sizeof(int), data);
+		LoadCLUT(clutslot);
+	}
+	if (event == AGSE_ENTERROOM) {
+		ResetRemapping();
+		delete[] Reflection.Objects;
+		Reflection.Objects = new objrefopt [engine->GetNumObjects()]();
+	}
+	return 0;
+}
+
+int AGS_EngineDebugHook(const char *scriptName, int lineNum, int reserved) {
+	return 0;
+}
+void AGS_EngineInitGfx(const char *driverID, void *data) {}
+
+// *** END RUN TIME ****
+
+#if defined(BUILTIN_PLUGINS)
+} // namespace agspalrender
+#endif
diff --git a/engines/ags/plugins/ags_pal_render/ags_pal_render.h b/engines/ags/plugins/ags_pal_render/ags_pal_render.h
new file mode 100644
index 0000000000..61063daf90
--- /dev/null
+++ b/engines/ags/plugins/ags_pal_render/ags_pal_render.h
@@ -0,0 +1,14 @@
+#ifndef AGS_TOUCH_H
+#define AGS_TOUCH_H
+
+#include "plugin/agsplugin.h"
+
+namespace agspalrender {
+void AGS_EngineStartup(IAGSEngine *lpEngine);
+void AGS_EngineShutdown();
+int AGS_EngineOnEvent(int event, int data);
+int AGS_EngineDebugHook(const char *scriptName, int lineNum, int reserved);
+void AGS_EngineInitGfx(const char *driverID, void *data);
+}
+
+#endif
\ No newline at end of file
diff --git a/engines/ags/plugins/ags_pal_render/agsplugin.h b/engines/ags/plugins/ags_pal_render/agsplugin.h
new file mode 100644
index 0000000000..f9fd46e6ed
--- /dev/null
+++ b/engines/ags/plugins/ags_pal_render/agsplugin.h
@@ -0,0 +1,564 @@
+//=============================================================================
+//
+// Adventure Game Studio (AGS)
+//
+// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
+// The full list of copyright holders can be found in the Copyright.txt
+// file, which is part of this source code distribution.
+//
+// The AGS source code is provided under the Artistic License 2.0.
+// A copy of this license can be found in the file License.txt and at
+// http://www.opensource.org/licenses/artistic-license-2.0.php
+//
+//=============================================================================
+//
+// AGS Plugin interface header file
+//
+// #define THIS_IS_THE_PLUGIN beforehand if including from the plugin
+//
+//=============================================================================
+
+#ifndef _AGS_PLUGIN_H
+#define _AGS_PLUGIN_H
+
+// If the plugin isn't using DDraw, don't require the headers
+#ifndef DIRECTDRAW_VERSION
+typedef void *LPDIRECTDRAW2;
+typedef void *LPDIRECTDRAWSURFACE2;
+#endif
+
+#ifndef DIRECTSOUND_VERSION
+typedef void *LPDIRECTSOUND;
+#endif
+
+#ifndef DIRECTINPUT_VERSION
+typedef void *LPDIRECTINPUTDEVICE;
+#endif
+
+// If the user isn't using Allegro or WinGDI, define the BITMAP into something
+#if !defined(ALLEGRO_H) && !defined(_WINGDI_) && !defined(BITMAP_DEFINED)
+typedef char BITMAP;
+#endif
+
+// If not using windows.h, define HWND
+#if !defined(_WINDOWS_) && !defined(HWND)
+typedef int HWND;
+#endif
+
+// This file is distributed as part of the Plugin API docs, so
+// ensure that WINDOWS_VERSION is defined (if applicable)
+#if defined(_WINDOWS_) || defined(_WIN32)
+#ifndef WINDOWS_VERSION
+#define WINDOWS_VERSION
+#endif
+#endif
+
+// DOS engine doesn't know about stdcall / neither does Linux version
+#if !defined (WINDOWS_VERSION)
+#define __stdcall
+#endif
+
+#ifndef int32
+#define int32 int
+#endif
+
+#define AGSIFUNC(type) virtual type __stdcall
+
+#define MASK_WALKABLE   1
+#define MASK_WALKBEHIND 2
+#define MASK_HOTSPOT    3
+// MASK_REGIONS is interface version 11 and above only
+#define MASK_REGIONS    4
+
+// **** WARNING: DO NOT ALTER THESE CLASSES IN ANY WAY!
+// **** CHANGING THE ORDER OF THE FUNCTIONS OR ADDING ANY VARIABLES
+// **** WILL CRASH THE SYSTEM.
+
+struct AGSColor {
+	unsigned char r, g, b;
+	unsigned char padding;
+};
+
+struct AGSGameOptions {
+	int32 score;      // player's current score
+	int32 usedmode;   // set by ProcessClick to last cursor mode used
+	int32 disabled_user_interface;  // >0 while in cutscene/etc
+	int32 gscript_timer;    // obsolete
+	int32 debug_mode;       // whether we're in debug mode
+	int32 globalvars[50];   // obsolete
+	int32 messagetime;      // time left for auto-remove messages
+	int32 usedinv;          // inventory item last used
+	int32 inv_top, inv_numdisp, inv_numorder, inv_numinline;
+	int32 text_speed;       // how quickly text is removed
+	int32 sierra_inv_color; // background used to paint defualt inv window
+	int32 talkanim_speed;   // animation speed of talking anims
+	int32 inv_item_wid, inv_item_hit; // set by SetInvDimensions
+	int32 speech_text_shadow;         // colour of outline fonts (default black)
+	int32 swap_portrait_side;         // sierra-style speech swap sides
+	int32 speech_textwindow_gui;      // textwindow used for sierra-style speech
+	int32 follow_change_room_timer;   // delay before moving following characters into new room
+	int32 totalscore;           // maximum possible score
+	int32 skip_display;         // how the user can skip normal Display windows
+	int32 no_multiloop_repeat;  // for backwards compatibility
+	int32 roomscript_finished;  // on_call finished in room
+	int32 used_inv_on;          // inv item they clicked on
+	int32 no_textbg_when_voice; // no textwindow bgrnd when voice speech is used
+	int32 max_dialogoption_width; // max width of dialog options text window
+	int32 no_hicolor_fadein;      // fade out but instant in for hi-color
+	int32 bgspeech_game_speed;    // is background speech relative to game speed
+	int32 bgspeech_stay_on_display; // whether to remove bg speech when DisplaySpeech is used
+	int32 unfactor_speech_from_textlength; // remove "&10" when calculating time for text to stay
+	int32 mp3_loop_before_end;    // loop this time before end of track (ms)
+	int32 speech_music_drop;      // how much to drop music volume by when speech is played
+	int32 in_cutscene;            // we are between a StartCutscene and EndCutscene
+	int32 fast_forward;           // player has elected to skip cutscene
+	int32 room_width;      // width of current room (320-res co-ordinates)
+	int32 room_height;     // height of current room (320-res co-ordinates)
+};
+
+// AGSCharacter.flags
+#define CHF_NOSCALING       1
+#define CHF_FIXVIEW         2     // between SetCharView and ReleaseCharView
+#define CHF_NOINTERACT      4
+#define CHF_NODIAGONAL      8
+#define CHF_ALWAYSIDLE      0x10
+#define CHF_NOLIGHTING      0x20
+#define CHF_NOTURNING       0x40
+#define CHF_NOWALKBEHINDS   0x80
+
+struct AGSCharacter {
+	int32 defview;
+	int32 talkview;
+	int32 view;
+	int32 room, prevroom;
+	int32 x, y, wait;
+	int32 flags;
+	short following;
+	short followinfo;
+	int32 idleview;           // the loop will be randomly picked
+	short idletime, idleleft; // num seconds idle before playing anim
+	short transparency;       // if character is transparent
+	short baseline;
+	int32 activeinv;
+	int32 talkcolor;
+	int32 thinkview;
+	int32 reserved[2];
+	short walkspeed_y, pic_yoffs;
+	int32 z;
+	int32 reserved2[5];
+	short loop, frame;
+	short walking, animating;
+	short walkspeed, animspeed;
+	short inv[301];
+	short actx, acty;
+	char  name[40];
+	char  scrname[20];
+	char  on;
+};
+
+// AGSObject.flags
+#define OBJF_NOINTERACT 1     // not clickable
+#define OBJF_NOWALKBEHINDS 2  // ignore walk-behinds
+
+struct AGSObject {
+	int32 x, y;
+	int32 transparent;    // current transparency setting
+	int32 reserved[4];
+	short num;            // sprite slot number
+	short baseline;       // <=0 to use Y co-ordinate; >0 for specific baseline
+	short view, loop, frame; // only used to track animation - 'num' holds the current sprite
+	short wait, moving;
+	char  cycling;        // is it currently animating?
+	char  overall_speed;
+	char  on;
+	char  flags;
+};
+
+// AGSViewFrame.flags
+#define FRAF_MIRRORED  1  // flipped left to right
+
+struct AGSViewFrame {
+	int32 pic;            // sprite slot number
+	short xoffs, yoffs;
+	short speed;
+	int32 flags;
+	int32 sound;          // play sound when this frame comes round
+	int32 reserved_for_future[2];
+};
+
+// AGSMouseCursor.flags
+#define MCF_ANIMATEMOVE 1
+#define MCF_DISABLED    2
+#define MCF_STANDARD    4
+#define MCF_ONLYANIMOVERHOTSPOT 8
+
+struct AGSMouseCursor {
+	int32 pic;            // sprite slot number
+	short hotx, hoty;     // x,y hotspot co-ordinates
+	short view;           // view (for animating cursors) or -1
+	char  name[10];       // name of cursor mode
+	char  flags;          // MCF_flags above
+};
+
+// The editor-to-plugin interface
+class IAGSEditor {
+public:
+	int32 version;
+	int32 pluginId;   // used internally, do not touch this
+
+public:
+	// get the HWND of the main editor frame
+	AGSIFUNC(HWND) GetEditorHandle();
+	// get the HWND of the current active window
+	AGSIFUNC(HWND) GetWindowHandle();
+	// add some script to the default header
+	AGSIFUNC(void) RegisterScriptHeader(const char *header);
+	// de-register a script header (pass same pointer as when added)
+	AGSIFUNC(void) UnregisterScriptHeader(const char *header);
+
+};
+
+
+// Below are interface 3 and later
+#define AGSE_KEYPRESS        1
+#define AGSE_MOUSECLICK      2
+#define AGSE_POSTSCREENDRAW  4
+// Below are interface 4 and later
+#define AGSE_PRESCREENDRAW   8
+// Below are interface 5 and later
+#define AGSE_SAVEGAME        0x10
+#define AGSE_RESTOREGAME     0x20
+// Below are interface 6 and later
+#define AGSE_PREGUIDRAW      0x40
+#define AGSE_LEAVEROOM       0x80
+#define AGSE_ENTERROOM       0x100
+#define AGSE_TRANSITIONIN    0x200
+#define AGSE_TRANSITIONOUT   0x400
+// Below are interface 12 and later
+#define AGSE_FINALSCREENDRAW 0x800
+#define AGSE_TRANSLATETEXT  0x1000
+// Below are interface 13 and later
+#define AGSE_SCRIPTDEBUG    0x2000
+#define AGSE_AUDIODECODE    0x4000 // obsolete, no longer supported
+// Below are interface 18 and later
+#define AGSE_SPRITELOAD     0x8000
+// Below are interface 21 and later
+#define AGSE_PRERENDER     0x10000
+// Below are interface 24 and later
+#define AGSE_PRESAVEGAME     0x20000
+#define AGSE_POSTRESTOREGAME 0x40000
+#define AGSE_TOOHIGH         0x80000
+
+// GetFontType font types
+#define FNT_INVALID 0
+#define FNT_SCI     1
+#define FNT_TTF     2
+
+// PlaySoundChannel sound types
+#define PSND_WAVE       1
+#define PSND_MP3STREAM  2
+#define PSND_MP3STATIC  3
+#define PSND_OGGSTREAM  4
+#define PSND_OGGSTATIC  5
+#define PSND_MIDI       6
+#define PSND_MOD        7
+
+class IAGSScriptManagedObject {
+public:
+	// when a ref count reaches 0, this is called with the address
+	// of the object. Return 1 to remove the object from memory, 0 to
+	// leave it
+	virtual int Dispose(const char *address, bool force) = 0;
+	// return the type name of the object
+	virtual const char *GetType() = 0;
+	// serialize the object into BUFFER (which is BUFSIZE bytes)
+	// return number of bytes used
+	virtual int Serialize(const char *address, char *buffer, int bufsize) = 0;
+};
+
+class IAGSManagedObjectReader {
+public:
+	virtual void Unserialize(int key, const char *serializedData, int dataSize) = 0;
+};
+
+class IAGSFontRenderer {
+public:
+	virtual bool LoadFromDisk(int fontNumber, int fontSize) = 0;
+	virtual void FreeMemory(int fontNumber) = 0;
+	virtual bool SupportsExtendedCharacters(int fontNumber) = 0;
+	virtual int GetTextWidth(const char *text, int fontNumber) = 0;
+	virtual int GetTextHeight(const char *text, int fontNumber) = 0;
+	virtual void RenderText(const char *text, int fontNumber, BITMAP *destination, int x, int y, int colour) = 0;
+	virtual void AdjustYCoordinateForFont(int *ycoord, int fontNumber) = 0;
+	virtual void EnsureTextValidForFont(char *text, int fontNumber) = 0;
+};
+
+// The plugin-to-engine interface
+class IAGSEngine {
+public:
+	int32 version;
+	int32 pluginId;   // used internally, do not touch
+
+public:
+	// quit the game
+	AGSIFUNC(void) AbortGame(const char *reason);
+	// get engine version
+	AGSIFUNC(const char *) GetEngineVersion();
+	// register a script function with the system
+	AGSIFUNC(void) RegisterScriptFunction(const char *name, void *address);
+#ifdef WINDOWS_VERSION
+	// get game window handle
+	AGSIFUNC(HWND) GetWindowHandle();
+	// get reference to main DirectDraw interface
+	AGSIFUNC(LPDIRECTDRAW2) GetDirectDraw2();
+	// get the DDraw surface associated with a bitmap
+	AGSIFUNC(LPDIRECTDRAWSURFACE2) GetBitmapSurface(BITMAP *);
+#endif
+	// get a reference to the screen bitmap
+	AGSIFUNC(BITMAP *) GetScreen();
+
+	// *** BELOW ARE INTERFACE VERSION 2 AND ABOVE ONLY
+	// ask the engine to call back when a certain event happens
+	AGSIFUNC(void) RequestEventHook(int32 event);
+	// get the options data saved in the editor
+	AGSIFUNC(int)  GetSavedData(char *buffer, int32 bufsize);
+
+	// *** BELOW ARE INTERFACE VERSION 3 AND ABOVE ONLY
+	// get the virtual screen
+	AGSIFUNC(BITMAP *) GetVirtualScreen();
+	// write text to the screen in the specified font and colour
+	AGSIFUNC(void) DrawText(int32 x, int32 y, int32 font, int32 color, char *text);
+	// get screen dimensions
+	AGSIFUNC(void) GetScreenDimensions(int32 *width, int32 *height, int32 *coldepth);
+	// get screen surface to draw on
+	AGSIFUNC(unsigned char **) GetRawBitmapSurface(BITMAP *);
+	// release the surface
+	AGSIFUNC(void) ReleaseBitmapSurface(BITMAP *);
+	// get the current mouse co-ordinates
+	AGSIFUNC(void) GetMousePosition(int32 *x, int32 *y);
+
+	// *** BELOW ARE INTERFACE VERSION 4 AND ABOVE ONLY
+	// get the current room number
+	AGSIFUNC(int)  GetCurrentRoom();
+	// get the number of background scenes in this room
+	AGSIFUNC(int)  GetNumBackgrounds();
+	// get the current background frame
+	AGSIFUNC(int)  GetCurrentBackground();
+	// get a background scene bitmap
+	AGSIFUNC(BITMAP *) GetBackgroundScene(int32);
+	// get dimensions of a bitmap
+	AGSIFUNC(void) GetBitmapDimensions(BITMAP *bmp, int32 *width, int32 *height, int32 *coldepth);
+
+	// *** BELOW ARE INTERFACE VERSION 5 AND ABOVE ONLY
+	// similar to fwrite - buffer, size, filehandle
+	AGSIFUNC(int)  FWrite(void *, int32, int32);
+	// similar to fread - buffer, size, filehandle
+	AGSIFUNC(int)  FRead(void *, int32, int32);
+	// print text, wrapping as usual
+	AGSIFUNC(void) DrawTextWrapped(int32 x, int32 y, int32 width, int32 font, int32 color, const char *text);
+	// set the current active 'screen'
+	AGSIFUNC(void) SetVirtualScreen(BITMAP *);
+	// look up a word in the parser dictionary
+	AGSIFUNC(int)  LookupParserWord(const char *word);
+	// draw a bitmap to the active screen
+	AGSIFUNC(void) BlitBitmap(int32 x, int32 y, BITMAP *, int32 masked);
+	// update the mouse and music
+	AGSIFUNC(void) PollSystem();
+
+	// *** BELOW ARE INTERFACE VERSION 6 AND ABOVE ONLY
+	// get number of characters in game
+	AGSIFUNC(int)  GetNumCharacters();
+	// get reference to specified character struct
+	AGSIFUNC(AGSCharacter *) GetCharacter(int32);
+	// get reference to game struct
+	AGSIFUNC(AGSGameOptions *) GetGameOptions();
+	// get reference to current palette
+	AGSIFUNC(AGSColor *) GetPalette();
+	// update palette
+	AGSIFUNC(void) SetPalette(int32 start, int32 finish, AGSColor *);
+
+	// *** BELOW ARE INTERFACE VERSION 7 AND ABOVE ONLY
+	// get the current player character
+	AGSIFUNC(int)  GetPlayerCharacter();
+	// adjust to viewport co-ordinates
+	AGSIFUNC(void) RoomToViewport(int32 *x, int32 *y);
+	// adjust from viewport co-ordinates
+	AGSIFUNC(void) ViewportToRoom(int32 *x, int32 *y);
+	// number of objects in current room
+	AGSIFUNC(int)  GetNumObjects();
+	// get reference to specified object
+	AGSIFUNC(AGSObject *) GetObject(int32);
+	// get sprite graphic
+	AGSIFUNC(BITMAP *) GetSpriteGraphic(int32);
+	// create a new blank bitmap
+	AGSIFUNC(BITMAP *) CreateBlankBitmap(int32 width, int32 height, int32 coldep);
+	// free a created bitamp
+	AGSIFUNC(void) FreeBitmap(BITMAP *);
+
+	// *** BELOW ARE INTERFACE VERSION 8 AND ABOVE ONLY
+	// get one of the room area masks
+	AGSIFUNC(BITMAP *) GetRoomMask(int32);
+
+	// *** BELOW ARE INTERFACE VERSION 9 AND ABOVE ONLY
+	// get a particular view frame
+	AGSIFUNC(AGSViewFrame *) GetViewFrame(int32 view, int32 loop, int32 frame);
+	// get the walk-behind baseline of a specific WB area
+	AGSIFUNC(int)    GetWalkbehindBaseline(int32 walkbehind);
+	// get the address of a script function
+	AGSIFUNC(void *) GetScriptFunctionAddress(const char *funcName);
+	// get the transparent colour of a bitmap
+	AGSIFUNC(int)    GetBitmapTransparentColor(BITMAP *);
+	// get the character scaling level at a particular point
+	AGSIFUNC(int)    GetAreaScaling(int32 x, int32 y);
+	// equivalent to the text script function
+	AGSIFUNC(int)    IsGamePaused();
+
+	// *** BELOW ARE INTERFACE VERSION 10 AND ABOVE ONLY
+	// get the raw pixel value to use for the specified AGS colour
+	AGSIFUNC(int)    GetRawPixelColor(int32 color);
+
+	// *** BELOW ARE INTERFACE VERSION 11 AND ABOVE ONLY
+	// get the width / height of the specified sprite
+	AGSIFUNC(int)    GetSpriteWidth(int32);
+	AGSIFUNC(int)    GetSpriteHeight(int32);
+	// get the dimensions of the specified string in the specified font
+	AGSIFUNC(void)   GetTextExtent(int32 font, const char *text, int32 *width, int32 *height);
+	// print a message to the debug console
+	AGSIFUNC(void)   PrintDebugConsole(const char *text);
+	// play a sound on the specified channel
+	AGSIFUNC(void)   PlaySoundChannel(int32 channel, int32 soundType, int32 volume, int32 loop, const char *filename);
+	// same as text script function
+	AGSIFUNC(int)    IsChannelPlaying(int32 channel);
+
+	// *** BELOW ARE INTERFACE VERSION 12 AND ABOVE ONLY
+	// invalidate a region of the virtual screen
+	AGSIFUNC(void)   MarkRegionDirty(int32 left, int32 top, int32 right, int32 bottom);
+	// get mouse cursor details
+	AGSIFUNC(AGSMouseCursor *) GetMouseCursor(int32 cursor);
+	// get the various components of a pixel
+	AGSIFUNC(void)   GetRawColorComponents(int32 coldepth, int32 color, int32 *red, int32 *green, int32 *blue, int32 *alpha);
+	// make a pixel colour from the supplied components
+	AGSIFUNC(int)    MakeRawColorPixel(int32 coldepth, int32 red, int32 green, int32 blue, int32 alpha);
+	// get whether the font is TTF or SCI
+	AGSIFUNC(int)    GetFontType(int32 fontNum);
+	// create a new dynamic sprite slot
+	AGSIFUNC(int)    CreateDynamicSprite(int32 coldepth, int32 width, int32 height);
+	// free a created dynamic sprite
+	AGSIFUNC(void)   DeleteDynamicSprite(int32 slot);
+	// check if a sprite has an alpha channel
+	AGSIFUNC(int)    IsSpriteAlphaBlended(int32 slot);
+
+	// *** BELOW ARE INTERFACE VERSION 13 AND ABOVE ONLY
+	// un-request an event, requested earlier with RequestEventHook
+	AGSIFUNC(void)   UnrequestEventHook(int32 event);
+	// draw a translucent bitmap to the active screen
+	AGSIFUNC(void)   BlitSpriteTranslucent(int32 x, int32 y, BITMAP *, int32 trans);
+	// draw a sprite to the screen, but rotated around its centre
+	AGSIFUNC(void)   BlitSpriteRotated(int32 x, int32 y, BITMAP *, int32 angle);
+
+	// *** BELOW ARE INTERFACE VERSION 14 AND ABOVE ONLY
+#ifdef WINDOWS_VERSION
+	// get reference to main DirectSound interface
+	AGSIFUNC(LPDIRECTSOUND) GetDirectSound();
+#endif
+	// disable AGS sound engine
+	AGSIFUNC(void)   DisableSound();
+	// check whether a script function can be run now
+	AGSIFUNC(int)    CanRunScriptFunctionNow();
+	// call a user-defined script function
+	AGSIFUNC(int)    CallGameScriptFunction(const char *name, int32 globalScript, int32 numArgs, long arg1 = 0, long arg2 = 0, long arg3 = 0);
+
+	// *** BELOW ARE INTERFACE VERSION 15 AND ABOVE ONLY
+	// force any sprites on-screen using the slot to be updated
+	AGSIFUNC(void)   NotifySpriteUpdated(int32 slot);
+	// change whether the specified sprite is a 32-bit alpha blended image
+	AGSIFUNC(void)   SetSpriteAlphaBlended(int32 slot, int32 isAlphaBlended);
+	// run the specified script function whenever script engine is available
+	AGSIFUNC(void)   QueueGameScriptFunction(const char *name, int32 globalScript, int32 numArgs, long arg1 = 0, long arg2 = 0);
+	// register a new dynamic managed script object
+	AGSIFUNC(int)    RegisterManagedObject(const void *object, IAGSScriptManagedObject *callback);
+	// add an object reader for the specified object type
+	AGSIFUNC(void)   AddManagedObjectReader(const char *typeName, IAGSManagedObjectReader *reader);
+	// register an un-serialized managed script object
+	AGSIFUNC(void)   RegisterUnserializedObject(int key, const void *object, IAGSScriptManagedObject *callback);
+
+	// *** BELOW ARE INTERFACE VERSION 16 AND ABOVE ONLY
+	// get the address of a managed object based on its key
+	AGSIFUNC(void *)  GetManagedObjectAddressByKey(int key);
+	// get managed object's key from its address
+	AGSIFUNC(int)    GetManagedObjectKeyByAddress(const char *address);
+
+	// *** BELOW ARE INTERFACE VERSION 17 AND ABOVE ONLY
+	// create a new script string
+	AGSIFUNC(const char *) CreateScriptString(const char *fromText);
+
+	// *** BELOW ARE INTERFACE VERSION 18 AND ABOVE ONLY
+	// increment reference count
+	AGSIFUNC(int)    IncrementManagedObjectRefCount(const char *address);
+	// decrement reference count
+	AGSIFUNC(int)    DecrementManagedObjectRefCount(const char *address);
+	// set mouse position
+	AGSIFUNC(void)   SetMousePosition(int32 x, int32 y);
+	// simulate the mouse being clicked
+	AGSIFUNC(void)   SimulateMouseClick(int32 button);
+	// get number of waypoints on this movement path
+	AGSIFUNC(int)    GetMovementPathWaypointCount(int32 pathId);
+	// get the last waypoint that the char/obj passed
+	AGSIFUNC(int)    GetMovementPathLastWaypoint(int32 pathId);
+	// get the co-ordinates of the specified waypoint
+	AGSIFUNC(void)   GetMovementPathWaypointLocation(int32 pathId, int32 waypoint, int32 *x, int32 *y);
+	// get the speeds of the specified waypoint
+	AGSIFUNC(void)   GetMovementPathWaypointSpeed(int32 pathId, int32 waypoint, int32 *xSpeed, int32 *ySpeed);
+
+	// *** BELOW ARE INTERFACE VERSION 19 AND ABOVE ONLY
+	// get the current graphics driver ID
+	AGSIFUNC(const char *) GetGraphicsDriverID();
+
+	// *** BELOW ARE INTERFACE VERSION 22 AND ABOVE ONLY
+	// get whether we are running under the editor's debugger
+	AGSIFUNC(int)    IsRunningUnderDebugger();
+	// tells the engine to break into the debugger when the next line of script is run
+	AGSIFUNC(void)   BreakIntoDebugger();
+	// fills buffer with <install dir>\fileName, as appropriate
+	AGSIFUNC(void)   GetPathToFileInCompiledFolder(const char *fileName, char *buffer);
+
+	// *** BELOW ARE INTERFACE VERSION 23 AND ABOVE ONLY
+#ifdef WINDOWS_VERSION
+	// get reference to keyboard Direct Input device
+	AGSIFUNC(LPDIRECTINPUTDEVICE) GetDirectInputKeyboard();
+	// get reference to mouse Direct Input device
+	AGSIFUNC(LPDIRECTINPUTDEVICE) GetDirectInputMouse();
+#endif
+	// install a replacement renderer for the specified font number
+	AGSIFUNC(IAGSFontRenderer *) ReplaceFontRenderer(int fontNumber, IAGSFontRenderer *newRenderer);
+};
+
+#ifdef THIS_IS_THE_PLUGIN
+
+#ifdef WINDOWS_VERSION
+#define DLLEXPORT extern "C" __declspec(dllexport)
+#else
+// MAC VERSION: compile with -fvisibility=hidden
+// gcc -dynamiclib -std=gnu99 agsplugin.c -fvisibility=hidden -o agsplugin.dylib
+#define DLLEXPORT extern "C" __attribute__((visibility("default")))
+#endif
+
+DLLEXPORT const char *AGS_GetPluginName(void);
+DLLEXPORT int    AGS_EditorStartup(IAGSEditor *);
+DLLEXPORT void   AGS_EditorShutdown(void);
+DLLEXPORT void   AGS_EditorProperties(HWND);
+DLLEXPORT int    AGS_EditorSaveGame(char *, int);
+DLLEXPORT void   AGS_EditorLoadGame(char *, int);
+DLLEXPORT void   AGS_EngineStartup(IAGSEngine *);
+DLLEXPORT void   AGS_EngineShutdown(void);
+DLLEXPORT int    AGS_EngineOnEvent(int, int);
+DLLEXPORT int    AGS_EngineDebugHook(const char *, int, int);
+DLLEXPORT void   AGS_EngineInitGfx(const char *driverID, void *data);
+// We export this to verify that we are an AGS Plugin
+DLLEXPORT int    AGS_PluginV2() {
+	return 1;
+}
+
+#endif // THIS_IS_THE_PLUGIN
+
+#endif
diff --git a/engines/ags/plugins/ags_pal_render/pal_render.h b/engines/ags/plugins/ags_pal_render/pal_render.h
new file mode 100644
index 0000000000..09c2e6b5a5
--- /dev/null
+++ b/engines/ags/plugins/ags_pal_render/pal_render.h
@@ -0,0 +1,185 @@
+#ifndef __PALGORITHMS_PALRENDER_H
+#define __PALGORITHMS_PALRENDER_H
+
+#include "agsplugin.h"
+#include <stdint.h> // for int32_t types, __int32 is just Windows
+#include <algorithm>  // for std::max and std::min
+#include <cstring>  // for memcpy
+
+#undef min
+#undef max
+
+#ifndef _WIN32
+#define __forceinline __attribute__((always_inline))
+
+#define SCRIPT_FLOAT(x) int32_t __script_float##x
+#define INIT_SCRIPT_FLOAT(x) float x; std::memcpy(&x, &__script_float##x, sizeof(float))
+#define FLOAT_RETURN_TYPE int32_t
+#define RETURN_FLOAT(x) int32_t __ret##x; std::memcpy(&__ret##x, &x, sizeof(float)); return __ret##x
+#else
+#define SCRIPT_FLOAT(x) __int32 __script_float##x
+#define INIT_SCRIPT_FLOAT(x) float x; memcpy(&x, &__script_float##x, sizeof(float))
+#define FLOAT_RETURN_TYPE __int32
+#define RETURN_FLOAT(x) __int32 __ret##x; memcpy(&__ret##x, &x, sizeof(float)); return __ret##x
+#endif
+
+#if defined(BUILTIN_PLUGINS)
+namespace agspalrender {
+#endif
+
+struct PALSTRUCT {
+	int r;
+	int b;
+	int g;
+};
+
+extern IAGSEngine *engine;
+extern unsigned char clut[65536];
+extern unsigned char cycle_remap [256];
+extern const int alphamultiply [4096];
+extern PALSTRUCT objectivepal[256];
+
+// this class exists solely to take advantage of g++'s
+// -fvisibility-inlines-hidden option, so that these
+// methods can be inlined without any trace or complaint
+class Mix {
+public:
+
+//unsigned char MixColorAlpha (unsigned char fg,unsigned char bg,unsigned char alpha);
+//unsigned char MixColorAdditive (unsigned char fg,unsigned char bg,unsigned char alpha);
+	__forceinline static unsigned char MixColorAlpha(unsigned char fg, unsigned char bg, unsigned char alpha, int use_objpal = 0) {
+		unsigned char rfg = cycle_remap [fg]; //Automatic remapping of palette slots.
+		//unsigned char rbg = cycle_remap [bg]; //Saves on typing elsewhere.
+		AGSColor *palette = engine->GetPalette();
+		int i = 0;
+		//int out_r = (palette[fg].r>>1) * alpha + (palette[bg].r>>1) * (255 - alpha);
+		//int out_g = palette[fg].g * alpha + palette[bg].g * (255 - alpha);
+		//int out_b = (palette[fg].b>>1) * alpha + (palette[bg].b>>1) * (255 - alpha);
+		int out_r, out_g, out_b;
+		if (use_objpal == 0) {
+			out_r = (objectivepal[rfg].r >> 1) * alpha + (palette[bg].r >> 1) * (255 - alpha);
+			out_g = objectivepal[rfg].g * alpha + palette[bg].g * (255 - alpha);
+			out_b = (objectivepal[rfg].b >> 1) * alpha + (palette[bg].b >> 1) * (255 - alpha);
+		} else {
+			out_r = (objectivepal[rfg].r >> 1) * alpha + (objectivepal[bg].r >> 1) * (255 - alpha);
+			out_g = objectivepal[rfg].g * alpha + objectivepal[bg].g * (255 - alpha);
+			out_b = (objectivepal[rfg].b >> 1) * alpha + (objectivepal[bg].b >> 1) * (255 - alpha);
+		}
+		//char ralpha = std::max(0,std::min(63,alpha>>2));
+		//unsigned char invralpha = 64-ralpha;
+		//if (ralpha > alpha) engine->AbortGame ("wtf");
+		//int out_r = alphamultiply[((palette[fg].r>>1)<<6) +ralpha] + alphamultiply[((palette[bg].r>>1)<<6) +(invralpha)];
+		//int out_g = alphamultiply[((palette[fg].g)   <<6) +ralpha] + alphamultiply[((palette[bg].g)   <<6) +(invralpha)];
+		//int out_b = alphamultiply[((palette[fg].b>>1)<<6) +ralpha] + alphamultiply[((palette[bg].b>>1)<<6) +(invralpha)];
+		out_r = (out_r + 1 + (out_r >> 8)) >> 8;
+		out_g = (out_g + 1 + (out_g >> 8)) >> 8;
+		out_b = (out_b + 1 + (out_b >> 8)) >> 8;
+		//out_r = (out_r + 1 + (out_r >> 6)) >> 6;
+		//out_g = (out_g + 1 + (out_g >> 6)) >> 6;
+		//out_b = (out_b + 1 + (out_b >> 6)) >> 6;
+		i = ((out_r << 11) | (out_g << 5) | out_b);
+		unsigned char (*clutp) = clut;
+		//unsigned char result = cycle_remap [clut[i>>8][i%256]]; //Once again, to make sure that the palette slot used is the right one.
+		return cycle_remap[*(clutp + i)]; //Once again, to make sure that the palette slot used is the right one.
+		//engine->ReleaseBitmapSurface (clutspr);
+	}
+
+	__forceinline static unsigned char MixColorLightLevel(unsigned char fg, unsigned char intensity) {
+		unsigned char rfg = cycle_remap [fg]; //Automatic remapping of palette slots.
+		int i = 0;
+		//int dark_r = (((palette[fg].r>>1) * (intensity))>>8);
+		//int dark_b = (((palette[fg].b>>1) * (intensity))>>8);
+		//int dark_g = (((palette[fg].g)    * (intensity))>>8);
+		int dark_r = (((objectivepal[rfg].r >> 1) * (intensity)) >> 8);
+		int dark_b = (((objectivepal[rfg].b >> 1) * (intensity)) >> 8);
+		int dark_g = (((objectivepal[rfg].g)    * (intensity)) >> 8);
+		i = ((dark_r << 11) | (dark_g << 5) | dark_b);
+		unsigned char (*clutp) = clut;
+		return cycle_remap [*(clutp + i)]; //Once again, to make sure that the palette slot used is the right one.
+	}
+
+	__forceinline static unsigned char MixColorAdditive(unsigned char fg, unsigned char bg, unsigned char alpha, int use_objpal = 0) {
+		unsigned char rfg = cycle_remap [fg]; //Automatic remapping of palette slots.
+		unsigned char rbg = cycle_remap [bg]; //Saves on typing elsewhere.
+		//BITMAP *clutspr = engine->GetSpriteGraphic (clutslot);
+		//if (!clutspr) engine->AbortGame ("MixColorAlpha: Can't load CLUT sprite into memory.");
+		//unsigned char **clutarray = engine->GetRawBitmapSurface (clutspr);
+		AGSColor *palette = engine->GetPalette();
+		int i = 0;
+		int add_r, add_b, add_g = 0;
+		//char ralpha = std::max(0,std::min(63,alpha>>2));
+		//add_r = (((palette[fg].r>>1) * (alpha))>>8);
+		//add_b = (((palette[fg].b>>1) * (alpha))>>8);
+		//add_g = (((palette[fg].g)    * (alpha))>>8);
+		add_r = (((objectivepal[rfg].r >> 1) * (alpha)) >> 8);
+		add_b = (((objectivepal[rfg].b >> 1) * (alpha)) >> 8);
+		add_g = (((objectivepal[rfg].g)    * (alpha)) >> 8);
+		//int a_g = std::max(0,std::min(63,alpha>>2));
+		//add_r = ((alphamultiply[(palette[fg].r>>1)<<6)+ralpha])>>6);
+		//add_b = ((alphamultiply[(palette[fg].b>>1)<<6)+ralpha])>>6);
+		//add_g = ((alphamultiply[(palette[fg].g)   <<6)+ralpha])>>6);
+		//int out_r = std::min(31,(palette[bg].r>>1) + add_r);
+		//int out_g = std::min(63, palette[bg].g     + add_g);
+		//int out_b = std::min(31,(palette[bg].b>>1) + add_b);
+		int out_r, out_g, out_b;
+		if (use_objpal == 0) {
+			out_r = std::min(31, (palette[bg].r >> 1) + add_r);
+			out_g = std::min(63, palette[bg].g     + add_g);
+			out_b = std::min(31, (palette[bg].b >> 1) + add_b);
+		} else {
+			out_r = std::min(31, (objectivepal [bg].r >> 1) + add_r);
+			out_g = std::min(63, objectivepal [bg].g     + add_g);
+			out_b = std::min(31, (objectivepal [bg].b >> 1) + add_b);
+		}
+		i = ((out_r << 11) | (out_g << 5) | out_b);
+		unsigned char (*clutp) = clut;
+		unsigned char result = cycle_remap [*(clutp + i)]; //Once again, to make sure that the palette slot used is the right one.
+		//unsigned char result = cycle_remap [clut[i>>8][i%256]]; //Once again, to make sure that the palette slot used is the right one.
+		//engine->ReleaseBitmapSurface (clutspr);
+		return result;
+	}
+
+	__forceinline static unsigned char MixColorMultiply(unsigned char fg, unsigned char bg, unsigned char alpha, int use_objpal = 0) {
+		unsigned char rfg = cycle_remap [fg]; //Automatic remapping of palette slots.
+		unsigned char rbg = cycle_remap [bg]; //Saves on typing elsewhere.
+		AGSColor *palette = engine->GetPalette();
+		int i = 0;
+		int mul_r, mul_b, mul_g = 0;
+		int out_r, out_g, out_b = 0;
+		if (use_objpal == 0) {
+			mul_r = ((objectivepal[rfg].r >> 1) * (palette[rbg].r >> 1)) / 64;
+			mul_b = ((objectivepal[rfg].b >> 1) * (palette[rbg].b >> 1)) / 64;
+			mul_g = ((objectivepal[rfg].g * palette[rbg].g) / 64);
+			out_r = ((palette[rbg].r >> 1) * (63 - (alpha / 4)) + (mul_r * (alpha / 4))) / 63;
+			out_g = (palette[rbg].g * (63 - (alpha / 4)) + (mul_g * (alpha / 4))) / 63;
+			out_b = ((palette[rbg].b >> 1) * (63 - (alpha / 4)) + (mul_b * (alpha / 4))) / 63;
+		} else {
+			mul_r = ((objectivepal[rfg].r >> 1) * (objectivepal[rbg].r >> 1)) / 64;
+			mul_b = ((objectivepal[rfg].b >> 1) * (objectivepal[rbg].b >> 1)) / 64;
+			mul_g = ((objectivepal[rfg].g * objectivepal[rbg].g) / 64);
+
+			out_r = ((objectivepal[rbg].r >> 1) * (63 - (alpha / 4)) + (mul_r * (alpha / 4))) / 63;
+			out_g = (objectivepal[rbg].g * (63 - (alpha / 4)) + (mul_g * (alpha / 4))) / 63;
+			out_b = ((objectivepal[rbg].b >> 1) * (63 - (alpha / 4)) + (mul_b * (alpha / 4))) / 63;
+		}
+		i = ((out_r << 11) | (out_g << 5) | out_b);
+		unsigned char (*clutp) = clut;
+		unsigned char result = cycle_remap [*(clutp + i)]; //Once again, to make sure that the palette slot used is the right one.
+		//unsigned char result = cycle_remap [clut[i>>8][i%256]]; //Once again, to make sure that the palette slot used is the right one.
+		//engine->ReleaseBitmapSurface (clutspr);
+		return result;
+	}
+
+};
+
+unsigned char GetColor565(unsigned char r, unsigned char g, unsigned char b);
+
+unsigned short root(unsigned short x);
+float FastSin(float x);
+float FastCos(float x);
+
+#if defined(BUILTIN_PLUGINS)
+} // namespace agspalrender
+#endif
+
+#endif
\ No newline at end of file
diff --git a/engines/ags/plugins/ags_pal_render/raycast.cpp b/engines/ags/plugins/ags_pal_render/raycast.cpp
new file mode 100644
index 0000000000..9ce5d5c343
--- /dev/null
+++ b/engines/ags/plugins/ags_pal_render/raycast.cpp
@@ -0,0 +1,1498 @@
+/*
+Copyright (c) 2004-2007, Lode Vandevenne
+
+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.
+
+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 OWNER 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.
+*/
+
+#include "raycast.h"
+
+#include <cmath>
+#include <string>
+#include <vector>
+#include <iostream>
+#include <algorithm>
+#include <stdio.h>
+#include <math.h>
+
+#if defined(BUILTIN_PLUGINS)
+namespace agspalrender {
+#endif
+
+#define PI         (3.1415926535f)
+
+//Variable Declaration
+bool raycastOn;
+double posX = 22.0, posY = 11.5; //x and y start position
+double dirX = -1.0, dirY = 0.0; //initial direction vector
+double planeX = 0.0, planeY = 0.77; //the 2d raycaster version of camera plane
+double moveSpeed = (1.0 / 60.0) * 3.0; //the constant value is in squares/second
+double rotSpeed = (1.0 / 60.0) * 2.0; //the constant value is in radians/second
+unsigned char worldMap[64][64];
+unsigned char lightMap[64][64];
+int ceilingMap[64][64];
+int floorMap[64][64];
+int heightMap[64][64];
+unsigned char seenMap[64][64];
+//int mapWidth;
+//int mapHeight;
+#define mapWidth 64
+#define mapHeight 64
+int textureSlot;
+int ambientlight;
+int ambientweight = 0;
+int ambientcolor = 0;
+int ambientcolorAmount = 0;
+
+Sprite sprite[numSprites] = {};
+
+
+#define sWidth 320
+#define sHeight 160
+
+int editorMap [sWidth][sHeight] = {};
+
+unsigned char texture[MAX_TEXTURES][texWidth * texHeight];
+
+wallType wallData[256] = {};
+
+//arrays used to sort the sprites
+int spriteOrder[numSprites];
+double spriteTransformX[numSprites];
+double spriteTransformY[numSprites];
+
+unsigned char **transcolorbuffer;
+unsigned char **transalphabuffer;
+double **transzbuffer;
+bool *transslicedrawn;
+int *transwallblendmode;
+double **ZBuffer;
+double *distTable;
+short *interactionmap;
+int skybox = 0;
+bool heightmapOn;
+
+int noclip = 0;
+
+int selectedX;
+int selectedY;
+unsigned char selectedColor;
+
+void Ray_SelectTile(int x, int y, unsigned char color) {
+	if (x < 0 || x > mapWidth) selectedX = -1;
+	else if (y < 0 || y > mapWidth) selectedY = -1;
+	else {
+		selectedX = x;
+		selectedY = y;
+		selectedColor = color;
+	}
+}
+
+int Ray_HasSeenTile(int x, int y) {
+	if (x < 0 || x > mapWidth) return -1;
+	else if (y < 0 || y > mapWidth) return -1;
+	return seenMap [x][y];
+}
+
+void Ray_SetNoClip(int value) {
+	noclip = value;
+}
+
+int Ray_GetNoClip() {
+	return noclip;
+}
+
+void Ray_DrawTile(int spr, int tile) {
+	BITMAP *sprite = engine->GetSpriteGraphic(spr);
+	unsigned char **sprarray = engine->GetRawBitmapSurface(sprite);
+	for (int y = 0; y < 64; ++y)
+		for (int x = 0; x < 64; ++x)
+			sprarray [y][x] = texture [tile][(texWidth * y) + x];
+	engine->ReleaseBitmapSurface(sprite);
+}
+
+void Ray_DrawOntoTile(int spr, int tile) {
+	BITMAP *sprite = engine->GetSpriteGraphic(spr);
+	unsigned char **sprarray = engine->GetRawBitmapSurface(sprite);
+	for (int y = 0; y < 64; ++y)
+		for (int x = 0; x < 64; ++x)
+			texture [tile][(texWidth * y) + x] = sprarray [y][x];
+	engine->ReleaseBitmapSurface(sprite);
+}
+
+int Ray_GetTileX_At(int x, int y) {
+	if (x < 0 || x > 319  || y < 0 || y > 159) return -1;
+	else return editorMap [x][y] >> 16;
+}
+
+int Ray_GetTileY_At(int x, int y) {
+	if (x < 0 || x > 319  || y < 0 || y > 159) return -1;
+	else return editorMap [x][y] & 0x0000FFFF;
+}
+
+void Ray_SetWallAt(int x, int y, int id) {
+	if (x < 0 || x >= mapWidth) return;
+	if (y < 0 || y >= mapHeight) return;
+	worldMap [x][y] = id;
+}
+
+int Ray_GetWallAt(int x, int y) {
+	if (x < 0 || x >= mapWidth) return -1;
+	if (y < 0 || y >= mapHeight) return -1;
+	return worldMap [x][y];
+}
+
+int Ray_GetAmbientWeight() {
+	return ambientweight;
+}
+
+void Ray_SetAmbientLight(int value) {
+	ambientlight = std::min(255, std::max(0, value));
+}
+
+void Ray_SetAmbientColor(int color, int amount) {
+	ambientcolor = color;
+	ambientcolorAmount = amount;
+}
+
+int Ray_GetAmbientLight() {
+	return ambientlight;
+}
+double fsqrt(double y) {
+	double x, z, tempf;
+	unsigned long *tfptr = ((unsigned long *)&tempf) + 1;
+
+	tempf = y;
+	*tfptr = (0xbfcdd90a - *tfptr) >> 1; /* estimate of 1/sqrt(y) */
+	x =  tempf;
+	z =  y * 0.5;                      /* hoist out the �/2�    */
+	x = (1.5 * x) - (x * x) * (x * z); /* iteration formula     */
+	x = (1.5 * x) - (x * x) * (x * z);
+	x = (1.5 * x) - (x * x) * (x * z);
+	x = (1.5 * x) - (x * x) * (x * z);
+	x = (1.5 * x) - (x * x) * (x * z);
+	return x * y;
+}
+
+void Ray_SetWallHotspot(int id, char hotsp) {
+	wallData[id].hotspotinteract = hotsp;
+}
+
+void Ray_SetWallTextures(int id, int n, int s, int w, int e) {
+	wallData[id].texture[0] = n;
+	wallData[id].texture[1] = s;
+	wallData[id].texture[2] = w;
+	wallData[id].texture[3] = e;
+}
+
+void Ray_SetWallSolid(int id, int n, int s, int w, int e) {
+	wallData[id].solid [0] = std::max(0, std::min(n, 1));
+	wallData[id].solid [1] = std::max(0, std::min(s, 1));
+	wallData[id].solid [2] = std::max(0, std::min(w, 1));
+	wallData[id].solid [3] = std::max(0, std::min(e, 1));
+}
+
+void Ray_SetWallIgnoreLighting(int id, int n, int s, int w, int e) {
+	wallData[id].ignorelighting [0] = std::max(0, std::min(n, 1));
+	wallData[id].ignorelighting [1] = std::max(0, std::min(s, 1));
+	wallData[id].ignorelighting [2] = std::max(0, std::min(w, 1));
+	wallData[id].ignorelighting [3] = std::max(0, std::min(e, 1));
+}
+
+void Ray_SetWallAlpha(int id, int n, int s, int w, int e) {
+	wallData[id].alpha [0] = std::max(0, std::min(n, 255));
+	wallData[id].alpha [1] = std::max(0, std::min(s, 255));
+	wallData[id].alpha [2] = std::max(0, std::min(w, 255));
+	wallData[id].alpha [3] = std::max(0, std::min(e, 255));
+}
+
+void Ray_SetWallBlendType(int id, int n, int s, int w, int e) {
+	wallData[id].blendtype [0] = std::max(0, std::min(n, 10));
+	wallData[id].blendtype [1] = std::max(0, std::min(s, 10));
+	wallData[id].blendtype [2] = std::max(0, std::min(w, 10));
+	wallData[id].blendtype [3] = std::max(0, std::min(e, 10));
+}
+
+
+
+
+int Ray_GetWallHotspot(int id) {
+	return wallData[id].hotspotinteract;
+}
+
+int Ray_GetWallTexture(int id, int dir) {
+	return wallData[id].texture[dir];
+}
+
+int Ray_GetWallSolid(int id, int dir) {
+	return wallData[id].solid [dir];
+}
+
+int Ray_GetWallIgnoreLighting(int id, int dir) {
+	return wallData[id].ignorelighting [dir];
+}
+
+int Ray_GetWallAlpha(int id, int dir) {
+	return wallData[id].alpha [dir];
+}
+
+int Ray_GetWallBlendType(int id, int dir) {
+	return wallData[id].blendtype [dir];
+}
+
+
+
+
+
+FLOAT_RETURN_TYPE Ray_GetMoveSpeed() {
+	float mSpeed = (float)moveSpeed;
+	RETURN_FLOAT(mSpeed);
+}
+
+
+void Ray_SetMoveSpeed(SCRIPT_FLOAT(speed)) {
+	INIT_SCRIPT_FLOAT(speed);
+	moveSpeed = (double)speed;
+}
+
+FLOAT_RETURN_TYPE Ray_GetRotSpeed() {
+	float rSpeed = (float)rotSpeed;
+	RETURN_FLOAT(rSpeed);
+}
+
+void Ray_SetRotSpeed(SCRIPT_FLOAT(speed)) {
+	INIT_SCRIPT_FLOAT(speed);
+	rotSpeed = (double)speed;
+}
+
+
+int Ray_GetLightAt(int x, int y) {
+	return lightMap [x][y];
+}
+
+void Ray_SetLightAt(int x, int y, int light) {
+	lightMap [x][y] = light;
+}
+
+void Ray_SetPlaneY(SCRIPT_FLOAT(y)) {
+	INIT_SCRIPT_FLOAT(y);
+	planeY = (double)y;
+}
+
+FLOAT_RETURN_TYPE Ray_GetPlaneY() {
+	float pY = (float)planeY;
+	RETURN_FLOAT(pY);
+}
+
+void Ray_SetPlayerPosition(SCRIPT_FLOAT(x), SCRIPT_FLOAT(y)) {
+	INIT_SCRIPT_FLOAT(x);
+	INIT_SCRIPT_FLOAT(y);
+	posX = (double)x;
+	posY = (double)y;
+}
+
+FLOAT_RETURN_TYPE Ray_GetPlayerX() {
+
+	float x = (float)posX;
+	RETURN_FLOAT(x);
+}
+
+FLOAT_RETURN_TYPE Ray_GetPlayerY() {
+	float y = (float)posY;
+	RETURN_FLOAT(y);
+}
+
+int Ray_GetPlayerAngle() {
+	double bgrad = atan2(dirY, dirX);
+	int bgdeg = (int)(bgrad / PI * 180.0) + 180;
+	return bgdeg % 360;
+}
+
+void Ray_SetPlayerAngle(int angle) {
+	int realangle = angle % 360;
+	if (realangle < 0) realangle += 360;
+
+	int anglediff = realangle - Ray_GetPlayerAngle();
+	double radians = 0.0174533 * anglediff;
+	double oldDirX = dirX;
+	dirX = dirX * cos(radians) - dirY * sin(radians);
+	dirY = oldDirX * sin(radians) + dirY * cos(radians);
+	double oldPlaneX = planeX;
+	planeX = planeX * cos(radians) - planeY * sin(radians);
+	planeY = oldPlaneX * sin(radians) + planeY * cos(radians);
+}
+
+
+void LoadHeightMap(int heightmapSlot) {
+	int tempw = engine->GetSpriteWidth(heightmapSlot);
+	int temph = engine->GetSpriteHeight(heightmapSlot);
+	if (tempw != mapWidth || temph != mapHeight) engine->AbortGame("LoadHeightMap: Map sizes are mismatched!");
+	BITMAP *heightmapBm = engine->GetSpriteGraphic(heightmapSlot);
+	if (!heightmapBm) engine->AbortGame("LoadHeightMap: Cannot load sprite into memory.");
+	unsigned char **hmArray = engine->GetRawBitmapSurface(heightmapBm);
+
+	for (int i = 0; i < tempw; i++) {
+		for (int j = 0; j < temph; j++) {
+			heightMap[i][j] = hmArray[i][j];
+		}
+	}
+	engine->ReleaseBitmapSurface(heightmapBm);
+	heightmapOn = true;
+}
+
+void LoadMap(int worldmapSlot, int lightmapSlot, int ceilingmapSlot, int floormapSlot) {
+	int tempw = engine->GetSpriteWidth(worldmapSlot);
+	int temph = engine->GetSpriteHeight(worldmapSlot);
+	BITMAP *worldmapBm;
+	BITMAP *lightmapBm;
+	BITMAP *floormapBm;
+	BITMAP *ceilingmapBm;
+	unsigned char **wmArray;
+	unsigned char **lmArray;
+	unsigned char **fmArray;
+	unsigned char **cmArray;
+	worldmapBm = engine->GetSpriteGraphic(worldmapSlot);
+	if (!worldmapBm) engine->AbortGame("LoadMap: Couldn't load worldmap sprite into memory.");
+	wmArray = engine->GetRawBitmapSurface(worldmapBm);
+	if (engine->GetSpriteWidth(lightmapSlot) != tempw || engine->GetSpriteHeight(lightmapSlot) != temph) engine->AbortGame("LoadMap: Lightmap has different dimensions to worldmap.");
+	else {
+		lightmapBm = engine->GetSpriteGraphic(lightmapSlot);
+		if (!lightmapBm) engine->AbortGame("LoadMap: Couldn't load lightmap sprite into memory.");
+		lmArray = engine->GetRawBitmapSurface(lightmapBm);
+	}
+	if (engine->GetSpriteWidth(ceilingmapSlot) != tempw || engine->GetSpriteHeight(ceilingmapSlot) != temph) engine->AbortGame("LoadMap: Ceilingmap has different dimensions to worldmap.");
+	else {
+		ceilingmapBm = engine->GetSpriteGraphic(ceilingmapSlot);
+		if (!ceilingmapBm) engine->AbortGame("LoadMap: Couldn't load ceilingmap sprite into memory.");
+		cmArray = engine->GetRawBitmapSurface(ceilingmapBm);
+	}
+	if (engine->GetSpriteWidth(floormapSlot) != tempw || engine->GetSpriteHeight(floormapSlot) != temph) engine->AbortGame("LoadMap: Floormap has different dimensions to worldmap.");
+	else {
+		floormapBm = engine->GetSpriteGraphic(floormapSlot);
+		if (!floormapBm) engine->AbortGame("LoadMap: Couldn't load floormap sprite into memory.");
+		fmArray = engine->GetRawBitmapSurface(floormapBm);
+	}
+	for (int i = 0; i < tempw; i++) {
+		for (int j = 0; j < temph; j++) {
+			worldMap[i][j] = wmArray[i][j];
+			lightMap[i][j] = lmArray[i][j];
+			floorMap[i][j] = fmArray[i][j];
+			ceilingMap[i][j] = cmArray[i][j];
+			heightMap[i][j] = 0;
+			seenMap[i][j] = 0;
+		}
+	}
+	engine->ReleaseBitmapSurface(worldmapBm);
+	engine->ReleaseBitmapSurface(lightmapBm);
+	engine->ReleaseBitmapSurface(ceilingmapBm);
+	engine->ReleaseBitmapSurface(floormapBm);
+	//LoadHeightMap (31); //debug only
+}
+
+FLOAT_RETURN_TYPE Ray_GetSpriteScaleX(int id) {
+	float scale = (float)sprite[id].uDivW;
+	RETURN_FLOAT(scale);
+}
+
+void Ray_SetSpriteScaleX(int id, SCRIPT_FLOAT(scale)) {
+	INIT_SCRIPT_FLOAT(scale);
+	sprite[id].uDivW = scale;
+}
+
+FLOAT_RETURN_TYPE Ray_GetSpriteScaleY(int id) {
+	float scale = (float)sprite[id].uDivH;
+	RETURN_FLOAT(scale);
+}
+
+void Ray_SetSpriteScaleY(int id, SCRIPT_FLOAT(scale)) {
+	INIT_SCRIPT_FLOAT(scale);
+	sprite[id].uDivH = scale;
+}
+
+int Ray_GetSpriteAlpha(int id) {
+	return sprite[id].alpha;
+}
+
+void Ray_SetSpriteAlpha(int id, int alpha) {
+	sprite[id].alpha = alpha;
+}
+
+int Ray_GetSpritePic(int id) {
+	return sprite[id].texture;
+}
+
+void Ray_SetSpritePic(int id, int slot) {
+	sprite[id].texture = slot;
+}
+
+
+
+int Ray_GetSpriteAngle(int id) {
+	return sprite[id].angle;
+}
+
+void Ray_SetSpriteAngle(int id, int angle) {
+	sprite[id].angle = angle % 360;
+}
+
+int Ray_GetSpriteInteractObj(int id) {
+	return sprite[id].objectinteract;
+}
+
+void Ray_SetSpriteView(int id, int view) {
+	sprite[id].view = view;
+}
+
+void Ray_SetSpriteBlendType(int id, int type) {
+	sprite[id].blendmode = type;
+}
+
+int Ray_GetSpriteBlendType(int id) {
+	return sprite[id].blendmode;
+}
+
+
+int Ray_GetSpriteView(int id) {
+	return sprite[id].view;
+}
+
+void Ray_SetSpriteFrame(int id, int frame) {
+	sprite[id].frame = frame;
+}
+
+int Ray_GetSpriteFrame(int id) {
+	return sprite[id].frame;
+}
+
+void Ray_SetSpriteInteractObj(int id, int obj) {
+	sprite[id].objectinteract = obj;
+}
+
+void Ray_SetSpritePosition(int id, SCRIPT_FLOAT(x), SCRIPT_FLOAT(y)) {
+	INIT_SCRIPT_FLOAT(x);
+	INIT_SCRIPT_FLOAT(y);
+	sprite[id].x = x;
+	sprite[id].y = y;
+}
+
+void Ray_SetSpriteVertOffset(int id, SCRIPT_FLOAT(vMove)) {
+	INIT_SCRIPT_FLOAT(vMove);
+	sprite[id].vMove = vMove;
+}
+
+
+FLOAT_RETURN_TYPE Ray_GetSpriteVertOffset(int id) {
+	float x = (float)sprite[id].vMove;
+	RETURN_FLOAT(x);
+}
+
+FLOAT_RETURN_TYPE Ray_GetSpriteX(int id) {
+	float x = (float)sprite[id].x;
+	RETURN_FLOAT(x);
+}
+
+FLOAT_RETURN_TYPE Ray_GetSpriteY(int id) {
+	float y = (float)sprite[id].y;
+	RETURN_FLOAT(y);
+}
+
+void Ray_InitSprite(int id, SCRIPT_FLOAT(x), SCRIPT_FLOAT(y), int slot, unsigned char alpha, int blendmode, SCRIPT_FLOAT(scale_x), SCRIPT_FLOAT(scale_y), SCRIPT_FLOAT(vMove)) {
+	INIT_SCRIPT_FLOAT(x);
+	INIT_SCRIPT_FLOAT(y);
+	INIT_SCRIPT_FLOAT(scale_x);
+	INIT_SCRIPT_FLOAT(scale_y);
+	INIT_SCRIPT_FLOAT(vMove);
+	sprite[id].x = x;
+	sprite[id].y = y;
+	sprite[id].texture = slot;
+	sprite[id].alpha = alpha;
+	sprite[id].blendmode = blendmode;
+	sprite[id].uDivW = scale_x;
+	sprite[id].uDivH = scale_y;
+	sprite[id].vMove = vMove;
+}
+
+//function used to sort the sprites
+void combSort(int *order, double *dist, int amount);
+
+void MakeTextures(int slot) {
+	textureSlot = slot;
+	int sourceWidth = engine->GetSpriteWidth(slot);
+	int sourceHeight = engine->GetSpriteHeight(slot);
+	int max = (sourceWidth / texWidth) * (sourceHeight / texHeight);
+	if (max > MAX_TEXTURES) engine->AbortGame("MakeTextures: Source file has too many tiles to load.");
+	BITMAP *texspr = engine->GetSpriteGraphic(slot);
+	unsigned char **texbuffer = engine->GetRawBitmapSurface(texspr);
+	int numTilesX = sourceWidth / texWidth;
+	int numTilesY = sourceHeight / texHeight;
+	int totaltiles = numTilesX * numTilesY;
+	for (int numX = 0; numX < numTilesX; ++numX) {
+		for (int numY = 0; numY < numTilesY; ++numY) {
+			for (int x = 0; x < texWidth; ++x)
+				for (int y = 0; y < texHeight; ++y) {
+					texture[(numY * numTilesX) + numX][(texWidth * y) + x] = texbuffer [y + (texHeight * numY)][x + (texWidth * numX)];
+				}
+		}
+	}
+	engine->ReleaseBitmapSurface(texspr);
+
+	for (int i = 0; i < 11; i++) {
+		for (int j = 0; j < 4; j++) {
+			wallData[i].texture[j] = i;
+			if (i == 10) wallData[i].texture[j] = 11;
+			if (i > 0) wallData[i].solid[j] = 1;
+			else wallData[i].solid[j] = 0;
+			if (i != 10) wallData[i].alpha[j] = 255;
+			else {
+				wallData[i].alpha[j] = 128;
+				wallData[i].blendtype[j] = 0;
+				wallData[i].solid[j] = 0;
+			}
+		}
+	}
+	wallData[1].texture[0] = 1;
+	wallData[1].texture[1] = 2;
+	wallData[1].texture[2] = 3;
+	wallData[1].texture[3] = 4;
+	wallData[1].solid[0] = 0;
+
+
+
+}
+
+//double ZBuffer[screenWidth][screenHeight];
+
+void Ray_SetFloorAt(int x, int y, int tex) {
+	if (x < 0 || x > mapWidth || y < 0 || y > mapHeight || tex > 511) return;
+	else floorMap[x][y] = tex;
+}
+
+void Ray_SetCeilingAt(int x, int y, int tex) {
+	if (x < 0 || x > mapWidth || y < 0 || y > mapHeight || tex > 511) return;
+	else ceilingMap[x][y] = tex;
+}
+
+int Ray_GetCeilingAt(int x, int y) {
+	if (x < 0 || x > mapWidth || y < 0 || y > mapHeight) return -1;
+	else return ceilingMap [x][y];
+}
+
+
+int Ray_GetFloorAt(int x, int y) {
+	if (x < 0 || x > mapWidth || y < 0 || y > mapHeight) return -1;
+	else return floorMap [x][y];
+}
+
+
+int Ray_GetLightingAt(int x, int y) {
+	if (x < 0 || x > mapWidth || y < 0 || y > mapHeight) return -1;
+	else {
+		int lighting = 0;
+		if (ceilingMap[x][y] == 0) {
+			lighting = ambientlight;
+			if (ambientlight < lightMap [x][y]) lighting = lightMap[x][y];
+		}
+		return lighting;
+	}
+}
+
+void Ray_SetLightingAt(int x, int y, unsigned char lighting) {
+	if (x < 0 || x > mapWidth || y < 0 || y > mapHeight) return;
+	else {
+		lightMap [x][y] = lighting;
+	}
+}
+
+void Ray_SetSkyBox(int slot) {
+	BITMAP *test = engine->GetSpriteGraphic(slot);
+	if (test) {
+		skybox = slot;
+	} else engine->AbortGame("Ray_SetSkybox: No such sprite!");
+}
+
+int Ray_GetSkyBox(int slot) {
+	return skybox;
+}
+
+int Ray_GetHotspotAt(int x, int y) {
+	if (!interactionmap) return -1;
+	else if (x > sWidth || x < 0 || y > sHeight || y < 0) return -1;
+	else return interactionmap [x * sWidth + y] & 0x00FF;
+}
+
+int Ray_GetObjectAt(int x, int y) {
+	if (!interactionmap) return -1;
+	else if (x > sWidth || x < 0 || y > sHeight || y < 0) return -1;
+	else return interactionmap [x * sWidth + y] >> 8;
+}
+
+FLOAT_RETURN_TYPE Ray_GetDistanceAt(int x, int y) {
+	float falsereturn = -1.0f;
+	if (!ZBuffer) {
+		RETURN_FLOAT(falsereturn);
+	} else if (x > sWidth || x < 0 || y > sHeight || y < 0) {
+		RETURN_FLOAT(falsereturn);
+	} else {
+
+		float zbuf = (float)ZBuffer[x][y];
+		RETURN_FLOAT(zbuf);
+	}
+}
+
+void Init_Raycaster() {
+	if (ZBuffer) return;
+	if (!worldMap) return;
+	transcolorbuffer = new unsigned char *[sWidth];
+	transalphabuffer = new unsigned char *[sWidth];
+	transslicedrawn = new bool[sWidth]();
+	transzbuffer = new double*[sWidth];
+	transwallblendmode = new int [mapWidth]();
+	ZBuffer = new double*[sWidth];
+	distTable = new double[sHeight + (sHeight >> 1)];
+	interactionmap = new short[sWidth * sHeight]();
+	for (int y = 0; y < sHeight + (sHeight >> 1); y++) {
+		distTable [y] = sHeight / (2.0 * y - sHeight);
+	}
+	for (int x = 0; x < sWidth; x++) {
+		transcolorbuffer[x] = new unsigned char [sHeight * (mapWidth)]();
+		transalphabuffer[x] = new unsigned char [sHeight * (mapWidth)]();
+		transzbuffer[x] = new double [sHeight * (mapWidth)]();
+		ZBuffer[x] = new double [sHeight]();
+		transslicedrawn [x] = false;
+	}
+}
+
+bool rendering;
+void Raycast_Render(int slot) {
+	ambientweight = 0;
+	raycastOn = true;
+	double playerrad = atan2(dirY, dirX) + (2.0 * PI);
+	rendering = true;
+	int32 w = sWidth, h = sHeight;
+	BITMAP *screen = engine->GetSpriteGraphic(slot);
+	if (!screen) engine->AbortGame("Raycast_Render: No valid sprite to draw on.");
+	engine->GetBitmapDimensions(screen, &w, &h, nullptr);
+	BITMAP *sbBm = engine->GetSpriteGraphic(skybox);
+	if (!sbBm) engine->AbortGame("Raycast_Render: No valid skybox sprite.");
+	if (skybox > 0) {
+		int bgdeg = (int)((playerrad / PI) * 180.0) + 180;
+		int xoffset = (int)(playerrad * 320.0);
+		BITMAP *virtsc = engine->GetVirtualScreen();
+		engine->SetVirtualScreen(screen);
+		xoffset = abs(xoffset % w);
+		if (xoffset > 0) {
+			engine->BlitBitmap(xoffset - 320, 1, sbBm, false);
+		}
+		engine->BlitBitmap(xoffset, 1, sbBm, false);
+		engine->SetVirtualScreen(virtsc);
+	}
+	int transwallcount = 0;
+	unsigned char **buffer = engine->GetRawBitmapSurface(screen);
+	for (int x = 0; x < w; x++) {
+		transslicedrawn [x] = false;
+		for (int y = 0; y < h; y++) {
+			ZBuffer[x][y] = 0;
+		}
+	}
+	int multiplier = mapWidth;
+	memset(interactionmap, 0, sizeof(short) * (sHeight * sWidth));
+	//start the main loop
+	for (int x = 0; x < w; x++) {
+		transwallcount = 0;
+		//calculate ray position and direction
+		double cameraX = 2 * x / double(w) - 1; //x-coordinate in camera space
+		double rayPosX = posX;
+		double rayPosY = posY;
+		double rayDirX = dirX + planeX * cameraX;
+		double rayDirY = dirY + planeY * cameraX;
+
+		//which box of the map we're in
+		int mapX = int(rayPosX);
+		int mapY = int(rayPosY);
+
+		//length of ray from current position to next x or y-side
+		double sideDistX;
+		double sideDistY;
+
+		//length of ray from one x or y-side to next x or y-side
+		double deltaDistX = fsqrt(1 + (rayDirY * rayDirY) / (rayDirX * rayDirX));
+		double deltaDistY = fsqrt(1 + (rayDirX * rayDirX) / (rayDirY * rayDirY));
+		double perpWallDist;
+
+		//what direction to step in x or y-direction (either +1 or -1)
+		int stepX;
+		int stepY;
+		int prevmapX = 0;
+		int prevmapY = 0;
+		int hit = 0; //was there a wall hit?
+		int side; //was a NS or a EW wall hit?
+
+		//calculate step and initial sideDist
+		if (rayDirX < 0) {
+			stepX = -1;
+			sideDistX = (rayPosX - mapX) * deltaDistX;
+		} else {
+			stepX = 1;
+			sideDistX = (mapX + 1.0 - rayPosX) * deltaDistX;
+		}
+		if (rayDirY < 0) {
+			stepY = -1;
+			sideDistY = (rayPosY - mapY) * deltaDistY;
+		} else {
+			stepY = 1;
+			sideDistY = (mapY + 1.0 - rayPosY) * deltaDistY;
+		}
+		//perform DDA
+		bool deeper = true;
+		bool opposite = true;
+		bool oppositedrawn = false;
+		double wallX; //where exactly the wall was hit
+		int drawStart;
+		int drawEnd;
+		while (hit == 0 && deeper == true) {
+			if (opposite) {
+				rayDirX = -rayDirX;
+				rayDirY = -rayDirY;
+				stepX = -stepX;
+				stepY = -stepY;
+				if (sideDistX < sideDistY) side = 0;
+				else side = 1;
+			} else if (sideDistX < sideDistY) { //jump to next map square, OR in x-direction, OR in y-direction
+				sideDistX += deltaDistX;
+				mapX += stepX;
+				mapX = abs(mapX) % mapHeight;
+				side = 0;
+				if (oppositedrawn && worldMap[mapX][mapY] > 8) {
+					opposite = true;
+					oppositedrawn = false;
+					rayDirX = -rayDirX;
+					rayDirY = -rayDirY;
+					stepX = -stepX;
+					stepY = -stepY;
+					if (sideDistX < sideDistY) side = 0;
+					else side = 1;
+				} else {
+					oppositedrawn = false;
+					opposite = false;
+				}
+			} else {
+				sideDistY += deltaDistY;
+				mapY += stepY;
+				mapY = abs(mapY) % mapHeight;
+				side = 1;
+				if (oppositedrawn && worldMap[mapX][mapY] > 8) {
+					opposite = true;
+					oppositedrawn = false;
+					rayDirX = -rayDirX;
+					rayDirY = -rayDirY;
+					stepX = -stepX;
+					stepY = -stepY;
+					if (sideDistX < sideDistY) side = 0;
+					else side = 1;
+				} else {
+					oppositedrawn = false;
+					opposite = false;
+				}
+			}
+			int texside;
+			if (rayDirX > 0 && side == 0) texside = 0;
+			if (rayDirX < 0 && side == 0) texside = 1;
+			if (rayDirY > 0 && side == 1) texside = 2;
+			if (rayDirY < 0 && side == 1) texside = 3;
+
+			//set this tile as seen.
+			seenMap[mapX][mapY] = 1;
+			//Check if ray has hit a wall
+			if (wallData[worldMap[mapX][mapY]].texture[texside]) {
+				bool ambientpixels = false;
+				hit = 1; //Set this to true so that by default, it's impossible to hang the engine.
+				deeper = false; //Set this to false so that we don't go deeper than we need to.
+
+				//Calculate distance of perpendicular ray (oblique distance will give fisheye effect!)
+				if (side == 0) perpWallDist = fabs((mapX - rayPosX + (1 - stepX) / 2) / rayDirX);
+				else       perpWallDist = fabs((mapY - rayPosY + (1 - stepY) / 2) / rayDirY);
+				//Calculate height of line to draw on screen
+				int lineHeight = abs(int(h / perpWallDist));
+
+				//calculate lowest and highest pixel to fill in current stripe
+				drawStart = -lineHeight / 2 + h / 2;
+				if (drawStart < 0) drawStart = 0;
+				drawEnd = lineHeight / 2 + h / 2;
+				if (drawEnd >= h) drawEnd = h;
+				//texturing calculations
+				int texNum = wallData[worldMap[mapX][mapY]].texture[texside] - 1; //1 subtracted from it so that texture 0 can be used!
+				if (!opposite) {
+					//calculate value of wallX
+					if (side == 1) wallX = rayPosX + ((mapY - rayPosY + (1 - stepY) / 2) / rayDirY) * rayDirX;
+					else       wallX = rayPosY + ((mapX - rayPosX + (1 - stepX) / 2) / rayDirX) * rayDirY;
+				} else {
+					if (side == 1) wallX = rayPosX + ((mapY - rayPosY + (1 - stepY) / 2) / -rayDirY) * -rayDirX;
+					else       wallX = rayPosY + ((mapX - rayPosX + (1 - stepX) / 2) / -rayDirX) * -rayDirY;
+				}
+				wallX -= floor((wallX));
+
+				//x coordinate on the texture
+				int wall_light = 255;
+				int texX = int(wallX * double(texWidth));
+				if (side == 0 && rayDirX > 0) texX = texWidth - texX - 1;
+				if (side == 1 && rayDirY < 0) texX = texWidth - texX - 1;
+				bool do_ambient = false;
+				if (!opposite) {
+					if (rayDirX > 0 && side == 0) {
+						wall_light = lightMap [(int)mapX - 1 % mapWidth][(int)mapY] << 5;
+						if (ceilingMap [(int)mapX - 1 % mapWidth][(int)mapY] <= 1) do_ambient = true;
+						else if (texture[ceilingMap [(int)mapX - 1 % mapWidth][(int)mapY] - 1][(texWidth * (63 - texX)) + 63] == 0) do_ambient = true;
+					}
+					if (rayDirX < 0 && side == 0) {
+						wall_light = lightMap [(int)mapX + 1 % mapWidth][(int)mapY] << 5;
+						if (ceilingMap [(int)mapX + 1 % mapWidth][(int)mapY] <= 1) do_ambient = true;
+						else if (texture[ceilingMap [(int)mapX + 1 % mapWidth][(int)mapY] - 1][(texWidth * texX) + 0] == 0) do_ambient = true;
+
+					}
+					if (rayDirY > 0 && side == 1) {
+						wall_light = lightMap [(int)mapX][(int)mapY - 1 % mapHeight] << 5;
+						if (ceilingMap [(int)mapX][(int)mapY - 1 % mapHeight] <= 1) do_ambient = true;
+						else if (texture[ceilingMap [(int)mapX][(int)mapY - 1 % mapHeight] - 1][(texWidth * 63) + texX] == 0) do_ambient = true;
+					}
+					if (rayDirY < 0 && side == 1) {
+						wall_light = lightMap [(int)mapX][(int)mapY + 1 % mapHeight] << 5;
+						if (ceilingMap [(int)mapX][(int)mapY + 1 % mapHeight] <= 1) do_ambient = true;
+						else if (texture[ceilingMap [(int)mapX][(int)mapY + 1 % mapHeight] - 1][(texWidth * 0) + 63 - texX] == 0) do_ambient = true;
+					}
+				} else if (opposite) {
+					wall_light = lightMap [(int)mapX][(int)mapY] << 5;
+					if (ceilingMap [(int)mapX][(int)mapY] <= 1) do_ambient = true;
+					if (rayDirX > 0 && side == 0) {
+						if (texture[ceilingMap [(int)mapX][(int)mapY] - 1][(texWidth * (63 - texX)) + 63] == 0) do_ambient = true;
+					}
+					if (rayDirX < 0 && side == 0) {
+						if (texture[ceilingMap [(int)mapX][(int)mapY] - 1][(texWidth * texX) + 63] == 0) do_ambient = true;
+					}
+					if (rayDirY > 0 && side == 1) {
+						if (texture[ceilingMap [(int)mapX][(int)mapY] - 1][(texWidth * 0) + (63 - texX)] == 0) do_ambient = true;
+					}
+					if (rayDirY < 0 && side == 1) {
+						if (texture[ceilingMap [(int)mapX][(int)mapY] - 1][(texWidth * 63) + texX] == 0) do_ambient = true;
+					}
+				}
+				if (do_ambient) {
+					ambientpixels = true;
+					wall_light = std::max(wall_light, ambientlight);
+				}
+				wall_light = std::min(255, std::max(0, wall_light));
+				bool alphastripe = false;
+				for (int y = drawStart; y < drawEnd; y++) {
+					if (ZBuffer[x][y] > perpWallDist || ZBuffer[x][y] == 0) { //We can draw.
+						int d = y * 256 - h * 128 + lineHeight * 128; //256 and 128 factors to avoid floats
+						int texY = ((d * texHeight) / lineHeight) / 256;
+						int color = texture[texNum][texWidth * texY + texX];
+						if (color > 0) {
+							if (ambientpixels && ambientcolor) color = Mix::MixColorMultiply(ambientcolor, color, ambientcolorAmount, 1);
+							if (!wallData[worldMap[mapX][mapY]].ignorelighting[texside] && wall_light < 255) color = Mix::MixColorLightLevel(color, wall_light);
+							if (wallData[worldMap[mapX][mapY]].alpha[texside] == 255 && wallData[worldMap[mapX][mapY]].mask[texside] == 0) {
+								buffer[y][x] = color;
+								if (ambientpixels) ambientweight++;
+								//SET THE ZBUFFER FOR THE SPRITE CASTING
+								ZBuffer[x][y] = perpWallDist; //perpendicular distance is used
+								interactionmap [x * sWidth + y] = wallData[worldMap[mapX][mapY]].hotspotinteract;
+								editorMap [x][y] = ((short)mapX) << 16 | ((short)mapY);
+							} else {
+								if (transslicedrawn[x] == false) {
+									memset(transcolorbuffer[x], 0, sizeof(unsigned char) * (sHeight * mapWidth));
+									memset(transalphabuffer[x], 0, sizeof(unsigned char) * (sHeight * mapWidth));
+									//memset (transzbuffer[x],0,sizeof(double)*(sHeight*mapWidth));
+									transslicedrawn[x] = true;
+								}
+								transwallblendmode[transwallcount] = wallData[worldMap[mapX][mapY]].blendtype[texside];
+								int transwalloffset = transwallcount * h;
+								transcolorbuffer[x][transwalloffset + y] = color;
+								if (ambientpixels) ambientweight++;
+								if (wallData[worldMap[mapX][mapY]].mask[texside] == 0) transalphabuffer[x][transwalloffset + y] = wallData[worldMap[mapX][mapY]].alpha[texside];
+								else {
+									transalphabuffer[x][transwalloffset + y] = (wallData[worldMap[mapX][mapY]].alpha[texside] + texture[wallData[worldMap[mapX][mapY]].mask[texside]][texWidth * texY + texX]) >> 1;
+								}
+								transzbuffer[x][transwalloffset + y] = perpWallDist;
+								hit = 0;
+								deeper = true;
+								alphastripe = true;
+							}
+						} else {
+							//We found transparency, we have to draw deeper.
+							deeper = true;
+							hit = 0;
+						}
+						if ((int)mapX == selectedX && (int)mapY == selectedY) {
+							if (texX == 0 || texX == 63 || texY == 0 || texY == 63) {
+								buffer[y][x] = selectedColor;
+								ZBuffer [x][y] = perpWallDist;
+							}
+						}
+
+					}
+				}
+				if (alphastripe) {
+					if (transwallcount < mapWidth) {
+						transwallcount++;
+					}
+					alphastripe = false;
+				}
+				if (opposite) {
+					if (mapX == 0 || mapX == mapWidth || mapY == 0 || mapY == mapHeight) {
+						deeper = false;
+						hit = 0;
+					}
+					oppositedrawn = true;
+					if (deeper) opposite = false;
+					rayDirX = -rayDirX;
+					rayDirY = -rayDirY;
+					stepX = -stepX;
+					stepY = -stepY;
+				} else if (!opposite && deeper) {
+					opposite = true;
+					prevmapX = mapX;
+					prevmapY = mapY;
+				}
+				//End of wall drawing functions.
+			} else if (opposite) {
+				opposite = false;
+				//oppositedrawn = false;
+				rayDirX = -rayDirX;
+				rayDirY = -rayDirY;
+				stepX = -stepX;
+				stepY = -stepY;
+			} else if (!opposite && deeper) {
+				opposite = true;
+				prevmapX = mapX;
+				prevmapY = mapY;
+			}
+			//End of loop.
+		}
+
+		//FLOOR CASTING
+
+		double floorXWall, floorYWall; //x, y position of the floor texel at the bottom of the wall
+		//4 different wall directions possible
+		if (side == 0 && rayDirX > 0) {
+			floorXWall = mapX;
+			floorYWall = mapY + wallX;
+			if (opposite) floorXWall = floorXWall + 1.0;
+		} else if (side == 0 && rayDirX < 0) {
+			floorXWall = mapX + 1.0;
+			floorYWall = mapY + wallX;
+			if (opposite) floorXWall = floorXWall - 1.0;
+		} else if (side == 1 && rayDirY > 0) {
+			floorXWall = mapX + wallX;
+			floorYWall = mapY;
+			if (opposite) floorYWall = floorYWall + 1.0;
+		} else {
+			floorXWall = mapX + wallX;
+			floorYWall = mapY + 1.0;
+			if (opposite) floorYWall = floorYWall - 1.0;
+		}
+
+		double distWall, distPlayer, currentDist;
+
+		distWall = perpWallDist;
+		distPlayer = 0.0;
+		if (drawEnd < 0) drawEnd = h - 1; //becomes < 0 when the integer overflows
+		//draw the floor from drawEnd to the bottom of the screen
+		int drawdist = h;
+		int expandeddraw = h >> 1;
+		for (int y = drawEnd; y < drawdist + expandeddraw; y++) {
+			//currentDist = h / (2.0 * y - h); //you could make a small lookup table for this instead
+			currentDist = distTable[y];
+			if (y > h - 1) {
+				if (!heightMap) break;
+				double weight = (currentDist - distPlayer) / (distWall - distPlayer);
+
+				double currentFloorX = weight * floorXWall + (1.0 - weight) * posX;
+				double currentFloorY = weight * floorYWall + (1.0 - weight) * posY;
+
+				int floorTexX, floorTexY;
+				int cmapX = (int)currentFloorX;
+				if (cmapX > mapWidth - 1) cmapX = mapWidth - 1;
+				if (cmapX < 0) cmapX = 0;
+				int cmapY = (int)currentFloorY;
+				if (cmapY > mapHeight - 1) cmapY = mapHeight - 1;
+				if (cmapY < 0) cmapY = 0;
+				if (heightMap[cmapX][cmapY] - 1 < 1) continue;
+				int lighting = lightMap [cmapX][cmapY] << 5;
+				lighting = std::min(255, std::max(0, lighting));
+				floorTexX = int(currentFloorX * texWidth) % texWidth;
+				floorTexY = int(currentFloorY * texHeight) % texHeight;
+				int floorcolor = 0;
+				int ceilingcolor = 0;
+				int texpos = texWidth * floorTexY + floorTexX;
+				if (ceilingMap[cmapX][cmapY] - 1 > 0) {
+					ceilingcolor = texture[ceilingMap[cmapX][cmapY] - 1][texWidth * floorTexY + floorTexX];
+				}
+				if (floorMap[cmapX][cmapY] - 1 > 0) {
+					floorcolor = texture[floorMap[cmapX][cmapY] - 1][texpos];
+				} else continue;
+				if (ceilingcolor == 0) {
+					lighting = std::max(lighting, ambientlight);
+					ambientweight ++;
+				}
+				if (lighting < 255) {
+					if (floorcolor) floorcolor = Mix::MixColorLightLevel(floorcolor, lighting);
+				}
+
+				if (heightMap && floorcolor > 0) {
+					if (heightMap[cmapX][cmapY] - 1 > 0) {
+						int raisedfloorstart = y - (int)(texture[heightMap[cmapX][cmapY] - 1][texpos] / currentDist);
+						if (raisedfloorstart > h - 1) continue;
+						if (raisedfloorstart < 0) raisedfloorstart = 0;
+						for (int ny = raisedfloorstart; ny < y; ny++) {
+							if (ny < h && (ZBuffer[x][ny] > currentDist || ZBuffer[x][ny] == 0)) {
+								ZBuffer[x][ny] = currentDist; //perpendicular distance is used
+								buffer[ny][x] = floorcolor;
+								interactionmap [x * sWidth + ny] = 0;
+								editorMap [x][ny] = ((short)mapX) << 16 | ((short)mapY);
+							}
+						}
+						if (raisedfloorstart < y && y == h - 1 && y == h + expandeddraw) expandeddraw ++;
+					}
+				}
+			} else {
+				double weight = (currentDist - distPlayer) / (distWall - distPlayer);
+
+				double currentFloorX = weight * floorXWall + (1.0 - weight) * posX;
+				double currentFloorY = weight * floorYWall + (1.0 - weight) * posY;
+
+				int floorTexX, floorTexY;
+				int cmapX = (int)currentFloorX % mapWidth;
+				if (cmapX < 0) cmapX = 0;
+				int cmapY = (int)currentFloorY % mapHeight;
+				if (cmapY < 0) cmapY = 0;
+				int lighting = lightMap [cmapX][cmapY] << 5;
+				lighting = std::min(255, std::max(0, lighting));
+				floorTexX = int(currentFloorX * texWidth) % texWidth;
+				floorTexY = int(currentFloorY * texHeight) % texHeight;
+				int floorcolor = 0;
+				int ceilingcolor = 0;
+				if (floorMap[cmapX][cmapY] - 1 > 0) {
+					floorcolor = texture[floorMap[cmapX][cmapY] - 1][texWidth * floorTexY + floorTexX];
+				}
+				if (ceilingMap[cmapX][cmapY] - 1 > 0) {
+					ceilingcolor = texture[ceilingMap[cmapX][cmapY] - 1][texWidth * floorTexY + floorTexX];
+				}
+				if (ceilingcolor == 0) {
+					lighting = std::max(lighting, ambientlight);
+					ambientweight++;
+				}
+				if (lighting < 255) {
+					if (floorcolor) floorcolor = Mix::MixColorLightLevel(floorcolor, lighting);
+					if (ceilingcolor) ceilingcolor = Mix::MixColorLightLevel(ceilingcolor, lighting);
+				}
+
+				if (heightMap && floorcolor > 0 && (currentDist < ZBuffer[x][y] || ZBuffer[x][y] == 0)) {
+					if (heightMap[cmapX][cmapY] - 1 > 0) {
+						int raisedfloorstart = y - (int)(texture[heightMap[cmapX][cmapY] - 1][texWidth * floorTexY + floorTexX] / currentDist);
+						if (raisedfloorstart > h - 1) continue;
+						if (raisedfloorstart < 0) raisedfloorstart = 0;
+						for (int ny = raisedfloorstart; ny < y; ny++) {
+							if (ZBuffer[x][ny] > currentDist || ZBuffer[x][ny] == 0) {
+								ZBuffer[x][ny] = currentDist; //perpendicular distance is used
+								buffer[ny][x] = floorcolor;
+								interactionmap [x * sWidth + ny] = 0;
+								editorMap [x][ny] = ((short)cmapX) << 16 | ((short)cmapY);
+							}
+						}
+						if (raisedfloorstart < y && y == h - 1 && y == h + expandeddraw) expandeddraw ++;
+					}
+				}
+				//floor
+				//ceiling (symmetrical!)
+				//SET THE ZBUFFER FOR THE SPRITE CASTING
+				if (floorcolor > 0 && (currentDist < ZBuffer[x][y] || ZBuffer[x][y] == 0)) {
+					ZBuffer[x][y] = currentDist; //perpendicular distance is used
+					buffer[y][x] = floorcolor;
+					editorMap [x][y] = ((short)cmapX) << 16 | ((short)cmapY);
+				} else ZBuffer[x][y] = 9999999999999.0;
+				if (currentDist < ZBuffer[x][h - y] || ZBuffer[x][h - y] == 0) {
+					if (ceilingcolor > 0) {
+						ZBuffer[x][h - y] = currentDist; //perpendicular distance is used
+						buffer[h - y][x] = ceilingcolor;
+					} else ZBuffer[x][h - y] = 999999999999.0;
+					editorMap [x][h - y] = ((short)cmapX) << 16 | ((short)cmapY);
+				}
+				interactionmap [x * sWidth + y] = 0;
+				interactionmap [x * sWidth + (h - y)] = 0;
+				if ((int)cmapX == selectedX && (int)cmapY == selectedY) {
+					if (floorTexX == 0 || floorTexX == 63 || floorTexY == 0 || floorTexY == 63) {
+						buffer[y][x] = selectedColor;
+						ZBuffer [x][y] = perpWallDist;
+						buffer[h - y][x] = selectedColor;
+						ZBuffer [x][h - y] = perpWallDist;
+					}
+				}
+
+
+			}
+		}
+		//TRANSLUCENT WALL RENDERING
+		if (transslicedrawn[x] == true) {
+			for (int y = 0; y < h; y++) {
+				for (int transwalldrawn = 0; transwalldrawn < transwallcount; transwalldrawn++) {
+					int transwalloffset = transwalldrawn * h;
+					int color = transcolorbuffer[x][transwalloffset + y];
+					if (color != 0) {
+						if (transwallblendmode[transwalldrawn] == 0) buffer[y][x] = Mix::MixColorAlpha(color, buffer[y][x], transalphabuffer[x][transwalloffset + y]); //paint pixel if it isn't black, black is the invisible color
+						else if (transwallblendmode[transwalldrawn] == 1) buffer[y][x] = Mix::MixColorAdditive(color, buffer[y][x], transalphabuffer[x][transwalloffset + y]);
+						//if (ZBuffer[x][y] > transzbuffer[transwalldrawn*h+y]) ZBuffer[x][y] = transzbuffer[transwalldrawn*h+y]; //put the sprite on the zbuffer so we can draw around it.
+					}
+				}
+			}
+		}
+		//End of wall loop.
+	}
+
+
+	//SPRITE CASTING
+	//sort sprites from far to close
+
+	//Initialize Sprites for casting.
+	double invDet = 1.0 / (planeX * dirY - dirX * planeY);
+	for (int i = 0; i < numSprites; i++) {
+		spriteOrder[i] = i;
+		spriteTransformY[i] = ((posX - sprite[i].x) * (posX - sprite[i].x) + (posY - sprite[i].y) * (posY - sprite[i].y));
+	}
+	combSort(spriteOrder, spriteTransformY, numSprites);
+	for (int i = 0; i < numSprites; i++) {
+		double spriteX = sprite[spriteOrder[i]].x - posX;
+		double spriteY = sprite[spriteOrder[i]].y - posY;
+		spriteTransformX[i] = invDet * (dirY * spriteX - dirX * spriteY);
+		spriteTransformY[i] = invDet * (-planeY * spriteX + planeX * spriteY);
+	}
+
+	int transwalldraw = 0;
+	//after sorting the sprites, do the projection and draw them
+	for (int i = 0; i < numSprites; i++) {
+		int flipped = 0;
+		if (sprite[spriteOrder[i]].view != 0) {
+
+			double sprrad = atan2(sprite[spriteOrder[i]].y - posY, sprite[spriteOrder[i]].x - posX);
+			int sprdeg = (int)(sprrad / 3.1415 * 180.0);
+			sprdeg = ((sprdeg + 180) + sprite[spriteOrder[i]].angle) % 360;
+			int loop = 0;
+			if (sprdeg > 336 || sprdeg < 23) loop = 0;
+			else if (sprdeg > 22 && sprdeg < 68) loop = 6;
+			else if (sprdeg > 67 && sprdeg < 113) loop = 1;
+			else if (sprdeg > 112 && sprdeg < 158) loop = 7;
+			else if (sprdeg > 157 && sprdeg < 203) loop = 3;
+			else if (sprdeg > 202 && sprdeg < 248) loop = 5;
+			else if (sprdeg > 247 && sprdeg < 293) loop = 2;
+			else if (sprdeg > 292 && sprdeg < 337) loop = 4;
+			AGSViewFrame *vf = engine->GetViewFrame(sprite[spriteOrder[i]].view, loop, sprite[spriteOrder[i]].frame);
+			if (vf == nullptr) engine->AbortGame("Raycast_Render: Unable to load viewframe of sprite.");
+			else {
+				sprite[spriteOrder[i]].texture = vf->pic;
+				int (*sfGetGameParameter)(int, int, int, int);
+				sfGetGameParameter = ((int(*)(int, int, int, int)) engine->GetScriptFunctionAddress("GetGameParameter"));
+				flipped = sfGetGameParameter(13, sprite[spriteOrder[i]].view, loop, sprite[spriteOrder[i]].frame);
+			}
+		}
+		//translate sprite position to relative to camera
+		//double spriteX = sprite[spriteOrder[i]].x - posX;
+		//double spriteY = sprite[spriteOrder[i]].y - posY;
+
+		//transform sprite with the inverse camera matrix
+		// [ planeX   dirX ] -1                                       [ dirY      -dirX ]
+		// [               ]       =  1/(planeX*dirY-dirX*planeY) *   [                 ]
+		// [ planeY   dirY ]                                          [ -planeY  planeX ]
+
+		//double invDet = 1.0 / (planeX * dirY - dirX * planeY); //required for correct matrix multiplication
+		double spriteX = sprite[spriteOrder[i]].x - posX;
+		double spriteY = sprite[spriteOrder[i]].y - posY;
+		//double transformX = invDet * (dirY * spriteX - dirX * spriteY);
+		//double transformY = invDet * (-planeY * spriteX + planeX * spriteY); //this is actually the depth inside the screen, that what Z is in 3D
+
+		int spriteScreenX = int((w / 2) * (1 + spriteTransformX[i] / spriteTransformY[i]));
+
+		//parameters for scaling and moving the sprites
+		BITMAP *spritetexbm = engine->GetSpriteGraphic(sprite[spriteOrder[i]].texture);
+		unsigned char **spritetex = engine->GetRawBitmapSurface(spritetexbm);
+		int sprw = engine->GetSpriteWidth(sprite[spriteOrder[i]].texture);
+		int sprh = engine->GetSpriteHeight(sprite[spriteOrder[i]].texture);
+
+		double uDiv = ((double)sprw / (double)texWidth) + sprite[spriteOrder[i]].uDivW;
+		double vDiv = ((double)sprh / (double)texHeight) + sprite[spriteOrder[i]].uDivH;
+		double vMove = sprite[spriteOrder[i]].vMove + ((double)texHeight - (double)sprh) * 1.6;
+		double hMove = sprite[spriteOrder[i]].hMove;
+		int vMoveScreen = int(vMove / spriteTransformY[i]);
+		int hMoveScreen = int(hMove / spriteTransformY[i]);
+		//calculate height of the sprite on screen
+		int spriteHeight = abs(int(h / (spriteTransformY[i]) * vDiv)) ; //using "transformY" instead of the real distance prevents fisheye
+		//calculate lowest and highest pixel to fill in current stripe
+		int drawStartY = -spriteHeight / 2 + h / 2 + vMoveScreen;
+		if (drawStartY < 0) drawStartY = 0;
+		int drawEndY = spriteHeight / 2 + h / 2 + vMoveScreen;
+		if (drawEndY >= h) drawEndY = h - 1;
+
+		//calculate width of the sprite
+		int spriteWidth = abs(int (h / (spriteTransformY[i]) * uDiv)) ;
+		int drawStartX = -spriteWidth / 2 + spriteScreenX + hMoveScreen;
+		if (drawStartX < 0) drawStartX = 0;
+		int drawEndX = spriteWidth / 2 + spriteScreenX + hMoveScreen;
+		if (drawEndX >= w) drawEndX = w - 1;
+		int spr_light = lightMap [(int)sprite[spriteOrder[i]].x][(int)sprite[spriteOrder[i]].y] << 5;
+		spr_light = std::min(255, std::max(0, spr_light));
+		int floorTexX = int(sprite[spriteOrder[i]].x * texWidth) % texWidth;
+		int floorTexY = int(sprite[spriteOrder[i]].y * texHeight) % texHeight;
+		if (ceilingMap [(int)sprite[spriteOrder[i]].x][(int)sprite[spriteOrder[i]].y] == 0) {
+			spr_light = std::max(spr_light, ambientlight);
+		} else if (texture[ceilingMap [(int)sprite[spriteOrder[i]].x][(int)sprite[spriteOrder[i]].y] - 1][texWidth * floorTexY + floorTexX] == 0) spr_light = std::max(spr_light, ambientlight);
+		//loop through every vertical stripe of the sprite on screen
+
+
+		for (int stripe = drawStartX; stripe < drawEndX; stripe++) {
+			transwalldraw = 0;
+			//int texX = int(256 * (stripe - (-spriteWidth / 2 + spriteScreenX)) * texWidth / spriteWidth) / 256;
+			int texX = int(256 * (stripe - (-spriteWidth / 2 + spriteScreenX)) *  sprw / spriteWidth) / 256;
+			if (texX >= sprw || texX < 0) continue;
+			if (flipped) texX = sprw - texX;
+			//the conditions in the if are:
+			//1) it's in front of camera plane so you don't see things behind you
+			//2) it's on the screen (left)
+			//3) it's on the screen (right)
+			//4) ZBuffer, with perpendicular distance
+			if (spriteTransformY[i] > 0 && stripe > 0 && stripe < w)
+				for (int y = drawStartY; y < drawEndY; y++) { //for every pixel of the current stripe
+					if (spriteTransformY[i] < ZBuffer[stripe][y]) {
+						if (transslicedrawn[stripe]) while ((transzbuffer[stripe][transwalldraw * h + y] > spriteTransformY[i] && transzbuffer[stripe][transwalldraw * h + y] != 0) && (transwalldraw < transwallcount)) transwalldraw++;
+						int d = (y - vMoveScreen) * 256 - h * 128 + spriteHeight * 128; //256 and 128 factors to avoid floats
+						//int texY = ((d * texHeight) / spriteHeight) / 256;
+						int texY = ((d * sprh) / spriteHeight) / 256;
+						if (texY >= sprh || texY < 0) continue;
+						//unsigned char color = texture[sprite[spriteOrder[i]].texture][texWidth * texY + texX]; //get current color from the texture
+						unsigned char color = spritetex[texY][texX]; //get current color from the texture
+						if (color != 0) {
+							if (sprite[spriteOrder[i]].alpha < 255) {
+								if (sprite[spriteOrder[i]].blendmode == 0) color = Mix::MixColorAlpha(color, buffer[y][stripe], sprite[spriteOrder[i]].alpha);
+								if (sprite[spriteOrder[i]].blendmode == 1) color = Mix::MixColorAdditive(color, buffer[y][stripe], sprite[spriteOrder[i]].alpha);
+							}
+							color = Mix::MixColorLightLevel(color, spr_light);
+							if (transzbuffer[stripe][transwalldraw * h + y] < spriteTransformY[i] && transzbuffer[stripe][transwalldraw * h + y] != 0 && transslicedrawn[stripe] && transcolorbuffer[stripe][transwalldraw * h + y] > 0 && transalphabuffer[stripe][transwalldraw * h + y] > 0) {
+								if (transwallblendmode[transwalldraw] == 0) color = Mix::MixColorAlpha(color, transcolorbuffer[stripe][transwalldraw * h + y], transalphabuffer[stripe][transwalldraw * h + y]);
+								else if (transwallblendmode[transwalldraw] == 1) color = Mix::MixColorAdditive(color, transcolorbuffer[stripe][transwalldraw * h + y], transalphabuffer[stripe][transwalldraw * h + y]);
+								buffer[y][stripe] = color;
+								ZBuffer[stripe][y] = transzbuffer[stripe][transwalldraw * h + y];
+							} else {
+								buffer[y][stripe] = color; //paint pixel if it isn't black, black is the invisible color
+								ZBuffer[stripe][y] = spriteTransformY[i]; //put the sprite on the zbuffer so we can draw around it.
+							}
+							interactionmap [stripe * sWidth + y] = sprite[spriteOrder[i]].objectinteract << 8;
+						}
+					}
+				}
+		}
+		engine->ReleaseBitmapSurface(spritetexbm);
+	}
+	engine->ReleaseBitmapSurface(screen);
+	engine->NotifySpriteUpdated(slot);
+	rendering = false;
+
+}
+
+void QuitCleanup() {
+	if (!rendering) {
+		for (int i = 0; i < sWidth; ++i) {
+			if (transcolorbuffer[i])delete [] transcolorbuffer[i];
+			if (transalphabuffer[i])delete [] transalphabuffer[i];
+			if (transzbuffer[i])delete [] transzbuffer[i];
+			if (ZBuffer[i]) delete [] ZBuffer[i];
+		}
+		if (transcolorbuffer) delete [] transcolorbuffer;
+		if (transalphabuffer) delete [] transalphabuffer;
+		if (transzbuffer) delete [] transzbuffer;
+		if (ZBuffer) delete [] ZBuffer;
+		if (transwallblendmode) delete [] transwallblendmode;
+		if (interactionmap) delete [] interactionmap;
+	}
+}
+
+void MoveForward() {
+	double newposx = 0;
+	if (dirX > 0) newposx = 0.1 + posX + dirX * moveSpeed;
+	else newposx = -0.1 + posX + dirX * moveSpeed;
+	int texsidex = 0;
+	int inside_texsidex = 0;
+	double newposy = 0;
+	if (dirY > 0) newposy = 0.1 + posY + dirY * moveSpeed;
+	else newposy = -0.1 + posY + dirY * moveSpeed;
+	int texsidey = 0;
+	int inside_texsidey = 0;
+	bool inside = false;
+	if ((int)newposx == (int)posX && (int)newposy == (int)posY) inside = true;
+	if (dirX > 0 && !inside) {
+		texsidex = 0;
+		inside_texsidex = 1;
+	} else if (dirX > 0) {
+		texsidex = 1;
+		inside_texsidex = 0;
+	}
+	if (dirX < 0 && !inside) {
+		texsidex = 1;
+		inside_texsidex = 0;
+	} else if (dirX < 0) {
+		texsidex = 0;
+		inside_texsidex = 1;
+	}
+
+	if (dirY > 0 && !inside) {
+		texsidey = 2;
+		inside_texsidey = 3;
+	} else if (dirY > 0) {
+		texsidey = 3;
+		inside_texsidey = 2;
+	}
+	if (dirY < 0 && !inside) {
+		texsidey = 3;
+		inside_texsidey = 2;
+	} else if (dirY < 0) {
+		texsidey = 2;
+		inside_texsidey = 3;
+	}
+
+	if (!noclip && !inside) {
+		if (wallData[worldMap[int(newposx)][int(posY)]].solid[texsidex] == false && wallData[worldMap[int(posX)][int(posY)]].solid[inside_texsidex] == false && int(newposx) > -1 && int(newposx) < mapWidth) posX += dirX * moveSpeed;
+		if (wallData[worldMap[int(posX)][int(newposy)]].solid[texsidey] == false && wallData[worldMap[int(posX)][int(posY)]].solid[inside_texsidey] == false && int(newposy) > -1 && int(newposy) < mapHeight) posY += dirY * moveSpeed;
+	} else if (!noclip && inside) {
+		posX += dirX * moveSpeed;
+		posY += dirY * moveSpeed;
+	} else {
+		if (int(newposx) > -1 && int(newposx) < mapWidth) posX += dirX * moveSpeed;
+		if (int(newposy) > -1 && int(newposy) < mapHeight) posY += dirY * moveSpeed;
+	}
+}
+
+void MoveBackward() {
+	double newposx = 0;
+	if (dirX > 0) newposx = -0.1 + posX - dirX * moveSpeed;
+	else newposx = 0.1 + posX - dirX * moveSpeed;
+	int texsidex = 0;
+	int inside_texsidex = 0;
+	double newposy = 0;
+	if (dirY > 0) newposy = -0.1 + posY - dirY * moveSpeed;
+	else newposy = 0.1 + posY - dirY * moveSpeed;
+	int texsidey = 0;
+	int inside_texsidey = 0;
+	bool inside = false;
+	if ((int)newposx == (int)posX && (int)newposy == (int)posY) inside = true;
+	if (dirX > 0 && !inside) {
+		texsidex = 1;
+		inside_texsidex = 0;
+	} else if (dirX > 0) {
+		texsidex = 0;
+		inside_texsidex = 1;
+	}
+	if (dirX < 0 && !inside) {
+		texsidex = 0;
+		inside_texsidex = 1;
+	} else if (dirX < 0) {
+		texsidex = 1;
+		inside_texsidex = 0;
+	}
+
+	if (dirY > 0 && !inside) {
+		texsidey = 3;
+		inside_texsidey = 2;
+	} else if (dirY > 0) {
+		texsidey = 2;
+		inside_texsidey = 3;
+	}
+	if (dirY < 0 && !inside) {
+		texsidey = 2;
+		inside_texsidey = 3;
+	} else if (dirY < 0) {
+		texsidey = 3;
+		inside_texsidey = 2;
+	}
+
+	if ((int)posX == (int)newposy && (int)posY == (int)newposy) inside = true;
+	if (!noclip && !inside) {
+		if (wallData[worldMap[int(newposx)][int(posY)]].solid[texsidex] == false && wallData[worldMap[int(posX)][int(posY)]].solid[inside_texsidex] == false && int(newposx) > -1 && int(newposx) < mapWidth) posX -= dirX * moveSpeed;
+		if (wallData[worldMap[int(posX)][int(newposy)]].solid[texsidey] == false && wallData[worldMap[int(posX)][int(posY)]].solid[inside_texsidey] == false && int(newposy) > -1 && int(newposy) < mapHeight) posY -= dirY * moveSpeed;
+	} else if (!noclip && inside) {
+		posX -= dirX * moveSpeed;
+		posY -= dirY * moveSpeed;
+	} else {
+		if (int(newposx) > -1 && int(newposx) < mapWidth) posX -= dirX * moveSpeed;
+		if (int(newposy) > -1 && int(newposy) < mapHeight) posY -= dirY * moveSpeed;
+	}
+}
+
+
+
+/*
+void MoveBackward ()
+{
+      double newposx;
+      if (dirX > 0) newposx = -0.2 + posX - dirX * moveSpeed;
+      else newposx = 0.2 + posX - dirX * moveSpeed;
+      double newposy;
+      if (dirY > 0) newposy = -0.2 + posY - dirY * moveSpeed;
+      else newposy = 0.2 + posY - dirY * moveSpeed;
+      if(worldMap[int(newposx)][int(posY)] == false || worldMap[int(newposx)][int(posY)] > 8) posX -= dirX * moveSpeed;
+      if(worldMap[int(posX)][int(newposy)] == false || worldMap[int(posX)][int(newposy)] > 8) posY -= dirY * moveSpeed;
+}
+*/
+
+void RotateLeft() {
+	double oldDirX = dirX;
+	dirX = dirX * cos(rotSpeed) - dirY * sin(rotSpeed);
+	dirY = oldDirX * sin(rotSpeed) + dirY * cos(rotSpeed);
+	double oldPlaneX = planeX;
+	planeX = planeX * cos(rotSpeed) - planeY * sin(rotSpeed);
+	planeY = oldPlaneX * sin(rotSpeed) + planeY * cos(rotSpeed);
+}
+
+void RotateRight() {
+	double oldDirX = dirX;
+	dirX = dirX * cos(-rotSpeed) - dirY * sin(-rotSpeed);
+	dirY = oldDirX * sin(-rotSpeed) + dirY * cos(-rotSpeed);
+	double oldPlaneX = planeX;
+	planeX = planeX * cos(-rotSpeed) - planeY * sin(-rotSpeed);
+	planeY = oldPlaneX * sin(-rotSpeed) + planeY * cos(-rotSpeed);
+}
+
+//sort algorithm
+void combSort(int *order, double *dist, int amount) {
+	int gap = amount;
+	bool swapped = false;
+	while (gap > 1 || swapped) {
+		//shrink factor 1.3
+		gap = (gap * 10) / 13;
+		if (gap == 9 || gap == 10) gap = 11;
+		if (gap < 1) gap = 1;
+		swapped = false;
+		for (int i = 0; i < amount - gap; i++) {
+			int j = i + gap;
+			if (dist[i] < dist[j]) {
+				std::swap(dist[i], dist[j]);
+				std::swap(order[i], order[j]);
+				swapped = true;
+			}
+		}
+	}
+}
+
+#if defined(BUILTIN_PLUGINS)
+} // namespace agspalrender
+#endif
diff --git a/engines/ags/plugins/ags_pal_render/raycast.h b/engines/ags/plugins/ags_pal_render/raycast.h
new file mode 100644
index 0000000000..87f4c1ed6f
--- /dev/null
+++ b/engines/ags/plugins/ags_pal_render/raycast.h
@@ -0,0 +1,189 @@
+#ifndef __PALGORITHMS_RAYCAST_H
+#define __PALGORITHMS_RAYCAST_H
+
+#include "palrender.h"
+
+#define mapWidth 64
+#define mapHeight 64
+
+#if defined(BUILTIN_PLUGINS)
+namespace agspalrender {
+#endif
+
+struct Sprite {
+	double x;
+	double y;
+	int texture;
+	unsigned char alpha;
+	int blendmode;
+	double uDivW;
+	double uDivH;
+	double vMove;
+	double hMove;
+	char objectinteract;
+	int view;
+	int frame;
+	int angle;
+};
+
+struct wallType {
+	int texture[4];
+	int solid[4];
+	int ignorelighting[4];
+	int alpha[4];
+	int blendtype[4];
+	int mask[4];
+	unsigned char hotspotinteract;
+};
+
+
+extern bool raycastOn;
+extern double posX;
+extern double posY; //x and y start position
+extern double dirX;
+extern double dirY; //initial direction vector
+extern double planeX;
+extern double planeY; //the 2d raycaster version of camera plane
+extern double moveSpeed; //the constant value is in squares/second
+extern double rotSpeed; //the constant value is in radians/second
+extern unsigned char worldMap[64][64];
+extern unsigned char lightMap[64][64];
+extern int ceilingMap[64][64];
+extern int floorMap[64][64];
+extern int heightMap[64][64];
+extern unsigned char seenMap[64][64];
+//extern int mapWidth;
+//extern int mapHeight;
+extern int textureSlot;
+extern int ambientlight;
+
+#define numSprites 256
+extern Sprite sprite[numSprites];
+
+
+#define texWidth 64
+#define texHeight 64
+#define MAX_TEXTURES 512
+extern unsigned char texture[][texWidth * texHeight];
+
+extern bool heightmapOn;
+
+
+extern wallType wallData[256];
+
+//arrays used to sort the sprites
+extern unsigned char **transcolorbuffer;
+extern unsigned char **transalphabuffer;
+extern double **transzbuffer;
+extern bool *transslicedrawn;
+extern int *transwallblendmode;
+extern double **ZBuffer;
+extern double *distTable;
+extern short *interactionmap;
+extern int skybox;
+
+
+
+void MakeTextures(int slot);
+void Raycast_Render(int slot);
+void MoveForward();
+void MoveBackward();
+void RotateLeft();
+void RotateRight();
+void Init_Raycaster();
+void QuitCleanup();
+void LoadMap(int worldmapSlot, int lightmapSlot, int ceilingmapSlot, int floormapSlot);
+void Ray_InitSprite(int id, SCRIPT_FLOAT(x), SCRIPT_FLOAT(y), int slot, unsigned char alpha, int blendmode, SCRIPT_FLOAT(scale_x), SCRIPT_FLOAT(scale_y), SCRIPT_FLOAT(vMove));
+void Ray_SetPlayerPosition(SCRIPT_FLOAT(x), SCRIPT_FLOAT(y));
+FLOAT_RETURN_TYPE Ray_GetPlayerX();
+FLOAT_RETURN_TYPE Ray_GetPlayerY();
+int Ray_GetPlayerAngle();
+void Ray_SetPlayerAngle(int angle);
+
+int Ray_GetWallHotspot(int id);
+int Ray_GetWallTexture(int id, int dir);
+int Ray_GetWallSolid(int id, int dir);
+int Ray_GetWallIgnoreLighting(int id, int dir);
+int Ray_GetWallAlpha(int id, int dir);
+int Ray_GetWallBlendType(int id, int dir);
+
+void Ray_SelectTile(int x, int y, unsigned char color);
+
+int Ray_GetHotspotAt(int x, int y);
+int Ray_GetObjectAt(int x, int y);
+
+void Ray_DrawTile(int spr, int tile);
+void Ray_DrawOntoTile(int spr, int tile);
+void Ray_SetNoClip(int value);
+int Ray_GetNoClip();
+void Ray_SetSpriteInteractObj(int id, int obj);
+int  Ray_GetSpriteInteractObj(int id);
+void Ray_SetSpritePosition(int id, SCRIPT_FLOAT(x), SCRIPT_FLOAT(y));
+void Ray_SetSpriteVertOffset(int id, SCRIPT_FLOAT(vMove));
+FLOAT_RETURN_TYPE Ray_GetSpriteVertOffset(int id);
+FLOAT_RETURN_TYPE Ray_GetSpriteX(int id);
+FLOAT_RETURN_TYPE Ray_GetSpriteY(int id);
+
+void Ray_SetWallHotspot(int id, char hotsp);
+void Ray_SetWallTextures(int id, int n, int s, int w, int e);
+void Ray_SetWallSolid(int id, int n, int s, int w, int e);
+void Ray_SetWallIgnoreLighting(int id, int n, int s, int w, int e);
+void Ray_SetWallAlpha(int id, int n, int s, int w, int e);
+void Ray_SetWallBlendType(int id, int n, int s, int w, int e);
+
+FLOAT_RETURN_TYPE Ray_GetMoveSpeed();
+void Ray_SetMoveSpeed(SCRIPT_FLOAT(speed));
+FLOAT_RETURN_TYPE Ray_GetRotSpeed();
+void Ray_SetRotSpeed(SCRIPT_FLOAT(speed));
+int Ray_GetWallAt(int x, int y);
+int Ray_GetLightAt(int x, int y);
+void Ray_SetLightAt(int x, int y, int light);
+void Ray_SetWallAt(int x, int y, int id);
+void Ray_SetPlaneY(SCRIPT_FLOAT(y));
+FLOAT_RETURN_TYPE Ray_GetDistanceAt(int x, int y);
+int Ray_GetSpriteAngle(int id);
+void Ray_SetSpriteAngle(int id, int angle);
+void Ray_SetSpriteView(int id, int view);
+int Ray_GetSpriteView(int id);
+void Ray_SetSpriteFrame(int id, int frame);
+int Ray_GetSpriteFrame(int id);
+
+int Ray_GetTileX_At(int x, int y);
+int Ray_GetTileY_At(int x, int y);
+
+void Ray_SetSkyBox(int slot);
+int Ray_GetSkyBox(int slot);
+
+void Ray_SetAmbientLight(int value);
+int Ray_GetAmbientLight();
+void Ray_SetAmbientColor(int color, int amount);
+
+
+int Ray_GetSpriteAlpha(int id);
+void Ray_SetSpriteAlpha(int id, int alpha);
+int Ray_GetSpritePic(int id);
+void Ray_SetSpritePic(int id, int slot);
+
+FLOAT_RETURN_TYPE Ray_GetSpriteScaleX(int id);
+void Ray_SetSpriteScaleX(int id, SCRIPT_FLOAT(scale));
+FLOAT_RETURN_TYPE Ray_GetSpriteScaleY(int id);
+void Ray_SetSpriteScaleY(int id, SCRIPT_FLOAT(scale));
+
+void Ray_SetSpriteBlendType(int id, int type);
+int Ray_GetSpriteBlendType(int id);
+
+void Ray_SetFloorAt(int x, int y, int tex);
+void Ray_SetCeilingAt(int x, int y, int tex);
+int Ray_GetCeilingAt(int x, int y);
+int Ray_GetFloorAt(int x, int y);
+int Ray_GetLightingAt(int x, int y);
+void Ray_SetLightingAt(int x, int y, unsigned char lighting);
+int Ray_GetAmbientWeight();
+
+int Ray_HasSeenTile(int x, int y);
+
+#if defined(BUILTIN_PLUGINS)
+} // namespace agspalrender
+#endif
+
+#endif
\ No newline at end of file
diff --git a/engines/ags/plugins/ags_parallax/ags_parallax.cpp b/engines/ags/plugins/ags_parallax/ags_parallax.cpp
new file mode 100644
index 0000000000..05c32b94dd
--- /dev/null
+++ b/engines/ags/plugins/ags_parallax/ags_parallax.cpp
@@ -0,0 +1,287 @@
+/*
+
+This is not the AGS Parallax plugin by Scorpiorus
+but a workalike plugin created by JJS for the AGS engine ports.
+
+*/
+
+#include "core/platform.h"
+
+#if AGS_PLATFORM_OS_WINDOWS
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#pragma warning(disable : 4244)
+#endif
+
+#if !defined(BUILTIN_PLUGINS)
+#define THIS_IS_THE_PLUGIN
+#endif
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <math.h>
+
+#include "plugin/agsplugin.h"
+
+#if defined(BUILTIN_PLUGINS)
+namespace ags_parallax {
+#endif
+
+//#define DEBUG
+
+const unsigned int Magic = 0xCAFE0000;
+const unsigned int Version = 2;
+const unsigned int SaveMagic = Magic + Version;
+
+int screen_width = 320;
+int screen_height = 200;
+int screen_color_depth = 32;
+
+IAGSEngine *engine;
+
+bool enabled = false;
+
+
+typedef struct {
+	int x;
+	int y;
+	int slot;
+	int speed;
+} sprite_t;
+
+#define MAX_SPEED 1000
+#define MAX_SPRITES 100
+sprite_t sprites[MAX_SPRITES];
+
+// workaround to fix this error:
+//   psp-fixup-imports ags_parallax.elf
+//   Error, no .lib.stub section found
+void dummy() {
+	void *tmp = new int;
+}
+
+static size_t engineFileRead(void *ptr, size_t size, size_t count, long fileHandle) {
+	auto totalBytes = engine->FRead(ptr, size * count, fileHandle);
+	return totalBytes / size;
+}
+
+static size_t engineFileWrite(const void *ptr, size_t size, size_t count, long fileHandle) {
+	auto totalBytes = engine->FWrite(const_cast<void *>(ptr), size * count, fileHandle);
+	return totalBytes / size;
+}
+
+void RestoreGame(long fileHandle) {
+	unsigned int SaveVersion = 0;
+	engineFileRead(&SaveVersion, sizeof(SaveVersion), 1, fileHandle);
+
+	if (SaveVersion != SaveMagic) {
+		engine->AbortGame("ags_parallax: bad save.");
+	}
+
+	engineFileRead(sprites, sizeof(sprite_t), MAX_SPRITES, fileHandle);
+	engineFileRead(&enabled, sizeof(bool), 1, fileHandle);
+}
+
+void SaveGame(long file) {
+	engineFileWrite(&SaveMagic, sizeof(SaveMagic), 1, file);
+	engineFileWrite(sprites, sizeof(sprite_t), MAX_SPRITES, file);
+	engineFileWrite(&enabled, sizeof(bool), 1, file);
+}
+
+
+void Initialize() {
+	memset(sprites, 0, sizeof(sprite_t) * MAX_SPRITES);
+
+	int i;
+	for (i = 0; i < MAX_SPRITES; i++)
+		sprites[i].slot = -1;
+
+	enabled = false;
+}
+
+
+void Draw(bool foreground) {
+	if (!enabled)
+		return;
+
+	BITMAP *bmp;
+	int i;
+
+	int offsetX = 0;
+	int offsetY = 0;
+	engine->ViewportToRoom(&offsetX, &offsetY);
+
+	for (i = 0; i < MAX_SPRITES; i++) {
+		if (sprites[i].slot > -1) {
+			if (foreground) {
+				if (sprites[i].speed > 0) {
+					bmp = engine->GetSpriteGraphic(sprites[i].slot);
+					if (bmp)
+						engine->BlitBitmap(sprites[i].x - offsetX - (sprites[i].speed * offsetX / 100), sprites[i].y, bmp, 1);
+				}
+			} else {
+				if (sprites[i].speed <= 0) {
+					bmp = engine->GetSpriteGraphic(sprites[i].slot);
+					if (bmp)
+						engine->BlitBitmap(sprites[i].x - offsetX - (sprites[i].speed * offsetX / 1000), sprites[i].y, bmp, 1);
+				}
+			}
+		}
+	}
+}
+
+
+
+
+
+// ********************************************
+// ************  AGS Interface  ***************
+// ********************************************
+
+void pxDrawSprite(int id, int x, int y, int slot, int speed) {
+#ifdef DEBUG
+	char buffer[200];
+	sprintf(buffer, "%s %d %d %d %d %d\n", "pxDrawSprite", id, x, y, slot, speed);
+	engine->PrintDebugConsole(buffer);
+#endif
+
+	if ((id < 0) || (id >= MAX_SPRITES))
+		return;
+
+	if ((speed < -MAX_SPEED) || (speed > MAX_SPEED))
+		speed = 0;
+
+	sprites[id].x = x;
+	sprites[id].y = y;
+	sprites[id].slot = slot;
+	sprites[id].speed = speed;
+
+	engine->RoomToViewport(&sprites[id].x, &sprites[id].y);
+
+	enabled = true;
+}
+
+
+void pxDeleteSprite(int id) {
+#ifdef DEBUG
+	char buffer[200];
+	sprintf(buffer, "%s %d\n", "pxDeleteSprite", id);
+	engine->PrintDebugConsole(buffer);
+#endif
+
+	if ((id < 0) || (id >= MAX_SPRITES))
+		return;
+
+	sprites[id].slot = -1;
+}
+
+void AGS_EngineStartup(IAGSEngine *lpEngine) {
+	engine = lpEngine;
+
+	if (engine->version < 13)
+		engine->AbortGame("Engine interface is too old, need newer version of AGS.");
+
+	engine->RegisterScriptFunction("pxDrawSprite", (void *)&pxDrawSprite);
+	engine->RegisterScriptFunction("pxDeleteSprite", (void *)&pxDeleteSprite);
+
+	engine->RequestEventHook(AGSE_PREGUIDRAW);
+	engine->RequestEventHook(AGSE_PRESCREENDRAW);
+	engine->RequestEventHook(AGSE_ENTERROOM);
+	engine->RequestEventHook(AGSE_SAVEGAME);
+	engine->RequestEventHook(AGSE_RESTOREGAME);
+
+	Initialize();
+}
+
+void AGS_EngineShutdown() {
+}
+
+int AGS_EngineOnEvent(int event, int data) {
+	if (event == AGSE_PREGUIDRAW) {
+		Draw(true);
+	} else if (event == AGSE_PRESCREENDRAW) {
+		Draw(false);
+	} else if (event == AGSE_ENTERROOM) {
+		// Reset all sprites
+		Initialize();
+	} else if (event == AGSE_PRESCREENDRAW) {
+		// Get screen size once here
+		engine->GetScreenDimensions(&screen_width, &screen_height, &screen_color_depth);
+		engine->UnrequestEventHook(AGSE_PRESCREENDRAW);
+	} else if (event == AGSE_RESTOREGAME) {
+		RestoreGame(data);
+	} else if (event == AGSE_SAVEGAME) {
+		SaveGame(data);
+	}
+
+	return 0;
+}
+
+int AGS_EngineDebugHook(const char *scriptName, int lineNum, int reserved) {
+	return 0;
+}
+
+void AGS_EngineInitGfx(const char *driverID, void *data) {
+}
+
+
+
+#if AGS_PLATFORM_OS_WINDOWS && !defined(BUILTIN_PLUGINS)
+
+// ********************************************
+// ***********  Editor Interface  *************
+// ********************************************
+
+const char *scriptHeader =
+    "import void pxDrawSprite(int ID, int X, int Y, int SlotNum, int Speed);\r\n"
+    "import void pxDeleteSprite(int ID);\r\n";
+
+IAGSEditor *editor;
+
+
+LPCSTR AGS_GetPluginName(void) {
+	// Return the plugin description
+	return "Parallax plugin recreation";
+}
+
+int  AGS_EditorStartup(IAGSEditor *lpEditor) {
+	// User has checked the plugin to use it in their game
+
+	// If it's an earlier version than what we need, abort.
+	if (lpEditor->version < 1)
+		return -1;
+
+	editor = lpEditor;
+	editor->RegisterScriptHeader(scriptHeader);
+
+	// Return 0 to indicate success
+	return 0;
+}
+
+void AGS_EditorShutdown() {
+	// User has un-checked the plugin from their game
+	editor->UnregisterScriptHeader(scriptHeader);
+}
+
+void AGS_EditorProperties(HWND parent) {
+	// User has chosen to view the Properties of the plugin
+	// We could load up an options dialog or something here instead
+	MessageBoxA(parent, "Parallax plugin recreation by JJS", "About", MB_OK | MB_ICONINFORMATION);
+}
+
+int AGS_EditorSaveGame(char *buffer, int bufsize) {
+	// We don't want to save any persistent data
+	return 0;
+}
+
+void AGS_EditorLoadGame(char *buffer, int bufsize) {
+	// Nothing to load for this plugin
+}
+
+#endif
+
+
+#if defined(BUILTIN_PLUGINS)
+} // namespace ags_parallax
+#endif
diff --git a/engines/ags/plugins/ags_parallax/ags_parallax.h b/engines/ags/plugins/ags_parallax/ags_parallax.h
new file mode 100644
index 0000000000..c58126f149
--- /dev/null
+++ b/engines/ags/plugins/ags_parallax/ags_parallax.h
@@ -0,0 +1,14 @@
+#ifndef AGS_PARALLAX_H
+#define AGS_PARALLAX_H
+
+#include "plugin/agsplugin.h"
+
+namespace ags_parallax {
+void AGS_EngineStartup(IAGSEngine *lpEngine);
+void AGS_EngineShutdown();
+int AGS_EngineOnEvent(int event, int data);
+int AGS_EngineDebugHook(const char *scriptName, int lineNum, int reserved);
+void AGS_EngineInitGfx(const char *driverID, void *data);
+}
+
+#endif
\ No newline at end of file
diff --git a/engines/ags/plugins/ags_snow_rain/ags_snow_rain.cpp b/engines/ags/plugins/ags_snow_rain/ags_snow_rain.cpp
new file mode 100644
index 0000000000..bc61dc26be
--- /dev/null
+++ b/engines/ags/plugins/ags_snow_rain/ags_snow_rain.cpp
@@ -0,0 +1,841 @@
+/*
+
+This is not the AGS SnowRain plugin by Scorpiorus (http://www.bigbluecup.com/yabb/index.php?topic=25665.0),
+but a workalike plugin created by JJS for the AGS engine PSP port.
+
+*/
+
+#include "core/platform.h"
+
+#if AGS_PLATFORM_OS_WINDOWS
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#pragma warning(disable : 4244)
+#endif
+
+#if !defined(BUILTIN_PLUGINS)
+#define THIS_IS_THE_PLUGIN
+#endif
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <math.h>
+
+#ifdef PSP_VERSION
+#include <pspsdk.h>
+#include <pspmath.h>
+#define sin(x) vfpu_sinf(x)
+#endif
+
+#include "plugin/agsplugin.h"
+
+#if defined(BUILTIN_PLUGINS)
+namespace ags_snowrain {
+#endif
+
+//#define DEBUG
+//#define AGS_SNOWRAIN_DLL_SAVEGAME_COMPATIBILITY
+
+#define signum(x) ((x > 0) ? 1 : -1)
+
+const unsigned int Magic = 0xCAFE0000;
+const unsigned int Version = 2;
+const unsigned int SaveMagic = Magic + Version;
+const float PI = 3.14159265f;
+
+int screen_width = 320;
+int screen_height = 200;
+int screen_color_depth = 32;
+
+IAGSEngine *engine;
+
+
+typedef struct {
+	int view;
+	int loop;
+	bool is_default;
+	BITMAP *bitmap;
+} view_t;
+
+
+typedef struct {
+	float x;
+	float y;
+	int alpha;
+	float speed;
+	int max_y;
+	int kind_id;
+	int drift;
+	float drift_speed;
+	float drift_offset;
+} drop_t;
+
+
+class Weather {
+public:
+	Weather();
+	Weather(bool IsSnow);
+	~Weather();
+
+	void Initialize();
+	void InitializeParticles();
+
+	void RestoreGame(long file);
+	void SaveGame(long file);
+	bool ReinitializeViews();
+
+	bool IsActive();
+	void Update();
+	void UpdateWithDrift();
+	void EnterRoom();
+
+	void SetDriftRange(int min_value, int max_value);
+	void SetDriftSpeed(int min_value, int max_value);
+	void ChangeAmount(int amount);
+	void SetView(int kind_id, int event, int view, int loop);
+	void SetDefaultView(int view, int loop);
+	void SetTransparency(int min_value, int max_value);
+	void SetWindSpeed(int value);
+	void SetBaseline(int top, int bottom);
+	void SetAmount(int amount);
+	void SetFallSpeed(int min_value, int max_value);
+
+private:
+	void ClipToRange(int &variable, int min, int max);
+
+	bool mIsSnow;
+
+	int mMinDrift;
+	int mMaxDrift;
+	int mDeltaDrift;
+
+	int mMinDriftSpeed;
+	int mMaxDriftSpeed;
+	int mDeltaDriftSpeed;
+
+	int mAmount;
+	int mTargetAmount;
+
+	int mMinAlpha;
+	int mMaxAlpha;
+	int mDeltaAlpha;
+
+	float mWindSpeed;
+
+	int mTopBaseline;
+	int mBottomBaseline;
+	int mDeltaBaseline;
+
+	int mMinFallSpeed;
+	int mMaxFallSpeed;
+	int mDeltaFallSpeed;
+
+	drop_t mParticles[2000];
+	view_t mViews[5];
+
+	bool mViewsInitialized;
+};
+
+
+Weather::Weather() {
+	mIsSnow = false;
+	Initialize();
+}
+
+
+Weather::Weather(bool IsSnow) {
+	mIsSnow = IsSnow;
+	Initialize();
+}
+
+
+Weather::~Weather() = default;
+
+
+void Weather::Update() {
+	if (mTargetAmount > mAmount)
+		mAmount++;
+	else if (mTargetAmount < mAmount)
+		mAmount--;
+
+	if (!ReinitializeViews())
+		return;
+
+	int i;
+	for (i = 0; i < mAmount * 2; i++) {
+		mParticles[i].y += mParticles[i].speed;
+		mParticles[i].x += mWindSpeed;
+
+		if (mParticles[i].x < 0)
+			mParticles[i].x += screen_width;
+
+		if (mParticles[i].x > screen_width - 1)
+			mParticles[i].x -= screen_width;
+
+		if (mParticles[i].y > mParticles[i].max_y) {
+			mParticles[i].y = -1 * (rand() % screen_height);
+			mParticles[i].x = rand() % screen_width;
+			mParticles[i].alpha = rand() % mDeltaAlpha + mMinAlpha;
+			mParticles[i].speed = (float)(rand() % mDeltaFallSpeed + mMinFallSpeed) / 50.0f;
+			mParticles[i].max_y = rand() % mDeltaBaseline + mTopBaseline;
+		} else if ((mParticles[i].y > 0) && (mParticles[i].alpha > 0))
+			engine->BlitSpriteTranslucent(mParticles[i].x, mParticles[i].y, mViews[mParticles[i].kind_id].bitmap, mParticles[i].alpha);
+	}
+
+	engine->MarkRegionDirty(0, 0, screen_width, screen_height);
+}
+
+
+void Weather::UpdateWithDrift() {
+	if (mTargetAmount > mAmount)
+		mAmount++;
+	else if (mTargetAmount < mAmount)
+		mAmount--;
+
+	if (!ReinitializeViews())
+		return;
+
+	int i, drift;
+	for (i = 0; i < mAmount * 2; i++) {
+		mParticles[i].y += mParticles[i].speed;
+		drift = mParticles[i].drift * sin((float)(mParticles[i].y + mParticles[i].drift_offset) * mParticles[i].drift_speed * 2.0f * PI / 360.0f);
+
+		if (signum(mWindSpeed) == signum(drift))
+			mParticles[i].x += mWindSpeed;
+		else
+			mParticles[i].x += mWindSpeed / 4;
+
+		if (mParticles[i].x < 0)
+			mParticles[i].x += screen_width;
+
+		if (mParticles[i].x > screen_width - 1)
+			mParticles[i].x -= screen_width;
+
+		if (mParticles[i].y > mParticles[i].max_y) {
+			mParticles[i].y = -1 * (rand() % screen_height);
+			mParticles[i].x = rand() % screen_width;
+			mParticles[i].alpha = rand() % mDeltaAlpha + mMinAlpha;
+			mParticles[i].speed = (float)(rand() % mDeltaFallSpeed + mMinFallSpeed) / 50.0f;
+			mParticles[i].max_y = rand() % mDeltaBaseline + mTopBaseline;
+			mParticles[i].drift = rand() % mDeltaDrift + mMinDrift;
+			mParticles[i].drift_speed = (rand() % mDeltaDriftSpeed + mMinDriftSpeed) / 50.0f;
+		} else if ((mParticles[i].y > 0) && (mParticles[i].alpha > 0))
+			engine->BlitSpriteTranslucent(mParticles[i].x + drift, mParticles[i].y, mViews[mParticles[i].kind_id].bitmap, mParticles[i].alpha);
+	}
+
+	engine->MarkRegionDirty(0, 0, screen_width, screen_height);
+}
+
+static size_t engineFileRead(void *ptr, size_t size, size_t count, long fileHandle) {
+	auto totalBytes = engine->FRead(ptr, size * count, fileHandle);
+	return totalBytes / size;
+}
+
+static size_t engineFileWrite(const void *ptr, size_t size, size_t count, long fileHandle) {
+	auto totalBytes = engine->FWrite(const_cast<void *>(ptr), size * count, fileHandle);
+	return totalBytes / size;
+}
+
+void Weather::RestoreGame(long file) {
+	unsigned int SaveVersion = 0;
+	engineFileRead(&SaveVersion, sizeof(SaveVersion), 1, file);
+
+	if (SaveVersion != SaveMagic) {
+		engine->AbortGame("ags_snowrain: bad save.");
+	}
+
+	// Current version
+	engineFileRead(&mIsSnow, 4, 1, file);
+	engineFileRead(&mMinDrift, 4, 1, file);
+	engineFileRead(&mMaxDrift, 4, 1, file);
+	engineFileRead(&mDeltaDrift, 4, 1, file);
+	engineFileRead(&mMinDriftSpeed, 4, 1, file);
+	engineFileRead(&mMaxDriftSpeed, 4, 1, file);
+	engineFileRead(&mDeltaDriftSpeed, 4, 1, file);
+	engineFileRead(&mAmount, 4, 1, file);
+	engineFileRead(&mTargetAmount, 4, 1, file);
+	engineFileRead(&mMinAlpha, 4, 1, file);
+	engineFileRead(&mMaxAlpha, 4, 1, file);
+	engineFileRead(&mDeltaAlpha, 4, 1, file);
+	engineFileRead(&mWindSpeed, 4, 1, file);
+	engineFileRead(&mTopBaseline, 4, 1, file);
+	engineFileRead(&mBottomBaseline, 4, 1, file);
+	engineFileRead(&mDeltaBaseline, 4, 1, file);
+	engineFileRead(&mMinFallSpeed, 4, 1, file);
+	engineFileRead(&mMaxFallSpeed, 4, 1, file);
+	engineFileRead(&mDeltaFallSpeed, 4, 1, file);
+	engineFileRead(mViews, sizeof(view_t) * 5, 1, file);
+
+	InitializeParticles();
+}
+
+
+void Weather::SaveGame(long file) {
+	engineFileWrite(&SaveMagic, sizeof(SaveMagic), 1, file);
+
+	engineFileWrite(&mIsSnow, 4, 1, file);
+	engineFileWrite(&mMinDrift, 4, 1, file);
+	engineFileWrite(&mMaxDrift, 4, 1, file);
+	engineFileWrite(&mDeltaDrift, 4, 1, file);
+	engineFileWrite(&mMinDriftSpeed, 4, 1, file);
+	engineFileWrite(&mMaxDriftSpeed, 4, 1, file);
+	engineFileWrite(&mDeltaDriftSpeed, 4, 1, file);
+	engineFileWrite(&mAmount, 4, 1, file);
+	engineFileWrite(&mTargetAmount, 4, 1, file);
+	engineFileWrite(&mMinAlpha, 4, 1, file);
+	engineFileWrite(&mMaxAlpha, 4, 1, file);
+	engineFileWrite(&mDeltaAlpha, 4, 1, file);
+	engineFileWrite(&mWindSpeed, 4, 1, file);
+	engineFileWrite(&mTopBaseline, 4, 1, file);
+	engineFileWrite(&mBottomBaseline, 4, 1, file);
+	engineFileWrite(&mDeltaBaseline, 4, 1, file);
+	engineFileWrite(&mMinFallSpeed, 4, 1, file);
+	engineFileWrite(&mMaxFallSpeed, 4, 1, file);
+	engineFileWrite(&mDeltaFallSpeed, 4, 1, file);
+	engineFileWrite(mViews, sizeof(view_t) * 5, 1, file);
+}
+
+
+bool Weather::ReinitializeViews() {
+	if ((mViews[4].view == -1) || (mViews[4].loop == -1))
+		return false;
+
+	AGSViewFrame *view_frame = engine->GetViewFrame(mViews[4].view, mViews[4].loop, 0);
+	BITMAP *default_bitmap = engine->GetSpriteGraphic(view_frame->pic);
+
+	int i;
+	for (i = 0; i < 5; i++) {
+		if (mViews[i].bitmap != nullptr) {
+			if (mViews[i].is_default)
+				mViews[i].bitmap = default_bitmap;
+			else {
+				view_frame = engine->GetViewFrame(mViews[i].view, mViews[i].loop, 0);
+				mViews[i].bitmap = engine->GetSpriteGraphic(view_frame->pic);
+			}
+		}
+	}
+
+	return true;
+}
+
+
+bool Weather::IsActive() {
+	return (mAmount > 0) || (mTargetAmount != mAmount);
+}
+
+
+void Weather::EnterRoom() {
+	mAmount = mTargetAmount;
+}
+
+
+void Weather::ClipToRange(int &variable, int min, int max) {
+	if (variable < min)
+		variable = min;
+
+	if (variable > max)
+		variable = max;
+}
+
+
+void Weather::Initialize() {
+	SetDriftRange(10, 100);
+	SetDriftSpeed(10, 120);
+
+	SetTransparency(0, 0);
+	SetWindSpeed(0);
+	SetBaseline(0, 200);
+
+	if (mIsSnow)
+		SetFallSpeed(10, 70);
+	else
+		SetFallSpeed(100, 300);
+
+	mViewsInitialized = false;
+
+	int i;
+	for (i = 0; i < 5; i++) {
+		mViews[i].is_default = true;
+		mViews[i].view = -1;
+		mViews[i].loop = -1;
+		mViews[i].bitmap = nullptr;
+	}
+
+	SetAmount(0);
+}
+
+
+void Weather::InitializeParticles() {
+	memset(mParticles, 0, sizeof(drop_t) * 2000);
+	int i;
+	for (i = 0; i < 2000; i++) {
+		mParticles[i].kind_id = rand() % 5;
+		mParticles[i].y = rand() % (screen_height * 2) - screen_height;
+		mParticles[i].x = rand() % screen_width;
+		mParticles[i].alpha = rand() % mDeltaAlpha + mMinAlpha;
+		mParticles[i].speed = (float)(rand() % mDeltaFallSpeed + mMinFallSpeed) / 50.0f;
+		mParticles[i].max_y = rand() % mDeltaBaseline + mTopBaseline;
+		mParticles[i].drift = rand() % mDeltaDrift + mMinDrift;
+		mParticles[i].drift_speed = (rand() % mDeltaDriftSpeed + mMinDriftSpeed) / 50.0f;
+		mParticles[i].drift_offset = rand() % 100;
+	}
+}
+
+
+void Weather::SetDriftRange(int min_value, int max_value) {
+#ifdef DEBUG
+	char buffer[200];
+	sprintf(buffer, "%d %s %d %d\n", (int)mIsSnow, "SetDriftRange", min_value, max_value);
+	engine->PrintDebugConsole(buffer);
+#endif
+
+	ClipToRange(min_value, 0, 100);
+	ClipToRange(max_value, 0, 100);
+
+	if (min_value > max_value)
+		min_value = max_value;
+
+	mMinDrift = min_value / 2;
+	mMaxDrift = max_value / 2;
+	mDeltaDrift = mMaxDrift - mMinDrift;
+
+	if (mDeltaDrift == 0)
+		mDeltaDrift = 1;
+}
+
+
+void Weather::SetDriftSpeed(int min_value, int max_value) {
+#ifdef DEBUG
+	char buffer[200];
+	sprintf(buffer, "%d %s %d %d\n", (int)mIsSnow, "SetDriftSpeed", min_value, max_value);
+	engine->PrintDebugConsole(buffer);
+#endif
+
+	ClipToRange(min_value, 0, 200);
+	ClipToRange(max_value, 0, 200);
+
+	if (min_value > max_value)
+		min_value = max_value;
+
+	mMinDriftSpeed = min_value;
+	mMaxDriftSpeed = max_value;
+	mDeltaDriftSpeed = mMaxDriftSpeed - mMinDriftSpeed;
+
+	if (mDeltaDriftSpeed == 0)
+		mDeltaDriftSpeed = 1;
+}
+
+
+void Weather::ChangeAmount(int amount) {
+#ifdef DEBUG
+	char buffer[200];
+	sprintf(buffer, "%d %s %d\n", (int)mIsSnow, "ChangeAmount", amount);
+	engine->PrintDebugConsole(buffer);
+#endif
+
+	ClipToRange(amount, 0, 1000);
+
+	mTargetAmount = amount;
+}
+
+
+void Weather::SetView(int kind_id, int event, int view, int loop) {
+#ifdef DEBUG
+	char buffer[200];
+	sprintf(buffer, "%d %s %d %d %d %d\n", (int)mIsSnow, "SetView", kind_id, event, view, loop);
+	engine->PrintDebugConsole(buffer);
+#endif
+
+	AGSViewFrame *view_frame = engine->GetViewFrame(view, loop, 0);
+	mViews[kind_id].bitmap = engine->GetSpriteGraphic(view_frame->pic);
+	mViews[kind_id].is_default = false;
+	mViews[kind_id].view = view;
+	mViews[kind_id].loop = loop;
+
+	if (!mViewsInitialized)
+		SetDefaultView(view, loop);
+}
+
+
+void Weather::SetDefaultView(int view, int loop) {
+#ifdef DEBUG
+	char buffer[200];
+	sprintf(buffer, "%d %s %d %d\n", (int)mIsSnow, "SetDefaultView", view, loop);
+	engine->PrintDebugConsole(buffer);
+#endif
+
+	AGSViewFrame *view_frame = engine->GetViewFrame(view, loop, 0);
+	BITMAP *bitmap = engine->GetSpriteGraphic(view_frame->pic);
+
+	mViewsInitialized = true;
+
+	int i;
+	for (i = 0; i < 5; i++) {
+		if (mViews[i].is_default) {
+			mViews[i].view = view;
+			mViews[i].loop = loop;
+			mViews[i].bitmap = bitmap;
+		}
+	}
+}
+
+
+void Weather::SetTransparency(int min_value, int max_value) {
+#ifdef DEBUG
+	char buffer[200];
+	sprintf(buffer, "%d %s %d %d\n", (int)mIsSnow, "SetTransparency", min_value, max_value);
+	engine->PrintDebugConsole(buffer);
+#endif
+
+	ClipToRange(min_value, 0, 100);
+	ClipToRange(max_value, 0, 100);
+
+	if (min_value > max_value)
+		min_value = max_value;
+
+	mMinAlpha = 255 - floor((float)max_value * 2.55f + 0.5f);
+	mMaxAlpha = 255 - floor((float)min_value * 2.55f + 0.5f);
+	mDeltaAlpha = mMaxAlpha - mMinAlpha;
+
+	if (mDeltaAlpha == 0)
+		mDeltaAlpha = 1;
+
+	int i;
+	for (i = 0; i < 2000; i++)
+		mParticles[i].alpha = rand() % mDeltaAlpha + mMinAlpha;
+}
+
+
+void Weather::SetWindSpeed(int value) {
+#ifdef DEBUG
+	char buffer[200];
+	sprintf(buffer, "%d %s %d\n", (int)mIsSnow, "SetWindSpeed", value);
+	engine->PrintDebugConsole(buffer);
+#endif
+
+	ClipToRange(value, -200, 200);
+
+	mWindSpeed = (float)value / 20.0f;
+}
+
+
+void Weather::SetBaseline(int top, int bottom) {
+#ifdef DEBUG
+	char buffer[200];
+	sprintf(buffer, "%d %s %d %d\n", (int)mIsSnow, "SetBaseline", top, bottom);
+	engine->PrintDebugConsole(buffer);
+#endif
+
+	if (screen_height > 0) {
+		ClipToRange(top, 0, screen_height);
+		ClipToRange(bottom, 0, screen_height);
+	}
+
+	if (top > bottom)
+		top = bottom;
+
+	mTopBaseline = top;
+	mBottomBaseline = bottom;
+	mDeltaBaseline = mBottomBaseline - mTopBaseline;
+
+	if (mDeltaBaseline == 0)
+		mDeltaBaseline = 1;
+}
+
+
+void Weather::SetAmount(int amount) {
+#ifdef DEBUG
+	char buffer[200];
+	sprintf(buffer, "%d %s %d\n", (int)mIsSnow, "SetAmount", amount);
+	engine->PrintDebugConsole(buffer);
+#endif
+
+	ClipToRange(amount, 0, 1000);
+
+	mAmount = mTargetAmount = amount;
+
+	InitializeParticles();
+}
+
+
+void Weather::SetFallSpeed(int min_value, int max_value) {
+#ifdef DEBUG
+	char buffer[200];
+	sprintf(buffer, "%d %s %d %d\n", (int)mIsSnow, "SetFallSpeed", min_value, max_value);
+	engine->PrintDebugConsole(buffer);
+#endif
+
+	ClipToRange(min_value, 0, 1000);
+	ClipToRange(max_value, 0, 1000);
+
+	if (min_value > max_value)
+		min_value = max_value;
+
+	mMinFallSpeed = min_value;
+	mMaxFallSpeed = max_value;
+	mDeltaFallSpeed = mMaxFallSpeed - mMinFallSpeed;
+
+	if (mDeltaFallSpeed == 0)
+		mDeltaFallSpeed = 1;
+}
+
+
+
+Weather *rain;
+Weather *snow;
+
+
+
+
+// ********************************************
+// ************  AGS Interface  ***************
+// ********************************************
+
+void srSetWindSpeed(int value) {
+	snow->SetWindSpeed(value);
+	rain->SetWindSpeed(value);
+}
+
+void srSetBaseline(int top, int bottom) {
+	snow->SetBaseline(top, bottom);
+	rain->SetBaseline(top, bottom);
+}
+
+void srSetSnowDriftRange(int min_value, int max_value) {
+	snow->SetDriftRange(min_value, max_value);
+}
+
+void srSetSnowDriftSpeed(int min_value, int max_value) {
+	snow->SetDriftSpeed(min_value, max_value);
+}
+
+void srChangeSnowAmount(int amount) {
+	snow->ChangeAmount(amount);
+}
+
+void srSetSnowView(int kind_id, int event, int view, int loop) {
+	snow->SetView(kind_id, event, view, loop);
+}
+
+void srSetSnowDefaultView(int view, int loop) {
+	snow->SetDefaultView(view, loop);
+}
+
+void srSetSnowTransparency(int min_value, int max_value) {
+	snow->SetTransparency(min_value, max_value);
+}
+
+void srSetSnowWindSpeed(int value) {
+	snow->SetWindSpeed(value);
+}
+
+void srSetSnowBaseline(int top, int bottom) {
+	snow->SetBaseline(top, bottom);
+}
+
+void srSetSnowAmount(int amount) {
+	snow->SetAmount(amount);
+}
+
+void srSetSnowFallSpeed(int min_value, int max_value) {
+	snow->SetFallSpeed(min_value, max_value);
+}
+
+void srSetRainDriftRange(int min_value, int max_value) {
+	rain->SetDriftRange(min_value, max_value);
+}
+
+void srSetRainDriftSpeed(int min_value, int max_value) {
+	rain->SetDriftSpeed(min_value, max_value);
+}
+
+void srChangeRainAmount(int amount) {
+	rain->ChangeAmount(amount);
+}
+
+void srSetRainView(int kind_id, int event, int view, int loop) {
+	rain->SetView(kind_id, event, view, loop);
+}
+
+void srSetRainDefaultView(int view, int loop) {
+	rain->SetDefaultView(view, loop);
+}
+
+void srSetRainTransparency(int min_value, int max_value) {
+	rain->SetTransparency(min_value, max_value);
+}
+
+void srSetRainWindSpeed(int value) {
+	rain->SetWindSpeed(value);
+}
+
+void srSetRainBaseline(int top, int bottom) {
+	rain->SetBaseline(top, bottom);
+}
+
+void srSetRainAmount(int amount) {
+	rain->SetAmount(amount);
+}
+
+void srSetRainFallSpeed(int min_value, int max_value) {
+	rain->SetFallSpeed(min_value, max_value);
+}
+
+void AGS_EngineStartup(IAGSEngine *lpEngine) {
+	engine = lpEngine;
+
+	if (engine->version < 13)
+		engine->AbortGame("Engine interface is too old, need newer version of AGS.");
+
+	engine->RegisterScriptFunction("srSetSnowDriftRange", (void *)&srSetSnowDriftRange);
+	engine->RegisterScriptFunction("srSetSnowDriftSpeed", (void *)&srSetSnowDriftSpeed);
+	engine->RegisterScriptFunction("srSetSnowFallSpeed", (void *)&srSetSnowFallSpeed);
+	engine->RegisterScriptFunction("srChangeSnowAmount", (void *)&srChangeSnowAmount);
+	engine->RegisterScriptFunction("srSetSnowBaseline", (void *)&srSetSnowBaseline);
+	engine->RegisterScriptFunction("srSetSnowTransparency", (void *)&srSetSnowTransparency);
+	engine->RegisterScriptFunction("srSetSnowDefaultView", (void *)&srSetSnowDefaultView);
+	engine->RegisterScriptFunction("srSetSnowWindSpeed", (void *)&srSetSnowWindSpeed);
+	engine->RegisterScriptFunction("srSetSnowAmount", (void *)&srSetSnowAmount);
+	engine->RegisterScriptFunction("srSetSnowView", (void *)&srSetSnowView);
+
+	engine->RegisterScriptFunction("srSetRainDriftRange", (void *)&srSetRainDriftRange);
+	engine->RegisterScriptFunction("srSetRainDriftSpeed", (void *)&srSetRainDriftSpeed);
+	engine->RegisterScriptFunction("srSetRainFallSpeed", (void *)&srSetRainFallSpeed);
+	engine->RegisterScriptFunction("srChangeRainAmount", (void *)&srChangeRainAmount);
+	engine->RegisterScriptFunction("srSetRainBaseline", (void *)&srSetRainBaseline);
+	engine->RegisterScriptFunction("srSetRainTransparency", (void *)&srSetRainTransparency);
+	engine->RegisterScriptFunction("srSetRainDefaultView", (void *)&srSetRainDefaultView);
+	engine->RegisterScriptFunction("srSetRainWindSpeed", (void *)&srSetRainWindSpeed);
+	engine->RegisterScriptFunction("srSetRainAmount", (void *)&srSetRainAmount);
+	engine->RegisterScriptFunction("srSetRainView", (void *)&srSetRainView);
+
+	engine->RegisterScriptFunction("srSetWindSpeed", (void *)&srSetWindSpeed);
+	engine->RegisterScriptFunction("srSetBaseline", (void *)&srSetBaseline);
+
+	engine->RequestEventHook(AGSE_PREGUIDRAW);
+	engine->RequestEventHook(AGSE_PRESCREENDRAW);
+	engine->RequestEventHook(AGSE_ENTERROOM);
+	engine->RequestEventHook(AGSE_SAVEGAME);
+	engine->RequestEventHook(AGSE_RESTOREGAME);
+
+	rain = new Weather;
+	snow = new Weather(true);
+}
+
+void AGS_EngineShutdown() {
+	delete rain;
+	delete snow;
+}
+
+int AGS_EngineOnEvent(int event, int data) {
+	if (event == AGSE_PREGUIDRAW) {
+		if (rain->IsActive())
+			rain->Update();
+
+		if (snow->IsActive())
+			snow->UpdateWithDrift();
+	} else if (event == AGSE_ENTERROOM) {
+		rain->EnterRoom();
+		snow->EnterRoom();
+	} else if (event == AGSE_RESTOREGAME) {
+		rain->RestoreGame(data);
+		snow->RestoreGame(data);
+	} else if (event == AGSE_SAVEGAME) {
+		rain->SaveGame(data);
+		snow->SaveGame(data);
+	} else if (event == AGSE_PRESCREENDRAW) {
+		// Get screen size once here
+		engine->GetScreenDimensions(&screen_width, &screen_height, &screen_color_depth);
+		engine->UnrequestEventHook(AGSE_PRESCREENDRAW);
+	}
+
+	return 0;
+}
+
+int AGS_EngineDebugHook(const char *scriptName, int lineNum, int reserved) {
+	return 0;
+}
+
+void AGS_EngineInitGfx(const char *driverID, void *data) {
+}
+
+
+
+#if AGS_PLATFORM_OS_WINDOWS && !defined(BUILTIN_PLUGINS)
+
+// ********************************************
+// ***********  Editor Interface  *************
+// ********************************************
+
+const char *scriptHeader =
+    "import void srSetSnowDriftSpeed(int, int);\r\n"
+    "import void srSetSnowDriftRange(int, int);\r\n"
+    "import void srSetSnowFallSpeed(int, int);\r\n"
+    "import void srChangeSnowAmount(int);\r\n"
+    "import void srSetSnowBaseline(int, int);\r\n"
+    "import void srChangeRainAmount(int);\r\n"
+    "import void srSetRainView(int, int, int, int);\r\n"
+    "import void srSetRainTransparency(int, int);\r\n"
+    "import void srSetSnowTransparency(int, int);\r\n"
+    "import void srSetSnowDefaultView(int, int);\r\n"
+    "import void srSetRainDefaultView(int, int);\r\n"
+    "import void srSetRainWindSpeed(int);\r\n"
+    "import void srSetSnowWindSpeed(int);\r\n"
+    "import void srSetWindSpeed(int);\r\n"
+    "import void srSetRainBaseline(int, int);\r\n"
+    "import void srSetBaseline(int, int);\r\n"
+    "import void srSetSnowAmount(int);\r\n"
+    "import void srSetRainAmount(int);\r\n"
+    "import void srSetRainFallSpeed(int, int);\r\n"
+    "import void srSetSnowView(int, int, int, int);\r\n";
+
+
+IAGSEditor *editor;
+
+
+LPCSTR AGS_GetPluginName(void) {
+	// Return the plugin description
+	return "Snow/Rain plugin recreation";
+}
+
+int  AGS_EditorStartup(IAGSEditor *lpEditor) {
+	// User has checked the plugin to use it in their game
+
+	// If it's an earlier version than what we need, abort.
+	if (lpEditor->version < 1)
+		return -1;
+
+	editor = lpEditor;
+	editor->RegisterScriptHeader(scriptHeader);
+
+	// Return 0 to indicate success
+	return 0;
+}
+
+void AGS_EditorShutdown() {
+	// User has un-checked the plugin from their game
+	editor->UnregisterScriptHeader(scriptHeader);
+}
+
+void AGS_EditorProperties(HWND parent) {
+	// User has chosen to view the Properties of the plugin
+	// We could load up an options dialog or something here instead
+	MessageBoxA(parent, "Snow/Rain plugin recreation by JJS", "About", MB_OK | MB_ICONINFORMATION);
+}
+
+int AGS_EditorSaveGame(char *buffer, int bufsize) {
+	// We don't want to save any persistent data
+	return 0;
+}
+
+void AGS_EditorLoadGame(char *buffer, int bufsize) {
+	// Nothing to load for this plugin
+}
+
+#endif
+
+
+#if defined(BUILTIN_PLUGINS)
+} // namespace ags_snowrain
+#endif
diff --git a/engines/ags/plugins/ags_snow_rain/ags_snow_rain.h b/engines/ags/plugins/ags_snow_rain/ags_snow_rain.h
new file mode 100644
index 0000000000..1d198af90b
--- /dev/null
+++ b/engines/ags/plugins/ags_snow_rain/ags_snow_rain.h
@@ -0,0 +1,14 @@
+#ifndef AGS_SNOWRAIN_H
+#define AGS_SNOWRAIN_H
+
+#include "plugin/agsplugin.h"
+
+namespace ags_snowrain {
+void AGS_EngineStartup(IAGSEngine *lpEngine);
+void AGS_EngineShutdown();
+int AGS_EngineOnEvent(int event, int data);
+int AGS_EngineDebugHook(const char *scriptName, int lineNum, int reserved);
+void AGS_EngineInitGfx(const char *driverID, void *data);
+}
+
+#endif
\ No newline at end of file
diff --git a/engines/ags/plugins/ags_sprite_font/ags_sprite_font.cpp b/engines/ags/plugins/ags_sprite_font/ags_sprite_font.cpp
new file mode 100644
index 0000000000..acbc19801d
--- /dev/null
+++ b/engines/ags/plugins/ags_sprite_font/ags_sprite_font.cpp
@@ -0,0 +1,279 @@
+/***********************************************************
+ * AGSBlend                                                *
+ *                                                         *
+ * Author: Steven Poulton                                  *
+ *                                                         *
+ * Date: 09/01/2011                                        *
+ *                                                         *
+ * Description: An AGS Plugin to allow true Alpha Blending *
+ *                                                         *
+ ***********************************************************/
+
+#pragma region Defines_and_Includes
+
+#include "core/platform.h"
+
+#define MIN_EDITOR_VERSION 1
+#define MIN_ENGINE_VERSION 3
+
+#if AGS_PLATFORM_OS_WINDOWS
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#include <WinBase.h>
+#endif
+
+#define THIS_IS_THE_PLUGIN
+#include "plugin/agsplugin.h"
+#include "SpriteFontRenderer.h"
+#include "VariableWidthSpriteFont.h"
+
+
+#define DEFAULT_RGB_R_SHIFT_32  16
+#define DEFAULT_RGB_G_SHIFT_32  8
+#define DEFAULT_RGB_B_SHIFT_32  0
+#define DEFAULT_RGB_A_SHIFT_32  24
+
+#define abs(a)                       ((a)<0 ? -(a) : (a))
+#define ChannelBlend_Normal(B,L)     ((uint8)(B))
+#define ChannelBlend_Lighten(B,L)    ((uint8)((L > B) ? L:B))
+#define ChannelBlend_Darken(B,L)     ((uint8)((L > B) ? B:L))
+#define ChannelBlend_Multiply(B,L)   ((uint8)((B * L) / 255))
+#define ChannelBlend_Average(B,L)    ((uint8)((B + L) / 2))
+#define ChannelBlend_Add(B,L)        ((uint8)(min(255, (B + L))))
+#define ChannelBlend_Subtract(B,L)   ((uint8)((B + L < 255) ? 0:(B + L - 255)))
+#define ChannelBlend_Difference(B,L) ((uint8)(abs(B - L)))
+#define ChannelBlend_Negation(B,L)   ((uint8)(255 - abs(255 - B - L)))
+#define ChannelBlend_Screen(B,L)     ((uint8)(255 - (((255 - B) * (255 - L)) >> 8)))
+#define ChannelBlend_Exclusion(B,L)  ((uint8)(B + L - 2 * B * L / 255))
+#define ChannelBlend_Overlay(B,L)    ((uint8)((L < 128) ? (2 * B * L / 255):(255 - 2 * (255 - B) * (255 - L) / 255)))
+#define ChannelBlend_SoftLight(B,L)  ((uint8)((L < 128)?(2*((B>>1)+64))*((float)L/255):(255-(2*(255-((B>>1)+64))*(float)(255-L)/255))))
+#define ChannelBlend_HardLight(B,L)  (ChannelBlend_Overlay(L,B))
+#define ChannelBlend_ColorDodge(B,L) ((uint8)((L == 255) ? L:min(255, ((B << 8 ) / (255 - L)))))
+#define ChannelBlend_ColorBurn(B,L)  ((uint8)((L == 0) ? L:max(0, (255 - ((255 - B) << 8 ) / L))))
+#define ChannelBlend_LinearDodge(B,L)(ChannelBlend_Add(B,L))
+#define ChannelBlend_LinearBurn(B,L) (ChannelBlend_Subtract(B,L))
+#define ChannelBlend_LinearLight(B,L)((uint8)(L < 128)?ChannelBlend_LinearBurn(B,(2 * L)):ChannelBlend_LinearDodge(B,(2 * (L - 128))))
+#define ChannelBlend_VividLight(B,L) ((uint8)(L < 128)?ChannelBlend_ColorBurn(B,(2 * L)):ChannelBlend_ColorDodge(B,(2 * (L - 128))))
+#define ChannelBlend_PinLight(B,L)   ((uint8)(L < 128)?ChannelBlend_Darken(B,(2 * L)):ChannelBlend_Lighten(B,(2 * (L - 128))))
+#define ChannelBlend_HardMix(B,L)    ((uint8)((ChannelBlend_VividLight(B,L) < 128) ? 0:255))
+#define ChannelBlend_Reflect(B,L)    ((uint8)((L == 255) ? L:min(255, (B * B / (255 - L)))))
+#define ChannelBlend_Glow(B,L)       (ChannelBlend_Reflect(L,B))
+#define ChannelBlend_Phoenix(B,L)    ((uint8)(min(B,L) - max(B,L) + 255))
+#define ChannelBlend_Alpha(B,L,O)    ((uint8)(O * B + (1 - O) * L))
+#define ChannelBlend_AlphaF(B,L,F,O) (ChannelBlend_Alpha(F(B,L),B,O))
+
+
+#pragma endregion
+
+
+#if AGS_PLATFORM_OS_WINDOWS
+// The standard Windows DLL entry point
+
+BOOL APIENTRY DllMain(HANDLE hModule,
+                      DWORD  ul_reason_for_call,
+                      LPVOID lpReserved) {
+
+	switch (ul_reason_for_call)   {
+	case DLL_PROCESS_ATTACH:
+	case DLL_THREAD_ATTACH:
+	case DLL_THREAD_DETACH:
+	case DLL_PROCESS_DETACH:
+		break;
+	}
+	return TRUE;
+}
+#endif
+
+
+//define engine
+
+IAGSEngine *engine = nullptr;
+SpriteFontRenderer *fontRenderer = nullptr;
+VariableWidthSpriteFontRenderer *vWidthRenderer = nullptr;
+
+
+
+void SetSpriteFont(int fontNum, int sprite, int rows, int columns, int charWidth, int charHeight, int charMin, int charMax, bool use32bit) {
+	engine->PrintDebugConsole("AGSSpriteFont: SetSpriteFont");
+	fontRenderer->SetSpriteFont(fontNum, sprite, rows, columns, charWidth, charHeight, charMin, charMax, use32bit);
+	engine->ReplaceFontRenderer(fontNum, fontRenderer);
+
+}
+
+void SetVariableSpriteFont(int fontNum, int sprite) {
+	engine->PrintDebugConsole("AGSSpriteFont: SetVariableFont");
+	vWidthRenderer->SetSprite(fontNum, sprite);
+	engine->ReplaceFontRenderer(fontNum, vWidthRenderer);
+}
+
+void SetGlyph(int fontNum, int charNum, int x, int y, int width, int height) {
+	engine->PrintDebugConsole("AGSSpriteFont: SetGlyph");
+	vWidthRenderer->SetGlyph(fontNum, charNum, x, y, width, height);
+}
+
+void SetSpacing(int fontNum, int spacing) {
+	engine->PrintDebugConsole("AGSSpriteFont: SetSpacing");
+	vWidthRenderer->SetSpacing(fontNum, spacing);
+}
+//==============================================================================
+
+#if AGS_PLATFORM_OS_WINDOWS && !defined(BUILTIN_PLUGINS)
+// ***** Design time *****
+
+IAGSEditor *editor; // Editor interface
+
+const char *ourScriptHeader =
+    "import void SetSpriteFont(int fontNum, int sprite, int rows, int columns, int charWidth, int charHeight, int charMin, int charMax, bool use32bit);\r\n"
+    "import void SetVariableSpriteFont(int fontNum, int sprite);\r\n"
+    "import void SetGlyph(int fontNum, int charNum, int x, int y, int width, int height);\r\n"
+    "import void SetSpacing(int fontNum, int spacing);\r\n"
+    ;
+
+//------------------------------------------------------------------------------
+
+LPCSTR AGS_GetPluginName() {
+	return ("AGSSpriteFont");
+}
+
+//------------------------------------------------------------------------------
+
+int AGS_EditorStartup(IAGSEditor *lpEditor) {
+	// User has checked the plugin to use it in their game
+
+	// If it's an earlier version than what we need, abort.
+	if (lpEditor->version < MIN_EDITOR_VERSION)
+		return (-1);
+
+	editor = lpEditor;
+	editor->RegisterScriptHeader(ourScriptHeader);
+
+	// Return 0 to indicate success
+	return (0);
+}
+
+//------------------------------------------------------------------------------
+
+void AGS_EditorShutdown() {
+	// User has un-checked the plugin from their game
+	editor->UnregisterScriptHeader(ourScriptHeader);
+}
+
+//------------------------------------------------------------------------------
+
+void AGS_EditorProperties(HWND parent) {                      //*** optional ***
+	// User has chosen to view the Properties of the plugin
+	// We could load up an options dialog or something here instead
+	MessageBox(parent,
+	           L"AGSSpriteFont v1.0 By Calin Leafshade",
+	           L"About",
+	           MB_OK | MB_ICONINFORMATION);
+}
+
+//------------------------------------------------------------------------------
+
+int AGS_EditorSaveGame(char *buffer, int bufsize) {           //*** optional ***
+	// Called by the editor when the current game is saved to disk.
+	// Plugin configuration can be stored in [buffer] (max [bufsize] bytes)
+	// Return the amount of bytes written in the buffer
+	return (0);
+}
+
+//------------------------------------------------------------------------------
+
+void AGS_EditorLoadGame(char *buffer, int bufsize) {          //*** optional ***
+	// Called by the editor when a game is loaded from disk
+	// Previous written data can be read from [buffer] (size [bufsize]).
+	// Make a copy of the data, the buffer is freed after this function call.
+}
+
+//==============================================================================
+#endif
+
+
+// ***** Run time *****
+
+// Engine interface
+
+//------------------------------------------------------------------------------
+
+#define REGISTER(x) engine->RegisterScriptFunction(#x, (void *) (x));
+#define STRINGIFY(s) STRINGIFY_X(s)
+#define STRINGIFY_X(s) #s
+
+
+
+void AGS_EngineStartup(IAGSEngine *lpEngine) {
+	engine = lpEngine;
+	engine->PrintDebugConsole("AGSSpriteFont: Init fixed width renderer");
+	fontRenderer = new SpriteFontRenderer(engine);
+	engine->PrintDebugConsole("AGSSpriteFont: Init vari width renderer");
+	vWidthRenderer = new VariableWidthSpriteFontRenderer(engine);
+	// Make sure it's got the version with the features we need
+	if (engine->version < MIN_ENGINE_VERSION)
+		engine->AbortGame("Plugin needs engine version " STRINGIFY(MIN_ENGINE_VERSION) " or newer.");
+
+	//register functions
+	engine->PrintDebugConsole("AGSSpriteFont: Register functions");
+	REGISTER(SetSpriteFont)
+	REGISTER(SetVariableSpriteFont)
+	REGISTER(SetGlyph)
+	REGISTER(SetSpacing)
+}
+
+//------------------------------------------------------------------------------
+
+void AGS_EngineShutdown() {
+	// Called by the game engine just before it exits.
+	// This gives you a chance to free any memory and do any cleanup
+	// that you need to do before the engine shuts down.
+}
+
+//------------------------------------------------------------------------------
+
+int AGS_EngineOnEvent(int event, int data) {                  //*** optional ***
+	switch (event) {
+	/*
+	        case AGSE_KEYPRESS:
+	        case AGSE_MOUSECLICK:
+	        case AGSE_POSTSCREENDRAW:
+	        case AGSE_PRESCREENDRAW:
+	        case AGSE_SAVEGAME:
+	        case AGSE_RESTOREGAME:
+	        case AGSE_PREGUIDRAW:
+	        case AGSE_LEAVEROOM:
+	        case AGSE_ENTERROOM:
+	        case AGSE_TRANSITIONIN:
+	        case AGSE_TRANSITIONOUT:
+	        case AGSE_FINALSCREENDRAW:
+	        case AGSE_TRANSLATETEXT:
+	        case AGSE_SCRIPTDEBUG:
+	        case AGSE_SPRITELOAD:
+	        case AGSE_PRERENDER:
+	        case AGSE_PRESAVEGAME:
+	        case AGSE_POSTRESTOREGAME:
+	*/
+	default:
+		break;
+	}
+
+	// Return 1 to stop event from processing further (when needed)
+	return (0);
+}
+
+//------------------------------------------------------------------------------
+/*
+int AGS_EngineDebugHook(const char *scriptName,
+                        int lineNum, int reserved)            //*** optional ***
+{
+    // Can be used to debug scripts, see documentation
+}
+*/
+//------------------------------------------------------------------------------
+/*
+void AGS_EngineInitGfx(const char *driverID, void *data)      //*** optional ***
+{
+    // This allows you to make changes to how the graphics driver starts up.
+    // See documentation
+}
+*/
+//..............................................................................
diff --git a/engines/ags/plugins/ags_sprite_font/character_entry.cpp b/engines/ags/plugins/ags_sprite_font/character_entry.cpp
new file mode 100644
index 0000000000..fa0575da7f
--- /dev/null
+++ b/engines/ags/plugins/ags_sprite_font/character_entry.cpp
@@ -0,0 +1,13 @@
+#include "CharacterEntry.h"
+
+
+CharacterEntry::CharacterEntry(void) {
+	X = 0;
+	Y = 0;
+	Width = 0;
+	Height = 0;
+	Character = 0;
+}
+
+
+CharacterEntry::~CharacterEntry(void) = default;
diff --git a/engines/ags/plugins/ags_sprite_font/character_entry.h b/engines/ags/plugins/ags_sprite_font/character_entry.h
new file mode 100644
index 0000000000..2d2a23f174
--- /dev/null
+++ b/engines/ags/plugins/ags_sprite_font/character_entry.h
@@ -0,0 +1,12 @@
+#pragma once
+class CharacterEntry {
+public:
+	CharacterEntry(void);
+	~CharacterEntry(void);
+	int X;
+	int Y;
+	int Width;
+	int Height;
+	char Character;
+};
+
diff --git a/engines/ags/plugins/ags_sprite_font/color.cpp b/engines/ags/plugins/ags_sprite_font/color.cpp
new file mode 100644
index 0000000000..9e9c13b957
--- /dev/null
+++ b/engines/ags/plugins/ags_sprite_font/color.cpp
@@ -0,0 +1,28 @@
+#include "color.h"
+
+int getr32(int c) {
+	return ((c >> DEFAULT_RGB_R_SHIFT_32) & 0xFF);
+}
+
+
+int getg32(int c) {
+	return ((c >> DEFAULT_RGB_G_SHIFT_32) & 0xFF);
+}
+
+
+int getb32(int c) {
+	return ((c >> DEFAULT_RGB_B_SHIFT_32) & 0xFF);
+}
+
+
+int geta32(int c) {
+	return ((c >> DEFAULT_RGB_A_SHIFT_32) & 0xFF);
+}
+
+
+int makeacol32(int r, int g, int b, int a) {
+	return ((r << DEFAULT_RGB_R_SHIFT_32) |
+	        (g << DEFAULT_RGB_G_SHIFT_32) |
+	        (b << DEFAULT_RGB_B_SHIFT_32) |
+	        (a << DEFAULT_RGB_A_SHIFT_32));
+}
\ No newline at end of file
diff --git a/engines/ags/plugins/ags_sprite_font/color.h b/engines/ags/plugins/ags_sprite_font/color.h
new file mode 100644
index 0000000000..314f02a50d
--- /dev/null
+++ b/engines/ags/plugins/ags_sprite_font/color.h
@@ -0,0 +1,21 @@
+#ifndef  __COLORH
+#define __COLORH
+
+#define MAX(a, b)  (((a) > (b)) ? (a) : (b))
+#define DEFAULT_RGB_R_SHIFT_32  16
+#define DEFAULT_RGB_G_SHIFT_32  8
+#define DEFAULT_RGB_B_SHIFT_32  0
+#define DEFAULT_RGB_A_SHIFT_32  24
+
+#pragma region Color_Functions
+
+
+int getr32(int c);
+int getg32(int c);
+int getb32(int c);
+int geta32(int c);
+int makeacol32(int r, int g, int b, int a);
+
+#pragma endregion
+
+#endif
\ No newline at end of file
diff --git a/engines/ags/plugins/ags_sprite_font/sprite_font.cpp b/engines/ags/plugins/ags_sprite_font/sprite_font.cpp
new file mode 100644
index 0000000000..19e4ea1997
--- /dev/null
+++ b/engines/ags/plugins/ags_sprite_font/sprite_font.cpp
@@ -0,0 +1,7 @@
+#include "SpriteFont.h"
+
+
+SpriteFont::SpriteFont(void) = default;
+
+
+SpriteFont::~SpriteFont(void) = default;
diff --git a/engines/ags/plugins/ags_sprite_font/sprite_font.h b/engines/ags/plugins/ags_sprite_font/sprite_font.h
new file mode 100644
index 0000000000..860aaddeae
--- /dev/null
+++ b/engines/ags/plugins/ags_sprite_font/sprite_font.h
@@ -0,0 +1,16 @@
+#pragma once
+class SpriteFont {
+public:
+	SpriteFont(void);
+	~SpriteFont(void);
+	int SpriteNumber;
+	int MinChar;
+	int MaxChar;
+	int Rows;
+	int Columns;
+	int FontReplaced;
+	int CharHeight;
+	int CharWidth;
+	bool Use32bit;
+};
+
diff --git a/engines/ags/plugins/ags_sprite_font/sprite_font_renderer.cpp b/engines/ags/plugins/ags_sprite_font/sprite_font_renderer.cpp
new file mode 100644
index 0000000000..c12fca0382
--- /dev/null
+++ b/engines/ags/plugins/ags_sprite_font/sprite_font_renderer.cpp
@@ -0,0 +1,171 @@
+#include "SpriteFontRenderer.h"
+#include <stdio.h>
+#include <string.h>
+#include "color.h"
+
+
+
+SpriteFontRenderer::SpriteFontRenderer(IAGSEngine *engine) {
+	_engine = engine;
+}
+
+
+SpriteFontRenderer::~SpriteFontRenderer(void) = default;
+
+void SpriteFontRenderer::SetSpriteFont(int fontNum, int sprite, int rows, int columns, int charWidth, int charHeight, int charMin, int charMax, bool use32bit) {
+	SpriteFont *font = getFontFor(fontNum);
+	font->SpriteNumber = sprite;
+	font->Rows = rows;
+	font->Columns = columns;
+	font->MinChar = charMin;
+	font->MaxChar = charMax;
+	font->Use32bit = use32bit;
+	font->CharHeight = charHeight;
+	font->CharWidth = charWidth;
+
+}
+
+void SpriteFontRenderer::EnsureTextValidForFont(char *text, int fontNumber) {
+	SpriteFont *font = getFontFor(fontNumber);
+	for (int i = 0; i < strlen(text); i++) {
+		if (text[i] < font->MinChar || text[i] > font->MaxChar) {
+			if (font->MinChar < 63 || font->MaxChar > 63) text[i] = 63;
+			else text[i] = font->MinChar;
+
+		}
+
+	}
+}
+
+bool SpriteFontRenderer::SupportsExtendedCharacters(int fontNumber) {
+	return false;
+}
+
+int SpriteFontRenderer::GetTextWidth(const char *text, int fontNumber) {
+	SpriteFont *font = getFontFor(fontNumber);
+	int len = strlen(text);
+	return font->CharWidth * len;
+
+}
+
+int SpriteFontRenderer::GetTextHeight(const char *text, int fontNumber) {
+	SpriteFont *font = getFontFor(fontNumber);
+	return font->CharHeight;
+}
+
+SpriteFont *SpriteFontRenderer::getFontFor(int fontNum) {
+	SpriteFont *font;
+	for (int i = 0; i < _fonts.size(); i ++) {
+		font = _fonts.at(i);
+		if (font->FontReplaced == fontNum) return font;
+	}
+	//not found
+	font = new SpriteFont();
+	font->FontReplaced = fontNum;
+	_fonts.push_back(font);
+	return font;
+}
+
+
+
+void SpriteFontRenderer::RenderText(const char *text, int fontNumber, BITMAP *destination, int x, int y, int colour) {
+
+	SpriteFont *font = getFontFor(fontNumber);
+	BITMAP *vScreen = _engine->GetVirtualScreen();
+
+	//_engine->SetVirtualScreen(destination);
+
+	for (int i = 0; i < strlen(text); i++) {
+		char c = text[i];
+		c -= font->MinChar;
+		int row = c / font->Columns;
+		int column = c % font->Columns;
+		BITMAP *src = _engine->GetSpriteGraphic(font->SpriteNumber);
+		Draw(src, destination, x + (i * font->CharWidth), y, column * font->CharWidth, row * font->CharHeight, font->CharWidth, font->CharHeight);
+	}
+
+	//_engine->SetVirtualScreen(vScreen);
+}
+
+
+
+
+void SpriteFontRenderer::Draw(BITMAP *src, BITMAP *dest, int destx, int desty, int srcx, int srcy, int width, int height) {
+
+	int srcWidth, srcHeight, destWidth, destHeight, srcColDepth, destColDepth;
+
+	unsigned char **srccharbuffer = _engine->GetRawBitmapSurface(src);  //8bit
+	unsigned short **srcshortbuffer = (unsigned short **)srccharbuffer; //16bit;
+	unsigned int **srclongbuffer = (unsigned int **)srccharbuffer; //32bit
+
+	unsigned char **destcharbuffer = _engine->GetRawBitmapSurface(dest);  //8bit
+	unsigned short **destshortbuffer = (unsigned short **)destcharbuffer; //16bit;
+	unsigned int **destlongbuffer = (unsigned int **)destcharbuffer; //32bit
+
+	int transColor = _engine->GetBitmapTransparentColor(src);
+
+	_engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, &srcColDepth);
+	_engine->GetBitmapDimensions(dest, &destWidth, &destHeight, &destColDepth);
+
+	if (srcy + height > srcHeight || srcx + width > srcWidth || srcx < 0 || srcy < 0) return;
+
+	if (width + destx > destWidth) width = destWidth - destx;
+	if (height + desty > destHeight) height = destHeight - desty;
+
+	int startx = MAX(0, (-1 * destx));
+	int starty = MAX(0, (-1 * desty));
+
+
+	int srca, srcr, srcg, srcb, desta, destr, destg, destb, finalr, finalg, finalb, finala, col;
+
+	for (int x = startx; x < width; x ++) {
+
+		for (int y = starty; y <  height; y ++) {
+			int srcyy = y + srcy;
+			int srcxx = x + srcx;
+			int destyy = y + desty;
+			int destxx = x + destx;
+			if (destColDepth == 8) {
+				if (srccharbuffer[srcyy][srcxx] != transColor) destcharbuffer[destyy][destxx] = srccharbuffer[srcyy][srcxx];
+			} else if (destColDepth == 16) {
+				if (srcshortbuffer[srcyy][srcxx] != transColor) destshortbuffer[destyy][destxx] = srcshortbuffer[srcyy][srcxx];
+			} else if (destColDepth == 32) {
+				//if (srclongbuffer[srcyy][srcxx] != transColor) destlongbuffer[destyy][destxx] = srclongbuffer[srcyy][srcxx];
+
+				srca = (geta32(srclongbuffer[srcyy][srcxx]));
+
+				if (srca != 0) {
+
+					srcr =  getr32(srclongbuffer[srcyy][srcxx]);
+					srcg =  getg32(srclongbuffer[srcyy][srcxx]);
+					srcb =  getb32(srclongbuffer[srcyy][srcxx]);
+
+					destr =  getr32(destlongbuffer[destyy][destxx]);
+					destg =  getg32(destlongbuffer[destyy][destxx]);
+					destb =  getb32(destlongbuffer[destyy][destxx]);
+					desta =  geta32(destlongbuffer[destyy][destxx]);
+
+
+					finalr = srcr;
+					finalg = srcg;
+					finalb = srcb;
+
+
+					finala = 255 - (255 - srca) * (255 - desta) / 255;
+					finalr = srca * finalr / finala + desta * destr * (255 - srca) / finala / 255;
+					finalg = srca * finalg / finala + desta * destg * (255 - srca) / finala / 255;
+					finalb = srca * finalb / finala + desta * destb * (255 - srca) / finala / 255;
+					col = makeacol32(finalr, finalg, finalb, finala);
+					destlongbuffer[destyy][destxx] = col;
+				}
+
+			}
+		}
+	}
+
+	_engine->ReleaseBitmapSurface(src);
+	_engine->ReleaseBitmapSurface(dest);
+
+
+
+}
\ No newline at end of file
diff --git a/engines/ags/plugins/ags_sprite_font/sprite_font_renderer.h b/engines/ags/plugins/ags_sprite_font/sprite_font_renderer.h
new file mode 100644
index 0000000000..0fcd57684f
--- /dev/null
+++ b/engines/ags/plugins/ags_sprite_font/sprite_font_renderer.h
@@ -0,0 +1,29 @@
+#pragma once
+#include "plugin/agsplugin.h"
+#include "SpriteFont.h"
+#include <vector>
+class SpriteFontRenderer :
+	public IAGSFontRenderer {
+public:
+	SpriteFontRenderer(IAGSEngine *engine);
+	~SpriteFontRenderer(void);
+	bool LoadFromDisk(int fontNumber, int fontSize) override {
+		return true;
+	}
+	void FreeMemory(int fontNumber) override { }
+	bool SupportsExtendedCharacters(int fontNumber) override;
+	int GetTextWidth(const char *text, int fontNumber) override;
+	int GetTextHeight(const char *text, int fontNumber) override;
+	void RenderText(const char *text, int fontNumber, BITMAP *destination, int x, int y, int colour) override;
+	void AdjustYCoordinateForFont(int *ycoord, int fontNumber) override { }
+	void EnsureTextValidForFont(char *text, int fontNumber) override;
+	void SetSpriteFont(int fontNum, int sprite, int rows, int columns, int charWidth, int charHeight, int charMin, int charMax, bool use32bit);
+
+
+private:
+	SpriteFont *getFontFor(int fontNum);
+	void Draw(BITMAP *src, BITMAP *dest, int destx, int desty, int srcx, int srcy, int width, int height);
+	std::vector<SpriteFont * > _fonts;
+	IAGSEngine *_engine;
+};
+
diff --git a/engines/ags/plugins/ags_sprite_font/variable_width_font.cpp b/engines/ags/plugins/ags_sprite_font/variable_width_font.cpp
new file mode 100644
index 0000000000..41baaac170
--- /dev/null
+++ b/engines/ags/plugins/ags_sprite_font/variable_width_font.cpp
@@ -0,0 +1,19 @@
+#include "VariableWidthFont.h"
+
+
+VariableWidthFont::VariableWidthFont(void) {
+	Spacing = 0;
+	FontReplaced = 0;
+	SpriteNumber = 0;
+}
+
+
+VariableWidthFont::~VariableWidthFont(void) = default;
+
+void VariableWidthFont::SetGlyph(int character, int x, int y, int width, int height) {
+	characters[character].X = x;
+	characters[character].Y = y;
+	characters[character].Width = width;
+	characters[character].Height = height;
+	characters[character].Character = character;
+}
diff --git a/engines/ags/plugins/ags_sprite_font/variable_width_font.h b/engines/ags/plugins/ags_sprite_font/variable_width_font.h
new file mode 100644
index 0000000000..8eda7123cf
--- /dev/null
+++ b/engines/ags/plugins/ags_sprite_font/variable_width_font.h
@@ -0,0 +1,18 @@
+#pragma once
+#include <map>
+#include "CharacterEntry.h"
+#include "plugin/agsplugin.h"
+class VariableWidthFont {
+public:
+	VariableWidthFont(void);
+	~VariableWidthFont(void);
+	void SetGlyph(int character, int x, int y, int width, int height);
+	int SpriteNumber;
+	int FontReplaced;
+	int Spacing;
+	std::map<char, CharacterEntry> characters;
+
+private:
+
+};
+
diff --git a/engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.cpp b/engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.cpp
new file mode 100644
index 0000000000..b6015ef8e1
--- /dev/null
+++ b/engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.cpp
@@ -0,0 +1,182 @@
+#include "VariableWidthSpriteFont.h"
+#include <string>
+#include <string.h>
+#include "color.h"
+
+
+
+VariableWidthSpriteFontRenderer::VariableWidthSpriteFontRenderer(IAGSEngine *engine) {
+	_engine = engine;
+}
+
+
+VariableWidthSpriteFontRenderer::~VariableWidthSpriteFontRenderer(void) = default;
+
+
+
+
+bool VariableWidthSpriteFontRenderer::SupportsExtendedCharacters(int fontNumber) {
+	return false;
+}
+
+int VariableWidthSpriteFontRenderer::GetTextWidth(const char *text, int fontNumber) {
+	int total = 0;
+	VariableWidthFont *font = getFontFor(fontNumber);
+	for (int i = 0; i < strlen(text); i++) {
+		if (font->characters.count(text[i]) > 0) {
+			total += font->characters[text[i]].Width;
+			if (text[i] != ' ') total += font->Spacing;
+		}
+	}
+	return total;
+}
+
+int VariableWidthSpriteFontRenderer::GetTextHeight(const char *text, int fontNumber) {
+	VariableWidthFont *font = getFontFor(fontNumber);
+	for (int i = 0; i < strlen(text); i++) {
+		if (font->characters.count(text[i]) > 0) {
+			return font->characters[text[i]].Height;
+		}
+	}
+	return 0;
+}
+
+void VariableWidthSpriteFontRenderer::SetSpacing(int fontNum, int spacing) {
+	VariableWidthFont *font = getFontFor(fontNum);
+	font->Spacing = spacing;
+
+
+}
+
+void VariableWidthSpriteFontRenderer::EnsureTextValidForFont(char *text, int fontNumber) {
+	VariableWidthFont *font = getFontFor(fontNumber);
+	std::string s(text);
+
+	for (int i = s.length() - 1; i >= 0 ; i--) {
+		if (font->characters.count(s[i]) == 0) {
+			s.erase(i, 1);
+		}
+	}
+	text = strcpy(text, s.c_str());
+
+}
+
+void VariableWidthSpriteFontRenderer::SetGlyph(int fontNum, int charNum, int x, int y, int width, int height) {
+	VariableWidthFont *font = getFontFor(fontNum);
+	font->SetGlyph(charNum, x, y, width, height);
+}
+
+
+void VariableWidthSpriteFontRenderer::SetSprite(int fontNum, int spriteNum) {
+	VariableWidthFont *font = getFontFor(fontNum);
+	font->SpriteNumber = spriteNum;
+}
+
+VariableWidthFont *VariableWidthSpriteFontRenderer::getFontFor(int fontNum) {
+	VariableWidthFont *font;
+	for (int i = 0; i < _fonts.size(); i ++) {
+		font = _fonts.at(i);
+		if (font->FontReplaced == fontNum) return font;
+	}
+	//not found
+	font = new VariableWidthFont;
+	font->FontReplaced = fontNum;
+	_fonts.push_back(font);
+	return font;
+}
+
+void VariableWidthSpriteFontRenderer::RenderText(const char *text, int fontNumber, BITMAP *destination, int x, int y, int colour) {
+	VariableWidthFont *font = getFontFor(fontNumber);
+	int totalWidth = 0;
+	for (int i = 0; i < strlen(text); i++) {
+		char c = text[i];
+
+		BITMAP *src = _engine->GetSpriteGraphic(font->SpriteNumber);
+		Draw(src, destination, x + totalWidth, y, font->characters[c].X, font->characters[c].Y, font->characters[c].Width, font->characters[c].Height);
+		totalWidth += font->characters[c].Width;
+		if (text[i] != ' ') totalWidth += font->Spacing;
+	}
+
+}
+
+
+void VariableWidthSpriteFontRenderer::Draw(BITMAP *src, BITMAP *dest, int destx, int desty, int srcx, int srcy, int width, int height) {
+
+	int srcWidth, srcHeight, destWidth, destHeight, srcColDepth, destColDepth;
+
+	unsigned char **srccharbuffer = _engine->GetRawBitmapSurface(src);  //8bit
+	unsigned short **srcshortbuffer = (unsigned short **)srccharbuffer; //16bit;
+	unsigned int **srclongbuffer = (unsigned int **)srccharbuffer; //32bit
+
+	unsigned char **destcharbuffer = _engine->GetRawBitmapSurface(dest);  //8bit
+	unsigned short **destshortbuffer = (unsigned short **)destcharbuffer; //16bit;
+	unsigned int **destlongbuffer = (unsigned int **)destcharbuffer; //32bit
+
+	int transColor = _engine->GetBitmapTransparentColor(src);
+
+	_engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, &srcColDepth);
+	_engine->GetBitmapDimensions(dest, &destWidth, &destHeight, &destColDepth);
+
+	if (srcy + height > srcHeight || srcx + width > srcWidth || srcx < 0 || srcy < 0) return;
+
+	if (width + destx > destWidth) width = destWidth - destx;
+	if (height + desty > destHeight) height = destHeight - desty;
+
+	int startx = MAX(0, (-1 * destx));
+	int starty = MAX(0, (-1 * desty));
+
+
+	int srca, srcr, srcg, srcb, desta, destr, destg, destb, finalr, finalg, finalb, finala, col;
+
+	for (int x = startx; x < width; x ++) {
+
+		for (int y = starty; y <  height; y ++) {
+			int srcyy = y + srcy;
+			int srcxx = x + srcx;
+			int destyy = y + desty;
+			int destxx = x + destx;
+			if (destColDepth == 8) {
+				if (srccharbuffer[srcyy][srcxx] != transColor) destcharbuffer[destyy][destxx] = srccharbuffer[srcyy][srcxx];
+			} else if (destColDepth == 16) {
+				if (srcshortbuffer[srcyy][srcxx] != transColor) destshortbuffer[destyy][destxx] = srcshortbuffer[srcyy][srcxx];
+			} else if (destColDepth == 32) {
+				//if (srclongbuffer[srcyy][srcxx] != transColor) destlongbuffer[destyy][destxx] = srclongbuffer[srcyy][srcxx];
+
+				srca = (geta32(srclongbuffer[srcyy][srcxx]));
+
+				if (srca != 0) {
+
+					srcr =  getr32(srclongbuffer[srcyy][srcxx]);
+					srcg =  getg32(srclongbuffer[srcyy][srcxx]);
+					srcb =  getb32(srclongbuffer[srcyy][srcxx]);
+
+					destr =  getr32(destlongbuffer[destyy][destxx]);
+					destg =  getg32(destlongbuffer[destyy][destxx]);
+					destb =  getb32(destlongbuffer[destyy][destxx]);
+					desta =  geta32(destlongbuffer[destyy][destxx]);
+
+
+					finalr = srcr;
+					finalg = srcg;
+					finalb = srcb;
+
+
+					finala = 255 - (255 - srca) * (255 - desta) / 255;
+					finalr = srca * finalr / finala + desta * destr * (255 - srca) / finala / 255;
+					finalg = srca * finalg / finala + desta * destg * (255 - srca) / finala / 255;
+					finalb = srca * finalb / finala + desta * destb * (255 - srca) / finala / 255;
+					col = makeacol32(finalr, finalg, finalb, finala);
+					destlongbuffer[destyy][destxx] = col;
+				}
+
+			}
+		}
+	}
+
+	_engine->ReleaseBitmapSurface(src);
+	_engine->ReleaseBitmapSurface(dest);
+
+
+
+}
+
diff --git a/engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.h b/engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.h
new file mode 100644
index 0000000000..30b5211ca3
--- /dev/null
+++ b/engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.h
@@ -0,0 +1,30 @@
+#pragma once
+#include "plugin/agsplugin.h"
+#include "VariableWidthFont.h"
+#include <vector>
+class VariableWidthSpriteFontRenderer :
+	public IAGSFontRenderer {
+public:
+	VariableWidthSpriteFontRenderer(IAGSEngine *engine);
+	~VariableWidthSpriteFontRenderer(void);
+	bool LoadFromDisk(int fontNumber, int fontSize) override {
+		return true;
+	}
+	void FreeMemory(int fontNumber) override { }
+	bool SupportsExtendedCharacters(int fontNumber) override;
+	int GetTextWidth(const char *text, int fontNumber) override;
+	int GetTextHeight(const char *text, int fontNumber) override;
+	void RenderText(const char *text, int fontNumber, BITMAP *destination, int x, int y, int colour) override;
+	void AdjustYCoordinateForFont(int *ycoord, int fontNumber) override { }
+	void EnsureTextValidForFont(char *text, int fontNumber) override;
+	void SetGlyph(int fontNum, int charNum, int x, int y, int width, int height);
+	void SetSprite(int fontNum, int spriteNum);
+	void SetSpacing(int fontNum, int spacing);
+
+private:
+	IAGSEngine *_engine;
+	std::vector<VariableWidthFont * > _fonts;
+	VariableWidthFont *getFontFor(int fontNum);
+	void Draw(BITMAP *src, BITMAP *dest, int destx, int desty, int srcx, int srcy, int width, int height);
+};
+
diff --git a/engines/ags/plugins/dll.cpp b/engines/ags/plugins/dll.cpp
index 76dcb86a23..1662de7958 100644
--- a/engines/ags/plugins/dll.cpp
+++ b/engines/ags/plugins/dll.cpp
@@ -22,7 +22,7 @@
 
 #include "ags/lib/allegro.h"
 #include "ags/plugins/dll.h"
-#include "ags/plugins/agscreditz/agscreditz.h"
+#include "ags/plugins/ags_creditz/ags_creditz.h"
 #include "ags/ags.h"
 #include "ags/detection.h"
 #include "common/str.h"
@@ -36,7 +36,7 @@ void *dlopen(const char *filename) {
 	// Check for if the game specifies a specific plugin version for this game
 	int version = 0;
 	for (const ::AGS::PluginVersion *v = ::AGS::g_vm->getNeededPlugins();
-			v->_plugin; ++v) {
+	        v->_plugin; ++v) {
 		if (Common::String::format("lib%s.so", v->_plugin).equalsIgnoreCase(filename)) {
 			version = v->_version;
 			break;
diff --git a/engines/ags/plugins/dll.h b/engines/ags/plugins/dll.h
index d1e9c768a3..5b797a3d49 100644
--- a/engines/ags/plugins/dll.h
+++ b/engines/ags/plugins/dll.h
@@ -91,7 +91,9 @@ class DLL {
 protected:
 	Common::HashMap<Common::String, void *, Common::IgnoreCase_Hash, Common::IgnoreCase_EqualTo> _methods;
 
-	static int    AGS_PluginV2() { return 1; }
+	static int    AGS_PluginV2() {
+		return 1;
+	}
 	static int    AGS_EditorStartup(IAGSEditor *);
 	static void   AGS_EditorShutdown();
 	static void   AGS_EditorProperties(HWND);


Commit: 8dcf692ce5b2d18451629a6ae73a4eb13712008b
    https://github.com/scummvm/scummvm/commit/8dcf692ce5b2d18451629a6ae73a4eb13712008b
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added AGSFlashlight plugin

Changed paths:
    engines/ags/module.mk
    engines/ags/plugins/ags_flashlight/ags_flashlight.cpp
    engines/ags/plugins/ags_flashlight/ags_flashlight.h
    engines/ags/plugins/dll.cpp


diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index ad2657cdcd..75c55be114 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -301,7 +301,8 @@ MODULE_OBJS = \
 	engine/script/script_runtime.o \
 	engine/script/systemimports.o \
 	plugins/dll.o \
-	plugins/ags_creditz/ags_creditz.o
+	plugins/ags_creditz/ags_creditz.o \
+	plugins/ags_flashlight/ags_flashlight.o
 
 ifdef ENABLE_AGS_TESTS
 MODULE_OBJS += \
diff --git a/engines/ags/plugins/ags_flashlight/ags_flashlight.cpp b/engines/ags/plugins/ags_flashlight/ags_flashlight.cpp
index 663e81c1b1..c36e7ec401 100644
--- a/engines/ags/plugins/ags_flashlight/ags_flashlight.cpp
+++ b/engines/ags/plugins/ags_flashlight/ags_flashlight.cpp
@@ -1,131 +1,241 @@
-/*
+/* 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 not the AGS Flashlight plugin,
-but a workalike plugin created by JJS for the AGS engine PSP port.
+#include "ags/lib/allegro.h"
+#include "ags/plugins/ags_flashlight/ags_flashlight.h"
+#include "ags/shared/core/platform.h"
+#include "common/str.h"
 
-*/
+namespace AGS3 {
+namespace Plugins {
+namespace AGSFlashlight {
 
-#include "core/platform.h"
+const unsigned int Magic = 0xBABE0000;
+const unsigned int Version = 2;
+const unsigned int SaveMagic = Magic + Version;
+const float PI = 3.14159265f;
 
-#if AGS_PLATFORM_OS_WINDOWS
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#pragma warning(disable : 4244)
-#endif
+int AGSFlashlight::AGSFlashlight::screen_width = 320;
+int AGSFlashlight::screen_height = 200;
+int AGSFlashlight::screen_color_depth = 16;
 
-#if !defined(BUILTIN_PLUGINS)
-#define THIS_IS_THE_PLUGIN
-#endif
+bool AGSFlashlight::g_BitmapMustBeUpdated = true;
 
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <math.h>
+int AGSFlashlight::g_RedTint = 0;
+int AGSFlashlight::g_GreenTint = 0;
+int AGSFlashlight::g_BlueTint = 0;
 
-#if defined(PSP_VERSION)
-#include <pspsdk.h>
-#include <pspmath.h>
-#include <pspdisplay.h>
-#define sin(x) vfpu_sinf(x)
-#endif
+int AGSFlashlight::g_DarknessLightLevel = 100;
+int AGSFlashlight::g_BrightnessLightLevel = 100;
+int AGSFlashlight::g_DarknessSize = 0;
+int AGSFlashlight::g_DarknessDiameter = 0;
+int AGSFlashlight::g_BrightnessSize = 0;
 
-#include "plugin/agsplugin.h"
+int AGSFlashlight::g_FlashlightX = 0;
+int AGSFlashlight::g_FlashlightY = 0;
+int AGSFlashlight::g_FlashlightDrawAtX = 0;
+int AGSFlashlight::g_FlashlightDrawAtY = 0;
 
-#if defined(BUILTIN_PLUGINS)
-namespace agsflashlight {
-#endif
+bool AGSFlashlight::g_FlashlightFollowMouse = false;
 
-#if defined(__GNUC__)
-inline unsigned long _blender_alpha16_bgr(unsigned long y) __attribute__((always_inline));
-inline void calc_x_n(unsigned long bla) __attribute__((always_inline));
-#endif
+int AGSFlashlight::g_FollowCharacterId = 0;
+int AGSFlashlight::g_FollowCharacterDx = 0;
+int AGSFlashlight::g_FollowCharacterDy = 0;
+int AGSFlashlight::g_FollowCharacterHorz = 0;
+int AGSFlashlight::g_FollowCharacterVert = 0;
 
-const unsigned int Magic = 0xBABE0000;
-const unsigned int Version = 2;
-const unsigned int SaveMagic = Magic + Version;
-const float PI = 3.14159265f;
+AGSCharacter *AGSFlashlight::g_FollowCharacter = nullptr;
+
+BITMAP *AGSFlashlight::g_LightBitmap = nullptr;
 
-int screen_width = 320;
-int screen_height = 200;
-int screen_color_depth = 16;
+unsigned long AGSFlashlight::flashlight_x;
+unsigned long AGSFlashlight::flashlight_n;
 
-IAGSEngine *engine;
 
-bool g_BitmapMustBeUpdated = true;
+IAGSEngine *AGSFlashlight::_engine;
 
-int g_RedTint = 0;
-int g_GreenTint = 0;
-int g_BlueTint = 0;
+AGSFlashlight::AGSFlashlight() {
+	_engine = nullptr;
+	screen_width = 320;
+	screen_height = 200;
+	screen_color_depth = 16;
 
-int g_DarknessLightLevel = 100;
-int g_BrightnessLightLevel = 100;
-int g_DarknessSize = 0;
-int g_DarknessDiameter = 0;
-int g_BrightnessSize = 0;
+	g_BitmapMustBeUpdated = true;
 
-int g_FlashlightX = 0;
-int g_FlashlightY = 0;
-int g_FlashlightDrawAtX = 0;
-int g_FlashlightDrawAtY = 0;
+	g_RedTint = 0;
+	g_GreenTint = 0;
+	g_BlueTint = 0;
 
-bool g_FlashlightFollowMouse = false;
+	g_DarknessLightLevel = 100;
+	g_BrightnessLightLevel = 100;
+	g_DarknessSize = 0;
+	g_DarknessDiameter = 0;
+	g_BrightnessSize = 0;
 
-int g_FollowCharacterId = 0;
-int g_FollowCharacterDx = 0;
-int g_FollowCharacterDy = 0;
-int g_FollowCharacterHorz = 0;
-int g_FollowCharacterVert = 0;
+	g_FlashlightX = 0;
+	g_FlashlightY = 0;
+	g_FlashlightDrawAtX = 0;
+	g_FlashlightDrawAtY = 0;
 
-AGSCharacter *g_FollowCharacter = nullptr;
+	g_FlashlightFollowMouse = false;
 
-BITMAP *g_LightBitmap = nullptr;
+	g_FollowCharacterId = 0;
+	g_FollowCharacterDx = 0;
+	g_FollowCharacterDy = 0;
+	g_FollowCharacterHorz = 0;
+	g_FollowCharacterVert = 0;
 
+	g_FollowCharacter = nullptr;
+	g_LightBitmap = nullptr;
+	flashlight_x = 0;
+	flashlight_n = 0;
 
-// This function is from Allegro, split for more performance.
 
-/* _blender_alpha16_bgr
- *  Combines a 32 bit RGBA sprite with a 16 bit RGB destination, optimised
- *  for when one pixel is in an RGB layout and the other is BGR.
- */
+	DLL_METHOD(AGS_GetPluginName);
+	DLL_METHOD(AGS_EngineShutdown);
+	DLL_METHOD(AGS_EngineOnEvent);
+	DLL_METHOD(AGS_EngineDebugHook);
+	DLL_METHOD(AGS_EngineInitGfx);
+}
+
+const char *AGSFlashlight::AGS_GetPluginName() {
+	return "Flashlight plugin recreation";
+}
 
-unsigned long x, n;
+void AGSFlashlight::AGS_EngineStartup(IAGSEngine *engine) {
+	_engine = engine;
 
-inline void calc_x_n(unsigned long _x) {
-	x = _x;
+	if (_engine->version < 13)
+		_engine->AbortGame("Engine interface is too old, need newer version of AGS.");
+
+	SCRIPT_METHOD("SetFlashlightTint");
+	SCRIPT_METHOD("GetFlashlightTintRed");
+	SCRIPT_METHOD("GetFlashlightTintGreen");
+	SCRIPT_METHOD("GetFlashlightTintBlue");
+
+	SCRIPT_METHOD("GetFlashlightMinLightLevel");
+	SCRIPT_METHOD("GetFlashlightMaxLightLevel");
+
+	SCRIPT_METHOD("SetFlashlightDarkness");
+	SCRIPT_METHOD("GetFlashlightDarkness");
+	SCRIPT_METHOD("SetFlashlightDarknessSize");
+	SCRIPT_METHOD("GetFlashlightDarknessSize");
+
+	SCRIPT_METHOD("SetFlashlightBrightness");
+	SCRIPT_METHOD("GetFlashlightBrightness");
+	SCRIPT_METHOD("SetFlashlightBrightnessSize");
+	SCRIPT_METHOD("GetFlashlightBrightnessSize");
+
+	SCRIPT_METHOD("SetFlashlightPosition");
+	SCRIPT_METHOD("GetFlashlightPositionX");
+	SCRIPT_METHOD("GetFlashlightPositionY");
+
+
+	SCRIPT_METHOD("SetFlashlightFollowMouse");
+	SCRIPT_METHOD("GetFlashlightFollowMouse");
+
+	SCRIPT_METHOD("SetFlashlightFollowCharacter");
+	SCRIPT_METHOD("GetFlashlightFollowCharacter");
+	SCRIPT_METHOD("GetFlashlightCharacterDX");
+	SCRIPT_METHOD("GetFlashlightCharacterDY");
+	SCRIPT_METHOD("GetFlashlightCharacterHorz");
+	SCRIPT_METHOD("GetFlashlightCharacterVert");
+
+	SCRIPT_METHOD("SetFlashlightMask");
+	SCRIPT_METHOD("GetFlashlightMask");
+
+	_engine->RequestEventHook(AGSE_PREGUIDRAW);
+	_engine->RequestEventHook(AGSE_PRESCREENDRAW);
+	_engine->RequestEventHook(AGSE_SAVEGAME);
+	_engine->RequestEventHook(AGSE_RESTOREGAME);
+}
+
+void AGSFlashlight::AGS_EngineShutdown() {
+}
+
+int AGSFlashlight::AGS_EngineOnEvent(int event, int data) {
+	if (event == AGSE_PREGUIDRAW) {
+		Update();
+	} else if (event == AGSE_RESTOREGAME) {
+		RestoreGame(data);
+	} else if (event == AGSE_SAVEGAME) {
+		SaveGame(data);
+	} else if (event == AGSE_PRESCREENDRAW) {
+		// Get screen size once here.
+		_engine->GetScreenDimensions(&screen_width, &screen_height, &screen_color_depth);
+		_engine->UnrequestEventHook(AGSE_PRESCREENDRAW);
 
-	n = x >> 24;
+		// Only 16 bit color depth is supported.
+		if (screen_color_depth != 16) {
+			_engine->UnrequestEventHook(AGSE_PREGUIDRAW);
+			_engine->UnrequestEventHook(AGSE_PRESCREENDRAW);
+			_engine->UnrequestEventHook(AGSE_SAVEGAME);
+			_engine->UnrequestEventHook(AGSE_RESTOREGAME);
+		}
+	}
 
-	if (n)
-		n = (n + 1) / 8;
+	return 0;
+}
 
-	x = ((x >> 19) & 0x001F) | ((x >> 5) & 0x07E0) | ((x << 8) & 0xF800);
+int AGSFlashlight::AGS_EngineDebugHook(const char *scriptName, int lineNum, int reserved) {
+	return 0;
+}
 
-	x = (x | (x << 16)) & 0x7E0F81F;
+void AGSFlashlight::AGS_EngineInitGfx(const char *driverID, void *data) {
 }
 
 
-inline unsigned long _blender_alpha16_bgr(unsigned long y) {
+void AGSFlashlight::calc_x_n(unsigned long x) {
+	flashlight_x = x;
+
+	flashlight_n = flashlight_x >> 24;
+
+	if (flashlight_n)
+		flashlight_n = (flashlight_n + 1) / 8;
+
+	flashlight_x = ((flashlight_x >> 19) & 0x001F) | ((flashlight_x >> 5) & 0x07E0) | ((flashlight_x << 8) & 0xF800);
+
+	flashlight_x = (flashlight_x | (flashlight_x << 16)) & 0x7E0F81F;
+}
+
+inline unsigned long AGSFlashlight::_blender_alpha16_bgr(unsigned long y) {
 	unsigned long result;
 
 	y = ((y & 0xFFFF) | (y << 16)) & 0x7E0F81F;
 
-	result = ((x - y) * n / 32 + y) & 0x7E0F81F;
+	result = ((flashlight_x - y) * flashlight_n / 32 + y) & 0x7E0F81F;
 
 	return ((result & 0xFFFF) | (result >> 16));
 }
 
-
-
-inline void setPixel(int x, int y, int color, unsigned int *pixel) {
+inline void AGSFlashlight::setPixel(int x, int y, int color, unsigned int *pixel) {
 	if ((x >= g_DarknessDiameter) || (y >= g_DarknessDiameter) || (x < 0) || (y < 0))
 		return;
 
 	*(pixel + (y * g_DarknessDiameter) + x) = color;
 }
 
-
-void plotCircle(int xm, int ym, int r, unsigned int color) {
-	unsigned int *pixel = *(unsigned int **)engine->GetRawBitmapSurface(g_LightBitmap);
+void AGSFlashlight::plotCircle(int xm, int ym, int r, unsigned int color) {
+	unsigned int *pixel = *(unsigned int **)_engine->GetRawBitmapSurface(g_LightBitmap);
 
 	int x = -r;
 	int y = 0;
@@ -152,11 +262,10 @@ void plotCircle(int xm, int ym, int r, unsigned int color) {
 			err +=  ++y * 2 + 1;
 	} while (x < 0);
 
-	engine->ReleaseBitmapSurface(g_LightBitmap);
+	_engine->ReleaseBitmapSurface(g_LightBitmap);
 }
 
-
-void ClipToRange(int &variable, int min, int max) {
+void AGSFlashlight::ClipToRange(int &variable, int min, int max) {
 	if (variable < min)
 		variable = min;
 
@@ -164,10 +273,9 @@ void ClipToRange(int &variable, int min, int max) {
 		variable = max;
 }
 
-
-void AlphaBlendBitmap() {
-	unsigned short *destpixel = *(unsigned short **)engine->GetRawBitmapSurface(engine->GetVirtualScreen());
-	unsigned int *sourcepixel = *(unsigned int **)engine->GetRawBitmapSurface(g_LightBitmap);
+void AGSFlashlight::AlphaBlendBitmap() {
+	unsigned short *destpixel = *(unsigned short **)_engine->GetRawBitmapSurface(_engine->GetVirtualScreen());
+	unsigned int *sourcepixel = *(unsigned int **)_engine->GetRawBitmapSurface(g_LightBitmap);
 
 	unsigned short *currentdestpixel = destpixel;
 	unsigned int *currentsourcepixel = sourcepixel;
@@ -196,21 +304,20 @@ void AlphaBlendBitmap() {
 		}
 	}
 
-	engine->ReleaseBitmapSurface(engine->GetVirtualScreen());
-	engine->ReleaseBitmapSurface(g_LightBitmap);
+	_engine->ReleaseBitmapSurface(_engine->GetVirtualScreen());
+	_engine->ReleaseBitmapSurface(g_LightBitmap);
 }
 
-
-void DrawTint() {
+void AGSFlashlight::DrawTint() {
 	int x, y;
-	BITMAP *screen = engine->GetVirtualScreen();
-	unsigned short *destpixel = *(unsigned short **)engine->GetRawBitmapSurface(screen);
+	BITMAP *screen = _engine->GetVirtualScreen();
+	unsigned short *destpixel = *(unsigned short **)_engine->GetRawBitmapSurface(screen);
 
 	int32 red, blue, green, alpha;
 
 	for (y = 0; y < screen_height; y++) {
 		for (x = 0; x < screen_width; x++) {
-			engine->GetRawColorComponents(16, *destpixel, &red, &green, &blue, &alpha);
+			_engine->GetRawColorComponents(16, *destpixel, &red, &green, &blue, &alpha);
 
 			if (g_RedTint != 0) {
 				red += g_RedTint * 8;
@@ -236,20 +343,19 @@ void DrawTint() {
 					green = 0;
 			}
 
-			*destpixel = engine->MakeRawColorPixel(16, red, green, blue, alpha);
+			*destpixel = _engine->MakeRawColorPixel(16, red, green, blue, alpha);
 			destpixel++;
 		}
 	}
 
-	engine->ReleaseBitmapSurface(screen);
+	_engine->ReleaseBitmapSurface(screen);
 }
 
-
-void DrawDarkness() {
+void AGSFlashlight::DrawDarkness() {
 	int x, y;
 	unsigned int color = (255 - (int)((float)g_DarknessLightLevel * 2.55f)) << 24;
-	BITMAP *screen = engine->GetVirtualScreen();
-	unsigned short *destpixel = *(unsigned short **)engine->GetRawBitmapSurface(screen);
+	BITMAP *screen = _engine->GetVirtualScreen();
+	unsigned short *destpixel = *(unsigned short **)_engine->GetRawBitmapSurface(screen);
 	unsigned short *currentpixel;
 
 	calc_x_n(color);
@@ -314,22 +420,21 @@ void DrawDarkness() {
 		}
 	}
 
-	engine->ReleaseBitmapSurface(screen);
+	_engine->ReleaseBitmapSurface(screen);
 }
 
-
-void CreateLightBitmap() {
+void AGSFlashlight::CreateLightBitmap() {
 	if (g_DarknessSize == 0)
 		return;
 
 	if (g_LightBitmap)
-		engine->FreeBitmap(g_LightBitmap);
+		_engine->FreeBitmap(g_LightBitmap);
 
-	g_LightBitmap = engine->CreateBlankBitmap(g_DarknessDiameter, g_DarknessDiameter, 32);
+	g_LightBitmap = _engine->CreateBlankBitmap(g_DarknessDiameter, g_DarknessDiameter, 32);
 
 	// Fill with darkness color.
 	unsigned int color = (255 - (int)((float)g_DarknessLightLevel * 2.55f)) << 24;
-	unsigned int *pixel = *(unsigned int **)engine->GetRawBitmapSurface(g_LightBitmap);
+	unsigned int *pixel = *(unsigned int **)_engine->GetRawBitmapSurface(g_LightBitmap);
 
 	int i;
 	for (i = 0; i < g_DarknessDiameter * g_DarknessDiameter; i++)
@@ -356,7 +461,7 @@ void CreateLightBitmap() {
 
 			current_value += increment;
 
-			if (current_value > targetcolor)
+			if ((uint)current_value > targetcolor)
 				current_value = targetcolor;
 
 			plotCircle(g_DarknessSize, g_DarknessSize, i, (current_value << 24) + color);
@@ -371,18 +476,17 @@ void CreateLightBitmap() {
 			plotCircle(g_DarknessSize, g_DarknessSize, i, color);
 	}
 
-	engine->ReleaseBitmapSurface(g_LightBitmap);
+	_engine->ReleaseBitmapSurface(g_LightBitmap);
 }
 
-
-void Update() {
+void AGSFlashlight::Update() {
 	if (g_BitmapMustBeUpdated) {
 		CreateLightBitmap();
 		g_BitmapMustBeUpdated = false;
 	}
 
 	if (g_FlashlightFollowMouse) {
-		engine->GetMousePosition(&g_FlashlightX, &g_FlashlightY);
+		_engine->GetMousePosition(&g_FlashlightX, &g_FlashlightY);
 	} else if (g_FollowCharacter != nullptr) {
 		g_FlashlightX = g_FollowCharacter->x + g_FollowCharacterDx;
 		g_FlashlightY = g_FollowCharacter->y + g_FollowCharacterDy;
@@ -429,25 +533,25 @@ void Update() {
 	if (g_DarknessLightLevel != 100)
 		DrawDarkness();
 
-	engine->MarkRegionDirty(0, 0, screen_width, screen_height);
+	_engine->MarkRegionDirty(0, 0, screen_width, screen_height);
 }
 
-static size_t engineFileRead(void *ptr, size_t size, size_t count, long fileHandle) {
-	auto totalBytes = engine->FRead(ptr, size * count, fileHandle);
+size_t AGSFlashlight::engineFileRead(void *ptr, size_t size, size_t count, long fileHandle) {
+	auto totalBytes = _engine->FRead(ptr, size * count, fileHandle);
 	return totalBytes / size;
 }
 
-static size_t engineFileWrite(const void *ptr, size_t size, size_t count, long fileHandle) {
-	auto totalBytes = engine->FWrite(const_cast<void *>(ptr), size * count, fileHandle);
+size_t AGSFlashlight::engineFileWrite(const void *ptr, size_t size, size_t count, long fileHandle) {
+	auto totalBytes = _engine->FWrite(const_cast<void *>(ptr), size * count, fileHandle);
 	return totalBytes / size;
 }
 
-void RestoreGame(long file) {
+void AGSFlashlight::RestoreGame(long file) {
 	unsigned int SaveVersion = 0;
 	engineFileRead(&SaveVersion, sizeof(SaveVersion), 1, file);
 
 	if (SaveVersion != SaveMagic) {
-		engine->AbortGame("agsflashlight: bad save.");
+		_engine->AbortGame("agsflashlight: bad save.");
 	}
 
 	// Current version
@@ -473,13 +577,12 @@ void RestoreGame(long file) {
 	engineFileRead(&g_FollowCharacterVert, 4, 1, file);
 
 	if (g_FollowCharacterId != 0)
-		g_FollowCharacter = engine->GetCharacter(g_FollowCharacterId);
+		g_FollowCharacter = _engine->GetCharacter(g_FollowCharacterId);
 
 	g_BitmapMustBeUpdated = true;
 }
 
-
-void SaveGame(long file) {
+void AGSFlashlight::SaveGame(long file) {
 	engineFileWrite(&SaveMagic, sizeof(SaveMagic), 1, file);
 
 	engineFileWrite(&g_RedTint, 4, 1, file);
@@ -509,10 +612,7 @@ void SaveGame(long file) {
 // ************  AGS Interface  ***************
 // ********************************************
 
-
-
-// tint screen
-void SetFlashlightTint(int RedTint, int GreenTint, int BlueTint) {
+void AGSFlashlight::SetFlashlightTint(int RedTint, int GreenTint, int BlueTint) {
 	ClipToRange(RedTint, -31, 31);
 	ClipToRange(GreenTint, -31, 31);
 	ClipToRange(BlueTint, -31, 31);
@@ -525,27 +625,27 @@ void SetFlashlightTint(int RedTint, int GreenTint, int BlueTint) {
 	g_BlueTint = BlueTint;
 }
 
-int GetFlashlightTintRed() {
+int AGSFlashlight::GetFlashlightTintRed() {
 	return g_RedTint;
 }
 
-int GetFlashlightTintGreen() {
+int AGSFlashlight::GetFlashlightTintGreen() {
 	return g_GreenTint;
 }
 
-int GetFlashlightTintBlue() {
+int AGSFlashlight::GetFlashlightTintBlue() {
 	return g_BlueTint;
 }
 
-int GetFlashlightMinLightLevel() {
+int AGSFlashlight::GetFlashlightMinLightLevel() {
 	return 0;
 }
 
-int GetFlashlightMaxLightLevel() {
+int AGSFlashlight::GetFlashlightMaxLightLevel() {
 	return 100;
 }
 
-void SetFlashlightDarkness(int LightLevel) {
+void AGSFlashlight::SetFlashlightDarkness(int LightLevel) {
 	ClipToRange(LightLevel, 0, 100);
 
 	if (LightLevel != g_DarknessLightLevel) {
@@ -557,11 +657,11 @@ void SetFlashlightDarkness(int LightLevel) {
 	}
 }
 
-int GetFlashlightDarkness() {
+int AGSFlashlight::GetFlashlightDarkness() {
 	return g_DarknessLightLevel;
 }
 
-void SetFlashlightDarknessSize(int Size) {
+void AGSFlashlight::SetFlashlightDarknessSize(int Size) {
 	if (Size != g_DarknessSize) {
 		g_BitmapMustBeUpdated = true;
 		g_DarknessSize = Size;
@@ -569,12 +669,12 @@ void SetFlashlightDarknessSize(int Size) {
 	}
 }
 
-int GetFlashlightDarknessSize() {
+int AGSFlashlight::GetFlashlightDarknessSize() {
 	return g_DarknessSize;
 }
 
 
-void SetFlashlightBrightness(int LightLevel) {
+void AGSFlashlight::SetFlashlightBrightness(int LightLevel) {
 	ClipToRange(LightLevel, 0, 100);
 
 	if (LightLevel != g_BrightnessLightLevel) {
@@ -586,244 +686,80 @@ void SetFlashlightBrightness(int LightLevel) {
 	}
 }
 
-int GetFlashlightBrightness() {
+int AGSFlashlight::GetFlashlightBrightness() {
 	return g_BrightnessLightLevel;
 }
 
-void SetFlashlightBrightnessSize(int Size) {
+void AGSFlashlight::SetFlashlightBrightnessSize(int Size) {
 	if (Size != g_BrightnessSize) {
 		g_BitmapMustBeUpdated = true;
 		g_BrightnessSize = Size;
 	}
 }
 
-int GetFlashlightBrightnessSize() {
+int AGSFlashlight::GetFlashlightBrightnessSize() {
 	return g_BrightnessSize;
 }
 
-void SetFlashlightPosition(int X, int Y) {
+void AGSFlashlight::SetFlashlightPosition(int X, int Y) {
 	g_FlashlightX = X;
 	g_FlashlightY = Y;
 }
 
-int GetFlashlightPositionX() {
+int AGSFlashlight::GetFlashlightPositionX() {
 	return g_FlashlightX;
 }
 
-int GetFlashlightPositionY() {
+int AGSFlashlight::GetFlashlightPositionY() {
 	return g_FlashlightY;
 }
 
-void SetFlashlightFollowMouse(int OnOff) {
+void AGSFlashlight::SetFlashlightFollowMouse(int OnOff) {
 	g_FlashlightFollowMouse = (OnOff != 0);
 }
 
-int GetFlashlightFollowMouse() {
+int AGSFlashlight::GetFlashlightFollowMouse() {
 	return g_FlashlightFollowMouse ? 1 : 0;
 }
 
-void SetFlashlightFollowCharacter(int CharacterId, int dx, int dy, int horz, int vert) {
+void AGSFlashlight::SetFlashlightFollowCharacter(int CharacterId, int dx, int dy, int horz, int vert) {
 	g_FollowCharacterId = CharacterId;
 	g_FollowCharacterDx = dx;
 	g_FollowCharacterDy = dy;
 	g_FollowCharacterHorz = horz;
 	g_FollowCharacterVert = vert;
 
-	g_FollowCharacter = engine->GetCharacter(CharacterId);
+	g_FollowCharacter = _engine->GetCharacter(CharacterId);
 }
 
-int GetFlashlightFollowCharacter() {
+int AGSFlashlight::GetFlashlightFollowCharacter() {
 	return g_FollowCharacterId;
 }
 
-int GetFlashlightCharacterDX() {
+int AGSFlashlight::GetFlashlightCharacterDX() {
 	return g_FollowCharacterDx;
 }
 
-int GetFlashlightCharacterDY() {
+int AGSFlashlight::GetFlashlightCharacterDY() {
 	return g_FollowCharacterDy;
 }
 
-int GetFlashlightCharacterHorz() {
+int AGSFlashlight::GetFlashlightCharacterHorz() {
 	return g_FollowCharacterHorz;
 }
 
-int GetFlashlightCharacterVert() {
+int AGSFlashlight::GetFlashlightCharacterVert() {
 	return g_FollowCharacterVert;
 }
 
-void SetFlashlightMask(int SpriteSlot) {
+void AGSFlashlight::SetFlashlightMask(int SpriteSlot) {
 	// Not implemented.
 }
 
-int GetFlashlightMask() {
+int AGSFlashlight::GetFlashlightMask() {
 	return 0;
 }
 
-void AGS_EngineStartup(IAGSEngine *lpEngine) {
-	engine = lpEngine;
-
-	if (engine->version < 13)
-		engine->AbortGame("Engine interface is too old, need newer version of AGS.");
-
-	engine->RegisterScriptFunction("SetFlashlightTint", (void *)&SetFlashlightTint);
-	engine->RegisterScriptFunction("GetFlashlightTintRed", (void *)&GetFlashlightTintRed);
-	engine->RegisterScriptFunction("GetFlashlightTintGreen", (void *)&GetFlashlightTintGreen);
-	engine->RegisterScriptFunction("GetFlashlightTintBlue", (void *)&GetFlashlightTintBlue);
-
-	engine->RegisterScriptFunction("GetFlashlightMinLightLevel", (void *)&GetFlashlightMinLightLevel);
-	engine->RegisterScriptFunction("GetFlashlightMaxLightLevel", (void *)&GetFlashlightMaxLightLevel);
-
-	engine->RegisterScriptFunction("SetFlashlightDarkness", (void *)&SetFlashlightDarkness);
-	engine->RegisterScriptFunction("GetFlashlightDarkness", (void *)&GetFlashlightDarkness);
-	engine->RegisterScriptFunction("SetFlashlightDarknessSize", (void *)&SetFlashlightDarknessSize);
-	engine->RegisterScriptFunction("GetFlashlightDarknessSize", (void *)&GetFlashlightDarknessSize);
-
-	engine->RegisterScriptFunction("SetFlashlightBrightness", (void *)&SetFlashlightBrightness);
-	engine->RegisterScriptFunction("GetFlashlightBrightness", (void *)&GetFlashlightBrightness);
-	engine->RegisterScriptFunction("SetFlashlightBrightnessSize", (void *)&SetFlashlightBrightnessSize);
-	engine->RegisterScriptFunction("GetFlashlightBrightnessSize", (void *)&GetFlashlightBrightnessSize);
-
-	engine->RegisterScriptFunction("SetFlashlightPosition", (void *)&SetFlashlightPosition);
-	engine->RegisterScriptFunction("GetFlashlightPositionX", (void *)&GetFlashlightPositionX);
-	engine->RegisterScriptFunction("GetFlashlightPositionY", (void *)&GetFlashlightPositionY);
-
-
-	engine->RegisterScriptFunction("SetFlashlightFollowMouse", (void *)&SetFlashlightFollowMouse);
-	engine->RegisterScriptFunction("GetFlashlightFollowMouse", (void *)&GetFlashlightFollowMouse);
-
-	engine->RegisterScriptFunction("SetFlashlightFollowCharacter", (void *)&SetFlashlightFollowCharacter);
-	engine->RegisterScriptFunction("GetFlashlightFollowCharacter", (void *)&GetFlashlightFollowCharacter);
-	engine->RegisterScriptFunction("GetFlashlightCharacterDX", (void *)&GetFlashlightCharacterDX);
-	engine->RegisterScriptFunction("GetFlashlightCharacterDY", (void *)&GetFlashlightCharacterDY);
-	engine->RegisterScriptFunction("GetFlashlightCharacterHorz", (void *)&GetFlashlightCharacterHorz);
-	engine->RegisterScriptFunction("GetFlashlightCharacterVert", (void *)&GetFlashlightCharacterVert);
-
-	engine->RegisterScriptFunction("SetFlashlightMask", (void *)&SetFlashlightMask);
-	engine->RegisterScriptFunction("GetFlashlightMask", (void *)&GetFlashlightMask);
-
-	engine->RequestEventHook(AGSE_PREGUIDRAW);
-	engine->RequestEventHook(AGSE_PRESCREENDRAW);
-	engine->RequestEventHook(AGSE_SAVEGAME);
-	engine->RequestEventHook(AGSE_RESTOREGAME);
-}
-
-void AGS_EngineShutdown() {
-
-}
-
-int AGS_EngineOnEvent(int event, int data) {
-	if (event == AGSE_PREGUIDRAW) {
-		Update();
-	} else if (event == AGSE_RESTOREGAME) {
-		RestoreGame(data);
-	} else if (event == AGSE_SAVEGAME) {
-		SaveGame(data);
-	} else if (event == AGSE_PRESCREENDRAW) {
-		// Get screen size once here.
-		engine->GetScreenDimensions(&screen_width, &screen_height, &screen_color_depth);
-		engine->UnrequestEventHook(AGSE_PRESCREENDRAW);
-
-		// Only 16 bit color depth is supported.
-		if (screen_color_depth != 16) {
-			engine->UnrequestEventHook(AGSE_PREGUIDRAW);
-			engine->UnrequestEventHook(AGSE_PRESCREENDRAW);
-			engine->UnrequestEventHook(AGSE_SAVEGAME);
-			engine->UnrequestEventHook(AGSE_RESTOREGAME);
-		}
-	}
-
-	return 0;
-}
-
-int AGS_EngineDebugHook(const char *scriptName, int lineNum, int reserved) {
-	return 0;
-}
-
-void AGS_EngineInitGfx(const char *driverID, void *data) {
-}
-
-
-
-#if AGS_PLATFORM_OS_WINDOWS && !defined(BUILTIN_PLUGINS)
-
-// ********************************************
-// ***********  Editor Interface  *************
-// ********************************************
-
-const char *scriptHeader =
-    "import void SetFlashlightTint(int RedTint, int GreenTint, int BlueTint);\r\n"
-    "import int GetFlashlightTintRed();\r\n"
-    "import int GetFlashlightTintGreen();\r\n"
-    "import int GetFlashlightTintBlue();\r\n"
-    "import int GetFlashlightMinLightLevel();\r\n"
-    "import int GetFlashlightMaxLightLevel();\r\n"
-    "import void SetFlashlightDarkness(int LightLevel);\r\n"
-    "import int GetFlashlightDarkness();\r\n"
-    "import void SetFlashlightDarknessSize(int Size);\r\n"
-    "import int GetFlashlightDarknessSize();\r\n"
-    "import void SetFlashlightBrightness(int LightLevel);\r\n"
-    "import int GetFlashlightBrightness();\r\n"
-    "import void SetFlashlightBrightnessSize(int Size);\r\n"
-    "import int GetFlashlightBrightnessSize();\r\n"
-    "import void SetFlashlightPosition(int X, int Y);\r\n"
-    "import int GetFlashlightPositionX();\r\n"
-    "import int GetFlashlightPositionY();\r\n"
-    "import void SetFlashlightFollowMouse(int OnOff);\r\n"
-    "import int GetFlashlightFollowMouse ();\r\n"
-    "import void SetFlashlightFollowCharacter(int CharacterId, int dx, int dy, int horz, int vert);\r\n"
-    "import int GetFlashlightFollowCharacter();\r\n"
-    "import int GetFlashlightCharacterDX();\r\n"
-    "import int GetFlashlightCharacterDY();\r\n"
-    "import int GetFlashlightCharacterHorz();\r\n"
-    "import int GetFlashlightCharacterVert();\r\n";
-
-
-IAGSEditor *editor;
-
-
-LPCSTR AGS_GetPluginName(void) {
-	// Return the plugin description
-	return "Flashlight plugin recreation";
-}
-
-int  AGS_EditorStartup(IAGSEditor *lpEditor) {
-	// User has checked the plugin to use it in their game
-
-	// If it's an earlier version than what we need, abort.
-	if (lpEditor->version < 1)
-		return -1;
-
-	editor = lpEditor;
-	editor->RegisterScriptHeader(scriptHeader);
-
-	// Return 0 to indicate success
-	return 0;
-}
-
-void AGS_EditorShutdown() {
-	// User has un-checked the plugin from their game
-	editor->UnregisterScriptHeader(scriptHeader);
-}
-
-void AGS_EditorProperties(HWND parent) {
-	// User has chosen to view the Properties of the plugin
-	// We could load up an options dialog or something here instead
-	MessageBoxA(parent, "Flashlight plugin recreation by JJS", "About", MB_OK | MB_ICONINFORMATION);
-}
-
-int AGS_EditorSaveGame(char *buffer, int bufsize) {
-	// We don't want to save any persistent data
-	return 0;
-}
-
-void AGS_EditorLoadGame(char *buffer, int bufsize) {
-	// Nothing to load for this plugin
-}
-
-#endif
-
-
-#if defined(BUILTIN_PLUGINS)
-} // namespace agsflashlight
-#endif
+} // namespace AGSFlashlight
+} // namespace Plugins
+} // namespace AGS3
diff --git a/engines/ags/plugins/ags_flashlight/ags_flashlight.h b/engines/ags/plugins/ags_flashlight/ags_flashlight.h
index cd01110630..d225d7e501 100644
--- a/engines/ags/plugins/ags_flashlight/ags_flashlight.h
+++ b/engines/ags/plugins/ags_flashlight/ags_flashlight.h
@@ -1,14 +1,132 @@
-#ifndef AGS_FLASHLIGHT_H
-#define AGS_FLASHLIGHT_H
+/* 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 "plugin/agsplugin.h"
+#ifndef AGS_PLUGINS_AGSFLASHLIGHT_AGSFLASHLIGHT_H
+#define AGS_PLUGINS_AGSFLASHLIGHT_AGSFLASHLIGHT_H
 
-namespace agsflashlight {
-void AGS_EngineStartup(IAGSEngine *lpEngine);
-void AGS_EngineShutdown();
-int AGS_EngineOnEvent(int event, int data);
-int AGS_EngineDebugHook(const char *scriptName, int lineNum, int reserved);
-void AGS_EngineInitGfx(const char *driverID, void *data);
-}
+#include "ags/plugins/dll.h"
+#include "ags/lib/allegro.h"
+#include "common/array.h"
+#include "common/rect.h"
+#include "common/str.h"
 
-#endif
\ No newline at end of file
+namespace AGS3 {
+namespace Plugins {
+namespace AGSFlashlight {
+
+/**
+ * This is not the AGS Flashlight plugin,
+ * but a workalike plugin originally created for the AGS engine PSP port.
+ */
+class AGSFlashlight : public DLL {
+private:
+	static IAGSEngine *_engine;
+	static int screen_width;
+	static int screen_height;
+	static int screen_color_depth;
+	static bool g_BitmapMustBeUpdated;
+	static int g_RedTint;
+	static int g_GreenTint;
+	static int g_BlueTint;
+	static int g_DarknessLightLevel;
+	static int g_BrightnessLightLevel;
+	static int g_DarknessSize;
+	static int g_DarknessDiameter;
+	static int g_BrightnessSize;
+	static int g_FlashlightX;
+	static int g_FlashlightY;
+	static int g_FlashlightDrawAtX;
+	static int g_FlashlightDrawAtY;
+	static bool g_FlashlightFollowMouse;
+	static int g_FollowCharacterId;
+	static int g_FollowCharacterDx;
+	static int g_FollowCharacterDy;
+	static int g_FollowCharacterHorz;
+	static int g_FollowCharacterVert;
+	static AGSCharacter *g_FollowCharacter;
+	static BITMAP *g_LightBitmap;
+	static unsigned long flashlight_x, flashlight_n;
+
+private:
+	static const char *AGS_GetPluginName();
+	static void AGS_EngineStartup(IAGSEngine *engine);
+	static void AGS_EngineShutdown();
+	static int AGS_EngineOnEvent(int event, int data);
+	static int AGS_EngineDebugHook(const char *scriptName, int lineNum, int reserved);
+	static void AGS_EngineInitGfx(const char *driverID, void *data);
+
+private:
+	/**
+	 * This function is from Allegro, split for more performance.
+	 *  Combines a 32 bit RGBA sprite with a 16 bit RGB destination, optimised
+	 *  for when one pixel is in an RGB layout and the other is BGR.
+	 */
+	static inline unsigned long _blender_alpha16_bgr(unsigned long y);
+	static inline void calc_x_n(unsigned long x);
+	static inline void setPixel(int x, int y, int color, unsigned int *pixel);
+	static void plotCircle(int xm, int ym, int r, unsigned int color);
+	static void ClipToRange(int &variable, int min, int max);
+	static void AlphaBlendBitmap();
+	static void DrawTint();
+	static void DrawDarkness();
+	static void CreateLightBitmap();
+	static void Update();
+	static size_t engineFileRead(void *ptr, size_t size, size_t count, long fileHandle);
+	static size_t engineFileWrite(const void *ptr, size_t size, size_t count, long fileHandle);
+	static void RestoreGame(long file);
+	static void SaveGame(long file);
+	static void SetFlashlightTint(int RedTint, int GreenTint, int BlueTint);
+	static int GetFlashlightTintRed();
+	static int GetFlashlightTintGreen();
+	static int GetFlashlightTintBlue();
+	static int GetFlashlightMinLightLevel();
+	static int GetFlashlightMaxLightLevel();
+	static void SetFlashlightDarkness(int LightLevel);
+	static int GetFlashlightDarkness();
+	static void SetFlashlightDarknessSize(int Size);
+	static int GetFlashlightDarknessSize();
+	static void SetFlashlightBrightness(int LightLevel);
+	static int GetFlashlightBrightness();
+	static void SetFlashlightBrightnessSize(int Size);
+	static int GetFlashlightBrightnessSize();
+	static void SetFlashlightPosition(int X, int Y);
+	static int GetFlashlightPositionX();
+	static int GetFlashlightPositionY();
+	static void SetFlashlightFollowMouse(int OnOff);
+	static int GetFlashlightFollowMouse();
+	static void SetFlashlightFollowCharacter(int CharacterId, int dx, int dy, int horz, int vert);
+	static int GetFlashlightFollowCharacter();
+	static int GetFlashlightCharacterDX();
+	static int GetFlashlightCharacterDY();
+	static int GetFlashlightCharacterHorz();
+	static int GetFlashlightCharacterVert();
+	static void SetFlashlightMask(int SpriteSlot);
+	static int GetFlashlightMask();
+public:
+	AGSFlashlight();
+};
+
+} // namespace AGSFlashlight
+} // namespace Plugins
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/plugins/dll.cpp b/engines/ags/plugins/dll.cpp
index 1662de7958..c1fd382345 100644
--- a/engines/ags/plugins/dll.cpp
+++ b/engines/ags/plugins/dll.cpp
@@ -23,6 +23,7 @@
 #include "ags/lib/allegro.h"
 #include "ags/plugins/dll.h"
 #include "ags/plugins/ags_creditz/ags_creditz.h"
+#include "ags/plugins/ags_flashlight/ags_flashlight.h"
 #include "ags/ags.h"
 #include "ags/detection.h"
 #include "common/str.h"
@@ -49,6 +50,8 @@ void *dlopen(const char *filename) {
 		else
 			return new AGSCreditz::AGSCreditz11();
 	}
+	if (fname.equalsIgnoreCase("libAGSFlashlight.so"))
+		return new AGSFlashlight::AGSFlashlight();
 
 	return nullptr;
 }


Commit: 8659371368d2a27c8bf89cf24bb42486634bf798
    https://github.com/scummvm/scummvm/commit/8659371368d2a27c8bf89cf24bb42486634bf798
Author: Thierry Crozat (criezy at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix volume range in SOUNDCLIP::get_volume

The original has an inline function that returns the volume as a
percentage. In ScummVM this was made pure virtual and derived
classes returned the volume from the mixer between 0 and 255.
The different range caused various asserts.

This commit restore the code to how it is in the original AGS.
If we find issues with synchronization that require using the
volume from the mixer, we can't change the code back to using
a virtual function but we will need to scale the mixer volume
to be in the [0, 100] range.

Changed paths:
    engines/ags/engine/media/audio/audio.cpp
    engines/ags/engine/media/audio/clip_mymidi.cpp
    engines/ags/engine/media/audio/clip_mymidi.h
    engines/ags/engine/media/audio/soundclip.cpp
    engines/ags/engine/media/audio/soundclip.h


diff --git a/engines/ags/engine/media/audio/audio.cpp b/engines/ags/engine/media/audio/audio.cpp
index 342fc3aac7..90b4a96829 100644
--- a/engines/ags/engine/media/audio/audio.cpp
+++ b/engines/ags/engine/media/audio/audio.cpp
@@ -277,7 +277,7 @@ static void audio_update_polled_stuff() {
 
 	if (play.crossfading_out_channel > 0) {
 		SOUNDCLIP *ch = lock.GetChannel(play.crossfading_out_channel);
-		int newVolume = ch ? ch->get_volume_percent() - play.crossfade_out_volume_per_step : 0;
+		int newVolume = ch ? ch->get_volume() - play.crossfade_out_volume_per_step : 0;
 		if (newVolume > 0) {
 			AudioChannel_SetVolume(&scrAudioChannel[play.crossfading_out_channel], newVolume);
 		} else {
@@ -291,7 +291,7 @@ static void audio_update_polled_stuff() {
 
 	if (play.crossfading_in_channel > 0) {
 		SOUNDCLIP *ch = lock.GetChannel(play.crossfading_in_channel);
-		int newVolume = ch ? ch->get_volume_percent() + play.crossfade_in_volume_per_step : 0;
+		int newVolume = ch ? ch->get_volume() + play.crossfade_in_volume_per_step : 0;
 		if (newVolume > play.crossfade_final_volume_in) {
 			newVolume = play.crossfade_final_volume_in;
 		}
diff --git a/engines/ags/engine/media/audio/clip_mymidi.cpp b/engines/ags/engine/media/audio/clip_mymidi.cpp
index fc05ad53d6..84b7b80298 100644
--- a/engines/ags/engine/media/audio/clip_mymidi.cpp
+++ b/engines/ags/engine/media/audio/clip_mymidi.cpp
@@ -84,10 +84,6 @@ bool MYMIDI::is_playing() const {
 	return ::AGS::g_music->isPlaying();
 }
 
-int MYMIDI::get_volume() const {
-	return _mixer->getVolumeForSoundType(Audio::Mixer::kMusicSoundType);
-}
-
 void MYMIDI::set_volume(int volume) {
 	_mixer->setVolumeForSoundType(Audio::Mixer::kMusicSoundType, volume);
 }
diff --git a/engines/ags/engine/media/audio/clip_mymidi.h b/engines/ags/engine/media/audio/clip_mymidi.h
index 0fa224390e..3e1d22e786 100644
--- a/engines/ags/engine/media/audio/clip_mymidi.h
+++ b/engines/ags/engine/media/audio/clip_mymidi.h
@@ -56,7 +56,6 @@ struct MYMIDI : public SOUNDCLIP {
 	int play() override;
 	void stop() override;
 	bool is_playing() const override;
-	int get_volume() const override;
 	void set_volume(int volume) override;
 	void set_panning(int newPanning) override;
 };
diff --git a/engines/ags/engine/media/audio/soundclip.cpp b/engines/ags/engine/media/audio/soundclip.cpp
index 2c88f0b9aa..f48ae074af 100644
--- a/engines/ags/engine/media/audio/soundclip.cpp
+++ b/engines/ags/engine/media/audio/soundclip.cpp
@@ -27,8 +27,8 @@ namespace AGS3 {
 
 SOUNDCLIP::SOUNDCLIP() : _state(SoundClipInitial), _panning(128), _panningAsPercentage(0),
 		_sourceClip(nullptr), _sourceClipType(0), _speed(1000), _priority(50),
-		_xSource(-1), _ySource(-1), _maximumPossibleDistanceAway(0),
-		_volAsPercentage(100), _vol(0), _volModifier(0), _repeat(false) {
+		_xSource(-1), _ySource(-1), _maximumPossibleDistanceAway(0), _muted(false),
+		_volAsPercentage(0), _vol(0), _volModifier(0), _repeat(false) {
 	_mixer = ::AGS::g_vm->_mixer;
 }
 
@@ -127,10 +127,6 @@ int SoundClipWaveBase::get_length_ms() {
 	return 0;
 }
 
-int SoundClipWaveBase::get_volume() const {
-	return _mixer->getChannelVolume(_soundHandle);
-}
-
 void SoundClipWaveBase::set_volume(int volume) {
 	_mixer->setChannelVolume(_soundHandle, volume);
 }
diff --git a/engines/ags/engine/media/audio/soundclip.h b/engines/ags/engine/media/audio/soundclip.h
index ccd071cd21..3580f72def 100644
--- a/engines/ags/engine/media/audio/soundclip.h
+++ b/engines/ags/engine/media/audio/soundclip.h
@@ -80,19 +80,24 @@ struct SOUNDCLIP {
 	virtual int get_pos_ms() = 0;
 	virtual int get_length_ms() = 0; // return total track length in ms (or 0)
 	virtual int get_sound_type() const = 0;
-	virtual int get_volume() const = 0;
 	virtual void set_volume(int volume) = 0;
 	virtual void set_panning(int newPanning) = 0;
 	inline int get_speed() const { return _speed; }
 	virtual void set_speed(int new_speed);
 
 	void poll();
+
+	// Gets clip's volume property, as percentage (0 - 100);
+	// note this may not be the real volume of playback (which could e.g. be muted)
+	inline int get_volume() const {
+		return _volAsPercentage;
+	}
+
 	// Sets the current volume property, as percentage (0 - 100).
 	inline void set_volume_percent(int volume) {
-		set_volume((volume * 255) / 100);
-	}
-	inline int get_volume_percent() const {
-		return get_volume() * 100 / 255;
+		_volAsPercentage = volume;
+		if (!_muted)
+			set_volume((volume * 255) / 100);
 	}
 	void adjust_volume();
 	int play_from(int position);
@@ -141,13 +146,6 @@ struct SOUNDCLIP {
 		return state_ == SoundClipPlaying || state_ == SoundClipPaused;
 	}
 
-
-	// Gets clip's volume property, as percentage (0 - 100);
-	// note this may not be the real volume of playback (which could e.g. be muted)
-	inline int get_volume() const {
-		return volAsPercentage;
-	}
-
 	inline bool is_muted() const {
 		return muted;
 	}
@@ -198,7 +196,6 @@ struct SoundClipWaveBase : public SOUNDCLIP {
 	int get_pos() override;
 	int get_pos_ms() override;
 	int get_length_ms() override;
-	int get_volume() const override;
 	void set_volume(int volume) override;
 	void set_panning(int newPanning) override;
 };


Commit: 372284a67ede31db30e54a333f2fedf08a700306
    https://github.com/scummvm/scummvm/commit/372284a67ede31db30e54a333f2fedf08a700306
Author: Thierry Crozat (criezy at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix game data parser for versions between 2.6 and 2.7.1

This is backported from the main AGS repo where this fixe was
made a few days ago.

Changed paths:
    engines/ags/shared/ac/gamesetupstruct.cpp


diff --git a/engines/ags/shared/ac/gamesetupstruct.cpp b/engines/ags/shared/ac/gamesetupstruct.cpp
index 73cb35d8de..91d6e53e83 100644
--- a/engines/ags/shared/ac/gamesetupstruct.cpp
+++ b/engines/ags/shared/ac/gamesetupstruct.cpp
@@ -295,11 +295,15 @@ HGameFileError GameSetupStruct::read_customprops(Shared::Stream *in, GameDataVer
 		for (int i = 0; i < numviews; ++i)
 			viewNames[i] = String::FromStream(in);
 
-		for (int i = 0; i < numinvitems; ++i)
-			invScriptNames[i] = String::FromStream(in);
+		if (data_ver >= kGameVersion_270) {
+			for (int i = 0; i < numinvitems; ++i)
+				invScriptNames[i] = String::FromStream(in);
 
-		for (int i = 0; i < numdialog; ++i)
-			dialogScriptNames[i] = String::FromStream(in);
+			if (data_ver >= kGameVersion_272) {
+				for (int i = 0; i < numdialog; ++i)
+					dialogScriptNames[i] = String::FromStream(in);
+			}
+		}
 	}
 	return HGameFileError::None();
 }


Commit: e5b3b38dad9f82d0c801ae40495e3e3d65191e92
    https://github.com/scummvm/scummvm/commit/e5b3b38dad9f82d0c801ae40495e3e3d65191e92
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added AGSBlend plugin

Changed paths:
    engines/ags/module.mk
    engines/ags/plugins/ags_blend/ags_blend.cpp
    engines/ags/plugins/ags_blend/ags_blend.h
    engines/ags/plugins/ags_flashlight/ags_flashlight.cpp
    engines/ags/plugins/ags_flashlight/ags_flashlight.h
    engines/ags/plugins/dll.cpp


diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 75c55be114..f9c053ed34 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -301,6 +301,7 @@ MODULE_OBJS = \
 	engine/script/script_runtime.o \
 	engine/script/systemimports.o \
 	plugins/dll.o \
+	plugins/ags_blend/ags_blend.o \
 	plugins/ags_creditz/ags_creditz.o \
 	plugins/ags_flashlight/ags_flashlight.o
 
diff --git a/engines/ags/plugins/ags_blend/ags_blend.cpp b/engines/ags/plugins/ags_blend/ags_blend.cpp
index eeb3584a50..f32f79dec6 100644
--- a/engines/ags/plugins/ags_blend/ags_blend.cpp
+++ b/engines/ags/plugins/ags_blend/ags_blend.cpp
@@ -1,42 +1,38 @@
-/***********************************************************
- * AGSBlend                                                *
- *                                                         *
- * Author: Steven Poulton                                  *
- *                                                         *
- * Date: 09/01/2011                                        *
- *                                                         *
- * Description: An AGS Plugin to allow true Alpha Blending *
- *                                                         *
- ***********************************************************/
+/* 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 "ags/plugins/ags_blend/ags_blend.h"
+#include "ags/shared/core/platform.h"
+#include "common/algorithm.h"
+
+namespace AGS3 {
+namespace Plugins {
+namespace AGSBlend {
 
 #pragma region Defines_and_Includes
 
-#include "core/platform.h"
-
 #define MIN_EDITOR_VERSION 1
 #define MIN_ENGINE_VERSION 3
 
-#if AGS_PLATFORM_OS_WINDOWS
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#endif
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <math.h>
-
-#if !defined(BUILTIN_PLUGINS)
-#define THIS_IS_THE_PLUGIN
-#endif
-
-#include "plugin/agsplugin.h"
-
-#if defined(BUILTIN_PLUGINS)
-namespace agsblend {
-#endif
-
-typedef unsigned char uint8;
-
 #define DEFAULT_RGB_R_SHIFT_32  16
 #define DEFAULT_RGB_G_SHIFT_32  8
 #define DEFAULT_RGB_B_SHIFT_32  0
@@ -76,56 +72,60 @@ typedef unsigned char uint8;
 #define ChannelBlend_Alpha(B,L,O)    ((uint8)(O * B + (1 - O) * L))
 #define ChannelBlend_AlphaF(B,L,F,O) (ChannelBlend_Alpha(F(B,L),B,O))
 
+#define STRINGIFY(s) STRINGIFY_X(s)
+#define STRINGIFY_X(s) #s
 
 #pragma endregion
 
-#if AGS_PLATFORM_OS_WINDOWS
-// The standard Windows DLL entry point
+IAGSEngine *AGSBlend::_engine;
 
-BOOL APIENTRY DllMain(HANDLE hModule,
-                      DWORD  ul_reason_for_call,
-                      LPVOID lpReserved) {
+AGSBlend::AGSBlend() : DLL() {
+	DLL_METHOD(AGS_GetPluginName);
+	DLL_METHOD(AGS_EngineStartup);
+}
 
-	switch (ul_reason_for_call)   {
-	case DLL_PROCESS_ATTACH:
-	case DLL_THREAD_ATTACH:
-	case DLL_THREAD_DETACH:
-	case DLL_PROCESS_DETACH:
-		break;
-	}
-	return TRUE;
+const char *AGSBlend::AGS_GetPluginName() {
+	return "AGSBlend";
 }
-#endif
 
-//define engine
+void AGSBlend::AGS_EngineStartup(IAGSEngine *engine) {
+	_engine = engine;
 
-IAGSEngine *engine;
+	// Make sure it's got the version with the features we need
+	if (_engine->version < MIN_ENGINE_VERSION)
+		_engine->AbortGame("Plugin needs engine version " STRINGIFY(MIN_ENGINE_VERSION) " or newer.");
+
+	// Register functions
+	SCRIPT_METHOD(GetAlpha);
+	SCRIPT_METHOD(PutAlpha);
+	SCRIPT_METHOD(DrawAlpha);
+	SCRIPT_METHOD(Blur);
+	SCRIPT_METHOD(HighPass);
+	SCRIPT_METHOD(DrawAdd);
+	SCRIPT_METHOD(DrawSprite);
+}
 
+//------------------------------------------------------------------------------
 
 #pragma region Color_Functions
 
-
-int getr32(int c) {
+static int getr32(int c) {
 	return ((c >> DEFAULT_RGB_R_SHIFT_32) & 0xFF);
 }
 
-
-int getg32(int c) {
+static int getg32(int c) {
 	return ((c >> DEFAULT_RGB_G_SHIFT_32) & 0xFF);
 }
 
-
-int getb32(int c) {
+static int getb32(int c) {
 	return ((c >> DEFAULT_RGB_B_SHIFT_32) & 0xFF);
 }
 
-
-int geta32(int c) {
+static int geta32(int c) {
 	return ((c >> DEFAULT_RGB_A_SHIFT_32) & 0xFF);
 }
 
-
-int makeacol32(int r, int g, int b, int a) {
+static int makeacol32(int r, int g, int b, int a) {
 	return ((r << DEFAULT_RGB_R_SHIFT_32) |
 	        (g << DEFAULT_RGB_G_SHIFT_32) |
 	        (b << DEFAULT_RGB_B_SHIFT_32) |
@@ -137,60 +137,36 @@ int makeacol32(int r, int g, int b, int a) {
 #pragma region Pixel32_Definition
 
 struct Pixel32 {
-
 public:
-	Pixel32();
-	~Pixel32() = default;
-	int GetColorAsInt();
-	int Red;
-	int Green;
-	int Blue;
-	int Alpha;
+	int Red = 0;
+	int Green = 0;
+	int Blue = 0;
+	int Alpha = 0;
 
+	int GetColorAsInt() const {
+		return makeacol32(Red, Green, Blue, Alpha);
+	}
 };
 
-Pixel32::Pixel32() {
-	Red = 0;
-	Blue = 0;
-	Green = 0;
-	Alpha = 0;
-}
-
-int Pixel32::GetColorAsInt() {
-
-	return makeacol32(Red, Green, Blue, Alpha);
-
-}
-
 #pragma endregion
 
-/// <summary>
-/// Gets the alpha value at coords x,y
-/// </summary>
-int GetAlpha(int sprite, int x, int y) {
-
+int AGSBlend::GetAlpha(int sprite, int x, int y) {
+	BITMAP *engineSprite = _engine->GetSpriteGraphic(sprite);
 
-	BITMAP *engineSprite = engine->GetSpriteGraphic(sprite);
-
-	unsigned char **charbuffer = engine->GetRawBitmapSurface(engineSprite);
+	unsigned char **charbuffer = _engine->GetRawBitmapSurface(engineSprite);
 	unsigned int **longbuffer = (unsigned int **)charbuffer;
 
 	int alpha = geta32(longbuffer[y][x]);
 
-	engine->ReleaseBitmapSurface(engineSprite);
+	_engine->ReleaseBitmapSurface(engineSprite);
 
 	return alpha;
-
 }
 
-/// <summary>
-/// Sets the alpha value at coords x,y
-/// </summary>
-int PutAlpha(int sprite, int x, int y, int alpha) {
+int AGSBlend::PutAlpha(int sprite, int x, int y, int alpha) {
+	BITMAP *engineSprite = _engine->GetSpriteGraphic(sprite);
 
-	BITMAP *engineSprite = engine->GetSpriteGraphic(sprite);
-
-	unsigned char **charbuffer = engine->GetRawBitmapSurface(engineSprite);
+	unsigned char **charbuffer = _engine->GetRawBitmapSurface(engineSprite);
 	unsigned int **longbuffer = (unsigned int **)charbuffer;
 
 
@@ -199,31 +175,22 @@ int PutAlpha(int sprite, int x, int y, int alpha) {
 	int b = getb32(longbuffer[y][x]);
 	longbuffer[y][x] = makeacol32(r, g, b, alpha);
 
-	engine->ReleaseBitmapSurface(engineSprite);
+	_engine->ReleaseBitmapSurface(engineSprite);
 
 	return alpha;
-
 }
 
-
-/// <summary>
-///  Translates index from a 2D array to a 1D array
-/// </summary>
-int xytolocale(int x, int y, int width) {
-
+int AGSBlend::xytolocale(int x, int y, int width) {
 	return (y * width + x);
-
-
 }
 
-int HighPass(int sprite, int threshold) {
-
-	BITMAP *src = engine->GetSpriteGraphic(sprite);
+int AGSBlend::HighPass(int sprite, int threshold) {
+	BITMAP *src = _engine->GetSpriteGraphic(sprite);
 	int srcWidth, srcHeight;
 
-	engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, nullptr);
+	_engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, nullptr);
 
-	unsigned char **srccharbuffer = engine->GetRawBitmapSurface(src);
+	unsigned char **srccharbuffer = _engine->GetRawBitmapSurface(src);
 	unsigned int **srclongbuffer = (unsigned int **)srccharbuffer;
 
 	for (int y = 0; y < srcHeight; y++) {
@@ -248,15 +215,13 @@ int HighPass(int sprite, int threshold) {
 
 }
 
-
-int Blur(int sprite, int radius) {
-
-	BITMAP *src = engine->GetSpriteGraphic(sprite);
+int AGSBlend::Blur(int sprite, int radius) {
+	BITMAP *src = _engine->GetSpriteGraphic(sprite);
 
 	int srcWidth, srcHeight;
-	engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, nullptr);
+	_engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, nullptr);
 
-	unsigned char **srccharbuffer = engine->GetRawBitmapSurface(src);
+	unsigned char **srccharbuffer = _engine->GetRawBitmapSurface(src);
 	unsigned int **srclongbuffer = (unsigned int **)srccharbuffer;
 	int negrad = -1 * radius;
 
@@ -265,31 +230,21 @@ int Blur(int sprite, int radius) {
 	Pixel32 *Dest = new Pixel32[(srcWidth + (radius * 2)) * (srcHeight + (radius * 2))];  // this is the destination sprite. both have a border all the way round equal to the radius for the blurring.
 	Pixel32 *Temp = new Pixel32[(srcWidth + (radius * 2)) * (srcHeight + (radius * 2))];
 
-
 	int arraywidth = srcWidth + (radius * 2); //define the array width since its used many times in the algorithm
 
-
 	for (int y = 0; y < srcHeight; y++) { //copy the sprite to the Pixels class array
-
 		for (int x = 0; x < srcWidth; x++) {
-
 			int locale = xytolocale(x + radius, y + radius, arraywidth);
 
 			Pixels[locale].Red = getr32(srclongbuffer[y][x]);
 			Pixels[locale].Green = getg32(srclongbuffer[y][x]);
 			Pixels[locale].Blue = getb32(srclongbuffer[y][x]);
 			Pixels[locale].Alpha = geta32(srclongbuffer[y][x]);
-
-
-
 		}
-
 	}
 
-
 	int  numofpixels = (radius * 2 + 1);
 	for (int y = 0; y < srcHeight; y++) {
-
 		int totalr = 0;
 		int totalg = 0;
 		int totalb = 0;
@@ -310,19 +265,16 @@ int Blur(int sprite, int radius) {
 		Temp[locale].Blue = totalb / numofpixels;
 		Temp[locale].Alpha = totala / numofpixels;
 
-
 		// Subsequent pixels just update window total
 		for (int x = 1; x < srcWidth; x++) {
 			// Subtract pixel leaving window
-			int locale = xytolocale(x - 1, y + radius, arraywidth);
+			locale = xytolocale(x - 1, y + radius, arraywidth);
 			totala -= Pixels[locale].Alpha;
 			totalr -= (Pixels[locale].Red * Pixels[locale].Alpha) / 255;
 			totalg -= (Pixels[locale].Green * Pixels[locale].Alpha) / 255;
 			totalb -= (Pixels[locale].Blue * Pixels[locale].Alpha) / 255;
 
-
 			// Add pixel entering window
-
 			locale = xytolocale(x + radius + radius, y + radius, arraywidth);
 			totala += Pixels[locale].Alpha;
 			totalr += (Pixels[locale].Red * Pixels[locale].Alpha) / 255;
@@ -335,15 +287,10 @@ int Blur(int sprite, int radius) {
 			Temp[locale].Green = totalg / numofpixels;
 			Temp[locale].Blue = totalb / numofpixels;
 			Temp[locale].Alpha = totala / numofpixels;
-
 		}
 	}
 
-
-
-
 	for (int x = 0; x < srcWidth; x++) {
-
 		int totalr = 0;
 		int totalg = 0;
 		int totalb = 0;
@@ -364,11 +311,10 @@ int Blur(int sprite, int radius) {
 		Dest[locale].Blue = totalb / numofpixels;
 		Dest[locale].Alpha = totala / numofpixels;
 
-
 		// Subsequent pixels just update window total
 		for (int y = 1; y < srcHeight; y++) {
 			// Subtract pixel leaving window
-			int locale = xytolocale(x + radius, y - 1, arraywidth);
+			locale = xytolocale(x + radius, y - 1, arraywidth);
 			totala -= Temp[locale].Alpha;
 			totalr -= (Temp[locale].Red * Temp[locale].Alpha) / 255;
 			totalg -= (Temp[locale].Green * Temp[locale].Alpha) / 255;
@@ -389,64 +335,51 @@ int Blur(int sprite, int radius) {
 			Dest[locale].Green = totalg / numofpixels;
 			Dest[locale].Blue = totalb / numofpixels;
 			Dest[locale].Alpha = totala / numofpixels;
-
 		}
 	}
 
-
-
 	for (int y = 0; y < srcHeight; y++) {
 
 		for (int x = 0; x < srcWidth; x++) {
 			int locale = xytolocale(x + radius, y + radius, arraywidth);
 			srclongbuffer[y][x] = Dest[locale].GetColorAsInt(); //write the destination array to the main buffer
-
 		}
-
 	}
+
 	delete [] Pixels;
 	delete [] Dest;
 	delete [] Temp;
-	engine->ReleaseBitmapSurface(src);
+	_engine->ReleaseBitmapSurface(src);
 	delete srclongbuffer;
 	delete srccharbuffer;
-	return 0;
-}
-
-int Clamp(int val, int min, int max) {
-
-	if (val < min) return min;
-	else if (val > max) return max;
-	else return val;
 
+	return 0;
 }
 
-int DrawSprite(int destination, int sprite, int x, int y, int DrawMode, int trans) {
-
+int AGSBlend::DrawSprite(int destination, int sprite, int x, int y, int DrawMode, int trans) {
 	trans = 100 - trans;
 	int srcWidth, srcHeight, destWidth, destHeight;
 
-	BITMAP *src = engine->GetSpriteGraphic(sprite);
-	BITMAP *dest = engine->GetSpriteGraphic(destination);
+	BITMAP *src = _engine->GetSpriteGraphic(sprite);
+	BITMAP *dest = _engine->GetSpriteGraphic(destination);
 
-	engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, nullptr);
-	engine->GetBitmapDimensions(dest, &destWidth, &destHeight, nullptr);
+	_engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, nullptr);
+	_engine->GetBitmapDimensions(dest, &destWidth, &destHeight, nullptr);
 
 	if (x > destWidth || y > destHeight || x + srcWidth < 0 || y + srcHeight < 0) return 1; // offscreen
 
-	unsigned char **srccharbuffer = engine->GetRawBitmapSurface(src);
+	unsigned char **srccharbuffer = _engine->GetRawBitmapSurface(src);
 	unsigned int **srclongbuffer = (unsigned int **)srccharbuffer;
 
-	unsigned char **destcharbuffer = engine->GetRawBitmapSurface(dest);
+	unsigned char **destcharbuffer = _engine->GetRawBitmapSurface(dest);
 	unsigned int **destlongbuffer = (unsigned int **)destcharbuffer;
 
-
-
 	if (srcWidth + x > destWidth) srcWidth = destWidth - x - 1;
 	if (srcHeight + y > destHeight) srcHeight = destHeight - y - 1;
 
 	int destx, desty;
-	int srcr, srcg, srcb, srca, destr, destg, destb, desta, finalr, finalg, finalb, finala;
+	int srcr, srcg, srcb, srca, destr, destg, destb, desta;
+	int finalr = 0, finalg = 0, finalb = 0, finala = 0;
 	unsigned int col;
 	int starty = 0;
 	int startx = 0;
@@ -457,9 +390,7 @@ int DrawSprite(int destination, int sprite, int x, int y, int DrawMode, int tran
 	int ycount = 0;
 	int xcount = 0;
 	for (ycount = starty; ycount < srcHeight; ycount ++) {
-
 		for (xcount = startx; xcount < srcWidth; xcount ++) {
-
 			destx = xcount + x;
 			desty = ycount + y;
 
@@ -476,208 +407,153 @@ int DrawSprite(int destination, int sprite, int x, int y, int DrawMode, int tran
 				destb =  getb32(destlongbuffer[desty][destx]);
 				desta =  geta32(destlongbuffer[desty][destx]);
 
-
-
-
 				switch (DrawMode) {
-
 				case 0:
-
 					finalr = srcr;
 					finalg = srcg;
 					finalb = srcb;
 					break;
 
 				case 1:
-
 					finalr = ChannelBlend_Lighten(srcr, destr);
 					finalg = ChannelBlend_Lighten(srcg, destg);
 					finalb = ChannelBlend_Lighten(srcb, destb);
 					break;
 
 				case 2:
-
-
 					finalr = ChannelBlend_Darken(srcr, destr);
 					finalg = ChannelBlend_Darken(srcg, destg);
 					finalb = ChannelBlend_Darken(srcb, destb);
 					break;
 
 				case 3:
-
-
 					finalr = ChannelBlend_Multiply(srcr, destr);
 					finalg = ChannelBlend_Multiply(srcg, destg);
 					finalb = ChannelBlend_Multiply(srcb, destb);
 					break;
 
 				case 4:
-
-
 					finalr = ChannelBlend_Add(srcr, destr);
 					finalg = ChannelBlend_Add(srcg, destg);
 					finalb = ChannelBlend_Add(srcb, destb);
 					break;
 
 				case 5:
-
-
 					finalr = ChannelBlend_Subtract(srcr, destr);
 					finalg = ChannelBlend_Subtract(srcg, destg);
 					finalb = ChannelBlend_Subtract(srcb, destb);
 					break;
 
 				case 6:
-
-
 					finalr = ChannelBlend_Difference(srcr, destr);
 					finalg = ChannelBlend_Difference(srcg, destg);
 					finalb = ChannelBlend_Difference(srcb, destb);
 					break;
 
 				case 7:
-
-
 					finalr = ChannelBlend_Negation(srcr, destr);
 					finalg = ChannelBlend_Negation(srcg, destg);
 					finalb = ChannelBlend_Negation(srcb, destb);
 					break;
 
 				case 8:
-
-
 					finalr = ChannelBlend_Screen(srcr, destr);
 					finalg = ChannelBlend_Screen(srcg, destg);
 					finalb = ChannelBlend_Screen(srcb, destb);
 					break;
 
-
 				case 9:
-
-
 					finalr = ChannelBlend_Exclusion(srcr, destr);
 					finalg = ChannelBlend_Exclusion(srcg, destg);
 					finalb = ChannelBlend_Exclusion(srcb, destb);
 					break;
 
-
 				case 10:
-
-
 					finalr = ChannelBlend_Overlay(srcr, destr);
 					finalg = ChannelBlend_Overlay(srcg, destg);
 					finalb = ChannelBlend_Overlay(srcb, destb);
 					break;
 
-
 				case 11:
-
-
 					finalr = ChannelBlend_SoftLight(srcr, destr);
 					finalg = ChannelBlend_SoftLight(srcg, destg);
 					finalb = ChannelBlend_SoftLight(srcb, destb);
 					break;
 
 				case 12:
-
-
 					finalr = ChannelBlend_HardLight(srcr, destr);
 					finalg = ChannelBlend_HardLight(srcg, destg);
 					finalb = ChannelBlend_HardLight(srcb, destb);
 					break;
 
 				case 13:
-
-
 					finalr = ChannelBlend_ColorDodge(srcr, destr);
 					finalg = ChannelBlend_ColorDodge(srcg, destg);
 					finalb = ChannelBlend_ColorDodge(srcb, destb);
 					break;
 
 				case 14:
-
-
 					finalr = ChannelBlend_ColorBurn(srcr, destr);
 					finalg = ChannelBlend_ColorBurn(srcg, destg);
 					finalb = ChannelBlend_ColorBurn(srcb, destb);
 					break;
 
 				case 15:
-
-
 					finalr = ChannelBlend_LinearDodge(srcr, destr);
 					finalg = ChannelBlend_LinearDodge(srcg, destg);
 					finalb = ChannelBlend_LinearDodge(srcb, destb);
 					break;
 
 				case 16:
-
-
 					finalr = ChannelBlend_LinearBurn(srcr, destr);
 					finalg = ChannelBlend_LinearBurn(srcg, destg);
 					finalb = ChannelBlend_LinearBurn(srcb, destb);
 					break;
 
-
-
 				case 17:
-
-
 					finalr = ChannelBlend_LinearLight(srcr, destr);
 					finalg = ChannelBlend_LinearLight(srcg, destg);
 					finalb = ChannelBlend_LinearLight(srcb, destb);
 					break;
 
-
-
 				case 18:
-
-
 					finalr = ChannelBlend_VividLight(srcr, destr);
 					finalg = ChannelBlend_VividLight(srcg, destg);
 					finalb = ChannelBlend_VividLight(srcb, destb);
 					break;
 
 				case 19:
-
-
 					finalr = ChannelBlend_PinLight(srcr, destr);
 					finalg = ChannelBlend_PinLight(srcg, destg);
 					finalb = ChannelBlend_PinLight(srcb, destb);
 					break;
 
 				case 20:
-
-
 					finalr = ChannelBlend_HardMix(srcr, destr);
 					finalg = ChannelBlend_HardMix(srcg, destg);
 					finalb = ChannelBlend_HardMix(srcb, destb);
 					break;
 
 				case 21:
-
-
 					finalr = ChannelBlend_Reflect(srcr, destr);
 					finalg = ChannelBlend_Reflect(srcg, destg);
 					finalb = ChannelBlend_Reflect(srcb, destb);
 					break;
 
 				case 22:
-
-
 					finalr = ChannelBlend_Glow(srcr, destr);
 					finalg = ChannelBlend_Glow(srcg, destg);
 					finalb = ChannelBlend_Glow(srcb, destb);
 					break;
 
 				case 23:
-
-
 					finalr = ChannelBlend_Phoenix(srcr, destr);
 					finalg = ChannelBlend_Phoenix(srcg, destg);
 					finalb = ChannelBlend_Phoenix(srcb, destb);
 					break;
 
+				default:
+					break;
 				}
 
 				finala = 255 - (255 - srca) * (255 - desta) / 255;
@@ -694,31 +570,28 @@ int DrawSprite(int destination, int sprite, int x, int y, int DrawMode, int tran
 
 	}
 
-	engine->ReleaseBitmapSurface(src);
-	engine->ReleaseBitmapSurface(dest);
-	engine->NotifySpriteUpdated(destination);
+	_engine->ReleaseBitmapSurface(src);
+	_engine->ReleaseBitmapSurface(dest);
+	_engine->NotifySpriteUpdated(destination);
 	return 0;
 
 }
 
-
-int DrawAdd(int destination, int sprite, int x, int y, float scale) {
-
-
+int AGSBlend::DrawAdd(int destination, int sprite, int x, int y, float scale) {
 	int srcWidth, srcHeight, destWidth, destHeight;
 
-	BITMAP *src = engine->GetSpriteGraphic(sprite);
-	BITMAP *dest = engine->GetSpriteGraphic(destination);
+	BITMAP *src = _engine->GetSpriteGraphic(sprite);
+	BITMAP *dest = _engine->GetSpriteGraphic(destination);
 
-	engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, nullptr);
-	engine->GetBitmapDimensions(dest, &destWidth, &destHeight, nullptr);
+	_engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, nullptr);
+	_engine->GetBitmapDimensions(dest, &destWidth, &destHeight, nullptr);
 
 	if (x > destWidth || y > destHeight) return 1; // offscreen
 
-	unsigned char **srccharbuffer = engine->GetRawBitmapSurface(src);
+	unsigned char **srccharbuffer = _engine->GetRawBitmapSurface(src);
 	unsigned int **srclongbuffer = (unsigned int **)srccharbuffer;
 
-	unsigned char **destcharbuffer = engine->GetRawBitmapSurface(dest);
+	unsigned char **destcharbuffer = _engine->GetRawBitmapSurface(dest);
 	unsigned int **destlongbuffer = (unsigned int **)destcharbuffer;
 
 	if (srcWidth + x > destWidth) srcWidth = destWidth - x - 1;
@@ -736,20 +609,14 @@ int DrawAdd(int destination, int sprite, int x, int y, float scale) {
 	if (x < 0) startx = -1 * x;
 	if (y < 0) starty = -1 * y;
 
-
-
 	for (ycount = starty; ycount < srcHeight; ycount ++) {
-
 		for (xcount = startx; xcount < srcWidth; xcount ++) {
-
 			destx = xcount + x;
 			desty = ycount + y;
 
 			srca = (geta32(srclongbuffer[ycount][xcount]));
 
 			if (srca != 0) {
-
-
 				srcr =  getr32(srclongbuffer[ycount][xcount]) * srca / 255 * scale;
 				srcg =  getg32(srclongbuffer[ycount][xcount]) * srca / 255 * scale;
 				srcb =  getb32(srclongbuffer[ycount][xcount]) * srca / 255 * scale;
@@ -767,47 +634,39 @@ int DrawAdd(int destination, int sprite, int x, int y, float scale) {
 				}
 
 				finala = 255 - (255 - srca) * (255 - desta) / 255;
-				finalr = Clamp(srcr + destr, 0, 255);
-				finalg = Clamp(srcg + destg, 0, 255);
-				finalb = Clamp(srcb + destb, 0, 255);
+				finalr = CLIP(srcr + destr, 0, 255);
+				finalg = CLIP(srcg + destg, 0, 255);
+				finalb = CLIP(srcb + destb, 0, 255);
 				col = makeacol32(finalr, finalg, finalb, finala);
 				destlongbuffer[desty][destx] = col;
-
 			}
-
 		}
-
 	}
 
-	engine->ReleaseBitmapSurface(src);
-	engine->ReleaseBitmapSurface(dest);
-	engine->NotifySpriteUpdated(destination);
-	return 0;
-
-
+	_engine->ReleaseBitmapSurface(src);
+	_engine->ReleaseBitmapSurface(dest);
+	_engine->NotifySpriteUpdated(destination);
 
+	return 0;
 }
 
-
-
-int DrawAlpha(int destination, int sprite, int x, int y, int trans) {
-
+int AGSBlend::DrawAlpha(int destination, int sprite, int x, int y, int trans) {
 	trans = 100 - trans;
 
 	int srcWidth, srcHeight, destWidth, destHeight;
 
-	BITMAP *src = engine->GetSpriteGraphic(sprite);
-	BITMAP *dest = engine->GetSpriteGraphic(destination);
+	BITMAP *src = _engine->GetSpriteGraphic(sprite);
+	BITMAP *dest = _engine->GetSpriteGraphic(destination);
 
-	engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, nullptr);
-	engine->GetBitmapDimensions(dest, &destWidth, &destHeight, nullptr);
+	_engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, nullptr);
+	_engine->GetBitmapDimensions(dest, &destWidth, &destHeight, nullptr);
 
 	if (x > destWidth || y > destHeight) return 1; // offscreen
 
-	unsigned char **srccharbuffer = engine->GetRawBitmapSurface(src);
+	unsigned char **srccharbuffer = _engine->GetRawBitmapSurface(src);
 	unsigned int **srclongbuffer = (unsigned int **)srccharbuffer;
 
-	unsigned char **destcharbuffer = engine->GetRawBitmapSurface(dest);
+	unsigned char **destcharbuffer = _engine->GetRawBitmapSurface(dest);
 	unsigned int **destlongbuffer = (unsigned int **)destcharbuffer;
 
 	if (srcWidth + x > destWidth) srcWidth = destWidth - x - 1;
@@ -825,18 +684,14 @@ int DrawAlpha(int destination, int sprite, int x, int y, int trans) {
 	if (x < 0) startx = -1 * x;
 	if (y < 0) starty = -1 * y;
 
-
 	for (ycount = starty; ycount < srcHeight; ycount ++) {
-
 		for (xcount = startx; xcount < srcWidth; xcount ++) {
-
 			destx = xcount + x;
 			desty = ycount + y;
 
 			srca = (geta32(srclongbuffer[ycount][xcount])) * trans / 100;
 
 			if (srca != 0) {
-
 				srcr =  getr32(srclongbuffer[ycount][xcount]);
 				srcg =  getg32(srclongbuffer[ycount][xcount]);
 				srcb =  getb32(srclongbuffer[ycount][xcount]);
@@ -852,191 +707,17 @@ int DrawAlpha(int destination, int sprite, int x, int y, int trans) {
 				finalb = srca * srcb / finala + desta * destb * (255 - srca) / finala / 255;
 
 				destlongbuffer[desty][destx] = makeacol32(finalr, finalg, finalb, finala);
-
 			}
-
 		}
-
-	}
-
-	engine->ReleaseBitmapSurface(src);
-	engine->ReleaseBitmapSurface(dest);
-	engine->NotifySpriteUpdated(destination);
-
-	return 0;
-}
-
-
-#if AGS_PLATFORM_OS_WINDOWS
-
-//==============================================================================
-
-// ***** Design time *****
-
-IAGSEditor *editor; // Editor interface
-
-const char *ourScriptHeader =
-    "import int DrawAlpha(int destination, int sprite, int x, int y, int transparency);\r\n"
-    "import int GetAlpha(int sprite, int x, int y);\r\n"
-    "import int PutAlpha(int sprite, int x, int y, int alpha);\r\n"
-    "import int Blur(int sprite, int radius);\r\n"
-    "import int HighPass(int sprite, int threshold);\r\n"
-    "import int DrawAdd(int destination, int sprite, int x, int y, float scale);\r\n"
-    "import int DrawSprite(int destination, int sprite, int x, int y, int DrawMode, int trans);";
-
-
-
-
-//------------------------------------------------------------------------------
-
-LPCSTR AGS_GetPluginName() {
-	return ("AGSBlend");
-}
-
-//------------------------------------------------------------------------------
-
-int AGS_EditorStartup(IAGSEditor *lpEditor) {
-	// User has checked the plugin to use it in their game
-
-	// If it's an earlier version than what we need, abort.
-	if (lpEditor->version < MIN_EDITOR_VERSION)
-		return (-1);
-
-	editor = lpEditor;
-	editor->RegisterScriptHeader(ourScriptHeader);
-
-	// Return 0 to indicate success
-	return (0);
-}
-
-//------------------------------------------------------------------------------
-
-void AGS_EditorShutdown() {
-	// User has un-checked the plugin from their game
-	editor->UnregisterScriptHeader(ourScriptHeader);
-}
-
-//------------------------------------------------------------------------------
-
-void AGS_EditorProperties(HWND parent) {                      //*** optional ***
-	// User has chosen to view the Properties of the plugin
-	// We could load up an options dialog or something here instead
-	/*  MessageBox(parent,
-	               L"AGSBlend v1.0 By Calin Leafshade",
-	               L"About",
-	               MB_OK | MB_ICONINFORMATION);
-	         */
-}
-
-//------------------------------------------------------------------------------
-
-int AGS_EditorSaveGame(char *buffer, int bufsize) {           //*** optional ***
-	// Called by the editor when the current game is saved to disk.
-	// Plugin configuration can be stored in [buffer] (max [bufsize] bytes)
-	// Return the amount of bytes written in the buffer
-	return (0);
-}
-
-//------------------------------------------------------------------------------
-
-void AGS_EditorLoadGame(char *buffer, int bufsize) {          //*** optional ***
-	// Called by the editor when a game is loaded from disk
-	// Previous written data can be read from [buffer] (size [bufsize]).
-	// Make a copy of the data, the buffer is freed after this function call.
-}
-
-//==============================================================================
-
-#endif
-
-// ***** Run time *****
-
-// Engine interface
-
-//------------------------------------------------------------------------------
-
-#define REGISTER(x) engine->RegisterScriptFunction(#x, (void *) (x));
-#define STRINGIFY(s) STRINGIFY_X(s)
-#define STRINGIFY_X(s) #s
-
-void AGS_EngineStartup(IAGSEngine *lpEngine) {
-	engine = lpEngine;
-
-	// Make sure it's got the version with the features we need
-	if (engine->version < MIN_ENGINE_VERSION)
-		engine->AbortGame("Plugin needs engine version " STRINGIFY(MIN_ENGINE_VERSION) " or newer.");
-
-	//register functions
-
-	REGISTER(GetAlpha)
-	REGISTER(PutAlpha)
-	REGISTER(DrawAlpha)
-	REGISTER(Blur)
-	REGISTER(HighPass)
-	REGISTER(DrawAdd)
-	REGISTER(DrawSprite)
-
-
-}
-
-//------------------------------------------------------------------------------
-
-void AGS_EngineShutdown() {
-	// Called by the game engine just before it exits.
-	// This gives you a chance to free any memory and do any cleanup
-	// that you need to do before the engine shuts down.
-}
-
-//------------------------------------------------------------------------------
-
-int AGS_EngineOnEvent(int event, int data) {                  //*** optional ***
-	switch (event) {
-	/*
-	        case AGSE_KEYPRESS:
-	        case AGSE_MOUSECLICK:
-	        case AGSE_POSTSCREENDRAW:
-	        case AGSE_PRESCREENDRAW:
-	        case AGSE_SAVEGAME:
-	        case AGSE_RESTOREGAME:
-	        case AGSE_PREGUIDRAW:
-	        case AGSE_LEAVEROOM:
-	        case AGSE_ENTERROOM:
-	        case AGSE_TRANSITIONIN:
-	        case AGSE_TRANSITIONOUT:
-	        case AGSE_FINALSCREENDRAW:
-	        case AGSE_TRANSLATETEXT:
-	        case AGSE_SCRIPTDEBUG:
-	        case AGSE_SPRITELOAD:
-	        case AGSE_PRERENDER:
-	        case AGSE_PRESAVEGAME:
-	        case AGSE_POSTRESTOREGAME:
-	*/
-	default:
-		break;
 	}
 
-	// Return 1 to stop event from processing further (when needed)
-	return (0);
-}
-
-//------------------------------------------------------------------------------
+	_engine->ReleaseBitmapSurface(src);
+	_engine->ReleaseBitmapSurface(dest);
+	_engine->NotifySpriteUpdated(destination);
 
-int AGS_EngineDebugHook(const char *scriptName,
-                        int lineNum, int reserved) {          //*** optional ***
-	// Can be used to debug scripts, see documentation
 	return 0;
 }
 
-//------------------------------------------------------------------------------
-
-void AGS_EngineInitGfx(const char *driverID, void *data) {    //*** optional ***
-	// This allows you to make changes to how the graphics driver starts up.
-	// See documentation
-}
-
-//..............................................................................
-
-
-#if defined(BUILTIN_PLUGINS)
-}
-#endif
+} // namespace AGSBlend
+} // namespace Plugins
+} // namespace AGS3
diff --git a/engines/ags/plugins/ags_blend/ags_blend.h b/engines/ags/plugins/ags_blend/ags_blend.h
index c09349c9f1..5e6d8c1669 100644
--- a/engines/ags/plugins/ags_blend/ags_blend.h
+++ b/engines/ags/plugins/ags_blend/ags_blend.h
@@ -1,14 +1,73 @@
-#ifndef AGS_BLEND_H
-#define AGS_BLEND_H
+/* 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 "plugin/agsplugin.h"
+#ifndef AGS_PLUGINS_AGS_BLEND_AGS_BLEND_H
+#define AGS_PLUGINS_AGS_BLEND_AGS_BLEND_H
 
-namespace agsblend {
-void AGS_EngineStartup(IAGSEngine *lpEngine);
-void AGS_EngineShutdown();
-int AGS_EngineOnEvent(int event, int data);
-int AGS_EngineDebugHook(const char *scriptName, int lineNum, int reserved);
-void AGS_EngineInitGfx(const char *driverID, void *data);
-}
+#include "ags/plugins/dll.h"
 
-#endif
\ No newline at end of file
+namespace AGS3 {
+namespace Plugins {
+namespace AGSBlend {
+
+/**
+ * Author: Steven Poulton
+ * Description: An AGS Plugin to allow true Alpha Blending
+ */
+class AGSBlend : public DLL {
+private:
+	static IAGSEngine *_engine;
+private:
+	static const char *AGS_GetPluginName();
+	static void AGS_EngineStartup(IAGSEngine *lpEngine);
+
+private:
+	/**
+	 * Gets the alpha value at coords x,y
+	 */
+	static int GetAlpha(int sprite, int x, int y);
+
+	/**
+	 * Sets the alpha value at coords x,y
+	 */
+	static int PutAlpha(int sprite, int x, int y, int alpha);
+
+	/**
+	 * Translates index from a 2D array to a 1D array
+	 */
+	static int xytolocale(int x, int y, int width);
+
+	static int HighPass(int sprite, int threshold);
+	static int Blur(int sprite, int radius);
+	static int DrawSprite(int destination, int sprite, int x, int y, int DrawMode, int trans);
+	static int DrawAdd(int destination, int sprite, int x, int y, float scale);
+	static int DrawAlpha(int destination, int sprite, int x, int y, int trans);
+
+public:
+	AGSBlend();
+};
+
+} // namespace AGSBlend
+} // namespace Plugins
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/plugins/ags_flashlight/ags_flashlight.cpp b/engines/ags/plugins/ags_flashlight/ags_flashlight.cpp
index c36e7ec401..0e2353a23f 100644
--- a/engines/ags/plugins/ags_flashlight/ags_flashlight.cpp
+++ b/engines/ags/plugins/ags_flashlight/ags_flashlight.cpp
@@ -73,7 +73,7 @@ unsigned long AGSFlashlight::flashlight_n;
 
 IAGSEngine *AGSFlashlight::_engine;
 
-AGSFlashlight::AGSFlashlight() {
+AGSFlashlight::AGSFlashlight() : DLL() {
 	_engine = nullptr;
 	screen_width = 320;
 	screen_height = 200;
diff --git a/engines/ags/plugins/ags_flashlight/ags_flashlight.h b/engines/ags/plugins/ags_flashlight/ags_flashlight.h
index d225d7e501..2c24fde7c0 100644
--- a/engines/ags/plugins/ags_flashlight/ags_flashlight.h
+++ b/engines/ags/plugins/ags_flashlight/ags_flashlight.h
@@ -25,9 +25,6 @@
 
 #include "ags/plugins/dll.h"
 #include "ags/lib/allegro.h"
-#include "common/array.h"
-#include "common/rect.h"
-#include "common/str.h"
 
 namespace AGS3 {
 namespace Plugins {
diff --git a/engines/ags/plugins/dll.cpp b/engines/ags/plugins/dll.cpp
index c1fd382345..f08ce59b96 100644
--- a/engines/ags/plugins/dll.cpp
+++ b/engines/ags/plugins/dll.cpp
@@ -22,6 +22,7 @@
 
 #include "ags/lib/allegro.h"
 #include "ags/plugins/dll.h"
+#include "ags/plugins/ags_blend/ags_blend.h"
 #include "ags/plugins/ags_creditz/ags_creditz.h"
 #include "ags/plugins/ags_flashlight/ags_flashlight.h"
 #include "ags/ags.h"
@@ -44,12 +45,16 @@ void *dlopen(const char *filename) {
 		}
 	}
 
+	if (fname.equalsIgnoreCase("libAGSBlend.so"))
+		return new AGSBlend::AGSBlend();
+
 	if (fname.equalsIgnoreCase("libagsCreditz.so")) {
 		if (version == 20)
 			return new AGSCreditz::AGSCreditz20();
 		else
 			return new AGSCreditz::AGSCreditz11();
 	}
+
 	if (fname.equalsIgnoreCase("libAGSFlashlight.so"))
 		return new AGSFlashlight::AGSFlashlight();
 


Commit: f46df1bb904fbe76880b938fa815863b853f1baf
    https://github.com/scummvm/scummvm/commit/f46df1bb904fbe76880b938fa815863b853f1baf
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added AGSPalRender plugin

Changed paths:
  R engines/ags/plugins/ags_pal_render/agsplugin.h
    engines/ags/module.mk
    engines/ags/plugins/ags_flashlight/ags_flashlight.cpp
    engines/ags/plugins/ags_flashlight/ags_flashlight.h
    engines/ags/plugins/ags_pal_render/ags_pal_render.cpp
    engines/ags/plugins/ags_pal_render/ags_pal_render.h
    engines/ags/plugins/ags_pal_render/pal_render.h
    engines/ags/plugins/ags_pal_render/raycast.cpp
    engines/ags/plugins/ags_pal_render/raycast.h
    engines/ags/plugins/dll.cpp


diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index f9c053ed34..fbfc1d2395 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -303,7 +303,9 @@ MODULE_OBJS = \
 	plugins/dll.o \
 	plugins/ags_blend/ags_blend.o \
 	plugins/ags_creditz/ags_creditz.o \
-	plugins/ags_flashlight/ags_flashlight.o
+	plugins/ags_flashlight/ags_flashlight.o \
+	plugins/ags_pal_render/ags_pal_render.o \
+	plugins/ags_pal_render/raycast.o
 
 ifdef ENABLE_AGS_TESTS
 MODULE_OBJS += \
diff --git a/engines/ags/plugins/ags_flashlight/ags_flashlight.cpp b/engines/ags/plugins/ags_flashlight/ags_flashlight.cpp
index 0e2353a23f..116c4a0449 100644
--- a/engines/ags/plugins/ags_flashlight/ags_flashlight.cpp
+++ b/engines/ags/plugins/ags_flashlight/ags_flashlight.cpp
@@ -111,10 +111,9 @@ AGSFlashlight::AGSFlashlight() : DLL() {
 
 
 	DLL_METHOD(AGS_GetPluginName);
+	DLL_METHOD(AGS_EngineStartup);
 	DLL_METHOD(AGS_EngineShutdown);
 	DLL_METHOD(AGS_EngineOnEvent);
-	DLL_METHOD(AGS_EngineDebugHook);
-	DLL_METHOD(AGS_EngineInitGfx);
 }
 
 const char *AGSFlashlight::AGS_GetPluginName() {
@@ -196,14 +195,6 @@ int AGSFlashlight::AGS_EngineOnEvent(int event, int data) {
 	return 0;
 }
 
-int AGSFlashlight::AGS_EngineDebugHook(const char *scriptName, int lineNum, int reserved) {
-	return 0;
-}
-
-void AGSFlashlight::AGS_EngineInitGfx(const char *driverID, void *data) {
-}
-
-
 void AGSFlashlight::calc_x_n(unsigned long x) {
 	flashlight_x = x;
 
diff --git a/engines/ags/plugins/ags_flashlight/ags_flashlight.h b/engines/ags/plugins/ags_flashlight/ags_flashlight.h
index 2c24fde7c0..182b3dfb2c 100644
--- a/engines/ags/plugins/ags_flashlight/ags_flashlight.h
+++ b/engines/ags/plugins/ags_flashlight/ags_flashlight.h
@@ -68,8 +68,6 @@ private:
 	static void AGS_EngineStartup(IAGSEngine *engine);
 	static void AGS_EngineShutdown();
 	static int AGS_EngineOnEvent(int event, int data);
-	static int AGS_EngineDebugHook(const char *scriptName, int lineNum, int reserved);
-	static void AGS_EngineInitGfx(const char *driverID, void *data);
 
 private:
 	/**
diff --git a/engines/ags/plugins/ags_pal_render/ags_pal_render.cpp b/engines/ags/plugins/ags_pal_render/ags_pal_render.cpp
index 7275320213..b7467a09f5 100644
--- a/engines/ags/plugins/ags_pal_render/ags_pal_render.cpp
+++ b/engines/ags/plugins/ags_pal_render/ags_pal_render.cpp
@@ -1,36 +1,34 @@
-//
-// ags_template.cpp : Example AGS plugin file
-// See the online API reference for details of how this works.
-// Copyright (c) 2002 Chris Jones
-//
-
-#include "core/platform.h"
-
-#if AGS_PLATFORM_OS_WINDOWS
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#endif
-
-#if !defined(BUILTIN_PLUGINS)
-#define THIS_IS_THE_PLUGIN
-#endif
-
-#include <algorithm>
-#include <cmath>
-#include <string>
-#include <vector>
-#include <iostream>
-#include <math.h>
-#include <time.h>
-#include <stdlib.h>
-#include <string>
-#include <stdio.h>
-
-
-
-#include "plugin/agsplugin.h"
-#include "palrender.h"
-#include "raycast.h"
+/* 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 "ags/lib/allegro.h"
+#include "ags/plugins/ags_pal_render/ags_pal_render.h"
+#include "ags/plugins/ags_pal_render/pal_render.h"
+#include "ags/plugins/ags_pal_render/raycast.h"
+#include "ags/ags.h"
+
+namespace AGS3 {
+namespace Plugins {
+namespace AGSPalRender {
 
 #define MAX_OVERLAYS 128
 #define MAX_STARS 1024
@@ -40,31 +38,6 @@
 #define HALF_PI    (0.5f * PI)
 #define TWO_PI     (2.0f * PI)
 #define TWO_PI_INV (1.0f / TWO_PI)
-// DllMain - standard Windows DLL entry point.
-// The AGS editor will cause this to get called when the editor first
-// starts up, and when it shuts down at the end.
-
-#if AGS_PLATFORM_OS_WINDOWS
-bool APIENTRY DllMain(HANDLE hModule,
-                      DWORD  ul_reason_for_call,
-                      LPVOID lpReserved) {
-
-	switch (ul_reason_for_call)   {
-	case DLL_PROCESS_ATTACH:
-	case DLL_THREAD_ATTACH:
-	case DLL_THREAD_DETACH:
-	case DLL_PROCESS_DETACH:
-		break;
-	}
-	return TRUE;
-}
-#endif
-
-
-
-#if defined(BUILTIN_PLUGINS)
-namespace agspalrender {
-#endif
 
 const float halfpi = (0.5f * PI);
 const float twopi  = (2.0f * PI);
@@ -72,6 +45,8 @@ const float twopi_inv = (1.0f / TWO_PI);
 const float pisquared = PI * PI;
 const float picubed = PI * PI * PI;
 
+IAGSEngine *engine;
+
 //unsigned char clut[256][256];
 unsigned char clut[65536];
 
@@ -161,313 +136,6 @@ BITMAP *backgroundimage;
 PALSTRUCT objectivepal[256];
 int bgimgspr;
 
-// ***** DESIGN TIME CALLS *******
-#if AGS_PLATFORM_OS_WINDOWS && !defined(BUILTIN_PLUGINS)
-
-IAGSEditor *editor;
-const char *ourScriptHeader =
-    "enum BlendingMode {																	\r\n"
-    "eBlendAlpha = 0,																		\r\n"
-    "eBlendAdditive = 1																	\r\n"
-    "};																					\r\n"
-    "enum ObjectiveMode {																	\r\n"
-    "eUseStandardPal = 0,																	\r\n"
-    "eUseObjectivePal = 1																	\r\n"
-    "};																					\r\n"
-    "enum PlasmaMixMode {																	\r\n"
-    "ePlasmaNone = 0,																		\r\n"
-    "ePlasmaHorzBars = 1,																    \r\n"
-    "ePlasmaVertBars = 2,																    \r\n"
-    "ePlasmaCircle   = 3,																    \r\n"
-    "ePlasmaDiagBars = 4																    \r\n"
-    "};																					\r\n"
-    "enum PlasmaRootType {																\r\n"
-    "ePlasmaSlowRoot = 1,																	\r\n"
-    "ePlasmaFastRoot = 0																    \r\n"
-    "};																					\r\n"
-    "enum TransOverlayLevel {																\r\n"
-    "eTOBackground = 0,																	\r\n"
-    "eTOPreGUI     = 1,																	\r\n"
-    "eTOPostGUI    = 2																	\r\n"
-    "};																					\r\n"
-    "enum LensLevel {																		\r\n"
-    "eLensBackgroundPreTO = 0,															\r\n"
-    "eLensBackgroundPostTO = 1,															\r\n"
-    "eLensPreGUIPreTO     = 2,															\r\n"
-    "eLensPreGUIPostTO     = 3,															\r\n"
-    "eLensPostGUIPreTO     = 4,															\r\n"
-    "eLensPostGUIPostTO     = 5															\r\n"
-    "};																					\r\n"
-
-    "struct Raycast {																					   \r\n"
-    "import static void Render (int slot);															   \r\n"
-    "import static void UnloadEngine ();	//$AUTOCOMPLETEIGNORE$										   \r\n"
-    "import static void MoveForward ();																   \r\n"
-    "import static void MoveBackward ();																   \r\n"
-    "import static void RotateLeft ();																   \r\n"
-    "import static void RotateRight ();																   \r\n"
-    "import static void MakeTextures (int slot);														   \r\n"
-    "import static void Initialize (); 																   \r\n"
-    "import static void LoadMap (int worldmapSlot,int lightmapSlot,int ceilingmapSlot,int floormapSlot); \r\n"
-    "import static void SetCameraPosition (float x,float y);				 						   \r\n"
-    "import static float GetCameraX (); 														       \r\n"
-    "import static float GetCameraY (); 															   \r\n"
-    "import static int GetCameraAngle (); 														   \r\n"
-    "import static void SetCameraAngle (int angle); 												   \r\n"
-    "import static void InitSprite (int id, float x, float y, int slot, char alpha=255, BlendingMode blendmode=0, float scale_x=0, float scale_y=0, float vMove=0);\r\n"
-    "import static int GetHotspotAtXY (int x,int y); 												   \r\n"
-    "import static int GetObjectAtXY (int x,int y); 												   \r\n"
-
-    "import static void SetSpriteInteractObj (int id,int obj); 									   \r\n"
-    "import static int  GetSpriteInteractObj (int id);		 									   \r\n"
-    "import static void SetSpritePosition (int id, float x, float y); 							   \r\n"
-    "import static void SetSpriteVertOffset (int id, float vMove); 								   \r\n"
-    "import static float GetSpriteVertOffset (int id);	 										   \r\n"
-    "import static float GetSpriteX (int id); 													   \r\n"
-    "import static float GetSpriteY (int id);														   \r\n"
-    "import static int GetSpriteAngle (int id);													   \r\n"
-    "import static void SetSpriteAngle (int id,int angle);										   \r\n"
-    "import static void SetSpriteView (int id,int view);											   \r\n"
-    "import static int GetSpriteView (int id);													   \r\n"
-    "import static void SetSpriteFrame (int id,int frame);										   \r\n"
-    "import static int GetSpriteFrame (int id);													   \r\n"
-    "import static float GetSpriteScaleX (int id);											       \r\n"
-    "import static void SetSpriteScaleX (int id,float scale);									       \r\n"
-    "import static float GetSpriteScaleY (int id);												   \r\n"
-    "import static void SetSpriteScaleY (int id,float scale);										   \r\n"
-
-
-    "import static void SetWallHotspot (int id,char hotsp);	 									   \r\n"
-    "import static void SetWallTextures (int id,int n,int s,int w,int e);							   \r\n"
-    "import static void SetWallSolid (int id,int n,int s,int w,int e); 							   \r\n"
-    "import static void SetWallIgnoreLighting (int id,int n,int s,int w,int e);					   \r\n"
-    "import static void SetWallAlpha (int id,int n,int s,int w,int e); 							   \r\n"
-    "import static void SetWallBlendType (int id,BlendingMode n,BlendingMode s,BlendingMode w,BlendingMode e);\r\n"
-
-    "import static float GetMoveSpeed ();															   \r\n"
-    "import static void SetMoveSpeed (float speed);												   \r\n"
-    "import static float GetRotSpeed ();															   \r\n"
-    "import static void SetRotSpeed (float speed); 												   \r\n"
-    "import static int GetWallAt (int x,int y); 													   \r\n"
-    "import static int GetLightAt (int x,int y); 													   \r\n"
-    "import static void SetLightAt (int x,int y, int light); 										   \r\n"
-    "import static void SetWallAt (int x,int y,int id);											   \r\n"
-    "import static void SetPlaneY (float y);	 													   \r\n"
-    "import static float GetDistanceAt (int x,int y);					  							   \r\n"
-    "import static void SetSkyBox (int slot);						  							   	   \r\n"
-    "import static int GetSkyBox (int slot);						  							       \r\n"
-    "import static void SetAmbientLight (int value);				  							       \r\n"
-    "import static int GetAmbientLight ();						  							       \r\n"
-    "import static void SetFloorAt (int x,int y,int tex);										       \r\n"
-    "import static void SetCeilingAt (int x,int y,int tex);									       \r\n"
-    "import static int GetCeilingAt (int x,int y);											       \r\n"
-    "import static int GetFloorAt (int x,int y);						  						       \r\n"
-    "import static int GetLightingAt (int x,int y);						 					       \r\n"
-    "import static void SetLightingAt (int x,int y,char lighting);						 		   \r\n"
-    "import static int GetAmbientWeight ();														   \r\n"
-    "import static int GetTileX_At (int x,int y);													   \r\n"
-    "import static int GetTileY_At (int x,int y);													   \r\n"
-    "///Draws a loaded tile onto a sprite (make sure it's 64x64 pixels).							   \r\n"
-    "import static void DrawTile (int spr,int tile);												   \r\n"
-    "///Draws a sprite onto a tile (make sure it's 64x64 pixels).									   \r\n"
-    "import static void DrawOntoTile (int spr,int tile);											   \r\n"
-    "import static int GetWallHotspot (int id);													   \r\n"
-    "import static int GetWallTexture (int id,int dir);											   \r\n"
-    "import static int GetWallSolid (int id,int dir);												   \r\n"
-    "import static int GetWallIgnoreLighting (int id,int dir);									   \r\n"
-    "import static int GetWallAlpha (int id, int dir);											   \r\n"
-    "import static int GetWallBlendType (int id,int dir);											   \r\n"
-    "import static void SelectTile (int x,int y, char color);										   \r\n"
-    "import static void SetNoClip (int value);													   \r\n"
-    "import static int GetNoClip ();																   \r\n"
-    "import static int HasSeenTile (int x,int y);													   \r\n"
-    "import static int GetSpriteAlpha (int id);													   \r\n"
-    "import static void SetSpriteAlpha (int id,int alpha);										   \r\n"
-    "import static int GetSpritePic (int id);														   \r\n"
-    "import static void SetSpritePic (int id,int slot);											   \r\n"
-    "import static void SetSpriteBlendType (int id,BlendingMode type);							   \r\n"
-    "import static int GetSpriteBlendType (int id);												   \r\n"
-    "import static void SetAmbientColor (int color,int amount);									   \r\n"
-    "int dummy; //$AUTOCOMPLETEIGNORE$															   \r\n"
-    "};																							   \r\n"
-
-    "struct PALInternal {																	\r\n"
-    "///Loads the colour lookup table for translucency effects. Used by module.			\r\n"
-    "import static int LoadCLUT (int slot);// $AUTOCOMPLETESTATICONLY$					\r\n"
-    "///Cycles the internal palette structure of the plugin. Internal use only.			\r\n"
-    "import static void CycleRemap (int start, int end);// $AUTOCOMPLETESTATICONLY$		\r\n"
-    "///Resets the remap array.															\r\n"
-    "import static void ResetRemapping ();				// $AUTOCOMPLETESTATICONLY$		\r\n"
-    "///Gets the closest palette slot from 16 bit colour space.							\r\n"
-    "import static char GetColor565 (char r,char g,char b);// $AUTOCOMPLETESTATICONLY$	\r\n"
-    "///Returns the true location of a remapped colour.									\r\n"
-    "import static char GetRemappedSlot (char slot);//$AUTOCOMPLETESTATICONLY$			\r\n"
-    "///Gets the luminosity of the palette slot.											\r\n"
-    "import static int GetLuminosityFromPalette (int slot);// $AUTOCOMPLETESTATICONLY$	\r\n"
-    "///Polynomial Sine Approximation.													\r\n"
-    "import static float FastSin (float x);// $AUTOCOMPLETESTATICONLY$					\r\n"
-    "///Polynomial Cosine Approximation.													\r\n"
-    "import static float FastCos (float x);// $AUTOCOMPLETESTATICONLY$					\r\n"
-    "///Ludicrously Fast Integer Root (0-0xFFFF)											\r\n"
-    "import static int FastRoot(int x);	 // $AUTOCOMPLETESTATICONLY$					\r\n"
-    "import static int GetModifiedBackgroundImage ();	//$AUTOCOMPLETEIGNORE$				\r\n"
-    "import static void WriteObjectivePalette (char index,char r,char b, char g);			\r\n"
-    "import static int ReadObjectivePaletteR (char index);								\r\n"
-    "import static int ReadObjectivePaletteB (char index);								\r\n"
-    "import static int ReadObjectivePaletteG (char index);								\r\n"
-    "int dummy; //$AUTOCOMPLETEIGNORE$													\r\n"
-    "};																					\r\n"
-
-    "struct Translucence {																																	 \r\n"
-    "///Creates a translucent overlay. level=0: Background,level=1: Below GUIs,level=2:Above GUIs. blendmode=0: Alpha, blendmode=1: Additive			 		 \r\n"
-    "import static int CreateOverlay (int id, int sprite, int alpha, int level, int ox, int oy,int mask=0,BlendingMode blendmode=0);// $AUTOCOMPLETESTATICONLY$\r\n"
-    "///Deletes translucent overlay.																															 \r\n"
-    "import static int DeleteOverlay (int id);// $AUTOCOMPLETESTATICONLY$																						 \r\n"
-    "///Moves Translucent Overlay to OX,OY.																													 \r\n"
-    "import static int Move (int id, int ox, int oy);// $AUTOCOMPLETESTATICONLY$																				 \r\n"
-    "///Get X coordinate of translucent overlay.																												 \r\n"
-    "import static int GetOverlayX (int id);// $AUTOCOMPLETESTATICONLY$																						 \r\n"
-    "///Get Y coordinate of translucent overlay.																												 \r\n"
-    "import static int GetOverlayY (int id);// $AUTOCOMPLETESTATICONLY$																						 \r\n"
-    "///Get the sprite slot for translucent overlay id																										 \r\n"
-    "import static int GetOverlaySprite (int id);// $AUTOCOMPLETESTATICONLY$																					 \r\n"
-    "///Get the level the overlay is drawn on currently.																										 \r\n"
-    "import static int GetOverlayLevel (int id);// $AUTOCOMPLETESTATICONLY$																					 \r\n"
-    "///Get whether Translucent Overlay is currently being drawn.																								 \r\n"
-    "import static int GetOverlayEnabled (int id);// $AUTOCOMPLETESTATICONLY$																					 \r\n"
-    "///Get the alpha channel for translucent overlay id. (0-255)																								 \r\n"
-    "import static int GetOverlayAlpha (int id);// $AUTOCOMPLETESTATICONLY$																					 \r\n"
-    "///Set translucent overlay id's alpha. (0-255)																											 \r\n"
-    "import static int SetOverlayAlpha (int id, int alpha);// $AUTOCOMPLETESTATICONLY$																		 \r\n"
-    "///Turn overlay on or off.																																 \r\n"
-    "import static int SetOverlayEnabled (int id, int toggle);// $AUTOCOMPLETESTATICONLY$																		 \r\n"
-    "///Blend bg with fg (fg is changed) together at alpha translevel.																						 \r\n"
-    "import static int DrawTransSprite (int sprite, int bg, int translevel,int mask=0,BlendingMode blendmode=0,ObjectiveMode use_objpal=0);// $AUTOCOMPLETESTATICONLY$ \r\n"
-    "int dummy; //$AUTOCOMPLETEIGNORE$																														 \r\n"
-    "};																																						 \r\n"
-
-    "struct Reflections {																																\r\n"
-    "///Turn reflective floors off or on.																												\r\n"
-    "import static int Set (int toggle);// $AUTOCOMPLETESTATICONLY$																					\r\n"
-    "///Check if reflections are turned on.																											\r\n"
-    "import static int IsReflecting ();// $AUTOCOMPLETESTATICONLY$																					\r\n"
-    "import static void SetCharacterReflected (int id,int refl);// $AUTOCOMPLETESTATICONLY$															\r\n"
-    "import static void SetObjectReflected (int id,int refl);// $AUTOCOMPLETESTATICONLY$																\r\n"
-    "import static int GetCharacterReflected (int id);// $AUTOCOMPLETESTATICONLY$																		\r\n"
-    "import static int GetObjectReflected (int id);// $AUTOCOMPLETESTATICONLY$																		\r\n"
-    "import static void ReplaceCharacterReflectionView (int id,int view);// $AUTOCOMPLETESTATICONLY$													\r\n"
-    "import static void SetObjectReflectionIgnoreScaling (int id,int wb);// $AUTOCOMPLETESTATICONLY$													\r\n"
-    "int dummy; //$AUTOCOMPLETEIGNORE$																												\r\n"
-    "};																																				\r\n"
-
-
-    "struct LensDistort {																																\r\n"
-    "import static void SetPos (int x,int y);															// $AUTOCOMPLETESTATICONLY$						\r\n"
-    "import static int GetX ();																		// $AUTOCOMPLETESTATICONLY$						\r\n"
-    "import static int GetY ();																		// $AUTOCOMPLETESTATICONLY$						\r\n"
-    "import static void Set (int toggle);																// $AUTOCOMPLETESTATICONLY$						\r\n"
-    "import static int IsDrawn ();																	// $AUTOCOMPLETESTATICONLY$						\r\n"
-    "import static void SetOffsetClamp (int clamp);													//$AUTOCOMPLETEIGNORE$							\r\n"
-    "import static int GetOffsetClamp ();																//$AUTOCOMPLETEIGNORE$							\r\n"
-    "import static int GetLevel ();																	// $AUTOCOMPLETESTATICONLY$						\r\n"
-    "import static void SetLevel (int level);															// $AUTOCOMPLETESTATICONLY$						\r\n"
-    "import static void Initialize (int width, int zoom, int lensx,int lensy,LensLevel level,int clamp=-1);	// $AUTOCOMPLETESTATICONLY$				\r\n"
-    "int dummy; //$AUTOCOMPLETEIGNORE$																												\r\n"
-    "};																																				\r\n"
-
-    "struct Plasma {																																	\r\n"
-    "///Set options for plasma generation. 0 = None. 1 = Horizontal Bars (data=width). 2 = Vertical Bars (data=width). 3 = Circle (data=x,data2=y,data3=width). 4 = Diagonal Bars (data=width) \r\n"
-    "import static void SetPlasmaType (int component, PlasmaMixMode type, int data=0, int data2=0, int data3=0);// $AUTOCOMPLETESTATICONLY$						\r\n"
-    "///Set all plasma settings to 0.																													\r\n"
-    "import static void ResetPlasmaSettings ();// $AUTOCOMPLETESTATICONLY$\r\n"
-    "///Draw Plasma into dynamic sprite slot using range palstart-palend. Remember to use SetPlasmaType first!										\r\n"
-    "import static void DrawPlasma (int slot, int palstart, int palend);// $AUTOCOMPLETESTATICONLY$													\r\n"
-    "///Draw fire effect into sprite, and alpha channel into masksprite.																				\r\n"
-    "import static void DoFire (int sprite, int masksprite, int palstart,int palend, int strength, int seed=0,int cutoff=0,int windspeed=0);// $AUTOCOMPLETESTATICONLY$\r\n"
-    "int dummy; //$AUTOCOMPLETEIGNORE$																												\r\n"
-    "import static void SetRootType (PlasmaRootType real);// $AUTOCOMPLETESTATICONLY$															\r\n"
-    "import static int GetRootType ();// $AUTOCOMPLETESTATICONLY$																				\r\n"
-    "};																																				\r\n"
-
-    "struct Starfield {																																\r\n"
-    "import static void Draw (int slot, int maskslot);																								\r\n"
-    "import static void RotateStar (int star, int angle,int px,int py);																				\r\n"
-    "import static void Iterate (int slot);																											\r\n"
-    "import static void Initialize (int slot,int maxstars);																							\r\n"
-    "import static void SetOriginPoint (int x,int y);																									\r\n"
-    "import static float GetStarX (int i);																											\r\n"
-    "import static float GetStarY (int i);																											\r\n"
-    "import static float GetStarZ (int i);																											\r\n"
-    "import static void SetStarPosition (int star,float x,float y,float z);																			\r\n"
-    "import static void SetStarColor (int star, char color);																							\r\n"
-    "import static char GetStarColor (int star);																										\r\n"
-    "import static void SetStarSprite (int star, int slot);																							\r\n"
-    "import static int GetStarSprite (int star);																										\r\n"
-    "import static void SetStarSpriteRange (int start, int end, int slot);																			\r\n"
-    "import static int GetOverscan ();																												\r\n"
-    "import static void SetOverscan (int overscan);																									\r\n"
-    "import static int GetOriginX ();																													\r\n"
-    "import static int GetOriginY ();																													\r\n"
-    "import static void SetDepthMultiplier (int multi);																								\r\n"
-    "import static int GetDepthMultiplier ();																											\r\n"
-    "import static int GetMaxStars ();																												\r\n"
-    "import static void SetStarSpriteScaleBoost (int star,int boost);																					\r\n"
-    "import static int GetStarSpriteScaleBoost (int star);																							\r\n"
-    "import static void SetStarMaxRadius (int star,int radius);																						\r\n"
-    "import static int GetStarMaxRadius (int star);																									\r\n"
-    "int dummy; //$AUTOCOMPLETEIGNORE$																												\r\n"
-    "};																																				\r\n";
-
-const char *AGS_GetPluginName(void) {
-	// Return the plugin description
-	return "PALgorithms Translucent Overlay Renderer";
-}
-
-int  AGS_EditorStartup(IAGSEditor *lpEditor) {
-	// User has checked the plugin to use it in their game
-
-	// If it's an earlier version than what we need, abort.
-	if (lpEditor->version < 1)
-		return -1;
-
-	editor = lpEditor;
-	editor->RegisterScriptHeader(ourScriptHeader);
-
-	// Return 0 to indicate success
-	return 0;
-}
-
-void AGS_EditorShutdown() {
-	// User has un-checked the plugin from their game
-	editor->UnregisterScriptHeader(ourScriptHeader);
-}
-
-#if AGS_PLATFORM_OS_WINDOWS
-void AGS_EditorProperties(HWND parent) {
-	// User has chosen to view the Properties of the plugin
-	// We could load up an options dialog or something here instead
-	MessageBox(parent, "PALgorithms Translucent Overlay Renderer & Other Demo Effects (c) 2015 Scavenger", "About", MB_OK | MB_ICONINFORMATION);
-}
-
-#endif
-
-int AGS_EditorSaveGame(char *buffer, int bufsize) {
-	// We don't want to save any persistent data
-	return 0;
-}
-
-void AGS_EditorLoadGame(char *buffer, int bufsize) {
-	// Nothing to load for this dummy plugin
-}
-
-#endif // #if AGS_PLATFORM_OS_WINDOWS && !defined(BUILTIN_PLUGINS)
-// ******* END DESIGN TIME  *******
-
-
-// ****** RUN TIME ********
-
-IAGSEngine *engine;
-
 void WriteObjectivePalette(unsigned char index, unsigned char r, unsigned char b, unsigned char g) {
 	objectivepal[index].r = r;
 	objectivepal[index].b = b;
@@ -534,7 +202,7 @@ unsigned short root(unsigned short x) {
 }
 
 
-inline float Hill(float x) {
+float Hill(float x) {
 	const float a0 = 1.0f;
 	const float a2 = 2.0f / PI - 12.0f / (pisquared);
 	const float a3 = 16.0f / (picubed) - 4.0f / (pisquared);
@@ -585,7 +253,7 @@ void DrawLens(int ox, int oy) {
 	BITMAP *virtsc = engine->GetVirtualScreen();
 	if (!virtsc) engine->AbortGame("DrawLens: Cannot get virtual screen.");
 	BITMAP *lenswrite = engine->CreateBlankBitmap(LensOption.lenswidth, LensOption.lenswidth, 8);
-	unsigned char **screen = engine->GetRawBitmapSurface(virtsc);
+	unsigned char **vScreen = engine->GetRawBitmapSurface(virtsc);
 	unsigned char **lensarray = engine->GetRawBitmapSurface(lenswrite);
 	int radius = LensOption.lenswidth >> 1;
 	for (int y = 0; y < LensOption.lenswidth; y++) {
@@ -595,8 +263,8 @@ void DrawLens(int ox, int oy) {
 			int coffx = lens[lenspos].xoffset;
 			int coffy = lens[lenspos].yoffset;
 			if (oy + coffy > 0 && oy + coffy < sh && ox + coffx > 0 && ox + coffx < sw) {
-				lensarray[y][x] = screen[oy + coffy][ox + coffx];
-				//screen[oy+coffy][ox+coffx] = abs(coffy);
+				lensarray[y][x] = vScreen[oy + coffy][ox + coffx];
+				//vScreen[oy+coffy][ox+coffx] = ABS(coffy);
 			}
 		}
 	}
@@ -608,7 +276,7 @@ void DrawLens(int ox, int oy) {
 	    {
 	        if (oy+y > 0 && oy+y < sh && ox+x > 0 && ox+x < sw)
 	        {
-	            screen[oy+y][ox+x] = lensarray[y][x];
+	            vScreen[oy+y][ox+x] = lensarray[y][x];
 	        }
 	    }
 	}
@@ -622,7 +290,7 @@ void DrawLens(int ox, int oy) {
 			int dy = cy + oy;
 			if ((cxsq + cysq <= radsq) && dx < sw && dx >= 0 && dy < sh && dy >= 0 && cy + radius < LensOption.lenswidth - 1 && cx + radius < LensOption.lenswidth - 1) {
 				//if (cy+radius < 0 || cx+radius < 0) engine->AbortGame ("I did something wrong");
-				screen[dy][dx] = lensarray[cy + radius][cx + radius];
+				vScreen[dy][dx] = lensarray[cy + radius][cx + radius];
 			}
 		}
 	}
@@ -810,9 +478,9 @@ void DrawPlasma(int slot, int palstart, int palend) {
 	engine->NotifySpriteUpdated(slot);
 }
 
-void DoFire(int sprite, int masksprite, int palstart, int palend, int strength, int seed, int cutoff, int windspeed) {
+void DoFire(int spriteId, int masksprite, int palstart, int palend, int strength, int seed, int cutoff, int windspeed) {
 	BITMAP *firespr = engine->GetSpriteGraphic(masksprite);
-	BITMAP *firecolorspr = engine->GetSpriteGraphic(sprite);
+	BITMAP *firecolorspr = engine->GetSpriteGraphic(spriteId);
 	BITMAP *seedspr;
 	int32 w, h = 0;
 	int range, basecol, dir = 0;
@@ -832,25 +500,31 @@ void DoFire(int sprite, int masksprite, int palstart, int palend, int strength,
 	int sparky = 0;
 	//srand(time(NULL));
 	for (int y = 0; y < h - 1; y++) {
-		if (rand() % 10 > 7 - windspeed) { //Wind right
+		if ((int)::AGS::g_vm->getRandomNumber(9) > 7 - windspeed) { //Wind right
 			for (int x = w - 1; x > 1; x--) {
 				fire[y][x] = fire[y][x - 1];
 			}
-		} else if (rand() % 10 > 7 + windspeed) { // wind left
+		} else if ((int)::AGS::g_vm->getRandomNumber(9) > 7 + windspeed) { // wind left
 			for (int x = 0; x < w - 1; x++) {
 				fire[y][x] = fire[y][x + 1];
 			}
 		}
 	}
 	for (int x = 0; x < w; x++) {
-		sparky = abs(rand() % (h - 2));
-		if (sparky < h && sparky > 0 && fire[h - sparky][x] > cutoff && abs(rand() % 10) > 7) fire[h - sparky][x] = 255;
-		sparky = abs(rand() % (h - 2));
-		if (sparky < h && sparky > 0 && fire[h - sparky][x] > cutoff && abs(rand() % 10) > 7) fire[h - sparky][x] = 0;
+		sparky = ABS((int)::AGS::g_vm->getRandomNumber(0x7fffffff) % (h - 2));
+		if (sparky < h && sparky > 0 && fire[h - sparky][x] > cutoff &&
+				ABS((int)::AGS::g_vm->getRandomNumber(0x7fffffff) % 10) > 7)
+			fire[h - sparky][x] = 255;
+		sparky = ABS((int)::AGS::g_vm->getRandomNumber(0x7fffffff) % (h - 2));
+		if (sparky < h && sparky > 0 && fire[h - sparky][x] > cutoff &&
+				ABS((int)::AGS::g_vm->getRandomNumber(0x7fffffff) % 10) > 7)
+			fire[h - sparky][x] = 0;
 	}
 	if (seed == 0) {
-		for (int x = 0; x < w; x++) fire[h - 1][x] = 255;
-		for (int x = 0; x < w; x++) fire[h - 2][x] = abs(32768 + rand()) % 256;
+		for (int x = 0; x < w; x++)
+			fire[h - 1][x] = 255;
+		for (int x = 0; x < w; x++)
+			fire[h - 2][x] = ::AGS::g_vm->getRandomNumber(255);
 	} else if (seed > 0) {
 		seedspr = engine->GetSpriteGraphic(seed);
 		BITMAP *virtsc = engine->GetVirtualScreen();
@@ -859,7 +533,7 @@ void DoFire(int sprite, int masksprite, int palstart, int palend, int strength,
 		engine->SetVirtualScreen(virtsc);
 		engine->ReleaseBitmapSurface(virtsc);
 		engine->ReleaseBitmapSurface(seedspr);
-		engine->NotifySpriteUpdated(sprite);
+		engine->NotifySpriteUpdated(spriteId);
 		engine->NotifySpriteUpdated(masksprite);
 	}
 
@@ -878,7 +552,7 @@ void DoFire(int sprite, int masksprite, int palstart, int palend, int strength,
 	}
 	engine->ReleaseBitmapSurface(firespr);
 	engine->ReleaseBitmapSurface(firecolorspr);
-	engine->NotifySpriteUpdated(sprite);
+	engine->NotifySpriteUpdated(spriteId);
 	engine->NotifySpriteUpdated(masksprite);
 }
 
@@ -1025,14 +699,14 @@ void InitializeStars(int slot, int maxstars) {
 	Starfield.overscan = 20;
 	stars = new starstype [Starfield.maxstars];
 	for (int i = 0; i < Starfield.maxstars; i++) {
-		stars[i].x = (float)((rand() % sw) << 1) - sw;
+		stars[i].x = (float)((::AGS::g_vm->getRandomNumber(0x7fffffff) % sw) << 1) - sw;
 		if (stars[i].x < 1.0 && stars[i].x > -1.0) stars[i].x = (float)sw;
-		stars[i].y = (float)((rand() % sh) << 1) - sh;
+		stars[i].y = (float)((::AGS::g_vm->getRandomNumber(0x7fffffff) % sh) << 1) - sh;
 		if (stars[i].y < 1.0 && stars[i].y > -1.0) stars[i].y = (float)sh;
 		stars[i].z = (float)(MAX_DEPTH);
-		stars[i].color = (rand() % 240);
+		stars[i].color = (::AGS::g_vm->getRandomNumber(0x7fffffff) % 240);
 		stars[i].sprite = 0;
-		stars[i].maxrad = (rand() % 5);
+		stars[i].maxrad = (::AGS::g_vm->getRandomNumber(0x7fffffff) % 5);
 	}
 }
 
@@ -1047,9 +721,9 @@ void IterateStars(int slot) {
 		int px = static_cast<int>(stars[i].x * k + Starfield.originx);
 		int py = static_cast<int>(stars[i].y * k + Starfield.originy);
 		if (px >= sw + Starfield.overscan || px < 0 - Starfield.overscan || py >= sh + Starfield.overscan || py < 0 - Starfield.overscan) {
-			stars[i].x = (float)((rand() % sw) << 1) - sw;
+			stars[i].x = (float)((::AGS::g_vm->getRandomNumber(0x7fffffff) % sw) << 1) - sw;
 			if (stars[i].x < 1.0 && stars[i].x > -1.0) stars[i].x = (float)sw;
-			stars[i].y = (float)((rand() % sh) << 1) - sh;
+			stars[i].y = (float)((::AGS::g_vm->getRandomNumber(0x7fffffff) % sh) << 1) - sh;
 			if (stars[i].y < 1.0 && stars[i].y > 1.0) stars[i].y = (float)sh;
 			stars[i].z = (float)MAX_DEPTH;
 			//stars[i].color = (rand () %240);
@@ -1180,9 +854,9 @@ void DrawStars(int slot, int maskslot) {
 		int px = static_cast<int>(stars[i].x * k + Starfield.originx);
 		int py = static_cast<int>(stars[i].y * k + Starfield.originy);
 		if (px >= sw + Starfield.overscan || px < 0 - Starfield.overscan || py >= sh + Starfield.overscan || py < 0 - Starfield.overscan) {
-			stars[i].x = (float)((rand() % sw) << 1) - sw;
+			stars[i].x = (float)((::AGS::g_vm->getRandomNumber(0x7fffffff) % sw) << 1) - sw;
 			if (stars[i].x < 1.0 && stars[i].x > -1.0) stars[i].x = (float)sw;
-			stars[i].y = (float)((rand() % sh) << 1) - sh;
+			stars[i].y = (float)((::AGS::g_vm->getRandomNumber(0x7fffffff) % sh) << 1) - sh;
 			if (stars[i].y < 1.0 && stars[i].y > 1.0) stars[i].y = (float)sh;
 			stars[i].z = (float)MAX_DEPTH;
 			//stars[i].color = (rand () %240);
@@ -1265,9 +939,9 @@ void DrawStars(int slot, int maskslot) {
 				int x2, y2 ;
 				int ox = px - (w2 >> 1);
 				int oy = py - (h2 >> 1);
-				for (int i = 0; i < h2; i++) {
-					int temprzy = i * y_ratio;
-					int ey = oy + i;
+				for (int ii = 0; ii < h2; ii++) {
+					int temprzy = ii * y_ratio;
+					int ey = oy + ii;
 					for (int j = 0; j < w2; j++) {
 						x2 = ((j * x_ratio) >> 16);
 						y2 = ((temprzy) >> 16);
@@ -1278,7 +952,7 @@ void DrawStars(int slot, int maskslot) {
 								screenarray [ey][ex] = orig[y2][x2];
 							}
 						}
-						//resized [i][j] = orig [y2][x2];
+						//resized [ii][j] = orig [y2][x2];
 					}
 				}
 				engine->ReleaseBitmapSurface(origspr);
@@ -1338,14 +1012,13 @@ void DrawStars(int slot, int maskslot) {
 }
 
 
-int CreateTranslucentOverlay(int id, int sprite, int alpha, int level, int ox, int oy, int mask = 0, int blendmode = 0) {
-
-	BITMAP *testspr = engine->GetSpriteGraphic(sprite);
-	if (testspr) overlay[id].sprite = sprite;
-	else engine->AbortGame("CreateTranslucentOverlay: Invalid sprite.");
+int CreateTranslucentOverlay(int id, int spriteId, int alpha, int level, int ox, int oy, int mask = 0, int blendmode = 0) {
+	BITMAP *testspr = engine->GetSpriteGraphic(spriteId);
+	if (testspr) overlay[id].sprite = spriteId;
+	else engine->AbortGame("CreateTranslucentOverlay: Invalid spriteId.");
 	engine->ReleaseBitmapSurface(testspr);
-	overlay[id].level = std::max(0, std::min(level, 4));
-	overlay[id].trans = std::max(0, std::min(alpha, 255));
+	overlay[id].level = MAX(0, MIN(level, 4));
+	overlay[id].trans = MAX(0, MIN(alpha, 255));
 	overlay[id].spritemask = mask;
 	overlay[id].x = ox;
 	overlay[id].y = oy;
@@ -1523,8 +1196,8 @@ int DrawReflections(int id, int charobj = 0) {
 	engine->RoomToViewport(&ox, &oy);
 	int yoffset = 0;
 	int translevel = 7;
-	bool dither = false;
-	bool dodither = false;
+	//bool dither = false;
+	//bool dodither = false;
 	int counter = 0;
 	int rowcount = 101 - (int)(50.0 * ((double)(scale) / 100.0));
 	int delay = screenh / rowcount;
@@ -1591,7 +1264,7 @@ int DrawReflections(int id, int charobj = 0) {
 }
 
 
-int DrawTransSprite(int sprite, int bg, int translevel, int mask = 0, int blendmode = 0, int use_objpal = 0) {
+int DrawTransSprite(int spriteId, int bg, int translevel, int mask = 0, int blendmode = 0, int use_objpal = 0) {
 	BITMAP *maskspr = nullptr;
 	unsigned char **maskarray;
 	if (mask > 0) maskspr = engine->GetSpriteGraphic(mask);
@@ -1604,10 +1277,10 @@ int DrawTransSprite(int sprite, int bg, int translevel, int mask = 0, int blendm
 	// Get a reference to the screen we'll draw onto
 	BITMAP *bgspr = engine->GetSpriteGraphic(bg);
 	//BITMAP *clutspr = engine->GetSpriteGraphic (clutslot);
-	BITMAP *spritespr = engine->GetSpriteGraphic(sprite);
+	BITMAP *spritespr = engine->GetSpriteGraphic(spriteId);
 	if (!bgspr) engine->AbortGame("DrawTransSprite: Can't load background");
-	//if (!clutspr) engine->AbortGame ("Can't load CLUT sprite into memory.");
-	if (!spritespr) engine->AbortGame("DrawTransSprite: Can't load overlay sprite into memory.");
+	//if (!clutspr) engine->AbortGame ("Can't load CLUT spriteId into memory.");
+	if (!spritespr) engine->AbortGame("DrawTransSprite: Can't load overlay spriteId into memory.");
 	// Get its surface
 	int32 sprw, sprh, coldepth;
 	int32 bgw, bgh;
@@ -1624,9 +1297,9 @@ int DrawTransSprite(int sprite, int bg, int translevel, int mask = 0, int blendm
 	//int transamount = 256 * translevel; //old
 	while (y < sprh) {
 		while (x < sprw) {
-			if (spritearray [y][x] != 0 && y < bgh && x < bgw && y >= 0 && x >= 0) { // If the sprite isn't transparent, and isn't drawn off the edge of the bg.
+			if (spritearray [y][x] != 0 && y < bgh && x < bgw && y >= 0 && x >= 0) { // If the spriteId isn't transparent, and isn't drawn off the edge of the bg.
 				if (mask > 0) {
-					translevel = std::max(maskarray [y][x] - tloffset, 0);
+					translevel = MAX(maskarray [y][x] - tloffset, 0);
 				}
 				//spritearray[y][x] = cycle_remap[clutarray [cycle_remap[bgarray[y][x]]+transamount][cycle_remap[spritearray [y][x]]]]; //old
 				if (blendmode == 0) spritearray[y][x] = Mix::MixColorAlpha(spritearray [y][x], bgarray[y][x], translevel, use_objpal);
@@ -1642,22 +1315,22 @@ int DrawTransSprite(int sprite, int bg, int translevel, int mask = 0, int blendm
 	engine->ReleaseBitmapSurface(bgspr);
 	//engine->ReleaseBitmapSurface (clutspr);
 	engine->ReleaseBitmapSurface(spritespr);
-	engine->NotifySpriteUpdated(sprite);
+	engine->NotifySpriteUpdated(spriteId);
 	return 0;
 }
 
-int DrawTranslucentOverlay(int sprite, int translevel, int ox, int oy, int mask = 0, int blendmode = 0) {
+int DrawTranslucentOverlay(int spriteId, int translevel, int ox, int oy, int mask = 0, int blendmode = 0) {
 	if (translevel == 0) return 0;
 	BITMAP *maskspr;
 	unsigned char **maskarray;
 	// Get a reference to the screen we'll draw onto
 	BITMAP *virtsc = engine->GetVirtualScreen();
 	//BITMAP *clutspr = engine->GetSpriteGraphic (clutslot);
-	BITMAP *spritespr = engine->GetSpriteGraphic(sprite);
+	BITMAP *spritespr = engine->GetSpriteGraphic(spriteId);
 	if (mask > 0) maskspr = engine->GetSpriteGraphic(mask);
 	if (!virtsc) engine->AbortGame("DrawTranslucentOverlay: Can't load virtual screen.");
-	//if (!clutspr) engine->AbortGame ("Can't load CLUT sprite into memory.");
-	if (!spritespr) engine->AbortGame("DrawTranslucentOverlay: Can't load overlay sprite into memory.");
+	//if (!clutspr) engine->AbortGame ("Can't load CLUT spriteId into memory.");
+	if (!spritespr) engine->AbortGame("DrawTranslucentOverlay: Can't load overlay spriteId into memory.");
 	// Get its surface
 	int32 sprw, sprh, coldepth;
 	int32 screenw, screenh;
@@ -1679,10 +1352,10 @@ int DrawTranslucentOverlay(int sprite, int translevel, int ox, int oy, int mask
 	//int transamount = 256 * translevel; //old
 	while (y < sprh) {
 		while (x < sprw) {
-			if (spritearray [y][x] != 0 && y + oy < screenh && x + ox < screenw && y + oy >= 0 && x + ox >= 0) { // If the sprite isn't transparent, and isn't drawn off the edge of the screen.
+			if (spritearray [y][x] != 0 && y + oy < screenh && x + ox < screenw && y + oy >= 0 && x + ox >= 0) { // If the spriteId isn't transparent, and isn't drawn off the edge of the screen.
 				//charbuffer[y+oy][x+ox] = cycle_remap[clutarray [cycle_remap[charbuffer[y+oy][x+ox]]+transamount][cycle_remap[spritearray [y][x]]]]; //old
 				if (mask > 0) {
-					translevel = std::max(maskarray [y][x] - tloffset, 0);
+					translevel = MAX(maskarray [y][x] - tloffset, 0);
 				}
 				if (blendmode == 0) {
 					if (translevel == 255) {
@@ -1706,10 +1379,24 @@ int DrawTranslucentOverlay(int sprite, int translevel, int ox, int oy, int mask
 	engine->ReleaseBitmapSurface(spritespr);
 	if (mask > 0) engine->ReleaseBitmapSurface(maskspr);
 	engine->MarkRegionDirty(ox, oy, dirtywidth, dirtyheight);
+
 	return 0;
 }
 
-void AGS_EngineStartup(IAGSEngine *lpEngine) {
+/*------------------------------------------------------------------*/
+
+AGSPalRender::AGSPalRender() : DLL() {
+	DLL_METHOD(AGS_GetPluginName);
+	DLL_METHOD(AGS_EngineStartup);
+	DLL_METHOD(AGS_EngineShutdown);
+	DLL_METHOD(AGS_EngineOnEvent);
+}
+
+const char *AGSPalRender::AGS_GetPluginName() {
+	return "PALgorithms Translucent Overlay Renderer";
+}
+
+void AGSPalRender::AGS_EngineStartup(IAGSEngine *lpEngine) {
 	engine = lpEngine;
 
 	// Make sure it's got the version with the features we need
@@ -1901,16 +1588,15 @@ void AGS_EngineStartup(IAGSEngine *lpEngine) {
 	Init_Raycaster();
 }
 
-void AGS_EngineShutdown() {
+void AGSPalRender::AGS_EngineShutdown() {
 	// no work to do here - but if we had created any dynamic sprites,
 	// we should delete them here
-	delete [] Reflection.Characters;
-	delete [] Reflection.Objects;
-	//QuitCleanup ();
+	delete[] Reflection.Characters;
+	delete[] Reflection.Objects;
+	//QuitCleanup();
 }
 
-
-int AGS_EngineOnEvent(int event, int data) {
+int AGSPalRender::AGS_EngineOnEvent(int event, int data) {
 	if (event == AGSE_PRESCREENDRAW && clutslot > 0) {
 		if (drawreflections) {
 			int32 sh, sw = 0;
@@ -2152,13 +1838,6 @@ int AGS_EngineOnEvent(int event, int data) {
 	return 0;
 }
 
-int AGS_EngineDebugHook(const char *scriptName, int lineNum, int reserved) {
-	return 0;
-}
-void AGS_EngineInitGfx(const char *driverID, void *data) {}
-
-// *** END RUN TIME ****
-
-#if defined(BUILTIN_PLUGINS)
-} // namespace agspalrender
-#endif
+} // namespace AGSPalRender
+} // namespace Plugins
+} // namespace AGS3
diff --git a/engines/ags/plugins/ags_pal_render/ags_pal_render.h b/engines/ags/plugins/ags_pal_render/ags_pal_render.h
index 61063daf90..bf3247852a 100644
--- a/engines/ags/plugins/ags_pal_render/ags_pal_render.h
+++ b/engines/ags/plugins/ags_pal_render/ags_pal_render.h
@@ -1,14 +1,47 @@
-#ifndef AGS_TOUCH_H
-#define AGS_TOUCH_H
+/* 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 "plugin/agsplugin.h"
+#ifndef AGS_PLUGINS_AGS_PAL_RENDER_AGS_PAL_RENDER_H
+#define AGS_PLUGINS_AGS_PAL_RENDER_AGS_PAL_RENDER_H
 
-namespace agspalrender {
-void AGS_EngineStartup(IAGSEngine *lpEngine);
-void AGS_EngineShutdown();
-int AGS_EngineOnEvent(int event, int data);
-int AGS_EngineDebugHook(const char *scriptName, int lineNum, int reserved);
-void AGS_EngineInitGfx(const char *driverID, void *data);
-}
+#include "ags/plugins/dll.h"
 
-#endif
\ No newline at end of file
+namespace AGS3 {
+namespace Plugins {
+namespace AGSPalRender {
+
+class AGSPalRender : public DLL {
+private:
+	static const char *AGS_GetPluginName();
+	static void AGS_EngineStartup(IAGSEngine *lpEngine);
+	static void AGS_EngineShutdown();
+	static int AGS_EngineOnEvent(int event, int data);
+
+public:
+	AGSPalRender();
+};
+
+} // namespace AGSPalRender
+} // namespace Plugins
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/plugins/ags_pal_render/agsplugin.h b/engines/ags/plugins/ags_pal_render/agsplugin.h
deleted file mode 100644
index f9fd46e6ed..0000000000
--- a/engines/ags/plugins/ags_pal_render/agsplugin.h
+++ /dev/null
@@ -1,564 +0,0 @@
-//=============================================================================
-//
-// Adventure Game Studio (AGS)
-//
-// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
-// The full list of copyright holders can be found in the Copyright.txt
-// file, which is part of this source code distribution.
-//
-// The AGS source code is provided under the Artistic License 2.0.
-// A copy of this license can be found in the file License.txt and at
-// http://www.opensource.org/licenses/artistic-license-2.0.php
-//
-//=============================================================================
-//
-// AGS Plugin interface header file
-//
-// #define THIS_IS_THE_PLUGIN beforehand if including from the plugin
-//
-//=============================================================================
-
-#ifndef _AGS_PLUGIN_H
-#define _AGS_PLUGIN_H
-
-// If the plugin isn't using DDraw, don't require the headers
-#ifndef DIRECTDRAW_VERSION
-typedef void *LPDIRECTDRAW2;
-typedef void *LPDIRECTDRAWSURFACE2;
-#endif
-
-#ifndef DIRECTSOUND_VERSION
-typedef void *LPDIRECTSOUND;
-#endif
-
-#ifndef DIRECTINPUT_VERSION
-typedef void *LPDIRECTINPUTDEVICE;
-#endif
-
-// If the user isn't using Allegro or WinGDI, define the BITMAP into something
-#if !defined(ALLEGRO_H) && !defined(_WINGDI_) && !defined(BITMAP_DEFINED)
-typedef char BITMAP;
-#endif
-
-// If not using windows.h, define HWND
-#if !defined(_WINDOWS_) && !defined(HWND)
-typedef int HWND;
-#endif
-
-// This file is distributed as part of the Plugin API docs, so
-// ensure that WINDOWS_VERSION is defined (if applicable)
-#if defined(_WINDOWS_) || defined(_WIN32)
-#ifndef WINDOWS_VERSION
-#define WINDOWS_VERSION
-#endif
-#endif
-
-// DOS engine doesn't know about stdcall / neither does Linux version
-#if !defined (WINDOWS_VERSION)
-#define __stdcall
-#endif
-
-#ifndef int32
-#define int32 int
-#endif
-
-#define AGSIFUNC(type) virtual type __stdcall
-
-#define MASK_WALKABLE   1
-#define MASK_WALKBEHIND 2
-#define MASK_HOTSPOT    3
-// MASK_REGIONS is interface version 11 and above only
-#define MASK_REGIONS    4
-
-// **** WARNING: DO NOT ALTER THESE CLASSES IN ANY WAY!
-// **** CHANGING THE ORDER OF THE FUNCTIONS OR ADDING ANY VARIABLES
-// **** WILL CRASH THE SYSTEM.
-
-struct AGSColor {
-	unsigned char r, g, b;
-	unsigned char padding;
-};
-
-struct AGSGameOptions {
-	int32 score;      // player's current score
-	int32 usedmode;   // set by ProcessClick to last cursor mode used
-	int32 disabled_user_interface;  // >0 while in cutscene/etc
-	int32 gscript_timer;    // obsolete
-	int32 debug_mode;       // whether we're in debug mode
-	int32 globalvars[50];   // obsolete
-	int32 messagetime;      // time left for auto-remove messages
-	int32 usedinv;          // inventory item last used
-	int32 inv_top, inv_numdisp, inv_numorder, inv_numinline;
-	int32 text_speed;       // how quickly text is removed
-	int32 sierra_inv_color; // background used to paint defualt inv window
-	int32 talkanim_speed;   // animation speed of talking anims
-	int32 inv_item_wid, inv_item_hit; // set by SetInvDimensions
-	int32 speech_text_shadow;         // colour of outline fonts (default black)
-	int32 swap_portrait_side;         // sierra-style speech swap sides
-	int32 speech_textwindow_gui;      // textwindow used for sierra-style speech
-	int32 follow_change_room_timer;   // delay before moving following characters into new room
-	int32 totalscore;           // maximum possible score
-	int32 skip_display;         // how the user can skip normal Display windows
-	int32 no_multiloop_repeat;  // for backwards compatibility
-	int32 roomscript_finished;  // on_call finished in room
-	int32 used_inv_on;          // inv item they clicked on
-	int32 no_textbg_when_voice; // no textwindow bgrnd when voice speech is used
-	int32 max_dialogoption_width; // max width of dialog options text window
-	int32 no_hicolor_fadein;      // fade out but instant in for hi-color
-	int32 bgspeech_game_speed;    // is background speech relative to game speed
-	int32 bgspeech_stay_on_display; // whether to remove bg speech when DisplaySpeech is used
-	int32 unfactor_speech_from_textlength; // remove "&10" when calculating time for text to stay
-	int32 mp3_loop_before_end;    // loop this time before end of track (ms)
-	int32 speech_music_drop;      // how much to drop music volume by when speech is played
-	int32 in_cutscene;            // we are between a StartCutscene and EndCutscene
-	int32 fast_forward;           // player has elected to skip cutscene
-	int32 room_width;      // width of current room (320-res co-ordinates)
-	int32 room_height;     // height of current room (320-res co-ordinates)
-};
-
-// AGSCharacter.flags
-#define CHF_NOSCALING       1
-#define CHF_FIXVIEW         2     // between SetCharView and ReleaseCharView
-#define CHF_NOINTERACT      4
-#define CHF_NODIAGONAL      8
-#define CHF_ALWAYSIDLE      0x10
-#define CHF_NOLIGHTING      0x20
-#define CHF_NOTURNING       0x40
-#define CHF_NOWALKBEHINDS   0x80
-
-struct AGSCharacter {
-	int32 defview;
-	int32 talkview;
-	int32 view;
-	int32 room, prevroom;
-	int32 x, y, wait;
-	int32 flags;
-	short following;
-	short followinfo;
-	int32 idleview;           // the loop will be randomly picked
-	short idletime, idleleft; // num seconds idle before playing anim
-	short transparency;       // if character is transparent
-	short baseline;
-	int32 activeinv;
-	int32 talkcolor;
-	int32 thinkview;
-	int32 reserved[2];
-	short walkspeed_y, pic_yoffs;
-	int32 z;
-	int32 reserved2[5];
-	short loop, frame;
-	short walking, animating;
-	short walkspeed, animspeed;
-	short inv[301];
-	short actx, acty;
-	char  name[40];
-	char  scrname[20];
-	char  on;
-};
-
-// AGSObject.flags
-#define OBJF_NOINTERACT 1     // not clickable
-#define OBJF_NOWALKBEHINDS 2  // ignore walk-behinds
-
-struct AGSObject {
-	int32 x, y;
-	int32 transparent;    // current transparency setting
-	int32 reserved[4];
-	short num;            // sprite slot number
-	short baseline;       // <=0 to use Y co-ordinate; >0 for specific baseline
-	short view, loop, frame; // only used to track animation - 'num' holds the current sprite
-	short wait, moving;
-	char  cycling;        // is it currently animating?
-	char  overall_speed;
-	char  on;
-	char  flags;
-};
-
-// AGSViewFrame.flags
-#define FRAF_MIRRORED  1  // flipped left to right
-
-struct AGSViewFrame {
-	int32 pic;            // sprite slot number
-	short xoffs, yoffs;
-	short speed;
-	int32 flags;
-	int32 sound;          // play sound when this frame comes round
-	int32 reserved_for_future[2];
-};
-
-// AGSMouseCursor.flags
-#define MCF_ANIMATEMOVE 1
-#define MCF_DISABLED    2
-#define MCF_STANDARD    4
-#define MCF_ONLYANIMOVERHOTSPOT 8
-
-struct AGSMouseCursor {
-	int32 pic;            // sprite slot number
-	short hotx, hoty;     // x,y hotspot co-ordinates
-	short view;           // view (for animating cursors) or -1
-	char  name[10];       // name of cursor mode
-	char  flags;          // MCF_flags above
-};
-
-// The editor-to-plugin interface
-class IAGSEditor {
-public:
-	int32 version;
-	int32 pluginId;   // used internally, do not touch this
-
-public:
-	// get the HWND of the main editor frame
-	AGSIFUNC(HWND) GetEditorHandle();
-	// get the HWND of the current active window
-	AGSIFUNC(HWND) GetWindowHandle();
-	// add some script to the default header
-	AGSIFUNC(void) RegisterScriptHeader(const char *header);
-	// de-register a script header (pass same pointer as when added)
-	AGSIFUNC(void) UnregisterScriptHeader(const char *header);
-
-};
-
-
-// Below are interface 3 and later
-#define AGSE_KEYPRESS        1
-#define AGSE_MOUSECLICK      2
-#define AGSE_POSTSCREENDRAW  4
-// Below are interface 4 and later
-#define AGSE_PRESCREENDRAW   8
-// Below are interface 5 and later
-#define AGSE_SAVEGAME        0x10
-#define AGSE_RESTOREGAME     0x20
-// Below are interface 6 and later
-#define AGSE_PREGUIDRAW      0x40
-#define AGSE_LEAVEROOM       0x80
-#define AGSE_ENTERROOM       0x100
-#define AGSE_TRANSITIONIN    0x200
-#define AGSE_TRANSITIONOUT   0x400
-// Below are interface 12 and later
-#define AGSE_FINALSCREENDRAW 0x800
-#define AGSE_TRANSLATETEXT  0x1000
-// Below are interface 13 and later
-#define AGSE_SCRIPTDEBUG    0x2000
-#define AGSE_AUDIODECODE    0x4000 // obsolete, no longer supported
-// Below are interface 18 and later
-#define AGSE_SPRITELOAD     0x8000
-// Below are interface 21 and later
-#define AGSE_PRERENDER     0x10000
-// Below are interface 24 and later
-#define AGSE_PRESAVEGAME     0x20000
-#define AGSE_POSTRESTOREGAME 0x40000
-#define AGSE_TOOHIGH         0x80000
-
-// GetFontType font types
-#define FNT_INVALID 0
-#define FNT_SCI     1
-#define FNT_TTF     2
-
-// PlaySoundChannel sound types
-#define PSND_WAVE       1
-#define PSND_MP3STREAM  2
-#define PSND_MP3STATIC  3
-#define PSND_OGGSTREAM  4
-#define PSND_OGGSTATIC  5
-#define PSND_MIDI       6
-#define PSND_MOD        7
-
-class IAGSScriptManagedObject {
-public:
-	// when a ref count reaches 0, this is called with the address
-	// of the object. Return 1 to remove the object from memory, 0 to
-	// leave it
-	virtual int Dispose(const char *address, bool force) = 0;
-	// return the type name of the object
-	virtual const char *GetType() = 0;
-	// serialize the object into BUFFER (which is BUFSIZE bytes)
-	// return number of bytes used
-	virtual int Serialize(const char *address, char *buffer, int bufsize) = 0;
-};
-
-class IAGSManagedObjectReader {
-public:
-	virtual void Unserialize(int key, const char *serializedData, int dataSize) = 0;
-};
-
-class IAGSFontRenderer {
-public:
-	virtual bool LoadFromDisk(int fontNumber, int fontSize) = 0;
-	virtual void FreeMemory(int fontNumber) = 0;
-	virtual bool SupportsExtendedCharacters(int fontNumber) = 0;
-	virtual int GetTextWidth(const char *text, int fontNumber) = 0;
-	virtual int GetTextHeight(const char *text, int fontNumber) = 0;
-	virtual void RenderText(const char *text, int fontNumber, BITMAP *destination, int x, int y, int colour) = 0;
-	virtual void AdjustYCoordinateForFont(int *ycoord, int fontNumber) = 0;
-	virtual void EnsureTextValidForFont(char *text, int fontNumber) = 0;
-};
-
-// The plugin-to-engine interface
-class IAGSEngine {
-public:
-	int32 version;
-	int32 pluginId;   // used internally, do not touch
-
-public:
-	// quit the game
-	AGSIFUNC(void) AbortGame(const char *reason);
-	// get engine version
-	AGSIFUNC(const char *) GetEngineVersion();
-	// register a script function with the system
-	AGSIFUNC(void) RegisterScriptFunction(const char *name, void *address);
-#ifdef WINDOWS_VERSION
-	// get game window handle
-	AGSIFUNC(HWND) GetWindowHandle();
-	// get reference to main DirectDraw interface
-	AGSIFUNC(LPDIRECTDRAW2) GetDirectDraw2();
-	// get the DDraw surface associated with a bitmap
-	AGSIFUNC(LPDIRECTDRAWSURFACE2) GetBitmapSurface(BITMAP *);
-#endif
-	// get a reference to the screen bitmap
-	AGSIFUNC(BITMAP *) GetScreen();
-
-	// *** BELOW ARE INTERFACE VERSION 2 AND ABOVE ONLY
-	// ask the engine to call back when a certain event happens
-	AGSIFUNC(void) RequestEventHook(int32 event);
-	// get the options data saved in the editor
-	AGSIFUNC(int)  GetSavedData(char *buffer, int32 bufsize);
-
-	// *** BELOW ARE INTERFACE VERSION 3 AND ABOVE ONLY
-	// get the virtual screen
-	AGSIFUNC(BITMAP *) GetVirtualScreen();
-	// write text to the screen in the specified font and colour
-	AGSIFUNC(void) DrawText(int32 x, int32 y, int32 font, int32 color, char *text);
-	// get screen dimensions
-	AGSIFUNC(void) GetScreenDimensions(int32 *width, int32 *height, int32 *coldepth);
-	// get screen surface to draw on
-	AGSIFUNC(unsigned char **) GetRawBitmapSurface(BITMAP *);
-	// release the surface
-	AGSIFUNC(void) ReleaseBitmapSurface(BITMAP *);
-	// get the current mouse co-ordinates
-	AGSIFUNC(void) GetMousePosition(int32 *x, int32 *y);
-
-	// *** BELOW ARE INTERFACE VERSION 4 AND ABOVE ONLY
-	// get the current room number
-	AGSIFUNC(int)  GetCurrentRoom();
-	// get the number of background scenes in this room
-	AGSIFUNC(int)  GetNumBackgrounds();
-	// get the current background frame
-	AGSIFUNC(int)  GetCurrentBackground();
-	// get a background scene bitmap
-	AGSIFUNC(BITMAP *) GetBackgroundScene(int32);
-	// get dimensions of a bitmap
-	AGSIFUNC(void) GetBitmapDimensions(BITMAP *bmp, int32 *width, int32 *height, int32 *coldepth);
-
-	// *** BELOW ARE INTERFACE VERSION 5 AND ABOVE ONLY
-	// similar to fwrite - buffer, size, filehandle
-	AGSIFUNC(int)  FWrite(void *, int32, int32);
-	// similar to fread - buffer, size, filehandle
-	AGSIFUNC(int)  FRead(void *, int32, int32);
-	// print text, wrapping as usual
-	AGSIFUNC(void) DrawTextWrapped(int32 x, int32 y, int32 width, int32 font, int32 color, const char *text);
-	// set the current active 'screen'
-	AGSIFUNC(void) SetVirtualScreen(BITMAP *);
-	// look up a word in the parser dictionary
-	AGSIFUNC(int)  LookupParserWord(const char *word);
-	// draw a bitmap to the active screen
-	AGSIFUNC(void) BlitBitmap(int32 x, int32 y, BITMAP *, int32 masked);
-	// update the mouse and music
-	AGSIFUNC(void) PollSystem();
-
-	// *** BELOW ARE INTERFACE VERSION 6 AND ABOVE ONLY
-	// get number of characters in game
-	AGSIFUNC(int)  GetNumCharacters();
-	// get reference to specified character struct
-	AGSIFUNC(AGSCharacter *) GetCharacter(int32);
-	// get reference to game struct
-	AGSIFUNC(AGSGameOptions *) GetGameOptions();
-	// get reference to current palette
-	AGSIFUNC(AGSColor *) GetPalette();
-	// update palette
-	AGSIFUNC(void) SetPalette(int32 start, int32 finish, AGSColor *);
-
-	// *** BELOW ARE INTERFACE VERSION 7 AND ABOVE ONLY
-	// get the current player character
-	AGSIFUNC(int)  GetPlayerCharacter();
-	// adjust to viewport co-ordinates
-	AGSIFUNC(void) RoomToViewport(int32 *x, int32 *y);
-	// adjust from viewport co-ordinates
-	AGSIFUNC(void) ViewportToRoom(int32 *x, int32 *y);
-	// number of objects in current room
-	AGSIFUNC(int)  GetNumObjects();
-	// get reference to specified object
-	AGSIFUNC(AGSObject *) GetObject(int32);
-	// get sprite graphic
-	AGSIFUNC(BITMAP *) GetSpriteGraphic(int32);
-	// create a new blank bitmap
-	AGSIFUNC(BITMAP *) CreateBlankBitmap(int32 width, int32 height, int32 coldep);
-	// free a created bitamp
-	AGSIFUNC(void) FreeBitmap(BITMAP *);
-
-	// *** BELOW ARE INTERFACE VERSION 8 AND ABOVE ONLY
-	// get one of the room area masks
-	AGSIFUNC(BITMAP *) GetRoomMask(int32);
-
-	// *** BELOW ARE INTERFACE VERSION 9 AND ABOVE ONLY
-	// get a particular view frame
-	AGSIFUNC(AGSViewFrame *) GetViewFrame(int32 view, int32 loop, int32 frame);
-	// get the walk-behind baseline of a specific WB area
-	AGSIFUNC(int)    GetWalkbehindBaseline(int32 walkbehind);
-	// get the address of a script function
-	AGSIFUNC(void *) GetScriptFunctionAddress(const char *funcName);
-	// get the transparent colour of a bitmap
-	AGSIFUNC(int)    GetBitmapTransparentColor(BITMAP *);
-	// get the character scaling level at a particular point
-	AGSIFUNC(int)    GetAreaScaling(int32 x, int32 y);
-	// equivalent to the text script function
-	AGSIFUNC(int)    IsGamePaused();
-
-	// *** BELOW ARE INTERFACE VERSION 10 AND ABOVE ONLY
-	// get the raw pixel value to use for the specified AGS colour
-	AGSIFUNC(int)    GetRawPixelColor(int32 color);
-
-	// *** BELOW ARE INTERFACE VERSION 11 AND ABOVE ONLY
-	// get the width / height of the specified sprite
-	AGSIFUNC(int)    GetSpriteWidth(int32);
-	AGSIFUNC(int)    GetSpriteHeight(int32);
-	// get the dimensions of the specified string in the specified font
-	AGSIFUNC(void)   GetTextExtent(int32 font, const char *text, int32 *width, int32 *height);
-	// print a message to the debug console
-	AGSIFUNC(void)   PrintDebugConsole(const char *text);
-	// play a sound on the specified channel
-	AGSIFUNC(void)   PlaySoundChannel(int32 channel, int32 soundType, int32 volume, int32 loop, const char *filename);
-	// same as text script function
-	AGSIFUNC(int)    IsChannelPlaying(int32 channel);
-
-	// *** BELOW ARE INTERFACE VERSION 12 AND ABOVE ONLY
-	// invalidate a region of the virtual screen
-	AGSIFUNC(void)   MarkRegionDirty(int32 left, int32 top, int32 right, int32 bottom);
-	// get mouse cursor details
-	AGSIFUNC(AGSMouseCursor *) GetMouseCursor(int32 cursor);
-	// get the various components of a pixel
-	AGSIFUNC(void)   GetRawColorComponents(int32 coldepth, int32 color, int32 *red, int32 *green, int32 *blue, int32 *alpha);
-	// make a pixel colour from the supplied components
-	AGSIFUNC(int)    MakeRawColorPixel(int32 coldepth, int32 red, int32 green, int32 blue, int32 alpha);
-	// get whether the font is TTF or SCI
-	AGSIFUNC(int)    GetFontType(int32 fontNum);
-	// create a new dynamic sprite slot
-	AGSIFUNC(int)    CreateDynamicSprite(int32 coldepth, int32 width, int32 height);
-	// free a created dynamic sprite
-	AGSIFUNC(void)   DeleteDynamicSprite(int32 slot);
-	// check if a sprite has an alpha channel
-	AGSIFUNC(int)    IsSpriteAlphaBlended(int32 slot);
-
-	// *** BELOW ARE INTERFACE VERSION 13 AND ABOVE ONLY
-	// un-request an event, requested earlier with RequestEventHook
-	AGSIFUNC(void)   UnrequestEventHook(int32 event);
-	// draw a translucent bitmap to the active screen
-	AGSIFUNC(void)   BlitSpriteTranslucent(int32 x, int32 y, BITMAP *, int32 trans);
-	// draw a sprite to the screen, but rotated around its centre
-	AGSIFUNC(void)   BlitSpriteRotated(int32 x, int32 y, BITMAP *, int32 angle);
-
-	// *** BELOW ARE INTERFACE VERSION 14 AND ABOVE ONLY
-#ifdef WINDOWS_VERSION
-	// get reference to main DirectSound interface
-	AGSIFUNC(LPDIRECTSOUND) GetDirectSound();
-#endif
-	// disable AGS sound engine
-	AGSIFUNC(void)   DisableSound();
-	// check whether a script function can be run now
-	AGSIFUNC(int)    CanRunScriptFunctionNow();
-	// call a user-defined script function
-	AGSIFUNC(int)    CallGameScriptFunction(const char *name, int32 globalScript, int32 numArgs, long arg1 = 0, long arg2 = 0, long arg3 = 0);
-
-	// *** BELOW ARE INTERFACE VERSION 15 AND ABOVE ONLY
-	// force any sprites on-screen using the slot to be updated
-	AGSIFUNC(void)   NotifySpriteUpdated(int32 slot);
-	// change whether the specified sprite is a 32-bit alpha blended image
-	AGSIFUNC(void)   SetSpriteAlphaBlended(int32 slot, int32 isAlphaBlended);
-	// run the specified script function whenever script engine is available
-	AGSIFUNC(void)   QueueGameScriptFunction(const char *name, int32 globalScript, int32 numArgs, long arg1 = 0, long arg2 = 0);
-	// register a new dynamic managed script object
-	AGSIFUNC(int)    RegisterManagedObject(const void *object, IAGSScriptManagedObject *callback);
-	// add an object reader for the specified object type
-	AGSIFUNC(void)   AddManagedObjectReader(const char *typeName, IAGSManagedObjectReader *reader);
-	// register an un-serialized managed script object
-	AGSIFUNC(void)   RegisterUnserializedObject(int key, const void *object, IAGSScriptManagedObject *callback);
-
-	// *** BELOW ARE INTERFACE VERSION 16 AND ABOVE ONLY
-	// get the address of a managed object based on its key
-	AGSIFUNC(void *)  GetManagedObjectAddressByKey(int key);
-	// get managed object's key from its address
-	AGSIFUNC(int)    GetManagedObjectKeyByAddress(const char *address);
-
-	// *** BELOW ARE INTERFACE VERSION 17 AND ABOVE ONLY
-	// create a new script string
-	AGSIFUNC(const char *) CreateScriptString(const char *fromText);
-
-	// *** BELOW ARE INTERFACE VERSION 18 AND ABOVE ONLY
-	// increment reference count
-	AGSIFUNC(int)    IncrementManagedObjectRefCount(const char *address);
-	// decrement reference count
-	AGSIFUNC(int)    DecrementManagedObjectRefCount(const char *address);
-	// set mouse position
-	AGSIFUNC(void)   SetMousePosition(int32 x, int32 y);
-	// simulate the mouse being clicked
-	AGSIFUNC(void)   SimulateMouseClick(int32 button);
-	// get number of waypoints on this movement path
-	AGSIFUNC(int)    GetMovementPathWaypointCount(int32 pathId);
-	// get the last waypoint that the char/obj passed
-	AGSIFUNC(int)    GetMovementPathLastWaypoint(int32 pathId);
-	// get the co-ordinates of the specified waypoint
-	AGSIFUNC(void)   GetMovementPathWaypointLocation(int32 pathId, int32 waypoint, int32 *x, int32 *y);
-	// get the speeds of the specified waypoint
-	AGSIFUNC(void)   GetMovementPathWaypointSpeed(int32 pathId, int32 waypoint, int32 *xSpeed, int32 *ySpeed);
-
-	// *** BELOW ARE INTERFACE VERSION 19 AND ABOVE ONLY
-	// get the current graphics driver ID
-	AGSIFUNC(const char *) GetGraphicsDriverID();
-
-	// *** BELOW ARE INTERFACE VERSION 22 AND ABOVE ONLY
-	// get whether we are running under the editor's debugger
-	AGSIFUNC(int)    IsRunningUnderDebugger();
-	// tells the engine to break into the debugger when the next line of script is run
-	AGSIFUNC(void)   BreakIntoDebugger();
-	// fills buffer with <install dir>\fileName, as appropriate
-	AGSIFUNC(void)   GetPathToFileInCompiledFolder(const char *fileName, char *buffer);
-
-	// *** BELOW ARE INTERFACE VERSION 23 AND ABOVE ONLY
-#ifdef WINDOWS_VERSION
-	// get reference to keyboard Direct Input device
-	AGSIFUNC(LPDIRECTINPUTDEVICE) GetDirectInputKeyboard();
-	// get reference to mouse Direct Input device
-	AGSIFUNC(LPDIRECTINPUTDEVICE) GetDirectInputMouse();
-#endif
-	// install a replacement renderer for the specified font number
-	AGSIFUNC(IAGSFontRenderer *) ReplaceFontRenderer(int fontNumber, IAGSFontRenderer *newRenderer);
-};
-
-#ifdef THIS_IS_THE_PLUGIN
-
-#ifdef WINDOWS_VERSION
-#define DLLEXPORT extern "C" __declspec(dllexport)
-#else
-// MAC VERSION: compile with -fvisibility=hidden
-// gcc -dynamiclib -std=gnu99 agsplugin.c -fvisibility=hidden -o agsplugin.dylib
-#define DLLEXPORT extern "C" __attribute__((visibility("default")))
-#endif
-
-DLLEXPORT const char *AGS_GetPluginName(void);
-DLLEXPORT int    AGS_EditorStartup(IAGSEditor *);
-DLLEXPORT void   AGS_EditorShutdown(void);
-DLLEXPORT void   AGS_EditorProperties(HWND);
-DLLEXPORT int    AGS_EditorSaveGame(char *, int);
-DLLEXPORT void   AGS_EditorLoadGame(char *, int);
-DLLEXPORT void   AGS_EngineStartup(IAGSEngine *);
-DLLEXPORT void   AGS_EngineShutdown(void);
-DLLEXPORT int    AGS_EngineOnEvent(int, int);
-DLLEXPORT int    AGS_EngineDebugHook(const char *, int, int);
-DLLEXPORT void   AGS_EngineInitGfx(const char *driverID, void *data);
-// We export this to verify that we are an AGS Plugin
-DLLEXPORT int    AGS_PluginV2() {
-	return 1;
-}
-
-#endif // THIS_IS_THE_PLUGIN
-
-#endif
diff --git a/engines/ags/plugins/ags_pal_render/pal_render.h b/engines/ags/plugins/ags_pal_render/pal_render.h
index 09c2e6b5a5..1f448174e3 100644
--- a/engines/ags/plugins/ags_pal_render/pal_render.h
+++ b/engines/ags/plugins/ags_pal_render/pal_render.h
@@ -1,31 +1,40 @@
-#ifndef __PALGORITHMS_PALRENDER_H
-#define __PALGORITHMS_PALRENDER_H
-
-#include "agsplugin.h"
-#include <stdint.h> // for int32_t types, __int32 is just Windows
-#include <algorithm>  // for std::max and std::min
-#include <cstring>  // for memcpy
-
-#undef min
-#undef max
-
-#ifndef _WIN32
-#define __forceinline __attribute__((always_inline))
-
-#define SCRIPT_FLOAT(x) int32_t __script_float##x
-#define INIT_SCRIPT_FLOAT(x) float x; std::memcpy(&x, &__script_float##x, sizeof(float))
-#define FLOAT_RETURN_TYPE int32_t
-#define RETURN_FLOAT(x) int32_t __ret##x; std::memcpy(&__ret##x, &x, sizeof(float)); return __ret##x
-#else
-#define SCRIPT_FLOAT(x) __int32 __script_float##x
+/* 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 AGS_PLUGINS_AGS_PAL_RENDER_PAL_RENDER_H
+#define AGS_PLUGINS_AGS_PAL_RENDER_PAL_RENDER_H
+
+#include "ags/lib/allegro.h"
+#include "ags/engine/plugin/agsplugin.h"
+#include "common/algorithm.h"
+
+namespace AGS3 {
+namespace Plugins {
+namespace AGSPalRender {
+
+#define SCRIPT_FLOAT(x) int32 __script_float##x
 #define INIT_SCRIPT_FLOAT(x) float x; memcpy(&x, &__script_float##x, sizeof(float))
-#define FLOAT_RETURN_TYPE __int32
-#define RETURN_FLOAT(x) __int32 __ret##x; memcpy(&__ret##x, &x, sizeof(float)); return __ret##x
-#endif
-
-#if defined(BUILTIN_PLUGINS)
-namespace agspalrender {
-#endif
+#define FLOAT_RETURN_TYPE int32
+#define RETURN_FLOAT(x) int32 __ret##x; memcpy(&__ret##x, &x, sizeof(float)); return __ret##x
 
 struct PALSTRUCT {
 	int r;
@@ -44,11 +53,10 @@ extern PALSTRUCT objectivepal[256];
 // methods can be inlined without any trace or complaint
 class Mix {
 public:
-
 //unsigned char MixColorAlpha (unsigned char fg,unsigned char bg,unsigned char alpha);
 //unsigned char MixColorAdditive (unsigned char fg,unsigned char bg,unsigned char alpha);
-	__forceinline static unsigned char MixColorAlpha(unsigned char fg, unsigned char bg, unsigned char alpha, int use_objpal = 0) {
-		unsigned char rfg = cycle_remap [fg]; //Automatic remapping of palette slots.
+	static unsigned char MixColorAlpha(unsigned char fg, unsigned char bg, unsigned char alpha, int use_objpal = 0) {
+		unsigned char rfg = cycle_remap[fg]; //Automatic remapping of palette slots.
 		//unsigned char rbg = cycle_remap [bg]; //Saves on typing elsewhere.
 		AGSColor *palette = engine->GetPalette();
 		int i = 0;
@@ -57,15 +65,15 @@ public:
 		//int out_b = (palette[fg].b>>1) * alpha + (palette[bg].b>>1) * (255 - alpha);
 		int out_r, out_g, out_b;
 		if (use_objpal == 0) {
-			out_r = (objectivepal[rfg].r >> 1) * alpha + (palette[bg].r >> 1) * (255 - alpha);
+			out_r = (objectivepal[rfg].r >> 1) *alpha + (palette[bg].r >> 1) *(255 - alpha);
 			out_g = objectivepal[rfg].g * alpha + palette[bg].g * (255 - alpha);
-			out_b = (objectivepal[rfg].b >> 1) * alpha + (palette[bg].b >> 1) * (255 - alpha);
+			out_b = (objectivepal[rfg].b >> 1) *alpha + (palette[bg].b >> 1) *(255 - alpha);
 		} else {
-			out_r = (objectivepal[rfg].r >> 1) * alpha + (objectivepal[bg].r >> 1) * (255 - alpha);
+			out_r = (objectivepal[rfg].r >> 1) *alpha + (objectivepal[bg].r >> 1) *(255 - alpha);
 			out_g = objectivepal[rfg].g * alpha + objectivepal[bg].g * (255 - alpha);
-			out_b = (objectivepal[rfg].b >> 1) * alpha + (objectivepal[bg].b >> 1) * (255 - alpha);
+			out_b = (objectivepal[rfg].b >> 1) *alpha + (objectivepal[bg].b >> 1) *(255 - alpha);
 		}
-		//char ralpha = std::max(0,std::min(63,alpha>>2));
+		//char ralpha = MAX(0,MIN(63,alpha>>2));
 		//unsigned char invralpha = 64-ralpha;
 		//if (ralpha > alpha) engine->AbortGame ("wtf");
 		//int out_r = alphamultiply[((palette[fg].r>>1)<<6) +ralpha] + alphamultiply[((palette[bg].r>>1)<<6) +(invralpha)];
@@ -78,13 +86,13 @@ public:
 		//out_g = (out_g + 1 + (out_g >> 6)) >> 6;
 		//out_b = (out_b + 1 + (out_b >> 6)) >> 6;
 		i = ((out_r << 11) | (out_g << 5) | out_b);
-		unsigned char (*clutp) = clut;
+		unsigned char(*clutp) = clut;
 		//unsigned char result = cycle_remap [clut[i>>8][i%256]]; //Once again, to make sure that the palette slot used is the right one.
 		return cycle_remap[*(clutp + i)]; //Once again, to make sure that the palette slot used is the right one.
 		//engine->ReleaseBitmapSurface (clutspr);
 	}
 
-	__forceinline static unsigned char MixColorLightLevel(unsigned char fg, unsigned char intensity) {
+	static unsigned char MixColorLightLevel(unsigned char fg, unsigned char intensity) {
 		unsigned char rfg = cycle_remap [fg]; //Automatic remapping of palette slots.
 		int i = 0;
 		//int dark_r = (((palette[fg].r>>1) * (intensity))>>8);
@@ -98,38 +106,38 @@ public:
 		return cycle_remap [*(clutp + i)]; //Once again, to make sure that the palette slot used is the right one.
 	}
 
-	__forceinline static unsigned char MixColorAdditive(unsigned char fg, unsigned char bg, unsigned char alpha, int use_objpal = 0) {
-		unsigned char rfg = cycle_remap [fg]; //Automatic remapping of palette slots.
-		unsigned char rbg = cycle_remap [bg]; //Saves on typing elsewhere.
+	static unsigned char MixColorAdditive(unsigned char fg, unsigned char bg, unsigned char alpha, int use_objpal = 0) {
+		unsigned char rfg = cycle_remap[fg]; //Automatic remapping of palette slots.
+		//unsigned char rbg = cycle_remap[bg]; //Saves on typing elsewhere.
 		//BITMAP *clutspr = engine->GetSpriteGraphic (clutslot);
 		//if (!clutspr) engine->AbortGame ("MixColorAlpha: Can't load CLUT sprite into memory.");
 		//unsigned char **clutarray = engine->GetRawBitmapSurface (clutspr);
 		AGSColor *palette = engine->GetPalette();
 		int i = 0;
 		int add_r, add_b, add_g = 0;
-		//char ralpha = std::max(0,std::min(63,alpha>>2));
+		//char ralpha = MAX(0,MIN(63,alpha>>2));
 		//add_r = (((palette[fg].r>>1) * (alpha))>>8);
 		//add_b = (((palette[fg].b>>1) * (alpha))>>8);
 		//add_g = (((palette[fg].g)    * (alpha))>>8);
 		add_r = (((objectivepal[rfg].r >> 1) * (alpha)) >> 8);
 		add_b = (((objectivepal[rfg].b >> 1) * (alpha)) >> 8);
 		add_g = (((objectivepal[rfg].g)    * (alpha)) >> 8);
-		//int a_g = std::max(0,std::min(63,alpha>>2));
+		//int a_g = MAX(0,MIN(63,alpha>>2));
 		//add_r = ((alphamultiply[(palette[fg].r>>1)<<6)+ralpha])>>6);
 		//add_b = ((alphamultiply[(palette[fg].b>>1)<<6)+ralpha])>>6);
 		//add_g = ((alphamultiply[(palette[fg].g)   <<6)+ralpha])>>6);
-		//int out_r = std::min(31,(palette[bg].r>>1) + add_r);
-		//int out_g = std::min(63, palette[bg].g     + add_g);
-		//int out_b = std::min(31,(palette[bg].b>>1) + add_b);
+		//int out_r = MIN(31,(palette[bg].r>>1) + add_r);
+		//int out_g = MIN(63, palette[bg].g     + add_g);
+		//int out_b = MIN(31,(palette[bg].b>>1) + add_b);
 		int out_r, out_g, out_b;
 		if (use_objpal == 0) {
-			out_r = std::min(31, (palette[bg].r >> 1) + add_r);
-			out_g = std::min(63, palette[bg].g     + add_g);
-			out_b = std::min(31, (palette[bg].b >> 1) + add_b);
+			out_r = MIN(31, (palette[bg].r >> 1) + add_r);
+			out_g = MIN(63, palette[bg].g     + add_g);
+			out_b = MIN(31, (palette[bg].b >> 1) + add_b);
 		} else {
-			out_r = std::min(31, (objectivepal [bg].r >> 1) + add_r);
-			out_g = std::min(63, objectivepal [bg].g     + add_g);
-			out_b = std::min(31, (objectivepal [bg].b >> 1) + add_b);
+			out_r = MIN(31, (objectivepal [bg].r >> 1) + add_r);
+			out_g = MIN(63, objectivepal [bg].g     + add_g);
+			out_b = MIN(31, (objectivepal [bg].b >> 1) + add_b);
 		}
 		i = ((out_r << 11) | (out_g << 5) | out_b);
 		unsigned char (*clutp) = clut;
@@ -139,7 +147,7 @@ public:
 		return result;
 	}
 
-	__forceinline static unsigned char MixColorMultiply(unsigned char fg, unsigned char bg, unsigned char alpha, int use_objpal = 0) {
+	static unsigned char MixColorMultiply(unsigned char fg, unsigned char bg, unsigned char alpha, int use_objpal = 0) {
 		unsigned char rfg = cycle_remap [fg]; //Automatic remapping of palette slots.
 		unsigned char rbg = cycle_remap [bg]; //Saves on typing elsewhere.
 		AGSColor *palette = engine->GetPalette();
@@ -178,8 +186,8 @@ unsigned short root(unsigned short x);
 float FastSin(float x);
 float FastCos(float x);
 
-#if defined(BUILTIN_PLUGINS)
-} // namespace agspalrender
-#endif
+} // namespace AGSPalRender
+} // namespace Plugins
+} // namespace AGS3
 
-#endif
\ No newline at end of file
+#endif
diff --git a/engines/ags/plugins/ags_pal_render/raycast.cpp b/engines/ags/plugins/ags_pal_render/raycast.cpp
index 9ce5d5c343..8309081ee3 100644
--- a/engines/ags/plugins/ags_pal_render/raycast.cpp
+++ b/engines/ags/plugins/ags_pal_render/raycast.cpp
@@ -1,39 +1,31 @@
-/*
-Copyright (c) 2004-2007, Lode Vandevenne
-
-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.
-
-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 OWNER 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.
-*/
-
-#include "raycast.h"
-
-#include <cmath>
-#include <string>
-#include <vector>
-#include <iostream>
-#include <algorithm>
-#include <stdio.h>
-#include <math.h>
-
-#if defined(BUILTIN_PLUGINS)
-namespace agspalrender {
-#endif
+/* 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 "ags/lib/allegro.h"
+#include "ags/plugins/ags_pal_render/raycast.h"
+
+namespace AGS3 {
+namespace Plugins {
+namespace AGSPalRender {
 
 #define PI         (3.1415926535f)
 
@@ -163,7 +155,7 @@ int Ray_GetAmbientWeight() {
 }
 
 void Ray_SetAmbientLight(int value) {
-	ambientlight = std::min(255, std::max(0, value));
+	ambientlight = MIN(255, MAX(0, value));
 }
 
 void Ray_SetAmbientColor(int color, int amount) {
@@ -202,31 +194,31 @@ void Ray_SetWallTextures(int id, int n, int s, int w, int e) {
 }
 
 void Ray_SetWallSolid(int id, int n, int s, int w, int e) {
-	wallData[id].solid [0] = std::max(0, std::min(n, 1));
-	wallData[id].solid [1] = std::max(0, std::min(s, 1));
-	wallData[id].solid [2] = std::max(0, std::min(w, 1));
-	wallData[id].solid [3] = std::max(0, std::min(e, 1));
+	wallData[id].solid [0] = MAX(0, MIN(n, 1));
+	wallData[id].solid [1] = MAX(0, MIN(s, 1));
+	wallData[id].solid [2] = MAX(0, MIN(w, 1));
+	wallData[id].solid [3] = MAX(0, MIN(e, 1));
 }
 
 void Ray_SetWallIgnoreLighting(int id, int n, int s, int w, int e) {
-	wallData[id].ignorelighting [0] = std::max(0, std::min(n, 1));
-	wallData[id].ignorelighting [1] = std::max(0, std::min(s, 1));
-	wallData[id].ignorelighting [2] = std::max(0, std::min(w, 1));
-	wallData[id].ignorelighting [3] = std::max(0, std::min(e, 1));
+	wallData[id].ignorelighting [0] = MAX(0, MIN(n, 1));
+	wallData[id].ignorelighting [1] = MAX(0, MIN(s, 1));
+	wallData[id].ignorelighting [2] = MAX(0, MIN(w, 1));
+	wallData[id].ignorelighting [3] = MAX(0, MIN(e, 1));
 }
 
 void Ray_SetWallAlpha(int id, int n, int s, int w, int e) {
-	wallData[id].alpha [0] = std::max(0, std::min(n, 255));
-	wallData[id].alpha [1] = std::max(0, std::min(s, 255));
-	wallData[id].alpha [2] = std::max(0, std::min(w, 255));
-	wallData[id].alpha [3] = std::max(0, std::min(e, 255));
+	wallData[id].alpha [0] = MAX(0, MIN(n, 255));
+	wallData[id].alpha [1] = MAX(0, MIN(s, 255));
+	wallData[id].alpha [2] = MAX(0, MIN(w, 255));
+	wallData[id].alpha [3] = MAX(0, MIN(e, 255));
 }
 
 void Ray_SetWallBlendType(int id, int n, int s, int w, int e) {
-	wallData[id].blendtype [0] = std::max(0, std::min(n, 10));
-	wallData[id].blendtype [1] = std::max(0, std::min(s, 10));
-	wallData[id].blendtype [2] = std::max(0, std::min(w, 10));
-	wallData[id].blendtype [3] = std::max(0, std::min(e, 10));
+	wallData[id].blendtype [0] = MAX(0, MIN(n, 10));
+	wallData[id].blendtype [1] = MAX(0, MIN(s, 10));
+	wallData[id].blendtype [2] = MAX(0, MIN(w, 10));
+	wallData[id].blendtype [3] = MAX(0, MIN(e, 10));
 }
 
 
@@ -893,9 +885,9 @@ void Raycast_Render(int slot) {
 				}
 				if (do_ambient) {
 					ambientpixels = true;
-					wall_light = std::max(wall_light, ambientlight);
+					wall_light = MAX(wall_light, ambientlight);
 				}
-				wall_light = std::min(255, std::max(0, wall_light));
+				wall_light = MIN(255, MAX(0, wall_light));
 				bool alphastripe = false;
 				for (int y = drawStart; y < drawEnd; y++) {
 					if (ZBuffer[x][y] > perpWallDist || ZBuffer[x][y] == 0) { //We can draw.
@@ -1033,7 +1025,7 @@ void Raycast_Render(int slot) {
 				if (cmapY < 0) cmapY = 0;
 				if (heightMap[cmapX][cmapY] - 1 < 1) continue;
 				int lighting = lightMap [cmapX][cmapY] << 5;
-				lighting = std::min(255, std::max(0, lighting));
+				lighting = MIN(255, MAX(0, lighting));
 				floorTexX = int(currentFloorX * texWidth) % texWidth;
 				floorTexY = int(currentFloorY * texHeight) % texHeight;
 				int floorcolor = 0;
@@ -1046,7 +1038,7 @@ void Raycast_Render(int slot) {
 					floorcolor = texture[floorMap[cmapX][cmapY] - 1][texpos];
 				} else continue;
 				if (ceilingcolor == 0) {
-					lighting = std::max(lighting, ambientlight);
+					lighting = MAX(lighting, ambientlight);
 					ambientweight ++;
 				}
 				if (lighting < 255) {
@@ -1081,7 +1073,7 @@ void Raycast_Render(int slot) {
 				int cmapY = (int)currentFloorY % mapHeight;
 				if (cmapY < 0) cmapY = 0;
 				int lighting = lightMap [cmapX][cmapY] << 5;
-				lighting = std::min(255, std::max(0, lighting));
+				lighting = MIN(255, MAX(0, lighting));
 				floorTexX = int(currentFloorX * texWidth) % texWidth;
 				floorTexY = int(currentFloorY * texHeight) % texHeight;
 				int floorcolor = 0;
@@ -1093,7 +1085,7 @@ void Raycast_Render(int slot) {
 					ceilingcolor = texture[ceilingMap[cmapX][cmapY] - 1][texWidth * floorTexY + floorTexX];
 				}
 				if (ceilingcolor == 0) {
-					lighting = std::max(lighting, ambientlight);
+					lighting = MAX(lighting, ambientlight);
 					ambientweight++;
 				}
 				if (lighting < 255) {
@@ -1252,12 +1244,12 @@ void Raycast_Render(int slot) {
 		int drawEndX = spriteWidth / 2 + spriteScreenX + hMoveScreen;
 		if (drawEndX >= w) drawEndX = w - 1;
 		int spr_light = lightMap [(int)sprite[spriteOrder[i]].x][(int)sprite[spriteOrder[i]].y] << 5;
-		spr_light = std::min(255, std::max(0, spr_light));
+		spr_light = MIN(255, MAX(0, spr_light));
 		int floorTexX = int(sprite[spriteOrder[i]].x * texWidth) % texWidth;
 		int floorTexY = int(sprite[spriteOrder[i]].y * texHeight) % texHeight;
 		if (ceilingMap [(int)sprite[spriteOrder[i]].x][(int)sprite[spriteOrder[i]].y] == 0) {
-			spr_light = std::max(spr_light, ambientlight);
-		} else if (texture[ceilingMap [(int)sprite[spriteOrder[i]].x][(int)sprite[spriteOrder[i]].y] - 1][texWidth * floorTexY + floorTexX] == 0) spr_light = std::max(spr_light, ambientlight);
+			spr_light = MAX(spr_light, ambientlight);
+		} else if (texture[ceilingMap [(int)sprite[spriteOrder[i]].x][(int)sprite[spriteOrder[i]].y] - 1][texWidth * floorTexY + floorTexX] == 0) spr_light = MAX(spr_light, ambientlight);
 		//loop through every vertical stripe of the sprite on screen
 
 
@@ -1485,14 +1477,15 @@ void combSort(int *order, double *dist, int amount) {
 		for (int i = 0; i < amount - gap; i++) {
 			int j = i + gap;
 			if (dist[i] < dist[j]) {
-				std::swap(dist[i], dist[j]);
-				std::swap(order[i], order[j]);
+				SWAP(dist[i], dist[j]);
+				SWAP(order[i], order[j]);
 				swapped = true;
 			}
 		}
 	}
 }
 
-#if defined(BUILTIN_PLUGINS)
-} // namespace agspalrender
-#endif
+} // namespace AGSBlend
+} // namespace Plugins
+} // namespace AGS3
+
diff --git a/engines/ags/plugins/ags_pal_render/raycast.h b/engines/ags/plugins/ags_pal_render/raycast.h
index 87f4c1ed6f..3e797a37e3 100644
--- a/engines/ags/plugins/ags_pal_render/raycast.h
+++ b/engines/ags/plugins/ags_pal_render/raycast.h
@@ -1,15 +1,37 @@
-#ifndef __PALGORITHMS_RAYCAST_H
-#define __PALGORITHMS_RAYCAST_H
-
-#include "palrender.h"
+/* 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 AGS_PLUGINS_AGS_PAL_RENDER_RAYCAST_H
+#define AGS_PLUGINS_AGS_PAL_RENDER_RAYCAST_H
+
+#include "ags/plugins/ags_pal_render/pal_render.h"
+
+namespace AGS3 {
+namespace Plugins {
+namespace AGSPalRender {
 
 #define mapWidth 64
 #define mapHeight 64
 
-#if defined(BUILTIN_PLUGINS)
-namespace agspalrender {
-#endif
-
 struct Sprite {
 	double x;
 	double y;
@@ -182,8 +204,8 @@ int Ray_GetAmbientWeight();
 
 int Ray_HasSeenTile(int x, int y);
 
-#if defined(BUILTIN_PLUGINS)
-} // namespace agspalrender
-#endif
+} // namespace AGSPalRender
+} // namespace Plugins
+} // namespace AGS3
 
-#endif
\ No newline at end of file
+#endif
diff --git a/engines/ags/plugins/dll.cpp b/engines/ags/plugins/dll.cpp
index f08ce59b96..74217cd2ee 100644
--- a/engines/ags/plugins/dll.cpp
+++ b/engines/ags/plugins/dll.cpp
@@ -25,6 +25,7 @@
 #include "ags/plugins/ags_blend/ags_blend.h"
 #include "ags/plugins/ags_creditz/ags_creditz.h"
 #include "ags/plugins/ags_flashlight/ags_flashlight.h"
+#include "ags/plugins/ags_pal_render/ags_pal_render.h"
 #include "ags/ags.h"
 #include "ags/detection.h"
 #include "common/str.h"
@@ -58,6 +59,9 @@ void *dlopen(const char *filename) {
 	if (fname.equalsIgnoreCase("libAGSFlashlight.so"))
 		return new AGSFlashlight::AGSFlashlight();
 
+	if (fname.equalsIgnoreCase("libAGSPalRender.so"))
+		return new AGSPalRender::AGSPalRender();
+
 	return nullptr;
 }
 


Commit: 17341f6133d5a4b2daac0068e4d7951bc35cee45
    https://github.com/scummvm/scummvm/commit/17341f6133d5a4b2daac0068e4d7951bc35cee45
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added AGSParallax plugin

Changed paths:
    engines/ags/module.mk
    engines/ags/plugins/ags_pal_render/raycast.cpp
    engines/ags/plugins/ags_parallax/ags_parallax.cpp
    engines/ags/plugins/ags_parallax/ags_parallax.h


diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index fbfc1d2395..295eab3901 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -305,7 +305,8 @@ MODULE_OBJS = \
 	plugins/ags_creditz/ags_creditz.o \
 	plugins/ags_flashlight/ags_flashlight.o \
 	plugins/ags_pal_render/ags_pal_render.o \
-	plugins/ags_pal_render/raycast.o
+	plugins/ags_pal_render/raycast.o \
+	plugins/ags_parallax/ags_parallax.o
 
 ifdef ENABLE_AGS_TESTS
 MODULE_OBJS += \
diff --git a/engines/ags/plugins/ags_pal_render/raycast.cpp b/engines/ags/plugins/ags_pal_render/raycast.cpp
index 8309081ee3..fe26cfb8bb 100644
--- a/engines/ags/plugins/ags_pal_render/raycast.cpp
+++ b/engines/ags/plugins/ags_pal_render/raycast.cpp
@@ -1485,7 +1485,7 @@ void combSort(int *order, double *dist, int amount) {
 	}
 }
 
-} // namespace AGSBlend
+} // namespace AGSPalRender
 } // namespace Plugins
 } // namespace AGS3
 
diff --git a/engines/ags/plugins/ags_parallax/ags_parallax.cpp b/engines/ags/plugins/ags_parallax/ags_parallax.cpp
index 05c32b94dd..c4575bf1cd 100644
--- a/engines/ags/plugins/ags_parallax/ags_parallax.cpp
+++ b/engines/ags/plugins/ags_parallax/ags_parallax.cpp
@@ -1,108 +1,143 @@
-/*
+/* 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 "ags/plugins/ags_parallax/ags_parallax.h"
+#include "ags/shared/core/platform.h"
+
+namespace AGS3 {
+namespace Plugins {
+namespace AGSParallax {
 
-This is not the AGS Parallax plugin by Scorpiorus
-but a workalike plugin created by JJS for the AGS engine ports.
-
-*/
-
-#include "core/platform.h"
-
-#if AGS_PLATFORM_OS_WINDOWS
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#pragma warning(disable : 4244)
-#endif
-
-#if !defined(BUILTIN_PLUGINS)
-#define THIS_IS_THE_PLUGIN
-#endif
+const unsigned int Magic = 0xCAFE0000;
+const unsigned int Version = 2;
+const unsigned int SaveMagic = Magic + Version;
 
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <math.h>
+IAGSEngine *AGSParallax::_engine;
+int AGSParallax::_screenWidth;
+int AGSParallax::_screenHeight;
+int AGSParallax::_screenColorDepth;
+bool AGSParallax::_enabled;
+Sprite AGSParallax::_sprites[MAX_SPRITES];
 
-#include "plugin/agsplugin.h"
 
-#if defined(BUILTIN_PLUGINS)
-namespace ags_parallax {
-#endif
+AGSParallax::AGSParallax() : DLL() {
+	_engine = nullptr;
+	_screenWidth = 320;
+	_screenHeight = 200;
+	_screenColorDepth = 32;
+	_enabled = false;
 
-//#define DEBUG
+	DLL_METHOD(AGS_GetPluginName);
+	DLL_METHOD(AGS_EngineStartup);
+	DLL_METHOD(AGS_EngineOnEvent);
+}
 
-const unsigned int Magic = 0xCAFE0000;
-const unsigned int Version = 2;
-const unsigned int SaveMagic = Magic + Version;
+const char *AGSParallax::AGS_GetPluginName() {
+	return "Parallax plugin recreation";
+}
 
-int screen_width = 320;
-int screen_height = 200;
-int screen_color_depth = 32;
+void AGSParallax::AGS_EngineStartup(IAGSEngine *engine) {
+	_engine = engine;
 
-IAGSEngine *engine;
+	if (_engine->version < 13)
+		_engine->AbortGame("Engine interface is too old, need newer version of AGS.");
 
-bool enabled = false;
+	SCRIPT_METHOD("pxDrawSprite");
+	SCRIPT_METHOD("pxDeleteSprite");
 
+	_engine->RequestEventHook(AGSE_PREGUIDRAW);
+	_engine->RequestEventHook(AGSE_PRESCREENDRAW);
+	_engine->RequestEventHook(AGSE_ENTERROOM);
+	_engine->RequestEventHook(AGSE_SAVEGAME);
+	_engine->RequestEventHook(AGSE_RESTOREGAME);
 
-typedef struct {
-	int x;
-	int y;
-	int slot;
-	int speed;
-} sprite_t;
+	Initialize();
+}
 
-#define MAX_SPEED 1000
-#define MAX_SPRITES 100
-sprite_t sprites[MAX_SPRITES];
+int AGSParallax::AGS_EngineOnEvent(int event, int data) {
+	if (event == AGSE_PREGUIDRAW) {
+		Draw(true);
+	} else if (event == AGSE_PRESCREENDRAW) {
+		Draw(false);
+	} else if (event == AGSE_ENTERROOM) {
+		// Reset all _sprites
+		Initialize();
+	} else if (event == AGSE_PRESCREENDRAW) {
+		// Get screen size once here
+		_engine->GetScreenDimensions(&_screenWidth, &_screenHeight, &_screenColorDepth);
+		_engine->UnrequestEventHook(AGSE_PRESCREENDRAW);
+	} else if (event == AGSE_RESTOREGAME) {
+		RestoreGame(data);
+	} else if (event == AGSE_SAVEGAME) {
+		SaveGame(data);
+	}
 
-// workaround to fix this error:
-//   psp-fixup-imports ags_parallax.elf
-//   Error, no .lib.stub section found
-void dummy() {
-	void *tmp = new int;
+	return 0;
 }
 
-static size_t engineFileRead(void *ptr, size_t size, size_t count, long fileHandle) {
-	auto totalBytes = engine->FRead(ptr, size * count, fileHandle);
+size_t AGSParallax::engineFileRead(void *ptr, size_t size, size_t count, long fileHandle) {
+	auto totalBytes = _engine->FRead(ptr, size * count, fileHandle);
 	return totalBytes / size;
 }
 
-static size_t engineFileWrite(const void *ptr, size_t size, size_t count, long fileHandle) {
-	auto totalBytes = engine->FWrite(const_cast<void *>(ptr), size * count, fileHandle);
+size_t AGSParallax::engineFileWrite(const void *ptr, size_t size, size_t count, long fileHandle) {
+	auto totalBytes = _engine->FWrite(const_cast<void *>(ptr), size * count, fileHandle);
 	return totalBytes / size;
 }
 
-void RestoreGame(long fileHandle) {
+void AGSParallax::RestoreGame(long fileHandle) {
 	unsigned int SaveVersion = 0;
 	engineFileRead(&SaveVersion, sizeof(SaveVersion), 1, fileHandle);
 
 	if (SaveVersion != SaveMagic) {
-		engine->AbortGame("ags_parallax: bad save.");
+		_engine->AbortGame("ags_parallax: bad save.");
 	}
 
-	engineFileRead(sprites, sizeof(sprite_t), MAX_SPRITES, fileHandle);
-	engineFileRead(&enabled, sizeof(bool), 1, fileHandle);
+	// TODO: This seems endian/packing unsafe
+	engineFileRead(_sprites, sizeof(Sprite), MAX_SPRITES, fileHandle);
+	engineFileRead(&_enabled, sizeof(bool), 1, fileHandle);
 }
 
-void SaveGame(long file) {
+void AGSParallax::SaveGame(long file) {
+	warning("TODO: AGSParallax::SaveGame is endian unsafe");
 	engineFileWrite(&SaveMagic, sizeof(SaveMagic), 1, file);
-	engineFileWrite(sprites, sizeof(sprite_t), MAX_SPRITES, file);
-	engineFileWrite(&enabled, sizeof(bool), 1, file);
+	engineFileWrite(_sprites, sizeof(Sprite), MAX_SPRITES, file);
+	engineFileWrite(&_enabled, sizeof(bool), 1, file);
 }
 
 
-void Initialize() {
-	memset(sprites, 0, sizeof(sprite_t) * MAX_SPRITES);
+void AGSParallax::Initialize() {
+	memset(_sprites, 0, sizeof(Sprite) * MAX_SPRITES);
 
 	int i;
 	for (i = 0; i < MAX_SPRITES; i++)
-		sprites[i].slot = -1;
+		_sprites[i].slot = -1;
 
-	enabled = false;
+	_enabled = false;
 }
 
 
-void Draw(bool foreground) {
-	if (!enabled)
+void AGSParallax::Draw(bool foreground) {
+	if (!_enabled)
 		return;
 
 	BITMAP *bmp;
@@ -110,21 +145,21 @@ void Draw(bool foreground) {
 
 	int offsetX = 0;
 	int offsetY = 0;
-	engine->ViewportToRoom(&offsetX, &offsetY);
+	_engine->ViewportToRoom(&offsetX, &offsetY);
 
 	for (i = 0; i < MAX_SPRITES; i++) {
-		if (sprites[i].slot > -1) {
+		if (_sprites[i].slot > -1) {
 			if (foreground) {
-				if (sprites[i].speed > 0) {
-					bmp = engine->GetSpriteGraphic(sprites[i].slot);
+				if (_sprites[i].speed > 0) {
+					bmp = _engine->GetSpriteGraphic(_sprites[i].slot);
 					if (bmp)
-						engine->BlitBitmap(sprites[i].x - offsetX - (sprites[i].speed * offsetX / 100), sprites[i].y, bmp, 1);
+						_engine->BlitBitmap(_sprites[i].x - offsetX - (_sprites[i].speed * offsetX / 100), _sprites[i].y, bmp, 1);
 				}
 			} else {
-				if (sprites[i].speed <= 0) {
-					bmp = engine->GetSpriteGraphic(sprites[i].slot);
+				if (_sprites[i].speed <= 0) {
+					bmp = _engine->GetSpriteGraphic(_sprites[i].slot);
 					if (bmp)
-						engine->BlitBitmap(sprites[i].x - offsetX - (sprites[i].speed * offsetX / 1000), sprites[i].y, bmp, 1);
+						_engine->BlitBitmap(_sprites[i].x - offsetX - (_sprites[i].speed * offsetX / 1000), _sprites[i].y, bmp, 1);
 				}
 			}
 		}
@@ -132,18 +167,11 @@ void Draw(bool foreground) {
 }
 
 
-
-
-
-// ********************************************
-// ************  AGS Interface  ***************
-// ********************************************
-
-void pxDrawSprite(int id, int x, int y, int slot, int speed) {
+void AGSParallax::pxDrawSprite(int id, int x, int y, int slot, int speed) {
 #ifdef DEBUG
 	char buffer[200];
 	sprintf(buffer, "%s %d %d %d %d %d\n", "pxDrawSprite", id, x, y, slot, speed);
-	engine->PrintDebugConsole(buffer);
+	_engine->PrintDebugConsole(buffer);
 #endif
 
 	if ((id < 0) || (id >= MAX_SPRITES))
@@ -152,136 +180,30 @@ void pxDrawSprite(int id, int x, int y, int slot, int speed) {
 	if ((speed < -MAX_SPEED) || (speed > MAX_SPEED))
 		speed = 0;
 
-	sprites[id].x = x;
-	sprites[id].y = y;
-	sprites[id].slot = slot;
-	sprites[id].speed = speed;
+	_sprites[id].x = x;
+	_sprites[id].y = y;
+	_sprites[id].slot = slot;
+	_sprites[id].speed = speed;
 
-	engine->RoomToViewport(&sprites[id].x, &sprites[id].y);
+	_engine->RoomToViewport(&_sprites[id].x, &_sprites[id].y);
 
-	enabled = true;
+	_enabled = true;
 }
 
 
-void pxDeleteSprite(int id) {
+void AGSParallax::pxDeleteSprite(int id) {
 #ifdef DEBUG
 	char buffer[200];
 	sprintf(buffer, "%s %d\n", "pxDeleteSprite", id);
-	engine->PrintDebugConsole(buffer);
+	_engine->PrintDebugConsole(buffer);
 #endif
 
 	if ((id < 0) || (id >= MAX_SPRITES))
 		return;
 
-	sprites[id].slot = -1;
-}
-
-void AGS_EngineStartup(IAGSEngine *lpEngine) {
-	engine = lpEngine;
-
-	if (engine->version < 13)
-		engine->AbortGame("Engine interface is too old, need newer version of AGS.");
-
-	engine->RegisterScriptFunction("pxDrawSprite", (void *)&pxDrawSprite);
-	engine->RegisterScriptFunction("pxDeleteSprite", (void *)&pxDeleteSprite);
-
-	engine->RequestEventHook(AGSE_PREGUIDRAW);
-	engine->RequestEventHook(AGSE_PRESCREENDRAW);
-	engine->RequestEventHook(AGSE_ENTERROOM);
-	engine->RequestEventHook(AGSE_SAVEGAME);
-	engine->RequestEventHook(AGSE_RESTOREGAME);
-
-	Initialize();
-}
-
-void AGS_EngineShutdown() {
-}
-
-int AGS_EngineOnEvent(int event, int data) {
-	if (event == AGSE_PREGUIDRAW) {
-		Draw(true);
-	} else if (event == AGSE_PRESCREENDRAW) {
-		Draw(false);
-	} else if (event == AGSE_ENTERROOM) {
-		// Reset all sprites
-		Initialize();
-	} else if (event == AGSE_PRESCREENDRAW) {
-		// Get screen size once here
-		engine->GetScreenDimensions(&screen_width, &screen_height, &screen_color_depth);
-		engine->UnrequestEventHook(AGSE_PRESCREENDRAW);
-	} else if (event == AGSE_RESTOREGAME) {
-		RestoreGame(data);
-	} else if (event == AGSE_SAVEGAME) {
-		SaveGame(data);
-	}
-
-	return 0;
-}
-
-int AGS_EngineDebugHook(const char *scriptName, int lineNum, int reserved) {
-	return 0;
-}
-
-void AGS_EngineInitGfx(const char *driverID, void *data) {
-}
-
-
-
-#if AGS_PLATFORM_OS_WINDOWS && !defined(BUILTIN_PLUGINS)
-
-// ********************************************
-// ***********  Editor Interface  *************
-// ********************************************
-
-const char *scriptHeader =
-    "import void pxDrawSprite(int ID, int X, int Y, int SlotNum, int Speed);\r\n"
-    "import void pxDeleteSprite(int ID);\r\n";
-
-IAGSEditor *editor;
-
-
-LPCSTR AGS_GetPluginName(void) {
-	// Return the plugin description
-	return "Parallax plugin recreation";
-}
-
-int  AGS_EditorStartup(IAGSEditor *lpEditor) {
-	// User has checked the plugin to use it in their game
-
-	// If it's an earlier version than what we need, abort.
-	if (lpEditor->version < 1)
-		return -1;
-
-	editor = lpEditor;
-	editor->RegisterScriptHeader(scriptHeader);
-
-	// Return 0 to indicate success
-	return 0;
-}
-
-void AGS_EditorShutdown() {
-	// User has un-checked the plugin from their game
-	editor->UnregisterScriptHeader(scriptHeader);
-}
-
-void AGS_EditorProperties(HWND parent) {
-	// User has chosen to view the Properties of the plugin
-	// We could load up an options dialog or something here instead
-	MessageBoxA(parent, "Parallax plugin recreation by JJS", "About", MB_OK | MB_ICONINFORMATION);
-}
-
-int AGS_EditorSaveGame(char *buffer, int bufsize) {
-	// We don't want to save any persistent data
-	return 0;
+	_sprites[id].slot = -1;
 }
 
-void AGS_EditorLoadGame(char *buffer, int bufsize) {
-	// Nothing to load for this plugin
-}
-
-#endif
-
-
-#if defined(BUILTIN_PLUGINS)
-} // namespace ags_parallax
-#endif
+} // namespace AGSParallax
+} // namespace Plugins
+} // namespace AGS3
diff --git a/engines/ags/plugins/ags_parallax/ags_parallax.h b/engines/ags/plugins/ags_parallax/ags_parallax.h
index c58126f149..74d17089ce 100644
--- a/engines/ags/plugins/ags_parallax/ags_parallax.h
+++ b/engines/ags/plugins/ags_parallax/ags_parallax.h
@@ -1,14 +1,79 @@
-#ifndef AGS_PARALLAX_H
-#define AGS_PARALLAX_H
+/* 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 "plugin/agsplugin.h"
+#ifndef AGS_PLUGINS_AGS_PARALLAX_AGS_PARALLAX_H
+#define AGS_PLUGINS_AGS_PARALLAX_AGS_PARALLAX_H
 
-namespace ags_parallax {
-void AGS_EngineStartup(IAGSEngine *lpEngine);
-void AGS_EngineShutdown();
-int AGS_EngineOnEvent(int event, int data);
-int AGS_EngineDebugHook(const char *scriptName, int lineNum, int reserved);
-void AGS_EngineInitGfx(const char *driverID, void *data);
-}
+#include "ags/plugins/dll.h"
 
-#endif
\ No newline at end of file
+namespace AGS3 {
+namespace Plugins {
+namespace AGSParallax {
+
+struct Sprite {
+	int x;
+	int y;
+	int slot;
+	int speed;
+};
+
+#define MAX_SPEED 1000
+#define MAX_SPRITES 100
+
+/**
+ * This is not the AGS Parallax plugin by Scorpiorus
+ * but a workalike plugin created for the AGS engine ports.
+ */
+class AGSParallax : public DLL {
+private:
+	static IAGSEngine *_engine;
+	static int _screenWidth;
+	static int _screenHeight;
+	static int _screenColorDepth;
+
+	static bool _enabled;
+	static Sprite _sprites[MAX_SPRITES];
+private:
+	static const char *AGS_GetPluginName();
+	static void AGS_EngineStartup(IAGSEngine *lpEngine);
+	static int AGS_EngineOnEvent(int event, int data);
+
+	static void pxDrawSprite(int id, int x, int y, int slot, int speed);
+	static void pxDeleteSprite(int id);
+
+private:
+	static size_t engineFileRead(void *ptr, size_t size, size_t count, long fileHandle);
+	static size_t engineFileWrite(const void *ptr, size_t size, size_t count, long fileHandle);
+	static void RestoreGame(long fileHandle);
+	static void SaveGame(long file);
+	static void Initialize();
+	static void Draw(bool foreground);
+
+public:
+	AGSParallax();
+};
+
+} // namespace AGSParallax
+} // namespace Plugins
+} // namespace AGS3
+
+#endif


Commit: 64224bb59d0d0ad0cc368565fe6ce24f9524b8c8
    https://github.com/scummvm/scummvm/commit/64224bb59d0d0ad0cc368565fe6ce24f9524b8c8
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Make AGSParallax plugin endian safe

Changed paths:
    engines/ags/plugins/ags_parallax/ags_parallax.cpp
    engines/ags/plugins/ags_parallax/ags_parallax.h


diff --git a/engines/ags/plugins/ags_parallax/ags_parallax.cpp b/engines/ags/plugins/ags_parallax/ags_parallax.cpp
index c4575bf1cd..a07e7382fe 100644
--- a/engines/ags/plugins/ags_parallax/ags_parallax.cpp
+++ b/engines/ags/plugins/ags_parallax/ags_parallax.cpp
@@ -22,6 +22,7 @@
 
 #include "ags/plugins/ags_parallax/ags_parallax.h"
 #include "ags/shared/core/platform.h"
+#include "common/endian.h"
 
 namespace AGS3 {
 namespace Plugins {
@@ -69,8 +70,6 @@ void AGSParallax::AGS_EngineStartup(IAGSEngine *engine) {
 	_engine->RequestEventHook(AGSE_ENTERROOM);
 	_engine->RequestEventHook(AGSE_SAVEGAME);
 	_engine->RequestEventHook(AGSE_RESTOREGAME);
-
-	Initialize();
 }
 
 int AGSParallax::AGS_EngineOnEvent(int event, int data) {
@@ -80,7 +79,7 @@ int AGSParallax::AGS_EngineOnEvent(int event, int data) {
 		Draw(false);
 	} else if (event == AGSE_ENTERROOM) {
 		// Reset all _sprites
-		Initialize();
+		clear();
 	} else if (event == AGSE_PRESCREENDRAW) {
 		// Get screen size once here
 		_engine->GetScreenDimensions(&_screenWidth, &_screenHeight, &_screenColorDepth);
@@ -94,6 +93,15 @@ int AGSParallax::AGS_EngineOnEvent(int event, int data) {
 	return 0;
 }
 
+void AGSParallax::clear() {
+	for (int i = 0; i < MAX_SPRITES; i++) {
+		_sprites[i] = Sprite();
+		_sprites[i].slot = -1;
+	}
+
+	_enabled = false;
+}
+
 size_t AGSParallax::engineFileRead(void *ptr, size_t size, size_t count, long fileHandle) {
 	auto totalBytes = _engine->FRead(ptr, size * count, fileHandle);
 	return totalBytes / size;
@@ -104,38 +112,29 @@ size_t AGSParallax::engineFileWrite(const void *ptr, size_t size, size_t count,
 	return totalBytes / size;
 }
 
-void AGSParallax::RestoreGame(long fileHandle) {
-	unsigned int SaveVersion = 0;
-	engineFileRead(&SaveVersion, sizeof(SaveVersion), 1, fileHandle);
+void AGSParallax::RestoreGame(long file) {
+	byte saveVersion[4];
+	engineFileRead(&saveVersion, 4, 1, file);
 
-	if (SaveVersion != SaveMagic) {
+	if (READ_LE_UINT32(saveVersion) != SaveMagic) {
 		_engine->AbortGame("ags_parallax: bad save.");
 	}
 
-	// TODO: This seems endian/packing unsafe
-	engineFileRead(_sprites, sizeof(Sprite), MAX_SPRITES, fileHandle);
-	engineFileRead(&_enabled, sizeof(bool), 1, fileHandle);
+	for (int i = 0; i < MAX_SPRITES; ++i)
+		_sprites[i].load(_engine, file);
+	engineFileRead(&_enabled, sizeof(bool), 1, file);
 }
 
 void AGSParallax::SaveGame(long file) {
-	warning("TODO: AGSParallax::SaveGame is endian unsafe");
-	engineFileWrite(&SaveMagic, sizeof(SaveMagic), 1, file);
-	engineFileWrite(_sprites, sizeof(Sprite), MAX_SPRITES, file);
-	engineFileWrite(&_enabled, sizeof(bool), 1, file);
-}
-
-
-void AGSParallax::Initialize() {
-	memset(_sprites, 0, sizeof(Sprite) * MAX_SPRITES);
-
-	int i;
-	for (i = 0; i < MAX_SPRITES; i++)
-		_sprites[i].slot = -1;
+	byte saveVersion[4];
+	WRITE_LE_UINT32(saveVersion, SaveMagic);
+	engineFileWrite(&SaveMagic, 4, 1, file);
 
-	_enabled = false;
+	for (int i = 0; i < MAX_SPRITES; ++i)
+		_sprites[i].save(_engine, file);
+	engineFileWrite(&_enabled, 1, 1, file);
 }
 
-
 void AGSParallax::Draw(bool foreground) {
 	if (!_enabled)
 		return;
@@ -166,7 +165,6 @@ void AGSParallax::Draw(bool foreground) {
 	}
 }
 
-
 void AGSParallax::pxDrawSprite(int id, int x, int y, int slot, int speed) {
 #ifdef DEBUG
 	char buffer[200];
@@ -204,6 +202,34 @@ void AGSParallax::pxDeleteSprite(int id) {
 	_sprites[id].slot = -1;
 }
 
+/*------------------------------------------------------------------*/
+
+void Sprite::save(IAGSEngine *engine, long file) {
+	saveInt(engine, file, x);
+	saveInt(engine, file, y);
+	saveInt(engine, file, slot);
+	saveInt(engine, file, speed);
+}
+
+void Sprite::load(IAGSEngine *engine, long file) {
+	x = loadInt(engine, file);
+	y = loadInt(engine, file);
+	slot = loadInt(engine, file);
+	speed = loadInt(engine, file);
+}
+
+void saveInt(IAGSEngine *engine, long file, int value) {
+	byte buf[4];
+	WRITE_LE_INT32(buf, value);
+	engine->FWrite(buf, 4, file);
+}
+
+int loadInt(IAGSEngine *engine, long file) {
+	byte buf[4];
+	engine->FRead(buf, 4, file);
+	return READ_LE_INT32(buf);
+}
+
 } // namespace AGSParallax
 } // namespace Plugins
 } // namespace AGS3
diff --git a/engines/ags/plugins/ags_parallax/ags_parallax.h b/engines/ags/plugins/ags_parallax/ags_parallax.h
index 74d17089ce..2d441e38e0 100644
--- a/engines/ags/plugins/ags_parallax/ags_parallax.h
+++ b/engines/ags/plugins/ags_parallax/ags_parallax.h
@@ -30,10 +30,15 @@ namespace Plugins {
 namespace AGSParallax {
 
 struct Sprite {
-	int x;
-	int y;
-	int slot;
-	int speed;
+	int x = 0;
+	int y = 0;
+	int slot = -1;
+	int speed = 0;
+
+	void save(IAGSEngine *engine, long file);
+	void load(IAGSEngine *engine, long file);
+	void saveInt(IAGSEngine *engine, long file, int value);
+	int loadInt(IAGSEngine *engine, long file);
 };
 
 #define MAX_SPEED 1000
@@ -63,10 +68,10 @@ private:
 private:
 	static size_t engineFileRead(void *ptr, size_t size, size_t count, long fileHandle);
 	static size_t engineFileWrite(const void *ptr, size_t size, size_t count, long fileHandle);
-	static void RestoreGame(long fileHandle);
+	static void RestoreGame(long file);
 	static void SaveGame(long file);
-	static void Initialize();
 	static void Draw(bool foreground);
+	static void clear();
 
 public:
 	AGSParallax();


Commit: c6824e1caff4197795aa979dcc726cdeeebb0814
    https://github.com/scummvm/scummvm/commit/c6824e1caff4197795aa979dcc726cdeeebb0814
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added AGSSnowRain plugin

Changed paths:
  A engines/ags/plugins/ags_snow_rain/weather.cpp
  A engines/ags/plugins/ags_snow_rain/weather.h
    engines/ags/module.mk
    engines/ags/plugins/ags_snow_rain/ags_snow_rain.cpp
    engines/ags/plugins/ags_snow_rain/ags_snow_rain.h
    engines/ags/plugins/dll.cpp


diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 295eab3901..72899f2818 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -306,7 +306,9 @@ MODULE_OBJS = \
 	plugins/ags_flashlight/ags_flashlight.o \
 	plugins/ags_pal_render/ags_pal_render.o \
 	plugins/ags_pal_render/raycast.o \
-	plugins/ags_parallax/ags_parallax.o
+	plugins/ags_parallax/ags_parallax.o \
+	plugins/ags_snow_rain/ags_snow_rain.o \
+	plugins/ags_snow_rain/weather.o
 
 ifdef ENABLE_AGS_TESTS
 MODULE_OBJS += \
diff --git a/engines/ags/plugins/ags_snow_rain/ags_snow_rain.cpp b/engines/ags/plugins/ags_snow_rain/ags_snow_rain.cpp
index bc61dc26be..051a0ed63b 100644
--- a/engines/ags/plugins/ags_snow_rain/ags_snow_rain.cpp
+++ b/engines/ags/plugins/ags_snow_rain/ags_snow_rain.cpp
@@ -1,841 +1,218 @@
-/*
-
-This is not the AGS SnowRain plugin by Scorpiorus (http://www.bigbluecup.com/yabb/index.php?topic=25665.0),
-but a workalike plugin created by JJS for the AGS engine PSP port.
-
-*/
-
-#include "core/platform.h"
-
-#if AGS_PLATFORM_OS_WINDOWS
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#pragma warning(disable : 4244)
-#endif
-
-#if !defined(BUILTIN_PLUGINS)
-#define THIS_IS_THE_PLUGIN
-#endif
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <math.h>
-
-#ifdef PSP_VERSION
-#include <pspsdk.h>
-#include <pspmath.h>
-#define sin(x) vfpu_sinf(x)
-#endif
-
-#include "plugin/agsplugin.h"
-
-#if defined(BUILTIN_PLUGINS)
-namespace ags_snowrain {
-#endif
-
-//#define DEBUG
-//#define AGS_SNOWRAIN_DLL_SAVEGAME_COMPATIBILITY
-
-#define signum(x) ((x > 0) ? 1 : -1)
-
-const unsigned int Magic = 0xCAFE0000;
-const unsigned int Version = 2;
-const unsigned int SaveMagic = Magic + Version;
-const float PI = 3.14159265f;
-
-int screen_width = 320;
-int screen_height = 200;
-int screen_color_depth = 32;
-
-IAGSEngine *engine;
-
-
-typedef struct {
-	int view;
-	int loop;
-	bool is_default;
-	BITMAP *bitmap;
-} view_t;
-
-
-typedef struct {
-	float x;
-	float y;
-	int alpha;
-	float speed;
-	int max_y;
-	int kind_id;
-	int drift;
-	float drift_speed;
-	float drift_offset;
-} drop_t;
-
-
-class Weather {
-public:
-	Weather();
-	Weather(bool IsSnow);
-	~Weather();
-
-	void Initialize();
-	void InitializeParticles();
-
-	void RestoreGame(long file);
-	void SaveGame(long file);
-	bool ReinitializeViews();
-
-	bool IsActive();
-	void Update();
-	void UpdateWithDrift();
-	void EnterRoom();
-
-	void SetDriftRange(int min_value, int max_value);
-	void SetDriftSpeed(int min_value, int max_value);
-	void ChangeAmount(int amount);
-	void SetView(int kind_id, int event, int view, int loop);
-	void SetDefaultView(int view, int loop);
-	void SetTransparency(int min_value, int max_value);
-	void SetWindSpeed(int value);
-	void SetBaseline(int top, int bottom);
-	void SetAmount(int amount);
-	void SetFallSpeed(int min_value, int max_value);
-
-private:
-	void ClipToRange(int &variable, int min, int max);
-
-	bool mIsSnow;
-
-	int mMinDrift;
-	int mMaxDrift;
-	int mDeltaDrift;
-
-	int mMinDriftSpeed;
-	int mMaxDriftSpeed;
-	int mDeltaDriftSpeed;
-
-	int mAmount;
-	int mTargetAmount;
-
-	int mMinAlpha;
-	int mMaxAlpha;
-	int mDeltaAlpha;
-
-	float mWindSpeed;
-
-	int mTopBaseline;
-	int mBottomBaseline;
-	int mDeltaBaseline;
-
-	int mMinFallSpeed;
-	int mMaxFallSpeed;
-	int mDeltaFallSpeed;
-
-	drop_t mParticles[2000];
-	view_t mViews[5];
-
-	bool mViewsInitialized;
-};
-
-
-Weather::Weather() {
-	mIsSnow = false;
-	Initialize();
-}
-
-
-Weather::Weather(bool IsSnow) {
-	mIsSnow = IsSnow;
-	Initialize();
-}
-
-
-Weather::~Weather() = default;
-
-
-void Weather::Update() {
-	if (mTargetAmount > mAmount)
-		mAmount++;
-	else if (mTargetAmount < mAmount)
-		mAmount--;
-
-	if (!ReinitializeViews())
-		return;
-
-	int i;
-	for (i = 0; i < mAmount * 2; i++) {
-		mParticles[i].y += mParticles[i].speed;
-		mParticles[i].x += mWindSpeed;
-
-		if (mParticles[i].x < 0)
-			mParticles[i].x += screen_width;
-
-		if (mParticles[i].x > screen_width - 1)
-			mParticles[i].x -= screen_width;
-
-		if (mParticles[i].y > mParticles[i].max_y) {
-			mParticles[i].y = -1 * (rand() % screen_height);
-			mParticles[i].x = rand() % screen_width;
-			mParticles[i].alpha = rand() % mDeltaAlpha + mMinAlpha;
-			mParticles[i].speed = (float)(rand() % mDeltaFallSpeed + mMinFallSpeed) / 50.0f;
-			mParticles[i].max_y = rand() % mDeltaBaseline + mTopBaseline;
-		} else if ((mParticles[i].y > 0) && (mParticles[i].alpha > 0))
-			engine->BlitSpriteTranslucent(mParticles[i].x, mParticles[i].y, mViews[mParticles[i].kind_id].bitmap, mParticles[i].alpha);
-	}
-
-	engine->MarkRegionDirty(0, 0, screen_width, screen_height);
-}
-
-
-void Weather::UpdateWithDrift() {
-	if (mTargetAmount > mAmount)
-		mAmount++;
-	else if (mTargetAmount < mAmount)
-		mAmount--;
-
-	if (!ReinitializeViews())
-		return;
-
-	int i, drift;
-	for (i = 0; i < mAmount * 2; i++) {
-		mParticles[i].y += mParticles[i].speed;
-		drift = mParticles[i].drift * sin((float)(mParticles[i].y + mParticles[i].drift_offset) * mParticles[i].drift_speed * 2.0f * PI / 360.0f);
-
-		if (signum(mWindSpeed) == signum(drift))
-			mParticles[i].x += mWindSpeed;
-		else
-			mParticles[i].x += mWindSpeed / 4;
-
-		if (mParticles[i].x < 0)
-			mParticles[i].x += screen_width;
-
-		if (mParticles[i].x > screen_width - 1)
-			mParticles[i].x -= screen_width;
-
-		if (mParticles[i].y > mParticles[i].max_y) {
-			mParticles[i].y = -1 * (rand() % screen_height);
-			mParticles[i].x = rand() % screen_width;
-			mParticles[i].alpha = rand() % mDeltaAlpha + mMinAlpha;
-			mParticles[i].speed = (float)(rand() % mDeltaFallSpeed + mMinFallSpeed) / 50.0f;
-			mParticles[i].max_y = rand() % mDeltaBaseline + mTopBaseline;
-			mParticles[i].drift = rand() % mDeltaDrift + mMinDrift;
-			mParticles[i].drift_speed = (rand() % mDeltaDriftSpeed + mMinDriftSpeed) / 50.0f;
-		} else if ((mParticles[i].y > 0) && (mParticles[i].alpha > 0))
-			engine->BlitSpriteTranslucent(mParticles[i].x + drift, mParticles[i].y, mViews[mParticles[i].kind_id].bitmap, mParticles[i].alpha);
-	}
-
-	engine->MarkRegionDirty(0, 0, screen_width, screen_height);
-}
-
-static size_t engineFileRead(void *ptr, size_t size, size_t count, long fileHandle) {
-	auto totalBytes = engine->FRead(ptr, size * count, fileHandle);
-	return totalBytes / size;
-}
-
-static size_t engineFileWrite(const void *ptr, size_t size, size_t count, long fileHandle) {
-	auto totalBytes = engine->FWrite(const_cast<void *>(ptr), size * count, fileHandle);
-	return totalBytes / size;
-}
-
-void Weather::RestoreGame(long file) {
-	unsigned int SaveVersion = 0;
-	engineFileRead(&SaveVersion, sizeof(SaveVersion), 1, file);
-
-	if (SaveVersion != SaveMagic) {
-		engine->AbortGame("ags_snowrain: bad save.");
-	}
-
-	// Current version
-	engineFileRead(&mIsSnow, 4, 1, file);
-	engineFileRead(&mMinDrift, 4, 1, file);
-	engineFileRead(&mMaxDrift, 4, 1, file);
-	engineFileRead(&mDeltaDrift, 4, 1, file);
-	engineFileRead(&mMinDriftSpeed, 4, 1, file);
-	engineFileRead(&mMaxDriftSpeed, 4, 1, file);
-	engineFileRead(&mDeltaDriftSpeed, 4, 1, file);
-	engineFileRead(&mAmount, 4, 1, file);
-	engineFileRead(&mTargetAmount, 4, 1, file);
-	engineFileRead(&mMinAlpha, 4, 1, file);
-	engineFileRead(&mMaxAlpha, 4, 1, file);
-	engineFileRead(&mDeltaAlpha, 4, 1, file);
-	engineFileRead(&mWindSpeed, 4, 1, file);
-	engineFileRead(&mTopBaseline, 4, 1, file);
-	engineFileRead(&mBottomBaseline, 4, 1, file);
-	engineFileRead(&mDeltaBaseline, 4, 1, file);
-	engineFileRead(&mMinFallSpeed, 4, 1, file);
-	engineFileRead(&mMaxFallSpeed, 4, 1, file);
-	engineFileRead(&mDeltaFallSpeed, 4, 1, file);
-	engineFileRead(mViews, sizeof(view_t) * 5, 1, file);
-
-	InitializeParticles();
-}
-
-
-void Weather::SaveGame(long file) {
-	engineFileWrite(&SaveMagic, sizeof(SaveMagic), 1, file);
-
-	engineFileWrite(&mIsSnow, 4, 1, file);
-	engineFileWrite(&mMinDrift, 4, 1, file);
-	engineFileWrite(&mMaxDrift, 4, 1, file);
-	engineFileWrite(&mDeltaDrift, 4, 1, file);
-	engineFileWrite(&mMinDriftSpeed, 4, 1, file);
-	engineFileWrite(&mMaxDriftSpeed, 4, 1, file);
-	engineFileWrite(&mDeltaDriftSpeed, 4, 1, file);
-	engineFileWrite(&mAmount, 4, 1, file);
-	engineFileWrite(&mTargetAmount, 4, 1, file);
-	engineFileWrite(&mMinAlpha, 4, 1, file);
-	engineFileWrite(&mMaxAlpha, 4, 1, file);
-	engineFileWrite(&mDeltaAlpha, 4, 1, file);
-	engineFileWrite(&mWindSpeed, 4, 1, file);
-	engineFileWrite(&mTopBaseline, 4, 1, file);
-	engineFileWrite(&mBottomBaseline, 4, 1, file);
-	engineFileWrite(&mDeltaBaseline, 4, 1, file);
-	engineFileWrite(&mMinFallSpeed, 4, 1, file);
-	engineFileWrite(&mMaxFallSpeed, 4, 1, file);
-	engineFileWrite(&mDeltaFallSpeed, 4, 1, file);
-	engineFileWrite(mViews, sizeof(view_t) * 5, 1, file);
-}
-
-
-bool Weather::ReinitializeViews() {
-	if ((mViews[4].view == -1) || (mViews[4].loop == -1))
-		return false;
-
-	AGSViewFrame *view_frame = engine->GetViewFrame(mViews[4].view, mViews[4].loop, 0);
-	BITMAP *default_bitmap = engine->GetSpriteGraphic(view_frame->pic);
-
-	int i;
-	for (i = 0; i < 5; i++) {
-		if (mViews[i].bitmap != nullptr) {
-			if (mViews[i].is_default)
-				mViews[i].bitmap = default_bitmap;
-			else {
-				view_frame = engine->GetViewFrame(mViews[i].view, mViews[i].loop, 0);
-				mViews[i].bitmap = engine->GetSpriteGraphic(view_frame->pic);
-			}
-		}
-	}
-
-	return true;
-}
-
-
-bool Weather::IsActive() {
-	return (mAmount > 0) || (mTargetAmount != mAmount);
-}
-
-
-void Weather::EnterRoom() {
-	mAmount = mTargetAmount;
-}
-
-
-void Weather::ClipToRange(int &variable, int min, int max) {
-	if (variable < min)
-		variable = min;
-
-	if (variable > max)
-		variable = max;
-}
-
-
-void Weather::Initialize() {
-	SetDriftRange(10, 100);
-	SetDriftSpeed(10, 120);
-
-	SetTransparency(0, 0);
-	SetWindSpeed(0);
-	SetBaseline(0, 200);
-
-	if (mIsSnow)
-		SetFallSpeed(10, 70);
-	else
-		SetFallSpeed(100, 300);
-
-	mViewsInitialized = false;
-
-	int i;
-	for (i = 0; i < 5; i++) {
-		mViews[i].is_default = true;
-		mViews[i].view = -1;
-		mViews[i].loop = -1;
-		mViews[i].bitmap = nullptr;
-	}
-
-	SetAmount(0);
-}
-
-
-void Weather::InitializeParticles() {
-	memset(mParticles, 0, sizeof(drop_t) * 2000);
-	int i;
-	for (i = 0; i < 2000; i++) {
-		mParticles[i].kind_id = rand() % 5;
-		mParticles[i].y = rand() % (screen_height * 2) - screen_height;
-		mParticles[i].x = rand() % screen_width;
-		mParticles[i].alpha = rand() % mDeltaAlpha + mMinAlpha;
-		mParticles[i].speed = (float)(rand() % mDeltaFallSpeed + mMinFallSpeed) / 50.0f;
-		mParticles[i].max_y = rand() % mDeltaBaseline + mTopBaseline;
-		mParticles[i].drift = rand() % mDeltaDrift + mMinDrift;
-		mParticles[i].drift_speed = (rand() % mDeltaDriftSpeed + mMinDriftSpeed) / 50.0f;
-		mParticles[i].drift_offset = rand() % 100;
-	}
-}
-
-
-void Weather::SetDriftRange(int min_value, int max_value) {
-#ifdef DEBUG
-	char buffer[200];
-	sprintf(buffer, "%d %s %d %d\n", (int)mIsSnow, "SetDriftRange", min_value, max_value);
-	engine->PrintDebugConsole(buffer);
-#endif
-
-	ClipToRange(min_value, 0, 100);
-	ClipToRange(max_value, 0, 100);
-
-	if (min_value > max_value)
-		min_value = max_value;
-
-	mMinDrift = min_value / 2;
-	mMaxDrift = max_value / 2;
-	mDeltaDrift = mMaxDrift - mMinDrift;
-
-	if (mDeltaDrift == 0)
-		mDeltaDrift = 1;
-}
-
-
-void Weather::SetDriftSpeed(int min_value, int max_value) {
-#ifdef DEBUG
-	char buffer[200];
-	sprintf(buffer, "%d %s %d %d\n", (int)mIsSnow, "SetDriftSpeed", min_value, max_value);
-	engine->PrintDebugConsole(buffer);
-#endif
-
-	ClipToRange(min_value, 0, 200);
-	ClipToRange(max_value, 0, 200);
-
-	if (min_value > max_value)
-		min_value = max_value;
-
-	mMinDriftSpeed = min_value;
-	mMaxDriftSpeed = max_value;
-	mDeltaDriftSpeed = mMaxDriftSpeed - mMinDriftSpeed;
-
-	if (mDeltaDriftSpeed == 0)
-		mDeltaDriftSpeed = 1;
-}
-
-
-void Weather::ChangeAmount(int amount) {
-#ifdef DEBUG
-	char buffer[200];
-	sprintf(buffer, "%d %s %d\n", (int)mIsSnow, "ChangeAmount", amount);
-	engine->PrintDebugConsole(buffer);
-#endif
-
-	ClipToRange(amount, 0, 1000);
-
-	mTargetAmount = amount;
-}
-
-
-void Weather::SetView(int kind_id, int event, int view, int loop) {
-#ifdef DEBUG
-	char buffer[200];
-	sprintf(buffer, "%d %s %d %d %d %d\n", (int)mIsSnow, "SetView", kind_id, event, view, loop);
-	engine->PrintDebugConsole(buffer);
-#endif
-
-	AGSViewFrame *view_frame = engine->GetViewFrame(view, loop, 0);
-	mViews[kind_id].bitmap = engine->GetSpriteGraphic(view_frame->pic);
-	mViews[kind_id].is_default = false;
-	mViews[kind_id].view = view;
-	mViews[kind_id].loop = loop;
-
-	if (!mViewsInitialized)
-		SetDefaultView(view, loop);
-}
-
-
-void Weather::SetDefaultView(int view, int loop) {
-#ifdef DEBUG
-	char buffer[200];
-	sprintf(buffer, "%d %s %d %d\n", (int)mIsSnow, "SetDefaultView", view, loop);
-	engine->PrintDebugConsole(buffer);
-#endif
-
-	AGSViewFrame *view_frame = engine->GetViewFrame(view, loop, 0);
-	BITMAP *bitmap = engine->GetSpriteGraphic(view_frame->pic);
-
-	mViewsInitialized = true;
-
-	int i;
-	for (i = 0; i < 5; i++) {
-		if (mViews[i].is_default) {
-			mViews[i].view = view;
-			mViews[i].loop = loop;
-			mViews[i].bitmap = bitmap;
-		}
-	}
+/* 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 "ags/plugins/ags_snow_rain/ags_snow_rain.h"
+
+namespace AGS3 {
+namespace Plugins {
+namespace AGSSnowRain {
+
+IAGSEngine *_engine;
+int _screenWidth;
+int _screenHeight;
+int _screenColorDepth;
+
+Weather *AGSSnowRain::_rain;
+Weather *AGSSnowRain::_snow;
+
+AGSSnowRain::AGSSnowRain() : DLL() {
+	_engine = nullptr;
+	_screenWidth = 320;
+	_screenHeight  = 200;
+	_screenColorDepth = 32;
+
+	DLL_METHOD(AGS_GetPluginName);
+	DLL_METHOD(AGS_EngineStartup);
+	DLL_METHOD(AGS_EngineShutdown);
+	DLL_METHOD(AGS_EngineOnEvent);
+}
+
+const char *AGSSnowRain::AGS_GetPluginName() {
+	// Return the plugin description
+	return "Snow/Rain plugin recreation";
 }
 
+void AGSSnowRain::AGS_EngineStartup(IAGSEngine *engine) {
+	_engine = engine;
 
-void Weather::SetTransparency(int min_value, int max_value) {
-#ifdef DEBUG
-	char buffer[200];
-	sprintf(buffer, "%d %s %d %d\n", (int)mIsSnow, "SetTransparency", min_value, max_value);
-	engine->PrintDebugConsole(buffer);
-#endif
+	if (_engine->version < 13)
+		_engine->AbortGame("Engine interface is too old, need newer version of AGS.");
 
-	ClipToRange(min_value, 0, 100);
-	ClipToRange(max_value, 0, 100);
+	SCRIPT_METHOD("srSetSnowDriftRange");
+	SCRIPT_METHOD("srSetSnowDriftSpeed");
+	SCRIPT_METHOD("srSetSnowFallSpeed");
+	SCRIPT_METHOD("srChangeSnowAmount");
+	SCRIPT_METHOD("srSetSnowBaseline");
+	SCRIPT_METHOD("srSetSnowTransparency");
+	SCRIPT_METHOD("srSetSnowDefaultView");
+	SCRIPT_METHOD("srSetSnowWindSpeed");
+	SCRIPT_METHOD("srSetSnowAmount");
+	SCRIPT_METHOD("srSetSnowView");
 
-	if (min_value > max_value)
-		min_value = max_value;
+	SCRIPT_METHOD("srSetRainDriftRange");
+	SCRIPT_METHOD("srSetRainDriftSpeed");
+	SCRIPT_METHOD("srSetRainFallSpeed");
+	SCRIPT_METHOD("srChangeRainAmount");
+	SCRIPT_METHOD("srSetRainBaseline");
+	SCRIPT_METHOD("srSetRainTransparency");
+	SCRIPT_METHOD("srSetRainDefaultView");
+	SCRIPT_METHOD("srSetRainWindSpeed");
+	SCRIPT_METHOD("srSetRainAmount");
+	SCRIPT_METHOD("srSetRainView");
 
-	mMinAlpha = 255 - floor((float)max_value * 2.55f + 0.5f);
-	mMaxAlpha = 255 - floor((float)min_value * 2.55f + 0.5f);
-	mDeltaAlpha = mMaxAlpha - mMinAlpha;
+	SCRIPT_METHOD("srSetWindSpeed");
+	SCRIPT_METHOD("srSetBaseline");
 
-	if (mDeltaAlpha == 0)
-		mDeltaAlpha = 1;
+	_engine->RequestEventHook(AGSE_PREGUIDRAW);
+	_engine->RequestEventHook(AGSE_PRESCREENDRAW);
+	_engine->RequestEventHook(AGSE_ENTERROOM);
+	_engine->RequestEventHook(AGSE_SAVEGAME);
+	_engine->RequestEventHook(AGSE_RESTOREGAME);
 
-	int i;
-	for (i = 0; i < 2000; i++)
-		mParticles[i].alpha = rand() % mDeltaAlpha + mMinAlpha;
+	_rain = new Weather();
+	_snow = new Weather(true);
 }
 
-
-void Weather::SetWindSpeed(int value) {
-#ifdef DEBUG
-	char buffer[200];
-	sprintf(buffer, "%d %s %d\n", (int)mIsSnow, "SetWindSpeed", value);
-	engine->PrintDebugConsole(buffer);
-#endif
-
-	ClipToRange(value, -200, 200);
-
-	mWindSpeed = (float)value / 20.0f;
+void AGSSnowRain::AGS_EngineShutdown() {
+	delete _rain;
+	delete _snow;
 }
 
+int AGSSnowRain::AGS_EngineOnEvent(int event, int data) {
+	if (event == AGSE_PREGUIDRAW) {
+		if (_rain->IsActive())
+			_rain->Update();
 
-void Weather::SetBaseline(int top, int bottom) {
-#ifdef DEBUG
-	char buffer[200];
-	sprintf(buffer, "%d %s %d %d\n", (int)mIsSnow, "SetBaseline", top, bottom);
-	engine->PrintDebugConsole(buffer);
-#endif
-
-	if (screen_height > 0) {
-		ClipToRange(top, 0, screen_height);
-		ClipToRange(bottom, 0, screen_height);
+		if (_snow->IsActive())
+			_snow->UpdateWithDrift();
+	} else if (event == AGSE_ENTERROOM) {
+		_rain->EnterRoom();
+		_snow->EnterRoom();
+	} else if (event == AGSE_RESTOREGAME) {
+		_rain->RestoreGame(data);
+		_snow->RestoreGame(data);
+	} else if (event == AGSE_SAVEGAME) {
+		_rain->SaveGame(data);
+		_snow->SaveGame(data);
+	} else if (event == AGSE_PRESCREENDRAW) {
+		// Get screen size once here
+		_engine->GetScreenDimensions(&_screenWidth, &_screenHeight , &_screenColorDepth);
+		_engine->UnrequestEventHook(AGSE_PRESCREENDRAW);
 	}
 
-	if (top > bottom)
-		top = bottom;
-
-	mTopBaseline = top;
-	mBottomBaseline = bottom;
-	mDeltaBaseline = mBottomBaseline - mTopBaseline;
-
-	if (mDeltaBaseline == 0)
-		mDeltaBaseline = 1;
-}
-
-
-void Weather::SetAmount(int amount) {
-#ifdef DEBUG
-	char buffer[200];
-	sprintf(buffer, "%d %s %d\n", (int)mIsSnow, "SetAmount", amount);
-	engine->PrintDebugConsole(buffer);
-#endif
-
-	ClipToRange(amount, 0, 1000);
-
-	mAmount = mTargetAmount = amount;
-
-	InitializeParticles();
-}
-
-
-void Weather::SetFallSpeed(int min_value, int max_value) {
-#ifdef DEBUG
-	char buffer[200];
-	sprintf(buffer, "%d %s %d %d\n", (int)mIsSnow, "SetFallSpeed", min_value, max_value);
-	engine->PrintDebugConsole(buffer);
-#endif
-
-	ClipToRange(min_value, 0, 1000);
-	ClipToRange(max_value, 0, 1000);
-
-	if (min_value > max_value)
-		min_value = max_value;
-
-	mMinFallSpeed = min_value;
-	mMaxFallSpeed = max_value;
-	mDeltaFallSpeed = mMaxFallSpeed - mMinFallSpeed;
-
-	if (mDeltaFallSpeed == 0)
-		mDeltaFallSpeed = 1;
-}
-
-
-
-Weather *rain;
-Weather *snow;
-
-
-
-
-// ********************************************
-// ************  AGS Interface  ***************
-// ********************************************
-
-void srSetWindSpeed(int value) {
-	snow->SetWindSpeed(value);
-	rain->SetWindSpeed(value);
+	return 0;
 }
 
-void srSetBaseline(int top, int bottom) {
-	snow->SetBaseline(top, bottom);
-	rain->SetBaseline(top, bottom);
-}
 
-void srSetSnowDriftRange(int min_value, int max_value) {
-	snow->SetDriftRange(min_value, max_value);
+void AGSSnowRain::srSetWindSpeed(int value) {
+	_snow->SetWindSpeed(value);
+	_rain->SetWindSpeed(value);
 }
 
-void srSetSnowDriftSpeed(int min_value, int max_value) {
-	snow->SetDriftSpeed(min_value, max_value);
+void AGSSnowRain::srSetBaseline(int top, int bottom) {
+	_snow->SetBaseline(top, bottom);
+	_rain->SetBaseline(top, bottom);
 }
 
-void srChangeSnowAmount(int amount) {
-	snow->ChangeAmount(amount);
+void AGSSnowRain::srSetSnowDriftRange(int min_value, int max_value) {
+	_snow->SetDriftRange(min_value, max_value);
 }
 
-void srSetSnowView(int kind_id, int event, int view, int loop) {
-	snow->SetView(kind_id, event, view, loop);
+void AGSSnowRain::srSetSnowDriftSpeed(int min_value, int max_value) {
+	_snow->SetDriftSpeed(min_value, max_value);
 }
 
-void srSetSnowDefaultView(int view, int loop) {
-	snow->SetDefaultView(view, loop);
+void AGSSnowRain::srChangeSnowAmount(int amount) {
+	_snow->ChangeAmount(amount);
 }
 
-void srSetSnowTransparency(int min_value, int max_value) {
-	snow->SetTransparency(min_value, max_value);
+void AGSSnowRain::srSetSnowView(int kind_id, int event, int view, int loop) {
+	_snow->SetView(kind_id, event, view, loop);
 }
 
-void srSetSnowWindSpeed(int value) {
-	snow->SetWindSpeed(value);
+void AGSSnowRain::srSetSnowDefaultView(int view, int loop) {
+	_snow->SetDefaultView(view, loop);
 }
 
-void srSetSnowBaseline(int top, int bottom) {
-	snow->SetBaseline(top, bottom);
+void AGSSnowRain::srSetSnowTransparency(int min_value, int max_value) {
+	_snow->SetTransparency(min_value, max_value);
 }
 
-void srSetSnowAmount(int amount) {
-	snow->SetAmount(amount);
+void AGSSnowRain::srSetSnowWindSpeed(int value) {
+	_snow->SetWindSpeed(value);
 }
 
-void srSetSnowFallSpeed(int min_value, int max_value) {
-	snow->SetFallSpeed(min_value, max_value);
+void AGSSnowRain::srSetSnowBaseline(int top, int bottom) {
+	_snow->SetBaseline(top, bottom);
 }
 
-void srSetRainDriftRange(int min_value, int max_value) {
-	rain->SetDriftRange(min_value, max_value);
+void AGSSnowRain::srSetSnowAmount(int amount) {
+	_snow->SetAmount(amount);
 }
 
-void srSetRainDriftSpeed(int min_value, int max_value) {
-	rain->SetDriftSpeed(min_value, max_value);
+void AGSSnowRain::srSetSnowFallSpeed(int min_value, int max_value) {
+	_snow->SetFallSpeed(min_value, max_value);
 }
 
-void srChangeRainAmount(int amount) {
-	rain->ChangeAmount(amount);
+void AGSSnowRain::srSetRainDriftRange(int min_value, int max_value) {
+	_rain->SetDriftRange(min_value, max_value);
 }
 
-void srSetRainView(int kind_id, int event, int view, int loop) {
-	rain->SetView(kind_id, event, view, loop);
+void AGSSnowRain::srSetRainDriftSpeed(int min_value, int max_value) {
+	_rain->SetDriftSpeed(min_value, max_value);
 }
 
-void srSetRainDefaultView(int view, int loop) {
-	rain->SetDefaultView(view, loop);
+void AGSSnowRain::srChangeRainAmount(int amount) {
+	_rain->ChangeAmount(amount);
 }
 
-void srSetRainTransparency(int min_value, int max_value) {
-	rain->SetTransparency(min_value, max_value);
+void AGSSnowRain::srSetRainView(int kind_id, int event, int view, int loop) {
+	_rain->SetView(kind_id, event, view, loop);
 }
 
-void srSetRainWindSpeed(int value) {
-	rain->SetWindSpeed(value);
+void AGSSnowRain::srSetRainDefaultView(int view, int loop) {
+	_rain->SetDefaultView(view, loop);
 }
 
-void srSetRainBaseline(int top, int bottom) {
-	rain->SetBaseline(top, bottom);
+void AGSSnowRain::srSetRainTransparency(int min_value, int max_value) {
+	_rain->SetTransparency(min_value, max_value);
 }
 
-void srSetRainAmount(int amount) {
-	rain->SetAmount(amount);
+void AGSSnowRain::srSetRainWindSpeed(int value) {
+	_rain->SetWindSpeed(value);
 }
 
-void srSetRainFallSpeed(int min_value, int max_value) {
-	rain->SetFallSpeed(min_value, max_value);
+void AGSSnowRain::srSetRainBaseline(int top, int bottom) {
+	_rain->SetBaseline(top, bottom);
 }
 
-void AGS_EngineStartup(IAGSEngine *lpEngine) {
-	engine = lpEngine;
-
-	if (engine->version < 13)
-		engine->AbortGame("Engine interface is too old, need newer version of AGS.");
-
-	engine->RegisterScriptFunction("srSetSnowDriftRange", (void *)&srSetSnowDriftRange);
-	engine->RegisterScriptFunction("srSetSnowDriftSpeed", (void *)&srSetSnowDriftSpeed);
-	engine->RegisterScriptFunction("srSetSnowFallSpeed", (void *)&srSetSnowFallSpeed);
-	engine->RegisterScriptFunction("srChangeSnowAmount", (void *)&srChangeSnowAmount);
-	engine->RegisterScriptFunction("srSetSnowBaseline", (void *)&srSetSnowBaseline);
-	engine->RegisterScriptFunction("srSetSnowTransparency", (void *)&srSetSnowTransparency);
-	engine->RegisterScriptFunction("srSetSnowDefaultView", (void *)&srSetSnowDefaultView);
-	engine->RegisterScriptFunction("srSetSnowWindSpeed", (void *)&srSetSnowWindSpeed);
-	engine->RegisterScriptFunction("srSetSnowAmount", (void *)&srSetSnowAmount);
-	engine->RegisterScriptFunction("srSetSnowView", (void *)&srSetSnowView);
-
-	engine->RegisterScriptFunction("srSetRainDriftRange", (void *)&srSetRainDriftRange);
-	engine->RegisterScriptFunction("srSetRainDriftSpeed", (void *)&srSetRainDriftSpeed);
-	engine->RegisterScriptFunction("srSetRainFallSpeed", (void *)&srSetRainFallSpeed);
-	engine->RegisterScriptFunction("srChangeRainAmount", (void *)&srChangeRainAmount);
-	engine->RegisterScriptFunction("srSetRainBaseline", (void *)&srSetRainBaseline);
-	engine->RegisterScriptFunction("srSetRainTransparency", (void *)&srSetRainTransparency);
-	engine->RegisterScriptFunction("srSetRainDefaultView", (void *)&srSetRainDefaultView);
-	engine->RegisterScriptFunction("srSetRainWindSpeed", (void *)&srSetRainWindSpeed);
-	engine->RegisterScriptFunction("srSetRainAmount", (void *)&srSetRainAmount);
-	engine->RegisterScriptFunction("srSetRainView", (void *)&srSetRainView);
-
-	engine->RegisterScriptFunction("srSetWindSpeed", (void *)&srSetWindSpeed);
-	engine->RegisterScriptFunction("srSetBaseline", (void *)&srSetBaseline);
-
-	engine->RequestEventHook(AGSE_PREGUIDRAW);
-	engine->RequestEventHook(AGSE_PRESCREENDRAW);
-	engine->RequestEventHook(AGSE_ENTERROOM);
-	engine->RequestEventHook(AGSE_SAVEGAME);
-	engine->RequestEventHook(AGSE_RESTOREGAME);
-
-	rain = new Weather;
-	snow = new Weather(true);
+void AGSSnowRain::srSetRainAmount(int amount) {
+	_rain->SetAmount(amount);
 }
 
-void AGS_EngineShutdown() {
-	delete rain;
-	delete snow;
+void AGSSnowRain::srSetRainFallSpeed(int min_value, int max_value) {
+	_rain->SetFallSpeed(min_value, max_value);
 }
 
-int AGS_EngineOnEvent(int event, int data) {
-	if (event == AGSE_PREGUIDRAW) {
-		if (rain->IsActive())
-			rain->Update();
-
-		if (snow->IsActive())
-			snow->UpdateWithDrift();
-	} else if (event == AGSE_ENTERROOM) {
-		rain->EnterRoom();
-		snow->EnterRoom();
-	} else if (event == AGSE_RESTOREGAME) {
-		rain->RestoreGame(data);
-		snow->RestoreGame(data);
-	} else if (event == AGSE_SAVEGAME) {
-		rain->SaveGame(data);
-		snow->SaveGame(data);
-	} else if (event == AGSE_PRESCREENDRAW) {
-		// Get screen size once here
-		engine->GetScreenDimensions(&screen_width, &screen_height, &screen_color_depth);
-		engine->UnrequestEventHook(AGSE_PRESCREENDRAW);
-	}
-
-	return 0;
-}
-
-int AGS_EngineDebugHook(const char *scriptName, int lineNum, int reserved) {
-	return 0;
-}
-
-void AGS_EngineInitGfx(const char *driverID, void *data) {
-}
-
-
-
-#if AGS_PLATFORM_OS_WINDOWS && !defined(BUILTIN_PLUGINS)
-
-// ********************************************
-// ***********  Editor Interface  *************
-// ********************************************
-
-const char *scriptHeader =
-    "import void srSetSnowDriftSpeed(int, int);\r\n"
-    "import void srSetSnowDriftRange(int, int);\r\n"
-    "import void srSetSnowFallSpeed(int, int);\r\n"
-    "import void srChangeSnowAmount(int);\r\n"
-    "import void srSetSnowBaseline(int, int);\r\n"
-    "import void srChangeRainAmount(int);\r\n"
-    "import void srSetRainView(int, int, int, int);\r\n"
-    "import void srSetRainTransparency(int, int);\r\n"
-    "import void srSetSnowTransparency(int, int);\r\n"
-    "import void srSetSnowDefaultView(int, int);\r\n"
-    "import void srSetRainDefaultView(int, int);\r\n"
-    "import void srSetRainWindSpeed(int);\r\n"
-    "import void srSetSnowWindSpeed(int);\r\n"
-    "import void srSetWindSpeed(int);\r\n"
-    "import void srSetRainBaseline(int, int);\r\n"
-    "import void srSetBaseline(int, int);\r\n"
-    "import void srSetSnowAmount(int);\r\n"
-    "import void srSetRainAmount(int);\r\n"
-    "import void srSetRainFallSpeed(int, int);\r\n"
-    "import void srSetSnowView(int, int, int, int);\r\n";
-
-
-IAGSEditor *editor;
-
-
-LPCSTR AGS_GetPluginName(void) {
-	// Return the plugin description
-	return "Snow/Rain plugin recreation";
-}
-
-int  AGS_EditorStartup(IAGSEditor *lpEditor) {
-	// User has checked the plugin to use it in their game
-
-	// If it's an earlier version than what we need, abort.
-	if (lpEditor->version < 1)
-		return -1;
-
-	editor = lpEditor;
-	editor->RegisterScriptHeader(scriptHeader);
-
-	// Return 0 to indicate success
-	return 0;
-}
-
-void AGS_EditorShutdown() {
-	// User has un-checked the plugin from their game
-	editor->UnregisterScriptHeader(scriptHeader);
-}
-
-void AGS_EditorProperties(HWND parent) {
-	// User has chosen to view the Properties of the plugin
-	// We could load up an options dialog or something here instead
-	MessageBoxA(parent, "Snow/Rain plugin recreation by JJS", "About", MB_OK | MB_ICONINFORMATION);
-}
-
-int AGS_EditorSaveGame(char *buffer, int bufsize) {
-	// We don't want to save any persistent data
-	return 0;
-}
-
-void AGS_EditorLoadGame(char *buffer, int bufsize) {
-	// Nothing to load for this plugin
-}
-
-#endif
-
-
-#if defined(BUILTIN_PLUGINS)
-} // namespace ags_snowrain
-#endif
+} // namespace AGSSnowRain
+} // namespace Plugins
+} // namespace AGS3
diff --git a/engines/ags/plugins/ags_snow_rain/ags_snow_rain.h b/engines/ags/plugins/ags_snow_rain/ags_snow_rain.h
index 1d198af90b..148e865af7 100644
--- a/engines/ags/plugins/ags_snow_rain/ags_snow_rain.h
+++ b/engines/ags/plugins/ags_snow_rain/ags_snow_rain.h
@@ -1,14 +1,83 @@
-#ifndef AGS_SNOWRAIN_H
-#define AGS_SNOWRAIN_H
+/* 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 "plugin/agsplugin.h"
+#ifndef AGS_PLUGINS_AGS_SNOW_RAIN_AGS_SNOW_RAIN_H
+#define AGS_PLUGINS_AGS_SNOW_RAIN_AGS_SNOW_RAIN_H
 
-namespace ags_snowrain {
-void AGS_EngineStartup(IAGSEngine *lpEngine);
-void AGS_EngineShutdown();
-int AGS_EngineOnEvent(int event, int data);
-int AGS_EngineDebugHook(const char *scriptName, int lineNum, int reserved);
-void AGS_EngineInitGfx(const char *driverID, void *data);
-}
+#include "ags/plugins/dll.h"
+#include "ags/plugins/ags_snow_rain/weather.h"
 
-#endif
\ No newline at end of file
+namespace AGS3 {
+namespace Plugins {
+namespace AGSSnowRain {
+
+extern IAGSEngine *_engine;
+extern int _screenWidth;
+extern int _screenHeight;
+extern int _screenColorDepth;
+
+/**
+ * This is not the original AGS SnowRain plugin, but a workalike
+ * plugin created for the AGS engine PSP port.
+ */
+class AGSSnowRain : public DLL {
+private:
+	static Weather *_rain;
+	static Weather *_snow;
+private:
+	static const char *AGS_GetPluginName();
+	static void AGS_EngineStartup(IAGSEngine *lpEngine);
+	static void AGS_EngineShutdown();
+	static int AGS_EngineOnEvent(int event, int data);
+
+private:
+	static void srSetWindSpeed(int value);
+	static void srSetBaseline(int top, int bottom);
+	static void srSetSnowDriftRange(int min_value, int max_value);
+	static void srSetSnowDriftSpeed(int min_value, int max_value);
+	static void srChangeSnowAmount(int amount);
+	static void srSetSnowView(int kind_id, int event, int view, int loop);
+	static void srSetSnowDefaultView(int view, int loop);
+	static void srSetSnowTransparency(int min_value, int max_value);
+	static void srSetSnowWindSpeed(int value);
+	static void srSetSnowBaseline(int top, int bottom);
+	static void srSetSnowAmount(int amount);
+	static void srSetSnowFallSpeed(int min_value, int max_value);
+	static void srSetRainDriftRange(int min_value, int max_value);
+	static void srSetRainDriftSpeed(int min_value, int max_value);
+	static void srChangeRainAmount(int amount);
+	static void srSetRainView(int kind_id, int event, int view, int loop);
+	static void srSetRainDefaultView(int view, int loop);
+	static void srSetRainTransparency(int min_value, int max_value);
+	static void srSetRainWindSpeed(int value);
+	static void srSetRainBaseline(int top, int bottom);
+	static void srSetRainAmount(int amount);
+	static void srSetRainFallSpeed(int min_value, int max_value);
+public:
+	AGSSnowRain();
+};
+
+} // namespace AGSSnowRain
+} // namespace Plugins
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/plugins/ags_snow_rain/weather.cpp b/engines/ags/plugins/ags_snow_rain/weather.cpp
new file mode 100644
index 0000000000..6771162cf9
--- /dev/null
+++ b/engines/ags/plugins/ags_snow_rain/weather.cpp
@@ -0,0 +1,463 @@
+/* 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 "ags/lib/allegro.h"
+#include "ags/plugins/ags_snow_rain/weather.h"
+#include "ags/plugins/ags_snow_rain/ags_snow_rain.h"
+#include "ags/ags.h"
+
+namespace AGS3 {
+namespace Plugins {
+namespace AGSSnowRain {
+
+#define signum(x) ((x > 0) ? 1 : -1)
+
+const unsigned int Magic = 0xCAFE0000;
+const unsigned int Version = 2;
+const unsigned int SaveMagic = Magic + Version;
+const float PI = 3.14159265f;
+
+Weather::Weather() {
+	mIsSnow = false;
+	Initialize();
+}
+
+Weather::Weather(bool IsSnow) {
+	mIsSnow = IsSnow;
+	Initialize();
+}
+
+Weather::~Weather() = default;
+
+void Weather::Update() {
+	if (mTargetAmount > mAmount)
+		mAmount++;
+	else if (mTargetAmount < mAmount)
+		mAmount--;
+
+	if (!ReinitializeViews())
+		return;
+
+	int i;
+	for (i = 0; i < mAmount * 2; i++) {
+		mParticles[i].y += mParticles[i].speed;
+		mParticles[i].x += mWindSpeed;
+
+		if (mParticles[i].x < 0)
+			mParticles[i].x += _screenWidth;
+
+		if (mParticles[i].x > _screenWidth - 1)
+			mParticles[i].x -= _screenWidth;
+
+		if (mParticles[i].y > mParticles[i].max_y) {
+			mParticles[i].y = -1 * (::AGS::g_vm->getRandomNumber(0x7fffffff) % _screenHeight);
+			mParticles[i].x = ::AGS::g_vm->getRandomNumber(0x7fffffff) % _screenWidth;
+			mParticles[i].alpha = ::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaAlpha + mMinAlpha;
+			mParticles[i].speed = (float)(::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaFallSpeed + mMinFallSpeed) / 50.0f;
+			mParticles[i].max_y = ::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaBaseline + mTopBaseline;
+		} else if ((mParticles[i].y > 0) && (mParticles[i].alpha > 0))
+			_engine->BlitSpriteTranslucent(mParticles[i].x, mParticles[i].y, mViews[mParticles[i].kind_id].bitmap, mParticles[i].alpha);
+	}
+
+	_engine->MarkRegionDirty(0, 0, _screenWidth, _screenHeight);
+}
+
+void Weather::UpdateWithDrift() {
+	if (mTargetAmount > mAmount)
+		mAmount++;
+	else if (mTargetAmount < mAmount)
+		mAmount--;
+
+	if (!ReinitializeViews())
+		return;
+
+	int i, drift;
+	for (i = 0; i < mAmount * 2; i++) {
+		mParticles[i].y += mParticles[i].speed;
+		drift = mParticles[i].drift * sin((float)(mParticles[i].y +
+			mParticles[i].drift_offset) * mParticles[i].drift_speed * 2.0f * PI / 360.0f);
+
+		if (signum(mWindSpeed) == signum(drift))
+			mParticles[i].x += mWindSpeed;
+		else
+			mParticles[i].x += mWindSpeed / 4;
+
+		if (mParticles[i].x < 0)
+			mParticles[i].x += _screenWidth;
+
+		if (mParticles[i].x > _screenWidth - 1)
+			mParticles[i].x -= _screenWidth;
+
+		if (mParticles[i].y > mParticles[i].max_y) {
+			mParticles[i].y = -1 * (::AGS::g_vm->getRandomNumber(0x7fffffff) % _screenHeight);
+			mParticles[i].x = ::AGS::g_vm->getRandomNumber(0x7fffffff) % _screenWidth;
+			mParticles[i].alpha = ::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaAlpha + mMinAlpha;
+			mParticles[i].speed = (float)(::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaFallSpeed + mMinFallSpeed) / 50.0f;
+			mParticles[i].max_y = ::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaBaseline + mTopBaseline;
+			mParticles[i].drift = ::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaDrift + mMinDrift;
+			mParticles[i].drift_speed = (::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaDriftSpeed + mMinDriftSpeed) / 50.0f;
+		} else if ((mParticles[i].y > 0) && (mParticles[i].alpha > 0))
+			_engine->BlitSpriteTranslucent(mParticles[i].x + drift, mParticles[i].y, mViews[mParticles[i].kind_id].bitmap, mParticles[i].alpha);
+	}
+
+	_engine->MarkRegionDirty(0, 0, _screenWidth, _screenHeight);
+}
+
+static size_t engineFileRead(void *ptr, size_t size, size_t count, long fileHandle) {
+	auto totalBytes = _engine->FRead(ptr, size * count, fileHandle);
+	return totalBytes / size;
+}
+
+static size_t engineFileWrite(const void *ptr, size_t size, size_t count, long fileHandle) {
+	auto totalBytes = _engine->FWrite(const_cast<void *>(ptr), size * count, fileHandle);
+	return totalBytes / size;
+}
+
+void Weather::RestoreGame(long file) {
+	unsigned int SaveVersion = 0;
+	engineFileRead(&SaveVersion, sizeof(SaveVersion), 1, file);
+
+	if (SaveVersion != SaveMagic) {
+		_engine->AbortGame("ags_snowrain: bad save.");
+	}
+
+	// Current version
+	engineFileRead(&mIsSnow, 4, 1, file);
+	engineFileRead(&mMinDrift, 4, 1, file);
+	engineFileRead(&mMaxDrift, 4, 1, file);
+	engineFileRead(&mDeltaDrift, 4, 1, file);
+	engineFileRead(&mMinDriftSpeed, 4, 1, file);
+	engineFileRead(&mMaxDriftSpeed, 4, 1, file);
+	engineFileRead(&mDeltaDriftSpeed, 4, 1, file);
+	engineFileRead(&mAmount, 4, 1, file);
+	engineFileRead(&mTargetAmount, 4, 1, file);
+	engineFileRead(&mMinAlpha, 4, 1, file);
+	engineFileRead(&mMaxAlpha, 4, 1, file);
+	engineFileRead(&mDeltaAlpha, 4, 1, file);
+	engineFileRead(&mWindSpeed, 4, 1, file);
+	engineFileRead(&mTopBaseline, 4, 1, file);
+	engineFileRead(&mBottomBaseline, 4, 1, file);
+	engineFileRead(&mDeltaBaseline, 4, 1, file);
+	engineFileRead(&mMinFallSpeed, 4, 1, file);
+	engineFileRead(&mMaxFallSpeed, 4, 1, file);
+	engineFileRead(&mDeltaFallSpeed, 4, 1, file);
+	engineFileRead(mViews, sizeof(View) * 5, 1, file);
+
+	InitializeParticles();
+}
+
+void Weather::SaveGame(long file) {
+	engineFileWrite(&SaveMagic, sizeof(SaveMagic), 1, file);
+
+	engineFileWrite(&mIsSnow, 4, 1, file);
+	engineFileWrite(&mMinDrift, 4, 1, file);
+	engineFileWrite(&mMaxDrift, 4, 1, file);
+	engineFileWrite(&mDeltaDrift, 4, 1, file);
+	engineFileWrite(&mMinDriftSpeed, 4, 1, file);
+	engineFileWrite(&mMaxDriftSpeed, 4, 1, file);
+	engineFileWrite(&mDeltaDriftSpeed, 4, 1, file);
+	engineFileWrite(&mAmount, 4, 1, file);
+	engineFileWrite(&mTargetAmount, 4, 1, file);
+	engineFileWrite(&mMinAlpha, 4, 1, file);
+	engineFileWrite(&mMaxAlpha, 4, 1, file);
+	engineFileWrite(&mDeltaAlpha, 4, 1, file);
+	engineFileWrite(&mWindSpeed, 4, 1, file);
+	engineFileWrite(&mTopBaseline, 4, 1, file);
+	engineFileWrite(&mBottomBaseline, 4, 1, file);
+	engineFileWrite(&mDeltaBaseline, 4, 1, file);
+	engineFileWrite(&mMinFallSpeed, 4, 1, file);
+	engineFileWrite(&mMaxFallSpeed, 4, 1, file);
+	engineFileWrite(&mDeltaFallSpeed, 4, 1, file);
+	engineFileWrite(mViews, sizeof(View) * 5, 1, file);
+}
+
+bool Weather::ReinitializeViews() {
+	if ((mViews[4].view == -1) || (mViews[4].loop == -1))
+		return false;
+
+	AGSViewFrame *view_frame = _engine->GetViewFrame(mViews[4].view, mViews[4].loop, 0);
+	BITMAP *default_bitmap = _engine->GetSpriteGraphic(view_frame->pic);
+
+	int i;
+	for (i = 0; i < 5; i++) {
+		if (mViews[i].bitmap != nullptr) {
+			if (mViews[i].is_default)
+				mViews[i].bitmap = default_bitmap;
+			else {
+				view_frame = _engine->GetViewFrame(mViews[i].view, mViews[i].loop, 0);
+				mViews[i].bitmap = _engine->GetSpriteGraphic(view_frame->pic);
+			}
+		}
+	}
+
+	return true;
+}
+
+bool Weather::IsActive() {
+	return (mAmount > 0) || (mTargetAmount != mAmount);
+}
+
+void Weather::EnterRoom() {
+	mAmount = mTargetAmount;
+}
+
+void Weather::ClipToRange(int &variable, int min, int max) {
+	if (variable < min)
+		variable = min;
+
+	if (variable > max)
+		variable = max;
+}
+
+void Weather::Initialize() {
+	SetDriftRange(10, 100);
+	SetDriftSpeed(10, 120);
+
+	SetTransparency(0, 0);
+	SetWindSpeed(0);
+	SetBaseline(0, 200);
+
+	if (mIsSnow)
+		SetFallSpeed(10, 70);
+	else
+		SetFallSpeed(100, 300);
+
+	mViewsInitialized = false;
+
+	int i;
+	for (i = 0; i < 5; i++) {
+		mViews[i].is_default = true;
+		mViews[i].view = -1;
+		mViews[i].loop = -1;
+		mViews[i].bitmap = nullptr;
+	}
+
+	SetAmount(0);
+}
+
+void Weather::InitializeParticles() {
+	memset(mParticles, 0, sizeof(Drop) * 2000);
+	int i;
+	for (i = 0; i < 2000; i++) {
+		mParticles[i].kind_id = ::AGS::g_vm->getRandomNumber(0x7fffffff) % 5;
+		mParticles[i].y = ::AGS::g_vm->getRandomNumber(0x7fffffff) % (_screenHeight * 2) - _screenHeight;
+		mParticles[i].x = ::AGS::g_vm->getRandomNumber(0x7fffffff) % _screenWidth;
+		mParticles[i].alpha = ::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaAlpha + mMinAlpha;
+		mParticles[i].speed = (float)(::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaFallSpeed + mMinFallSpeed) / 50.0f;
+		mParticles[i].max_y = ::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaBaseline + mTopBaseline;
+		mParticles[i].drift = ::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaDrift + mMinDrift;
+		mParticles[i].drift_speed = (::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaDriftSpeed + mMinDriftSpeed) / 50.0f;
+		mParticles[i].drift_offset = ::AGS::g_vm->getRandomNumber(0x7fffffff) % 100;
+	}
+}
+
+void Weather::SetDriftRange(int min_value, int max_value) {
+#ifdef DEBUG
+	char buffer[200];
+	sprintf(buffer, "%d %s %d %d\n", (int)mIsSnow, "SetDriftRange", min_value, max_value);
+	_engine->PrintDebugConsole(buffer);
+#endif
+
+	ClipToRange(min_value, 0, 100);
+	ClipToRange(max_value, 0, 100);
+
+	if (min_value > max_value)
+		min_value = max_value;
+
+	mMinDrift = min_value / 2;
+	mMaxDrift = max_value / 2;
+	mDeltaDrift = mMaxDrift - mMinDrift;
+
+	if (mDeltaDrift == 0)
+		mDeltaDrift = 1;
+}
+
+void Weather::SetDriftSpeed(int min_value, int max_value) {
+#ifdef DEBUG
+	char buffer[200];
+	sprintf(buffer, "%d %s %d %d\n", (int)mIsSnow, "SetDriftSpeed", min_value, max_value);
+	_engine->PrintDebugConsole(buffer);
+#endif
+
+	ClipToRange(min_value, 0, 200);
+	ClipToRange(max_value, 0, 200);
+
+	if (min_value > max_value)
+		min_value = max_value;
+
+	mMinDriftSpeed = min_value;
+	mMaxDriftSpeed = max_value;
+	mDeltaDriftSpeed = mMaxDriftSpeed - mMinDriftSpeed;
+
+	if (mDeltaDriftSpeed == 0)
+		mDeltaDriftSpeed = 1;
+}
+
+void Weather::ChangeAmount(int amount) {
+#ifdef DEBUG
+	char buffer[200];
+	sprintf(buffer, "%d %s %d\n", (int)mIsSnow, "ChangeAmount", amount);
+	_engine->PrintDebugConsole(buffer);
+#endif
+
+	ClipToRange(amount, 0, 1000);
+
+	mTargetAmount = amount;
+}
+
+void Weather::SetView(int kind_id, int event, int view, int loop) {
+#ifdef DEBUG
+	char buffer[200];
+	sprintf(buffer, "%d %s %d %d %d %d\n", (int)mIsSnow, "SetView", kind_id, event, view, loop);
+	_engine->PrintDebugConsole(buffer);
+#endif
+
+	AGSViewFrame *view_frame = _engine->GetViewFrame(view, loop, 0);
+	mViews[kind_id].bitmap = _engine->GetSpriteGraphic(view_frame->pic);
+	mViews[kind_id].is_default = false;
+	mViews[kind_id].view = view;
+	mViews[kind_id].loop = loop;
+
+	if (!mViewsInitialized)
+		SetDefaultView(view, loop);
+}
+
+void Weather::SetDefaultView(int view, int loop) {
+#ifdef DEBUG
+	char buffer[200];
+	sprintf(buffer, "%d %s %d %d\n", (int)mIsSnow, "SetDefaultView", view, loop);
+	_engine->PrintDebugConsole(buffer);
+#endif
+
+	AGSViewFrame *view_frame = _engine->GetViewFrame(view, loop, 0);
+	BITMAP *bitmap = _engine->GetSpriteGraphic(view_frame->pic);
+
+	mViewsInitialized = true;
+
+	int i;
+	for (i = 0; i < 5; i++) {
+		if (mViews[i].is_default) {
+			mViews[i].view = view;
+			mViews[i].loop = loop;
+			mViews[i].bitmap = bitmap;
+		}
+	}
+}
+
+void Weather::SetTransparency(int min_value, int max_value) {
+#ifdef DEBUG
+	char buffer[200];
+	sprintf(buffer, "%d %s %d %d\n", (int)mIsSnow, "SetTransparency", min_value, max_value);
+	_engine->PrintDebugConsole(buffer);
+#endif
+
+	ClipToRange(min_value, 0, 100);
+	ClipToRange(max_value, 0, 100);
+
+	if (min_value > max_value)
+		min_value = max_value;
+
+	mMinAlpha = 255 - floor((float)max_value * 2.55f + 0.5f);
+	mMaxAlpha = 255 - floor((float)min_value * 2.55f + 0.5f);
+	mDeltaAlpha = mMaxAlpha - mMinAlpha;
+
+	if (mDeltaAlpha == 0)
+		mDeltaAlpha = 1;
+
+	int i;
+	for (i = 0; i < 2000; i++)
+		mParticles[i].alpha = ::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaAlpha + mMinAlpha;
+}
+
+void Weather::SetWindSpeed(int value) {
+#ifdef DEBUG
+	char buffer[200];
+	sprintf(buffer, "%d %s %d\n", (int)mIsSnow, "SetWindSpeed", value);
+	_engine->PrintDebugConsole(buffer);
+#endif
+
+	ClipToRange(value, -200, 200);
+
+	mWindSpeed = (float)value / 20.0f;
+}
+
+void Weather::SetBaseline(int top, int bottom) {
+#ifdef DEBUG
+	char buffer[200];
+	sprintf(buffer, "%d %s %d %d\n", (int)mIsSnow, "SetBaseline", top, bottom);
+	_engine->PrintDebugConsole(buffer);
+#endif
+
+	if (_screenHeight > 0) {
+		ClipToRange(top, 0, _screenHeight);
+		ClipToRange(bottom, 0, _screenHeight);
+	}
+
+	if (top > bottom)
+		top = bottom;
+
+	mTopBaseline = top;
+	mBottomBaseline = bottom;
+	mDeltaBaseline = mBottomBaseline - mTopBaseline;
+
+	if (mDeltaBaseline == 0)
+		mDeltaBaseline = 1;
+}
+
+void Weather::SetAmount(int amount) {
+#ifdef DEBUG
+	char buffer[200];
+	sprintf(buffer, "%d %s %d\n", (int)mIsSnow, "SetAmount", amount);
+	_engine->PrintDebugConsole(buffer);
+#endif
+
+	ClipToRange(amount, 0, 1000);
+
+	mAmount = mTargetAmount = amount;
+
+	InitializeParticles();
+}
+
+void Weather::SetFallSpeed(int min_value, int max_value) {
+#ifdef DEBUG
+	char buffer[200];
+	sprintf(buffer, "%d %s %d %d\n", (int)mIsSnow, "SetFallSpeed", min_value, max_value);
+	_engine->PrintDebugConsole(buffer);
+#endif
+
+	ClipToRange(min_value, 0, 1000);
+	ClipToRange(max_value, 0, 1000);
+
+	if (min_value > max_value)
+		min_value = max_value;
+
+	mMinFallSpeed = min_value;
+	mMaxFallSpeed = max_value;
+	mDeltaFallSpeed = mMaxFallSpeed - mMinFallSpeed;
+
+	if (mDeltaFallSpeed == 0)
+		mDeltaFallSpeed = 1;
+}
+
+} // namespace AGSSnowRain
+} // namespace Plugins
+} // namespace AGS3
diff --git a/engines/ags/plugins/ags_snow_rain/weather.h b/engines/ags/plugins/ags_snow_rain/weather.h
new file mode 100644
index 0000000000..c05879e2ce
--- /dev/null
+++ b/engines/ags/plugins/ags_snow_rain/weather.h
@@ -0,0 +1,120 @@
+/* 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 AGS_PLUGINS_AGS_SNOW_RAIN_WEATHER_H
+#define AGS_PLUGINS_AGS_SNOW_RAIN_WEATHER_H
+
+#include "ags/plugins/dll.h"
+
+namespace AGS3 {
+namespace Plugins {
+namespace AGSSnowRain {
+
+struct View {
+	int view = 0;
+	int loop = 0;
+	bool is_default = false;
+	BITMAP *bitmap = nullptr;
+};
+
+struct Drop {
+	float x = 0;
+	float y = 0;
+	int alpha = 0;
+	float speed = 0;
+	int max_y = 0;
+	int kind_id = 0;
+	int drift = 0;
+	float drift_speed = 0;
+	float drift_offset = 0;
+};
+
+class Weather {
+public:
+	Weather();
+	Weather(bool IsSnow);
+	~Weather();
+
+	void Initialize();
+	void InitializeParticles();
+
+	void RestoreGame(long file);
+	void SaveGame(long file);
+	bool ReinitializeViews();
+
+	bool IsActive();
+	void Update();
+	void UpdateWithDrift();
+	void EnterRoom();
+
+	void SetDriftRange(int min_value, int max_value);
+	void SetDriftSpeed(int min_value, int max_value);
+	void ChangeAmount(int amount);
+	void SetView(int kind_id, int event, int view, int loop);
+	void SetDefaultView(int view, int loop);
+	void SetTransparency(int min_value, int max_value);
+	void SetWindSpeed(int value);
+	void SetBaseline(int top, int bottom);
+	void SetAmount(int amount);
+	void SetFallSpeed(int min_value, int max_value);
+
+private:
+	void ClipToRange(int &variable, int min, int max);
+
+	bool mIsSnow;
+
+	int mMinDrift;
+	int mMaxDrift;
+	int mDeltaDrift;
+
+	int mMinDriftSpeed;
+	int mMaxDriftSpeed;
+	int mDeltaDriftSpeed;
+
+	int mAmount;
+	int mTargetAmount;
+
+	int mMinAlpha;
+	int mMaxAlpha;
+	int mDeltaAlpha;
+
+	float mWindSpeed;
+
+	int mTopBaseline;
+	int mBottomBaseline;
+	int mDeltaBaseline;
+
+	int mMinFallSpeed;
+	int mMaxFallSpeed;
+	int mDeltaFallSpeed;
+
+	Drop mParticles[2000];
+	View mViews[5];
+
+	bool mViewsInitialized;
+};
+
+} // namespace AGSSnowRain
+} // namespace Plugins
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/plugins/dll.cpp b/engines/ags/plugins/dll.cpp
index 74217cd2ee..4d3554b5ce 100644
--- a/engines/ags/plugins/dll.cpp
+++ b/engines/ags/plugins/dll.cpp
@@ -26,6 +26,7 @@
 #include "ags/plugins/ags_creditz/ags_creditz.h"
 #include "ags/plugins/ags_flashlight/ags_flashlight.h"
 #include "ags/plugins/ags_pal_render/ags_pal_render.h"
+#include "ags/plugins/ags_snow_rain/ags_snow_rain.h"
 #include "ags/ags.h"
 #include "ags/detection.h"
 #include "common/str.h"
@@ -62,6 +63,9 @@ void *dlopen(const char *filename) {
 	if (fname.equalsIgnoreCase("libAGSPalRender.so"))
 		return new AGSPalRender::AGSPalRender();
 
+	if (fname.equalsIgnoreCase("libAGSSnowRain.so"))
+		return new AGSSnowRain::AGSSnowRain();
+
 	return nullptr;
 }
 


Commit: 08caa53082ec18ff539cf22b321450b6b55fd4cd
    https://github.com/scummvm/scummvm/commit/08caa53082ec18ff539cf22b321450b6b55fd4cd
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Made AGSSnowRain endian safe

Changed paths:
  A engines/ags/plugins/serializer.h
    engines/ags/plugins/ags_snow_rain/ags_snow_rain.cpp
    engines/ags/plugins/ags_snow_rain/weather.cpp
    engines/ags/plugins/ags_snow_rain/weather.h


diff --git a/engines/ags/plugins/ags_snow_rain/ags_snow_rain.cpp b/engines/ags/plugins/ags_snow_rain/ags_snow_rain.cpp
index 051a0ed63b..36caa39999 100644
--- a/engines/ags/plugins/ags_snow_rain/ags_snow_rain.cpp
+++ b/engines/ags/plugins/ags_snow_rain/ags_snow_rain.cpp
@@ -108,11 +108,13 @@ int AGSSnowRain::AGS_EngineOnEvent(int event, int data) {
 		_rain->EnterRoom();
 		_snow->EnterRoom();
 	} else if (event == AGSE_RESTOREGAME) {
-		_rain->RestoreGame(data);
-		_snow->RestoreGame(data);
+		Serializer s(_engine, data, true);
+		_rain->SyncGame(s);
+		_snow->SyncGame(s);
 	} else if (event == AGSE_SAVEGAME) {
-		_rain->SaveGame(data);
-		_snow->SaveGame(data);
+		Serializer s(_engine, data, false);
+		_rain->SyncGame(s);
+		_snow->SyncGame(s);
 	} else if (event == AGSE_PRESCREENDRAW) {
 		// Get screen size once here
 		_engine->GetScreenDimensions(&_screenWidth, &_screenHeight , &_screenColorDepth);
diff --git a/engines/ags/plugins/ags_snow_rain/weather.cpp b/engines/ags/plugins/ags_snow_rain/weather.cpp
index 6771162cf9..5b76e6ce5c 100644
--- a/engines/ags/plugins/ags_snow_rain/weather.cpp
+++ b/engines/ags/plugins/ags_snow_rain/weather.cpp
@@ -36,175 +36,156 @@ const unsigned int Version = 2;
 const unsigned int SaveMagic = Magic + Version;
 const float PI = 3.14159265f;
 
-Weather::Weather() {
-	mIsSnow = false;
+
+void View::SyncGame(Serializer &s) {
+	s.syncAsInt(view);
+	s.syncAsInt(loop);
+	s.syncAsBool(is_default);
+
+	// Pointer saved/loaded raw structure, which included bitmap pointer
+	int dummy = 0;
+	s.syncAsInt(dummy);
+}
+
+/*------------------------------------------------------------------*/
+
+Weather::Weather() : _mIsSnow(false) {
 	Initialize();
 }
 
-Weather::Weather(bool IsSnow) {
-	mIsSnow = IsSnow;
+Weather::Weather(bool IsSnow) : _mIsSnow(IsSnow) {
 	Initialize();
 }
 
 Weather::~Weather() = default;
 
 void Weather::Update() {
-	if (mTargetAmount > mAmount)
-		mAmount++;
-	else if (mTargetAmount < mAmount)
-		mAmount--;
+	if (_mTargetAmount > _mAmount)
+		_mAmount++;
+	else if (_mTargetAmount < _mAmount)
+		_mAmount--;
 
 	if (!ReinitializeViews())
 		return;
 
 	int i;
-	for (i = 0; i < mAmount * 2; i++) {
-		mParticles[i].y += mParticles[i].speed;
-		mParticles[i].x += mWindSpeed;
-
-		if (mParticles[i].x < 0)
-			mParticles[i].x += _screenWidth;
-
-		if (mParticles[i].x > _screenWidth - 1)
-			mParticles[i].x -= _screenWidth;
-
-		if (mParticles[i].y > mParticles[i].max_y) {
-			mParticles[i].y = -1 * (::AGS::g_vm->getRandomNumber(0x7fffffff) % _screenHeight);
-			mParticles[i].x = ::AGS::g_vm->getRandomNumber(0x7fffffff) % _screenWidth;
-			mParticles[i].alpha = ::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaAlpha + mMinAlpha;
-			mParticles[i].speed = (float)(::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaFallSpeed + mMinFallSpeed) / 50.0f;
-			mParticles[i].max_y = ::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaBaseline + mTopBaseline;
-		} else if ((mParticles[i].y > 0) && (mParticles[i].alpha > 0))
-			_engine->BlitSpriteTranslucent(mParticles[i].x, mParticles[i].y, mViews[mParticles[i].kind_id].bitmap, mParticles[i].alpha);
+	for (i = 0; i < _mAmount * 2; i++) {
+		_mParticles[i].y += _mParticles[i].speed;
+		_mParticles[i].x += _mWindSpeed;
+
+		if (_mParticles[i].x < 0)
+			_mParticles[i].x += _screenWidth;
+
+		if (_mParticles[i].x > _screenWidth - 1)
+			_mParticles[i].x -= _screenWidth;
+
+		if (_mParticles[i].y > _mParticles[i].max_y) {
+			_mParticles[i].y = -1 * (::AGS::g_vm->getRandomNumber(0x7fffffff) % _screenHeight);
+			_mParticles[i].x = ::AGS::g_vm->getRandomNumber(0x7fffffff) % _screenWidth;
+			_mParticles[i].alpha = ::AGS::g_vm->getRandomNumber(0x7fffffff) % _mDeltaAlpha + _mMinAlpha;
+			_mParticles[i].speed = (float)(::AGS::g_vm->getRandomNumber(0x7fffffff) % _mDeltaFallSpeed + _mMinFallSpeed) / 50.0f;
+			_mParticles[i].max_y = ::AGS::g_vm->getRandomNumber(0x7fffffff) % _mDeltaBaseline + _mTopBaseline;
+		} else if ((_mParticles[i].y > 0) && (_mParticles[i].alpha > 0))
+			_engine->BlitSpriteTranslucent(_mParticles[i].x, _mParticles[i].y, _mViews[_mParticles[i].kind_id].bitmap, _mParticles[i].alpha);
 	}
 
 	_engine->MarkRegionDirty(0, 0, _screenWidth, _screenHeight);
 }
 
 void Weather::UpdateWithDrift() {
-	if (mTargetAmount > mAmount)
-		mAmount++;
-	else if (mTargetAmount < mAmount)
-		mAmount--;
+	if (_mTargetAmount > _mAmount)
+		_mAmount++;
+	else if (_mTargetAmount < _mAmount)
+		_mAmount--;
 
 	if (!ReinitializeViews())
 		return;
 
 	int i, drift;
-	for (i = 0; i < mAmount * 2; i++) {
-		mParticles[i].y += mParticles[i].speed;
-		drift = mParticles[i].drift * sin((float)(mParticles[i].y +
-			mParticles[i].drift_offset) * mParticles[i].drift_speed * 2.0f * PI / 360.0f);
+	for (i = 0; i < _mAmount * 2; i++) {
+		_mParticles[i].y += _mParticles[i].speed;
+		drift = _mParticles[i].drift * sin((float)(_mParticles[i].y +
+			_mParticles[i].drift_offset) * _mParticles[i].drift_speed * 2.0f * PI / 360.0f);
 
-		if (signum(mWindSpeed) == signum(drift))
-			mParticles[i].x += mWindSpeed;
+		if (signum(_mWindSpeed) == signum(drift))
+			_mParticles[i].x += _mWindSpeed;
 		else
-			mParticles[i].x += mWindSpeed / 4;
-
-		if (mParticles[i].x < 0)
-			mParticles[i].x += _screenWidth;
-
-		if (mParticles[i].x > _screenWidth - 1)
-			mParticles[i].x -= _screenWidth;
-
-		if (mParticles[i].y > mParticles[i].max_y) {
-			mParticles[i].y = -1 * (::AGS::g_vm->getRandomNumber(0x7fffffff) % _screenHeight);
-			mParticles[i].x = ::AGS::g_vm->getRandomNumber(0x7fffffff) % _screenWidth;
-			mParticles[i].alpha = ::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaAlpha + mMinAlpha;
-			mParticles[i].speed = (float)(::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaFallSpeed + mMinFallSpeed) / 50.0f;
-			mParticles[i].max_y = ::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaBaseline + mTopBaseline;
-			mParticles[i].drift = ::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaDrift + mMinDrift;
-			mParticles[i].drift_speed = (::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaDriftSpeed + mMinDriftSpeed) / 50.0f;
-		} else if ((mParticles[i].y > 0) && (mParticles[i].alpha > 0))
-			_engine->BlitSpriteTranslucent(mParticles[i].x + drift, mParticles[i].y, mViews[mParticles[i].kind_id].bitmap, mParticles[i].alpha);
+			_mParticles[i].x += _mWindSpeed / 4;
+
+		if (_mParticles[i].x < 0)
+			_mParticles[i].x += _screenWidth;
+
+		if (_mParticles[i].x > _screenWidth - 1)
+			_mParticles[i].x -= _screenWidth;
+
+		if (_mParticles[i].y > _mParticles[i].max_y) {
+			_mParticles[i].y = -1 * (::AGS::g_vm->getRandomNumber(0x7fffffff) % _screenHeight);
+			_mParticles[i].x = ::AGS::g_vm->getRandomNumber(0x7fffffff) % _screenWidth;
+			_mParticles[i].alpha = ::AGS::g_vm->getRandomNumber(0x7fffffff) % _mDeltaAlpha + _mMinAlpha;
+			_mParticles[i].speed = (float)(::AGS::g_vm->getRandomNumber(0x7fffffff) % _mDeltaFallSpeed + _mMinFallSpeed) / 50.0f;
+			_mParticles[i].max_y = ::AGS::g_vm->getRandomNumber(0x7fffffff) % _mDeltaBaseline + _mTopBaseline;
+			_mParticles[i].drift = ::AGS::g_vm->getRandomNumber(0x7fffffff) % _mDeltaDrift + _mMinDrift;
+			_mParticles[i].drift_speed = (::AGS::g_vm->getRandomNumber(0x7fffffff) % _mDeltaDriftSpeed + _mMinDriftSpeed) / 50.0f;
+		} else if ((_mParticles[i].y > 0) && (_mParticles[i].alpha > 0))
+			_engine->BlitSpriteTranslucent(_mParticles[i].x + drift, _mParticles[i].y, _mViews[_mParticles[i].kind_id].bitmap, _mParticles[i].alpha);
 	}
 
 	_engine->MarkRegionDirty(0, 0, _screenWidth, _screenHeight);
 }
 
-static size_t engineFileRead(void *ptr, size_t size, size_t count, long fileHandle) {
-	auto totalBytes = _engine->FRead(ptr, size * count, fileHandle);
-	return totalBytes / size;
-}
-
-static size_t engineFileWrite(const void *ptr, size_t size, size_t count, long fileHandle) {
-	auto totalBytes = _engine->FWrite(const_cast<void *>(ptr), size * count, fileHandle);
-	return totalBytes / size;
-}
-
-void Weather::RestoreGame(long file) {
-	unsigned int SaveVersion = 0;
-	engineFileRead(&SaveVersion, sizeof(SaveVersion), 1, file);
+void Weather::SyncGame(Serializer &s) {
+	int saveVersion = 0;
+	s.syncAsInt(saveVersion);
 
-	if (SaveVersion != SaveMagic) {
+	if (s.isLoading() && saveVersion != SaveMagic) {
 		_engine->AbortGame("ags_snowrain: bad save.");
+		return;
 	}
 
-	// Current version
-	engineFileRead(&mIsSnow, 4, 1, file);
-	engineFileRead(&mMinDrift, 4, 1, file);
-	engineFileRead(&mMaxDrift, 4, 1, file);
-	engineFileRead(&mDeltaDrift, 4, 1, file);
-	engineFileRead(&mMinDriftSpeed, 4, 1, file);
-	engineFileRead(&mMaxDriftSpeed, 4, 1, file);
-	engineFileRead(&mDeltaDriftSpeed, 4, 1, file);
-	engineFileRead(&mAmount, 4, 1, file);
-	engineFileRead(&mTargetAmount, 4, 1, file);
-	engineFileRead(&mMinAlpha, 4, 1, file);
-	engineFileRead(&mMaxAlpha, 4, 1, file);
-	engineFileRead(&mDeltaAlpha, 4, 1, file);
-	engineFileRead(&mWindSpeed, 4, 1, file);
-	engineFileRead(&mTopBaseline, 4, 1, file);
-	engineFileRead(&mBottomBaseline, 4, 1, file);
-	engineFileRead(&mDeltaBaseline, 4, 1, file);
-	engineFileRead(&mMinFallSpeed, 4, 1, file);
-	engineFileRead(&mMaxFallSpeed, 4, 1, file);
-	engineFileRead(&mDeltaFallSpeed, 4, 1, file);
-	engineFileRead(mViews, sizeof(View) * 5, 1, file);
-
-	InitializeParticles();
-}
-
-void Weather::SaveGame(long file) {
-	engineFileWrite(&SaveMagic, sizeof(SaveMagic), 1, file);
-
-	engineFileWrite(&mIsSnow, 4, 1, file);
-	engineFileWrite(&mMinDrift, 4, 1, file);
-	engineFileWrite(&mMaxDrift, 4, 1, file);
-	engineFileWrite(&mDeltaDrift, 4, 1, file);
-	engineFileWrite(&mMinDriftSpeed, 4, 1, file);
-	engineFileWrite(&mMaxDriftSpeed, 4, 1, file);
-	engineFileWrite(&mDeltaDriftSpeed, 4, 1, file);
-	engineFileWrite(&mAmount, 4, 1, file);
-	engineFileWrite(&mTargetAmount, 4, 1, file);
-	engineFileWrite(&mMinAlpha, 4, 1, file);
-	engineFileWrite(&mMaxAlpha, 4, 1, file);
-	engineFileWrite(&mDeltaAlpha, 4, 1, file);
-	engineFileWrite(&mWindSpeed, 4, 1, file);
-	engineFileWrite(&mTopBaseline, 4, 1, file);
-	engineFileWrite(&mBottomBaseline, 4, 1, file);
-	engineFileWrite(&mDeltaBaseline, 4, 1, file);
-	engineFileWrite(&mMinFallSpeed, 4, 1, file);
-	engineFileWrite(&mMaxFallSpeed, 4, 1, file);
-	engineFileWrite(&mDeltaFallSpeed, 4, 1, file);
-	engineFileWrite(mViews, sizeof(View) * 5, 1, file);
+	// TODO: At some point check whether the original did a packed
+	// structure for Weather, or if bools were padded to 4 bytes
+	s.syncAsBool(_mIsSnow);
+	s.syncAsInt(_mMinDrift);
+	s.syncAsInt(_mMaxDrift);
+	s.syncAsInt(_mDeltaDrift);
+	s.syncAsInt(_mMinDriftSpeed);
+	s.syncAsInt(_mMaxDriftSpeed);
+	s.syncAsInt(_mDeltaDriftSpeed);
+	s.syncAsInt(_mAmount);
+	s.syncAsInt(_mTargetAmount);
+	s.syncAsInt(_mMinAlpha);
+	s.syncAsInt(_mMaxAlpha);
+	s.syncAsInt(_mDeltaAlpha);
+	s.syncAsFloat(_mWindSpeed);
+	s.syncAsInt(_mTopBaseline);
+	s.syncAsInt(_mBottomBaseline);
+	s.syncAsInt(_mDeltaBaseline);
+	s.syncAsInt(_mMinFallSpeed);
+	s.syncAsInt(_mMaxFallSpeed);
+	s.syncAsInt(_mDeltaFallSpeed);
+
+	for (int i = 0; i < 5; ++i)
+		_mViews[i].SyncGame(s);
+
+	if (s.isLoading())
+		InitializeParticles();
 }
 
 bool Weather::ReinitializeViews() {
-	if ((mViews[4].view == -1) || (mViews[4].loop == -1))
+	if ((_mViews[4].view == -1) || (_mViews[4].loop == -1))
 		return false;
 
-	AGSViewFrame *view_frame = _engine->GetViewFrame(mViews[4].view, mViews[4].loop, 0);
+	AGSViewFrame *view_frame = _engine->GetViewFrame(_mViews[4].view, _mViews[4].loop, 0);
 	BITMAP *default_bitmap = _engine->GetSpriteGraphic(view_frame->pic);
 
 	int i;
 	for (i = 0; i < 5; i++) {
-		if (mViews[i].bitmap != nullptr) {
-			if (mViews[i].is_default)
-				mViews[i].bitmap = default_bitmap;
+		if (_mViews[i].bitmap != nullptr) {
+			if (_mViews[i].is_default)
+				_mViews[i].bitmap = default_bitmap;
 			else {
-				view_frame = _engine->GetViewFrame(mViews[i].view, mViews[i].loop, 0);
-				mViews[i].bitmap = _engine->GetSpriteGraphic(view_frame->pic);
+				view_frame = _engine->GetViewFrame(_mViews[i].view, _mViews[i].loop, 0);
+				_mViews[i].bitmap = _engine->GetSpriteGraphic(view_frame->pic);
 			}
 		}
 	}
@@ -213,11 +194,11 @@ bool Weather::ReinitializeViews() {
 }
 
 bool Weather::IsActive() {
-	return (mAmount > 0) || (mTargetAmount != mAmount);
+	return (_mAmount > 0) || (_mTargetAmount != _mAmount);
 }
 
 void Weather::EnterRoom() {
-	mAmount = mTargetAmount;
+	_mAmount = _mTargetAmount;
 }
 
 void Weather::ClipToRange(int &variable, int min, int max) {
@@ -236,37 +217,37 @@ void Weather::Initialize() {
 	SetWindSpeed(0);
 	SetBaseline(0, 200);
 
-	if (mIsSnow)
+	if (_mIsSnow)
 		SetFallSpeed(10, 70);
 	else
 		SetFallSpeed(100, 300);
 
-	mViewsInitialized = false;
+	_mViewsInitialized = false;
 
 	int i;
 	for (i = 0; i < 5; i++) {
-		mViews[i].is_default = true;
-		mViews[i].view = -1;
-		mViews[i].loop = -1;
-		mViews[i].bitmap = nullptr;
+		_mViews[i].is_default = true;
+		_mViews[i].view = -1;
+		_mViews[i].loop = -1;
+		_mViews[i].bitmap = nullptr;
 	}
 
 	SetAmount(0);
 }
 
 void Weather::InitializeParticles() {
-	memset(mParticles, 0, sizeof(Drop) * 2000);
+	memset(_mParticles, 0, sizeof(Drop) * 2000);
 	int i;
 	for (i = 0; i < 2000; i++) {
-		mParticles[i].kind_id = ::AGS::g_vm->getRandomNumber(0x7fffffff) % 5;
-		mParticles[i].y = ::AGS::g_vm->getRandomNumber(0x7fffffff) % (_screenHeight * 2) - _screenHeight;
-		mParticles[i].x = ::AGS::g_vm->getRandomNumber(0x7fffffff) % _screenWidth;
-		mParticles[i].alpha = ::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaAlpha + mMinAlpha;
-		mParticles[i].speed = (float)(::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaFallSpeed + mMinFallSpeed) / 50.0f;
-		mParticles[i].max_y = ::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaBaseline + mTopBaseline;
-		mParticles[i].drift = ::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaDrift + mMinDrift;
-		mParticles[i].drift_speed = (::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaDriftSpeed + mMinDriftSpeed) / 50.0f;
-		mParticles[i].drift_offset = ::AGS::g_vm->getRandomNumber(0x7fffffff) % 100;
+		_mParticles[i].kind_id = ::AGS::g_vm->getRandomNumber(0x7fffffff) % 5;
+		_mParticles[i].y = ::AGS::g_vm->getRandomNumber(0x7fffffff) % (_screenHeight * 2) - _screenHeight;
+		_mParticles[i].x = ::AGS::g_vm->getRandomNumber(0x7fffffff) % _screenWidth;
+		_mParticles[i].alpha = ::AGS::g_vm->getRandomNumber(0x7fffffff) % _mDeltaAlpha + _mMinAlpha;
+		_mParticles[i].speed = (float)(::AGS::g_vm->getRandomNumber(0x7fffffff) % _mDeltaFallSpeed + _mMinFallSpeed) / 50.0f;
+		_mParticles[i].max_y = ::AGS::g_vm->getRandomNumber(0x7fffffff) % _mDeltaBaseline + _mTopBaseline;
+		_mParticles[i].drift = ::AGS::g_vm->getRandomNumber(0x7fffffff) % _mDeltaDrift + _mMinDrift;
+		_mParticles[i].drift_speed = (::AGS::g_vm->getRandomNumber(0x7fffffff) % _mDeltaDriftSpeed + _mMinDriftSpeed) / 50.0f;
+		_mParticles[i].drift_offset = ::AGS::g_vm->getRandomNumber(0x7fffffff) % 100;
 	}
 }
 
@@ -283,12 +264,12 @@ void Weather::SetDriftRange(int min_value, int max_value) {
 	if (min_value > max_value)
 		min_value = max_value;
 
-	mMinDrift = min_value / 2;
-	mMaxDrift = max_value / 2;
-	mDeltaDrift = mMaxDrift - mMinDrift;
+	_mMinDrift = min_value / 2;
+	_mMaxDrift = max_value / 2;
+	_mDeltaDrift = _mMaxDrift - _mMinDrift;
 
-	if (mDeltaDrift == 0)
-		mDeltaDrift = 1;
+	if (_mDeltaDrift == 0)
+		_mDeltaDrift = 1;
 }
 
 void Weather::SetDriftSpeed(int min_value, int max_value) {
@@ -304,12 +285,12 @@ void Weather::SetDriftSpeed(int min_value, int max_value) {
 	if (min_value > max_value)
 		min_value = max_value;
 
-	mMinDriftSpeed = min_value;
-	mMaxDriftSpeed = max_value;
-	mDeltaDriftSpeed = mMaxDriftSpeed - mMinDriftSpeed;
+	_mMinDriftSpeed = min_value;
+	_mMaxDriftSpeed = max_value;
+	_mDeltaDriftSpeed = _mMaxDriftSpeed - _mMinDriftSpeed;
 
-	if (mDeltaDriftSpeed == 0)
-		mDeltaDriftSpeed = 1;
+	if (_mDeltaDriftSpeed == 0)
+		_mDeltaDriftSpeed = 1;
 }
 
 void Weather::ChangeAmount(int amount) {
@@ -321,7 +302,7 @@ void Weather::ChangeAmount(int amount) {
 
 	ClipToRange(amount, 0, 1000);
 
-	mTargetAmount = amount;
+	_mTargetAmount = amount;
 }
 
 void Weather::SetView(int kind_id, int event, int view, int loop) {
@@ -332,12 +313,12 @@ void Weather::SetView(int kind_id, int event, int view, int loop) {
 #endif
 
 	AGSViewFrame *view_frame = _engine->GetViewFrame(view, loop, 0);
-	mViews[kind_id].bitmap = _engine->GetSpriteGraphic(view_frame->pic);
-	mViews[kind_id].is_default = false;
-	mViews[kind_id].view = view;
-	mViews[kind_id].loop = loop;
+	_mViews[kind_id].bitmap = _engine->GetSpriteGraphic(view_frame->pic);
+	_mViews[kind_id].is_default = false;
+	_mViews[kind_id].view = view;
+	_mViews[kind_id].loop = loop;
 
-	if (!mViewsInitialized)
+	if (!_mViewsInitialized)
 		SetDefaultView(view, loop);
 }
 
@@ -351,14 +332,14 @@ void Weather::SetDefaultView(int view, int loop) {
 	AGSViewFrame *view_frame = _engine->GetViewFrame(view, loop, 0);
 	BITMAP *bitmap = _engine->GetSpriteGraphic(view_frame->pic);
 
-	mViewsInitialized = true;
+	_mViewsInitialized = true;
 
 	int i;
 	for (i = 0; i < 5; i++) {
-		if (mViews[i].is_default) {
-			mViews[i].view = view;
-			mViews[i].loop = loop;
-			mViews[i].bitmap = bitmap;
+		if (_mViews[i].is_default) {
+			_mViews[i].view = view;
+			_mViews[i].loop = loop;
+			_mViews[i].bitmap = bitmap;
 		}
 	}
 }
@@ -376,16 +357,16 @@ void Weather::SetTransparency(int min_value, int max_value) {
 	if (min_value > max_value)
 		min_value = max_value;
 
-	mMinAlpha = 255 - floor((float)max_value * 2.55f + 0.5f);
-	mMaxAlpha = 255 - floor((float)min_value * 2.55f + 0.5f);
-	mDeltaAlpha = mMaxAlpha - mMinAlpha;
+	_mMinAlpha = 255 - floor((float)max_value * 2.55f + 0.5f);
+	_mMaxAlpha = 255 - floor((float)min_value * 2.55f + 0.5f);
+	_mDeltaAlpha = _mMaxAlpha - _mMinAlpha;
 
-	if (mDeltaAlpha == 0)
-		mDeltaAlpha = 1;
+	if (_mDeltaAlpha == 0)
+		_mDeltaAlpha = 1;
 
 	int i;
 	for (i = 0; i < 2000; i++)
-		mParticles[i].alpha = ::AGS::g_vm->getRandomNumber(0x7fffffff) % mDeltaAlpha + mMinAlpha;
+		_mParticles[i].alpha = ::AGS::g_vm->getRandomNumber(0x7fffffff) % _mDeltaAlpha + _mMinAlpha;
 }
 
 void Weather::SetWindSpeed(int value) {
@@ -397,7 +378,7 @@ void Weather::SetWindSpeed(int value) {
 
 	ClipToRange(value, -200, 200);
 
-	mWindSpeed = (float)value / 20.0f;
+	_mWindSpeed = (float)value / 20.0f;
 }
 
 void Weather::SetBaseline(int top, int bottom) {
@@ -415,12 +396,12 @@ void Weather::SetBaseline(int top, int bottom) {
 	if (top > bottom)
 		top = bottom;
 
-	mTopBaseline = top;
-	mBottomBaseline = bottom;
-	mDeltaBaseline = mBottomBaseline - mTopBaseline;
+	_mTopBaseline = top;
+	_mBottomBaseline = bottom;
+	_mDeltaBaseline = _mBottomBaseline - _mTopBaseline;
 
-	if (mDeltaBaseline == 0)
-		mDeltaBaseline = 1;
+	if (_mDeltaBaseline == 0)
+		_mDeltaBaseline = 1;
 }
 
 void Weather::SetAmount(int amount) {
@@ -432,7 +413,7 @@ void Weather::SetAmount(int amount) {
 
 	ClipToRange(amount, 0, 1000);
 
-	mAmount = mTargetAmount = amount;
+	_mAmount = _mTargetAmount = amount;
 
 	InitializeParticles();
 }
@@ -450,12 +431,12 @@ void Weather::SetFallSpeed(int min_value, int max_value) {
 	if (min_value > max_value)
 		min_value = max_value;
 
-	mMinFallSpeed = min_value;
-	mMaxFallSpeed = max_value;
-	mDeltaFallSpeed = mMaxFallSpeed - mMinFallSpeed;
+	_mMinFallSpeed = min_value;
+	_mMaxFallSpeed = max_value;
+	_mDeltaFallSpeed = _mMaxFallSpeed - _mMinFallSpeed;
 
-	if (mDeltaFallSpeed == 0)
-		mDeltaFallSpeed = 1;
+	if (_mDeltaFallSpeed == 0)
+		_mDeltaFallSpeed = 1;
 }
 
 } // namespace AGSSnowRain
diff --git a/engines/ags/plugins/ags_snow_rain/weather.h b/engines/ags/plugins/ags_snow_rain/weather.h
index c05879e2ce..a2e634c9cf 100644
--- a/engines/ags/plugins/ags_snow_rain/weather.h
+++ b/engines/ags/plugins/ags_snow_rain/weather.h
@@ -24,6 +24,7 @@
 #define AGS_PLUGINS_AGS_SNOW_RAIN_WEATHER_H
 
 #include "ags/plugins/dll.h"
+#include "ags/plugins/serializer.h"
 
 namespace AGS3 {
 namespace Plugins {
@@ -34,6 +35,8 @@ struct View {
 	int loop = 0;
 	bool is_default = false;
 	BITMAP *bitmap = nullptr;
+
+	void SyncGame(Serializer &s);
 };
 
 struct Drop {
@@ -49,6 +52,41 @@ struct Drop {
 };
 
 class Weather {
+private:
+	void ClipToRange(int &variable, int min, int max);
+
+	bool _mIsSnow;
+
+	int _mMinDrift = 0;
+	int _mMaxDrift = 0;
+	int _mDeltaDrift = 0;
+
+	int _mMinDriftSpeed = 0;
+	int _mMaxDriftSpeed = 0;
+	int _mDeltaDriftSpeed = 0;
+
+	int _mAmount = 0;
+	int _mTargetAmount = 0;
+
+	int _mMinAlpha = 0;
+	int _mMaxAlpha = 0;
+	int _mDeltaAlpha = 0;
+
+	float _mWindSpeed = 0;
+
+	int _mTopBaseline = 0;
+	int _mBottomBaseline = 0;
+	int _mDeltaBaseline = 0;
+
+	int _mMinFallSpeed = 0;
+	int _mMaxFallSpeed = 0;
+	int _mDeltaFallSpeed = 0;
+
+	Drop _mParticles[2000];
+	View _mViews[5];
+
+	bool _mViewsInitialized;
+
 public:
 	Weather();
 	Weather(bool IsSnow);
@@ -57,8 +95,7 @@ public:
 	void Initialize();
 	void InitializeParticles();
 
-	void RestoreGame(long file);
-	void SaveGame(long file);
+	void SyncGame(Serializer &s);
 	bool ReinitializeViews();
 
 	bool IsActive();
@@ -77,40 +114,6 @@ public:
 	void SetAmount(int amount);
 	void SetFallSpeed(int min_value, int max_value);
 
-private:
-	void ClipToRange(int &variable, int min, int max);
-
-	bool mIsSnow;
-
-	int mMinDrift;
-	int mMaxDrift;
-	int mDeltaDrift;
-
-	int mMinDriftSpeed;
-	int mMaxDriftSpeed;
-	int mDeltaDriftSpeed;
-
-	int mAmount;
-	int mTargetAmount;
-
-	int mMinAlpha;
-	int mMaxAlpha;
-	int mDeltaAlpha;
-
-	float mWindSpeed;
-
-	int mTopBaseline;
-	int mBottomBaseline;
-	int mDeltaBaseline;
-
-	int mMinFallSpeed;
-	int mMaxFallSpeed;
-	int mDeltaFallSpeed;
-
-	Drop mParticles[2000];
-	View mViews[5];
-
-	bool mViewsInitialized;
 };
 
 } // namespace AGSSnowRain
diff --git a/engines/ags/plugins/serializer.h b/engines/ags/plugins/serializer.h
new file mode 100644
index 0000000000..ba48c0bc25
--- /dev/null
+++ b/engines/ags/plugins/serializer.h
@@ -0,0 +1,73 @@
+/* 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 AGS_PLUGINS_SERIALIZER_H
+#define AGS_PLUGINS_SERIALIZER_H
+
+#include "ags/engine/plugin/agsplugin.h"
+#include "common/serializer.h"
+
+namespace AGS3 {
+namespace Plugins {
+
+class Serializer {
+private:
+	IAGSEngine *_engine;
+	long _file;
+	bool _isLoading;
+public:
+	Serializer(IAGSEngine *engine, long file, bool isLoading) :
+		_engine(engine), _file(file), _isLoading(isLoading) {}
+
+	bool isLoading() const { return _isLoading; }
+	bool isSaving() const { return !_isLoading; }
+
+	void syncAsInt(int &value) {
+		byte buf[4];
+		if (_isLoading) {
+			_engine->FRead(buf, sizeof(int32), _file);
+			value = READ_LE_INT32(buf);
+		} else {
+			WRITE_LE_UINT32(buf, value);
+			_engine->FWrite(buf, sizeof(int32), _file);
+		}
+	}
+
+	void syncAsBool(bool &value) {
+		if (_isLoading)
+			_engine->FRead(&value, 1, _file);
+		else
+			_engine->FWrite(&value, 1, _file);
+	}
+
+	void syncAsFloat(float &value) {
+		if (_isLoading)
+			_engine->FRead(&value, sizeof(float), _file);
+		else
+			_engine->FWrite(&value, sizeof(float), _file);
+	}
+};
+
+} // namespace Plugins
+} // namespace AGS3
+
+#endif


Commit: b1b1e067f93d2a6672afa341d28098c6cb877b5b
    https://github.com/scummvm/scummvm/commit/b1b1e067f93d2a6672afa341d28098c6cb877b5b
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Change AGSParallax plugin to use save serializer

Changed paths:
    engines/ags/plugins/ags_parallax/ags_parallax.cpp
    engines/ags/plugins/ags_parallax/ags_parallax.h
    engines/ags/plugins/ags_snow_rain/weather.cpp


diff --git a/engines/ags/plugins/ags_parallax/ags_parallax.cpp b/engines/ags/plugins/ags_parallax/ags_parallax.cpp
index a07e7382fe..1bb6eff354 100644
--- a/engines/ags/plugins/ags_parallax/ags_parallax.cpp
+++ b/engines/ags/plugins/ags_parallax/ags_parallax.cpp
@@ -85,9 +85,11 @@ int AGSParallax::AGS_EngineOnEvent(int event, int data) {
 		_engine->GetScreenDimensions(&_screenWidth, &_screenHeight, &_screenColorDepth);
 		_engine->UnrequestEventHook(AGSE_PRESCREENDRAW);
 	} else if (event == AGSE_RESTOREGAME) {
-		RestoreGame(data);
+		Serializer s(_engine, data, true);
+		SyncGame(s);
 	} else if (event == AGSE_SAVEGAME) {
-		SaveGame(data);
+		Serializer s(_engine, data, false);
+		SyncGame(s);
 	}
 
 	return 0;
@@ -102,37 +104,17 @@ void AGSParallax::clear() {
 	_enabled = false;
 }
 
-size_t AGSParallax::engineFileRead(void *ptr, size_t size, size_t count, long fileHandle) {
-	auto totalBytes = _engine->FRead(ptr, size * count, fileHandle);
-	return totalBytes / size;
-}
-
-size_t AGSParallax::engineFileWrite(const void *ptr, size_t size, size_t count, long fileHandle) {
-	auto totalBytes = _engine->FWrite(const_cast<void *>(ptr), size * count, fileHandle);
-	return totalBytes / size;
-}
-
-void AGSParallax::RestoreGame(long file) {
-	byte saveVersion[4];
-	engineFileRead(&saveVersion, 4, 1, file);
-
-	if (READ_LE_UINT32(saveVersion) != SaveMagic) {
+void AGSParallax::SyncGame(Serializer &s) {
+	int saveVersion = SaveMagic;
+	s.syncAsInt(saveVersion);
+	if (saveVersion != SaveMagic) {
 		_engine->AbortGame("ags_parallax: bad save.");
+		return;
 	}
 
 	for (int i = 0; i < MAX_SPRITES; ++i)
-		_sprites[i].load(_engine, file);
-	engineFileRead(&_enabled, sizeof(bool), 1, file);
-}
-
-void AGSParallax::SaveGame(long file) {
-	byte saveVersion[4];
-	WRITE_LE_UINT32(saveVersion, SaveMagic);
-	engineFileWrite(&SaveMagic, 4, 1, file);
-
-	for (int i = 0; i < MAX_SPRITES; ++i)
-		_sprites[i].save(_engine, file);
-	engineFileWrite(&_enabled, 1, 1, file);
+		_sprites[i].SyncGame(s);
+	s.syncAsBool(_enabled);
 }
 
 void AGSParallax::Draw(bool foreground) {
@@ -204,30 +186,11 @@ void AGSParallax::pxDeleteSprite(int id) {
 
 /*------------------------------------------------------------------*/
 
-void Sprite::save(IAGSEngine *engine, long file) {
-	saveInt(engine, file, x);
-	saveInt(engine, file, y);
-	saveInt(engine, file, slot);
-	saveInt(engine, file, speed);
-}
-
-void Sprite::load(IAGSEngine *engine, long file) {
-	x = loadInt(engine, file);
-	y = loadInt(engine, file);
-	slot = loadInt(engine, file);
-	speed = loadInt(engine, file);
-}
-
-void saveInt(IAGSEngine *engine, long file, int value) {
-	byte buf[4];
-	WRITE_LE_INT32(buf, value);
-	engine->FWrite(buf, 4, file);
-}
-
-int loadInt(IAGSEngine *engine, long file) {
-	byte buf[4];
-	engine->FRead(buf, 4, file);
-	return READ_LE_INT32(buf);
+void Sprite::SyncGame(Serializer &s) {
+	s.syncAsInt(x);
+	s.syncAsInt(y);
+	s.syncAsInt(slot);
+	s.syncAsInt(speed);
 }
 
 } // namespace AGSParallax
diff --git a/engines/ags/plugins/ags_parallax/ags_parallax.h b/engines/ags/plugins/ags_parallax/ags_parallax.h
index 2d441e38e0..8647a95235 100644
--- a/engines/ags/plugins/ags_parallax/ags_parallax.h
+++ b/engines/ags/plugins/ags_parallax/ags_parallax.h
@@ -24,6 +24,7 @@
 #define AGS_PLUGINS_AGS_PARALLAX_AGS_PARALLAX_H
 
 #include "ags/plugins/dll.h"
+#include "ags/plugins/serializer.h"
 
 namespace AGS3 {
 namespace Plugins {
@@ -35,10 +36,7 @@ struct Sprite {
 	int slot = -1;
 	int speed = 0;
 
-	void save(IAGSEngine *engine, long file);
-	void load(IAGSEngine *engine, long file);
-	void saveInt(IAGSEngine *engine, long file, int value);
-	int loadInt(IAGSEngine *engine, long file);
+	void SyncGame(Serializer &s);
 };
 
 #define MAX_SPEED 1000
@@ -66,10 +64,7 @@ private:
 	static void pxDeleteSprite(int id);
 
 private:
-	static size_t engineFileRead(void *ptr, size_t size, size_t count, long fileHandle);
-	static size_t engineFileWrite(const void *ptr, size_t size, size_t count, long fileHandle);
-	static void RestoreGame(long file);
-	static void SaveGame(long file);
+	static void SyncGame(Serializer &s);
 	static void Draw(bool foreground);
 	static void clear();
 
diff --git a/engines/ags/plugins/ags_snow_rain/weather.cpp b/engines/ags/plugins/ags_snow_rain/weather.cpp
index 5b76e6ce5c..3798067749 100644
--- a/engines/ags/plugins/ags_snow_rain/weather.cpp
+++ b/engines/ags/plugins/ags_snow_rain/weather.cpp
@@ -134,7 +134,7 @@ void Weather::UpdateWithDrift() {
 }
 
 void Weather::SyncGame(Serializer &s) {
-	int saveVersion = 0;
+	int saveVersion = SaveMagic;
 	s.syncAsInt(saveVersion);
 
 	if (s.isLoading() && saveVersion != SaveMagic) {


Commit: a11cab9a508de0bb8e53e22911c5ae1c9b844ce9
    https://github.com/scummvm/scummvm/commit/a11cab9a508de0bb8e53e22911c5ae1c9b844ce9
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added AGSSpriteFont plugin

Changed paths:
  A engines/ags/plugins/ags_sprite_font/ags_sprite_font.h
    engines/ags/lib/std/map.h
    engines/ags/module.mk
    engines/ags/plugins/ags_sprite_font/ags_sprite_font.cpp
    engines/ags/plugins/ags_sprite_font/character_entry.cpp
    engines/ags/plugins/ags_sprite_font/character_entry.h
    engines/ags/plugins/ags_sprite_font/color.cpp
    engines/ags/plugins/ags_sprite_font/color.h
    engines/ags/plugins/ags_sprite_font/sprite_font.cpp
    engines/ags/plugins/ags_sprite_font/sprite_font.h
    engines/ags/plugins/ags_sprite_font/sprite_font_renderer.cpp
    engines/ags/plugins/ags_sprite_font/sprite_font_renderer.h
    engines/ags/plugins/ags_sprite_font/variable_width_font.cpp
    engines/ags/plugins/ags_sprite_font/variable_width_font.h
    engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.cpp
    engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.h
    engines/ags/plugins/dll.cpp


diff --git a/engines/ags/lib/std/map.h b/engines/ags/lib/std/map.h
index d4d2b87da5..b64afd9f98 100644
--- a/engines/ags/lib/std/map.h
+++ b/engines/ags/lib/std/map.h
@@ -177,6 +177,19 @@ public:
 	size_t size() const {
 		return _items.size();
 	}
+
+	/**
+	 * Returns the number of elements with a matching key
+	 */
+	size_t count(const Key &theKey) {
+		int count = 0;
+		for (iterator it = this->begin(); it != this->end(); ++it) {
+			if (it->_key == theKey)
+				++count;
+		}
+
+		return count;
+	}
 };
 
 template<class Key, class Val, class HashFunc = Common::Hash<Key>,
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 72899f2818..526a60c7a3 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -308,7 +308,14 @@ MODULE_OBJS = \
 	plugins/ags_pal_render/raycast.o \
 	plugins/ags_parallax/ags_parallax.o \
 	plugins/ags_snow_rain/ags_snow_rain.o \
-	plugins/ags_snow_rain/weather.o
+	plugins/ags_snow_rain/weather.o \
+	plugins/ags_sprite_font/ags_sprite_font.o \
+	plugins/ags_sprite_font/character_entry.o \
+	plugins/ags_sprite_font/color.o \
+	plugins/ags_sprite_font/sprite_font.o \
+	plugins/ags_sprite_font/sprite_font_renderer.o \
+	plugins/ags_sprite_font/variable_width_font.o \
+	plugins/ags_sprite_font/variable_width_sprite_font.o
 
 ifdef ENABLE_AGS_TESTS
 MODULE_OBJS += \
diff --git a/engines/ags/plugins/ags_sprite_font/ags_sprite_font.cpp b/engines/ags/plugins/ags_sprite_font/ags_sprite_font.cpp
index acbc19801d..cf81fb5757 100644
--- a/engines/ags/plugins/ags_sprite_font/ags_sprite_font.cpp
+++ b/engines/ags/plugins/ags_sprite_font/ags_sprite_font.cpp
@@ -1,33 +1,37 @@
-/***********************************************************
- * AGSBlend                                                *
- *                                                         *
- * Author: Steven Poulton                                  *
- *                                                         *
- * Date: 09/01/2011                                        *
- *                                                         *
- * Description: An AGS Plugin to allow true Alpha Blending *
- *                                                         *
- ***********************************************************/
-
-#pragma region Defines_and_Includes
-
-#include "core/platform.h"
+/* 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 "ags/plugins/ags_sprite_font/ags_sprite_font.h"
+#include "ags/shared/core/platform.h"
+
+namespace AGS3 {
+namespace Plugins {
+namespace AGSSpriteFont {
+
+#pragma region Defines
 
 #define MIN_EDITOR_VERSION 1
 #define MIN_ENGINE_VERSION 3
 
-#if AGS_PLATFORM_OS_WINDOWS
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#include <WinBase.h>
-#endif
-
-#define THIS_IS_THE_PLUGIN
-#include "plugin/agsplugin.h"
-#include "SpriteFontRenderer.h"
-#include "VariableWidthSpriteFont.h"
-
-
 #define DEFAULT_RGB_R_SHIFT_32  16
 #define DEFAULT_RGB_G_SHIFT_32  8
 #define DEFAULT_RGB_B_SHIFT_32  0
@@ -65,215 +69,71 @@
 
 #pragma endregion
 
+IAGSEngine *AGSSpriteFont::_engine;
+SpriteFontRenderer *AGSSpriteFont::_fontRenderer;
+VariableWidthSpriteFontRenderer *AGSSpriteFont::_vWidthRenderer;
 
-#if AGS_PLATFORM_OS_WINDOWS
-// The standard Windows DLL entry point
-
-BOOL APIENTRY DllMain(HANDLE hModule,
-                      DWORD  ul_reason_for_call,
-                      LPVOID lpReserved) {
-
-	switch (ul_reason_for_call)   {
-	case DLL_PROCESS_ATTACH:
-	case DLL_THREAD_ATTACH:
-	case DLL_THREAD_DETACH:
-	case DLL_PROCESS_DETACH:
-		break;
-	}
-	return TRUE;
-}
-#endif
-
-
-//define engine
-
-IAGSEngine *engine = nullptr;
-SpriteFontRenderer *fontRenderer = nullptr;
-VariableWidthSpriteFontRenderer *vWidthRenderer = nullptr;
-
-
-
-void SetSpriteFont(int fontNum, int sprite, int rows, int columns, int charWidth, int charHeight, int charMin, int charMax, bool use32bit) {
-	engine->PrintDebugConsole("AGSSpriteFont: SetSpriteFont");
-	fontRenderer->SetSpriteFont(fontNum, sprite, rows, columns, charWidth, charHeight, charMin, charMax, use32bit);
-	engine->ReplaceFontRenderer(fontNum, fontRenderer);
-
-}
-
-void SetVariableSpriteFont(int fontNum, int sprite) {
-	engine->PrintDebugConsole("AGSSpriteFont: SetVariableFont");
-	vWidthRenderer->SetSprite(fontNum, sprite);
-	engine->ReplaceFontRenderer(fontNum, vWidthRenderer);
-}
+#define STRINGIFY(s) STRINGIFY_X(s)
+#define STRINGIFY_X(s) #s
 
-void SetGlyph(int fontNum, int charNum, int x, int y, int width, int height) {
-	engine->PrintDebugConsole("AGSSpriteFont: SetGlyph");
-	vWidthRenderer->SetGlyph(fontNum, charNum, x, y, width, height);
-}
+AGSSpriteFont::AGSSpriteFont() : DLL() {
+	_engine = nullptr;
 
-void SetSpacing(int fontNum, int spacing) {
-	engine->PrintDebugConsole("AGSSpriteFont: SetSpacing");
-	vWidthRenderer->SetSpacing(fontNum, spacing);
+	DLL_METHOD(AGS_GetPluginName);
+	DLL_METHOD(AGS_EngineStartup);
+	DLL_METHOD(AGS_EngineShutdown);
 }
-//==============================================================================
 
-#if AGS_PLATFORM_OS_WINDOWS && !defined(BUILTIN_PLUGINS)
-// ***** Design time *****
-
-IAGSEditor *editor; // Editor interface
-
-const char *ourScriptHeader =
-    "import void SetSpriteFont(int fontNum, int sprite, int rows, int columns, int charWidth, int charHeight, int charMin, int charMax, bool use32bit);\r\n"
-    "import void SetVariableSpriteFont(int fontNum, int sprite);\r\n"
-    "import void SetGlyph(int fontNum, int charNum, int x, int y, int width, int height);\r\n"
-    "import void SetSpacing(int fontNum, int spacing);\r\n"
-    ;
-
-//------------------------------------------------------------------------------
-
-LPCSTR AGS_GetPluginName() {
-	return ("AGSSpriteFont");
+const char *AGSSpriteFont::AGS_GetPluginName() {
+	return "AGSSpriteFont";
 }
 
-//------------------------------------------------------------------------------
-
-int AGS_EditorStartup(IAGSEditor *lpEditor) {
-	// User has checked the plugin to use it in their game
-
-	// If it's an earlier version than what we need, abort.
-	if (lpEditor->version < MIN_EDITOR_VERSION)
-		return (-1);
-
-	editor = lpEditor;
-	editor->RegisterScriptHeader(ourScriptHeader);
+void AGSSpriteFont::AGS_EngineStartup(IAGSEngine *engine) {
+	engine = engine;
 
-	// Return 0 to indicate success
-	return (0);
-}
-
-//------------------------------------------------------------------------------
+	_engine->PrintDebugConsole("AGSSpriteFont: Init fixed width renderer");
+	_fontRenderer = new SpriteFontRenderer(engine);
+	_engine->PrintDebugConsole("AGSSpriteFont: Init vari width renderer");
+	_vWidthRenderer = new VariableWidthSpriteFontRenderer(engine);
+	// Make sure it's got the version with the features we need
+	if (_engine->version < MIN_ENGINE_VERSION)
+		_engine->AbortGame("Plugin needs engine version " STRINGIFY(MIN_ENGINE_VERSION) " or newer.");
 
-void AGS_EditorShutdown() {
-	// User has un-checked the plugin from their game
-	editor->UnregisterScriptHeader(ourScriptHeader);
+	//register functions
+	_engine->PrintDebugConsole("AGSSpriteFont: Register functions");
+	SCRIPT_METHOD(SetSpriteFont);
+	SCRIPT_METHOD(SetVariableSpriteFont);
+	SCRIPT_METHOD(SetGlyph);
+	SCRIPT_METHOD(SetSpacing);
 }
 
-//------------------------------------------------------------------------------
-
-void AGS_EditorProperties(HWND parent) {                      //*** optional ***
-	// User has chosen to view the Properties of the plugin
-	// We could load up an options dialog or something here instead
-	MessageBox(parent,
-	           L"AGSSpriteFont v1.0 By Calin Leafshade",
-	           L"About",
-	           MB_OK | MB_ICONINFORMATION);
+void AGSSpriteFont::AGS_EngineShutdown() {
+	delete _fontRenderer;
+	delete _vWidthRenderer;
 }
 
-//------------------------------------------------------------------------------
-
-int AGS_EditorSaveGame(char *buffer, int bufsize) {           //*** optional ***
-	// Called by the editor when the current game is saved to disk.
-	// Plugin configuration can be stored in [buffer] (max [bufsize] bytes)
-	// Return the amount of bytes written in the buffer
-	return (0);
+void AGSSpriteFont::SetSpriteFont(int fontNum, int sprite, int rows, int columns, int charWidth, int charHeight, int charMin, int charMax, bool use32bit) {
+	_engine->PrintDebugConsole("AGSSpriteFont: SetSpriteFont");
+	_fontRenderer->SetSpriteFont(fontNum, sprite, rows, columns, charWidth, charHeight, charMin, charMax, use32bit);
+	_engine->ReplaceFontRenderer(fontNum, _fontRenderer);
 }
 
-//------------------------------------------------------------------------------
-
-void AGS_EditorLoadGame(char *buffer, int bufsize) {          //*** optional ***
-	// Called by the editor when a game is loaded from disk
-	// Previous written data can be read from [buffer] (size [bufsize]).
-	// Make a copy of the data, the buffer is freed after this function call.
+void AGSSpriteFont::SetVariableSpriteFont(int fontNum, int sprite) {
+	_engine->PrintDebugConsole("AGSSpriteFont: SetVariableFont");
+	_vWidthRenderer->SetSprite(fontNum, sprite);
+	_engine->ReplaceFontRenderer(fontNum, _vWidthRenderer);
 }
 
-//==============================================================================
-#endif
-
-
-// ***** Run time *****
-
-// Engine interface
-
-//------------------------------------------------------------------------------
-
-#define REGISTER(x) engine->RegisterScriptFunction(#x, (void *) (x));
-#define STRINGIFY(s) STRINGIFY_X(s)
-#define STRINGIFY_X(s) #s
-
-
-
-void AGS_EngineStartup(IAGSEngine *lpEngine) {
-	engine = lpEngine;
-	engine->PrintDebugConsole("AGSSpriteFont: Init fixed width renderer");
-	fontRenderer = new SpriteFontRenderer(engine);
-	engine->PrintDebugConsole("AGSSpriteFont: Init vari width renderer");
-	vWidthRenderer = new VariableWidthSpriteFontRenderer(engine);
-	// Make sure it's got the version with the features we need
-	if (engine->version < MIN_ENGINE_VERSION)
-		engine->AbortGame("Plugin needs engine version " STRINGIFY(MIN_ENGINE_VERSION) " or newer.");
-
-	//register functions
-	engine->PrintDebugConsole("AGSSpriteFont: Register functions");
-	REGISTER(SetSpriteFont)
-	REGISTER(SetVariableSpriteFont)
-	REGISTER(SetGlyph)
-	REGISTER(SetSpacing)
+void AGSSpriteFont::SetGlyph(int fontNum, int charNum, int x, int y, int width, int height) {
+	_engine->PrintDebugConsole("AGSSpriteFont: SetGlyph");
+	_vWidthRenderer->SetGlyph(fontNum, charNum, x, y, width, height);
 }
 
-//------------------------------------------------------------------------------
-
-void AGS_EngineShutdown() {
-	// Called by the game engine just before it exits.
-	// This gives you a chance to free any memory and do any cleanup
-	// that you need to do before the engine shuts down.
+void AGSSpriteFont::SetSpacing(int fontNum, int spacing) {
+	_engine->PrintDebugConsole("AGSSpriteFont: SetSpacing");
+	_vWidthRenderer->SetSpacing(fontNum, spacing);
 }
 
-//------------------------------------------------------------------------------
-
-int AGS_EngineOnEvent(int event, int data) {                  //*** optional ***
-	switch (event) {
-	/*
-	        case AGSE_KEYPRESS:
-	        case AGSE_MOUSECLICK:
-	        case AGSE_POSTSCREENDRAW:
-	        case AGSE_PRESCREENDRAW:
-	        case AGSE_SAVEGAME:
-	        case AGSE_RESTOREGAME:
-	        case AGSE_PREGUIDRAW:
-	        case AGSE_LEAVEROOM:
-	        case AGSE_ENTERROOM:
-	        case AGSE_TRANSITIONIN:
-	        case AGSE_TRANSITIONOUT:
-	        case AGSE_FINALSCREENDRAW:
-	        case AGSE_TRANSLATETEXT:
-	        case AGSE_SCRIPTDEBUG:
-	        case AGSE_SPRITELOAD:
-	        case AGSE_PRERENDER:
-	        case AGSE_PRESAVEGAME:
-	        case AGSE_POSTRESTOREGAME:
-	*/
-	default:
-		break;
-	}
-
-	// Return 1 to stop event from processing further (when needed)
-	return (0);
-}
-
-//------------------------------------------------------------------------------
-/*
-int AGS_EngineDebugHook(const char *scriptName,
-                        int lineNum, int reserved)            //*** optional ***
-{
-    // Can be used to debug scripts, see documentation
-}
-*/
-//------------------------------------------------------------------------------
-/*
-void AGS_EngineInitGfx(const char *driverID, void *data)      //*** optional ***
-{
-    // This allows you to make changes to how the graphics driver starts up.
-    // See documentation
-}
-*/
-//..............................................................................
+} // namespace AGSSpriteFont
+} // namespace Plugins
+} // namespace AGS3
diff --git a/engines/ags/plugins/ags_sprite_font/ags_sprite_font.h b/engines/ags/plugins/ags_sprite_font/ags_sprite_font.h
new file mode 100644
index 0000000000..449c4d7a66
--- /dev/null
+++ b/engines/ags/plugins/ags_sprite_font/ags_sprite_font.h
@@ -0,0 +1,59 @@
+/* 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 AGS_PLUGINS_AGS_SPRITE_FONT_AGS_SPRITE_FONT_H
+#define AGS_PLUGINS_AGS_SPRITE_FONT_AGS_SPRITE_FONT_H
+
+#include "ags/plugins/dll.h"
+#include "ags/plugins/serializer.h"
+#include "ags/plugins/ags_sprite_font/sprite_font_renderer.h"
+#include "ags/plugins/ags_sprite_font/variable_width_sprite_font.h"
+
+namespace AGS3 {
+namespace Plugins {
+namespace AGSSpriteFont {
+
+class AGSSpriteFont : public DLL {
+private:
+	static IAGSEngine *_engine;
+	static SpriteFontRenderer *_fontRenderer;
+	static VariableWidthSpriteFontRenderer *_vWidthRenderer;
+private:
+	static const char *AGS_GetPluginName();
+	static void AGS_EngineStartup(IAGSEngine *lpEngine);
+	static void AGS_EngineShutdown();
+
+private:
+	static void SetSpriteFont(int fontNum, int sprite, int rows, int columns, int charWidth, int charHeight, int charMin, int charMax, bool use32bit);
+	static void SetVariableSpriteFont(int fontNum, int sprite);
+	static void SetGlyph(int fontNum, int charNum, int x, int y, int width, int height);
+	static void SetSpacing(int fontNum, int spacing);
+
+public:
+	AGSSpriteFont();
+};
+
+} // namespace AGSSpriteFont
+} // namespace Plugins
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/plugins/ags_sprite_font/character_entry.cpp b/engines/ags/plugins/ags_sprite_font/character_entry.cpp
index fa0575da7f..41376a1718 100644
--- a/engines/ags/plugins/ags_sprite_font/character_entry.cpp
+++ b/engines/ags/plugins/ags_sprite_font/character_entry.cpp
@@ -1,5 +1,30 @@
-#include "CharacterEntry.h"
+/* 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 "ags/plugins/ags_sprite_font/character_entry.h"
+
+namespace AGS3 {
+namespace Plugins {
+namespace AGSSpriteFont {
 
 CharacterEntry::CharacterEntry(void) {
 	X = 0;
@@ -11,3 +36,7 @@ CharacterEntry::CharacterEntry(void) {
 
 
 CharacterEntry::~CharacterEntry(void) = default;
+
+} // namespace AGSSpriteFont
+} // namespace Plugins
+} // namespace AGS3
diff --git a/engines/ags/plugins/ags_sprite_font/character_entry.h b/engines/ags/plugins/ags_sprite_font/character_entry.h
index 2d2a23f174..de782e6d87 100644
--- a/engines/ags/plugins/ags_sprite_font/character_entry.h
+++ b/engines/ags/plugins/ags_sprite_font/character_entry.h
@@ -1,4 +1,32 @@
-#pragma once
+/* 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 AGS_PLUGINS_AGS_SPRITE_FONT_CHAR_ENTRY_H
+#define AGS_PLUGINS_AGS_SPRITE_FONT_CHAR_ENTRY_H
+
+namespace AGS3 {
+namespace Plugins {
+namespace AGSSpriteFont {
+
 class CharacterEntry {
 public:
 	CharacterEntry(void);
@@ -10,3 +38,8 @@ public:
 	char Character;
 };
 
+} // namespace AGSSpriteFont
+} // namespace Plugins
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/plugins/ags_sprite_font/color.cpp b/engines/ags/plugins/ags_sprite_font/color.cpp
index 9e9c13b957..298118f419 100644
--- a/engines/ags/plugins/ags_sprite_font/color.cpp
+++ b/engines/ags/plugins/ags_sprite_font/color.cpp
@@ -1,4 +1,30 @@
-#include "color.h"
+/* 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 "ags/plugins/ags_sprite_font/color.h"
+
+namespace AGS3 {
+namespace Plugins {
+namespace AGSSpriteFont {
 
 int getr32(int c) {
 	return ((c >> DEFAULT_RGB_R_SHIFT_32) & 0xFF);
@@ -25,4 +51,8 @@ int makeacol32(int r, int g, int b, int a) {
 	        (g << DEFAULT_RGB_G_SHIFT_32) |
 	        (b << DEFAULT_RGB_B_SHIFT_32) |
 	        (a << DEFAULT_RGB_A_SHIFT_32));
-}
\ No newline at end of file
+}
+
+} // namespace AGSSpriteFont
+} // namespace Plugins
+} // namespace AGS3
diff --git a/engines/ags/plugins/ags_sprite_font/color.h b/engines/ags/plugins/ags_sprite_font/color.h
index 314f02a50d..cd7e1859ba 100644
--- a/engines/ags/plugins/ags_sprite_font/color.h
+++ b/engines/ags/plugins/ags_sprite_font/color.h
@@ -1,5 +1,31 @@
-#ifndef  __COLORH
-#define __COLORH
+/* 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 AGS_PLUGINS_AGS_SPRITE_FONT_COLOR_H
+#define AGS_PLUGINS_AGS_SPRITE_FONT_COLOR_H
+
+namespace AGS3 {
+namespace Plugins {
+namespace AGSSpriteFont {
 
 #define MAX(a, b)  (((a) > (b)) ? (a) : (b))
 #define DEFAULT_RGB_R_SHIFT_32  16
@@ -18,4 +44,8 @@ int makeacol32(int r, int g, int b, int a);
 
 #pragma endregion
 
-#endif
\ No newline at end of file
+} // namespace AGSSpriteFont
+} // namespace Plugins
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/plugins/ags_sprite_font/sprite_font.cpp b/engines/ags/plugins/ags_sprite_font/sprite_font.cpp
index 19e4ea1997..2681c46752 100644
--- a/engines/ags/plugins/ags_sprite_font/sprite_font.cpp
+++ b/engines/ags/plugins/ags_sprite_font/sprite_font.cpp
@@ -1,7 +1,36 @@
-#include "SpriteFont.h"
+/* 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 "ags/plugins/ags_sprite_font/sprite_font.h"
+
+namespace AGS3 {
+namespace Plugins {
+namespace AGSSpriteFont {
 
 SpriteFont::SpriteFont(void) = default;
 
 
 SpriteFont::~SpriteFont(void) = default;
+
+} // namespace AGSSpriteFont
+} // namespace Plugins
+} // namespace AGS3
diff --git a/engines/ags/plugins/ags_sprite_font/sprite_font.h b/engines/ags/plugins/ags_sprite_font/sprite_font.h
index 860aaddeae..59259c4344 100644
--- a/engines/ags/plugins/ags_sprite_font/sprite_font.h
+++ b/engines/ags/plugins/ags_sprite_font/sprite_font.h
@@ -1,4 +1,32 @@
-#pragma once
+/* 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 AGS_PLUGINS_AGS_SPRITE_FONT_SPRITE_FONT_H
+#define AGS_PLUGINS_AGS_SPRITE_FONT_SPRITE_FONT_H
+
+namespace AGS3 {
+namespace Plugins {
+namespace AGSSpriteFont {
+
 class SpriteFont {
 public:
 	SpriteFont(void);
@@ -14,3 +42,8 @@ public:
 	bool Use32bit;
 };
 
+} // namespace AGSSpriteFont
+} // namespace Plugins
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/plugins/ags_sprite_font/sprite_font_renderer.cpp b/engines/ags/plugins/ags_sprite_font/sprite_font_renderer.cpp
index c12fca0382..2062456daa 100644
--- a/engines/ags/plugins/ags_sprite_font/sprite_font_renderer.cpp
+++ b/engines/ags/plugins/ags_sprite_font/sprite_font_renderer.cpp
@@ -1,9 +1,31 @@
-#include "SpriteFontRenderer.h"
-#include <stdio.h>
-#include <string.h>
-#include "color.h"
-
-
+/* 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 "ags/plugins/ags_sprite_font/sprite_font_renderer.h"
+#include "ags/plugins/ags_sprite_font/color.h"
+
+namespace AGS3 {
+namespace Plugins {
+namespace AGSSpriteFont {
 
 SpriteFontRenderer::SpriteFontRenderer(IAGSEngine *engine) {
 	_engine = engine;
@@ -165,7 +187,8 @@ void SpriteFontRenderer::Draw(BITMAP *src, BITMAP *dest, int destx, int desty, i
 
 	_engine->ReleaseBitmapSurface(src);
 	_engine->ReleaseBitmapSurface(dest);
+}
 
-
-
-}
\ No newline at end of file
+} // namespace AGSSpriteFont
+} // namespace Plugins
+} // namespace AGS3
diff --git a/engines/ags/plugins/ags_sprite_font/sprite_font_renderer.h b/engines/ags/plugins/ags_sprite_font/sprite_font_renderer.h
index 0fcd57684f..7659af7745 100644
--- a/engines/ags/plugins/ags_sprite_font/sprite_font_renderer.h
+++ b/engines/ags/plugins/ags_sprite_font/sprite_font_renderer.h
@@ -1,7 +1,36 @@
-#pragma once
-#include "plugin/agsplugin.h"
-#include "SpriteFont.h"
-#include <vector>
+/* 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 AGS_PLUGINS_AGS_SPRITE_FONT_SPR_FONT_RENDERER_H
+#define AGS_PLUGINS_AGS_SPRITE_FONT_SPR_FONT_RENDERER_H
+
+#include "ags/plugins/ags_sprite_font/sprite_font.h"
+#include "ags/engine/plugin/agsplugin.h"
+#include "ags/lib/std/vector.h"
+
+namespace AGS3 {
+namespace Plugins {
+namespace AGSSpriteFont {
+
 class SpriteFontRenderer :
 	public IAGSFontRenderer {
 public:
@@ -19,7 +48,6 @@ public:
 	void EnsureTextValidForFont(char *text, int fontNumber) override;
 	void SetSpriteFont(int fontNum, int sprite, int rows, int columns, int charWidth, int charHeight, int charMin, int charMax, bool use32bit);
 
-
 private:
 	SpriteFont *getFontFor(int fontNum);
 	void Draw(BITMAP *src, BITMAP *dest, int destx, int desty, int srcx, int srcy, int width, int height);
@@ -27,3 +55,8 @@ private:
 	IAGSEngine *_engine;
 };
 
+} // namespace AGSSpriteFont
+} // namespace Plugins
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/plugins/ags_sprite_font/variable_width_font.cpp b/engines/ags/plugins/ags_sprite_font/variable_width_font.cpp
index 41baaac170..5361439b0d 100644
--- a/engines/ags/plugins/ags_sprite_font/variable_width_font.cpp
+++ b/engines/ags/plugins/ags_sprite_font/variable_width_font.cpp
@@ -1,5 +1,30 @@
-#include "VariableWidthFont.h"
+/* 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 "ags/plugins/ags_sprite_font/variable_width_font.h"
+
+namespace AGS3 {
+namespace Plugins {
+namespace AGSSpriteFont {
 
 VariableWidthFont::VariableWidthFont(void) {
 	Spacing = 0;
@@ -17,3 +42,7 @@ void VariableWidthFont::SetGlyph(int character, int x, int y, int width, int hei
 	characters[character].Height = height;
 	characters[character].Character = character;
 }
+
+} // namespace AGSSpriteFont
+} // namespace Plugins
+} // namespace AGS3
diff --git a/engines/ags/plugins/ags_sprite_font/variable_width_font.h b/engines/ags/plugins/ags_sprite_font/variable_width_font.h
index 8eda7123cf..5eb5bccbdd 100644
--- a/engines/ags/plugins/ags_sprite_font/variable_width_font.h
+++ b/engines/ags/plugins/ags_sprite_font/variable_width_font.h
@@ -1,7 +1,36 @@
-#pragma once
-#include <map>
-#include "CharacterEntry.h"
-#include "plugin/agsplugin.h"
+/* 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 AGS_PLUGINS_AGS_SPRITE_FONT_VAR_WIDTH_FONT_H
+#define AGS_PLUGINS_AGS_SPRITE_FONT_VAR_WIDTH_FONT_H
+
+#include "ags/plugins/ags_sprite_font/character_entry.h"
+#include "ags/engine/plugin/agsplugin.h"
+#include "ags/lib/std/map.h"
+
+namespace AGS3 {
+namespace Plugins {
+namespace AGSSpriteFont {
+
 class VariableWidthFont {
 public:
 	VariableWidthFont(void);
@@ -11,8 +40,10 @@ public:
 	int FontReplaced;
 	int Spacing;
 	std::map<char, CharacterEntry> characters;
-
-private:
-
 };
 
+} // namespace AGSSpriteFont
+} // namespace Plugins
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.cpp b/engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.cpp
index b6015ef8e1..827b686e99 100644
--- a/engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.cpp
+++ b/engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.cpp
@@ -1,9 +1,31 @@
-#include "VariableWidthSpriteFont.h"
-#include <string>
-#include <string.h>
-#include "color.h"
-
-
+/* 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 "ags/plugins/ags_sprite_font/variable_width_sprite_font.h"
+#include "ags/plugins/ags_sprite_font/color.h"
+
+namespace AGS3 {
+namespace Plugins {
+namespace AGSSpriteFont {
 
 VariableWidthSpriteFontRenderer::VariableWidthSpriteFontRenderer(IAGSEngine *engine) {
 	_engine = engine;
@@ -22,7 +44,7 @@ bool VariableWidthSpriteFontRenderer::SupportsExtendedCharacters(int fontNumber)
 int VariableWidthSpriteFontRenderer::GetTextWidth(const char *text, int fontNumber) {
 	int total = 0;
 	VariableWidthFont *font = getFontFor(fontNumber);
-	for (int i = 0; i < strlen(text); i++) {
+	for (int i = 0; i < (int)strlen(text); i++) {
 		if (font->characters.count(text[i]) > 0) {
 			total += font->characters[text[i]].Width;
 			if (text[i] != ' ') total += font->Spacing;
@@ -33,7 +55,7 @@ int VariableWidthSpriteFontRenderer::GetTextWidth(const char *text, int fontNumb
 
 int VariableWidthSpriteFontRenderer::GetTextHeight(const char *text, int fontNumber) {
 	VariableWidthFont *font = getFontFor(fontNumber);
-	for (int i = 0; i < strlen(text); i++) {
+	for (int i = 0; i < (int)strlen(text); i++) {
 		if (font->characters.count(text[i]) > 0) {
 			return font->characters[text[i]].Height;
 		}
@@ -50,9 +72,9 @@ void VariableWidthSpriteFontRenderer::SetSpacing(int fontNum, int spacing) {
 
 void VariableWidthSpriteFontRenderer::EnsureTextValidForFont(char *text, int fontNumber) {
 	VariableWidthFont *font = getFontFor(fontNumber);
-	std::string s(text);
+	Common::String s(text);
 
-	for (int i = s.length() - 1; i >= 0 ; i--) {
+	for (int i = (int)s.size() - 1; i >= 0 ; i--) {
 		if (font->characters.count(s[i]) == 0) {
 			s.erase(i, 1);
 		}
@@ -74,7 +96,7 @@ void VariableWidthSpriteFontRenderer::SetSprite(int fontNum, int spriteNum) {
 
 VariableWidthFont *VariableWidthSpriteFontRenderer::getFontFor(int fontNum) {
 	VariableWidthFont *font;
-	for (int i = 0; i < _fonts.size(); i ++) {
+	for (int i = 0; i < (int)_fonts.size(); i ++) {
 		font = _fonts.at(i);
 		if (font->FontReplaced == fontNum) return font;
 	}
@@ -88,7 +110,7 @@ VariableWidthFont *VariableWidthSpriteFontRenderer::getFontFor(int fontNum) {
 void VariableWidthSpriteFontRenderer::RenderText(const char *text, int fontNumber, BITMAP *destination, int x, int y, int colour) {
 	VariableWidthFont *font = getFontFor(fontNumber);
 	int totalWidth = 0;
-	for (int i = 0; i < strlen(text); i++) {
+	for (int i = 0; i < (int)strlen(text); i++) {
 		char c = text[i];
 
 		BITMAP *src = _engine->GetSpriteGraphic(font->SpriteNumber);
@@ -175,8 +197,8 @@ void VariableWidthSpriteFontRenderer::Draw(BITMAP *src, BITMAP *dest, int destx,
 
 	_engine->ReleaseBitmapSurface(src);
 	_engine->ReleaseBitmapSurface(dest);
-
-
-
 }
 
+} // namespace AGSSpriteFont
+} // namespace Plugins
+} // namespace AGS3
diff --git a/engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.h b/engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.h
index 30b5211ca3..edfffa4d5d 100644
--- a/engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.h
+++ b/engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.h
@@ -1,7 +1,37 @@
-#pragma once
-#include "plugin/agsplugin.h"
-#include "VariableWidthFont.h"
-#include <vector>
+/* 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 AGS_PLUGINS_AGS_SPRITE_FONT_VAR_WIDTH_SPR_FONT_H
+#define AGS_PLUGINS_AGS_SPRITE_FONT_VAR_WIDTH_SPR_FONT_H
+
+#include "ags/plugins/dll.h"
+#include "ags/plugins/serializer.h"
+#include "ags/engine/plugin/agsplugin.h"
+#include "ags/plugins/ags_sprite_font/variable_width_font.h"
+
+namespace AGS3 {
+namespace Plugins {
+namespace AGSSpriteFont {
+
 class VariableWidthSpriteFontRenderer :
 	public IAGSFontRenderer {
 public:
@@ -28,3 +58,8 @@ private:
 	void Draw(BITMAP *src, BITMAP *dest, int destx, int desty, int srcx, int srcy, int width, int height);
 };
 
+} // namespace AGSSpriteFont
+} // namespace Plugins
+} // namespace AGS3
+
+#endif
diff --git a/engines/ags/plugins/dll.cpp b/engines/ags/plugins/dll.cpp
index 4d3554b5ce..e629c2a438 100644
--- a/engines/ags/plugins/dll.cpp
+++ b/engines/ags/plugins/dll.cpp
@@ -27,6 +27,7 @@
 #include "ags/plugins/ags_flashlight/ags_flashlight.h"
 #include "ags/plugins/ags_pal_render/ags_pal_render.h"
 #include "ags/plugins/ags_snow_rain/ags_snow_rain.h"
+#include "ags/plugins/ags_sprite_font/ags_sprite_font.h"
 #include "ags/ags.h"
 #include "ags/detection.h"
 #include "common/str.h"
@@ -66,6 +67,9 @@ void *dlopen(const char *filename) {
 	if (fname.equalsIgnoreCase("libAGSSnowRain.so"))
 		return new AGSSnowRain::AGSSnowRain();
 
+	if (fname.equalsIgnoreCase("libAGSSpriteFont.so"))
+		return new AGSSpriteFont::AGSSpriteFont();
+
 	return nullptr;
 }
 


Commit: 8bc249b99fefc87690a041f0dadfe8a851960674
    https://github.com/scummvm/scummvm/commit/8bc249b99fefc87690a041f0dadfe8a851960674
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: gcc compilation fixes

Changed paths:
    engines/ags/engine/plugin/agsplugin.h
    engines/ags/plugins/ags_flashlight/ags_flashlight.cpp
    engines/ags/plugins/ags_pal_render/ags_pal_render.cpp
    engines/ags/plugins/ags_pal_render/raycast.cpp
    engines/ags/plugins/ags_parallax/ags_parallax.cpp
    engines/ags/plugins/ags_snow_rain/ags_snow_rain.cpp
    engines/ags/plugins/ags_snow_rain/weather.cpp
    engines/ags/plugins/ags_sprite_font/sprite_font_renderer.cpp
    engines/ags/plugins/ags_sprite_font/sprite_font_renderer.h
    engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.h


diff --git a/engines/ags/engine/plugin/agsplugin.h b/engines/ags/engine/plugin/agsplugin.h
index 3f564c214c..2ab5b3873c 100644
--- a/engines/ags/engine/plugin/agsplugin.h
+++ b/engines/ags/engine/plugin/agsplugin.h
@@ -31,6 +31,7 @@
 #ifndef AGS_ENGINE_PLUGIN_AGSPLUGIN_H
 #define AGS_ENGINE_PLUGIN_AGSPLUGIN_H
 
+#include "ags/shared/core/types.h"
 #include "common/array.h"
 
 namespace AGS3 {
diff --git a/engines/ags/plugins/ags_flashlight/ags_flashlight.cpp b/engines/ags/plugins/ags_flashlight/ags_flashlight.cpp
index 116c4a0449..cccddec62d 100644
--- a/engines/ags/plugins/ags_flashlight/ags_flashlight.cpp
+++ b/engines/ags/plugins/ags_flashlight/ags_flashlight.cpp
@@ -126,41 +126,41 @@ void AGSFlashlight::AGS_EngineStartup(IAGSEngine *engine) {
 	if (_engine->version < 13)
 		_engine->AbortGame("Engine interface is too old, need newer version of AGS.");
 
-	SCRIPT_METHOD("SetFlashlightTint");
-	SCRIPT_METHOD("GetFlashlightTintRed");
-	SCRIPT_METHOD("GetFlashlightTintGreen");
-	SCRIPT_METHOD("GetFlashlightTintBlue");
+	SCRIPT_METHOD(SetFlashlightTint);
+	SCRIPT_METHOD(GetFlashlightTintRed);
+	SCRIPT_METHOD(GetFlashlightTintGreen);
+	SCRIPT_METHOD(GetFlashlightTintBlue);
 
-	SCRIPT_METHOD("GetFlashlightMinLightLevel");
-	SCRIPT_METHOD("GetFlashlightMaxLightLevel");
+	SCRIPT_METHOD(GetFlashlightMinLightLevel);
+	SCRIPT_METHOD(GetFlashlightMaxLightLevel);
 
-	SCRIPT_METHOD("SetFlashlightDarkness");
-	SCRIPT_METHOD("GetFlashlightDarkness");
-	SCRIPT_METHOD("SetFlashlightDarknessSize");
-	SCRIPT_METHOD("GetFlashlightDarknessSize");
+	SCRIPT_METHOD(SetFlashlightDarkness);
+	SCRIPT_METHOD(GetFlashlightDarkness);
+	SCRIPT_METHOD(SetFlashlightDarknessSize);
+	SCRIPT_METHOD(GetFlashlightDarknessSize);
 
-	SCRIPT_METHOD("SetFlashlightBrightness");
-	SCRIPT_METHOD("GetFlashlightBrightness");
-	SCRIPT_METHOD("SetFlashlightBrightnessSize");
-	SCRIPT_METHOD("GetFlashlightBrightnessSize");
+	SCRIPT_METHOD(SetFlashlightBrightness);
+	SCRIPT_METHOD(GetFlashlightBrightness);
+	SCRIPT_METHOD(SetFlashlightBrightnessSize);
+	SCRIPT_METHOD(GetFlashlightBrightnessSize);
 
-	SCRIPT_METHOD("SetFlashlightPosition");
-	SCRIPT_METHOD("GetFlashlightPositionX");
-	SCRIPT_METHOD("GetFlashlightPositionY");
+	SCRIPT_METHOD(SetFlashlightPosition);
+	SCRIPT_METHOD(GetFlashlightPositionX);
+	SCRIPT_METHOD(GetFlashlightPositionY);
 
 
-	SCRIPT_METHOD("SetFlashlightFollowMouse");
-	SCRIPT_METHOD("GetFlashlightFollowMouse");
+	SCRIPT_METHOD(SetFlashlightFollowMouse);
+	SCRIPT_METHOD(GetFlashlightFollowMouse);
 
-	SCRIPT_METHOD("SetFlashlightFollowCharacter");
-	SCRIPT_METHOD("GetFlashlightFollowCharacter");
-	SCRIPT_METHOD("GetFlashlightCharacterDX");
-	SCRIPT_METHOD("GetFlashlightCharacterDY");
-	SCRIPT_METHOD("GetFlashlightCharacterHorz");
-	SCRIPT_METHOD("GetFlashlightCharacterVert");
+	SCRIPT_METHOD(SetFlashlightFollowCharacter);
+	SCRIPT_METHOD(GetFlashlightFollowCharacter);
+	SCRIPT_METHOD(GetFlashlightCharacterDX);
+	SCRIPT_METHOD(GetFlashlightCharacterDY);
+	SCRIPT_METHOD(GetFlashlightCharacterHorz);
+	SCRIPT_METHOD(GetFlashlightCharacterVert);
 
-	SCRIPT_METHOD("SetFlashlightMask");
-	SCRIPT_METHOD("GetFlashlightMask");
+	SCRIPT_METHOD(SetFlashlightMask);
+	SCRIPT_METHOD(GetFlashlightMask);
 
 	_engine->RequestEventHook(AGSE_PREGUIDRAW);
 	_engine->RequestEventHook(AGSE_PRESCREENDRAW);
diff --git a/engines/ags/plugins/ags_pal_render/ags_pal_render.cpp b/engines/ags/plugins/ags_pal_render/ags_pal_render.cpp
index b7467a09f5..58f89b6eb3 100644
--- a/engines/ags/plugins/ags_pal_render/ags_pal_render.cpp
+++ b/engines/ags/plugins/ags_pal_render/ags_pal_render.cpp
@@ -1068,14 +1068,18 @@ int GetTranslucentOverlayAlpha(int id) {
 }
 
 int SetTranslucentOverlayAlpha(int id, int alpha) {
-	if (alpha >= 0 && alpha < 256) overlay[id].trans = alpha;
-	else engine->AbortGame("CreateTranslucentOverlay: Invalid alpha selected.");
+	if (alpha >= 0 && alpha < 256)
+		overlay[id].trans = alpha;
+	else
+		engine->AbortGame("CreateTranslucentOverlay: Invalid alpha selected.");
 	return 0;
 }
 
 int SetTranslucentOverlayEnabled(int id, int toggle) {
-	if (toggle > 0) overlay[id].enabled = true;
-	else overlay[id].enabled = false;
+	if (toggle > 0)
+		overlay[id].enabled = true;
+	else
+		overlay[id].enabled = false;
 	return 0;
 }
 
@@ -1085,16 +1089,18 @@ void SetCharacterReflected(int id, int refl) {
 }
 
 void SetObjectReflected(int id, int refl) {
-	if (refl > 0) Reflection.Objects[id].reflect = 1;
-	else Reflection.Objects[id].reflect = 0;
+	if (refl > 0)
+		Reflection.Objects[id].reflect = 1;
+	else
+		Reflection.Objects[id].reflect = 0;
 }
 
 int GetCharacterReflected(int id) {
 	return Reflection.Characters[id].reflect;
 }
 
-void GetObjectReflected(int id) {
-	Reflection.Objects[id].reflect;
+int GetObjectReflected(int id) {
+	return Reflection.Objects[id].reflect;
 }
 
 void ReplaceCharacterReflectionView(int id, int view) {
@@ -1131,9 +1137,10 @@ int DrawReflections(int id, int charobj = 0) {
 	//Get character, and their sprite.
 	if (charobj == 0) {
 		currchar = engine->GetCharacter(id);
-		int view = 0;
+		/*int view = 0;
 		if (Reflection.Characters[id].replaceview == 0) view = currchar->view + 1;
 		else view = Reflection.Characters[id].replaceview;
+		*/
 		AGSViewFrame *vf = engine->GetViewFrame(currchar->view + 1, currchar->loop, currchar->frame);
 		charsprite = engine->GetSpriteGraphic(vf->pic);
 		long scaling = currchar->flags & CHF_NOSCALING;
@@ -1270,8 +1277,7 @@ int DrawTransSprite(int spriteId, int bg, int translevel, int mask = 0, int blen
 	if (mask > 0) maskspr = engine->GetSpriteGraphic(mask);
 	if (!maskspr && mask > 0) {
 		char maskerr [100];
-		int cx;
-		cx = snprintf(maskerr, 100, "DrawTransSprite: Can't load mask from slot %d.", mask);
+		snprintf(maskerr, 100, "DrawTransSprite: Can't load mask from slot %d.", mask);
 		engine->AbortGame(maskerr);
 	}
 	// Get a reference to the screen we'll draw onto
diff --git a/engines/ags/plugins/ags_pal_render/raycast.cpp b/engines/ags/plugins/ags_pal_render/raycast.cpp
index fe26cfb8bb..405c7550c7 100644
--- a/engines/ags/plugins/ags_pal_render/raycast.cpp
+++ b/engines/ags/plugins/ags_pal_render/raycast.cpp
@@ -111,21 +111,21 @@ int Ray_GetNoClip() {
 }
 
 void Ray_DrawTile(int spr, int tile) {
-	BITMAP *sprite = engine->GetSpriteGraphic(spr);
-	unsigned char **sprarray = engine->GetRawBitmapSurface(sprite);
+	BITMAP *img = engine->GetSpriteGraphic(spr);
+	unsigned char **sprarray = engine->GetRawBitmapSurface(img);
 	for (int y = 0; y < 64; ++y)
 		for (int x = 0; x < 64; ++x)
 			sprarray [y][x] = texture [tile][(texWidth * y) + x];
-	engine->ReleaseBitmapSurface(sprite);
+	engine->ReleaseBitmapSurface(img);
 }
 
 void Ray_DrawOntoTile(int spr, int tile) {
-	BITMAP *sprite = engine->GetSpriteGraphic(spr);
-	unsigned char **sprarray = engine->GetRawBitmapSurface(sprite);
+	BITMAP *img = engine->GetSpriteGraphic(spr);
+	unsigned char **sprarray = engine->GetRawBitmapSurface(img);
 	for (int y = 0; y < 64; ++y)
 		for (int x = 0; x < 64; ++x)
 			texture [tile][(texWidth * y) + x] = sprarray [y][x];
-	engine->ReleaseBitmapSurface(sprite);
+	engine->ReleaseBitmapSurface(img);
 }
 
 int Ray_GetTileX_At(int x, int y) {
@@ -351,14 +351,14 @@ void LoadHeightMap(int heightmapSlot) {
 void LoadMap(int worldmapSlot, int lightmapSlot, int ceilingmapSlot, int floormapSlot) {
 	int tempw = engine->GetSpriteWidth(worldmapSlot);
 	int temph = engine->GetSpriteHeight(worldmapSlot);
-	BITMAP *worldmapBm;
-	BITMAP *lightmapBm;
-	BITMAP *floormapBm;
-	BITMAP *ceilingmapBm;
-	unsigned char **wmArray;
-	unsigned char **lmArray;
-	unsigned char **fmArray;
-	unsigned char **cmArray;
+	BITMAP *worldmapBm = nullptr;
+	BITMAP *lightmapBm = nullptr;
+	BITMAP *floormapBm = nullptr;
+	BITMAP *ceilingmapBm = nullptr;
+	unsigned char **wmArray = nullptr;
+	unsigned char **lmArray = nullptr;
+	unsigned char **fmArray = nullptr;
+	unsigned char **cmArray = nullptr;
 	worldmapBm = engine->GetSpriteGraphic(worldmapSlot);
 	if (!worldmapBm) engine->AbortGame("LoadMap: Couldn't load worldmap sprite into memory.");
 	wmArray = engine->GetRawBitmapSurface(worldmapBm);
@@ -533,7 +533,7 @@ void MakeTextures(int slot) {
 	unsigned char **texbuffer = engine->GetRawBitmapSurface(texspr);
 	int numTilesX = sourceWidth / texWidth;
 	int numTilesY = sourceHeight / texHeight;
-	int totaltiles = numTilesX * numTilesY;
+	//int totaltiles = numTilesX * numTilesY;
 	for (int numX = 0; numX < numTilesX; ++numX) {
 		for (int numY = 0; numY < numTilesY; ++numY) {
 			for (int x = 0; x < texWidth; ++x)
@@ -648,8 +648,9 @@ FLOAT_RETURN_TYPE Ray_GetDistanceAt(int x, int y) {
 }
 
 void Init_Raycaster() {
-	if (ZBuffer) return;
-	if (!worldMap) return;
+	if (ZBuffer)
+		return;
+	//if (!worldMap) return;
 	transcolorbuffer = new unsigned char *[sWidth];
 	transalphabuffer = new unsigned char *[sWidth];
 	transslicedrawn = new bool[sWidth]();
@@ -683,7 +684,7 @@ void Raycast_Render(int slot) {
 	BITMAP *sbBm = engine->GetSpriteGraphic(skybox);
 	if (!sbBm) engine->AbortGame("Raycast_Render: No valid skybox sprite.");
 	if (skybox > 0) {
-		int bgdeg = (int)((playerrad / PI) * 180.0) + 180;
+		//int bgdeg = (int)((playerrad / PI) * 180.0) + 180;
 		int xoffset = (int)(playerrad * 320.0);
 		BITMAP *virtsc = engine->GetVirtualScreen();
 		engine->SetVirtualScreen(screen);
@@ -702,7 +703,7 @@ void Raycast_Render(int slot) {
 			ZBuffer[x][y] = 0;
 		}
 	}
-	int multiplier = mapWidth;
+	//int multiplier = mapWidth;
 	memset(interactionmap, 0, sizeof(short) * (sHeight * sWidth));
 	//start the main loop
 	for (int x = 0; x < w; x++) {
@@ -725,7 +726,7 @@ void Raycast_Render(int slot) {
 		//length of ray from one x or y-side to next x or y-side
 		double deltaDistX = fsqrt(1 + (rayDirY * rayDirY) / (rayDirX * rayDirX));
 		double deltaDistY = fsqrt(1 + (rayDirX * rayDirX) / (rayDirY * rayDirY));
-		double perpWallDist;
+		double perpWallDist = 0.0;
 
 		//what direction to step in x or y-direction (either +1 or -1)
 		int stepX;
@@ -733,7 +734,7 @@ void Raycast_Render(int slot) {
 		int prevmapX = 0;
 		int prevmapY = 0;
 		int hit = 0; //was there a wall hit?
-		int side; //was a NS or a EW wall hit?
+		int side = 0; //was a NS or a EW wall hit?
 
 		//calculate step and initial sideDist
 		if (rayDirX < 0) {
@@ -750,13 +751,13 @@ void Raycast_Render(int slot) {
 			stepY = 1;
 			sideDistY = (mapY + 1.0 - rayPosY) * deltaDistY;
 		}
-		//perform DDA
+		// Perform DDA
 		bool deeper = true;
 		bool opposite = true;
 		bool oppositedrawn = false;
-		double wallX; //where exactly the wall was hit
+		double wallX = 0; // Where exactly the wall was hit
 		int drawStart;
-		int drawEnd;
+		int drawEnd = 0;
 		while (hit == 0 && deeper == true) {
 			if (opposite) {
 				rayDirX = -rayDirX;
@@ -765,7 +766,7 @@ void Raycast_Render(int slot) {
 				stepY = -stepY;
 				if (sideDistX < sideDistY) side = 0;
 				else side = 1;
-			} else if (sideDistX < sideDistY) { //jump to next map square, OR in x-direction, OR in y-direction
+			} else if (sideDistX < sideDistY) { // jump to next map square, OR in x-direction, OR in y-direction
 				sideDistX += deltaDistX;
 				mapX += stepX;
 				mapX = abs(mapX) % mapHeight;
@@ -802,7 +803,7 @@ void Raycast_Render(int slot) {
 					opposite = false;
 				}
 			}
-			int texside;
+			int texside = 0;
 			if (rayDirX > 0 && side == 0) texside = 0;
 			if (rayDirX < 0 && side == 0) texside = 1;
 			if (rayDirY > 0 && side == 1) texside = 2;
@@ -976,6 +977,10 @@ void Raycast_Render(int slot) {
 			//End of loop.
 		}
 
+		// Unused variables
+		(void)prevmapX;
+		(void)prevmapY;
+
 		//FLOOR CASTING
 
 		double floorXWall, floorYWall; //x, y position of the floor texel at the bottom of the wall
@@ -1002,7 +1007,8 @@ void Raycast_Render(int slot) {
 
 		distWall = perpWallDist;
 		distPlayer = 0.0;
-		if (drawEnd < 0) drawEnd = h - 1; //becomes < 0 when the integer overflows
+		if (drawEnd < 0)
+			drawEnd = h - 1; //becomes < 0 when the integer overflows
 		//draw the floor from drawEnd to the bottom of the screen
 		int drawdist = h;
 		int expandeddraw = h >> 1;
@@ -1010,7 +1016,7 @@ void Raycast_Render(int slot) {
 			//currentDist = h / (2.0 * y - h); //you could make a small lookup table for this instead
 			currentDist = distTable[y];
 			if (y > h - 1) {
-				if (!heightMap) break;
+				//if (!heightMap) break;
 				double weight = (currentDist - distPlayer) / (distWall - distPlayer);
 
 				double currentFloorX = weight * floorXWall + (1.0 - weight) * posX;
@@ -1045,7 +1051,7 @@ void Raycast_Render(int slot) {
 					if (floorcolor) floorcolor = Mix::MixColorLightLevel(floorcolor, lighting);
 				}
 
-				if (heightMap && floorcolor > 0) {
+				if (/*heightMap &&*/ floorcolor > 0) {
 					if (heightMap[cmapX][cmapY] - 1 > 0) {
 						int raisedfloorstart = y - (int)(texture[heightMap[cmapX][cmapY] - 1][texpos] / currentDist);
 						if (raisedfloorstart > h - 1) continue;
@@ -1093,7 +1099,7 @@ void Raycast_Render(int slot) {
 					if (ceilingcolor) ceilingcolor = Mix::MixColorLightLevel(ceilingcolor, lighting);
 				}
 
-				if (heightMap && floorcolor > 0 && (currentDist < ZBuffer[x][y] || ZBuffer[x][y] == 0)) {
+				if (/*heightMap &&*/ floorcolor > 0 && (currentDist < ZBuffer[x][y] || ZBuffer[x][y] == 0)) {
 					if (heightMap[cmapX][cmapY] - 1 > 0) {
 						int raisedfloorstart = y - (int)(texture[heightMap[cmapX][cmapY] - 1][texWidth * floorTexY + floorTexX] / currentDist);
 						if (raisedfloorstart > h - 1) continue;
@@ -1210,8 +1216,8 @@ void Raycast_Render(int slot) {
 		// [ planeY   dirY ]                                          [ -planeY  planeX ]
 
 		//double invDet = 1.0 / (planeX * dirY - dirX * planeY); //required for correct matrix multiplication
-		double spriteX = sprite[spriteOrder[i]].x - posX;
-		double spriteY = sprite[spriteOrder[i]].y - posY;
+		//double spriteX = sprite[spriteOrder[i]].x - posX;
+		//double spriteY = sprite[spriteOrder[i]].y - posY;
 		//double transformX = invDet * (dirY * spriteX - dirX * spriteY);
 		//double transformY = invDet * (-planeY * spriteX + planeX * spriteY); //this is actually the depth inside the screen, that what Z is in 3D
 
diff --git a/engines/ags/plugins/ags_parallax/ags_parallax.cpp b/engines/ags/plugins/ags_parallax/ags_parallax.cpp
index 1bb6eff354..0a7b123e74 100644
--- a/engines/ags/plugins/ags_parallax/ags_parallax.cpp
+++ b/engines/ags/plugins/ags_parallax/ags_parallax.cpp
@@ -62,8 +62,8 @@ void AGSParallax::AGS_EngineStartup(IAGSEngine *engine) {
 	if (_engine->version < 13)
 		_engine->AbortGame("Engine interface is too old, need newer version of AGS.");
 
-	SCRIPT_METHOD("pxDrawSprite");
-	SCRIPT_METHOD("pxDeleteSprite");
+	SCRIPT_METHOD(pxDrawSprite);
+	SCRIPT_METHOD(pxDeleteSprite);
 
 	_engine->RequestEventHook(AGSE_PREGUIDRAW);
 	_engine->RequestEventHook(AGSE_PRESCREENDRAW);
@@ -107,7 +107,7 @@ void AGSParallax::clear() {
 void AGSParallax::SyncGame(Serializer &s) {
 	int saveVersion = SaveMagic;
 	s.syncAsInt(saveVersion);
-	if (saveVersion != SaveMagic) {
+	if ((uint)saveVersion != SaveMagic) {
 		_engine->AbortGame("ags_parallax: bad save.");
 		return;
 	}
diff --git a/engines/ags/plugins/ags_snow_rain/ags_snow_rain.cpp b/engines/ags/plugins/ags_snow_rain/ags_snow_rain.cpp
index 36caa39999..92764acc25 100644
--- a/engines/ags/plugins/ags_snow_rain/ags_snow_rain.cpp
+++ b/engines/ags/plugins/ags_snow_rain/ags_snow_rain.cpp
@@ -57,30 +57,30 @@ void AGSSnowRain::AGS_EngineStartup(IAGSEngine *engine) {
 	if (_engine->version < 13)
 		_engine->AbortGame("Engine interface is too old, need newer version of AGS.");
 
-	SCRIPT_METHOD("srSetSnowDriftRange");
-	SCRIPT_METHOD("srSetSnowDriftSpeed");
-	SCRIPT_METHOD("srSetSnowFallSpeed");
-	SCRIPT_METHOD("srChangeSnowAmount");
-	SCRIPT_METHOD("srSetSnowBaseline");
-	SCRIPT_METHOD("srSetSnowTransparency");
-	SCRIPT_METHOD("srSetSnowDefaultView");
-	SCRIPT_METHOD("srSetSnowWindSpeed");
-	SCRIPT_METHOD("srSetSnowAmount");
-	SCRIPT_METHOD("srSetSnowView");
-
-	SCRIPT_METHOD("srSetRainDriftRange");
-	SCRIPT_METHOD("srSetRainDriftSpeed");
-	SCRIPT_METHOD("srSetRainFallSpeed");
-	SCRIPT_METHOD("srChangeRainAmount");
-	SCRIPT_METHOD("srSetRainBaseline");
-	SCRIPT_METHOD("srSetRainTransparency");
-	SCRIPT_METHOD("srSetRainDefaultView");
-	SCRIPT_METHOD("srSetRainWindSpeed");
-	SCRIPT_METHOD("srSetRainAmount");
-	SCRIPT_METHOD("srSetRainView");
-
-	SCRIPT_METHOD("srSetWindSpeed");
-	SCRIPT_METHOD("srSetBaseline");
+	SCRIPT_METHOD(srSetSnowDriftRange);
+	SCRIPT_METHOD(srSetSnowDriftSpeed);
+	SCRIPT_METHOD(srSetSnowFallSpeed);
+	SCRIPT_METHOD(srChangeSnowAmount);
+	SCRIPT_METHOD(srSetSnowBaseline);
+	SCRIPT_METHOD(srSetSnowTransparency);
+	SCRIPT_METHOD(srSetSnowDefaultView);
+	SCRIPT_METHOD(srSetSnowWindSpeed);
+	SCRIPT_METHOD(srSetSnowAmount);
+	SCRIPT_METHOD(srSetSnowView);
+
+	SCRIPT_METHOD(srSetRainDriftRange);
+	SCRIPT_METHOD(srSetRainDriftSpeed);
+	SCRIPT_METHOD(srSetRainFallSpeed);
+	SCRIPT_METHOD(srChangeRainAmount);
+	SCRIPT_METHOD(srSetRainBaseline);
+	SCRIPT_METHOD(srSetRainTransparency);
+	SCRIPT_METHOD(srSetRainDefaultView);
+	SCRIPT_METHOD(srSetRainWindSpeed);
+	SCRIPT_METHOD(srSetRainAmount);
+	SCRIPT_METHOD(srSetRainView);
+
+	SCRIPT_METHOD(srSetWindSpeed);
+	SCRIPT_METHOD(srSetBaseline);
 
 	_engine->RequestEventHook(AGSE_PREGUIDRAW);
 	_engine->RequestEventHook(AGSE_PRESCREENDRAW);
diff --git a/engines/ags/plugins/ags_snow_rain/weather.cpp b/engines/ags/plugins/ags_snow_rain/weather.cpp
index 3798067749..c744be9bd7 100644
--- a/engines/ags/plugins/ags_snow_rain/weather.cpp
+++ b/engines/ags/plugins/ags_snow_rain/weather.cpp
@@ -137,7 +137,7 @@ void Weather::SyncGame(Serializer &s) {
 	int saveVersion = SaveMagic;
 	s.syncAsInt(saveVersion);
 
-	if (s.isLoading() && saveVersion != SaveMagic) {
+	if (s.isLoading() && (uint)saveVersion != SaveMagic) {
 		_engine->AbortGame("ags_snowrain: bad save.");
 		return;
 	}
diff --git a/engines/ags/plugins/ags_sprite_font/sprite_font_renderer.cpp b/engines/ags/plugins/ags_sprite_font/sprite_font_renderer.cpp
index 2062456daa..ed06779cf9 100644
--- a/engines/ags/plugins/ags_sprite_font/sprite_font_renderer.cpp
+++ b/engines/ags/plugins/ags_sprite_font/sprite_font_renderer.cpp
@@ -49,7 +49,7 @@ void SpriteFontRenderer::SetSpriteFont(int fontNum, int sprite, int rows, int co
 
 void SpriteFontRenderer::EnsureTextValidForFont(char *text, int fontNumber) {
 	SpriteFont *font = getFontFor(fontNumber);
-	for (int i = 0; i < strlen(text); i++) {
+	for (int i = 0; i < (int)strlen(text); i++) {
 		if (text[i] < font->MinChar || text[i] > font->MaxChar) {
 			if (font->MinChar < 63 || font->MaxChar > 63) text[i] = 63;
 			else text[i] = font->MinChar;
@@ -65,7 +65,7 @@ bool SpriteFontRenderer::SupportsExtendedCharacters(int fontNumber) {
 
 int SpriteFontRenderer::GetTextWidth(const char *text, int fontNumber) {
 	SpriteFont *font = getFontFor(fontNumber);
-	int len = strlen(text);
+	int len = (int)strlen(text);
 	return font->CharWidth * len;
 
 }
@@ -77,7 +77,7 @@ int SpriteFontRenderer::GetTextHeight(const char *text, int fontNumber) {
 
 SpriteFont *SpriteFontRenderer::getFontFor(int fontNum) {
 	SpriteFont *font;
-	for (int i = 0; i < _fonts.size(); i ++) {
+	for (int i = 0; i < (int)_fonts.size(); i ++) {
 		font = _fonts.at(i);
 		if (font->FontReplaced == fontNum) return font;
 	}
@@ -91,13 +91,12 @@ SpriteFont *SpriteFontRenderer::getFontFor(int fontNum) {
 
 
 void SpriteFontRenderer::RenderText(const char *text, int fontNumber, BITMAP *destination, int x, int y, int colour) {
-
 	SpriteFont *font = getFontFor(fontNumber);
-	BITMAP *vScreen = _engine->GetVirtualScreen();
+	//BITMAP *vScreen = _engine->GetVirtualScreen();
 
 	//_engine->SetVirtualScreen(destination);
 
-	for (int i = 0; i < strlen(text); i++) {
+	for (int i = 0; i < (int)strlen(text); i++) {
 		char c = text[i];
 		c -= font->MinChar;
 		int row = c / font->Columns;
diff --git a/engines/ags/plugins/ags_sprite_font/sprite_font_renderer.h b/engines/ags/plugins/ags_sprite_font/sprite_font_renderer.h
index 7659af7745..a5f2f373a0 100644
--- a/engines/ags/plugins/ags_sprite_font/sprite_font_renderer.h
+++ b/engines/ags/plugins/ags_sprite_font/sprite_font_renderer.h
@@ -31,11 +31,10 @@ namespace AGS3 {
 namespace Plugins {
 namespace AGSSpriteFont {
 
-class SpriteFontRenderer :
-	public IAGSFontRenderer {
+class SpriteFontRenderer : public IAGSFontRenderer {
 public:
 	SpriteFontRenderer(IAGSEngine *engine);
-	~SpriteFontRenderer(void);
+	virtual ~SpriteFontRenderer(void);
 	bool LoadFromDisk(int fontNumber, int fontSize) override {
 		return true;
 	}
diff --git a/engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.h b/engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.h
index edfffa4d5d..5625d21c1e 100644
--- a/engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.h
+++ b/engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.h
@@ -32,11 +32,10 @@ namespace AGS3 {
 namespace Plugins {
 namespace AGSSpriteFont {
 
-class VariableWidthSpriteFontRenderer :
-	public IAGSFontRenderer {
+class VariableWidthSpriteFontRenderer : public IAGSFontRenderer {
 public:
 	VariableWidthSpriteFontRenderer(IAGSEngine *engine);
-	~VariableWidthSpriteFontRenderer(void);
+	virtual ~VariableWidthSpriteFontRenderer();
 	bool LoadFromDisk(int fontNumber, int fontSize) override {
 		return true;
 	}


Commit: d6b8c21557d11f089951c2b89b726fe0b6050fc6
    https://github.com/scummvm/scummvm/commit/d6b8c21557d11f089951c2b89b726fe0b6050fc6
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Merged engine/plugin/ into plugins/ folder

Changed paths:
  A engines/ags/plugins/agsplugin.cpp
  A engines/ags/plugins/agsplugin.h
  A engines/ags/plugins/global_plugin.cpp
  A engines/ags/plugins/library.cpp
  A engines/ags/plugins/library.h
  A engines/ags/plugins/plugin_builtin.h
  A engines/ags/plugins/plugin_engine.h
  A engines/ags/plugins/pluginobjectreader.cpp
  A engines/ags/plugins/pluginobjectreader.h
  R engines/ags/engine/plugin/agsplugin.cpp
  R engines/ags/engine/plugin/agsplugin.h
  R engines/ags/engine/plugin/global_plugin.cpp
  R engines/ags/engine/plugin/library.cpp
  R engines/ags/engine/plugin/library.h
  R engines/ags/engine/plugin/plugin_builtin.h
  R engines/ags/engine/plugin/plugin_engine.h
  R engines/ags/engine/plugin/pluginobjectreader.cpp
  R engines/ags/engine/plugin/pluginobjectreader.h
    engines/ags/engine/ac/draw.cpp
    engines/ags/engine/ac/dynobj/cc_serializer.cpp
    engines/ags/engine/ac/event.cpp
    engines/ags/engine/ac/game.cpp
    engines/ags/engine/ac/global_translation.cpp
    engines/ags/engine/ac/room.cpp
    engines/ags/engine/ac/screen.cpp
    engines/ags/engine/ac/sprite.cpp
    engines/ags/engine/debugging/debug.cpp
    engines/ags/engine/game/game_init.cpp
    engines/ags/engine/game/savegame.cpp
    engines/ags/engine/game/savegame_components.cpp
    engines/ags/engine/main/game_file.cpp
    engines/ags/engine/main/game_run.cpp
    engines/ags/engine/main/quit.cpp
    engines/ags/engine/platform/base/agsplatformdriver.cpp
    engines/ags/engine/platform/linux/acpllnx.cpp
    engines/ags/engine/script/script_runtime.cpp
    engines/ags/engine/util/library_posix.h
    engines/ags/module.mk
    engines/ags/plugins/ags_pal_render/pal_render.h
    engines/ags/plugins/dll.h
    engines/ags/plugins/serializer.h


diff --git a/engines/ags/engine/ac/draw.cpp b/engines/ags/engine/ac/draw.cpp
index c559768d73..69714f99ea 100644
--- a/engines/ags/engine/ac/draw.cpp
+++ b/engines/ags/engine/ac/draw.cpp
@@ -61,8 +61,8 @@
 #include "ags/shared/font/fonts.h"
 #include "ags/shared/gui/guimain.h"
 #include "ags/engine/platform/base/agsplatformdriver.h"
-#include "ags/engine/plugin/agsplugin.h"
-#include "ags/engine/plugin/plugin_engine.h"
+#include "ags/plugins/agsplugin.h"
+#include "ags/plugins/plugin_engine.h"
 #include "ags/shared/ac/spritecache.h"
 #include "ags/engine/gfx/gfx_util.h"
 #include "ags/engine/gfx/graphicsdriver.h"
diff --git a/engines/ags/engine/ac/dynobj/cc_serializer.cpp b/engines/ags/engine/ac/dynobj/cc_serializer.cpp
index 1e91c8c8e6..7390b4629c 100644
--- a/engines/ags/engine/ac/dynobj/cc_serializer.cpp
+++ b/engines/ags/engine/ac/dynobj/cc_serializer.cpp
@@ -31,8 +31,8 @@
 #include "ags/engine/ac/dynobj/scriptviewport.h"
 #include "ags/engine/ac/game.h"
 #include "ags/engine/debugging/debug_log.h"
-#include "ags/engine/plugin/agsplugin.h"
-#include "ags/engine/plugin/pluginobjectreader.h"
+#include "ags/plugins/agsplugin.h"
+#include "ags/plugins/pluginobjectreader.h"
 
 namespace AGS3 {
 
diff --git a/engines/ags/engine/ac/event.cpp b/engines/ags/engine/ac/event.cpp
index bb7d9b23aa..005542c0da 100644
--- a/engines/ags/engine/ac/event.cpp
+++ b/engines/ags/engine/ac/event.cpp
@@ -33,8 +33,8 @@
 #include "ags/engine/ac/screen.h"
 #include "ags/shared/script/cc_error.h"
 #include "ags/engine/platform/base/agsplatformdriver.h"
-#include "ags/engine/plugin/agsplugin.h"
-#include "ags/engine/plugin/plugin_engine.h"
+#include "ags/plugins/agsplugin.h"
+#include "ags/plugins/plugin_engine.h"
 #include "ags/engine/script/script.h"
 #include "ags/shared/gfx/bitmap.h"
 #include "ags/engine/gfx/ddb.h"
diff --git a/engines/ags/engine/ac/game.cpp b/engines/ags/engine/ac/game.cpp
index f7788186da..a862d533b3 100644
--- a/engines/ags/engine/ac/game.cpp
+++ b/engines/ags/engine/ac/game.cpp
@@ -85,8 +85,8 @@
 #include "ags/engine/main/graphics_mode.h"
 #include "ags/engine/main/main.h"
 #include "ags/engine/media/audio/audio_system.h"
-#include "ags/engine/plugin/agsplugin.h"
-#include "ags/engine/plugin/plugin_engine.h"
+#include "ags/plugins/agsplugin.h"
+#include "ags/plugins/plugin_engine.h"
 #include "ags/shared/script/cc_error.h"
 #include "ags/engine/script/runtimescriptvalue.h"
 #include "ags/engine/script/script.h"
diff --git a/engines/ags/engine/ac/global_translation.cpp b/engines/ags/engine/ac/global_translation.cpp
index 6ee31b312e..6fe8bb586a 100644
--- a/engines/ags/engine/ac/global_translation.cpp
+++ b/engines/ags/engine/ac/global_translation.cpp
@@ -28,8 +28,8 @@
 #include "ags/engine/ac/string.h"
 #include "ags/engine/ac/tree_map.h"
 #include "ags/engine/platform/base/agsplatformdriver.h"
-#include "ags/engine/plugin/agsplugin.h"
-#include "ags/engine/plugin/plugin_engine.h"
+#include "ags/plugins/agsplugin.h"
+#include "ags/plugins/plugin_engine.h"
 #include "ags/shared/util/memory.h"
 #include "ags/shared/core/types.h"
 
diff --git a/engines/ags/engine/ac/room.cpp b/engines/ags/engine/ac/room.cpp
index d6c04b6a02..41ac25bceb 100644
--- a/engines/ags/engine/ac/room.cpp
+++ b/engines/ags/engine/ac/room.cpp
@@ -60,8 +60,8 @@
 #include "ags/shared/debugging/out.h"
 #include "ags/shared/game/room_version.h"
 #include "ags/engine/platform/base/agsplatformdriver.h"
-#include "ags/engine/plugin/agsplugin.h"
-#include "ags/engine/plugin/plugin_engine.h"
+#include "ags/plugins/agsplugin.h"
+#include "ags/plugins/plugin_engine.h"
 #include "ags/shared/script/cc_error.h"
 #include "ags/engine/script/script.h"
 #include "ags/engine/script/script_runtime.h"
diff --git a/engines/ags/engine/ac/screen.cpp b/engines/ags/engine/ac/screen.cpp
index 9306c4ac88..06fc83fe55 100644
--- a/engines/ags/engine/ac/screen.cpp
+++ b/engines/ags/engine/ac/screen.cpp
@@ -31,8 +31,8 @@
 #include "ags/engine/ac/dynobj/scriptuserobject.h"
 #include "ags/engine/script/script_runtime.h"
 #include "ags/engine/platform/base/agsplatformdriver.h"
-#include "ags/engine/plugin/agsplugin.h"
-#include "ags/engine/plugin/plugin_engine.h"
+#include "ags/plugins/agsplugin.h"
+#include "ags/plugins/plugin_engine.h"
 #include "ags/shared/gfx/bitmap.h"
 #include "ags/engine/gfx/graphicsdriver.h"
 
diff --git a/engines/ags/engine/ac/sprite.cpp b/engines/ags/engine/ac/sprite.cpp
index e8e1f2eeee..ccecda46bc 100644
--- a/engines/ags/engine/ac/sprite.cpp
+++ b/engines/ags/engine/ac/sprite.cpp
@@ -26,8 +26,8 @@
 #include "ags/engine/ac/sprite.h"
 #include "ags/engine/ac/system.h"
 #include "ags/engine/platform/base/agsplatformdriver.h"
-#include "ags/engine/plugin/agsplugin.h"
-#include "ags/engine/plugin/plugin_engine.h"
+#include "ags/plugins/agsplugin.h"
+#include "ags/plugins/plugin_engine.h"
 #include "ags/shared/ac/spritecache.h"
 #include "ags/shared/gfx/bitmap.h"
 #include "ags/engine/gfx/graphicsdriver.h"
diff --git a/engines/ags/engine/debugging/debug.cpp b/engines/ags/engine/debugging/debug.cpp
index 016f2b471c..44147bdefe 100644
--- a/engines/ags/engine/debugging/debug.cpp
+++ b/engines/ags/engine/debugging/debug.cpp
@@ -38,7 +38,7 @@
 #include "ags/engine/main/config.h"
 #include "ags/engine/media/audio/audio_system.h"
 #include "ags/engine/platform/base/agsplatformdriver.h"
-#include "ags/engine/plugin/plugin_engine.h"
+#include "ags/plugins/plugin_engine.h"
 #include "ags/engine/script/script.h"
 #include "ags/shared/script/script_common.h"
 #include "ags/shared/script/cc_error.h"
diff --git a/engines/ags/engine/game/game_init.cpp b/engines/ags/engine/game/game_init.cpp
index 8de53db9a1..5813e7e6c9 100644
--- a/engines/ags/engine/game/game_init.cpp
+++ b/engines/ags/engine/game/game_init.cpp
@@ -43,7 +43,7 @@
 #include "ags/shared/gfx/bitmap.h"
 #include "ags/engine/gfx/ddb.h"
 #include "ags/shared/gui/guilabel.h"
-#include "ags/engine/plugin/plugin_engine.h"
+#include "ags/plugins/plugin_engine.h"
 #include "ags/shared/script/cc_error.h"
 #include "ags/engine/script/exports.h"
 #include "ags/engine/script/script.h"
diff --git a/engines/ags/engine/game/savegame.cpp b/engines/ags/engine/game/savegame.cpp
index d2deb79b9d..085fbe669d 100644
--- a/engines/ags/engine/game/savegame.cpp
+++ b/engines/ags/engine/game/savegame.cpp
@@ -52,8 +52,8 @@
 #include "ags/engine/main/engine.h"
 #include "ags/engine/main/main.h"
 #include "ags/engine/platform/base/agsplatformdriver.h"
-#include "ags/engine/plugin/agsplugin.h"
-#include "ags/engine/plugin/plugin_engine.h"
+#include "ags/plugins/agsplugin.h"
+#include "ags/plugins/plugin_engine.h"
 #include "ags/engine/script/script.h"
 #include "ags/shared/script/cc_error.h"
 #include "ags/shared/util/alignedstream.h"
diff --git a/engines/ags/engine/game/savegame_components.cpp b/engines/ags/engine/game/savegame_components.cpp
index 4475b1fdb6..72a8c179cc 100644
--- a/engines/ags/engine/game/savegame_components.cpp
+++ b/engines/ags/engine/game/savegame_components.cpp
@@ -53,8 +53,8 @@
 #include "ags/shared/gui/guimain.h"
 #include "ags/shared/gui/guislider.h"
 #include "ags/shared/gui/guitextbox.h"
-#include "ags/engine/plugin/agsplugin.h"
-#include "ags/engine/plugin/plugin_engine.h"
+#include "ags/plugins/agsplugin.h"
+#include "ags/plugins/plugin_engine.h"
 #include "ags/shared/script/cc_error.h"
 #include "ags/engine/script/script.h"
 #include "ags/shared/util/filestream.h" // TODO: needed only because plugins expect file handle
diff --git a/engines/ags/engine/main/game_file.cpp b/engines/ags/engine/main/game_file.cpp
index 545ef80b75..000949b621 100644
--- a/engines/ags/engine/main/game_file.cpp
+++ b/engines/ags/engine/main/game_file.cpp
@@ -50,7 +50,7 @@
 #include "ags/engine/ac/gamesetup.h"
 #include "ags/shared/game/main_game_file.h"
 #include "ags/engine/game/game_init.h"
-#include "ags/engine/plugin/agsplugin.h"
+#include "ags/plugins/agsplugin.h"
 #include "ags/engine/script/script.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/main/game_run.cpp b/engines/ags/engine/main/game_run.cpp
index 68a830ee83..30e5eef2ff 100644
--- a/engines/ags/engine/main/game_run.cpp
+++ b/engines/ags/engine/main/game_run.cpp
@@ -57,8 +57,8 @@
 #include "ags/engine/main/engine.h"
 #include "ags/engine/main/game_run.h"
 #include "ags/engine/main/update.h"
-#include "ags/engine/plugin/agsplugin.h"
-#include "ags/engine/plugin/plugin_engine.h"
+#include "ags/plugins/agsplugin.h"
+#include "ags/plugins/plugin_engine.h"
 #include "ags/engine/script/script.h"
 #include "ags/shared/ac/spritecache.h"
 #include "ags/engine/media/audio/audio_system.h"
diff --git a/engines/ags/engine/main/quit.cpp b/engines/ags/engine/main/quit.cpp
index 822b273717..6d83fb3338 100644
--- a/engines/ags/engine/main/quit.cpp
+++ b/engines/ags/engine/main/quit.cpp
@@ -44,7 +44,7 @@
 #include "ags/engine/gfx/graphicsdriver.h"
 #include "ags/shared/gfx/bitmap.h"
 #include "ags/shared/core/assetmanager.h"
-#include "ags/engine/plugin/plugin_engine.h"
+#include "ags/plugins/plugin_engine.h"
 #include "ags/engine/media/audio/audio_system.h"
 #include "ags/engine/globals.h"
 #include "ags/ags.h"
diff --git a/engines/ags/engine/platform/base/agsplatformdriver.cpp b/engines/ags/engine/platform/base/agsplatformdriver.cpp
index 150a7f6418..5fff43d8c0 100644
--- a/engines/ags/engine/platform/base/agsplatformdriver.cpp
+++ b/engines/ags/engine/platform/base/agsplatformdriver.cpp
@@ -33,7 +33,7 @@
 #include "ags/shared/util/string_utils.h"
 #include "ags/shared/util/stream.h"
 #include "ags/shared/gfx/bitmap.h"
-#include "ags/engine/plugin/agsplugin.h"
+#include "ags/plugins/agsplugin.h"
 #include "ags/engine/ac/timer.h"
 #include "ags/engine/media/audio/audio_system.h"
 #include "ags/lib/system/datetime.h"
diff --git a/engines/ags/engine/platform/linux/acpllnx.cpp b/engines/ags/engine/platform/linux/acpllnx.cpp
index 415dd3dc72..966ef23e09 100644
--- a/engines/ags/engine/platform/linux/acpllnx.cpp
+++ b/engines/ags/engine/platform/linux/acpllnx.cpp
@@ -36,7 +36,7 @@
 #include "ags/engine/ac/runtime_defines.h"
 #include "ags/engine/gfx/gfxdefines.h"
 #include "ags/engine/platform/base/agsplatformdriver.h"
-#include "ags/engine/plugin/agsplugin.h"
+#include "ags/plugins/agsplugin.h"
 #include "ags/shared/util/string.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/script/script_runtime.cpp b/engines/ags/engine/script/script_runtime.cpp
index 2c4a1e7569..628b792ca3 100644
--- a/engines/ags/engine/script/script_runtime.cpp
+++ b/engines/ags/engine/script/script_runtime.cpp
@@ -39,7 +39,7 @@
 #include "ags/shared/script/cc_error.h"
 #include "ags/shared/script/cc_options.h"
 #include "ags/engine/script/systemimports.h"
-#include "ags/engine/plugin/agsplugin.h"
+#include "ags/plugins/agsplugin.h"
 #include "ags/engine/ac/dynobj/cc_dynamicarray.h"
 #include "ags/engine/ac/statobj/staticobject.h"
 
diff --git a/engines/ags/engine/util/library_posix.h b/engines/ags/engine/util/library_posix.h
index 04ab952340..bc9152d0d1 100644
--- a/engines/ags/engine/util/library_posix.h
+++ b/engines/ags/engine/util/library_posix.h
@@ -27,7 +27,7 @@
 #include "ags/shared/core/platform.h"
 #include "ags/shared/util/string.h"
 #include "ags/shared/debugging/out.h"
-#include "ags/engine/plugin/library.h"
+#include "ags/plugins/library.h"
 #include "ags/engine/globals.h"
 
 namespace AGS3 {
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index 526a60c7a3..c04cd2c01a 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -287,10 +287,6 @@ MODULE_OBJS = \
 	engine/media/video/video.o \
 	engine/platform/base/agsplatformdriver.o \
 	engine/platform/linux/acpllnx.o \
-	engine/plugin/agsplugin.o \
-	engine/plugin/global_plugin.o \
-	engine/plugin/library.o \
-	engine/plugin/pluginobjectreader.o \
 	engine/script/cc_instance.o \
 	engine/script/executingscript.o \
 	engine/script/exports.o \
@@ -300,7 +296,11 @@ MODULE_OBJS = \
 	engine/script/script_engine.o \
 	engine/script/script_runtime.o \
 	engine/script/systemimports.o \
+	plugins/agsplugin.o \
 	plugins/dll.o \
+	plugins/global_plugin.o \
+	plugins/library.o \
+	plugins/pluginobjectreader.o \
 	plugins/ags_blend/ags_blend.o \
 	plugins/ags_creditz/ags_creditz.o \
 	plugins/ags_flashlight/ags_flashlight.o \
diff --git a/engines/ags/plugins/ags_pal_render/pal_render.h b/engines/ags/plugins/ags_pal_render/pal_render.h
index 1f448174e3..1d61dab866 100644
--- a/engines/ags/plugins/ags_pal_render/pal_render.h
+++ b/engines/ags/plugins/ags_pal_render/pal_render.h
@@ -24,7 +24,7 @@
 #define AGS_PLUGINS_AGS_PAL_RENDER_PAL_RENDER_H
 
 #include "ags/lib/allegro.h"
-#include "ags/engine/plugin/agsplugin.h"
+#include "ags/plugins/agsplugin.h"
 #include "common/algorithm.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/plugin/agsplugin.cpp b/engines/ags/plugins/agsplugin.cpp
similarity index 99%
rename from engines/ags/engine/plugin/agsplugin.cpp
rename to engines/ags/plugins/agsplugin.cpp
index 7c18d3f358..07fccba737 100644
--- a/engines/ags/engine/plugin/agsplugin.cpp
+++ b/engines/ags/plugins/agsplugin.cpp
@@ -54,10 +54,10 @@
 #include "ags/shared/gui/guidefines.h"
 #include "ags/engine/main/game_run.h"
 #include "ags/engine/main/engine.h"
-#include "ags/engine/plugin/agsplugin.h"
-#include "ags/engine/plugin/plugin_engine.h"
-#include "ags/engine/plugin/plugin_builtin.h"
-#include "ags/engine/plugin/pluginobjectreader.h"
+#include "ags/plugins/agsplugin.h"
+#include "ags/plugins/plugin_engine.h"
+#include "ags/plugins/plugin_builtin.h"
+#include "ags/plugins/pluginobjectreader.h"
 #include "ags/engine/script/script.h"
 #include "ags/engine/script/script_runtime.h"
 #include "ags/shared/ac/spritecache.h"
diff --git a/engines/ags/engine/plugin/agsplugin.h b/engines/ags/plugins/agsplugin.h
similarity index 100%
rename from engines/ags/engine/plugin/agsplugin.h
rename to engines/ags/plugins/agsplugin.h
diff --git a/engines/ags/plugins/dll.h b/engines/ags/plugins/dll.h
index 5b797a3d49..b6406d9f5a 100644
--- a/engines/ags/plugins/dll.h
+++ b/engines/ags/plugins/dll.h
@@ -24,7 +24,7 @@
 #define AGS_PLUGINS_DLL_H
 
 #include "ags/shared/util/string.h"
-#include "ags/engine/plugin/agsplugin.h"
+#include "ags/plugins/agsplugin.h"
 #include "common/hashmap.h"
 #include "common/hash-str.h"
 
diff --git a/engines/ags/engine/plugin/global_plugin.cpp b/engines/ags/plugins/global_plugin.cpp
similarity index 100%
rename from engines/ags/engine/plugin/global_plugin.cpp
rename to engines/ags/plugins/global_plugin.cpp
diff --git a/engines/ags/engine/plugin/library.cpp b/engines/ags/plugins/library.cpp
similarity index 97%
rename from engines/ags/engine/plugin/library.cpp
rename to engines/ags/plugins/library.cpp
index 814fab68dc..1fe645d8fc 100644
--- a/engines/ags/engine/plugin/library.cpp
+++ b/engines/ags/plugins/library.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/engine/plugin/library.h"
+#include "ags/plugins/library.h"
 #include "ags/plugins/dll.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/plugin/library.h b/engines/ags/plugins/library.h
similarity index 100%
rename from engines/ags/engine/plugin/library.h
rename to engines/ags/plugins/library.h
diff --git a/engines/ags/engine/plugin/plugin_builtin.h b/engines/ags/plugins/plugin_builtin.h
similarity index 100%
rename from engines/ags/engine/plugin/plugin_builtin.h
rename to engines/ags/plugins/plugin_builtin.h
diff --git a/engines/ags/engine/plugin/plugin_engine.h b/engines/ags/plugins/plugin_engine.h
similarity index 100%
rename from engines/ags/engine/plugin/plugin_engine.h
rename to engines/ags/plugins/plugin_engine.h
diff --git a/engines/ags/engine/plugin/pluginobjectreader.cpp b/engines/ags/plugins/pluginobjectreader.cpp
similarity index 95%
rename from engines/ags/engine/plugin/pluginobjectreader.cpp
rename to engines/ags/plugins/pluginobjectreader.cpp
index c01edae79b..dd510ca1c0 100644
--- a/engines/ags/engine/plugin/pluginobjectreader.cpp
+++ b/engines/ags/plugins/pluginobjectreader.cpp
@@ -20,7 +20,7 @@
  *
  */
 
-#include "ags/engine/plugin/pluginobjectreader.h"
+#include "ags/plugins/pluginobjectreader.h"
 #include "ags/engine/ac/runtime_defines.h"
 
 namespace AGS3 {
diff --git a/engines/ags/engine/plugin/pluginobjectreader.h b/engines/ags/plugins/pluginobjectreader.h
similarity index 100%
rename from engines/ags/engine/plugin/pluginobjectreader.h
rename to engines/ags/plugins/pluginobjectreader.h
diff --git a/engines/ags/plugins/serializer.h b/engines/ags/plugins/serializer.h
index ba48c0bc25..e752ea060f 100644
--- a/engines/ags/plugins/serializer.h
+++ b/engines/ags/plugins/serializer.h
@@ -23,7 +23,7 @@
 #ifndef AGS_PLUGINS_SERIALIZER_H
 #define AGS_PLUGINS_SERIALIZER_H
 
-#include "ags/engine/plugin/agsplugin.h"
+#include "ags/plugins/agsplugin.h"
 #include "common/serializer.h"
 
 namespace AGS3 {


Commit: 57a1cd958011dac3add9903cff7fc71794aaa9ef
    https://github.com/scummvm/scummvm/commit/57a1cd958011dac3add9903cff7fc71794aaa9ef
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added AGSCredits 1.1 SetCredits method

Changed paths:
    engines/ags/plugins/ags_creditz/ags_creditz.cpp
    engines/ags/plugins/ags_creditz/ags_creditz.h
    engines/ags/plugins/ags_sprite_font/sprite_font_renderer.h
    engines/ags/plugins/ags_sprite_font/variable_width_font.h
    engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.h


diff --git a/engines/ags/plugins/ags_creditz/ags_creditz.cpp b/engines/ags/plugins/ags_creditz/ags_creditz.cpp
index 3e350d820b..639bf476d7 100644
--- a/engines/ags/plugins/ags_creditz/ags_creditz.cpp
+++ b/engines/ags/plugins/ags_creditz/ags_creditz.cpp
@@ -49,7 +49,6 @@ const char *AGSCreditz::AGS_GetPluginName() {
 
 void AGSCreditz::AGS_EngineStartup(IAGSEngine *engine) {
 	SCRIPT_METHOD(ScrollCredits);
-	SCRIPT_METHOD(GetCredit);
 	SCRIPT_METHOD(IsCreditScrollingFinished);
 	SCRIPT_METHOD(SetCreditImage);
 	SCRIPT_METHOD(PauseScroll);
@@ -74,11 +73,6 @@ void AGSCreditz::ScrollCredits(const ScriptMethodParams &params) {
 	PARAMS7(int, onoff, int, speed, int, fromY, int, toY, int, isautom, int, wait, int, res);
 }
 
-string AGSCreditz::GetCredit(const ScriptMethodParams &params) {
-	PARAMS1(int, ID);
-	return nullptr;
-}
-
 int AGSCreditz::IsCreditScrollingFinished(const ScriptMethodParams &params) {
 	return true;
 }
@@ -154,6 +148,8 @@ int AGSCreditz::IsStaticCreditsFinished(const ScriptMethodParams &params) {
 
 /*------------------------------------------------------------------*/
 
+const char *IMAGE_TEXT = "*i*m*a*g*e*";
+
 AGSCreditz11::AGSCreditz11() {
 	_version = VERSION_11;
 
@@ -162,12 +158,31 @@ AGSCreditz11::AGSCreditz11() {
 
 void AGSCreditz11::AGS_EngineStartup(IAGSEngine *engine) {
 	AGSCreditz::AGS_EngineStartup(engine);
+
 	SCRIPT_METHOD(SetCredit);
+	SCRIPT_METHOD(GetCredit);
 }
 
 void AGSCreditz11::SetCredit(const ScriptMethodParams &params) {
 	PARAMS7(int, ID, string, credit, int, colour, int, font, int, center, int, xpos, int, generateoutline);
 
+	if (ID >= _state->_credits[0].size())
+		_state->_credits[0].resize(ID + 1);
+
+	Credit &c = _state->_credits[0][ID];
+	c._text = credit;
+	c._fontSlot = font;
+	c._center = center;
+	c._x = xpos;
+	c._isSet = true;
+	c._outline = generateoutline;
+}
+
+const string AGSCreditz11::GetCredit(const ScriptMethodParams &params) {
+	PARAMS1(int, ID);
+
+	return (_state->_credits[0][ID]._text == IMAGE_TEXT) ?
+		"image" : _state->_credits[0][ID]._text.c_str();
 }
 
 /*------------------------------------------------------------------*/
@@ -180,6 +195,7 @@ AGSCreditz20::AGSCreditz20() {
 
 void AGSCreditz20::AGS_EngineStartup(IAGSEngine *engine) {
 	AGSCreditz::AGS_EngineStartup(engine);
+
 	SCRIPT_METHOD(SetCredit);
 }
 
@@ -191,9 +207,9 @@ void AGSCreditz20::SetCredit(const ScriptMethodParams &params) {
 		_state->_credits[sequence].resize(line + 1);
 
 	Credit &c = _state->_credits[sequence][line];
-	c._credit = credit;
+	c._text = credit;
 	c._fontSlot = font;
-	c._colorHeight = color;
+	c._color = color;
 	c._x = x_pos;
 	c._isSet = true;
 	if (gen_outline > 0)
diff --git a/engines/ags/plugins/ags_creditz/ags_creditz.h b/engines/ags/plugins/ags_creditz/ags_creditz.h
index 14f7ed67ba..b18669c755 100644
--- a/engines/ags/plugins/ags_creditz/ags_creditz.h
+++ b/engines/ags/plugins/ags_creditz/ags_creditz.h
@@ -33,11 +33,12 @@ namespace Plugins {
 namespace AGSCreditz {
 
 struct Credit {
-	Common::String _credit;
+	Common::String _text;
 	int _x = 0;
 	int _y = 0;
 	int _fontSlot = 0;
-	int _colorHeight = 0;
+	int _color = 0;
+	int _center = 0;
 	bool _isSet = false;
 	bool _image = false;
 	bool _outline = false;
@@ -121,7 +122,6 @@ protected:
 
 	// Shared Script methods
 	static void ScrollCredits(const ScriptMethodParams &params);
-	static string GetCredit(const ScriptMethodParams &params);
 	static int IsCreditScrollingFinished(const ScriptMethodParams &params);
 	static void SetCreditImage(const ScriptMethodParams &params);
 	static void PauseScroll(const ScriptMethodParams &params);
@@ -150,6 +150,7 @@ private:
 	static void AGS_EngineStartup(IAGSEngine *engine);
 
 	static void SetCredit(const ScriptMethodParams &params);
+	static const string GetCredit(const ScriptMethodParams &params);
 public:
 	AGSCreditz11();
 };
diff --git a/engines/ags/plugins/ags_sprite_font/sprite_font_renderer.h b/engines/ags/plugins/ags_sprite_font/sprite_font_renderer.h
index a5f2f373a0..89be9b1bbf 100644
--- a/engines/ags/plugins/ags_sprite_font/sprite_font_renderer.h
+++ b/engines/ags/plugins/ags_sprite_font/sprite_font_renderer.h
@@ -24,7 +24,7 @@
 #define AGS_PLUGINS_AGS_SPRITE_FONT_SPR_FONT_RENDERER_H
 
 #include "ags/plugins/ags_sprite_font/sprite_font.h"
-#include "ags/engine/plugin/agsplugin.h"
+#include "ags/plugins/agsplugin.h"
 #include "ags/lib/std/vector.h"
 
 namespace AGS3 {
diff --git a/engines/ags/plugins/ags_sprite_font/variable_width_font.h b/engines/ags/plugins/ags_sprite_font/variable_width_font.h
index 5eb5bccbdd..96c1f9e544 100644
--- a/engines/ags/plugins/ags_sprite_font/variable_width_font.h
+++ b/engines/ags/plugins/ags_sprite_font/variable_width_font.h
@@ -24,7 +24,7 @@
 #define AGS_PLUGINS_AGS_SPRITE_FONT_VAR_WIDTH_FONT_H
 
 #include "ags/plugins/ags_sprite_font/character_entry.h"
-#include "ags/engine/plugin/agsplugin.h"
+#include "ags/plugins/agsplugin.h"
 #include "ags/lib/std/map.h"
 
 namespace AGS3 {
diff --git a/engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.h b/engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.h
index 5625d21c1e..4bd05f58cc 100644
--- a/engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.h
+++ b/engines/ags/plugins/ags_sprite_font/variable_width_sprite_font.h
@@ -25,7 +25,7 @@
 
 #include "ags/plugins/dll.h"
 #include "ags/plugins/serializer.h"
-#include "ags/engine/plugin/agsplugin.h"
+#include "ags/plugins/agsplugin.h"
 #include "ags/plugins/ags_sprite_font/variable_width_font.h"
 
 namespace AGS3 {


Commit: 0bad8f3969e09de4ba3ea01e795f08a9ec24455e
    https://github.com/scummvm/scummvm/commit/0bad8f3969e09de4ba3ea01e795f08a9ec24455e
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Implementing AGSCreditz ScrollCredits

Changed paths:
    engines/ags/plugins/ags_creditz/ags_creditz.cpp
    engines/ags/plugins/ags_creditz/ags_creditz.h


diff --git a/engines/ags/plugins/ags_creditz/ags_creditz.cpp b/engines/ags/plugins/ags_creditz/ags_creditz.cpp
index 639bf476d7..28bc707fae 100644
--- a/engines/ags/plugins/ags_creditz/ags_creditz.cpp
+++ b/engines/ags/plugins/ags_creditz/ags_creditz.cpp
@@ -28,9 +28,11 @@ namespace AGSCreditz {
 
 AGSCreditz::Version AGSCreditz::_version;
 State *AGSCreditz::_state;
+IAGSEngine *AGSCreditz::_engine;
 
 AGSCreditz::AGSCreditz() {
 	_state = new State();
+	_engine = nullptr;
 
 	DLL_METHOD(AGS_GetPluginName);
 }
@@ -48,7 +50,8 @@ const char *AGSCreditz::AGS_GetPluginName() {
 }
 
 void AGSCreditz::AGS_EngineStartup(IAGSEngine *engine) {
-	SCRIPT_METHOD(ScrollCredits);
+	_engine = engine;
+
 	SCRIPT_METHOD(IsCreditScrollingFinished);
 	SCRIPT_METHOD(SetCreditImage);
 	SCRIPT_METHOD(PauseScroll);
@@ -69,10 +72,6 @@ void AGSCreditz::AGS_EngineStartup(IAGSEngine *engine) {
 	SCRIPT_METHOD(IsStaticCreditsFinished);
 }
 
-void AGSCreditz::ScrollCredits(const ScriptMethodParams &params) {
-	PARAMS7(int, onoff, int, speed, int, fromY, int, toY, int, isautom, int, wait, int, res);
-}
-
 int AGSCreditz::IsCreditScrollingFinished(const ScriptMethodParams &params) {
 	return true;
 }
@@ -160,6 +159,7 @@ void AGSCreditz11::AGS_EngineStartup(IAGSEngine *engine) {
 	AGSCreditz::AGS_EngineStartup(engine);
 
 	SCRIPT_METHOD(SetCredit);
+	SCRIPT_METHOD(ScrollCredits);
 	SCRIPT_METHOD(GetCredit);
 }
 
@@ -178,6 +178,33 @@ void AGSCreditz11::SetCredit(const ScriptMethodParams &params) {
 	c._outline = generateoutline;
 }
 
+void AGSCreditz11::ScrollCredits(const ScriptMethodParams &params) {
+	PARAMS7(int, onoff, int, speed, int, fromY, int, toY, int, isautom, int, wait, int, resolution);
+
+	if (onoff == 1) {
+		_state->_creditsRunning = true;
+		_state->_seqSettings[0].speed = speed;
+		_state->_seqSettings[0].endwait = wait;
+		_state->_seqSettings[0].startpoint = fromY;
+		_state->_seqSettings[0].endpoint = toY;
+		_state->_seqSettings[0].automatic = isautom;
+
+		_engine->GetScreenDimensions(&_state->_screenWidth,
+			&_state->_screenHeight, &_state->_screenColorDepth);
+		if (_state->_screenWidth == 320) {
+			_state->_resolutionFlag = (resolution != 2) ? 1 : 0;
+		} else if (_state->_screenWidth == 640) {
+			_state->_resolutionFlag = (resolution != 1) ? 1 : 0;
+		}
+
+	} else if (onoff == 0) {
+		_state->_creditsRunning = false;
+
+	} else {
+		_engine->AbortGame("ScrollCredits: OnOff value must be 1 or 0!");
+	}
+}
+
 const string AGSCreditz11::GetCredit(const ScriptMethodParams &params) {
 	PARAMS1(int, ID);
 
diff --git a/engines/ags/plugins/ags_creditz/ags_creditz.h b/engines/ags/plugins/ags_creditz/ags_creditz.h
index b18669c755..baf0b73897 100644
--- a/engines/ags/plugins/ags_creditz/ags_creditz.h
+++ b/engines/ags/plugins/ags_creditz/ags_creditz.h
@@ -106,6 +106,10 @@ struct State {
 	void *_maskScreen = nullptr;
 	void *_maski = nullptr;
 	void *_creditScreen = nullptr;
+
+	// Version 1.1 specific
+	bool _resolutionFlag = false;
+	int _screenWidth = 0, _screenHeight = 0, _screenColorDepth = 0;
 };
 
 class AGSCreditz : public DLL {
@@ -116,12 +120,12 @@ protected:
 
 	static Version _version;
 	static State *_state;
+	static IAGSEngine *_engine;
 protected:
 	static const char *AGS_GetPluginName();
 	static void AGS_EngineStartup(IAGSEngine *engine);
 
 	// Shared Script methods
-	static void ScrollCredits(const ScriptMethodParams &params);
 	static int IsCreditScrollingFinished(const ScriptMethodParams &params);
 	static void SetCreditImage(const ScriptMethodParams &params);
 	static void PauseScroll(const ScriptMethodParams &params);
@@ -150,6 +154,7 @@ private:
 	static void AGS_EngineStartup(IAGSEngine *engine);
 
 	static void SetCredit(const ScriptMethodParams &params);
+	static void ScrollCredits(const ScriptMethodParams &params);
 	static const string GetCredit(const ScriptMethodParams &params);
 public:
 	AGSCreditz11();


Commit: be2206d87976ee6f258a1fad8cce23ff78482878
    https://github.com/scummvm/scummvm/commit/be2206d87976ee6f258a1fad8cce23ff78482878
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Hook up loading savegames from launcher

Changed paths:
    engines/ags/ags.cpp
    engines/ags/engine/ac/game.cpp
    engines/ags/engine/ac/game.h
    engines/ags/engine/globals.h
    engines/ags/engine/main/game_start.cpp
    engines/ags/engine/main/game_start.h


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index bf61c62120..397a338f6b 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -65,7 +65,7 @@ namespace AGS3 {
 using namespace Shared;
 using namespace Engine;
 
-extern HSaveError load_game(const String &path, int slotNumber, bool &data_overwritten);
+extern HSaveError load_game(int slotNumber, bool &data_overwritten);
 
 extern GameSetup usetup;
 extern GameState play;
@@ -155,7 +155,7 @@ static int main_process_cmdline(ConfigTree &cfg, int argc, const char *argv[]) {
 		} else if (scumm_stricmp(arg, "-unregistergame") == 0) {
 			_G(justUnRegisterGame) = true;
 		} else if ((scumm_stricmp(arg, "-loadsavedgame") == 0) && (argc > ee + 1)) {
-			_G(loadSaveGameOnStartup) = argv[ee + 1];
+			_G(loadSaveGameOnStartup) = atoi(argv[ee + 1]);
 			ee++;
 		} else if ((scumm_stricmp(arg, "--enabledebugger") == 0) && (argc > ee + 1)) {
 			strcpy(_G(editor_debugger_instance_token), argv[ee + 1]);
@@ -348,6 +348,8 @@ Common::Error AGSEngine::run() {
 	if (AGS3::debug_flags & DBG_REGONLY)
 		return Common::kNoError;
 
+	_G(loadSaveGameOnStartup) = ConfMan.getInt("save_slot");
+
 #ifdef USE_CUSTOM_EXCEPTION_HANDLER
 	if (usetup.disable_exception_handling)
 #endif
@@ -380,7 +382,7 @@ void AGSEngine::setGraphicsMode(size_t w, size_t h) {
 
 Common::Error AGSEngine::loadGameState(int slot) {
 	bool dataOverwritten;
-	(void)AGS3::load_game("", slot, dataOverwritten);
+	(void)AGS3::load_game(slot, dataOverwritten);
 	return Common::kNoError;
 }
 
diff --git a/engines/ags/engine/ac/game.cpp b/engines/ags/engine/ac/game.cpp
index a862d533b3..2b96833501 100644
--- a/engines/ags/engine/ac/game.cpp
+++ b/engines/ags/engine/ac/game.cpp
@@ -1552,7 +1552,7 @@ bool read_savedgame_screenshot(const String &savedgame, int &want_shot) {
 	return true;
 }
 
-HSaveError load_game(const String &path, int slotNumber, bool &data_overwritten) {
+HSaveError load_game(int slotNumber, bool &data_overwritten) {
 	data_overwritten = false;
 	gameHasBeenRestored++;
 
@@ -1562,6 +1562,8 @@ HSaveError load_game(const String &path, int slotNumber, bool &data_overwritten)
 	HSaveError err;
 	SavegameSource src;
 	SavegameDescription desc;
+
+	String path = get_save_game_path(slotNumber);
 	err = OpenSavegame(path, src, desc, kSvgDesc_EnvInfo);
 
 	// saved in incompatible enviroment
@@ -1602,12 +1604,8 @@ HSaveError load_game(const String &path, int slotNumber, bool &data_overwritten)
 }
 
 bool try_restore_save(int slot) {
-	return try_restore_save(get_save_game_path(slot), slot);
-}
-
-bool try_restore_save(const Shared::String &path, int slot) {
 	bool data_overwritten;
-	HSaveError err = load_game(path, slot, data_overwritten);
+	HSaveError err = load_game(slot, data_overwritten);
 	if (!err) {
 		String error = String::FromFormat("Unable to restore the saved game.\n%s",
 		                                  err->FullMessage().GetCStr());
diff --git a/engines/ags/engine/ac/game.h b/engines/ags/engine/ac/game.h
index 2d6c813805..1d8c84428e 100644
--- a/engines/ags/engine/ac/game.h
+++ b/engines/ags/engine/ac/game.h
@@ -164,7 +164,6 @@ bool read_savedgame_screenshot(const Shared::String &savedgame, int &want_shot);
 // Tries to restore saved game and displays an error on failure; if the error occured
 // too late, when the game data was already overwritten, shuts engine down.
 bool try_restore_save(int slot);
-bool try_restore_save(const Shared::String &path, int slot);
 void serialize_bitmap(const Shared::Bitmap *thispic, Shared::Stream *out);
 // On Windows we could just use IIDFromString but this is platform-independant
 void convert_guid_from_text_to_binary(const char *guidText, unsigned char *buffer);
diff --git a/engines/ags/engine/globals.h b/engines/ags/engine/globals.h
index 6cca2e29d3..0166ce215e 100644
--- a/engines/ags/engine/globals.h
+++ b/engines/ags/engine/globals.h
@@ -90,7 +90,7 @@ public:
 	bool _justUnRegisterGame = false;
 	bool _justTellInfo = false;
 	std::set<String> _tellInfoKeys;
-	const char *_loadSaveGameOnStartup = nullptr;
+	int _loadSaveGameOnStartup = -1;
 
 #if ! AGS_PLATFORM_DEFINES_PSP_VARS
 	int _psp_video_framedrop = 1;
diff --git a/engines/ags/engine/main/game_start.cpp b/engines/ags/engine/main/game_start.cpp
index 5ea5356fe3..d12ca06d13 100644
--- a/engines/ags/engine/main/game_start.cpp
+++ b/engines/ags/engine/main/game_start.cpp
@@ -28,6 +28,7 @@
 #include "ags/shared/ac/characterinfo.h"
 #include "ags/engine/ac/game.h"
 #include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/util/directory.h"
 #include "ags/engine/ac/gamestate.h"
 #include "ags/engine/ac/global_game.h"
 #include "ags/engine/ac/mouse.h"
@@ -75,14 +76,9 @@ void start_game_init_editor_debugging() {
 }
 
 void start_game_load_savegame_on_startup() {
-	if (_G(loadSaveGameOnStartup) != nullptr) {
-		int saveGameNumber = 1000;
-		const char *sgName = strstr(_G(loadSaveGameOnStartup), "agssave.");
-		if (sgName != nullptr) {
-			sscanf(sgName, "agssave.%03d", &saveGameNumber);
-		}
+	if (_G(loadSaveGameOnStartup) != -1) {
 		current_fade_out_effect();
-		try_restore_save(_G(loadSaveGameOnStartup), saveGameNumber);
+		try_restore_save(_G(loadSaveGameOnStartup));
 	}
 }
 
@@ -123,7 +119,7 @@ void do_start_game() {
 		start_game();
 }
 
-void initialize_start_and_play_game(int override_start_room, const char *loadSaveOnStartup) {
+void initialize_start_and_play_game(int override_start_room, int loadSaveOnStartup) {
 //	try { // BEGIN try for ALI3DEXception
 
 		set_cursor_mode(MODE_WALK);
diff --git a/engines/ags/engine/main/game_start.h b/engines/ags/engine/main/game_start.h
index 8ca81c2c60..374400462b 100644
--- a/engines/ags/engine/main/game_start.h
+++ b/engines/ags/engine/main/game_start.h
@@ -25,8 +25,8 @@
 
 namespace AGS3 {
 
-void start_game();
-void initialize_start_and_play_game(int override_start_room, const char *loadSaveGameOnStartup);
+extern void start_game();
+extern void initialize_start_and_play_game(int override_start_room, int loadSaveGameOnStartup);
 
 } // namespace AGS3
 


Commit: e2878645b54642984475e8460388400de17daa9a
    https://github.com/scummvm/scummvm/commit/e2878645b54642984475e8460388400de17daa9a
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added savegame thumbnails

At the moment, savegames made using the in-game save dialogs
show the dialog in the thumbnail. Not sure if it will be possible
to work around in the future, since the display of any save
dialog is controlled by game scripts, and so it would be difficult
to figure out a point to get a screenshot ready before the dialog
has been shown

Changed paths:
    engines/ags/engine/ac/game.cpp
    engines/ags/engine/ac/richgamemedia.h
    engines/ags/metaengine.cpp
    engines/ags/metaengine.h


diff --git a/engines/ags/engine/ac/game.cpp b/engines/ags/engine/ac/game.cpp
index 2b96833501..a1425eb994 100644
--- a/engines/ags/engine/ac/game.cpp
+++ b/engines/ags/engine/ac/game.cpp
@@ -1017,7 +1017,9 @@ void WriteGameSetupStructBase_Aligned(Stream *out) {
 #define MAGICNUMBER 0xbeefcafe
 
 void create_savegame_screenshot(Bitmap *&screenShot) {
-	if (game.options[OPT_SAVESCREENSHOT]) {
+	// WORKAROUND: AGS originally only creates savegames if the game flags
+	// that it supports it. But we want it all the time for ScummVM GMM
+	if (/*game.options[OPT_SAVESCREENSHOT] */true) {
 		int usewid = data_to_game_coord(play.screenshot_width);
 		int usehit = data_to_game_coord(play.screenshot_height);
 		const Rect &viewport = play.GetMainViewport();
@@ -1072,15 +1074,13 @@ void save_game(int slotn, const char *descript) {
 
 		update_polled_stuff_if_runtime();
 
-		out.reset(Shared::File::OpenFile(nametouse, Shared::kFile_Open, Shared::kFile_ReadWrite));
 		out->Seek(12, kSeekBegin);
 		out->WriteInt32(screenShotOffset);
 		out->Seek(4);
 		out->WriteInt32(screenShotSize);
-	}
 
-	if (screenShot != nullptr)
 		delete screenShot;
+	}
 }
 
 HSaveError restore_game_head_dynamic_values(Stream *in, RestoredData &r_data) {
diff --git a/engines/ags/engine/ac/richgamemedia.h b/engines/ags/engine/ac/richgamemedia.h
index c66a46d835..7c650edc5f 100644
--- a/engines/ags/engine/ac/richgamemedia.h
+++ b/engines/ags/engine/ac/richgamemedia.h
@@ -58,8 +58,8 @@ public:
 	uint32    dwMagicNumber;
 	int       dwHeaderVersion;
 	int       dwHeaderSize;
-	int       dwThumbnailOffsetLowerDword;
-	int       dwThumbnailOffsetHigherDword;
+	uint32    dwThumbnailOffsetLowerDword;
+	uint32    dwThumbnailOffsetHigherDword;
 	int       dwThumbnailSize;
 	byte guidGameId[16];
 	uint16 szGameName[RM_MAXLENGTH];
diff --git a/engines/ags/metaengine.cpp b/engines/ags/metaengine.cpp
index 977c87d3e1..7dcee2ddd2 100644
--- a/engines/ags/metaengine.cpp
+++ b/engines/ags/metaengine.cpp
@@ -27,7 +27,9 @@
 #include "ags/shared/util/filestream.h"
 #include "ags/engine/ac/richgamemedia.h"
 #include "ags/engine/game/savegame.h"
+#include "common/memstream.h"
 #include "common/savefile.h"
+#include "image/bmp.h"
 
 const char *AGSMetaEngine::getName() const {
 	return "ags";
@@ -78,6 +80,73 @@ SaveStateList AGSMetaEngine::listSaves(const char *target) const {
 	return saveList;
 }
 
+bool AGSMetaEngine::hasFeature(MetaEngineFeature f) const {
+	return
+		(f == kSupportsListSaves) ||
+		(f == kSupportsDeleteSave) ||
+		(f == kSavesSupportMetaInfo) ||
+		(f == kSavesSupportThumbnail) ||
+		(f == kSupportsLoadingDuringStartup);
+}
+
+Common::String AGSMetaEngine::getSavegameFile(int saveGameIdx, const char *target) const {
+	if (saveGameIdx == kSavegameFilePattern) {
+		// Pattern requested
+		return Common::String::format("%s.###", target == nullptr ? getEngineId() : target);
+	} else {
+		// Specific filename requested
+		return Common::String::format("%s.%03d", target == nullptr ? getEngineId() : target, saveGameIdx);
+	}
+}
+
+SaveStateDescriptor AGSMetaEngine::querySaveMetaInfos(const char *target, int slot) const {
+	Common::String filename = Common::String::format("%s%s",
+		::AGS3::AGS::Shared::SAVE_FOLDER_PREFIX,
+		getSavegameFile(slot, target).c_str());
+
+	::AGS3::AGS::Shared::FileStream saveFile(filename, ::AGS3::AGS::Shared::kFile_Open,
+		::AGS3::AGS::Shared::kFile_Read);
+	if (saveFile.IsValid()) {
+		AGS3::RICH_GAME_MEDIA_HEADER rich_media_header;
+		rich_media_header.ReadFromFile(&saveFile);
+
+		if (rich_media_header.dwMagicNumber == RM_MAGICNUMBER) {
+			SaveStateDescriptor desc;
+			desc.setSaveSlot(slot);
+			if (slot == getAutosaveSlot()) {
+				desc.setAutosave(true);
+				desc.setWriteProtectedFlag(true);
+			}
+
+			// Thumbnail handling
+			if (rich_media_header.dwThumbnailOffsetLowerDword != 0 &&
+					rich_media_header.dwThumbnailSize != 0) {
+				// Read in the thumbnail data
+				byte *thumbData = (byte *)malloc(rich_media_header.dwThumbnailSize);
+				saveFile.Seek(rich_media_header.dwThumbnailOffsetLowerDword,
+					AGS3::AGS::Shared::kSeekCurrent);
+				saveFile.Read(thumbData, rich_media_header.dwThumbnailSize);
+				Common::MemoryReadStream thumbStream(thumbData,
+					rich_media_header.dwThumbnailSize, DisposeAfterUse::YES);
+
+				// Read in the thumbnail
+				Image::BitmapDecoder decoder;
+				if (decoder.loadStream(thumbStream)) {
+					const Graphics::Surface *src = decoder.getSurface();
+					Graphics::Surface *dest = new Graphics::Surface();
+					dest->copyFrom(*src);
+
+					desc.setThumbnail(dest);
+				}
+			}
+
+			return desc;
+		}
+	}
+
+	return SaveStateDescriptor();
+}
+
 #if PLUGIN_ENABLED_DYNAMIC(AGS)
 REGISTER_PLUGIN_DYNAMIC(AGS, PLUGIN_TYPE_ENGINE, AGSMetaEngine);
 #else
diff --git a/engines/ags/metaengine.h b/engines/ags/metaengine.h
index aeccb8f447..a98963441f 100644
--- a/engines/ags/metaengine.h
+++ b/engines/ags/metaengine.h
@@ -39,6 +39,33 @@ public:
 		return 999;
 	}
 
+	/**
+	 * Return the name of the save file for the given slot and optional target,
+	 * or a pattern for matching filenames against.
+	 *
+	 * @param saveGameIdx  Index of the save, or kSavegameFilePattern
+	 *                     for returning a filename pattern.
+	 * @param target       Game target. If omitted, then the engine ID is used.
+	 */
+	Common::String getSavegameFile(int saveGameIdx, const char *target = nullptr) const override;
+
+	/**
+	 * Determine whether the engine supports the specified MetaEngine feature.
+	 *
+	 * Used by e.g. the launcher to determine whether to enable the Load button.
+	 */
+	bool hasFeature(MetaEngineFeature f) const override;
+
+	/**
+	 * Return meta information from the specified save state.
+	 *
+	 * Depending on the MetaEngineFeatures set, this can include
+	 * thumbnails, save date and time, play time.
+	 *
+	 * @param target  Name of a config manager target.
+	 * @param slot    Slot number of the save state.
+	 */
+	SaveStateDescriptor querySaveMetaInfos(const char *target, int slot) const override;
 };
 
 #endif


Commit: f41fdec78214deb865cfd461ab8073b7938b89a5
    https://github.com/scummvm/scummvm/commit/f41fdec78214deb865cfd461ab8073b7938b89a5
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Implement GMM saving & loading

Changed paths:
    engines/ags/ags.cpp
    engines/ags/ags.h
    engines/ags/engine/ac/game.cpp
    engines/ags/metaengine.cpp


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index 397a338f6b..ce83538636 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -40,6 +40,7 @@
 #include "ags/engine/globals.h"
 #include "ags/engine/ac/gamesetup.h"
 #include "ags/engine/ac/gamestate.h"
+#include "ags/engine/ac/room.h"
 #include "ags/shared/core/def_version.h"
 #include "ags/engine/debugging/debugger.h"
 #include "ags/engine/debugging/debug_log.h"
@@ -50,6 +51,7 @@
 #include "ags/engine/main/mainheader.h"
 #include "ags/engine/main/main.h"
 #include "ags/engine/platform/base/agsplatformdriver.h"
+#include "ags/engine/script/script.h"
 #include "ags/engine/ac/route_finder.h"
 #include "ags/shared/core/assetmanager.h"
 #include "ags/shared/util/directory.h"
@@ -380,9 +382,17 @@ void AGSEngine::setGraphicsMode(size_t w, size_t h) {
 	_screen = new ::AGS3::BITMAP(_rawScreen);
 }
 
+bool AGSEngine::canLoadGameStateCurrently() {
+	return !::AGS3::thisroom.Options.SaveLoadDisabled && !::AGS3::inside_script;
+}
+
+bool AGSEngine::canSaveGameStateCurrently() {
+	return !::AGS3::thisroom.Options.SaveLoadDisabled && !::AGS3::inside_script;
+}
+
 Common::Error AGSEngine::loadGameState(int slot) {
 	bool dataOverwritten;
-	(void)AGS3::load_game(slot, dataOverwritten);
+	(void)AGS3::try_restore_save(slot);
 	return Common::kNoError;
 }
 
diff --git a/engines/ags/ags.h b/engines/ags/ags.h
index f1004110f1..dc8ebd2561 100644
--- a/engines/ags/ags.h
+++ b/engines/ags/ags.h
@@ -110,6 +110,22 @@ public:
 	 */
 	void setGraphicsMode(size_t w, size_t h);
 
+	bool hasFeature(EngineFeature f) const override {
+		return
+			(f == kSupportsLoadingDuringRuntime) ||
+			(f == kSupportsSavingDuringRuntime);
+	};
+
+	/**
+	 * Indicate whether a game state can be loaded.
+	 */
+	bool canLoadGameStateCurrently() override;
+
+	/**
+	 * Indicate whether a game state can be saved.
+	 */
+	bool canSaveGameStateCurrently() override;
+
 	/**
 	 * Load a savegame
 	 */
diff --git a/engines/ags/engine/ac/game.cpp b/engines/ags/engine/ac/game.cpp
index a1425eb994..af2bf4e48b 100644
--- a/engines/ags/engine/ac/game.cpp
+++ b/engines/ags/engine/ac/game.cpp
@@ -486,7 +486,7 @@ const char *Game_GetSaveSlotDescription(int slnum) {
 
 void restore_game_dialog() {
 	can_run_delayed_command();
-	if (thisroom.Options.SaveLoadDisabled == 1) {
+	if (thisroom.Options.SaveLoadDisabled) {
 		DisplayMessage(983);
 		return;
 	}
diff --git a/engines/ags/metaengine.cpp b/engines/ags/metaengine.cpp
index 7dcee2ddd2..5061513bb6 100644
--- a/engines/ags/metaengine.cpp
+++ b/engines/ags/metaengine.cpp
@@ -129,7 +129,7 @@ SaveStateDescriptor AGSMetaEngine::querySaveMetaInfos(const char *target, int sl
 				Common::MemoryReadStream thumbStream(thumbData,
 					rich_media_header.dwThumbnailSize, DisposeAfterUse::YES);
 
-				// Read in the thumbnail
+				// Decode the thumbnail
 				Image::BitmapDecoder decoder;
 				if (decoder.loadStream(thumbStream)) {
 					const Graphics::Surface *src = decoder.getSurface();


Commit: 3813c6db5ecc1413c1da3354b0c030e6efef2a0c
    https://github.com/scummvm/scummvm/commit/3813c6db5ecc1413c1da3354b0c030e6efef2a0c
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Cleanup of transparency color in Allegro stubs

Changed paths:
    engines/ags/lib/allegro/gfx.cpp


diff --git a/engines/ags/lib/allegro/gfx.cpp b/engines/ags/lib/allegro/gfx.cpp
index 8353437a61..28327b990a 100644
--- a/engines/ags/lib/allegro/gfx.cpp
+++ b/engines/ags/lib/allegro/gfx.cpp
@@ -30,6 +30,11 @@ namespace AGS3 {
 
 int color_conversion;
 
+// For Allegro, paletted sprites always use index 0 as the transparent color,
+// and for higher resolution formats uses bright pink RGB 255, 0, 255
+#define TRANSPARENT_COLOR(BITMAP) ((BITMAP).format.bytesPerPixel == 1 ? 0 : \
+	(BITMAP).format.RGBToColor(255, 0, 255))
+
 /*-------------------------------------------------------------------*/
 
 BITMAP::BITMAP(Graphics::ManagedSurface *owner) : _owner(owner),
@@ -212,7 +217,7 @@ int bitmap_color_depth(BITMAP *bmp) {
 
 int bitmap_mask_color(BITMAP *bmp) {
 	assert(bmp->format.bytesPerPixel > 1);
-	return bmp->format.RGBToColor(255, 0, 255);
+	return TRANSPARENT_COLOR(*bmp);
 }
 
 void add_palette_if_needed(Graphics::ManagedSurface &src, Graphics::ManagedSurface &dest) {
@@ -269,10 +274,7 @@ void draw_sprite(BITMAP *bmp, const BITMAP *sprite, int x, int y) {
 
 	add_palette_if_needed(spriteS, bmpS);
 
-	// For Allegro, paletted sprites always use index 0 as the transparent color,
-	// and for higher resolution formats uses bright pink RGB 255, 0, 255
-	bmpS.transBlitFrom(spriteS, Common::Point(x, y),
-		(spriteS.format.bytesPerPixel == 1) ? 0 : spriteS.format.RGBToColor(255, 0, 255));
+	bmpS.transBlitFrom(spriteS, Common::Point(x, y), TRANSPARENT_COLOR(spriteS));
 }
 
 void stretch_sprite(BITMAP *bmp, const BITMAP *sprite, int x, int y, int w, int h) {


Commit: 420cee48a5f8b8d2e42e7aeeb41656a26e39952e
    https://github.com/scummvm/scummvm/commit/420cee48a5f8b8d2e42e7aeeb41656a26e39952e
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
GRAPHICS: Allow ManagedSurface blitting to ignore transparency

Changed paths:
    graphics/managed_surface.h


diff --git a/graphics/managed_surface.h b/graphics/managed_surface.h
index 8416dcfc35..80ef2c5669 100644
--- a/graphics/managed_surface.h
+++ b/graphics/managed_surface.h
@@ -460,6 +460,15 @@ public:
 		uint transColor = 0, bool flipped = false, uint overrideColor = 0, uint srcAlpha = 0xff,
 		const Surface *mask = nullptr, bool maskOnly = false);
 
+	/**
+	 * Does a blitFrom ignoring any transparency settings
+	 */
+	void rawBlitFrom(const Surface &src, const Common::Rect &srcRect,
+			const Common::Point &destPos, const uint32 *palette) {
+		blitFromInner(src, srcRect, Common::Rect(destPos.x, destPos.y,
+			destPos.x + srcRect.width(), destPos.y + srcRect.height()), palette);
+	}
+
 	/**
 	 * Clear the entire surface.
 	 */


Commit: 81d891ebb06bf16472145f94f78d6384b680a12c
    https://github.com/scummvm/scummvm/commit/81d891ebb06bf16472145f94f78d6384b680a12c
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
GRAPHICS: ManagedSurface transBlitFrom ignore alpha matching transColor

Changed paths:
    graphics/managed_surface.cpp


diff --git a/graphics/managed_surface.cpp b/graphics/managed_surface.cpp
index e791ce5ddd..b2b4a33368 100644
--- a/graphics/managed_surface.cpp
+++ b/graphics/managed_surface.cpp
@@ -513,11 +513,19 @@ void transBlit(const Surface &src, const Common::Rect &srcRect, Surface &dest, c
 		const uint32 *dstPalette, const Surface *mask, bool maskOnly) {
 	int scaleX = SCALE_THRESHOLD * srcRect.width() / destRect.width();
 	int scaleY = SCALE_THRESHOLD * srcRect.height() / destRect.height();
+	byte rt1 = 0, gt1 = 0, bt1 = 0, rt2 = 0, gt2 = 0, bt2 = 0;
 
 	byte *lookup = nullptr;
 	if (srcPalette && dstPalette)
 		lookup = createPaletteLookup(srcPalette, dstPalette);
 
+	// If we're dealing with a 32-bit source surface, we need to split up the RGB,
+	// since we'll want to find matching RGB pixels irrespective of the alpha
+	bool isTrans32 = src.format.bytesPerPixel == 4 && transColor != (uint32)-1;
+	if (isTrans32) {
+		src.format.colorToRGB(transColor, rt1, gt1, bt1);
+	}
+
 	// Loop through drawing output lines
 	for (int destY = destRect.top, scaleYCtr = 0; destY < destRect.bottom; ++destY, scaleYCtr += scaleY) {
 		if (destY < 0 || destY >= dest.h)
@@ -536,7 +544,12 @@ void transBlit(const Surface &src, const Common::Rect &srcRect, Surface &dest, c
 				continue;
 
 			TSRC srcVal = srcLine[flipped ? src.w - scaleXCtr / SCALE_THRESHOLD - 1 : scaleXCtr / SCALE_THRESHOLD];
-			if (srcVal == transColor && !maskOnly)
+			if (isTrans32 && !maskOnly) {
+				src.format.colorToRGB(srcVal, rt2, gt2, bt2);
+				if (rt1 == rt2 && gt1 == gt2 && bt1 == bt2)
+					continue;
+
+			} else if (srcVal == transColor && !maskOnly)
 				continue;
 
 			if (mask) {


Commit: 8e192f5ce99edd57083daadee5e7123555e5766b
    https://github.com/scummvm/scummvm/commit/8e192f5ce99edd57083daadee5e7123555e5766b
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix rendering of player in KQ2+

Changed paths:
    engines/ags/lib/allegro/gfx.cpp


diff --git a/engines/ags/lib/allegro/gfx.cpp b/engines/ags/lib/allegro/gfx.cpp
index 28327b990a..b66bedf23a 100644
--- a/engines/ags/lib/allegro/gfx.cpp
+++ b/engines/ags/lib/allegro/gfx.cpp
@@ -224,6 +224,12 @@ void add_palette_if_needed(Graphics::ManagedSurface &src, Graphics::ManagedSurfa
 	if (src.format.bytesPerPixel == 1 && dest.format.bytesPerPixel > 1) {
 		byte pal[PALETTE_SIZE];
 		palette_to_rgb8(_current_palette, pal);
+
+		// Set transparent color for index 0
+		pal[0] = 0xff;
+		pal[1] = 0;
+		pal[2] = 0xff;
+
 		src.setPalette(pal, 0, PALETTE_COUNT);
 	}
 }
@@ -234,7 +240,13 @@ void blit(const BITMAP *src, BITMAP *dest, int src_x, int src_y, int dst_x, int
 
 	add_palette_if_needed(srcS, destS);
 
-	destS.blitFrom(srcS, Common::Rect(src_x, src_y, src_x + width, src_y + height), Common::Point(dst_x, dst_y));
+	if (dynamic_cast<Graphics::Screen *>(&destS) != nullptr) {
+		destS.blitFrom(srcS, Common::Rect(src_x, src_y, src_x + width, src_y + height),
+			Common::Point(dst_x, dst_y));
+	} else {
+		destS.rawBlitFrom(srcS, Common::Rect(src_x, src_y, src_x + width, src_y + height),
+			Common::Point(dst_x, dst_y), srcS.getPalette());
+	}
 }
 
 void stretch_blit(const BITMAP *src, BITMAP *dest, int source_x, int source_y, int source_width, int source_height,


Commit: 8ec4829dcb68f62fe14f9a05f04fc2ca7619f7ac
    https://github.com/scummvm/scummvm/commit/8ec4829dcb68f62fe14f9a05f04fc2ca7619f7ac
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added fallback detector

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


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index ce83538636..3ecd5815ed 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -391,7 +391,6 @@ bool AGSEngine::canSaveGameStateCurrently() {
 }
 
 Common::Error AGSEngine::loadGameState(int slot) {
-	bool dataOverwritten;
 	(void)AGS3::try_restore_save(slot);
 	return Common::kNoError;
 }
diff --git a/engines/ags/detection.cpp b/engines/ags/detection.cpp
index 204906a2d5..d1afbb2716 100644
--- a/engines/ags/detection.cpp
+++ b/engines/ags/detection.cpp
@@ -21,11 +21,86 @@
  */
 
 #include "base/plugins.h"
+#include "common/file.h"
 #include "ags/detection.h"
 #include "ags/detection_tables.h"
 
+namespace AGS3 {
+
+static const char *const HEAD_SIG = "CLIB\x1a";
+static const char *const TAIL_SIG = "CLIB\x1\x2\x3\x4SIGE";
+#define HEAD_SIG_SIZE 5
+#define TAIL_SIG_SIZE 12
+
+/**
+ * Detect the presence of an AGS game
+ * TODO: This is a compact version of MFLUtil::ReadSigsAndVersion. I didn't
+ * use the full version due to the complexities of including it when
+ * plugins are enabled. In the future, though, it would be nice to figure
+ * out, since the full version can handle not detecting on files that are
+ * AGS, but only contain sounds, etc. rather than a game
+ */
+static bool isAGSFile(Common::File &f) {
+	// Check for signature at beginning of file
+	char buffer[16];
+	if (f.read(buffer, HEAD_SIG_SIZE) == HEAD_SIG_SIZE &&
+			!memcmp(buffer, HEAD_SIG, HEAD_SIG_SIZE))
+		return true;
+
+	// Check for signature at end of EXE files
+	f.seek(-TAIL_SIG_SIZE, SEEK_END);
+	if (f.read(buffer, TAIL_SIG_SIZE) == TAIL_SIG_SIZE &&
+		!memcmp(buffer, TAIL_SIG, TAIL_SIG_SIZE))
+		return true;
+
+	return false;
+}
+
+} // namespace AGS3
+
 AGSMetaEngineDetection::AGSMetaEngineDetection() : AdvancedMetaEngineDetection(AGS::GAME_DESCRIPTIONS,
 	        sizeof(AGS::AGSGameDescription), AGS::GAME_NAMES) {
 }
 
+ADDetectedGame AGSMetaEngineDetection::fallbackDetect(const FileMap &allFiles, const Common::FSList &fslist) const {
+	// Set the default values for the fallback descriptor's ADGameDescription part.
+	AGS::g_fallbackDesc.desc.language = Common::UNK_LANG;
+	AGS::g_fallbackDesc.desc.platform = Common::kPlatformDOS;
+	AGS::g_fallbackDesc.desc.flags = ADGF_NO_FLAGS;
+
+	// // Set the defaults for gameid and extra
+	_gameid = "ags";
+	_extra.clear();
+
+	// Scan for AGS games
+	for (Common::FSList::const_iterator file = fslist.begin(); file != fslist.end(); ++file) {
+		if (file->isDirectory())
+			continue;
+
+		Common::String filename = file->getName();
+		if (!filename.hasSuffixIgnoreCase(".exe") &&
+				!filename.hasSuffixIgnoreCase(".ags") &&
+				!filename.equalsIgnoreCase("ac2game.dat"))
+			// Neither, so move on
+			continue;
+
+		Common::File f;
+		if (!f.open(allFiles[filename]))
+			continue;
+
+		if (AGS3::isAGSFile(f)) {
+			_filename = filename;
+
+			AGS::g_fallbackDesc.desc.gameId = _gameid.c_str();
+			AGS::g_fallbackDesc.desc.extra = _extra.c_str();
+			AGS::g_fallbackDesc.desc.filesDescriptions[0].fileName = _filename.c_str();
+			AGS::g_fallbackDesc.desc.filesDescriptions[0].fileSize = f.size();
+
+			return ADDetectedGame(&AGS::g_fallbackDesc.desc);
+		}
+	}
+
+	return ADDetectedGame();
+}
+
 REGISTER_PLUGIN_STATIC(AGS_DETECTION, PLUGIN_TYPE_ENGINE_DETECTION, AGSMetaEngineDetection);
diff --git a/engines/ags/detection.h b/engines/ags/detection.h
index 9ac3d6ae35..9c0710f374 100644
--- a/engines/ags/detection.h
+++ b/engines/ags/detection.h
@@ -39,7 +39,12 @@ struct AGSGameDescription {
 
 } // namespace AGS
 
+
 class AGSMetaEngineDetection : public AdvancedMetaEngineDetection {
+	mutable Common::String _gameid;
+	mutable Common::String _extra;
+	mutable Common::String _filename;
+
 public:
 	AGSMetaEngineDetection();
 	~AGSMetaEngineDetection() override {}
@@ -53,8 +58,10 @@ public:
 	}
 
 	const char *getOriginalCopyright() const override {
-		return "";
+		return "AGS Engine (C) Chris Jones";
 	}
+
+	ADDetectedGame fallbackDetect(const FileMap &allFiles, const Common::FSList &fslist) const override;
 };
 
 #endif
diff --git a/engines/ags/detection_tables.h b/engines/ags/detection_tables.h
index 267f99bf61..d389899617 100644
--- a/engines/ags/detection_tables.h
+++ b/engines/ags/detection_tables.h
@@ -105,4 +105,20 @@ static const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	{ AD_TABLE_END_MARKER }
 };
 
+/**
+ * The fallback game descriptor used by the fallback detection code
+ */
+static AGSGameDescription g_fallbackDesc = {
+	{
+		"",
+		"",
+		AD_ENTRY1(0, 0),
+		Common::UNK_LANG,
+		Common::kPlatformWindows,
+		ADGF_NO_FLAGS,
+		GUIO0()
+	},
+	nullptr
+};
+
 } // namespace AGS


Commit: a94af8118849382f3dcac50e780f797f62678408
    https://github.com/scummvm/scummvm/commit/a94af8118849382f3dcac50e780f797f62678408
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added tool to scan folders and build detection entries

When ScummVM is built with the new ENABLE_AGS_SCANNER define,
trying to start any game will instead scan all the folders
starting from the current directory downwards, and output
text suitable for pasting in the detection tables.

Changed paths:
  A engines/ags/tests/game_scanner.cpp
  A engines/ags/tests/game_scanner.h
    engines/ags/ags.cpp
    engines/ags/detection.h
    engines/ags/detection_tables.h
    engines/ags/module.mk
    engines/ags/shared/core/assetmanager.cpp
    engines/ags/shared/core/assetmanager.h
    engines/ags/shared/util/stdio_compat.cpp
    engines/ags/shared/util/stream.h


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index 3ecd5815ed..35b4c1385b 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -57,7 +57,7 @@
 #include "ags/shared/util/directory.h"
 #include "ags/shared/util/path.h"
 
-
+#include "ags/tests/game_scanner.h"
 #ifdef ENABLE_AGS_TESTS
 #include "ags/tests/test_all.h"
 #endif
@@ -313,6 +313,11 @@ Common::Error AGSEngine::run() {
 	const char *ARGV[] = { "scummvm.exe", filename };
 	const int ARGC = 2;
 
+#if ENABLE_AGS_SCANNER
+	AGS3::GameScanner scanner;
+	scanner.scan();
+	return Common::kNoError;
+#endif
 #ifdef ENABLE_AGS_TESTS
 	AGS3::Test_DoAllTests();
 	return Common::kNoError;
diff --git a/engines/ags/detection.h b/engines/ags/detection.h
index 9c0710f374..892a758edf 100644
--- a/engines/ags/detection.h
+++ b/engines/ags/detection.h
@@ -37,6 +37,10 @@ struct AGSGameDescription {
 	const PluginVersion *_plugins;
 };
 
+extern const PlainGameDescriptor GAME_NAMES[];
+
+extern const AGSGameDescription GAME_DESCRIPTIONS[];
+
 } // namespace AGS
 
 
diff --git a/engines/ags/detection_tables.h b/engines/ags/detection_tables.h
index d389899617..5fb16170ce 100644
--- a/engines/ags/detection_tables.h
+++ b/engines/ags/detection_tables.h
@@ -22,9 +22,12 @@
 
 namespace AGS {
 
-static const PlainGameDescriptor GAME_NAMES[] = {
+const PlainGameDescriptor GAME_NAMES[] = {
 	{ "ags", "Adventure Game Studio Game" },
 
+	{ "5daysastranger", "5 Days A Stranger" },
+	{ "7daysaskeptic", "7 Days A Skeptic" },
+	{ "absentparti", "Absent - Part I" },
 	{ "atotk", "A Tale Of Two Kingdoms" },
 	{ "bcremake", "Black Cauldron Remake" },
 	{ "blackwell1", "The Blackwell Legacy"},
@@ -77,10 +80,13 @@ static const PlainGameDescriptor GAME_NAMES[] = {
 
 static const PluginVersion AGSCREDITZ_11[] = { { "agscreditz", 11 }, { nullptr, 0 } };
 
-static const AGSGameDescription GAME_DESCRIPTIONS[] = {
-	ENGLISH_PLUGIN("bcremake", "bc.exe", "0710e2ec71042617f565c01824f0cf3c", 7683255, AGSCREDITZ_11),
+const AGSGameDescription GAME_DESCRIPTIONS[] = {
+	ENGLISH_ENTRY("5daysastranger", "5days.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 4440143),
+	ENGLISH_ENTRY("7daysaskeptic", "7days.exe", "465f972675db2da6040518221af5b0ba", 4693374),
+	ENGLISH_ENTRY("absentparti", "Absent - Part I.exe", "34ca36e3948aae8527dd0e90f0861a75", 31421924),
 	ENGLISH_ENTRY("atotk", "atotk.exe", "37cf2d4d07842d45b59c6dd9387c1ee7", 42872046),
 	ENGLISH_ENTRY("atotk", "atotk.exe", "37cf2d4d07842d45b59c6dd9387c1ee7", 42740200),
+	ENGLISH_PLUGIN("bcremake", "bc.exe", "0710e2ec71042617f565c01824f0cf3c", 7683255, AGSCREDITZ_11),
 	ENGLISH_ENTRY("blackwell1", "blackwell1.exe", "605e124cb7e0b56841c471e2d641c224", 18822697), // GOG
 	ENGLISH_ENTRY("blackwell2", "unbound.exe", "5c3a940514d91431e8e1c372018851ca", 14493753), // GOG
 	ENGLISH_ENTRY("blackwell3", "convergence.exe", "2260c1a21aba7ac00baf0100d4ca54f1", 172575801), // GOG
@@ -98,7 +104,7 @@ static const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("primordia", "primordia.exe", "22313e59c3233001488c26f18c80cc08", 973495830), // GOG
 	ENGLISH_ENTRY("primordia", "primordia.exe", "f2edc9c3161f1f538df9b4c59fc89e24", 978377890), // GOG
 	ENGLISH_ENTRY("resonance", "resonance.exe", "2e635c22bcbf0ed3d46f1bcde71812d4", 849404957), // GOG
-	// For some macOS and iOS releases the executable was renamed to ac2game.dat
+
 	ENGLISH_ENTRY("mage", "ac2game.dat", "2e822f554994f36e0c62da2acda874da", 30492258), // GOG, Mac
 	ENGLISH_ENTRY("unavowed", "ac2game.dat", "b1ff7d96667707daf4266975cea2bf90", 1755457364), // Steam, Mac
 
diff --git a/engines/ags/module.mk b/engines/ags/module.mk
index c04cd2c01a..d784b0a098 100644
--- a/engines/ags/module.mk
+++ b/engines/ags/module.mk
@@ -317,6 +317,11 @@ MODULE_OBJS = \
 	plugins/ags_sprite_font/variable_width_font.o \
 	plugins/ags_sprite_font/variable_width_sprite_font.o
 
+ifdef ENABLE_AGS_SCANNER
+MODULE_OBJS += \
+	tests/game_scanner.o
+endif
+
 ifdef ENABLE_AGS_TESTS
 MODULE_OBJS += \
 	tests/test_all.o \
diff --git a/engines/ags/shared/core/assetmanager.cpp b/engines/ags/shared/core/assetmanager.cpp
index e3f62a8f16..337da1c1e0 100644
--- a/engines/ags/shared/core/assetmanager.cpp
+++ b/engines/ags/shared/core/assetmanager.cpp
@@ -78,11 +78,16 @@ AssetManager::~AssetManager() {
 
 AssetError AssetManager::ReadDataFileTOC(const String &data_file, AssetLibInfo &lib) {
 	Stream *in = ci_fopen(data_file, Shared::kFile_Open, Shared::kFile_Read);
+	return ReadDataFileTOC(in, lib);
+}
+
+AssetError AssetManager::ReadDataFileTOC(Stream *in, AssetLibInfo &lib) {
 	if (in) {
 		MFLUtil::MFLError err = MFLUtil::ReadHeader(lib, in);
 		delete in;
 		return (err != MFLUtil::kMFLNoError) ? kAssetErrLibParse : kAssetNoError;
 	}
+
 	return kAssetErrNoLibFile;
 }
 
diff --git a/engines/ags/shared/core/assetmanager.h b/engines/ags/shared/core/assetmanager.h
index 383c61b52d..987d74d2d4 100644
--- a/engines/ags/shared/core/assetmanager.h
+++ b/engines/ags/shared/core/assetmanager.h
@@ -92,6 +92,7 @@ public:
 	static bool         IsDataFile(const String &data_file);
 	// Read data file table of contents into provided struct
 	static AssetError   ReadDataFileTOC(const String &data_file, AssetLibInfo &lib);
+	static AssetError   ReadDataFileTOC(Stream *data_file, AssetLibInfo &lib);
 
 	// NOTE: this group of methods are only temporarily public
 	static AssetError   SetDataFile(const String &data_file);
diff --git a/engines/ags/shared/util/stdio_compat.cpp b/engines/ags/shared/util/stdio_compat.cpp
index 449aa39eb7..6ec93ea7d8 100644
--- a/engines/ags/shared/util/stdio_compat.cpp
+++ b/engines/ags/shared/util/stdio_compat.cpp
@@ -49,7 +49,11 @@ file_off_t ags_ftell(Common::Stream *stream) {
 }
 
 Common::FSNode getFSNode(const char *path) {
-	Common::FSNode node(ConfMan.get("path"));
+	Common::FSNode node(path);
+	if (node.isReadable())
+		return node;
+
+	node = Common::FSNode(ConfMan.get("path"));
 	Common::String filePath(path);
 
 	// If it's the root game folder, return the node for it
diff --git a/engines/ags/shared/util/stream.h b/engines/ags/shared/util/stream.h
index 4b42de45e7..5489cde190 100644
--- a/engines/ags/shared/util/stream.h
+++ b/engines/ags/shared/util/stream.h
@@ -125,6 +125,85 @@ public:
 	}
 };
 
+class StreamScummVMFile : public Stream {
+private:
+	Common::SeekableReadStream *_stream;
+	DisposeAfterUse::Flag _disposeAfterUse;
+public:
+	StreamScummVMFile(Common::SeekableReadStream *stream,
+		DisposeAfterUse::Flag disposeAfterUse = DisposeAfterUse::NO) :
+		_stream(stream), _disposeAfterUse(disposeAfterUse) {}
+	~StreamScummVMFile() override {
+		Close();
+	}
+
+	void Close() {
+		if (_disposeAfterUse == DisposeAfterUse::YES)
+			delete _stream;
+		_stream = nullptr;
+	}
+
+	bool IsValid() const override { return _stream != nullptr; }
+	bool EOS() const override { return _stream->eos(); }
+	soff_t GetLength() const override { return _stream->size(); }
+	soff_t GetPosition() const override { return _stream->pos(); }
+	bool CanRead() const override { return true; }
+	bool CanWrite() const override { return false; }
+	bool CanSeek() const override { return true; }
+
+	size_t Read(void *buffer, size_t size) override {
+		return _stream->read(buffer, size);
+	}
+	int32_t ReadByte() override { return _stream->readByte(); }
+	size_t Write(const void *buffer, size_t size) override { return 0; }
+	int32_t WriteByte(uint8_t b) override { return 0; }
+
+	int8_t ReadInt8() override { return (int8)_stream->readByte(); }
+	int16_t ReadInt16() override { return _stream->readSint16LE(); }
+	int32_t ReadInt32() override { return _stream->readSint32LE(); }
+	int64_t ReadInt64() override { return _stream->readSint64LE(); }
+	bool ReadBool() override { return _stream->readByte() != 0; }
+	size_t ReadArray(void *buffer, size_t elem_size, size_t count) override {
+		return _stream->read(buffer, elem_size * count) / elem_size;
+	}
+	size_t ReadArrayOfInt8(int8_t *buffer, size_t count) override {
+		return _stream->read(buffer, count);
+	}
+	size_t ReadArrayOfInt16(int16_t *buffer, size_t count) override {
+		for (size_t i = 0; i < count; ++i)
+			*buffer++ = _stream->readSint16LE();
+		return count;
+	}
+	size_t ReadArrayOfInt32(int32_t *buffer, size_t count) override {
+		for (size_t i = 0; i < count; ++i)
+			*buffer++ = _stream->readSint32LE();
+		return count;
+	}
+	size_t ReadArrayOfInt64(int64_t *buffer, size_t count) override {
+		for (size_t i = 0; i < count; ++i)
+			*buffer++ = _stream->readSint64LE();
+		return count;
+	}
+
+	size_t WriteInt8(int8_t val) override { return 0; }
+	size_t WriteInt16(int16_t val) override { return 0; }
+	size_t WriteInt32(int32_t val) override { return 0; }
+	size_t WriteInt64(int64_t val) override { return 0; }
+	size_t WriteBool(bool val) override { return 0; }
+	size_t WriteArray(const void *buffer, size_t elem_size, size_t count) override { return 0; }
+	size_t WriteArrayOfInt8(const int8_t *buffer, size_t count) override { return 0; }
+	size_t WriteArrayOfInt16(const int16_t *buffer, size_t count) override { return 0; }
+	size_t WriteArrayOfInt32(const int32_t *buffer, size_t count) override { return 0; }
+	size_t WriteArrayOfInt64(const int64_t *buffer, size_t count) override { return 0; }
+
+	bool Seek(soff_t offset, StreamSeek origin = kSeekCurrent) override {
+		return _stream->seek(offset, origin);
+	}
+
+	bool HasErrors() const override { return _stream->err(); }
+	bool Flush() override { return true; }
+};
+
 } // namespace Shared
 } // namespace AGS
 } // namespace AGS3
diff --git a/engines/ags/tests/game_scanner.cpp b/engines/ags/tests/game_scanner.cpp
new file mode 100644
index 0000000000..3b4a7b6b44
--- /dev/null
+++ b/engines/ags/tests/game_scanner.cpp
@@ -0,0 +1,136 @@
+/* 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 "ags/tests/game_scanner.h"
+#include "ags/detection.h"
+#include "ags/shared/ac/gamesetupstruct.h"
+#include "ags/shared/core/assetmanager.h"
+#include "ags/shared/util/multifilelib.h"
+#include "ags/shared/util/string.h"
+#include "ags/engine/main/game_file.h"
+#include "common/config-manager.h"
+#include "common/file.h"
+#include "common/md5.h"
+#include "common/unzip.h"
+
+namespace AGS3 {
+
+extern bool define_gamedata_location(const AGS::Shared::String &exe_path);
+extern bool engine_try_init_gamedata(AGS::Shared::String gamepak_path);
+extern GameSetupStruct game;
+
+void GameScanner::scan() {
+	Common::FSNode folder("."); //ConfMan.get("path"));
+	scanFolder(folder);
+
+	for (EntryMap::iterator it = _games.begin(); it != _games.end(); ++it) {
+		debug("{ \"%s\", \"%s\" },", it->_key.c_str(), it->_value._gameName.c_str());
+	}
+	debug("");
+
+	for (EntryMap::iterator it = _games.begin(); it != _games.end(); ++it) {
+		debug("ENGLISH_ENTRY(\"%s\", \"%s\", \"%s\", %u),",
+			it->_key.c_str(), it->_value._filename.c_str(),
+			it->_value._md5.c_str(), it->_value._filesize);
+	}
+	debug("");
+}
+
+void GameScanner::scanFolder(const Common::FSNode &folder) {
+	Common::FSList fslist;
+	folder.getChildren(fslist, Common::FSNode::kListAll);
+
+	for (uint idx = 0; idx < fslist.size(); ++idx) {
+		Common::FSNode node = fslist[idx];
+		Common::String filename = node.getName();
+
+		if (node.isDirectory()) {
+			scanFolder(node);
+		} else if (filename.hasSuffixIgnoreCase(".exe") ||
+				filename.hasSuffixIgnoreCase(".ags") ||
+				filename.equalsIgnoreCase("ac2game.dat")) {
+			Common::String path = node.getPath();
+			scanFile(path);
+		}
+	}
+}
+
+void GameScanner::scanFile(const Common::String &filename) {
+	Common::File f;
+	Common::FSNode fsNode(filename);
+	if (!f.open(fsNode))
+		return;
+
+	int32 size = f.size();
+	Common::String md5 = Common::computeStreamMD5AsString(f, 5000);
+
+	// Check if it's an already known game
+	const ::AGS::AGSGameDescription *gameP = ::AGS::GAME_DESCRIPTIONS;
+	for (; gameP->desc.gameId; ++gameP) {
+		if (size == gameP->desc.filesDescriptions[0].fileSize &&
+				md5 == gameP->desc.filesDescriptions[0].md5)
+			// Known game, so skip
+			return;
+	}
+
+	// Check the game file
+	AGS::Shared::AssetLibInfo lib;
+	AGS::Shared::StreamScummVMFile *stream = new AGS::Shared::StreamScummVMFile(&f);
+	if (AGS::Shared::AssetManager::ReadDataFileTOC(stream, lib) != AGS::Shared::kAssetNoError)
+		return;
+	f.close();
+
+	AGS::Shared::AssetManager::DestroyInstance();
+	AGS::Shared::AssetManager::CreateInstance();
+	AGS::Shared::AssetManager::SetDataFile(filename);
+
+	if (!engine_try_init_gamedata(filename))
+		return;
+
+	AGS::Shared::HError err = preload_game_data();
+	if (!err)
+		return;
+
+	// Add an entry for the found game
+	Entry e;
+	e._filename = fsNode.getName();
+	e._filesize = size;
+	e._gameName = game.gamename;
+	e._md5 = md5;
+
+	Common::String id = convertGameNameToId(e._gameName);
+	_games[id] = e;
+} 
+
+Common::String GameScanner::convertGameNameToId(const Common::String &name) {
+	Common::String result;
+
+	for (uint idx = 0; idx < name.size(); ++idx) {
+		char c = name[idx];
+		if (Common::isAlnum(c))
+			result += tolower(c);
+	}
+
+	return result;
+}
+
+} // namespace AGS3
diff --git a/engines/ags/tests/game_scanner.h b/engines/ags/tests/game_scanner.h
new file mode 100644
index 0000000000..a798222fd6
--- /dev/null
+++ b/engines/ags/tests/game_scanner.h
@@ -0,0 +1,65 @@
+/* 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/hashmap.h"
+#include "common/fs.h"
+
+namespace AGS3 {
+
+/**
+ * A support class for scanning a hierarchy of folders for AGS games,
+ * and printing output suitable for posting into the detection tables.
+ * Scanning starts from the current directory when ScummVM is started
+ */
+class GameScanner {
+	struct Entry {
+		Common::String _gameName;
+		Common::String _filename;
+		Common::String _md5;
+		size_t _filesize;
+	};
+private:
+	typedef Common::HashMap<Common::String, Entry> EntryMap;
+	EntryMap _games;
+private:
+	/**
+	 * Scan a folder for AGS games
+	 */
+	void scanFolder(const Common::FSNode &folder);
+
+	/**
+	 * Scans a single file that may be an AGS game
+	 */
+	void scanFile(const Common::String &filename);
+
+	/**
+	 * Convert a game name to an appropriate game Id
+	 */
+	static Common::String convertGameNameToId(const Common::String &name);
+public:
+	/**
+	 * Main execution method
+	 */
+	void scan();
+};
+
+} // namespace AGS3


Commit: 175735f727218b6fd6b933f249dedf1e5ab1c514
    https://github.com/scummvm/scummvm/commit/175735f727218b6fd6b933f249dedf1e5ab1c514
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fixes for game scanner tool

Changed paths:
    engines/ags/ags.cpp
    engines/ags/tests/game_scanner.cpp
    engines/ags/tests/game_scanner.h


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index 35b4c1385b..a294f47614 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -57,7 +57,9 @@
 #include "ags/shared/util/directory.h"
 #include "ags/shared/util/path.h"
 
+#ifdef ENABLE_AGS_SCANNER
 #include "ags/tests/game_scanner.h"
+#endif
 #ifdef ENABLE_AGS_TESTS
 #include "ags/tests/test_all.h"
 #endif
diff --git a/engines/ags/tests/game_scanner.cpp b/engines/ags/tests/game_scanner.cpp
index 3b4a7b6b44..73e8580349 100644
--- a/engines/ags/tests/game_scanner.cpp
+++ b/engines/ags/tests/game_scanner.cpp
@@ -29,8 +29,8 @@
 #include "ags/engine/main/game_file.h"
 #include "common/config-manager.h"
 #include "common/file.h"
+#include "common/hashmap.h"
 #include "common/md5.h"
-#include "common/unzip.h"
 
 namespace AGS3 {
 
@@ -39,18 +39,23 @@ extern bool engine_try_init_gamedata(AGS::Shared::String gamepak_path);
 extern GameSetupStruct game;
 
 void GameScanner::scan() {
+	detectClashes();
+
 	Common::FSNode folder("."); //ConfMan.get("path"));
 	scanFolder(folder);
 
-	for (EntryMap::iterator it = _games.begin(); it != _games.end(); ++it) {
-		debug("{ \"%s\", \"%s\" },", it->_key.c_str(), it->_value._gameName.c_str());
+	Common::HashMap<Common::String, bool> gameDescs;
+	for (EntryArray::iterator it = _games.begin(); it != _games.end(); ++it) {
+		if (!gameDescs.contains(it->_id))
+			debug("{ \"%s\", \"%s\" },", it->_id.c_str(), it->_gameName.c_str());
+		gameDescs[it->_id] = true;
 	}
 	debug("");
 
-	for (EntryMap::iterator it = _games.begin(); it != _games.end(); ++it) {
+	for (EntryArray::iterator it = _games.begin(); it != _games.end(); ++it) {
 		debug("ENGLISH_ENTRY(\"%s\", \"%s\", \"%s\", %u),",
-			it->_key.c_str(), it->_value._filename.c_str(),
-			it->_value._md5.c_str(), it->_value._filesize);
+			it->_id.c_str(), it->_filename.c_str(),
+			it->_md5.c_str(), it->_filesize);
 	}
 	debug("");
 }
@@ -115,10 +120,10 @@ void GameScanner::scanFile(const Common::String &filename) {
 	e._filename = fsNode.getName();
 	e._filesize = size;
 	e._gameName = game.gamename;
+	e._id = convertGameNameToId(e._gameName);
 	e._md5 = md5;
 
-	Common::String id = convertGameNameToId(e._gameName);
-	_games[id] = e;
+	_games.push_back(e);
 } 
 
 Common::String GameScanner::convertGameNameToId(const Common::String &name) {
@@ -133,4 +138,20 @@ Common::String GameScanner::convertGameNameToId(const Common::String &name) {
 	return result;
 }
 
+void GameScanner::detectClashes() {
+	Common::HashMap<Common::String, bool> gameIds;
+	Common::HashMap<Common::String, bool> gameNames;
+
+	const PlainGameDescriptor *nameP = ::AGS::GAME_NAMES;
+	for (; nameP->gameId; ++nameP) {
+		if (gameIds.contains(nameP->gameId))
+			debug("Duplicate game Id: %s", nameP->gameId);
+		gameIds[nameP->gameId] = true;
+
+		if (gameNames.contains(nameP->description))
+			debug("Duplicate game name: %s", nameP->description);
+		gameNames[nameP->description] = true;
+	}
+}
+
 } // namespace AGS3
diff --git a/engines/ags/tests/game_scanner.h b/engines/ags/tests/game_scanner.h
index a798222fd6..b87a41190c 100644
--- a/engines/ags/tests/game_scanner.h
+++ b/engines/ags/tests/game_scanner.h
@@ -20,7 +20,7 @@
  *
  */
 
-#include "common/hashmap.h"
+#include "common/array.h"
 #include "common/fs.h"
 
 namespace AGS3 {
@@ -32,14 +32,15 @@ namespace AGS3 {
  */
 class GameScanner {
 	struct Entry {
+		Common::String _id;
 		Common::String _gameName;
 		Common::String _filename;
 		Common::String _md5;
 		size_t _filesize;
 	};
 private:
-	typedef Common::HashMap<Common::String, Entry> EntryMap;
-	EntryMap _games;
+	typedef Common::Array<Entry> EntryArray;
+	EntryArray _games;
 private:
 	/**
 	 * Scan a folder for AGS games
@@ -55,6 +56,11 @@ private:
 	 * Convert a game name to an appropriate game Id
 	 */
 	static Common::String convertGameNameToId(const Common::String &name);
+
+	/**
+	 * Detects clashes with game Ids in the existing detection table.
+	 */
+	static void detectClashes();
 public:
 	/**
 	 * Main execution method


Commit: 81af4252241a0c638393c0c23c826a1fd3e3b664
    https://github.com/scummvm/scummvm/commit/81af4252241a0c638393c0c23c826a1fd3e3b664
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added all games from agsarchives.com to detection table

Changed paths:
    engines/ags/detection_tables.h


diff --git a/engines/ags/detection_tables.h b/engines/ags/detection_tables.h
index 5fb16170ce..2374d76e9c 100644
--- a/engines/ags/detection_tables.h
+++ b/engines/ags/detection_tables.h
@@ -25,65 +25,1188 @@ namespace AGS {
 const PlainGameDescriptor GAME_NAMES[] = {
 	{ "ags", "Adventure Game Studio Game" },
 
+	// Pre-2.5 games that aren't supported by the current AGS engine
+	{ "qfg412", "Quest for Glory 4 1/2" },
+
+	// Post-2.5 games that are likely supported by the AGS engine
 	{ "5daysastranger", "5 Days A Stranger" },
 	{ "7daysaskeptic", "7 Days A Skeptic" },
-	{ "absentparti", "Absent - Part I" },
 	{ "atotk", "A Tale Of Two Kingdoms" },
 	{ "bcremake", "Black Cauldron Remake" },
-	{ "blackwell1", "The Blackwell Legacy"},
-	{ "blackwell2", "Blackwell Unbound"},
-	{ "blackwell3", "The Blackwell Convergence"},
-	{ "blackwell4", "The Blackwell Deception"},
-	{ "blackwell5", "The Blackwell Epiphany"},
-	{ "kq2agdi", "Kings Quest II - Romancing The Stones" },
+	{ "blackwell1", "The Blackwell Legacy" },
+	{ "blackwell2", "Blackwell Unbound" },
+	{ "blackwell3", "The Blackwell Convergence" },
+	{ "blackwell4", "The Blackwell Deception" },
+	{ "blackwell5", "The Blackwell Epiphany" },
+	{ "blackwellconvergence", "Blackwell Convergence" },
+	{ "blackwelllegacydemo", "Blackwell Legacy Demo" },
+	{ "blackwellunbounddemo", "Blackwell Unbound Demo" },
+	{ "geminirue", "Gemini Rue" },
+	{ "goldenwake", "A Golden Wake" },
+	{ "kathyrain", "Kathy Rain" },
 	{ "kq1agdi", "King's Quest I: Quest for the Crown Remake" },
 	{ "kq2agdi", "King's Quest II: Romancing The Stones" },
 	{ "kq3agdi", "King's Quest III Redux: To Heir is Human" },
-	{ "geminirue", "Gemini Rue"},
-	{ "goldenwake", "A Golden Wake"},
-	{ "kathyrain", "Kathy Rain"},
-	{ "qfi", "Quest for Infamy"},
-	{ "oott", "Order of the Thorne: The King's Challenge"},
-	{ "primordia", "Primordia"},
-	{ "resonance", "Resonance"},
-	{ "mage", "Mage's Initiation: Reign of the Elements"},
-	{ "unavowed", "Unavowed"},
+	{ "mage", "Mage's Initiation: Reign of the Elements" },
+	{ "oott", "Order of the Thorne: The King's Challenge" },
+	{ "primordia", "Primordia" },
+	{ "qfi", "Quest for Infamy" },
+	{ "resonance", "Resonance" },
+	{ "unavowed", "Unavowed" },
+
+	// Unsorted games
+	{ "10waysfromsunday", "10 Ways from Sunday" },
+	{ "1dayamosquito", "1 day a mosquito" },
+	{ "2034acaftercanadaii", "2034 A.C. (After Canada) II" },
+	{ "24hours", "24 Hours" },
+	{ "3piggiesalpha", "3piggiesAlpha" },
+	{ "46memorylane", "46 Memory Lane" },
+	{ "4ofclubs", "4 of Clubs" },
+	{ "6daysasacrifice", "6 Days A Sacrifice" },
+	{ "6mornings", "6mornings" },
+	{ "aazor", "Aazor" },
+	{ "abducted", "ABDUCTED" },
+	{ "absent", "Absent" },
+	{ "absentparti", "Absent - Part I" },
+	{ "access", "_Access" },
+	{ "aceking", "Ace King" },
+	{ "acequest", "Ace Quest" },
+	{ "achequest", "Ache Quest" },
+	{ "achristmasblunder", "A Christmas Blunder" },
+	{ "aciddd", "ACIDDD" },
+	{ "acureforthecommoncold", "A Cure for the Common Cold" },
+	{ "adaywithmichael", "A Day with Michael" },
+	{ "adventurequest", "Adventure Quest" },
+	{ "adventurequest2", "Adventure Quest  2" },
+	{ "adventuresofjoshanddyan", "Adventures of Josh and Dyan" },
+	{ "adventuresofmaxfaxepisode1", "Adventures of Max Fax (episode 1)" },
+	{ "adventuresofprincessmarian", "Adventures of Princess Marian" },
+	{ "adventuretheinsidejob", "Adventure: The Inside Job" },
+	{ "aerinde", "Aerinde" },
+	{ "aeronuts", "AeroNuts" },
+	{ "afriendindeed", "A Friend Indeed ..." },
+	{ "afrojones", "Afro Jones" },
+	{ "afterashadow", "After a Shadow" },
+	{ "agenthudson", "Agent Hudson" },
+	{ "agenttrinityepisode0theultimatum", "Agent Trinity - Episode 0 - The Ultimatum" },
+	{ "aggghost", "A G-G-Ghost!" },
+	{ "agitprop", "AGITPROP" },
+	{ "agnosticchicken", "Agnostic Chicken" },
+	{ "ags-mi3", "AGS MI3" },
+	{ "agsawards2008ceremony", "AGS Awards 2008 Ceremony " },
+	{ "agsdarts", "AGS Darts" },
+	{ "agsinvaders", "AGS Invaders" },
+	{ "agsjukebox", "AGS JukeBox" },
+	{ "agsmoduletester", "Ags Module Tester" },
+	{ "agsyahtzee2", "AGS Yahtzee 2" },
+	{ "agsyathzee", "AGS Yathzee" },
+	{ "agunshotinroom37", "A Gunshot in Room 37" },
+	{ "ahmetsagsfightgameremix", "Ahmet's AGS Fight Game Remix" },
+	{ "ainthegoffantabulousw", "A in the G of Fantabulous W" },
+	{ "airwaveifoughtthelawandthelawone", "~airwave~ - I Fought the Law, And the Law One" },
+	{ "akumayosagschess275", "Akumayo's AGS Chess 2.75" },
+	{ "alansaveschristmasandmostoftheworldtoo", "Alan saves Christmas (and most of the world too)" },
+	{ "albatheexplorer", "Alba the Explorer" },
+	{ "alienattack", "Alien Attack" },
+	{ "alienpuzzleinvasion", "Alien Puzzle Invasion" },
+	{ "alienrapeescape", "Alien Rape Escape" },
+	{ "alienthreat", "Alien Threat" },
+	{ "alientimezone", "Alien Time Zone" },
+	{ "aloneinthenight", "Alone in the Night" },
+	{ "alphadog", "Alpha Dog" },
+	{ "alphax", "Alpha X" },
+	{ "alquest1demo", "Al-Quest 1 Demo" },
+	{ "alysvsthephantomfelinefoe", "Alys vs. The Phantom Feline Foe" },
+	{ "amagicstone", "A magic stone" },
+	{ "amotospuf", "Amotos Puf" },
+	{ "amtag", "AMTAG" },
+	{ "anighttoremember", "A Night to Remember" },
+	{ "anna", "Anna" },
+	{ "annieandroidautomatedaffection", "Annie Android: Automated Affection" },
+	{ "anoblegame", "A Noble Game" },
+	{ "anthonysessay", "Anthony's Essay" },
+	{ "anticipatingmurder", "Anticipating Murder" },
+	{ "antiheroes", "Anti-Heroes" },
+	{ "apiratestale", "A pirates tale" },
+	{ "aplaceinthesun", "A Place In The Sun" },
+	{ "apprentice", "Apprentice" },
+	{ "apprentice2", "Apprentice 2" },
+	{ "apprenticedeluxe", "Apprentice Deluxe" },
+	{ "aprofoundjourney", "A Profound Journey" },
+	{ "archeos", "Archeos" },
+	{ "arewethereyet", "Are we there yet?" },
+	{ "armageddonmargaret", "Armageddon Margaret" },
+	{ "asecondface", "A SECOND FACE" },
+	{ "ashortnightmare", "A Short Nightmare" },
+	{ "asporia", "Asporia" },
+	{ "asterix", "Asterix" },
+	{ "astranded", "Astranded" },
+	{ "astron", "Astron" },
+	{ "aswinpathv01beta", "Aswin path v 0.1 beta" },
+	{ "ataleofbetrayal", "A Tale Of Betrayal" },
+	{ "ataleoftwokingdoms", "A Tale of Two Kingdoms" },
+	{ "atapi", "Atapi" },
+	{ "atotkjukebox", "ATOTK jukebox" },
+	{ "atreatandsometricks", "A Treat and Some Tricks" },
+	{ "aunaturel", "Au Naturel" },
+	{ "automation", "Automation" },
+	{ "averyspecialdog", "A very special dog" },
+	{ "awakener", "Awakener" },
+	{ "awakening", "Awakening" },
+	{ "awakeningofthesphinx", "Awakening of the Sphinx" },
+	{ "awalkindatomb", "A walk in da tomb" },
+	{ "awalkinthepark", "A Walk in the Park" },
+	{ "axmasevetale", "A Xmas Eve Tale" },
+	{ "backdoorman", "Back Door Man" },
+	{ "badluck", "BAD LUCK" },
+	{ "baldysadventure", "Baldy's Adventure" },
+	{ "baltazarthefamiliar", "Baltazar the Familiar" },
+	{ "bananamandemo", "Banana Man Demo" },
+	{ "bananaracer", "Banana Racer" },
+	{ "barndilemma", "Barn Dilemma" },
+	{ "barnrunner5part1", "Barn Runner 5 (Part 1)" },
+	{ "barnrunner5part2", "Barn Runner 5 (Part 2)" },
+	{ "barnrunnerholiday2", "Barn Runner: Holiday 2" },
+	{ "bartsquestfortv", "Bart's Quest For TV" },
+	{ "battlewarriors", "Battle Warriors" },
+	{ "beacon", "Beacon" },
+	{ "bear", "Bear" },
+	{ "beasts", "Beasts" },
+	{ "beautiesandbeasts", "Beauties and Beasts" },
+	{ "benjaminjordan", "Benjamin Jordan" },
+	{ "benjordancase1", "Ben Jordan Case 1" },
+	{ "bentheredanthat", "Ben There, Dan That!" },
+	{ "bernardsroom", "Bernards Room" },
+	{ "besieged", "besieged" },
+	{ "bestowersofeternity", "Bestowers of Eternity" },
+	{ "beyondreality", "Beyond Reality " },
+	{ "beyondterror", "BEYOND TERROR" },
+	{ "beyondthehorizon", "Beyond the horizon" },
+	{ "bigbadwolf3lilpiggies", "Big Bad Wolf & 3 Lil' Piggies" },
+	{ "bigglesonmars", "Biggles On Mars" },
+	{ "billyboysimportantwinelottery", "Billy Boy's Important Wine Lottery" },
+	{ "birdy", "Birdy" },
+	{ "bj7thecardinalsins", "BJ7: The Cardinal Sins" },
+	{ "bjcase2", "BJ Case 2" },
+	{ "bjcase3", "BJ Case 3" },
+	{ "bjcase4", "BJ Case 4" },
+	{ "bjcase5", "BJ Case 5" },
+	{ "bjcase6", "BJ Case 6" },
+	{ "blackmailinbrooklyn", "Blackmail In Brooklyn" },
+	{ "blackmorph", "Black Morph" },
+	{ "blackuddertodoubloonornottodoubloon", "Blackudder: To Doubloon or not to Doubloon" },
+	{ "bluemoon", "Blue Moon" },
+	{ "boardquest", "Board Quest" },
+	{ "bob", "BOB" },
+	{ "bobencavale", "Bob en cavale" },
+	{ "bobgoeshome", "Bob Goes Home" },
+	{ "bobgoeshomedeluxe", "Bob Goes Home Deluxe" },
+	{ "bobsquest1", "Bob's Quest 1" },
+	{ "bogsadventure", "Bog's Adventure" },
+	{ "boom", "Boom" },
+	{ "bowserquirkquest", "Bowser Quirk Quest" },
+	{ "box", "Box" },
+	{ "boyindahood", "Boy in da hood" },
+	{ "bradbradsonkeyquest", "Brad Bradson: Key Quest" },
+	{ "breakdownbyonedollar", "Breakdown by OneDollar" },
+	{ "bsg78unexpectedattherisingstar", "BSG78 - Unexpected at the Rising Star" },
+	{ "btd", "BTD" },
+	{ "bubsythebobcatinripvanbubsystarringbubsy", "Bubsy The Bobcat In Rip Van Bubsy Starring Bubsy" },
+	{ "buccaneer", "Buccaneer" },
+	{ "bullettrain", "Bullet Train" },
+	{ "bunawantsbeer", "Buna Wants Beer" },
+	{ "bunnyquest", "BunnyQuest" },
+	{ "burymeinthesand", "Bury Me in the Sand" },
+	{ "butcherstanys", "Butcher Stanys" },
+	{ "bytheswordconspiracy", "By the Sword: Conspiracy" },
+	{ "calebsdrunkenadventure", "CALEB'S DRUNKEN ADVENTURE" },
+	{ "calsoon2", "Calsoon 2" },
+	{ "capricorn", "CAPRICORN" },
+	{ "captaincringe", "Captain Cringe" },
+	{ "carrin", "Carrin" },
+	{ "carrotbobinzxspeccyworld", "Carrot Bob in ZX speccy world" },
+	{ "casablancathedayafter", "Casablanca The Day After" },
+	{ "castleoffire", "Castle of Fire" },
+	{ "catacombic", "Catacombic" },
+	{ "catapault", "CATapault" },
+	{ "cayannepepper", "CAYANNE PEPPER" },
+	{ "cedricandtherevolution", "Cedric and the Revolution" },
+	{ "celticchaos2fishermensfiends", "Celtic Chaos 2 - Fishermen's fiends" },
+	{ "chalksquest", "Chalk's Quest" },
+	{ "charliefoxtrot", "Charlie Foxtrot" },
+	{ "chatroom", "Chatroom" },
+	{ "cheerfulscience", "Cheerful Science" },
+	{ "chekken", "cheKKen" },
+	{ "chemin", "Chemin" },
+	{ "chezapa", "Chez Apa" },
+	{ "chickchaser", "Chick Chaser" },
+	{ "chicken", "Chicken" },
+	{ "chickenfraction", "Chicken Fraction" },
+	{ "chinesecheckers", "Chinese Checkers" },
+	{ "christmaspresent", "Christmas Present" },
+	{ "christmasquest", "Christmas Quest" },
+	{ "christmasquest2", "Christmas Quest 2" },
+	{ "christmasquest3santaslittlehelpdesk", "Christmas Quest 3: Santa's Little Helpdesk" },
+	{ "cirquedezale", "Cirque de Zale" },
+	{ "claire", "Claire" },
+	{ "classnotesv11", "Class Notes v1.1" },
+	{ "clex", "Clex" },
+	{ "clipl2heblinna", "Clip l2heb linna" },
+	{ "clubofevil", "Club of Evil" },
+	{ "coeldeckaflightgame", "Coel Decka Flight Game" },
+	{ "coinrush2", "Coin Rush 2" },
+	{ "colinsimpsonleavesemployme", "Colin Simpson Leaves Employme" },
+	{ "colourclash", "Colour Clash" },
+	{ "colourwise", "ColourWise" },
+	{ "colourwiseleveleditor", "ColourWise - Level Editor" },
+	{ "columbuslander", "Columbus Lander" },
+	{ "comradecitizenpart1", "Comrade Citizen (part 1)" },
+	{ "confessionsofacatburglar", "Confessions Of A Cat Burglar" },
+	{ "conspiracybelowzero", "Conspiracy: Below-Zero" },
+	{ "conspiracyofsongo", "Conspiracy of Songo" },
+	{ "constancethebarbarian", "Constance the Barbarian" },
+	{ "cosmos", "Cosmos" },
+	{ "cosmosquesti", "Cosmos Quest I" },
+	{ "cosmosquestii", "Cosmos Quest II" },
+	{ "cosmosquestiii", "Cosmos Quest III" },
+	{ "cougarsquestforfreedom", "Cougar's Quest for Freedom" },
+	{ "counterfeit", "Counterfeit" },
+	{ "cow", "cow" },
+	{ "coyote", "Coyote" },
+	{ "craftofevil", "Craft Of Evil" },
+	{ "crashevadedestroy", "Crash! Evade! Destroy!" },
+	{ "crave", "Crave" },
+	{ "crypt", "Crypt" },
+	{ "cryptic", "Cryptic" },
+	{ "csihunt1", "CSI Hunt 1" },
+	{ "cspb", "CSPB" },
+	{ "cuentosinconclusos", "Cuentos Inconclusos" },
+	{ "cyberjack", "cyberJACK" },
+	{ "daleks", "Daleks" },
+	{ "dalesfilmquest", "Dale's Film Quest" },
+	{ "damsel", "Damsel" },
+	{ "dancetilyoudrop", "Dance Til' You Drop!" },
+	{ "danewguys", "Da New Guys" },
+	{ "dangerouslandstournamentrpg", "DangerousLands Tournament+RPG" },
+	{ "dannydreadisoncall", "Danny Dread is On Call" },
+	{ "darkcave", "Dark Cave" },
+	{ "darkofnight", "Dark of Night" },
+	{ "darktimesmerrychristmas", "Dark Times (Merry Christmas)" },
+	{ "darum", "Darum" },
+	{ "davegeneric", "Dave Generic" },
+	{ "davidletterman", "David Letterman" },
+	{ "dawnswonderedatagesend", "Dawns Wondered: At Age's End" },
+	{ "ddddd", "DDDDD" },
+	{ "deadmeat", "Dead Meat" },
+	{ "deadofwinter", "Dead of Winter" },
+	{ "deathandtransfiguration", "Death and Transfiguration" },
+	{ "deathofanangel", "Death of an Angel" },
+	{ "deathsdoor", "Death's Door" },
+	{ "deathsquest", "Death's Quest" },
+	{ "deathworeendlessfeathersdisk1", "Death Wore Endless Feathers Disk 1" },
+	{ "demogame", "Demo Game" },
+	{ "demonday", "Demon Day" },
+	{ "derverschwundenehusky", "Der verschwundene Husky" },
+	{ "detectivegallo", "Detective Gallo" },
+	{ "detention", "Detention" },
+	{ "devochkaquest", "DevochkaQuest" },
+	{ "dgsearchofthebatterie", "DG: search of the batterie" },
+	{ "diamondsintheroughdemo", "Diamonds in the Rough DEMO" },
+	{ "diemaskennyarlathoteps", "Die Masken Nyarlathoteps" },
+	{ "disquiet", "Disquiet" },
+	{ "doctormaze", "DOCTOR MAZE" },
+	{ "doctormuttonchop", "Doctor Muttonchop" },
+	{ "donnaavengerofblood", "Donna: Avenger of Blood" },
+	{ "donniedarko", "Donnie Darko" },
+	{ "donspillacyconspiracyquest", "Don Spillacy Conspiracy Quest" },
+	{ "donthedweebdancedilemma", "Don the Dweeb: Dance Dilemma" },
+	{ "dontworryillbringthebeer", "Don't Worry, I'll Bring The Beer!" },
+	{ "dovadulasburn", "DoVaDuLa'S BuRn" },
+	{ "downfall", "Downfall" },
+	{ "dragonorb", "Dragon Orb" },
+	{ "dragontales", "DragonTales" },
+	{ "dreadmacfarlane", "Dread Mac Farlane" },
+	{ "dreadmacfarlane2", "Dread Mac Farlane 2" },
+	{ "dreamagine", "Dreamagine" },
+	{ "dreamer", "Dreamer" },
+	{ "dreamsequence", "dream sequence" },
+	{ "drlutztimetravelmachine", "Dr.Lutz Time Travel Machine" },
+	{ "dumbassdriversdemo", "Dumb.Ass Drivers! DEMO" },
+	{ "dungeonhands", "Dungeon Hands" },
+	{ "duskhunters", "Dusk Hunters" },
+	{ "dusttowater", "Dust to Water" },
+	{ "dutyandbeyond", "Duty and Beyond" },
+	{ "duzzquest", "DuzzQuest" },
+	{ "duzzquest2", "DuzzQuest2" },
+	{ "dysmaton", "Dysmaton" },
+	{ "earlbobbyislookingforaloodemo", "Earl Bobby is looking for a Loo - DEMO" },
+	{ "earlbobbyislookingforhisshoes", "Earl Bobby is looking for his Shoes" },
+	{ "earlbobbysballs", "Earl Bobby's Balls" },
+	{ "earlmansinthebreakout", "Earl Mansin: The Breakout" },
+	{ "earthlingpriorities", "Earthling Priorities" },
+	{ "easterislanddefender", "Easter Island Defender" },
+	{ "easy3d", "Easy3D" },
+	{ "edmund", "Edmund" },
+	{ "educatingadventuresofgirlandrabbit", "Educating Adventures of Girl and Rabbit" },
+	{ "eerieblue", "Eerie Blue" },
+	{ "electrctgui", "electrctGUI" },
+	{ "elevator", "Elevator" },
+	{ "elfer10", "Elfer 1.0" },
+	{ "elfmotorsinc", "Elf Motors Inc." },
+	{ "elforescuecraby", "ELFO: RESCUE CRABY" },
+	{ "eliminationbyimprovisation", "Elimination by Improvisation" },
+	{ "emeraldeyes", "Emerald Eyes" },
+	{ "emilyenough", "Emily Enough" },
+	{ "emmarodedemo", "Emma Ro?de (DEMO)" },
+	{ "emptymindblankfate", "Empty Mind - Blank Fate" },
+	{ "enoworld", "Enoworld" },
+	{ "enterthestory", "Enter The Story" },
+	{ "equilibrium", "Equilibrium" },
+	{ "erictheanteater", "Eric the Anteater" },
+	{ "erkadventuresinstoneagerealestate", "Erk: Adventures in Stoneage Real Estate" },
+	{ "errand", "Errand" },
+	{ "escape", "Escape" },
+	{ "escapefromasmallroom", "Escape From a Small Room" },
+	{ "escapefromevergreenforest", "Escape From Evergreen Forest" },
+	{ "escapefromlurrilous", "Escape from Lurrilous" },
+	{ "escapefromthesalemmoons", "Escape From The Salem Moons" },
+	{ "escapefromthezombiecity", "Escape From The Zombie City" },
+	{ "escapetheship", "Escape the ship" },
+	{ "esper", "ESPER" },
+	{ "eternallyus", "Eternally Us" },
+	{ "eventtimer", "Event Timer" },
+	{ "exclamation", "!" },
+	{ "exit", "Exit" },
+	{ "fadingshades", "Fading Shades" },
+	{ "fakethemoonlanding", "Fake the moon landing" },
+	{ "fallenangel", "Fallen Angel" },
+	{ "fallensoldier", "fallen soldier" },
+	{ "fanbots", "Fanbots" },
+	{ "farnowhere", "FAR NOWHERE" },
+	{ "fasmo", "Fasmo!" },
+	{ "fasmogoeswest", "Fasmo Goes West" },
+	{ "fbiquest", "FBI Quest" },
+	{ "fearaphobia", "FEARAPHOBIA" },
+	{ "featherweight", "Featherweight" },
+	{ "femspray", "FemSpray" },
+	{ "fengshuiandtheartoftvreception", "Feng Shui And The Art Of TV Reception" },
+	{ "feuersturmkapitel1", "Feuersturm - Kapitel 1" },
+	{ "feuersturmkapitel2", "Feuersturm - Kapitel 2" },
+	{ "feuersturmkapitel3", "Feuersturm - Kapitel 3" },
+	{ "fifa2003pro", "Fifa2003Pro" },
+	{ "fight", "Fight" },
+	{ "fightgame", "Fight Game" },
+	{ "fireflystory3d", "Firefly story 3D" },
+	{ "flamebarrel", "Flame Barrel" },
+	{ "flashbax", "Flashbax" },
+	{ "flowergirl", "flowergirl" },
+	{ "fluxworld", "Flux World" },
+	{ "forcemajeureiithezone", "Force majeure II: The Zone" },
+	{ "forfrogssakegetthefrogout", "FOR FROGS SAKE!  GET THE FROG OUT!" },
+	{ "forgettendeath", "Forgetten Death " },
+	{ "fortressofwonders", "Fortress of Wonders" },
+	{ "fountainofunicorns", "Fountain of Unicorns" },
+	{ "fountainofyouthdemo", "Fountain of Youth Demo" },
+	{ "framed", "Framed!" },
+	{ "frankenpooper", "Frankenpooper" },
+	{ "frankthefarmhandpart1", "Frank the Farmhand Part 1" },
+	{ "frankthefarmhandpart2", "Frank the Farmhand Part 2" },
+	{ "franticfrankoabergzwerggoneberserk", "Frantic Franko: A Bergzwerg Gone Berserk" },
+	{ "frasiercraneseattlerampage", "Frasier Crane:  Seattle Rampage" },
+	{ "fredandbarneymeetthefuture", "Fred and Barney meet the future" },
+	{ "fribbeldib", "Fribbeldib" },
+	{ "frogisland", "Frog Island" },
+	{ "fsis1000000quest", "FSi's $1000000 Quest!" },
+	{ "fsisalienation", "FSi's Alienation!" },
+	{ "fsiscotmattcehotsvd", "FSi's CotMATtCEHotSVD" },
+	{ "fsismhcfhr", "FSi's MHCFHR!" },
+	{ "fsispowercowfromuranus", "FSi's POWERCOW FROM URANUS!" },
+	{ "fulkinthedreamthaus", "fulk in the dreamt haus" },
+	{ "funsunmishaps", "Fun, Sun & Mishaps" },
+	{ "funwithnumbers", "Fun With Numbers" },
+	{ "gabyking", "GabyKing" },
+	{ "gamesgalore", "GAMES GALORE" },
+	{ "gassesuittollis3demo", "Gasse Suit Tollis 3 DEMO" },
+	{ "gatewayremake", "Gateway Remake" },
+	{ "genbu", "Genbu" },
+	{ "geometricshapes1circleboy", "Geometric Shapes 1: Circleboy" },
+	{ "gesundheitdemo", "Gesundheit! Demo" },
+	{ "getawayfrompluto", "Get away from PLUTO" },
+	{ "getfood", "Get food" },
+	{ "ghostdream", "Ghostdream" },
+	{ "ghosting", "Ghosting" },
+	{ "ghostvoyage", "Ghost Voyage" },
+	{ "glitchquest", "Glitch Quest" },
+	{ "glitchquestnofun", "Glitch Quest (nofun)" },
+	{ "gnomeshomebrewingadventure", "Gnome's Homebrewing Adventure" },
+	{ "gnrblexags", "Gnrblex_AGS" },
+	{ "goneboatfishin", "Gone Boat Fishin'" },
+	{ "goodmorningmrgingerbread", "Good Morning, Mr. Gingerbread!" },
+	{ "goodsantabadsanta", "GoodSanta, BadSanta" },
+	{ "gotalight", "Got a Light?" },
+	{ "gpslostadventure", "G P's Lost Adventure" },
+	{ "graveyard", "Graveyard" },
+	{ "gremlin", "Gremlin" },
+	{ "grizzlygooseofgosse", "Grizzly Goose of Gosse" },
+	{ "grr", "Grr!" },
+	{ "guardiansofgold", "Guardians of Gold" },
+	{ "guyslug", "Guy Slug" },
+	{ "guyverquestiicronos", "Guyver Quest II: Cronos" },
+	{ "guyverquestishoadventure", "Guyver Quest I: Sho Adventure" },
+	{ "gville1", "G-ville 1" },
+	{ "hack", "Hack" },
+	{ "halloween", "Halloween" },
+	{ "halloweenhorror", "Halloween Horror" },
+	{ "hallwayofadventures", "Hallway of Adventures" },
+	{ "hangon", "Hang On" },
+	{ "hansenhotel", "Hansen Hotel" },
+	{ "happyduckieadventure", "Happy Duckie Adventure" },
+	{ "hardspaceconquestofthegayliks", "Hard Space: Conquest of the Gayliks" },
+	{ "harrys21stbirthday", "Harry's 21st Birthday" },
+	{ "haventhesmallworld", "Haven - The Small World" },
+	{ "heartlanddeluxever11", "Heartland Deluxe Ver 1.1" },
+	{ "heartlandver12", "Heartland (ver 1.2)" },
+	{ "heavymetalnannulfthestrangestage", "Heavy Metal Nannulf: The Strange Stage" },
+	{ "heed", "Heed" },
+	{ "helpthegame", "HELP! the game" },
+	{ "henkstroemlostincellar", "Henk Stroem Lost In Cellar" },
+	{ "henman", "Hen Man" },
+	{ "hesgonehistorical", "He's Gone Historical" },
+	{ "hhgtgtowelday", "HHGTG: Towel Day" },
+	{ "hiddenplains", "Hidden Plains" },
+	{ "hiddentreasureryansfortune", "Hidden Treasure: Ryan's Fortune" },
+	{ "hide", "Hide" },
+	{ "hiliaderoleagainsthell", "Hilia Derole against Hell" },
+	{ "him", "Him" },
+	{ "hitchhikersguidetothegalaxyremake", "Hitchhiker's Guide to the Galaxy Remake" },
+	{ "hitthefreak", "Hit the Freak" },
+	{ "hlobb", "HLoBB" },
+	{ "hood", "Hood" },
+	{ "hope", "Hope" },
+	{ "horseparkdeluxe", "Horse Park DeLuxe" },
+	{ "hotel", "Hotel" },
+	{ "hotelhijinks", "Hotel Hijinks" },
+	{ "houseofhorror", "House of Horror" },
+	{ "howmany", "How many..." },
+	{ "howtheyfoundsilence", "How They Found Silence" },
+	{ "huongjiaoping", "Huong Jiao Ping" },
+	{ "huxzadventure", "Huxz Adventure" },
+	{ "hydeandseek", "Hyde and Seek" },
+	{ "iaman00b11omgwtflol", "i am a n00b!!1!!1!OMG WTF LOL" },
+	{ "iamjason", "IAMJASON" },
+	{ "iforgot", "I forgot..." },
+	{ "igs", "IGS" },
+	{ "iiispy", "IIISpy" },
+	{ "illuminationdiminishing", "IlluminationDiminishing" },
+	{ "imnotcrazyrightthecell", "I'm not crazy, right? - The Cell" },
+	{ "imnotcrazyrightthewell", "I'm not crazy, right? - The Well" },
+	{ "indianajonescomingofage", "Indiana Jones - Coming of Age" },
+	{ "indycositalianver", "IndyCoS - Italian ver" },
+	{ "infectionepii", "Infection_Ep_II" },
+	{ "infectionitheship", "Infection I - The ship" },
+	{ "inferno", "Inferno" },
+	{ "infinitemonkeys", "Infinite Monkeys" },
+	{ "insidemonkeyisland", "Inside Monkey Island" },
+	{ "insidemonkeyisland2cap", "Inside Monkey Island 2? cap." },
+	{ "inspectorgismoe", "Inspector Gismoe" },
+	{ "integerbattleship", "Integer Battleship" },
+	{ "intergalacticspacepancake", "Intergalactic Space Pancake!" },
+	{ "intothelight", "Into The Light" },
+	{ "invincibleisland", "Invincible Island" },
+	{ "isnkill", "ISN: Kill!" },
+	{ "isos", "ISOS" },
+	{ "itsabugslife", "It's a Bugs Life" },
+	{ "iwalkedapath", "I walked a path" },
+	{ "iwantout", "I want out!" },
+	{ "iwwhiiwwhitomirotpgthegame", "IWWHIIWWHITOMIROTPG: The Game!" },
+	{ "jacob", "Jacob" },
+	{ "jacquelinewhitecurseofthemummies", "Jacqueline White - Curse of the Mummies" },
+	{ "jamesbond", "James Bond" },
+	{ "jamesinneverland", "James in Neverland" },
+	{ "jamesperis", "James Peris" },
+	{ "jamesperis2demo", "James Peris 2 Demo" },
+	{ "javelincatch", "Javelin Catch" },
+	{ "jimmsquestiii", "Jimm's Quest III" },
+	{ "jimmysday", "Jimmy's Day" },
+	{ "jimmythetroublemaker", "Jimmy The Troublemaker" },
+	{ "joeshorriblehell", "Joe's Horrible Hell" },
+	{ "joesmiserablelife", "Joe's Miserable Life" },
+	{ "johnharrissafrakincse", "John Harris ?s a f?ra? kincse" },
+	{ "johnjebediahgunelisoladisepheret", "John Jebediah Gun e l'Isola di Sepheret" },
+	{ "johnnyrocket", "Johnny_Rocket" },
+	{ "johnsinclairvoodooinlondon", "John Sinclair - Voodoo in London" },
+	{ "jonnysmallvalley", "Jonny Smallvalley" },
+	{ "jorry", "Jorry" },
+	{ "juliusdangerous2", "Julius Dangerous 2" },
+	{ "juliusdangerousandthespaceinvaders", "Julius Dangerous  .. and the space invaders" },
+	{ "justanotherpointnclickadventure", "Just Another Point n Click Adventure" },
+	{ "justignorethem", "Just Ignore Them" },
+	{ "kanjigakusei", "Kanji Gakusei" },
+	{ "kartquestv053", "Kart-Quest - v0.53" },
+	{ "keptoshi", "Keptosh I" },
+	{ "keys", "Keys" },
+	{ "killereye", "Killer Eye" },
+	{ "killjoseda", "Kill Joseda" },
+	{ "killthelights", "Kill The Lights" },
+	{ "kingdomlegends", "Kingdom Legends" },
+	{ "kingsquestiii", "Kings Quest III" },
+	{ "kinkyislanddemo", "Kinky Island DEMO" },
+	{ "knightquestforgoldenring", "Knight Quest for Golden Ring" },
+	{ "knightsquestiii", "Knight's Quest III" },
+	{ "knightsquestiv", "Knight's Quest IV" },
+	{ "koddurova", "??? ??????" },
+	{ "koffeekrisis", "Koffee Krisis" },
+	{ "koscheitheimmortal", "Koschei The Immortal" },
+	{ "kristmaskrisis", "Kristmas Krisis" },
+	{ "ktx1", "KTX-1" },
+	{ "kumastory", "Kuma Story" },
+	{ "labor", "Labor" },
+	{ "labratescape", "Lab Rat Escape" },
+	{ "labyrinth", "Labyrinth" },
+	{ "lacicuta1", "La Cicuta1" },
+	{ "lacroixpan", "La Croix Pan" },
+	{ "laffaireaspirox", "L'Affaire Aspirox" },
+	{ "lagrancastanya", "La Gran Castanya" },
+	{ "lallaveyfabianshones", "LA LLAVE Y FABIAN SHONES" },
+	{ "laodiseadelfracasoii", "La Odisea del Fracaso II" },
+	{ "laportenoire", "La porte noire" },
+	{ "lastnfurious", "Last'n'Furious" },
+	{ "laundryday", "Laundry Day" },
+	{ "lavablava", "Lava Blava" },
+	{ "lazaruswantspants", "Lazarus Wants Pants" },
+	{ "lazytownthenewkiddemo", "LazyTown: The New Kid (demo)" },
+	{ "lbstoryofcedrickdusce", "LB: Story of Cedrick DUSCE!" },
+	{ "legendofrovendale", "Legend of Rovendale" },
+	{ "legendofseththebard", "Legend of Seth the Bard" },
+	{ "legendsofmardaram", "Legends of Mardaram" },
+	{ "leisuresuitlarry2", "Leisure Suit Larry 2" },
+	{ "leisuresuitlarrylil", "Leisure Suit Larry: L i L" },
+	{ "lesmiserables", "Les Miserables" },
+	{ "lessurvivants", "Les Survivants" },
+	{ "lichdomwheresdidiputthat", "Lichdom - Where's did I put that..." },
+	{ "life", "Life" },
+	{ "lifeboatstoryofcedrick", "Lifeboat: Story of Cedrick" },
+	{ "lifeofdduck", "Life of D. Duck" },
+	{ "lifeofdduckii", "Life of D. Duck II" },
+	{ "liftreasureofthetanones", "Lif Treasure of the Tanones" },
+	{ "lightcycles", "Light Cycles" },
+	{ "lightningmaster", "Lightning Master" },
+	{ "likeafox", "Like a Fox!" },
+	{ "limbo", "Limbo" },
+	{ "limeylizardwastewizard", "Limey Lizard: Waste Wizard" },
+	{ "litnunforgettablememories", "LitN  Unforgettable Memories" },
+	{ "littlegirlinunderland", "Little Girl in Underland" },
+	{ "livingnightmaredeluxe", "Living Nightmare Deluxe" },
+	{ "livingnightmareendlessdream", "Living Nightmare: Endless Dream" },
+	{ "livingnightmarefreedom", "Living Nightmare: Freedom" },
+	{ "lockedout", "Locked Out" },
+	{ "loftusandtheskycap", "Loftus and the Sky Cap" },
+	{ "lonecase", "LoneCase" },
+	{ "lonecase2", "Lone Case 2" },
+	{ "lonecase3showdown", "LoneCase3:Showdown" },
+	{ "lonelynight", "Lonely night" },
+	{ "longexpectedfriday", "Long expected Friday" },
+	{ "lonkeyisland", "Lonkey Island" },
+	{ "loomiireturnoftheswans", "Loom II Return Of The Swans" },
+	{ "losjovenesdelaguerra", "Los Jovenes De La Guerra" },
+	{ "lostanswers", "Lost Answers" },
+	{ "lostinparadise", "Lost In Paradise" },
+	{ "lostinthenightmare", "Lost In The Nightmare" },
+	{ "lostinthewoods", "Lost In The Woods" },
+	{ "lucidlucy", "LUCID LUCY" },
+	{ "lucylavender", "Lucy Lavender" },
+	{ "lukesexistentialnightmare", "Luke's Existential Nightmare" },
+	{ "lunarlanderprototype", "Lunar Lander Prototype" },
+	{ "lydiaandthemysteryofnellrenomanor", "Lydia and the Mystery of Nellreno Manor" },
+	{ "maggieandmax", "Maggie and Max" },
+	{ "magic8ball", "Magic-8-Ball" },
+	{ "magicalwhatevergirlrocksoutinthestoneage", "Magical Whatever Girl Rocks Out In The Stone Age" },
+	{ "magicballoffortune", "Magic Ball of Fortune" },
+	{ "magnumpm", "Magnum, P.M" },
+	{ "magsgame", "Mags Game" },
+	{ "magsic", "Magsic" },
+	{ "magsicii", "Magsic II" },
+	{ "magsjan", "MAGS-Jan" },
+	{ "magsjune2017", "MAGS june 2017" },
+	{ "magssep2007", "MAGS Sep 2007" },
+	{ "manboy", "Man Boy" },
+	{ "maniacmansiondeluxe", "Maniac Mansion Deluxe" },
+	{ "maniacmansionmania", "Maniac Mansion Mania" },
+	{ "maniacmansionmania02", "Maniac Mansion Mania 02" },
+	{ "mardsrevengebytk", "Mard's Revenge by TK" },
+	{ "martyausdemall", "Marty aus dem All" },
+	{ "mastersofsound", "MASTERS OF SOUND" },
+	{ "matttothefuture", "Matt to the Future" },
+	{ "medicaltheoriesofdrkur", "Medical Theories of Dr Kur" },
+	{ "mego2008silvesteredition", "Me Go 2008: Silvester Edition" },
+	{ "megoaway", "Me Go... Away!" },
+	{ "megocannibaljungle", "Me Go Cannibal Jungle!" },
+	{ "megostore", "Me Go Store!" },
+	{ "melrinthediscipleordeal", "Melrin: The disciple ordeal" },
+	{ "melrinthedragonmenace", "Melrin: The Dragon Menace" },
+	{ "melrinthependantquest", "Melrin: The Pendant Quest" },
+	{ "meltdrake3chapter1", "Melt & Drake 3 Chapter 1" },
+	{ "memoriesfade", "Memories Fade" },
+	{ "meninhats", "Men In Hats" },
+	{ "merrychristmas", "Merry Christmas" },
+	{ "messedupmothergoosedeluxemyassenhanced", "Messed-Up Mother Goose - DELUXE MY ASS: ENHANCED" },
+	{ "meta", "META" },
+	{ "meteorfamily20", "Meteor Family 2.0" },
+	{ "meteorheadrecycled", "METEORHEAD RECYCLED" },
+	{ "mi5thereturnoflechuck", "MI5 : The Return of LeChuck" },
+	{ "mibaddaytobedead", "MI:Bad Day to be Dead" },
+	{ "micarnivalofthedamned", "MI:Carnival of the Damned" },
+	{ "mickeymauserpart1", "Mickey Mauser: Part 1" },
+	{ "midastouch", "midastouch" },
+	{ "mikelechey", "Mike Lechey" },
+	{ "mikesroom2", "Mikes Room2" },
+	{ "milkshake", "Milkshake" },
+	{ "mindboggler", "MINDBOGGLER" },
+	{ "mindseye", "Mind's Eye" },
+	{ "minigame3", "Mini Game 3" },
+	{ "minigame4", "Mini Game 4" },
+	{ "missingsincemidnight", "Missing since Midnight" },
+	{ "mistdelaescueladearte", "Mist. de la Escuela de Arte" },
+	{ "mixertest", "Mixer Test" },
+	{ "mmm15ortmaschine", "MMM 15: Ortmaschine" },
+	{ "mmm4mimikryderemotionen", "MMM 4 - Mimikry der Emotionen" },
+	{ "mmmderklausschlgtzurck", "MMM-Der Klaus schl?gt zur?ck" },
+	{ "mmmepisode8", "MMM - Episode 8" },
+	{ "mmmradioaktiv", "MMM - Radioaktiv" },
+	{ "moncul", "Mon Cul!" },
+	{ "monkeystothemoon", "Monkeys to the Moon" },
+	{ "monkeywrench", "monkeywrench" },
+	{ "monsterfromthehountedhill", "Monster from the hounted hill" },
+	{ "moonlightmoggy", "Moonlight Moggy" },
+	{ "moose", "Moose" },
+	{ "moose2", "Moose 2" },
+	{ "mordimlaufrad", "Mord im Laufrad" },
+	{ "mordy2", "Mordy2" },
+	{ "mothersday", "Mothers Day" },
+	{ "motlpaa", "MOTLPAA" },
+	{ "mourirenmer", "Mourir en mer" },
+	{ "mrbee", "Mr Bee" },
+	{ "mrdangerscontest", "Mr. Danger's Contest" },
+	{ "murderinthemansion", "Murder in the Mansion" },
+	{ "murderofadrianelkwood", "Murder of Adrian Elkwood" },
+	{ "murphyssalvagejustmyluck", "Murphy's Salvage: Just My Luck" },
+	{ "murranchronicles1", "Murran Chronicles 1" },
+	{ "murranchronicles2", "Murran Chronicles 2" },
+	{ "mysterioushouse", "Mysterious house" },
+	{ "mysticseer", "Mystic Seer" },
+	{ "mythicalgambitflawlessfatality", "Mythical Gambit: Flawless Fatality" },
+	{ "nanobots", "Nanobots" },
+	{ "necroquest", "Necroquest" },
+	{ "nedysadventure", "Nedy's adventure" },
+	{ "nekusnewtrip", "Neku's new trip" },
+	{ "newgame", "New Game" },
+	{ "nellycootalotv15", "Nelly Cootalot v1.5" },
+	{ "neofeud", "Neofeud" },
+	{ "nesquest", "NES Quest" },
+	{ "news", "N.E.W.S." },
+	{ "nickitandrun", "Nick it and Run!!!" },
+	{ "nightoftheravingfeminist", "Night of the Raving Feminist " },
+	{ "nightwork", "Nightwork" },
+	{ "noactionjackson", "No-Action Jackson" },
+	{ "noahsquest", "Noah's Quest" },
+	{ "nobodycares", "Nobody Cares" },
+	{ "noiamspartacus", "No, I Am Spartacus!" },
+	{ "noisymountain", "Noisy Mountain" },
+	{ "nomonkeysbanana", "No Monkey's Banana" },
+	{ "norbisquest", "Norbi's quest" },
+	{ "norbisquest15", "Norbi's quest 1,5" },
+	{ "norbisquest2", "Norbi's quest 2" },
+	{ "norbiwinterspecial", "Norbi winter special" },
+	{ "normancooks", "Norman Cooks" },
+	{ "norserunereader", "Norse Rune Reader" },
+	{ "noughtscrosses", "Noughts & Crosses" },
+	{ "oceanspiritdennisscourgeoftheunderworld", "Oceanspirit Dennis: Scourge of the Underworld" },
+	{ "odottamaton", "Odot Tamat On" },
+	{ "omnipotenttarot", "Omnipotent Tarot" },
+	{ "onceuponacrime13b", "Once Upon A Crime 1.3B" },
+	{ "onceuponatime", "Once Upon A Time" },
+	{ "one", "One" },
+	{ "oneofakindadivinecomedyofmistakes", "One Of A Kind: A Divine Comedy of Mistakes" },
+	{ "onespytoomany", "One spy too many" },
+	{ "oneweekoneroom", "One Week One Room" },
+	{ "onleavingthebuilding", "On Leaving The Building" },
+	{ "onlythegooddieyoungenglishversion", "Only The Good Die Young - english version" },
+	{ "openquest", "OpenQuest!" },
+	{ "operationnovi", "Operation Novi" },
+	{ "operationsavebluecup", "Operation Save Blue Cup" },
+	{ "orangeman", "Orange man" },
+	{ "orowgame", "ORow Game" },
+	{ "osdarayofhope", "OSD: A Ray of Hope" },
+	{ "osdocd", "OSD:OCD" },
+	{ "osdthelostworldep2", "OSD.The lost world ep 2 " },
+	{ "osher", "Osher" },
+	{ "otakurivals", "Otaku Rivals " },
+	{ "otherworlds", "Other Worlds" },
+	{ "otisbuildsafire", "Otis Builds a Fire" },
+	{ "ouja", "Ouja" },
+	{ "outbreakbyabhijitkamat", "Outbreak by Abhijit Kamat" },
+	{ "outofgas", "Out of Gas" },
+	{ "overtheedge", "Over the Edge" },
+	{ "owlsquest", "Owl's Quest" },
+	{ "palettequest2", "Palette Quest 2" },
+	{ "pandainspace", "Panda In Space" },
+	{ "pandor", "Pandor" },
+	{ "paradiselost", "Paradise Lost" },
+	{ "parameciumcomplex", "Paramecium Complex" },
+	{ "paranormalwarriorwithin", "Paranormal Warrior Within" },
+	{ "party", "Party" },
+	{ "patchwork", "Patchwork" },
+	{ "paulaimwunderland", "Paula im Wunderland" },
+	{ "paulmooseinspaceworld", "Paul Moose In Space World" },
+	{ "paulquest", "Paul Quest" },
+	{ "pennistheultimateinpong", "Pennis: The Ultimate in Pong!" },
+	{ "perilsofpoom", "PERILS OF POOM" },
+	{ "pesterquest", "Pester Quest" },
+	{ "petalrose", "Petal Rose" },
+	{ "pharmacistjones", "Pharmacist Jones" },
+	{ "pickpocketrpg", "Pickpocket RPG" },
+	{ "pilotlight", "Pilot Light" },
+	{ "pimpinonparakuss", "Pimpin On Parakuss" },
+	{ "piratefry2", "Pirate Fry 2" },
+	{ "piratefry3", "Pirate Fry 3" },
+	{ "piratess", "Piratess" },
+	{ "pixelhunt", "Pixel Hunt" },
+	{ "pixia", "Pixia" },
+	{ "pixxxelhuntertheepic", "Pixxxelhunter The Epic" },
+	{ "plan10frommypants", "Plan10 from MY PANTS!!!" },
+	{ "planetxmas", "Planet Xmas" },
+	{ "platformerius", "Platformerius" },
+	{ "platformhorde", "Platform Horde" },
+	{ "pleurghburgdarkages", "Pleurghburg: Dark Ages" },
+	{ "plumberboy", "Plumberboy" },
+	{ "pm-cute", "PM Cute" },
+	{ "pmuvchvt", "PMUVCHVT" },
+	{ "pmxi", "PMXI" },
+	{ "pocketfluffyay", "PocketFluff_yay!" },
+	{ "politicallyyours", "Politically Yours" },
+	{ "pong", "Pong" },
+	{ "postmansquest", "Postman's Quest" },
+	{ "powernap", "Power Nap" },
+	{ "powerunlimited", "Power Unlimited" },
+	{ "pqtadventure", "PQTADVENTURE" },
+	{ "practicescript", "Practice Script" },
+	{ "predatorspreyforplants", "Predators Prey For Plants" },
+	{ "princessandallthekingdom", "Princess and all the kingdom" },
+	{ "princessmarianix", "Princess Marian IX" },
+	{ "princessmariansnowfight", "Princess Marian Snow Fight!" },
+	{ "princessmarianspigeonpinger", "Princess Marian's Pigeon Pinger" },
+	{ "princessmarianxmagichat", "Princess Marian X: Magic Hat" },
+	{ "principlesofevil", "Principles of Evil" },
+	{ "principlesofevilii", "Principles of Evil II" },
+	{ "prodigal", "Prodigal" },
+	{ "profneely", "Prof. Neely" },
+	{ "projectevilspyii", "Project Evilspy II" },
+	{ "proofoffiction", "Proof of Fiction" },
+	{ "prototypical", "Prototypical" },
+	{ "proxecto", "Proxecto" },
+	{ "psychopomp", "Psychopomp" },
+	{ "pubmasterquest2", "pub master quest.2" },
+	{ "pubmastersquest", "Pub Masters Quest" },
+	{ "puddypenguin", "Puddy Penguin" },
+	{ "pupupupulaisenseikkailut", "Pupu Pupulaisen Seikkailut" },
+	{ "purgatorio01", "Purgatorio 0.1" },
+	{ "purityofthesurf", "Purity of the Surf" },
+	{ "puzzlebotsdemo", "Puzzle Bots Demo" },
+	{ "pxenophobe", "PXenophobe" },
+	{ "quantumnauts", "QUANTUMNAUTS" },
+	{ "questfighter", "Quest Fighter" },
+	{ "questfighterii", "Quest Fighter II" },
+	{ "questforcinema", "QuestForCinema" },
+	{ "questforglory2vga", "Quest For Glory 2 VGA" },
+	{ "questforgloryii", "Quest for Glory II" },
+	{ "questforjesus", "Quest for Jesus" },
+	{ "questforpalette", "Quest for Palette" },
+	{ "questforthebluecup", "Quest for the Blue Cup" },
+	{ "questforyeti", "Quest for Yeti" },
+	{ "questforyrolg", "Quest for Yrolg" },
+	{ "quieromorir", "Quiero Morir" },
+	{ "quimbyquestanewdope", "Quimby Quest: A New Dope" },
+	{ "race", "R.ACE" },
+	{ "rackham", "Rackham" },
+	{ "ralphtheraven", "Ralph the Raven" },
+	{ "ramsesporterandtherelayforlove", "Ramses Porter and the Relay for Love" },
+	{ "rango", "Rango" },
+	{ "ratchannel", "Rat Channel" },
+	{ "rayandtheguitar", "Ray and the Guitar" },
+	{ "raybexter", "Ray Bexter" },
+	{ "razorsinthenight", "Razors in the Night" },
+	{ "reagentorange", "Re-Agent Orange" },
+	{ "realityonthenorm", "Reality-on-the-Norm" },
+	{ "recess", "Recess" },
+	{ "recess2", "Recess 2" },
+	{ "reddwarf", "Red Dwarf" },
+	{ "redflagg", "Red Flagg" },
+	{ "redpantsmeetsrobinsonclauseau", "Redpants meets Robinson Clauseau" },
+	{ "redpantstheprincessandthebeanstalk", "Redpants: The Princess and the Beanstalk" },
+	{ "reefriversquestforekoban", "Reef Rivers: Quest for Ekoban" },
+	{ "returntocivilization", "Return To Civilization" },
+	{ "revelation10", "Revelation 1.0" },
+	{ "rickyquest", "Ricky Quest" },
+	{ "righteouscity", "Righteous City" },
+	{ "roadofdestiny", "Road of Destiny" },
+	{ "roadracer", "Road Racer" },
+	{ "roastmothergoose", "Roast Mother Goose" },
+	{ "robbertredfordsavestheday", "Robbert Redford saves the day" },
+	{ "robbingtheprincess", "Robbing The Princess" },
+	{ "robertredford3", "Robert Redford 3" },
+	{ "robertredfordsavestheday", "Robert Redford saves the day" },
+	{ "robmassacreofchainsawness", "Rob: Massacre of Chainsawness" },
+	{ "robotragedy", "Robotragedy" },
+	{ "robotragedy2", "Robotragedy 2" },
+	{ "roccioquest", "Roccio Quest" },
+	{ "rockabillykid", "Rockabilly Kid" },
+	{ "rockburgerstreehouses", "Rock Burgers & Tree Houses" },
+	{ "rockrockrock", "Rock Rock Rock" },
+	{ "rockyroams", "Rocky roams" },
+	{ "rodequest2", "Rode Quest 2" },
+	{ "ronbeforethelegacy", "Ron- before the legacy" },
+	{ "ronsixteen", "RON: Sixteen" },
+	{ "rontimeoutintro", "RON: Time Out Intro" },
+	{ "roomoffear", "Room of fear " },
+	{ "rootofallevil", "Root of All Evil" },
+	{ "rosauradocelestialrescuefromdespair", "Rosaura Docelestial: Rescue from Despair" },
+	{ "rotnbelusebiusarrival", "RotN:Belusebius Arrival" },
+	{ "rowengoestowork", "Rowen Goes To Work" },
+	{ "rs15", "rs15" },
+	{ "rudeawakening", "Rude Awakening" },
+	{ "ryansdayout", "Ryan's Day Out" },
+	{ "saddsonissein", "Saddson Issein" },
+	{ "salazarsevilplan", "Salazar's evil plan" },
+	{ "sammysquest", "Sammy's Quest" },
+	{ "santaclausdown", "Santa Claus Down" },
+	{ "santassidekick", "Santas Sidekick" },
+	{ "satanquest", "Satan Quest" },
+	{ "satchsquest", "Satch's Quest" },
+	{ "saturdayschool", "Saturday School" },
+	{ "saw", "Saw" },
+	{ "saw2", "Saw 2" },
+	{ "scaredstiffa", "Scared Stiff a" },
+	{ "scarymaze", "Scary Maze" },
+	{ "schwarzweissrot", "SchwarzWeissRot" },
+	{ "scnider", "Scnider" },
+	{ "scytheisland", "Scythe Island" },
+	{ "searchforsanitydemo", "Search for Sanity Demo" },
+	{ "seashells", "Seashells" },
+	{ "seasongreetings2002", "Season Greetings 2002" },
+	{ "secretquestremake", "Secret Quest Remake" },
+	{ "secrets", "Secrets" },
+	{ "seega16engl5", "seega16_engl_5" },
+	{ "seegame15", "seegame15" },
+	{ "sevendoors", "Seven  Doors" },
+	{ "sga", "SGA" },
+	{ "shadesofgreye", "Shades of Greye" },
+	{ "shadowsoftheempiretd", "Shadows of the Empire - TD" },
+	{ "shailadusithlenqute", "Shai-la du Sith : l'Enqu?te" },
+	{ "shailaofthesith", "Shai-la of the Sith" },
+	{ "shem", "Shem" },
+	{ "sherlock", "Sherlock" },
+	{ "shiftersboxoutsidein", "Shifter's Box - Outside In" },
+	{ "shivahdemo", "Shivahdemo" },
+	{ "shoot", "Shoot" },
+	{ "shootmyvalentine", "Shoot my Valentine" },
+	{ "shortcut", "ShortCut" },
+	{ "shrivel", "Shrivel" },
+	{ "shunday", "Shunday" },
+	{ "sierraquest1", "Sierra Quest 1" },
+	{ "silentknightii", "Silent Knight II" },
+	{ "silentknightv11", "Silent Knight v.1.1" },
+	{ "simonthesorcerer3demo20", "Simon the Sorcerer 3 Demo 2.0" },
+	{ "skippysavestheday", "Skippy Saves The Day" },
+	{ "slaythedragon", "Slay the Dragon" },
+	{ "sleepyisland", "Sleepy Island" },
+	{ "slimequestforpizza", "Slime-Quest for Pizza" },
+	{ "slugprincess", "SlugPrincess" },
+	{ "sma21", "SMA 2.1" },
+	{ "sma31", "SMA 3.1" },
+	{ "sma4", "SMA 4" },
+	{ "smavi", "SMA VI" },
+	{ "smileysquest", "Smiley's Quest" },
+	{ "smileysquest2", "Smiley's Quest 2" },
+	{ "smoothhide", "Smooth Hide" },
+	{ "snakeamagsgame", "SNAKE - a MAGS game" },
+	{ "snakesofavalon", "Snakes of Avalon" },
+	{ "snakesonaplane", "Snakes on a plane!" },
+	{ "sniperandspotterservingthemotherland", "Sniper and spotter serving the motherland" },
+	{ "sonicandfriendsinclubhouse", "Sonic and friends in: Club house" },
+	{ "sosk", "Sosk" },
+	{ "sovietunterzoegersdorfsectorii", "Soviet Unterzoegersdorf: Sector II" },
+	{ "sowjetunterzgersdorf", "Sowjet-Unterz?gersdorf" },
+	{ "spacefreakers", "Space Freakers" },
+	{ "spacelynxes", "Space Lynxes" },
+	{ "spacepirates", "Space Pirates" },
+	{ "spacepoolalpha", "Space Pool Alpha" },
+	{ "spacequest45", "Space Quest 4.5" },
+	{ "spacequest55demoags", "Space Quest 5.5 demo (AGS)" },
+	{ "spacequestiiivgapreview", "Space Quest III VGA Preview" },
+	{ "sqm11", "Space Quest Mania 1x1" },
+	{ "sqm12", "Space Quest Mania 1x2" },
+	{ "sqm13", "Space Quest Mania 1x3" },
+	{ "sqm14", "Space Quest Mania 1x4" },
+	{ "sqm16", "Space Quest Mania 1x6" },
+	{ "spacerangers", "Space Rangers " },
+	{ "spacerangersep52", "Space Rangers Ep 52" },
+	{ "spacewar", "Space war" },
+	{ "spacewarepisode2strikba", "Spacewar episode 2(strik.ba.)" },
+	{ "spellbound", "Spellbound" },
+	{ "spilakassinn", "Spilakassinn" },
+	{ "spooks", "Spooks" },
+	{ "spoonsiiitheunauthorizededition", "Spoons III - The Unauthorized Edition" },
+	{ "spotthedifference", "Spot The Difference" },
+	{ "sproutsofevil", "Sprouts of evil" },
+	{ "sqkubikgetready", "SQ Kubik (Get ready?)" },
+	{ "sqmania1", "SQ Mania #1" },
+	{ "sqmania2remakeeng", "SQ Mania 2 Remake (ENG)" },
+	{ "sqmaniaep5", "SQ Mania Ep5" },
+	{ "sram2cinomehsrevengedemo", "SRAM 2 - CINOMEH'S REVENGE (demo)" },
+	{ "stablepeteandthejoust", "Stable Pete and the Joust" },
+	{ "stairquest", "Stair Quest" },
+	{ "stanamespiepisode1", "Stan Ames PI, Episode 1" },
+	{ "stansrevenge", "Stan's Revenge" },
+	{ "starshipcaramba", "Starship Caramba" },
+	{ "starshipposeidon", "Starship Poseidon" },
+	{ "start", "Start" },
+	{ "startreknewton", "Star Trek: Newton" },
+	{ "stediddyip1employment", "Stediddy IP1 - Employment" },
+	{ "stickmeni", "Stickmen I" },
+	{ "stickythestickfigurepart1thecrimsonhouse", "Sticky the Stick Figure Part 1: The Crimson House" },
+	{ "stinkymcpoopoo", "Stinky McPooPoo" },
+	{ "stranded", "STRANDED" },
+	{ "stranger", "Stranger" },
+	{ "strangerinstickworld", "Stranger in Stickworld" },
+	{ "strangerthings", "Stranger Things" },
+	{ "supaevil", "Supa-EviL" },
+	{ "supergirl", "Supergirl" },
+	{ "superjazzmandemo", "Super Jazz Man (DEMO)" },
+	{ "superracing", "Super Racing" },
+	{ "surreality", "Surreality" },
+	{ "sweed", "Sweed" },
+	{ "sword", "Sword" },
+	{ "sydneyfindsemployment", "Sydney Finds Employment" },
+	{ "sydneytreadsthecatwalk", "Sydney Treads the Catwalk" },
+	{ "symplokelaleyendadegustavobuenocapitulo1", "Symploke. La Leyenda de Gustavo Bueno. Capitulo 1" },
+	{ "tales", "Tales" },
+	{ "talesofchickenry", "Tales of Chickenry" },
+	{ "tao", "Tao" },
+	{ "tarthenia", "Tarthenia" },
+	{ "teamwork", "Teamwork" },
+	{ "templeofspheres", "Temple of Spheres" },
+	{ "tenhumstombpart1", "Tenhum's Tomb Part 1" },
+	{ "terrorofthevampire", "Terror of the Vampire!" },
+	{ "test", "Test" },
+	{ "test5", "test5" },
+	{ "textparsergame", "Text Parser Game" },
+	{ "thatday", "ThatDay" },
+	{ "the30minutewar", "The 30 Minute War" },
+	{ "the7thsense", "The 7th Sense" },
+	{ "theadventureofthehero", "The Adventure of the Hero" },
+	{ "theadventuresoffatman", "The Adventures of Fatman" },
+	{ "theadventuresofturquoisem", "The Adventures of Turquoise M" },
+	{ "theassassin", "The Assassin" },
+	{ "theawakening", "The Awakening" },
+	{ "thebadneighbours", "The bad neighbours" },
+	{ "thebar", "The Bar" },
+	{ "thebrokenbrain", "The Broken Brain" },
+	{ "thebunker", "The Bunker" },
+	{ "thecadaversynod", "The cadaver synod" },
+	{ "thecan", "The Can" },
+	{ "thecell", "The Cell" },
+	{ "thechrysalis", "The Chrysalis" },
+	{ "thecrackwelllegacy", "The Crackwell Legacy" },
+	{ "thecube", "The Cube" },
+	{ "thecurioussilence", "The Curious Silence" },
+	{ "thecurseoflife", "The Curse of Life" },
+	{ "thedayofdarkness", "The Day Of Darkness" },
+	{ "thedeathoflukesimpson", "The Death of Luke Simpson" },
+	{ "thedevilsshroudpart1", "The Devil's Shroud-part1" },
+	{ "thedigitalspell", "The Digital Spell" },
+	{ "thedusseldorfconspiracy", "The Dusseldorf Conspiracy" },
+	{ "thedwarvendaggerofblitz", "The Dwarven Dagger of Blitz" },
+	{ "theelevator", "The Elevator" },
+	{ "theenergizer", "The Energizer" },
+	{ "theepicadventures", "The epic adventures" },
+	{ "theeverbeginningtale", "The Ever-Beginning Tale" },
+	{ "theexecutionofanneboleyn", "The Execution of Anne Boleyn" },
+	{ "thefarm", "the farm" },
+	{ "theficklehandsoffate", "The Fickle Hands of Fate" },
+	{ "thefind", "The Find" },
+	{ "thegourmet", "The Gourmet" },
+	{ "thegreatcasserolecaper", "The Great Casserole Caper" },
+	{ "thegreatstrokeoff", "The Great Stroke-Off!" },
+	{ "thegruglegends", "The Grug Legends" },
+	{ "thehamlet", "The Hamlet" },
+	{ "thehauntedhouse", "The Haunted House" },
+	{ "theheist", "The Heist" },
+	{ "thehobbitriseofthedragonking", "The Hobbit: Rise of the Dragon King" },
+	{ "thehousethatatemysoul", "The house that ate my soul" },
+	{ "thehuntforgoldbeard", "The hunt for Goldbeard" },
+	{ "thehuntforshaunbinda", "The hunt for Shaun Binda" },
+	{ "thehuntforshaunbindadeluxeedition", "The Hunt For Shaun Binda Deluxe Edition" },
+	{ "theiraqiparadox", "The Iraqi Paradox" },
+	{ "thejackyard", "The Jackyard" },
+	{ "thejourneyhome", "The Journey Home" },
+	{ "thejourneyofiesir", "The Journey of Iesir" },
+	{ "thelastharvest", "The Last Harvest" },
+	{ "thelastsupperawhodunnit", "THE LAST SUPPER, A WHODUNNIT" },
+	{ "theloneloserdemo", "The Lone Loser - DEMO" },
+	{ "thelongtrip", "The Long Trip" },
+	{ "themajesticconspiracy", "The Majestic Conspiracy" },
+	{ "themarionette", "The Marionette" },
+	{ "themccarthychronicleschapter1", "The McCarthy Chronicles Chapter 1" },
+	{ "themcreedcasebytk", "The McReed Case by TK" },
+	{ "themysteriesofstiegomoors", "The Mysteries of Stiego Moors" },
+	{ "themysteryofhauntedhollow", "The Mystery of Haunted Hollow" },
+	{ "thenetherworld", "The Netherworld" },
+	{ "thenextcurse", "The Next Curse" },
+	{ "theoraclev11", "The Oracle v1.1" },
+	{ "thepark", "The Park" },
+	{ "theperfectmurder", "The Perfect Murder" },
+	{ "thephantominheritance", "The Phantom Inheritance" },
+	{ "thequestfortheholysalsa", "The Quest for the Holy Salsa" },
+	{ "thequesttozooloo", "The Quest To Zooloo" },
+	{ "theroadtomurder", "The Road to Murder" },
+	{ "therobolovers", "The Robolovers" },
+	{ "therotaryclub", "The Rotary Club" },
+	{ "thesearch", "The Search" },
+	{ "thesecretofchunkysalsa", "The Secret of Chunky Salsa" },
+	{ "thesecretofgoldenriver", "The Secret of Golden River" },
+	{ "thesecretofhuttongrammarschool", "The Secret of Hutton Grammar School" },
+	{ "thesecretofmountmonkey", "The secret of Mount Monkey" },
+	{ "thesecretplan1runningtostandstill", "The Secret Plan 1 - Running to stand still" },
+	{ "theshortestjourney", "The Shortest Journey" },
+	{ "thesmallestpoints", "The Smallest Points" },
+	{ "thesnaplock", "The Snaplock" },
+	{ "thespoons", "The spoons" },
+	{ "thestarryskyaboveme", "The Starry Sky Above Me" },
+	{ "thestring", "The String" },
+	{ "thesundownmystery", "The Sundown mystery" },
+	{ "thetombofthemoon", "The Tomb of the Moon" },
+	{ "thetrap", "The Trap" },
+	{ "thetreasuredmedallion", "The Treasured Medallion" },
+	{ "thetreasureoflochinch", "The Treasure of Loch Inch" },
+	{ "theuncertaintymachine", "The Uncertainty Machine" },
+	{ "theupliftmofopartyplan", "The Uplift Mofo Party Plan" },
+	{ "thevacuum", "The Vacuum" },
+	{ "thewitch", "The witch, ..." },
+	{ "thisgame", "This Game" },
+	{ "threeguyswalkintoheaven", "Three Guys Walk Into Heaven" },
+	{ "tilepuzzlegame", "Tile Puzzle Game" },
+	{ "tiltor", "Tiltor" },
+	{ "timegentlemenpleasedemo", "Time Gentlemen, Please DEMO" },
+	{ "timequest", "Time Quest" },
+	{ "timequest2", "Time Quest 2" },
+	{ "timesinkofchronos", "Timesink of Chronos" },
+	{ "timothylande", "Timothy Lande" },
+	{ "tmateundescanso", "T?mate un descanso" },
+	{ "tmntturtlesintime", "TMNT: Turtles in Time" },
+	{ "tomhanksaway", "Tom Hanks Away" },
+	{ "toomanykittens", "Too Many Kittens" },
+	{ "totalhangoverextreamzz", "Total Hangover ExtreamZz!" },
+	{ "tq", "tq" },
+	{ "trappedinabuilding", "Trapped in a building" },
+	{ "trevordaisoninouterspace", "Trevor Daison in outer space" },
+	{ "trexandmusclesambigtroubleinspf", "Trex and Muscle SAM big trouble in SPF" },
+	{ "trilbysnotes", "Trilby's Notes" },
+	{ "trilbytheartoftheft", "Trilby: The Art Of Theft" },
+	{ "trivialpassyouit", "Trivial Pass You It" },
+	{ "tuberainbow", "Tube Rainbow" },
+	{ "tvbrder", "Tv? Br?der" },
+	{ "twelvethirteen", "Twelve Thirteen" },
+	{ "twelvethirteenepisode2", "Twelve Thirteen, episode 2" },
+	{ "twelvethirteenepisode3", "Twelve Thirteen, episode 3" },
+	{ "twentiesflappersvsthemummy", "Twenties Flappers vs The Mummy" },
+	{ "twoofakind", "Two of a Kind" },
+	{ "uglyfiles", "UGLY FILES" },
+	{ "ulitsadimitrova", "Ulitsa Dimitrova" },
+	{ "unboundver10", "Unbound Ver 1.0" },
+	{ "unfinished", "unfinished" },
+	{ "unganeedsmumba", "UNGA needs MUMBA" },
+	{ "unintelligentdesign", "Unintelligent Design" },
+	{ "unprofev10", "Un Profe V 1.0" },
+	{ "untilihaveyou", "Until I Have You" },
+	{ "updatequest", "Update Quest" },
+	{ "utopiaoftyrant", "Utopia of Tyrant" },
+	{ "vacationquestthing", "Vacation Quest... Thing" },
+	{ "valhallaextinction", "Valhalla Extinction" },
+	{ "valis", "valis" },
+	{ "vankairbreak", "van K. Airbreak" },
+	{ "vegetablepatchextreemturbo", "Vegetable Patch Extreem Turbo" },
+	{ "veggietales3d", "Veggie Tales 3D" },
+	{ "veteranshootout", "Veteran shootout" },
+	{ "vicwreckleshalloweencostume", "Vic Wreckle's Halloween Costume" },
+	{ "virtualpiano10", "Virtual Piano 1.0" },
+	{ "vohaulsrevengeii", "Vohaul's revenge II" },
+	{ "vpxt2", "V  P  x  T  !  2  !" },
+	{ "waitingfortheloop", "Waiting For the Loop" },
+	{ "wallyweaseldemo", "Wally Weasel Demo" },
+	{ "waltersasteroid", "Walters-Asteroid" },
+	{ "warthogs", "Warthogs" },
+	{ "washedashore", "Washed Ashore" },
+	{ "washedashoredeluxe", "Washed Ashore Deluxe" },
+	{ "wasted", "Wasted" },
+	{ "waterquest", "WATER QUEST" },
+	{ "wcedit", "WCEdit...             " },
+	{ "wearevectors", "We Are Vectors" },
+	{ "welcometodarklake", "Welcome to Dark Lake" },
+	{ "wet", "WET " },
+	{ "what", "what!" },
+	{ "whatisthatthing", "what is that thing" },
+	{ "whatlinusbruckmansees", "What Linus Bruckman Sees" },
+	{ "wherebedragons", "Where Be Dragons?" },
+	{ "wheredidsamgo", "Where did Sam go?" },
+	{ "wheresmhatma", "Where's M' Hat Ma?" },
+	{ "whowantstoliveagain", "Who wants to live again?" },
+	{ "whowantstoliveforever", "Who wants to live forever?" },
+	{ "williamsnightmare", "Williams Nightmare" },
+	{ "willowhouse", "Willow House" },
+	{ "willy", "Willy" },
+	{ "winnersdontdodrugs", "Winners Dont' Do Drugs" },
+	{ "winterrose", "Winter Rose" },
+	{ "witch", "Witch" },
+	{ "witchnight", "Witch Night" },
+	{ "witness", "Witness!" },
+	{ "wizardhood", "Wizardhood" },
+	{ "woo", "Woo" },
+	{ "woolyrockbottom", "Wooly Rockbottom" },
+	{ "worldofwarcraftquest", "World of Warcraft Quest" },
+	{ "worm", "Worm" },
+	{ "wrathofthesolonoids", "Wrath of the Solonoids " },
+	{ "yoda", "Yoda" },
+	{ "yourgame", "Your Game" },
+	{ "yourlate", "Your late!" },
+	{ "zakmckracken", "Zak McKracken" },
+	{ "zombieattackdemo", "Zombie Attack Demo" },
+	{ "zombiefish", "Zombie Fish" },
+	{ "zooreal", "ZooReal" },
+	{ "zugzwang", "Zugzwang" },
 
 	{ 0, 0 }
 };
 
-#define ENGLISH_ENTRY(ID, FILENAME, MD5, SIZE) { \
-		{ \
-			ID, \
-			nullptr, \
-			AD_ENTRY1s(FILENAME, MD5, SIZE), \
-			Common::EN_ANY, \
-			Common::kPlatformUnknown, \
-			ADGF_UNSTABLE, \
-			GUIO1(GUIO_NOSPEECH) \
-		}, \
-		nullptr \
-	}
-
-#define ENGLISH_PLUGIN(ID, FILENAME, MD5, SIZE, PLUGIN_ARR) { \
-		{ \
-			ID, \
-			nullptr, \
-			AD_ENTRY1s(FILENAME, MD5, SIZE), \
-			Common::EN_ANY, \
-			Common::kPlatformUnknown, \
-			ADGF_UNSTABLE, \
-			GUIO1(GUIO_NOSPEECH) \
-		}, \
-		PLUGIN_ARR \
-	}
+#define UNSUPPORTED_ENTRY(ID, FILENAME, MD5, SIZE) \
+	{{ ID, nullptr, AD_ENTRY1s(FILENAME, MD5, SIZE), Common::EN_ANY, \
+	Common::kPlatformUnknown, ADGF_UNSTABLE, GUIO0() }, nullptr }
+#define ENGLISH_ENTRY(ID, FILENAME, MD5, SIZE) \
+	UNSUPPORTED_ENTRY(ID, FILENAME, MD5, SIZE)
+
+#define ENGLISH_PLUGIN(ID, FILENAME, MD5, SIZE, PLUGIN_ARR) \
+	{{ ID, nullptr, AD_ENTRY1s(FILENAME, MD5, SIZE), Common::EN_ANY, \
+	Common::kPlatformUnknown, ADGF_UNSTABLE, GUIO0() }, PLUGIN_ARR }
+
 
 static const PluginVersion AGSCREDITZ_11[] = { { "agscreditz", 11 }, { nullptr, 0 } };
 
 const AGSGameDescription GAME_DESCRIPTIONS[] = {
+	// Pre-2.5 games that aren't supported by the current AGS engine
+	UNSUPPORTED_ENTRY("qfg412", "qfg.exe", "8b21668ca462b0b6b35df43c5902b074", 26674790),
+
+	// Post-2.5 games that are likely supported by the AGS engine
 	ENGLISH_ENTRY("5daysastranger", "5days.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 4440143),
 	ENGLISH_ENTRY("7daysaskeptic", "7days.exe", "465f972675db2da6040518221af5b0ba", 4693374),
-	ENGLISH_ENTRY("absentparti", "Absent - Part I.exe", "34ca36e3948aae8527dd0e90f0861a75", 31421924),
 	ENGLISH_ENTRY("atotk", "atotk.exe", "37cf2d4d07842d45b59c6dd9387c1ee7", 42872046),
 	ENGLISH_ENTRY("atotk", "atotk.exe", "37cf2d4d07842d45b59c6dd9387c1ee7", 42740200),
 	ENGLISH_PLUGIN("bcremake", "bc.exe", "0710e2ec71042617f565c01824f0cf3c", 7683255, AGSCREDITZ_11),
@@ -104,10 +1227,1168 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("primordia", "primordia.exe", "22313e59c3233001488c26f18c80cc08", 973495830), // GOG
 	ENGLISH_ENTRY("primordia", "primordia.exe", "f2edc9c3161f1f538df9b4c59fc89e24", 978377890), // GOG
 	ENGLISH_ENTRY("resonance", "resonance.exe", "2e635c22bcbf0ed3d46f1bcde71812d4", 849404957), // GOG
-
 	ENGLISH_ENTRY("mage", "ac2game.dat", "2e822f554994f36e0c62da2acda874da", 30492258), // GOG, Mac
 	ENGLISH_ENTRY("unavowed", "ac2game.dat", "b1ff7d96667707daf4266975cea2bf90", 1755457364), // Steam, Mac
 
+	// Unsorted games
+	ENGLISH_ENTRY("10waysfromsunday", "10WaysFromSunday.exe", "495d45fb8adfd49690ae3b97921feec6", 11362765),
+	ENGLISH_ENTRY("1dayamosquito", "mosquito.exe", "465f972675db2da6040518221af5b0ba", 2178983),
+	ENGLISH_ENTRY("2034acaftercanadaii", "2034 AC II.exe", "1280ba7c269a68a9505871516319db0c", 35207006),
+	ENGLISH_ENTRY("24hours", "24.exe", "f120690b506dd63cd7d1112ea6af2f77", 1932370),
+	ENGLISH_ENTRY("3piggiesalpha", "Three Little Pigs and a Wolf.exe", "23a67b6de10ec35e9f5a4dfc7d928222", 14180634),
+	ENGLISH_ENTRY("3piggiesalpha", "3piggiesAlpha.exe", "23a67b6de10ec35e9f5a4dfc7d928222", 14181120),
+	ENGLISH_ENTRY("46memorylane", "diyu.exe", "e3962995a70923a8d5a8f1cf8f932eee", 66686277),
+	ENGLISH_ENTRY("4ofclubs", "4ofClubs.exe", "06a03fe35791b0578068ab1873455463", 5909169),
+	ENGLISH_ENTRY("5daysastranger", "5days.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 4614351),
+	ENGLISH_ENTRY("6daysasacrifice", "6das.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 7993899),
+	ENGLISH_ENTRY("6mornings", "project2.exe", "e7dac058b9bc0b42d489e474c2ddec84", 11595240),
+	ENGLISH_ENTRY("7daysaskeptic", "7days.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 4863356),
+	ENGLISH_ENTRY("aazor", "aazor.exe", "465f972675db2da6040518221af5b0ba", 4956212),
+	ENGLISH_ENTRY("abducted", "10 MINUTES.exe", "465f972675db2da6040518221af5b0ba", 2687034),
+	ENGLISH_ENTRY("absent", "Absent.exe", "aabdafae8b57dfc48fdf158a72326c23", 39284149),
+	ENGLISH_ENTRY("absentparti", "Absent - Part I.exe", "34ca36e3948aae8527dd0e90f0861a75", 31421924),
+	ENGLISH_ENTRY("access", "Access.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 1816218),
+	ENGLISH_ENTRY("aceking", "ags.exe", "f982756f0e2c2fbeca15d199b9851559", 338249917),
+	ENGLISH_ENTRY("acequest", "NEWGAME.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 4124225),
+	ENGLISH_ENTRY("achequest", "achequest.exe", "06a03fe35791b0578068ab1873455463", 2952369),
+	ENGLISH_ENTRY("achristmasblunder", "Blunder.exe", "35c11dc3b5f73b290489503b0a7c89e5", 1974915),
+	ENGLISH_ENTRY("aciddd", "acidddd.exe", "06a03fe35791b0578068ab1873455463", 1858394),
+	ENGLISH_ENTRY("acureforthecommoncold", "Game.exe", "06a03fe35791b0578068ab1873455463", 5247960),
+	ENGLISH_ENTRY("adaywithmichael", "ADWM.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 65283966),
+	ENGLISH_ENTRY("adventurequest", "Begin.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 1584015),
+	ENGLISH_ENTRY("adventurequest2", "adventure.exe", "f120690b506dd63cd7d1112ea6af2f77", 4603131),
+	ENGLISH_ENTRY("adventuresofjoshanddyan", "JoshandDyan.exe", "90413e9ae57e222f8913b09d2bc847bc", 3053444),
+	ENGLISH_ENTRY("adventuresofmaxfaxepisode1", "MaxFax1.exe", "f95aa7fd4c60ae0c64ab2bca085d0d15", 111272141),
+	ENGLISH_ENTRY("adventuresofprincessmarian", "marian.exe", "97d700529f5cc826f230c27acf81adfd", 3637811),
+	ENGLISH_ENTRY("adventuretheinsidejob", "Thalia.exe", "615e806856b7730afadf1fea9a756b70", 305012295),
+	ENGLISH_ENTRY("aerinde", "aerinde.exe", "3d40063da244931d67726a2d9600f1e8", 31700697),
+	ENGLISH_ENTRY("aeronuts", "AeroNuts.exe", "e446d58cf60bf13e32d0edd470065c7d", 10984662),
+	ENGLISH_ENTRY("afriendindeed", "TheHouse.exe", "3128b9f90e2f954ba704414ae854d10b", 6197624),
+	ENGLISH_ENTRY("afrojones", "afrojones.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 4739799),
+	ENGLISH_ENTRY("afterashadow", "After a Shadow.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 6157553),
+	ENGLISH_ENTRY("agenthudson", "ah.exe", "c7916b82f00c94013a3f7706b4d333c6", 15479216),
+	ENGLISH_ENTRY("agenttrinityepisode0theultimatum", "TheUltimatum_03.exe", "615e73fc1874e92d60a1996c2330ea36", 3777519),
+	ENGLISH_ENTRY("aggghost", "verbcoin.exe", "88d4158acfc9db9299e514979f289ced", 23937962),
+	ENGLISH_ENTRY("agitprop", "agitprop.exe", "a524cbb1c51589903c4043b98917f1d9", 12834513),
+	ENGLISH_ENTRY("agnosticchicken", "chicken.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 2473154),
+	ENGLISH_ENTRY("ags-mi3", "ags_mi3.exe", "0500aacb6c176d47ac0f8158f055db83", 5142697),
+	ENGLISH_ENTRY("agsawards2008ceremony", "aa2008.exe", "2615d67c2234f387e0ffd1a375476be0", 15151764),
+	ENGLISH_ENTRY("agsdarts", "AGS Darts.exe", "434c43a5e1ba2a11c1bde723ffeae719", 47771575),
+	ENGLISH_ENTRY("agsinvaders", "AGS-Invaders.exe", "f120690b506dd63cd7d1112ea6af2f77", 1394435),
+	ENGLISH_ENTRY("agsjukebox", "JukeBox2.exe", "a7aef57e360306c9377164f38d317ccb", 2914973),
+	ENGLISH_ENTRY("agsmoduletester", "V1.0 Source.exe", "95b7dd55f6e15c8a2118856ed9fe8ff9", 2020344),
+	ENGLISH_ENTRY("agsyahtzee2", "AGS Yahtzee 2.exe", "9e995c04d8642d6182d492c54a90b188", 71217276),
+	ENGLISH_ENTRY("agsyathzee", "AGS Yathzee.exe", "434c43a5e1ba2a11c1bde723ffeae719", 37295758),
+	ENGLISH_ENTRY("agunshotinroom37", "AGIR37.exe", "f120690b506dd63cd7d1112ea6af2f77", 1451303),
+	ENGLISH_ENTRY("ahmetsagsfightgameremix", "Fight.exe", "f120690b506dd63cd7d1112ea6af2f77", 2469641),
+	ENGLISH_ENTRY("ainthegoffantabulousw", "gfw.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 7991393),
+	ENGLISH_ENTRY("airwaveifoughtthelawandthelawone", "~airwave~.exe", "18456f28d9bf843b087e80072c85beca", 22521544),
+	ENGLISH_ENTRY("akumayosagschess275", "chess.exe", "f120690b506dd63cd7d1112ea6af2f77", 1198934),
+	ENGLISH_ENTRY("alansaveschristmasandmostoftheworldtoo", "ALANCMAS.exe", "3f76f9c4249bdc06794c13b098229c90", 39312224),
+	ENGLISH_ENTRY("albatheexplorer", "alba_explorer.exe", "0500aacb6c176d47ac0f8158f055db83", 2026147),
+	ENGLISH_ENTRY("alienattack", "Alien Attack.exe", "06a03fe35791b0578068ab1873455463", 11045476),
+	ENGLISH_ENTRY("alienpuzzleinvasion", "alien.exe", "a524cbb1c51589903c4043b98917f1d9", 10552264),
+	ENGLISH_ENTRY("alienrapeescape", "A.R.E.exe", "39d7a558298a9f1d40c1f415daf9bb74", 4802707),
+	ENGLISH_ENTRY("alienthreat", "Alien Threat.exe", "f120690b506dd63cd7d1112ea6af2f77", 6341266),
+	ENGLISH_ENTRY("alientimezone", "ATZ.exe", "0710e2ec71042617f565c01824f0cf3c", 2911858),
+	ENGLISH_ENTRY("aloneinthenight", "ALONE.exe", "0710e2ec71042617f565c01824f0cf3c", 9501343),
+	ENGLISH_ENTRY("alphadog", "Alpha_Dog.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 3329253),
+	ENGLISH_ENTRY("alphax", "Project SMASH.exe", "06a03fe35791b0578068ab1873455463", 25377719),
+	ENGLISH_ENTRY("alphax", "alphax.exe", "06a03fe35791b0578068ab1873455463", 17879795),
+	ENGLISH_ENTRY("alquest1demo", "AlQuest.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 20154310),
+	ENGLISH_ENTRY("alysvsthephantomfelinefoe", "Alys.exe", "3c5bd1713959ff469cb46ebe5542cfcf", 22323495),
+	ENGLISH_ENTRY("amagicstone", "A magic stone.exe", "465f972675db2da6040518221af5b0ba", 5478520),
+	ENGLISH_ENTRY("amotospuf", "Amotos.exe", "06a03fe35791b0578068ab1873455463", 10771879),
+	ENGLISH_ENTRY("amtag", "amtag.exe", "06a03fe35791b0578068ab1873455463", 8755912),
+	ENGLISH_ENTRY("anighttoremember", "The Trials.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 9643993),
+	ENGLISH_ENTRY("anna", "Anna.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 42337759),
+	ENGLISH_ENTRY("annieandroidautomatedaffection", "Annie source.exe", "fc17e9b3ab53f6b4841e2a4af5c782ff", 5015270),
+	ENGLISH_ENTRY("anoblegame", "a_noble_game.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 3580379),
+	ENGLISH_ENTRY("anthonysessay", "Copy of school.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 11033611),
+	ENGLISH_ENTRY("anticipatingmurder", "AGS.exe", "f120690b506dd63cd7d1112ea6af2f77", 19907137),
+	ENGLISH_ENTRY("antiheroes", "AntiHeroes.exe", "f120690b506dd63cd7d1112ea6af2f77", 3984580),
+	ENGLISH_ENTRY("apiratestale", "A_PIRATES_TALE.exe", "06a03fe35791b0578068ab1873455463", 13952670),
+	ENGLISH_ENTRY("aplaceinthesun", "InTheSun.exe", "7a3096ac0237cb6aa8e1718e28caf039", 40359648),
+	ENGLISH_ENTRY("apprentice", "App.exe", "ecc8eaa38fe3adea61ffc525d2ce5c0e", 14110306),
+	ENGLISH_ENTRY("apprentice2", "App2.exe", "465f972675db2da6040518221af5b0ba", 34159191),
+	ENGLISH_ENTRY("apprenticedeluxe", "App.exe", "45ab4f29031b50c8d01d10a269f77ff5", 17488604),
+	ENGLISH_ENTRY("aprofoundjourney", "apj.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 920131),
+	ENGLISH_ENTRY("archeos", "Archeos.exe", "2ff048659aaefd20d342db6428a5f1a0", 6661410),
+	ENGLISH_ENTRY("archeos", "Archeos.exe", "2ff048659aaefd20d342db6428a5f1a0", 6659974),
+	ENGLISH_ENTRY("arewethereyet", "AREwethereyet.exe", "f120690b506dd63cd7d1112ea6af2f77", 1054672),
+	ENGLISH_ENTRY("armageddonmargaret", "Armageddon Margaret.exe", "3128b9f90e2f954ba704414ae854d10b", 2951568),
+	ENGLISH_ENTRY("armageddonmargaret", "AM_Game.exe", "06a03fe35791b0578068ab1873455463", 3640885),
+	ENGLISH_ENTRY("asecondface", "Eye of Geltz.exe", "0e32c4b3380e286dc0cea8550f1c045e", 7061019),
+	ENGLISH_ENTRY("ashortnightmare", "A_Short_Nightmare.exe", "b142b43c146c25443a1d155d441a6a81", 94221930),
+	ENGLISH_ENTRY("asporia", "RPG.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 7094164),
+	ENGLISH_ENTRY("asterix", "Asterix.exe", "06a03fe35791b0578068ab1873455463", 62405430),
+	ENGLISH_ENTRY("astranded", "Astranded.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 1845395),
+	ENGLISH_ENTRY("astron", "Astron.exe", "a0fd918609b9d139e4076fa7a0052ae1", 71101771),
+	ENGLISH_ENTRY("aswinpathv01beta", "AGSGAME.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 14384181),
+	ENGLISH_ENTRY("ataleofbetrayal", "Mags.exe", "465f972675db2da6040518221af5b0ba", 11071496),
+	ENGLISH_ENTRY("ataleoftwokingdoms", "ATOTK.exe", "37cf2d4d07842d45b59c6dd9387c1ee7", 42785860),
+	ENGLISH_ENTRY("atapi", "Atapi.exe", "dd8586ebefd5c457e29b6b9845a576ea", 34114381),
+	ENGLISH_ENTRY("atotkjukebox", "Jukebox.exe", "37cf2d4d07842d45b59c6dd9387c1ee7", 1631992),
+	ENGLISH_ENTRY("atreatandsometricks", "A Treat and Some Tricks.exe", "495d45fb8adfd49690ae3b97921feec6", 33708250),
+	ENGLISH_ENTRY("aunaturel", "Au Naturel.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 8499426),
+	ENGLISH_ENTRY("automation", "automation.exe", "c16204dc8aa338e3199b2c62da0b33f4", 3943320),
+	ENGLISH_ENTRY("averyspecialdog", "dog.exe", "465f972675db2da6040518221af5b0ba", 2120544),
+	ENGLISH_ENTRY("awakener", "Awakener.exe", "3e62eafed0fc365821b7afdbf1aec3d8", 8896076),
+	ENGLISH_ENTRY("awakening", "EOB.exe", "a524cbb1c51589903c4043b98917f1d9", 21527657),
+	ENGLISH_ENTRY("awakeningofthesphinx", "awksphinx.exe", "0500aacb6c176d47ac0f8158f055db83", 7507867),
+	ENGLISH_ENTRY("awalkindatomb", "full game.exe", "0710e2ec71042617f565c01824f0cf3c", 1312738),
+	ENGLISH_ENTRY("awalkinthepark", "sag_mag_04_08.exe", "9cb3c8dc7a8ab9c44815955696be2677", 2908542),
+	ENGLISH_ENTRY("axmasevetale", "MAGS.exe", "71ca0d6c1c699595f28a2125948d4a84", 6489870),
+	ENGLISH_ENTRY("backdoorman", "hustler.exe", "2c26669a627da8e1e5159319b78ad1ce", 9558000),
+	ENGLISH_ENTRY("badluck", "Bad Luck.exe", "f120690b506dd63cd7d1112ea6af2f77", 10618466),
+	ENGLISH_ENTRY("baldysadventure", "Baldy.exe", "ea0d3284542db629f36cb6fc785e07bc", 179358984),
+	ENGLISH_ENTRY("baltazarthefamiliar", "Baltazar.exe", "9cb3c8dc7a8ab9c44815955696be2677", 2867294),
+	ENGLISH_ENTRY("bananamandemo", "Banana Man Demo.exe", "615e806856b7730afadf1fea9a756b70", 53524952),
+	ENGLISH_ENTRY("bananaracer", "BananaRacer.exe", "e93f9dfa8405f1ca9f881d160ab31dc2", 10452233),
+	ENGLISH_ENTRY("barndilemma", "woh.exe", "089fab88e6e1075a2f5b271f6f5b3c57", 2432485),
+	ENGLISH_ENTRY("barnrunner5part1", "Barn Runner 5-1.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 104073543),
+	ENGLISH_ENTRY("barnrunner5part2", "Barn Runner 5-2.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 200879890),
+	ENGLISH_ENTRY("barnrunnerholiday2", "Xmas 2.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 31770973),
+	ENGLISH_ENTRY("bartsquestfortv", "Simpsons.exe", "0500aacb6c176d47ac0f8158f055db83", 794013),
+	ENGLISH_ENTRY("battlewarriors", "Battle.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 16314318),
+	ENGLISH_ENTRY("beacon", "Beacon.exe", "af0d268193a9220891e983d03141ec58", 24671086),
+	ENGLISH_ENTRY("bear", "Bear.exe", "97020973a2a635fe28eb0ba4bdfaa70b", 3258662),
+	ENGLISH_ENTRY("beasts", "beasts.exe", "0500aacb6c176d47ac0f8158f055db83", 1295435),
+	ENGLISH_ENTRY("beautiesandbeasts", "BeautiesAndBeasts.exe", "089fab88e6e1075a2f5b271f6f5b3c57", 6507202),
+	ENGLISH_ENTRY("benjaminjordan", "BJ1.exe", "4b1378721f4f066f75102f3dca809224", 5678910),
+	ENGLISH_ENTRY("benjordancase1", "BJ1Deluxe.exe", "8275249f4ffbc28c1f10ad09a2786814", 8293704),
+	ENGLISH_ENTRY("bentheredanthat", "BTDT.exe", "90413e9ae57e222f8913b09d2bc847bc", 46342499),
+	ENGLISH_ENTRY("bernardsroom", "BernardsRoom.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 8767774),
+	ENGLISH_ENTRY("besieged", "besieged.exe", "615e806856b7730afadf1fea9a756b70", 11679795),
+	ENGLISH_ENTRY("bestowersofeternity", "Eternity.exe", "0b66a68c2c8aabe78c80e30b8b82acef", 16187539),
+	ENGLISH_ENTRY("beyondreality", "br.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 10879320),
+	ENGLISH_ENTRY("beyondterror", "BeyondTerror.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 8219797),
+	ENGLISH_ENTRY("beyondthehorizon", "Horizon.exe", "4d7d2addcde045dae6e0363a43f9acad", 15708563),
+	ENGLISH_ENTRY("bigbadwolf3lilpiggies", "Big Bad Wolf.exe", "06a03fe35791b0578068ab1873455463", 5812024),
+	ENGLISH_ENTRY("bigglesonmars", "Biggles On Mars.exe", "089fab88e6e1075a2f5b271f6f5b3c57", 29048931),
+	ENGLISH_ENTRY("billyboysimportantwinelottery", "BillyBoy.exe", "5881d6b88386317dc9d67524a14b11d4", 4872317),
+	ENGLISH_ENTRY("birdy", "Birdy.exe", "06a03fe35791b0578068ab1873455463", 4250415),
+	ENGLISH_ENTRY("bj7thecardinalsins", "BJ7.exe", "18b284c22010850f79bc5c20054a70c4", 13714066),
+	ENGLISH_ENTRY("bjcase2", "BJ2.exe", "465f972675db2da6040518221af5b0ba", 6318491),
+	ENGLISH_ENTRY("bjcase3", "BJ3.exe", "61f113e2e52e0dd27aeb438a55dd9b8c", 10841883),
+	ENGLISH_ENTRY("bjcase4", "BJ4.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 15303392),
+	ENGLISH_ENTRY("bjcase5", "BJ5.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 13681827),
+	ENGLISH_ENTRY("bjcase6", "BJ6.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 18281493),
+	ENGLISH_ENTRY("blackmailinbrooklyn", "brooklyn.exe", "3192c36199d2b0784f866b28da7106d8", 4913695),
+	ENGLISH_ENTRY("blackmorph", "Liechi.exe", "46859c6f77bdb311266daa589561fa6b", 14476030),
+	ENGLISH_ENTRY("blackuddertodoubloonornottodoubloon", "Blackudder.exe", "338fa79960d40689063af31c671b8729", 87695958),
+	ENGLISH_ENTRY("blackwellconvergence", "Convergence.exe", "856a6e0e22d2cb4a45d5bbc7245ce5e8", 29935120),
+	ENGLISH_ENTRY("blackwelllegacydemo", "Blackwell Demo.exe", "2eeca6bae968dc61b5ed36561efc0fca", 53342880),
+	ENGLISH_ENTRY("blackwellunbounddemo", "Unbound_Demo.exe", "6ee842f73649ced615c44d4eb303687c", 30057537),
+	ENGLISH_ENTRY("bluemoon", "Blue Moon.exe", "95dcf736be87cf7d40bf64d5b078c4b7", 14845997),
+	ENGLISH_ENTRY("boardquest", "Board Quest.exe", "465f972675db2da6040518221af5b0ba", 3930325),
+	ENGLISH_ENTRY("bob", "bob.exe", "0b7529a76f38283d6e850b8d56526fc1", 2874144),
+	ENGLISH_ENTRY("bobencavale", "Bob en cavale.exe", "06a03fe35791b0578068ab1873455463", 43264937),
+	ENGLISH_ENTRY("bobgoeshome", "Tut.exe", "0710e2ec71042617f565c01824f0cf3c", 1480234),
+	ENGLISH_ENTRY("bobgoeshomedeluxe", "BobDeluxe.exe", "0710e2ec71042617f565c01824f0cf3c", 1555913),
+	ENGLISH_ENTRY("bobsquest1", "BQ19.exe", "97d700529f5cc826f230c27acf81adfd", 2767487),
+	ENGLISH_ENTRY("bogsadventure", "BogsAdventure.exe", "25f919423520b921a041ec854e3a0217", 58789948),
+	ENGLISH_ENTRY("boom", "boom.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 934966),
+	ENGLISH_ENTRY("bowserquirkquest", "Bowser Quirk Quest.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 3046623),
+	ENGLISH_ENTRY("box", "Box.exe", "0b7529a76f38283d6e850b8d56526fc1", 748638),
+	ENGLISH_ENTRY("boyindahood", "Boy in da hood.exe", "afe40dc1416dd51e896ee0444d799f07", 12260759),
+	ENGLISH_ENTRY("bradbradsonkeyquest", "BADness.exe", "0500aacb6c176d47ac0f8158f055db83", 1190580),
+	ENGLISH_ENTRY("breakdownbyonedollar", "Breakdown.exe", "710ac163c281a5a539ffe2386264b990", 5273352),
+	ENGLISH_ENTRY("bsg78unexpectedattherisingstar", "BSG-E01.exe", "cf1ff01dfb8261f791ac95a7f5f05c1c", 401029955),
+	ENGLISH_ENTRY("btd", "BTD.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 6450527),
+	ENGLISH_ENTRY("bubsythebobcatinripvanbubsystarringbubsy", "Rip Van Bubsy.exe", "089fab88e6e1075a2f5b271f6f5b3c57", 52424482),
+	ENGLISH_ENTRY("buccaneer", "Buccaneer.exe", "c87aa6377abc18c1a1b2968ae6db08eb", 1576850),
+	ENGLISH_ENTRY("bullettrain", "Bullet Train.exe", "f120690b506dd63cd7d1112ea6af2f77", 17383747),
+	ENGLISH_ENTRY("bunawantsbeer", "BWB.exe", "c02022408287355175a601fd5ed1c66d", 2285202),
+	ENGLISH_ENTRY("bunnyquest", "BunnyQuest.exe", "28f82e420b82d07651b68114f90223c8", 1154928),
+	ENGLISH_ENTRY("burymeinthesand", "buryme.exe", "f10516e88ec858700804ee69d041aead", 24252498),
+	ENGLISH_ENTRY("butcherstanys", "Stanys.exe", "97d700529f5cc826f230c27acf81adfd", 1404933),
+	ENGLISH_ENTRY("bytheswordconspiracy", "bts.exe", "7dc7f61f79ba7a77d4ef8168bfd3d173", 60246329),
+	ENGLISH_ENTRY("calebsdrunkenadventure", "Calebdru.exe", "0b7529a76f38283d6e850b8d56526fc1", 15484923),
+	ENGLISH_ENTRY("calsoon2", "Looncalsoon.exe", "97d700529f5cc826f230c27acf81adfd", 18981033),
+	ENGLISH_ENTRY("capricorn", "capricorn.exe", "06a03fe35791b0578068ab1873455463", 4817076),
+	ENGLISH_ENTRY("captaincringe", "Captain_Cringe.exe", "dd8586ebefd5c457e29b6b9845a576ea", 2631464),
+	ENGLISH_ENTRY("carrin", "Carrin.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 2376923),
+	ENGLISH_ENTRY("carrotbobinzxspeccyworld", "CarrotBob.exe", "949f7440e3692b7366c2029979dee9a0", 914509),
+	ENGLISH_ENTRY("casablancathedayafter", "Casablanca.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 4238105),
+	ENGLISH_ENTRY("castleoffire", "Castle of Fire.exe", "b6f0726bd5776abee0d452b8f1073850", 14800915),
+	ENGLISH_ENTRY("catacombic", "Catacombic.exe", "057d1aa29f6fadd83209268efcfb35a3", 7317791),
+	ENGLISH_ENTRY("catapault", "catapault.exe", "290afe0bac54418822f15175e474731d", 8286661),
+	ENGLISH_ENTRY("cayannepepper", "cPepper.exe", "06a03fe35791b0578068ab1873455463", 16117141),
+	ENGLISH_ENTRY("cedricandtherevolution", "elves!.exe", "b216ee957dd677023e02d900281a02d6", 10205755),
+	ENGLISH_ENTRY("celticchaos2fishermensfiends", "CC2.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 17463014),
+	ENGLISH_ENTRY("chalksquest", "Chalk.exe", "0710e2ec71042617f565c01824f0cf3c", 5138049),
+	ENGLISH_ENTRY("charliefoxtrot", "foxtrot.exe", "0500aacb6c176d47ac0f8158f055db83", 48626762),
+	ENGLISH_ENTRY("chatroom", "Chatroom.exe", "089fab88e6e1075a2f5b271f6f5b3c57", 6760748),
+	ENGLISH_ENTRY("cheerfulscience", "CheerfulScience.exe", "06a03fe35791b0578068ab1873455463", 7740040),
+	ENGLISH_ENTRY("chekken", "cheKKen.exe", "bde175c0c4d87a59a7a082be595d08da", 13477393),
+	ENGLISH_ENTRY("chemin", "chemin.exe", "06a03fe35791b0578068ab1873455463", 3179064),
+	ENGLISH_ENTRY("chezapa", "CHEZAPA.exe", "9cf51833e787cc919837d9a8bd8fc14c", 2870327),
+	ENGLISH_ENTRY("chickchaser", "AMY.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 7968024),
+	ENGLISH_ENTRY("chicken", "Chicken.exe", "f120690b506dd63cd7d1112ea6af2f77", 30627567),
+	ENGLISH_ENTRY("chicken", "chicken.exe", "f120690b506dd63cd7d1112ea6af2f77", 1652888),
+	ENGLISH_ENTRY("chickenfraction", "Chicken.exe", "0500aacb6c176d47ac0f8158f055db83", 3021315),
+	ENGLISH_ENTRY("chinesecheckers", "ChineseCheckers.exe", "06a03fe35791b0578068ab1873455463", 3391826),
+	ENGLISH_ENTRY("christmaspresent", "christmas.exe", "3128b9f90e2f954ba704414ae854d10b", 5644948),
+	ENGLISH_ENTRY("christmasquest", "Christmas Quest.exe", "f120690b506dd63cd7d1112ea6af2f77", 14042816),
+	ENGLISH_ENTRY("christmasquest2", "ChristmasQuest2.exe", "06a03fe35791b0578068ab1873455463", 22683950),
+	ENGLISH_ENTRY("christmasquest3santaslittlehelpdesk", "CQ3.exe", "f0a7712890942b9155193cc4488a07bc", 50854625),
+	ENGLISH_ENTRY("cirquedezale", "cirque.exe", "3128b9f90e2f954ba704414ae854d10b", 8547131),
+	ENGLISH_ENTRY("claire", "Claire.exe", "b25674056fe8cc0b7bf0a4409c5c5bfc", 2781456),
+	ENGLISH_ENTRY("classnotesv11", "ClassNotes.exe", "0710e2ec71042617f565c01824f0cf3c", 5706836),
+	ENGLISH_ENTRY("clex", "Clex.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 1381575),
+	ENGLISH_ENTRY("clipl2heblinna", "Clip goes to town.exe", "0710e2ec71042617f565c01824f0cf3c", 1690928),
+	ENGLISH_ENTRY("clubofevil", "Club of Evil.exe", "65f53f81071dab6b3ab8363e4c76d12e", 11838011),
+	ENGLISH_ENTRY("coeldeckaflightgame", "coell deca.exe", "a524cbb1c51589903c4043b98917f1d9", 5497572),
+	ENGLISH_ENTRY("coinrush2", "coinrsh2.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 1260438),
+	ENGLISH_ENTRY("colinsimpsonleavesemployme", "Office.exe", "06a03fe35791b0578068ab1873455463", 11781006),
+	ENGLISH_ENTRY("colourclash", "ColourClash.exe", "0241777c2537fc5d077c05cde10bfa9f", 2803703),
+	ENGLISH_ENTRY("colourwise", "ColourWise.exe", "473f0e2fd72b747cef62d91090ab74c7", 24461117),
+	ENGLISH_ENTRY("colourwiseleveleditor", "ColourWise - Level Editor.exe", "3e09048ec0763a90ffa4eaeeb8f96df5", 3365519),
+	ENGLISH_ENTRY("columbuslander", "Columbus Lander.exe", "779421cd8ad5268e2efdb26e04608db7", 48744943),
+	ENGLISH_ENTRY("comradecitizenpart1", "Citizen.exe", "06a03fe35791b0578068ab1873455463", 2174301),
+	ENGLISH_ENTRY("confessionsofacatburglar", "cat.exe", "0500aacb6c176d47ac0f8158f055db83", 1328541),
+	ENGLISH_ENTRY("conspiracybelowzero", "Conspiracy.exe", "338fa79960d40689063af31c671b8729", 395111008),
+	ENGLISH_ENTRY("conspiracyofsongo", "Songo.exe", "934a3d245739d7ac66c021f8409c1044", 31526905),
+	ENGLISH_ENTRY("constancethebarbarian", "CTB.exe", "0500aacb6c176d47ac0f8158f055db83", 1150440),
+	ENGLISH_ENTRY("cosmos", "space.exe", "0500aacb6c176d47ac0f8158f055db83", 3591766),
+	ENGLISH_ENTRY("cosmosquesti", "tfas1.exe", "ff3d6e4edfca8b4f4f1c6cbf8e2781a6", 16653211),
+	ENGLISH_ENTRY("cosmosquestii", "tfas2-32bit.exe", "ff3d6e4edfca8b4f4f1c6cbf8e2781a6", 118740291),
+	ENGLISH_ENTRY("cosmosquestiii", "CQ3.exe", "18b284c22010850f79bc5c20054a70c4", 8674790),
+	ENGLISH_ENTRY("cougarsquestforfreedom", "chra.exe", "0500aacb6c176d47ac0f8158f055db83", 12654043),
+	ENGLISH_ENTRY("counterfeit", "Counterfeit.exe", "ef1645ccd3d16691ec3908c91f340c34", 2232297),
+	ENGLISH_ENTRY("cow", "cow.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 134670383),
+	ENGLISH_ENTRY("coyote", "Coyote.exe", "a524cbb1c51589903c4043b98917f1d9", 33124533),
+	ENGLISH_ENTRY("craftofevil", "Craft Of Evil.exe", "4c1d9a74c4acf6771aab4be704bf0797", 22409329),
+	ENGLISH_ENTRY("crashevadedestroy", "CED.exe", "06a03fe35791b0578068ab1873455463", 1938399),
+	ENGLISH_ENTRY("crave", "Crave.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 59222727),
+	ENGLISH_ENTRY("crypt", "crypt.exe", "0500aacb6c176d47ac0f8158f055db83", 2089059),
+	ENGLISH_ENTRY("cryptic", "Cryptic.exe", "d9143b143b011d7bd8726c1bb5dabc59", 6027654),
+	ENGLISH_ENTRY("csihunt1", "CSI Hunt 1.exe", "06a03fe35791b0578068ab1873455463", 2190662),
+	ENGLISH_ENTRY("cspb", "CSPB.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 77296215),
+	ENGLISH_ENTRY("cuentosinconclusos", "ShSt.exe", "28f82e420b82d07651b68114f90223c8", 1013809),
+	ENGLISH_ENTRY("cyberjack", "brewton24.exe", "e3962995a70923a8d5a8f1cf8f932eee", 3439339),
+	ENGLISH_ENTRY("daleks", "Daleks.exe", "0241777c2537fc5d077c05cde10bfa9f", 2409634),
+	ENGLISH_ENTRY("dalesfilmquest", "dale.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 2557975),
+	ENGLISH_ENTRY("damsel", "Damsel.exe", "809418706c429cee5d88e8d483c906cc", 77101995),
+	ENGLISH_ENTRY("dancetilyoudrop", "DanceTilYouDrop.exe", "0710e2ec71042617f565c01824f0cf3c", 4822399),
+	ENGLISH_ENTRY("danewguys", "DaNewGuys.exe", "97020973a2a635fe28eb0ba4bdfaa70b", 11998791),
+	ENGLISH_ENTRY("danewguys", "DaNewGuys.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 12115013),
+	ENGLISH_ENTRY("dangerouslandstournamentrpg", "dlrt2.exe", "0710e2ec71042617f565c01824f0cf3c", 21636362),
+	ENGLISH_ENTRY("dannydreadisoncall", "On Call.exe", "ef480ccb0831e452e55456e0ca24c761", 8787649),
+	ENGLISH_ENTRY("darkcave", "DarkCave.exe", "0d48d8b170624e8f33bd7cd7f3ad2052", 5293954),
+	ENGLISH_ENTRY("darkofnight", "D_o_N.exe", "3f7bb944e107f883d183f047d9d7f698", 10261961),
+	ENGLISH_ENTRY("darktimesmerrychristmas", "Dark Times (Merry Christmas).exe", "1b9f13d430bb15bf30d0fd044358db68", 49043355),
+	ENGLISH_ENTRY("darum", "Darum.exe", "0241777c2537fc5d077c05cde10bfa9f", 4082708),
+	ENGLISH_ENTRY("darum", "afterlife.exe", "0241777c2537fc5d077c05cde10bfa9f", 4082712),
+	ENGLISH_ENTRY("davegeneric", "generic.exe", "a524cbb1c51589903c4043b98917f1d9", 2449830),
+	ENGLISH_ENTRY("davidletterman", "letterman.exe", "615e806856b7730afadf1fea9a756b70", 17019706),
+	ENGLISH_ENTRY("dawnswonderedatagesend", "myGame.exe", "75f4c7f66b1be60af5b2d65f617b91a7", 243406385),
+	ENGLISH_ENTRY("ddddd", "DDDDD.exe", "f3f788c1e3a7b0b40e24e453fa1b9440", 21718220),
+	ENGLISH_ENTRY("deadmeat", "Cold Meat.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 41382750),
+	ENGLISH_ENTRY("deadofwinter", "DoW.exe", "615e806856b7730afadf1fea9a756b70", 7055437),
+	ENGLISH_ENTRY("deathandtransfiguration", "death.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 11103314),
+	ENGLISH_ENTRY("deathofanangel", "Angel.exe", "f120690b506dd63cd7d1112ea6af2f77", 3906130),
+	ENGLISH_ENTRY("deathsdoor", "Death's Door.exe", "089fab88e6e1075a2f5b271f6f5b3c57", 31447213),
+	ENGLISH_ENTRY("deathsquest", "HEHU!.exe", "949f7440e3692b7366c2029979dee9a0", 991809),
+	ENGLISH_ENTRY("deathworeendlessfeathersdisk1", "Cyberpunk.exe", "2aaa2609117a34adf666ea546e6dc000", 12620944),
+	ENGLISH_ENTRY("demogame", "Demo Game.exe", "f120690b506dd63cd7d1112ea6af2f77", 3296215),
+	ENGLISH_ENTRY("demonday", "Testgame.exe", "0b7529a76f38283d6e850b8d56526fc1", 6749329),
+	ENGLISH_ENTRY("derverschwundenehusky", "Husky.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 51932091),
+	ENGLISH_ENTRY("detectivegallo", "dgbuild.exe", "5f2e683b0d5e66e47f5800322982171e", 466252165),
+	ENGLISH_ENTRY("detention", "little.exe", "c16204dc8aa338e3199b2c62da0b33f4", 2362176),
+	ENGLISH_ENTRY("devochkaquest", "DevochkaQuest.exe", "84faea68bf7277610c2229be7b3e74af", 32769660),
+	ENGLISH_ENTRY("dgsearchofthebatterie", "dgsfb.exe", "88cf59aad15ca331ab0f854e16c84df3", 1664209),
+	ENGLISH_ENTRY("diamondsintheroughdemo", "Diamonds Demo.exe", "14c995189266969d538b31d1df451d3f", 2439365),
+	ENGLISH_ENTRY("diemaskennyarlathoteps", "ags_masken.exe", "74dc062c5f68f3d70da911f2db5737b6", 129219473),
+	ENGLISH_ENTRY("disquiet", "Disquiet.exe", "f90f5f612ed5879addfdd8634d093333", 9624101),
+	ENGLISH_ENTRY("doctormaze", "Maze.exe", "825ccacaabe2a3b0cd48d6f8deb42d72", 43934617),
+	ENGLISH_ENTRY("doctormuttonchop", "muttonchop.exe", "57e261dd3bb45761af4a002775e45710", 5781714),
+	ENGLISH_ENTRY("donnaavengerofblood", "DONNA.exe", "74aad8dfd71ed2ae9574a60be7610c43", 275096403),
+	ENGLISH_ENTRY("donniedarko", "Darko.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 1820048),
+	ENGLISH_ENTRY("donspillacyconspiracyquest", "DSAQ.exe", "f120690b506dd63cd7d1112ea6af2f77", 2066918),
+	ENGLISH_ENTRY("donthedweebdancedilemma", "Don the Dweeb.exe", "f120690b506dd63cd7d1112ea6af2f77", 2278453),
+	ENGLISH_ENTRY("dontworryillbringthebeer", "Don't Worry, I'll Bring The Beer.exe", "495d45fb8adfd49690ae3b97921feec6", 4446095),
+	ENGLISH_ENTRY("dovadulasburn", "FILES.exe", "9cb3c8dc7a8ab9c44815955696be2677", 26489645),
+	ENGLISH_ENTRY("downfall", "Downfall.exe", "aabdafae8b57dfc48fdf158a72326c23", 183357927),
+	ENGLISH_ENTRY("dragonorb", "DragonOrb.exe", "2bc8f994a7d1e05ed45f35abf2128231", 269836732),
+	ENGLISH_ENTRY("dragontales", "dragont.exe", "465f972675db2da6040518221af5b0ba", 9240132),
+	ENGLISH_ENTRY("dreadmacfarlane", "Dread.exe", "615e806856b7730afadf1fea9a756b70", 11157310),
+	ENGLISH_ENTRY("dreadmacfarlane2", "Dread2.exe", "fb787304e66798ba9d0172665a34f4cf", 5332574),
+	ENGLISH_ENTRY("dreamagine", "Game.exe", "256752c9a97b4780fc5e6f3239c8cdf1", 11122818),
+	ENGLISH_ENTRY("dreamer", "LittleDreamer.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 62151801),
+	ENGLISH_ENTRY("dreamsequence", "dreamseq.ags", "97d700529f5cc826f230c27acf81adfd", 4724470),
+	ENGLISH_ENTRY("drlutztimetravelmachine", "Dr.Lutz Machine.exe", "2bc8f994a7d1e05ed45f35abf2128231", 12602529),
+	ENGLISH_ENTRY("dumbassdriversdemo", "dumbass.exe", "f120690b506dd63cd7d1112ea6af2f77", 40580988),
+	ENGLISH_ENTRY("dungeonhands", "DungeonHands.exe", "0a6704159f6f716ac80da91c430430ce", 16276450),
+	ENGLISH_ENTRY("dungeonhands", "DungeonHands.exe", "f80ff6c2348f2bb90d3813719f54c870", 13751518),
+	ENGLISH_ENTRY("duskhunters", "DuskHunters.exe", "3128b9f90e2f954ba704414ae854d10b",3029482),
+	ENGLISH_ENTRY("dusttowater", "Dust to Water.exe", "0e32c4b3380e286dc0cea8550f1c045e", 70459846),
+	ENGLISH_ENTRY("dutyandbeyond", "Deliver.exe", "0710e2ec71042617f565c01824f0cf3c", 28873258),
+	ENGLISH_ENTRY("duzzquest", "DuzzQuest.exe", "3128b9f90e2f954ba704414ae854d10b", 13125200),
+	ENGLISH_ENTRY("duzzquest2", "DuzzQuest2.exe", "8911d942c1a71458370d37ca3e5bfdda", 59088366),
+	ENGLISH_ENTRY("dysmaton", "Dysmaton.exe", "6e861b1f476ff7cdf036082abb271329", 140513956),
+	ENGLISH_ENTRY("earlbobbyislookingforaloodemo", "Demo.exe", "0e32c4b3380e286dc0cea8550f1c045e", 4221725),
+	ENGLISH_ENTRY("earlbobbyislookingforhisshoes", "Bobby's Shoes.exe", "bb59de174d70797d774dec76a171352d", 12735626),
+	ENGLISH_ENTRY("earlbobbysballs", "Bobby's Balls.exe", "bb59de174d70797d774dec76a171352d", 4006605),
+	ENGLISH_ENTRY("earlmansinthebreakout", "Earl Mansin.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 108987401),
+	ENGLISH_ENTRY("earthlingpriorities", "Earthling Priorities.exe", "9b54ea3557373188d8388ec4d1ae5eed", 21490281),
+	ENGLISH_ENTRY("easterislanddefender", "Moia 'n Seek.exe", "804add6fbbb791b7be195dc0097434a1", 6359079),
+	ENGLISH_ENTRY("easy3d", "Easy3D.exe", "06a03fe35791b0578068ab1873455463", 13361265),
+	ENGLISH_ENTRY("edmund", "Edmundand the potato.exe", "615e73fc1874e92d60a1996c2330ea36", 4533124),
+	ENGLISH_ENTRY("educatingadventuresofgirlandrabbit", "Game.exe", "82da2565c456dcfb265ded6fe3189c0b", 2877964),
+	ENGLISH_ENTRY("eerieblue", "EerieBlue.exe", "bacdba3c759a861e899e6b0adcbb8bd5", 96605122),
+	ENGLISH_ENTRY("electrctgui", "electrctGUI.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 8941606),
+	ENGLISH_ENTRY("elevator", "Elevator.exe", "f10516e88ec858700804ee69d041aead", 29506915),
+	ENGLISH_ENTRY("elfer10", "socer.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 1911767),
+	ENGLISH_ENTRY("elfmotorsinc", "ElfMtrs.exe", "3421b46ff95c5885603086c39a038a20", 8036769),
+	ENGLISH_ENTRY("elforescuecraby", "elfo.exe", "31457af75a89b6141c31e8ed33a57e25", 10641021),
+	ENGLISH_ENTRY("eliminationbyimprovisation", "Stu2.exe", "9cf51833e787cc919837d9a8bd8fc14c", 971446),
+	ENGLISH_ENTRY("emeraldeyes", "Emerald.exe", "f120690b506dd63cd7d1112ea6af2f77", 2849945),
+	ENGLISH_ENTRY("emilyenough", "EE.exe", "97020973a2a635fe28eb0ba4bdfaa70b", 3141963),
+	ENGLISH_ENTRY("emmarodedemo", "Emma Roide.exe", "aefd91a131817036d224fe030e406c6e", 24919443),
+	ENGLISH_ENTRY("emptymindblankfate", "EMBF.exe", "18b284c22010850f79bc5c20054a70c4", 75732051),
+	ENGLISH_ENTRY("enoworld", "Enoworld.exe", "465f972675db2da6040518221af5b0ba", 16151170),
+	ENGLISH_ENTRY("enterthestory", "Enter The Story.exe", "0514661a4ba6772cf0db0cf839fc7003", 19589742),
+	ENGLISH_ENTRY("equilibrium", "EQ.exe", "0500aacb6c176d47ac0f8158f055db83", 8398394),
+	ENGLISH_ENTRY("erictheanteater", "eric.exe", "e750ecac380dca709028fc0744b9f7f6", 3865602),
+	ENGLISH_ENTRY("erkadventuresinstoneagerealestate", "AISRE.exe", "41e8fa920589300ed8b4aec09a658c90", 5958575),
+	ENGLISH_ENTRY("errand", "Errand.exe", "8212e96af620f6e02a37fdf583f79751", 4421187),
+	ENGLISH_ENTRY("escape", "Escape.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 962798),
+	ENGLISH_ENTRY("escapefromasmallroom", "game1.exe", "0b7529a76f38283d6e850b8d56526fc1", 803029),
+	ENGLISH_ENTRY("escapefromevergreenforest", "EFEF.exe", "2e58934bbe98335f33c20a23a6c6135a", 23855632),
+	ENGLISH_ENTRY("escapefromlurrilous", "EFL.exe", "4bcbc24015114752b3c7971128704689", 2756979),
+	ENGLISH_ENTRY("escapefromthesalemmoons", "Salem.exe", "9cf51833e787cc919837d9a8bd8fc14c", 1394026),
+	ENGLISH_ENTRY("escapefromthezombiecity", "zombie.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 3216299),
+	ENGLISH_ENTRY("escapetheship", "Escape.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 1063503),
+	ENGLISH_ENTRY("esper", "esper.exe", "0710e2ec71042617f565c01824f0cf3c", 17409715),
+	ENGLISH_ENTRY("eternallyus", "Eternally Us.exe", "3faa59edd92158ff2cbd4b9db54acf61", 43467084),
+	ENGLISH_ENTRY("eventtimer", "Timer.exe", "95b7dd55f6e15c8a2118856ed9fe8ff9", 3000682),
+	ENGLISH_ENTRY("exclamation", "!.exe", "0514661a4ba6772cf0db0cf839fc7003", 2785515),
+	ENGLISH_ENTRY("exit", "EXIT.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 54723513),
+	ENGLISH_ENTRY("fadingshades", "FadingShades.exe", "f120690b506dd63cd7d1112ea6af2f77", 20166198),
+	ENGLISH_ENTRY("fakethemoonlanding", "OperationStarman.exe", "495d45fb8adfd49690ae3b97921feec6", 56805472),
+	ENGLISH_ENTRY("fallenangel", "Fallen Angel.exe", "f120690b506dd63cd7d1112ea6af2f77", 3993369),
+	ENGLISH_ENTRY("fallensoldier", "fallen soldier.exe", "7a3096ac0237cb6aa8e1718e28caf039", 81522018),
+	ENGLISH_ENTRY("fanbots", "Game.exe", "aecd482222ff54206e43a029b5f0b170", 8665702),
+	ENGLISH_ENTRY("farnowhere", "FAR NOWHERE.exe", "06a03fe35791b0578068ab1873455463", 77186777),
+	ENGLISH_ENTRY("fasmo", "fasmo.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 16778433),
+	ENGLISH_ENTRY("fasmogoeswest", "FasmoGoesWest.exe", "f120690b506dd63cd7d1112ea6af2f77", 15348030),
+	ENGLISH_ENTRY("fbiquest", "FQ.exe", "465f972675db2da6040518221af5b0ba", 3838610),
+	ENGLISH_ENTRY("fearaphobia", "Fearaphobia.exe", "c48d0beedcdc1b05e9e25dcd60de46a9", 9646228),
+	ENGLISH_ENTRY("featherweight", "Featherweight.exe", "e8b2a430042709f07183c2c249e0e0d9", 6399452),
+	ENGLISH_ENTRY("femspray", "Fem.exe", "01d0e6bd812abaa307bcb10fc2193416", 49176669),
+	ENGLISH_ENTRY("fengshuiandtheartoftvreception", "Feng Shui And The Art Of TV Reception.exe", "c1b88c284a3d821f93d78a2e88487932", 22687931),
+	ENGLISH_ENTRY("feuersturmkapitel1", "Feuersturm.exe", "06a03fe35791b0578068ab1873455463", 5682579),
+	ENGLISH_ENTRY("feuersturmkapitel2", "fs2.exe", "06a03fe35791b0578068ab1873455463", 7043558),
+	ENGLISH_ENTRY("feuersturmkapitel3", "feuersturm3.exe", "206478d4d39e16571682b2cddf01a78f", 7826524),
+	ENGLISH_ENTRY("fifa2003pro", "Soccer.exe", "475da5decb9ad2a11e64e2e2e891d8e0", 2524958),
+	ENGLISH_ENTRY("fight", "boxen.exe", "3128b9f90e2f954ba704414ae854d10b", 3132938),
+	ENGLISH_ENTRY("fightgame", "Fight Game.exe", "463f79e5db4013d1b3be647edd7e338d", 1871790),
+	ENGLISH_ENTRY("fightgame", "Fight Game.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 3551992),
+	ENGLISH_ENTRY("fireflystory3d", "FFS 3D.exe", "27343924ddad3be0b97bdcaa71858b1b", 2254453),
+	ENGLISH_ENTRY("flamebarrel", "Flame barrel.exe", "06a03fe35791b0578068ab1873455463", 2298745),
+	ENGLISH_ENTRY("flashbax", "demo Flashbax.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 5527034),
+	ENGLISH_ENTRY("flowergirl", "flowergirl.exe", "9cb3c8dc7a8ab9c44815955696be2677", 62544543),
+	ENGLISH_ENTRY("fluxworld", "FluxWorld.exe", "06a03fe35791b0578068ab1873455463", 5614789),
+	ENGLISH_ENTRY("forcemajeureiithezone", "TheZoneDemo.exe", "b63d26c17bf292017f9a708ae9dc38ca", 18414473),
+	ENGLISH_ENTRY("forfrogssakegetthefrogout", "Frog2.exe", "0241777c2537fc5d077c05cde10bfa9f", 6723366),
+	ENGLISH_ENTRY("forgettendeath", "ForgettenDeath.exe", "06a03fe35791b0578068ab1873455463", 19427130),
+	ENGLISH_ENTRY("fortressofwonders", "Fortress.exe", "465f972675db2da6040518221af5b0ba", 4474304),
+	ENGLISH_ENTRY("fountainofunicorns", "pmvi.exe", "465f972675db2da6040518221af5b0ba", 3038012),
+	ENGLISH_ENTRY("fountainofyouthdemo", "foydemo.exe", "f120690b506dd63cd7d1112ea6af2f77", 14372003),
+	ENGLISH_ENTRY("framed", "Jhum.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 4572587),
+	ENGLISH_ENTRY("frankenpooper", "frankenpooper.exe", "fb3b0f6bad923958d9d9198daea125e6", 24372899),
+	ENGLISH_ENTRY("frankthefarmhandpart1", "Frank.exe", "0006c0a95a5f35ca0d275adecf9dfa1d", 22602166),
+	ENGLISH_ENTRY("frankthefarmhandpart2", "Frank2.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 63832313),
+	ENGLISH_ENTRY("franticfrankoabergzwerggoneberserk", "steelh1.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 118746106),
+	ENGLISH_ENTRY("frasiercraneseattlerampage", "FRASIER.exe", "0241777c2537fc5d077c05cde10bfa9f", 3688664),
+	ENGLISH_ENTRY("fredandbarneymeetthefuture", "Fred and Barney meet the future.exe", "c48d0beedcdc1b05e9e25dcd60de46a9", 234107316),
+	ENGLISH_ENTRY("fribbeldib", "firbbeldib.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 90835696),
+	ENGLISH_ENTRY("frogisland", "frog_island.exe", "465f972675db2da6040518221af5b0ba", 4355477),
+	ENGLISH_ENTRY("fsis1000000quest", "$1000000.exe", "0710e2ec71042617f565c01824f0cf3c", 833468),
+	ENGLISH_ENTRY("fsisalienation", "alienation.exe", "06a03fe35791b0578068ab1873455463", 3812243),
+	ENGLISH_ENTRY("fsiscotmattcehotsvd", "valgame.exe", "06a03fe35791b0578068ab1873455463", 2199912),
+	ENGLISH_ENTRY("fsismhcfhr", "das_id.exe", "0710e2ec71042617f565c01824f0cf3c", 1852114),
+	ENGLISH_ENTRY("fsispowercowfromuranus", "PowerCowen.exe", "0710e2ec71042617f565c01824f0cf3c", 1442185),
+	ENGLISH_ENTRY("fulkinthedreamthaus", "DreamtHaus.exe", "06a03fe35791b0578068ab1873455463", 47212093),
+	ENGLISH_ENTRY("funsunmishaps", "Fun, Sun & Mishaps.exe", "933200c8f306eccaaa484b1575da8528", 452348894),
+	ENGLISH_ENTRY("funwithnumbers", "fwn.exe", "a524cbb1c51589903c4043b98917f1d9", 18743833),
+	ENGLISH_ENTRY("gabyking", "GabyKing.exe", "1fd15cc387812c04447d89729b24b097", 2289131),
+	ENGLISH_ENTRY("gamesgalore", "gamesgalore.exe", "f120690b506dd63cd7d1112ea6af2f77", 7620552),
+	ENGLISH_ENTRY("gassesuittollis3demo", "Gst3_demo.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 4270243),
+	ENGLISH_ENTRY("gatewayremake", "Gateway Remake.exe", "0241777c2537fc5d077c05cde10bfa9f", 210991212),
+	ENGLISH_ENTRY("genbu", "Genbu.exe", "64fcaf7da0b257ea831f89c54be0ad72", 1892238),
+	ENGLISH_ENTRY("geometricshapes1circleboy", "Circle1.exe", "06a03fe35791b0578068ab1873455463", 2389129),
+	ENGLISH_ENTRY("gesundheitdemo", "gesundheit.exe", "5554b9e0df6241d25c9a070708e54478", 49666357),
+	ENGLISH_ENTRY("getawayfrompluto", "Get away.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 755529),
+	ENGLISH_ENTRY("getfood", "getfood.exe", "495d45fb8adfd49690ae3b97921feec6", 10600153),
+	ENGLISH_ENTRY("ghostdream", "Ghostdream.exe", "05594881531d62e4575545f3c8fd2576", 225600520),
+	ENGLISH_ENTRY("ghosting", "Shawshank.exe", "9cb3c8dc7a8ab9c44815955696be2677", 2968469),
+	ENGLISH_ENTRY("ghostvoyage", "Ghost Voyage.exe", "089fab88e6e1075a2f5b271f6f5b3c57", 7870814),
+	ENGLISH_ENTRY("glitchquest", "glitchquest.exe", "465f972675db2da6040518221af5b0ba", 3182715),
+	ENGLISH_ENTRY("glitchquestnofun", "GQnofun.exe", "465f972675db2da6040518221af5b0ba", 3181931),
+	ENGLISH_ENTRY("gnomeshomebrewingadventure", "gnomebrew.exe", "abb3aee32ae97a8475626cceefb0664e", 50307521),
+	ENGLISH_ENTRY("gnrblexags", "Gnrblex_AGS.exe", "476a1a39d43ea27577eacf907173e2c1", 85038656),
+	ENGLISH_ENTRY("goneboatfishin", "Gone Boat Fishin'.exe", "bdd1df0484e296faa348ffcb03e16273", 72936045),
+	ENGLISH_ENTRY("goodmorningmrgingerbread", "mister_gingerbread.exe", "b42f80733b6bd1ded5e29be2c683afa8", 7084332),
+	ENGLISH_ENTRY("goodsantabadsanta", "X-Mags.exe", "71ca0d6c1c699595f28a2125948d4a84", 1966547),
+	ENGLISH_ENTRY("gotalight", "gotalight.exe", "daa21f03e41b5d3e7fd7558be3f8616e", 4019593),
+	ENGLISH_ENTRY("gpslostadventure", "G.P.s Lost Adventure [Wells8892].exe", "06a03fe35791b0578068ab1873455463", 4181945),
+	ENGLISH_ENTRY("graveyard", "Graveyard.exe", "955b711b21d7a2df6af1bb0cccccbb08", 13699789),
+	ENGLISH_ENTRY("gremlin", "Gremlin.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 3962167),
+	ENGLISH_ENTRY("grizzlygooseofgosse", "Goose Fear.exe", "b69b5887e4a33a3b8588d52fed04b730", 32123559),
+	ENGLISH_ENTRY("grr", "Grr!.exe", "3128b9f90e2f954ba704414ae854d10b", 26753739),
+	ENGLISH_ENTRY("guardiansofgold", "Guardians of Gold.exe", "933200c8f306eccaaa484b1575da8528", 429166629),
+	ENGLISH_ENTRY("guyslug", "GuySlug.exe", "0710e2ec71042617f565c01824f0cf3c", 1959514),
+	ENGLISH_ENTRY("guyverquestiicronos", "Guyver Quest 2.exe", "465f972675db2da6040518221af5b0ba", 1138940),
+	ENGLISH_ENTRY("guyverquestishoadventure", "Guyver Quest.exe", "465f972675db2da6040518221af5b0ba", 774591),
+	ENGLISH_ENTRY("gville1", "GVILLE1.exe", "c1451c6631e1bf4de6d1ed3760ca1dc9", 2340624),
+	ENGLISH_ENTRY("hack", "Hack.exe", "f120690b506dd63cd7d1112ea6af2f77", 4384638),
+	ENGLISH_ENTRY("halloween", "Halloween.exe", "3128b9f90e2f954ba704414ae854d10b", 5130336),
+	ENGLISH_ENTRY("halloweenhorror", "Halloween.exe", "06a03fe35791b0578068ab1873455463", 33740975),
+	ENGLISH_ENTRY("hallwayofadventures", "Hallway.exe", "0710e2ec71042617f565c01824f0cf3c", 7085407),
+	ENGLISH_ENTRY("hangon", "HangOn.exe", "6e861b1f476ff7cdf036082abb271329", 4203208),
+	ENGLISH_ENTRY("hansenhotel", "Hotel.exe", "3128b9f90e2f954ba704414ae854d10b", 4006863),
+	ENGLISH_ENTRY("happyduckieadventure", "HDA.exe", "f120690b506dd63cd7d1112ea6af2f77", 1924654),
+	ENGLISH_ENTRY("hardspaceconquestofthegayliks", "Hard Space!.exe", "3ecd04c0e0df079ff906ec4696d5fe23", 11494382),
+	ENGLISH_ENTRY("harrys21stbirthday", "harold.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 3525444),
+	ENGLISH_ENTRY("haventhesmallworld", "A small world.exe", "b142b43c146c25443a1d155d441a6a81", 43019171),
+	ENGLISH_ENTRY("heartlanddeluxever11", "Heartland.exe", "0829f8e184ed6a4bf36b14ba42003a67", 6702004),
+	ENGLISH_ENTRY("heartlandver12", "Heartland V1.2.exe", "261d108f9213356a351b35b54867f342", 21237374),
+	ENGLISH_ENTRY("heavymetalnannulfthestrangestage", "NannulfMAGS.exe", "3c5bd1713959ff469cb46ebe5542cfcf", 21272417),
+	ENGLISH_ENTRY("heed", "Heed.exe", "e8b2a430042709f07183c2c249e0e0d9", 6300045),
+	ENGLISH_ENTRY("helpthegame", "HELP.exe", "06a03fe35791b0578068ab1873455463", 3686323),
+	ENGLISH_ENTRY("henkstroemlostincellar", "Henk_LIC.exe", "3128b9f90e2f954ba704414ae854d10b", 1391240),
+	ENGLISH_ENTRY("henman", "hen-man.exe", "615e73fc1874e92d60a1996c2330ea36", 19556067),
+	ENGLISH_ENTRY("hesgonehistorical", "His.exe", "465f972675db2da6040518221af5b0ba", 5768754),
+	ENGLISH_ENTRY("hhgtgtowelday", "TowelDay.exe", "18456f28d9bf843b087e80072c85beca", 5431338),
+	ENGLISH_ENTRY("hiddenplains", "eureka02.exe", "6afafd26476d17a5e2a8e41f690d3720", 384360829),
+	ENGLISH_ENTRY("hiddentreasureryansfortune", "HiddenTRF.exe", "504df40bf50a0859e3dc15b000dab5f6", 7345149),
+	ENGLISH_ENTRY("hide", "Hide.exe", "6e861b1f476ff7cdf036082abb271329", 13701886),
+	ENGLISH_ENTRY("hiliaderoleagainsthell", "Dark Trial demo.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 36442694),
+	ENGLISH_ENTRY("him", "twin.exe", "6b4ceb9e327ac99479c08d825461f4cb", 23721672),
+	ENGLISH_ENTRY("hitchhikersguidetothegalaxyremake", "HHGTG.exe", "e003041f4332f136920e636e39d3e127", 34956191),
+	ENGLISH_ENTRY("hitthefreak", "HTF.EXE", "f3a13b2d6c2e0fe04c6f466062920e23", 3103477),
+	ENGLISH_ENTRY("hlobb", "Boxing.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 9544151),
+	ENGLISH_ENTRY("hood", "hood.exe", "97d700529f5cc826f230c27acf81adfd", 1575198),
+	ENGLISH_ENTRY("hope", "Hope.exe", "f92eba780bd1177612e264263d34c555", 4195489),
+	ENGLISH_ENTRY("horseparkdeluxe", "Horse Park DeLuxe.exe", "089fab88e6e1075a2f5b271f6f5b3c57", 22491099),
+	ENGLISH_ENTRY("hotel", "Hotel.exe", "615e73fc1874e92d60a1996c2330ea36", 29586297),
+	ENGLISH_ENTRY("hotelhijinks", "HH.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 1490538),
+	ENGLISH_ENTRY("houseofhorror", "The House of Horror.exe", "c20fee88ad37d2d21837eee9d34f2dbe", 10120651),
+	ENGLISH_ENTRY("howmany", "How many.exe", "089fab88e6e1075a2f5b271f6f5b3c57", 5925931),
+	ENGLISH_ENTRY("howtheyfoundsilence", "How They Found Silence.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 5322796),
+	ENGLISH_ENTRY("huongjiaoping", "hotpot.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 47237302),
+	ENGLISH_ENTRY("huxzadventure", "Huxsadv.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 2053897),
+	ENGLISH_ENTRY("hydeandseek", "Hyde and Seek.exe", "c2f495a688dc19e66362657dee9aa895", 28066547),
+	ENGLISH_ENTRY("iaman00b11omgwtflol", "DadGame.exe", "3018c5443291aec823bc63342ce4c58b", 6073887),
+	ENGLISH_ENTRY("iamjason", "IAMJASON.exe", "e8985d9ffbfa1eda77f2eb8d1331944a", 4843842),
+	ENGLISH_ENTRY("iforgot", "Forgot.exe", "6aa30185326552359c7865e55c045a74", 7743871),
+	ENGLISH_ENTRY("igs", "IGS.exe", "95b7dd55f6e15c8a2118856ed9fe8ff9", 1204802),
+	ENGLISH_ENTRY("iiispy", "IIISpy.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 6696286),
+	ENGLISH_ENTRY("illuminationdiminishing", "IlluminationDiminishing.exe", "b142b43c146c25443a1d155d441a6a81", 49006319),
+	ENGLISH_ENTRY("illuminationdiminishing", "IlluminationDiminishing.exe", "b142b43c146c25443a1d155d441a6a81", 21227029),
+	ENGLISH_ENTRY("illuminationdiminishing", "IlluminationDiminishing.exe", "b142b43c146c25443a1d155d441a6a81", 49006279),
+	ENGLISH_ENTRY("imnotcrazyrightthecell", "I'm not crazy.exe", "9cb3c8dc7a8ab9c44815955696be2677", 3152216),
+	ENGLISH_ENTRY("imnotcrazyrightthewell", "The Well.exe", "9cb3c8dc7a8ab9c44815955696be2677", 5000358),
+	ENGLISH_ENTRY("indianajonescomingofage", "IndyCOA.exe", "90413e9ae57e222f8913b09d2bc847bc", 2368083),
+	ENGLISH_ENTRY("indycositalianver", "CoSdemo2.1-it.exe", "f120690b506dd63cd7d1112ea6af2f77", 5772985),
+	ENGLISH_ENTRY("infectionepii", "Infection_Ep_II_AGS.exe", "a524cbb1c51589903c4043b98917f1d9", 23691417),
+	ENGLISH_ENTRY("infectionitheship", "Infection I.exe", "7132ff7d6b0bc1e9f3e4bd4755390626", 25974295),
+	ENGLISH_ENTRY("inferno", "inf.exe", "97d700529f5cc826f230c27acf81adfd", 8783105),
+	ENGLISH_ENTRY("infinitemonkeys", "InfiniteMonkeys.exe", "4d7d2addcde045dae6e0363a43f9acad", 4841557),
+	ENGLISH_ENTRY("insidemonkeyisland", "MIIM.exe", "06a03fe35791b0578068ab1873455463", 5186306),
+	ENGLISH_ENTRY("insidemonkeyisland2cap", "MIIM2.exe", "06a03fe35791b0578068ab1873455463", 5885525),
+	ENGLISH_ENTRY("inspectorgismoe", "police.exe", "465f972675db2da6040518221af5b0ba", 2899579),
+	ENGLISH_ENTRY("integerbattleship", "intbattl.exe", "0500aacb6c176d47ac0f8158f055db83", 4158273),
+	ENGLISH_ENTRY("intergalacticspacepancake", "space.exe", "97d700529f5cc826f230c27acf81adfd", 1797309),
+	ENGLISH_ENTRY("intothelight", "ITL.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 12146182),
+	ENGLISH_ENTRY("invincibleisland", "Invincible.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 4218160),
+	ENGLISH_ENTRY("isnkill", "ISN.exe", "4d17844029d8910fbaae1bdc99e250f2", 7932669),
+	ENGLISH_ENTRY("isos", "ISOS.exe", "06a03fe35791b0578068ab1873455463", 7362937),
+	ENGLISH_ENTRY("itsabugslife", "It's a Bugs Life.exe", "c48d0beedcdc1b05e9e25dcd60de46a9", 201172081),
+	ENGLISH_ENTRY("iwalkedapath", "I walked a path.exe", "fd3ecd8289bebadbf775fe8a13b9c5d7", 89018261),
+	ENGLISH_ENTRY("iwantout", "I_want_out!.exe", "c2cb8ff1ad3028b08fd3dab91578b934", 22218677),
+	ENGLISH_ENTRY("iwwhiiwwhitomirotpgthegame", "IWWHIIWWHITOMIROTPG - The Game.exe", "5fd79c32d2b8bbd589f6254d611d2742", 3576019),
+	ENGLISH_ENTRY("jacob", "Jacob.exe", "90413e9ae57e222f8913b09d2bc847bc", 7101001),
+	ENGLISH_ENTRY("jacquelinewhitecurseofthemummies", "CurseOfTheMummies.exe", "e9bdea51db49da499c69e8c21a821a7f", 193723250),
+	ENGLISH_ENTRY("jamesbond", "platform2.exe", "949f7440e3692b7366c2029979dee9a0", 4467701),
+	ENGLISH_ENTRY("jamesinneverland", "JamesNeverland.exe", "06a03fe35791b0578068ab1873455463", 36488607),
+	ENGLISH_ENTRY("jamesperis", "James1.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 85631684),
+	ENGLISH_ENTRY("jamesperis2demo", "James2.exe", "06a03fe35791b0578068ab1873455463", 35766505),
+	ENGLISH_ENTRY("javelincatch", "JvlnCtch.exe", "3421b46ff95c5885603086c39a038a20", 1626263),
+	ENGLISH_ENTRY("jimmsquestiii", "JQ3.EXE", "0b7529a76f38283d6e850b8d56526fc1", 4930906),
+	ENGLISH_ENTRY("jimmysday", "jimmy.exe", "089fab88e6e1075a2f5b271f6f5b3c57", 13419394),
+	ENGLISH_ENTRY("jimmythetroublemaker", "Jimmy The Troublemaker.exe", "25976a689b0f4d73eac69b1728377ecb", 200843118),
+	ENGLISH_ENTRY("joeshorriblehell", "Joe's Horrible Hell.exe", "cdcc787023c51c6fc9ffc17118f6adff", 61061393),
+	ENGLISH_ENTRY("joesmiserablelife", "Joe's Miserable Life.exe", "1b9f13d430bb15bf30d0fd044358db68", 36705304),
+	ENGLISH_ENTRY("johnharrissafrakincse", "totp.exe", "74dc062c5f68f3d70da911f2db5737b6", 36463878),
+	ENGLISH_ENTRY("johnjebediahgunelisoladisepheret", "JJG.exe", "a28cb95e1769ba1bfa48f850390746c2", 88957123),
+	ENGLISH_ENTRY("johnnyrocket", "Rocket.exe", "a524cbb1c51589903c4043b98917f1d9", 10366294),
+	ENGLISH_ENTRY("johnsinclairvoodooinlondon", "John Sinclair - Voodoo in London.exe", "d72e72697a755c7de395b0f6c8cbbf0d", 56795991),
+	ENGLISH_ENTRY("jonnysmallvalley", "Jonny Smallvalley.exe", "01d0e6bd812abaa307bcb10fc2193416", 34437869),
+	ENGLISH_ENTRY("jorry", "JORRY DEMO.exe", "fe5f7dc7785b335aec72a2a834629bad", 124667001),
+	ENGLISH_ENTRY("juliusdangerous2", "Julius Dangerous 2.exe", "e2d4a98de69b1f8e6462c387710a441a", 146931732),
+	ENGLISH_ENTRY("juliusdangerousandthespaceinvaders", "Julius Dangerous.exe", "ddaf3807f1fe16b2813ff832b4fb471a", 83137140),
+	ENGLISH_ENTRY("justanotherpointnclickadventure", "Advent.exe", "6a98b4cc2f5a55421248be53f15a6a99", 9582620),
+	ENGLISH_ENTRY("justignorethem", "justignorethem.exe", "7a3096ac0237cb6aa8e1718e28caf039", 98544330),
+	ENGLISH_ENTRY("kanjigakusei", "KanjiGakusei.exe", "c1bce0ccfa858f0f5d2fe19997d89b05", 17604764),
+	ENGLISH_ENTRY("kartquestv053", "Kart.exe", "465f972675db2da6040518221af5b0ba", 77317312),
+	ENGLISH_ENTRY("keptoshi", "Keptosh.exe", "95b7dd55f6e15c8a2118856ed9fe8ff9", 2904848),
+	ENGLISH_ENTRY("keys", "Keys.exe", "75f4c7f66b1be60af5b2d65f617b91a7", 85582285),
+	ENGLISH_ENTRY("killereye", "killereye.exe", "0710e2ec71042617f565c01824f0cf3c", 1009042),
+	ENGLISH_ENTRY("killjoseda", "KillJD.exe", "20dc02a8f977caf5c4dc6f2a4c8d4378", 6034414),
+	ENGLISH_ENTRY("killthelights", "Kill The Lights.exe", "9b54ea3557373188d8388ec4d1ae5eed", 20416736),
+	ENGLISH_ENTRY("kingdomlegends", "Kingdom Legends.exe", "06a03fe35791b0578068ab1873455463", 2254139),
+	ENGLISH_ENTRY("kingsquestiii", "KQ3.exe", "f120690b506dd63cd7d1112ea6af2f77", 5883843),
+	ENGLISH_ENTRY("kinkyislanddemo", "KINKY.exe", "f120690b506dd63cd7d1112ea6af2f77", 10628479),
+	ENGLISH_ENTRY("knightquestforgoldenring", "KQuestGoldRing.exe", "f120690b506dd63cd7d1112ea6af2f77", 2582542),
+	ENGLISH_ENTRY("knightsquestiii", "KQ3TOM.exe", "0710e2ec71042617f565c01824f0cf3c", 8408641),
+	ENGLISH_ENTRY("knightsquestiv", "MAGSQuest.exe", "0500aacb6c176d47ac0f8158f055db83", 4074151),
+	ENGLISH_ENTRY("koddurova", "Kod Durova.exe", "615e73fc1874e92d60a1996c2330ea36", 498427333),
+	ENGLISH_ENTRY("koffeekrisis", "Koffee Krisis.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 2423111),
+	ENGLISH_ENTRY("koscheitheimmortal", "Koschei.exe", "465f972675db2da6040518221af5b0ba", 2771442),
+	ENGLISH_ENTRY("kristmaskrisis", "Kristmas Krisis.exe", "90413e9ae57e222f8913b09d2bc847bc", 2067681),
+	ENGLISH_ENTRY("ktx1", "KTX-1.exe", "615e73fc1874e92d60a1996c2330ea36", 13806290),
+	ENGLISH_ENTRY("kumastory", "Kuma Story.exe", "54e966a013d104bf23603c780438d089", 2893472),
+	ENGLISH_ENTRY("labor", "LaborEN.exe", "b9fcd61691d19d954a5cfd5fb57a6b45", 7245344),
+	ENGLISH_ENTRY("labratescape", "Joel.exe", "06a03fe35791b0578068ab1873455463", 3256136),
+	ENGLISH_ENTRY("labyrinth", "labyrnth.exe", "0710e2ec71042617f565c01824f0cf3c", 7686481),
+	ENGLISH_ENTRY("lacicuta1", "Cicuta1.exe", "1290e191d4f24893ce83ba0af5debd9e", 8665956),
+	ENGLISH_ENTRY("lacroixpan", "La Croix Pan.exe", "d9018b1792f6d959d7add4dc3f7cdb46", 12102643),
+	ENGLISH_ENTRY("laffaireaspirox", "L'Affaire Aspirox.exe", "23a67b6de10ec35e9f5a4dfc7d928222", 139865345),
+	ENGLISH_ENTRY("lagrancastanya", "PROJECT1.exe", "c87aa6377abc18c1a1b2968ae6db08eb", 39298012),
+	ENGLISH_ENTRY("lallaveyfabianshones", "LLAVE.exe", "a8d73d686b2eb77caab8c05e3e1f1d57", 3374527),
+	ENGLISH_ENTRY("laodiseadelfracasoii", "La Odisea II.exe", "0710e2ec71042617f565c01824f0cf3c", 3083622),
+	ENGLISH_ENTRY("laportenoire", "proute.exe", "06a03fe35791b0578068ab1873455463", 17087125),
+	ENGLISH_ENTRY("lastnfurious", "Last'n'Furious.exe", "3569271305cddb7156260cce9439e543", 17696093),
+	ENGLISH_ENTRY("laundryday", "Laundry Day.exe", "06a03fe35791b0578068ab1873455463", 2456888),
+	ENGLISH_ENTRY("lavablava", "Rumble.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 2294674),
+	ENGLISH_ENTRY("lazaruswantspants", "pants.exe", "9cf51833e787cc919837d9a8bd8fc14c", 1311852),
+	ENGLISH_ENTRY("lazytownthenewkiddemo", "newkiddemo1.2.exe", "9cb3c8dc7a8ab9c44815955696be2677", 15515508),
+	ENGLISH_ENTRY("lbstoryofcedrickdusce", "lifeboat.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 3563681),
+	ENGLISH_ENTRY("legendofrovendale", "Vampire.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 10018497),
+	ENGLISH_ENTRY("legendofseththebard", "LOSTB 1.48.exe", "a524cbb1c51589903c4043b98917f1d9", 10669482),
+	ENGLISH_ENTRY("legendsofmardaram", "LOM.exe", "0710e2ec71042617f565c01824f0cf3c", 50183544),
+	ENGLISH_ENTRY("leisuresuitlarry2", "Larry 2.exe", "949f7440e3692b7366c2029979dee9a0", 11971760),
+	ENGLISH_ENTRY("leisuresuitlarrylil", "LSL.exe", "34cf71d28e1e9c55934f624969011c7e", 18440862),
+	ENGLISH_ENTRY("lesmiserables", "Les Miserables.exe", "0514661a4ba6772cf0db0cf839fc7003", 127582664),
+	ENGLISH_ENTRY("lessurvivants", "Les_Survivants.exe", "c5d2c54c20cb606519b86d3890ee7fc0", 265445972),
+	ENGLISH_ENTRY("lichdomwheresdidiputthat", "Lichdom.exe", "0e6ae2b49c1a38363a77024f3ce31771", 7412719),
+	ENGLISH_ENTRY("life", "Life.exe", "97a2a2feb82708da8f6ed30c15a7eb53", 43833851),
+	ENGLISH_ENTRY("lifeboatstoryofcedrick", "lifeboat.exe", "3128b9f90e2f954ba704414ae854d10b", 2952689),
+	ENGLISH_ENTRY("lifeofdduck", "D Duck.exe", "0710e2ec71042617f565c01824f0cf3c", 49461615),
+	ENGLISH_ENTRY("lifeofdduckii", "D. Duck II.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 135923689),
+	ENGLISH_ENTRY("liftreasureofthetanones", "Lif.exe", "18b284c22010850f79bc5c20054a70c4", 3946641),
+	ENGLISH_ENTRY("lightcycles", "LightCycles.exe", "495d45fb8adfd49690ae3b97921feec6", 3415108),
+	ENGLISH_ENTRY("lightningmaster", "Master.exe", "27343924ddad3be0b97bdcaa71858b1b", 231301393),
+	ENGLISH_ENTRY("likeafox", "likeafox.exe", "c7916b82f00c94013a3f7706b4d333c6", 2707737),
+	ENGLISH_ENTRY("limbo", "Limbo Adventure.exe", "7c10efb8990fb48ded51fbcd88a6bf17", 30800724),
+	ENGLISH_ENTRY("limeylizardwastewizard", "LLWW.exe", "fab982fd31570655ac3b1858bd8265e4", 33755872),
+	ENGLISH_ENTRY("litnunforgettablememories", "litn_umtechdemo.exe", "f120690b506dd63cd7d1112ea6af2f77", 3507831),
+	ENGLISH_ENTRY("littlegirlinunderland", "Underland.exe", "06a03fe35791b0578068ab1873455463", 10125940),
+	ENGLISH_ENTRY("livingnightmaredeluxe", "Living Nightmare.exe", "4415d633ea1a2dcd03ff0eff43f182ee", 9997554),
+	ENGLISH_ENTRY("livingnightmareendlessdream", "LNED.exe", "4415d633ea1a2dcd03ff0eff43f182ee", 10671309),
+	ENGLISH_ENTRY("livingnightmarefreedom", "LNF.exe", "6aa30185326552359c7865e55c045a74", 26580184),
+	ENGLISH_ENTRY("lockedout", "locked-out.exe", "465f972675db2da6040518221af5b0ba", 1930862),
+	ENGLISH_ENTRY("loftusandtheskycap", "loftus.exe", "4c83816b87e6e253dc8e324e89bcbca3", 24333349),
+	ENGLISH_ENTRY("lonecase", "LoneCase.exe", "8661936f40669fa1672dced4df0521a0", 3550717),
+	ENGLISH_ENTRY("lonecase2", "Lone Case 2.exe", "cb3bbab6e565fcbd57af8f33a8609210", 6015178),
+	ENGLISH_ENTRY("lonecase3showdown", "lc 3.exe", "893df6568c294926f7efa3f3ec2ce14d", 7997004),
+	ENGLISH_ENTRY("lonelynight", "Lonely night.exe", "0710e2ec71042617f565c01824f0cf3c", 2488077),
+	ENGLISH_ENTRY("longexpectedfriday", "LEFRIDAY.exe", "28f82e420b82d07651b68114f90223c8", 7595812),
+	ENGLISH_ENTRY("lonkeyisland", "lonkey.exe", "4e92c6db88a34b62eef37a621aabfb53", 44134488),
+	ENGLISH_ENTRY("loomiireturnoftheswans", "loom2.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 9761097),
+	ENGLISH_ENTRY("losjovenesdelaguerra", "guerra.exe", "97d700529f5cc826f230c27acf81adfd", 4286035),
+	ENGLISH_ENTRY("lostanswers", "Lost Answers.exe", "c88de182eae58fdb43e5b4e587095ff5", 254684884),
+	ENGLISH_ENTRY("lostinparadise", "2paradise.exe", "06a03fe35791b0578068ab1873455463", 37279978),
+	ENGLISH_ENTRY("lostinthenightmare", "litn.exe", "0710e2ec71042617f565c01824f0cf3c", 5492994),
+	ENGLISH_ENTRY("lostinthenightmare", "litn.exe", "0710e2ec71042617f565c01824f0cf3c", 5493239),
+	ENGLISH_ENTRY("lostinthewoods", "LITW.exe", "00328f4f1e7729144483107b96b11df8", 55203461),
+	ENGLISH_ENTRY("lucidlucy", "LUCID LUCY.exe", "655363c390c7ae7225c237108edf50b7", 182038828),
+	ENGLISH_ENTRY("lucylavender", "Lucy.exe", "c87aa6377abc18c1a1b2968ae6db08eb", 7944054),
+	ENGLISH_ENTRY("lukesexistentialnightmare", "Lukeexit.exe", "95b7dd55f6e15c8a2118856ed9fe8ff9", 653834),
+	ENGLISH_ENTRY("lunarlanderprototype", "LunarLanderPrototype.exe", "495d45fb8adfd49690ae3b97921feec6", 3510282),
+	ENGLISH_ENTRY("lydiaandthemysteryofnellrenomanor", "LydiaW.exe", "615e73fc1874e92d60a1996c2330ea36", 33971307),
+	ENGLISH_ENTRY("maggieandmax", "Max.exe", "465f972675db2da6040518221af5b0ba", 5759981),
+	ENGLISH_ENTRY("magic8ball", "Magic-8-Ball.exe", "82da2565c456dcfb265ded6fe3189c0b", 4233735),
+	ENGLISH_ENTRY("magicalwhatevergirlrocksoutinthestoneage", "mwg.exe", "b2b99b5b3dcaee0fa292343c5a2c429b", 7784104),
+	ENGLISH_ENTRY("magicballoffortune", "Magic Ball.exe", "f120690b506dd63cd7d1112ea6af2f77", 6016698),
+	ENGLISH_ENTRY("magnumpm", "Magnum, P.M.exe", "06a03fe35791b0578068ab1873455463", 91711892),
+	ENGLISH_ENTRY("magsgame", "MAGSGAME.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 5025809),
+	ENGLISH_ENTRY("magsic", "Magsic.exe", "7a436b9a2e8e80c8aaaeed09ef9e3d3d", 22360144),
+	ENGLISH_ENTRY("magsicii", "MagsicII.exe", "28f82e420b82d07651b68114f90223c8", 30029761),
+	ENGLISH_ENTRY("magsjan", "MAGS-Jan.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 16729569),
+	ENGLISH_ENTRY("magsjune2017", "MAGS june 2017.exe", "e3962995a70923a8d5a8f1cf8f932eee", 304129558),
+	ENGLISH_ENTRY("magssep2007", "MAGS Sep 2007.exe", "f120690b506dd63cd7d1112ea6af2f77", 6007305),
+	ENGLISH_ENTRY("manboy", "Man Boy.exe", "1275885401b7d2ece491e704535707d9", 3038532),
+	ENGLISH_ENTRY("maniacmansiondeluxe", "Maniac.exe", "465f972675db2da6040518221af5b0ba", 10409172),
+	ENGLISH_ENTRY("maniacmansionmania", "MMM.exe", "465f972675db2da6040518221af5b0ba", 5476481),
+	ENGLISH_ENTRY("maniacmansionmania02", "MMM02.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 5830457),
+	ENGLISH_ENTRY("mardsrevengebytk", "MPLR.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 1771793),
+	ENGLISH_ENTRY("martyausdemall", "test3.exe", "0710e2ec71042617f565c01824f0cf3c", 4352013),
+	ENGLISH_ENTRY("mastersofsound", "MOS.exe", "bb59de174d70797d774dec76a171352d", 20298343),
+	ENGLISH_ENTRY("matttothefuture", "MTTF.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 5560975),
+	ENGLISH_ENTRY("medicaltheoriesofdrkur", "dfg.exe", "465f972675db2da6040518221af5b0ba", 3140527),
+	ENGLISH_ENTRY("mego2008silvesteredition", "Me Go Store III.exe", "06a03fe35791b0578068ab1873455463", 12040937),
+	ENGLISH_ENTRY("megoaway", "Me Go Store II.exe", "06a03fe35791b0578068ab1873455463", 6640781),
+	ENGLISH_ENTRY("megocannibaljungle", "mgcj.exe", "06a03fe35791b0578068ab1873455463", 7127871),
+	ENGLISH_ENTRY("megostore", "Me Go Store.exe", "90413e9ae57e222f8913b09d2bc847bc", 2961962),
+	ENGLISH_ENTRY("melrinthediscipleordeal", "Melrin.exe", "803e65c28364b6bf44b7c4610fcdaa5a", 12822475),
+	ENGLISH_ENTRY("melrinthedragonmenace", "Melrin3.exe", "803e65c28364b6bf44b7c4610fcdaa5a", 5802221),
+	ENGLISH_ENTRY("melrinthependantquest", "Melrin2.exe", "803e65c28364b6bf44b7c4610fcdaa5a", 4372768),
+	ENGLISH_ENTRY("meltdrake3chapter1", "CaK3.exe", "97d700529f5cc826f230c27acf81adfd", 6044911),
+	ENGLISH_ENTRY("memoriesfade", "MemoriesFade.exe", "d5d028212a242a9841feff24ec3db3c9", 7996519),
+	ENGLISH_ENTRY("meninhats", "GAME.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 1646510),
+	ENGLISH_ENTRY("merrychristmas", "Merry Christmas.exe", "172b30c282856b382464bed5fcb61e29", 4812266),
+	ENGLISH_ENTRY("messedupmothergoosedeluxemyassenhanced", "MMG.exe", "d642f2110a3dc0c48ab7b13f69b5caf6", 36523450),
+	ENGLISH_ENTRY("meta", "META.exe", "06a03fe35791b0578068ab1873455463", 10113135),
+	ENGLISH_ENTRY("meteorfamily20", "Meteor Family.exe", "06a03fe35791b0578068ab1873455463", 5759077),
+	ENGLISH_ENTRY("meteorheadrecycled", "Meteorhead.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 5081311),
+	ENGLISH_ENTRY("mi5thereturnoflechuck", "Demo.exe", "0500aacb6c176d47ac0f8158f055db83", 6235270),
+	ENGLISH_ENTRY("mibaddaytobedead", "Monkey.exe", "f120690b506dd63cd7d1112ea6af2f77", 2117238),
+	ENGLISH_ENTRY("micarnivalofthedamned", "MI-COD.exe", "90413e9ae57e222f8913b09d2bc847bc", 5114086),
+	ENGLISH_ENTRY("mickeymauserpart1", "MM.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 12076323),
+	ENGLISH_ENTRY("midastouch", "midastouch.exe", "6e861b1f476ff7cdf036082abb271329", 10810464),
+	ENGLISH_ENTRY("mikelechey", "Mike Lechey.exe", "06a03fe35791b0578068ab1873455463", 2349277),
+	ENGLISH_ENTRY("mikesroom2", "Mikes_late.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 5001254),
+	ENGLISH_ENTRY("milkshake", "Milkshake.exe", "615e806856b7730afadf1fea9a756b70", 1656268),
+	ENGLISH_ENTRY("mindboggler", "Rebel.exe", "847ca9d174cd091b7a1b82f032bdd052", 36979705),
+	ENGLISH_ENTRY("mindseye", "MindsEye.exe", "8a84eb07f484540ecc59ea80bf21dc9e", 30024175),
+	ENGLISH_ENTRY("minigame3", "Mini Game 3.exe", "465f972675db2da6040518221af5b0ba", 3455484),
+	ENGLISH_ENTRY("minigame4", "Mini Game 4.exe", "465f972675db2da6040518221af5b0ba", 4954264),
+	ENGLISH_ENTRY("missingsincemidnight", "msm.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 7989479),
+	ENGLISH_ENTRY("mistdelaescueladearte", "EA.exe", "465f972675db2da6040518221af5b0ba", 6732362),
+	ENGLISH_ENTRY("mixertest", "mixertest.exe", "0b7529a76f38283d6e850b8d56526fc1", 798369),
+	ENGLISH_ENTRY("mmm15ortmaschine", "MMM15.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 8957215),
+	ENGLISH_ENTRY("mmm4mimikryderemotionen", "mmm.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 8368739),
+	ENGLISH_ENTRY("mmmderklausschlgtzurck", "MMM-dksz.exe", "c1df737ef943e6e3cc09d36fcd4b1ed0", 8689677),
+	ENGLISH_ENTRY("mmmepisode8", "MMM - E8.exe", "45ab4f29031b50c8d01d10a269f77ff5", 5095385),
+	ENGLISH_ENTRY("mmmradioaktiv", "mmm_radioactive.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 7665414),
+	ENGLISH_ENTRY("moncul", "moncul.exe", "0710e2ec71042617f565c01824f0cf3c", 1493822),
+	ENGLISH_ENTRY("monkeystothemoon", "Monkeys to the Moon.exe", "77d91b65ff03c1f3a8381e39c7f693cb", 8720439),
+	ENGLISH_ENTRY("monkeywrench", "monkeywrench.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 27454116),
+	ENGLISH_ENTRY("monsterfromthehountedhill", "Monster.exe", "465f972675db2da6040518221af5b0ba", 6197451),
+	ENGLISH_ENTRY("moonlightmoggy", "Moggy.exe", "0a6704159f6f716ac80da91c430430ce", 13336128),
+	ENGLISH_ENTRY("moose", "MOOSE.exe", "95b7dd55f6e15c8a2118856ed9fe8ff9", 4732219),
+	ENGLISH_ENTRY("moose2", "MOOSE2.exe", "95b7dd55f6e15c8a2118856ed9fe8ff9", 1251361),
+	ENGLISH_ENTRY("mordimlaufrad", "MordImLaufrad.exe", "18b284c22010850f79bc5c20054a70c4", 4396809),
+	ENGLISH_ENTRY("mordy2", "Mordy2.exe", "0710e2ec71042617f565c01824f0cf3c", 5186329),
+	ENGLISH_ENTRY("mothersday", "mothersday.exe", "0b7529a76f38283d6e850b8d56526fc1", 1816363),
+	ENGLISH_ENTRY("motlpaa", "MOTLPAA.exe", "0710e2ec71042617f565c01824f0cf3c", 1575258),
+	ENGLISH_ENTRY("mourirenmer", "Mourir.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 2519706),
+	ENGLISH_ENTRY("mrbee", "BEE.exe", "95dcf736be87cf7d40bf64d5b078c4b7", 45542087),
+	ENGLISH_ENTRY("mrdangerscontest", "Danger.exe", "06a03fe35791b0578068ab1873455463", 7096987),
+	ENGLISH_ENTRY("murderinthemansion", "MitM 1.2.exe", "27df05bd72589a589c054d11d6d03c0f", 9758713),
+	ENGLISH_ENTRY("murderofadrianelkwood", "elkwood.exe", "06a03fe35791b0578068ab1873455463", 3685153),
+	ENGLISH_ENTRY("murphyssalvagejustmyluck", "space.exe", "f8029b1e9ff5ac01ae23896af44e885a", 51351465),
+	ENGLISH_ENTRY("murranchronicles1", "Jersey Devil.exe", "06a03fe35791b0578068ab1873455463", 20555872),
+	ENGLISH_ENTRY("murranchronicles2", "Talons.exe", "06a03fe35791b0578068ab1873455463", 17613066),
+	ENGLISH_ENTRY("mysterioushouse", "mh.exe", "495d45fb8adfd49690ae3b97921feec6", 42400316),
+	ENGLISH_ENTRY("mysticseer", "NickOfTime.exe", "f120690b506dd63cd7d1112ea6af2f77", 4460113),
+	ENGLISH_ENTRY("mythicalgambitflawlessfatality", "MGFF.exe", "4887d3dca056a0772741b42f66e018fb", 59711760),
+	ENGLISH_ENTRY("nanobots", "Nanobots.exe", "95dcf736be87cf7d40bf64d5b078c4b7", 41977727),
+	ENGLISH_ENTRY("necroquest", "necroquest01.exe", "6d4adcef07a14b53369d23edf5117252", 12389204),
+	ENGLISH_ENTRY("necroquest", "necroquest01.exe", "2d111a69de0723f337bad661cb006239", 9545924),
+	ENGLISH_ENTRY("nedysadventure", "Nedy.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 6463558),
+	ENGLISH_ENTRY("nekusnewtrip", "nnt.exe", "c0c1865c3c8369e034095a725ca1ddbf", 35012412),
+	ENGLISH_ENTRY("nekusnewtrip", "square enix.exe", "a524cbb1c51589903c4043b98917f1d9", 10630694),
+	ENGLISH_ENTRY("newgame", "Newgame.exe", "0b7529a76f38283d6e850b8d56526fc1", 1453831),
+	ENGLISH_ENTRY("nellycootalotv15", "Nelly Cootalot.exe", "18b284c22010850f79bc5c20054a70c4", 108256323),
+	ENGLISH_ENTRY("neofeud", "Neofeud Demo.exe", "6e861b1f476ff7cdf036082abb271329", 1886913453),
+	ENGLISH_ENTRY("nesquest", "NES Quest.exe", "8b72036706da98095057df615d07460b", 20881972),
+	ENGLISH_ENTRY("news", "WI-AA.exe", "06a03fe35791b0578068ab1873455463", 29631312),
+	ENGLISH_ENTRY("nickitandrun", "NIAREnglish.exe", "b25674056fe8cc0b7bf0a4409c5c5bfc", 14180082),
+	ENGLISH_ENTRY("nightoftheravingfeminist", "Prueba1.exe", "b25674056fe8cc0b7bf0a4409c5c5bfc", 7015243),
+	ENGLISH_ENTRY("nightwork", "Nightwork.exe", "f10516e88ec858700804ee69d041aead", 23059420),
+	ENGLISH_ENTRY("noactionjackson", "current.exe", "3128b9f90e2f954ba704414ae854d10b", 28343366),
+	ENGLISH_ENTRY("noahsquest", "Noah's Quest.exe", "c48d0beedcdc1b05e9e25dcd60de46a9", 107188362),
+	ENGLISH_ENTRY("nobodycares", "Nobody Cares.exe", "618d7dce9631229b4579340b964c6810", 20897642),
+	ENGLISH_ENTRY("noiamspartacus", "spartacus.exe", "28f82e420b82d07651b68114f90223c8", 1133879),
+	ENGLISH_ENTRY("noisymountain", "NoisyMountainE.exe", "465f972675db2da6040518221af5b0ba", 8031142),
+	ENGLISH_ENTRY("nomonkeysbanana", "NMB.exe", "36f44e064eab15e502caeb60fd09f52d", 2750366),
+	ENGLISH_ENTRY("norbisquest", "Norbi's quest.exe", "3128b9f90e2f954ba704414ae854d10b", 4912333),
+	ENGLISH_ENTRY("norbisquest15", "Norbi 1,5.exe", "f120690b506dd63cd7d1112ea6af2f77", 5455598),
+	ENGLISH_ENTRY("norbisquest2", "Norbi 2.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 14114728),
+	ENGLISH_ENTRY("norbiwinterspecial", "NWS.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 10149860),
+	ENGLISH_ENTRY("normancooks", "NORMAN.exe", "4d17844029d8910fbaae1bdc99e250f2", 9397734),
+	ENGLISH_ENTRY("norserunereader", "NorseRuneReader.exe", "f120690b506dd63cd7d1112ea6af2f77", 2111273),
+	ENGLISH_ENTRY("noughtscrosses", "Noughts.exe", "615e73fc1874e92d60a1996c2330ea36", 2159904),
+	ENGLISH_ENTRY("oceanspiritdennisscourgeoftheunderworld", "Oceanspirit Dennis.exe", "18456f28d9bf843b087e80072c85beca", 2419770),
+	ENGLISH_ENTRY("odottamaton", "Odottamaton.exe", "9d9e5ea323793fc526b1533d78c4f9c6", 23822268),
+	ENGLISH_ENTRY("omnipotenttarot", "OmnipotentTarot.exe", "f120690b506dd63cd7d1112ea6af2f77", 7166774),
+	ENGLISH_ENTRY("onceuponacrime13b", "OUAC.exe", "6ee842f73649ced615c44d4eb303687c", 6580658),
+	ENGLISH_ENTRY("onceuponatime", "Oncetime.exe", "18b284c22010850f79bc5c20054a70c4", 11633390),
+	ENGLISH_ENTRY("one", "one.exe", "0710e2ec71042617f565c01824f0cf3c", 53482630),
+	ENGLISH_ENTRY("oneofakindadivinecomedyofmistakes", "OneOfAKind.exe", "a524cbb1c51589903c4043b98917f1d9", 4031186),
+	ENGLISH_ENTRY("onespytoomany", "One spy too many.exe", "c48d0beedcdc1b05e9e25dcd60de46a9", 70521403),
+	ENGLISH_ENTRY("oneweekoneroom", "1 week 1 room.exe", "06a03fe35791b0578068ab1873455463", 4275934),
+	ENGLISH_ENTRY("onleavingthebuilding", "On Leaving The Building.exe", "fd68fced8b89792d2e90be87b33d4b19", 64776995),
+	ENGLISH_ENTRY("onlythegooddieyoungenglishversion", "OtGDY_En.exe", "87ccd318a469128530699388f916b86f", 153980124),
+	ENGLISH_ENTRY("openquest", "OpenQuest.exe", "90413e9ae57e222f8913b09d2bc847bc", 3407165),
+	ENGLISH_ENTRY("operationnovi", "Operation Novi.exe", "465f972675db2da6040518221af5b0ba", 24583968),
+	ENGLISH_ENTRY("operationsavebluecup", "OSBC.exe", "f120690b506dd63cd7d1112ea6af2f77", 3040865),
+	ENGLISH_ENTRY("orangeman", "Orange man.exe", "c38d6846c402bfcdedcf5c34cd8bc3ee", 1960932),
+	ENGLISH_ENTRY("orowgame", "orowgame.exe", "0710e2ec71042617f565c01824f0cf3c", 15632750),
+	ENGLISH_ENTRY("osdarayofhope", "ray_of_hope.exe", "25976a689b0f4d73eac69b1728377ecb", 6595789),
+	ENGLISH_ENTRY("osdocd", "OSD-OCD.exe", "9dbf699a0e41550bb080813a233e73a8", 47758168),
+	ENGLISH_ENTRY("osdthelostworldep2", "OSD.TLW2.exe", "a80ae4d0aea21508f1df9d18f2839bcb", 22076715),
+	ENGLISH_ENTRY("osher", "Osher.exe", "18b284c22010850f79bc5c20054a70c4", 389177994),
+	ENGLISH_ENTRY("otakurivals", "Kintaro.exe", "465f972675db2da6040518221af5b0ba", 4045893),
+	ENGLISH_ENTRY("otherworlds", "Other Worlds.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 10669659),
+	ENGLISH_ENTRY("otisbuildsafire", "obaf.exe", "c8d330b58da0a00a136c52ed3a20ae23", 4260705),
+	ENGLISH_ENTRY("ouja", "Ouja.exe", "4d7d2addcde045dae6e0363a43f9acad", 6254682),
+	ENGLISH_ENTRY("outbreakbyabhijitkamat", "outbreak.exe", "0500aacb6c176d47ac0f8158f055db83", 3271348),
+	ENGLISH_ENTRY("outofgas", "OutOfGas.exe", "6b4ceb9e327ac99479c08d825461f4cb", 18187986),
+	ENGLISH_ENTRY("outofgas", "OutOfGas.exe", "f0e74b3673867316e1cb3120c4289c66", 18200877),
+	ENGLISH_ENTRY("overtheedge", "jdags.exe", "05f7ff300b322bc431e7cda6a07b5976", 235453751),
+	ENGLISH_ENTRY("owlsquest", "King.exe", "a6906aec8617b81af44cf9420731fc34", 3506408),
+	ENGLISH_ENTRY("palettequest2", "PaletteQuest2.exe", "2b7ae26333ba15529a8bbbdb49605133", 771805),
+	ENGLISH_ENTRY("pandainspace", "pandasp.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 14340176),
+	ENGLISH_ENTRY("pandor", "Pandor.exe", "a6dc66da890952431371b62659e58a62", 18995824),
+	ENGLISH_ENTRY("paradiselost", "larywilc.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 9061068),
+	ENGLISH_ENTRY("parameciumcomplex", "paramaecium.exe", "0500aacb6c176d47ac0f8158f055db83", 2805720),
+	ENGLISH_ENTRY("paranormalwarriorwithin", "BJWW.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 3538617),
+	ENGLISH_ENTRY("party", "Party.exe", "f120690b506dd63cd7d1112ea6af2f77", 1888987),
+	ENGLISH_ENTRY("patchwork", "Patchwork.exe", "bbadca125279cb808b4ed0ff4b31448d", 110767860),
+	ENGLISH_ENTRY("paulaimwunderland", "PaulaWunderland.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 2249299),
+	ENGLISH_ENTRY("paulmooseinspaceworld", "Paul Moose In Space World.exe", "089fab88e6e1075a2f5b271f6f5b3c57", 15971406),
+	ENGLISH_ENTRY("paulquest", "calle.exe", "06a03fe35791b0578068ab1873455463", 3055837),
+	ENGLISH_ENTRY("pennistheultimateinpong", "Pennis.exe", "28f82e420b82d07651b68114f90223c8", 939611),
+	ENGLISH_ENTRY("perilsofpoom", "Poom.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 10455126),
+	ENGLISH_ENTRY("pesterquest", "PQ.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 2381566),
+	ENGLISH_ENTRY("petalrose", "petalrose.exe", "949f7440e3692b7366c2029979dee9a0", 748315),
+	ENGLISH_ENTRY("pharmacistjones", "Pharmacist Jones.exe", "00bb363ccb0acfe57893dd3ba6f1719c", 8285817),
+	ENGLISH_ENTRY("pickpocketrpg", "Pickpocket RPG.exe", "82da2565c456dcfb265ded6fe3189c0b", 44540638),
+	ENGLISH_ENTRY("pilotlight", "Pilot.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 9707781),
+	ENGLISH_ENTRY("pimpinonparakuss", "Squest2.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 3717277),
+	ENGLISH_ENTRY("piratefry2", "FryTworedo.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 8492745),
+	ENGLISH_ENTRY("piratefry3", "tryout.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 2318881),
+	ENGLISH_ENTRY("piratess", "Piratess.exe", "f120690b506dd63cd7d1112ea6af2f77", 2043871),
+	ENGLISH_ENTRY("pixelhunt", "pixelhunt.exe", "057d1aa29f6fadd83209268efcfb35a3", 3321338),
+	ENGLISH_ENTRY("pixia", "Pixia.exe", "0710e2ec71042617f565c01824f0cf3c", 1286189),
+	ENGLISH_ENTRY("pixxxelhuntertheepic", "pixelhunter.exe", "0710e2ec71042617f565c01824f0cf3c", 1621107),
+	ENGLISH_ENTRY("plan10frommypants", "plan10.exe", "06a03fe35791b0578068ab1873455463", 8514311),
+	ENGLISH_ENTRY("planetxmas", "PlanetX.exe", "64fcaf7da0b257ea831f89c54be0ad72", 4430665),
+	ENGLISH_ENTRY("platformerius", "platformerius.exe", "a3ad5fa6463c0116a2ac8986841860e0", 1512479),
+	ENGLISH_ENTRY("platformhorde", "Platform Horde.exe", "49157a0ea75b960eded4d0811a71d3e9", 14991450),
+	ENGLISH_ENTRY("pleurghburgdarkages", "Pleurgh.exe", "9cf51833e787cc919837d9a8bd8fc14c", 11555983),
+	ENGLISH_ENTRY("plumberboy", "Plumberboy.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 4169240),
+	ENGLISH_ENTRY("pm-cute", "pm-cute.exe", "28f82e420b82d07651b68114f90223c8", 2728354),
+	ENGLISH_ENTRY("pmuvchvt", "PMUVCHVT.exe", "06a03fe35791b0578068ab1873455463", 5127419),
+	ENGLISH_ENTRY("pmxi", "PMXI.exe", "609aa4339aea63a0ebc1fd6a659e6d4f", 3164504),
+	ENGLISH_ENTRY("pocketfluffyay", "Pketfluf.exe", "0b7529a76f38283d6e850b8d56526fc1", 10858438),
+	ENGLISH_ENTRY("politicallyyours", "Politically Yours.exe", "031bce0ec1a563faffc19a62ea17e35f", 4640266),
+	ENGLISH_ENTRY("pong", "Pong.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 611249),
+	ENGLISH_ENTRY("postmansquest", "PQ.exe", "345685aaec400c69a1e6d5e18a63850c", 6896450),
+	ENGLISH_ENTRY("powernap", "powernap.exe", "615e73fc1874e92d60a1996c2330ea36", 13308487),
+	ENGLISH_ENTRY("powerunlimited", "PU Bordspel.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 1842762),
+	ENGLISH_ENTRY("pqtadventure", "playpqt.exe", "0b7529a76f38283d6e850b8d56526fc1", 19914806),
+	ENGLISH_ENTRY("practicescript", "Practice.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 764358),
+	ENGLISH_ENTRY("predatorspreyforplants", "Predators Prey For Plants.exe", "d44551532361c1eeec9b167de35515d1", 2318985),
+	ENGLISH_ENTRY("princessandallthekingdom", "Copy of PHK.exe", "465f972675db2da6040518221af5b0ba", 24658916),
+	ENGLISH_ENTRY("princessmarianix", "phantom.exe", "2a486107b3f04f789c122a1d0e1f3d5f", 2067548),
+	ENGLISH_ENTRY("princessmariansnowfight", "pmsnow.exe", "f120690b506dd63cd7d1112ea6af2f77", 1250562),
+	ENGLISH_ENTRY("princessmarianspigeonpinger", "PMPP.exe", "e68aaf0cea1e5701a7bb50a757bb5f4b", 2929950),
+	ENGLISH_ENTRY("princessmarianxmagichat", "pmx.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 3243258),
+	ENGLISH_ENTRY("principlesofevil", "P of E.exe", "f120690b506dd63cd7d1112ea6af2f77", 43410398),
+	ENGLISH_ENTRY("principlesofevilii", "PoE II.exe", "f120690b506dd63cd7d1112ea6af2f77", 87236507),
+	ENGLISH_ENTRY("prodigal", "Prodigal.exe", "682a8c57c7678c99c1564fd43680f03e", 7486947),
+	ENGLISH_ENTRY("profneely", "ProfN.exe", "26cfa7bd1be5485e1f0385101b31e43b", 31956037),
+	ENGLISH_ENTRY("projectevilspyii", "Project Evilspy II.exe", "0b7529a76f38283d6e850b8d56526fc1", 1583899),
+	ENGLISH_ENTRY("proofoffiction", "PoF.exe", "9cf51833e787cc919837d9a8bd8fc14c", 2723885),
+	ENGLISH_ENTRY("prototypical", "Proto.exe", "06a03fe35791b0578068ab1873455463", 48507319),
+	ENGLISH_ENTRY("proxecto", "proxec.exe", "465f972675db2da6040518221af5b0ba", 2636209),
+	ENGLISH_ENTRY("psychopomp", "psychopomp.exe", "b142b43c146c25443a1d155d441a6a81", 23721476),
+	ENGLISH_ENTRY("pubmasterquest2", "shogin crystal.exe", "90baefd2f369cebe25f3aa9ad90332d2", 35191110),
+	ENGLISH_ENTRY("pubmastersquest", "Pub Master Quest [Demo].exe", "e1676318c8a040fcf508b817013dc8fe", 23431689),
+	ENGLISH_ENTRY("puddypenguin", "Penguin.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 2328158),
+	ENGLISH_ENTRY("pupupupulaisenseikkailut", "Pupupeli.exe", "23a67b6de10ec35e9f5a4dfc7d928222", 13453697),
+	ENGLISH_ENTRY("pupupupulaisenseikkailut", "Game.exe", "23a67b6de10ec35e9f5a4dfc7d928222", 13431315),
+	ENGLISH_ENTRY("purgatorio01", "Purgatorio 0.1.exe", "18b284c22010850f79bc5c20054a70c4", 194293367),
+	ENGLISH_ENTRY("purityofthesurf", "Surf.exe", "71ca0d6c1c699595f28a2125948d4a84", 11315703),
+	ENGLISH_ENTRY("puzzlebotsdemo", "Puzzlebots_Demo.exe", "34b49df9cf6eadb5c3587b3921d5b72f", 354138961),
+	ENGLISH_ENTRY("pxenophobe", "ProjXeno.exe", "465f972675db2da6040518221af5b0ba", 79053486),
+	ENGLISH_ENTRY("quantumnauts", "QNDEMO.exe", "aeb2dd29e5ff839cb3ee86cf3e87e3ca", 134237367),
+	ENGLISH_ENTRY("questfighter", "Quest Fighter.exe", "21fd0f65dfa48de2b39cb8ec23b30889", 2914128),
+	ENGLISH_ENTRY("questfighterii", "Quest Fighter 2.exe", "4d7d2addcde045dae6e0363a43f9acad", 5219511),
+	ENGLISH_ENTRY("questforcinema", "Questforcinema.exe", "465f972675db2da6040518221af5b0ba", 2670632),
+	ENGLISH_ENTRY("questforglory2vga", "Game.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 5408433),
+	ENGLISH_ENTRY("questforgloryii", "Qfg2vga.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 20523688),
+	ENGLISH_ENTRY("questforjesus", "QuestForJesus.exe", "495d45fb8adfd49690ae3b97921feec6", 3973088),
+	ENGLISH_ENTRY("questforpalette", "Palette Quest.exe", "0710e2ec71042617f565c01824f0cf3c", 754395),
+	ENGLISH_ENTRY("questforthebluecup", "Quest for the Cup.exe", "9cb3c8dc7a8ab9c44815955696be2677", 8760015),
+	ENGLISH_ENTRY("questforyeti", "Quest For Yeti.exe", "90413e9ae57e222f8913b09d2bc847bc", 2635580),
+	ENGLISH_ENTRY("questforyrolg", "Quest for Yrolg.exe", "c4f5b7b29be90ba0f8128298afb917de", 9388101),
+	ENGLISH_ENTRY("quieromorir", "ElMito.exe", "f120690b506dd63cd7d1112ea6af2f77", 11304944),
+	ENGLISH_ENTRY("quimbyquestanewdope", "QQuest.exe", "615e806856b7730afadf1fea9a756b70", 8801878),
+	ENGLISH_ENTRY("race", "R.ACE.exe", "06a03fe35791b0578068ab1873455463", 3842314),
+	ENGLISH_ENTRY("rackham", "Rackham.exe", "36f44e064eab15e502caeb60fd09f52d", 3672597),
+	ENGLISH_ENTRY("ralphtheraven", "RalphTheRaven.exe", "0500aacb6c176d47ac0f8158f055db83", 1655198),
+	ENGLISH_ENTRY("ramsesporterandtherelayforlove", "Ramses Porter and the Relay for Love.exe", "a524cbb1c51589903c4043b98917f1d9", 55490676),
+	ENGLISH_ENTRY("rango", "Rango.exe", "618d7dce9631229b4579340b964c6810", 21059129),
+	ENGLISH_ENTRY("ratchannel", "Rat Channel.exe", "c5d2c54c20cb606519b86d3890ee7fc0", 303946606),
+	ENGLISH_ENTRY("rayandtheguitar", "The Band.exe", "465f972675db2da6040518221af5b0ba", 1518249),
+	ENGLISH_ENTRY("raybexter", "Ray Bexter.exe", "3e8667bab45f2e5d7237db53ab376400", 5930752),
+	ENGLISH_ENTRY("raybexter", "Ray Bexter.exe", "d3bc2cf3a0f72f0fbe37d9edbd5ebec3", 5680319),
+	ENGLISH_ENTRY("razorsinthenight", "Razors.exe", "0500aacb6c176d47ac0f8158f055db83", 25442827),
+	ENGLISH_ENTRY("reagentorange", "Lab.exe", "83d96faa4efefcc9c03c01b9517f23bb", 13377038),
+	ENGLISH_ENTRY("realityonthenorm", "RoN-DayOfComet.exe", "465f972675db2da6040518221af5b0ba", 10497989),
+	ENGLISH_ENTRY("recess", "Recess.exe", "c87aa6377abc18c1a1b2968ae6db08eb", 1941530),
+	ENGLISH_ENTRY("recess2", "Recess2.exe", "45ab4f29031b50c8d01d10a269f77ff5", 2805921),
+	ENGLISH_ENTRY("reddwarf", "Red Dwarf.exe", "06a03fe35791b0578068ab1873455463", 2812268),
+	ENGLISH_ENTRY("redflagg", "Red Flagg.exe", "5901879fafae3812f71b3a2d73bee40e", 79414802),
+	ENGLISH_ENTRY("redpantsmeetsrobinsonclauseau", "DBL.exe", "c0aab3e02bbaf8468770480079436f61", 15658119),
+	ENGLISH_ENTRY("redpantstheprincessandthebeanstalk", "Redpants - The Princess and the Beanstalk.exe", "c0aab3e02bbaf8468770480079436f61", 28517345),
+	ENGLISH_ENTRY("reefriversquestforekoban", "Quest for Ekoban.exe", "338fa79960d40689063af31c671b8729", 179342350),
+	ENGLISH_ENTRY("returntocivilization", "ReturnTo.exe", "0710e2ec71042617f565c01824f0cf3c", 3280888),
+	ENGLISH_ENTRY("revelation10", "Revelation.exe", "06a03fe35791b0578068ab1873455463", 14512328),
+	ENGLISH_ENTRY("rickyquest", "black.exe", "06a03fe35791b0578068ab1873455463", 3250100),
+	ENGLISH_ENTRY("righteouscity", "RCII.exe", "06a03fe35791b0578068ab1873455463", 39085407),
+	ENGLISH_ENTRY("righteouscity", "RC PI - 3.00.exe", "089fab88e6e1075a2f5b271f6f5b3c57", 19786840),
+	ENGLISH_ENTRY("roadofdestiny", "ROD.exe", "618d7dce9631229b4579340b964c6810", 30127308),
+	ENGLISH_ENTRY("roadracer", "TR_Bryvis.exe", "cebb3ac5c3d2df939e7f0ec8f2975b64", 25080647),
+	ENGLISH_ENTRY("roastmothergoose", "RMG.exe", "00328f4f1e7729144483107b96b11df8", 46474982),
+	ENGLISH_ENTRY("robbertredfordsavestheday", "GAME.exe", "02635a77ab660023f59519c91329f7f5", 6537985),
+	ENGLISH_ENTRY("robbingtheprincess", "Princess.exe", "ac461eb75959761fe159917607c246b4", 5793384),
+	ENGLISH_ENTRY("robertredford3", "game.exe", "71ca0d6c1c699595f28a2125948d4a84", 10846423),
+	ENGLISH_ENTRY("robertredfordsavestheday", "ROBERT2.exe", "02635a77ab660023f59519c91329f7f5", 13075066),
+	ENGLISH_ENTRY("robmassacreofchainsawness", "Chainsaw.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 1153384),
+	ENGLISH_ENTRY("robotragedy", "Robotragedy.exe", "465f972675db2da6040518221af5b0ba", 130585260),
+	ENGLISH_ENTRY("robotragedy2", "Robotragedy 2.exe", "465f972675db2da6040518221af5b0ba", 256955387),
+	ENGLISH_ENTRY("roccioquest", "RoccioQuest.exe", "7727bf5360b00bfc1947455218137803", 5797284),
+	ENGLISH_ENTRY("rockabillykid", "Rockabilly Kid.exe", "ff3358d8f2726d544aadfde4f1ec8407", 2650305),
+	ENGLISH_ENTRY("rockburgerstreehouses", "RBTH.exe", "88cf59aad15ca331ab0f854e16c84df3", 1876674),
+	ENGLISH_ENTRY("rockrockrock", "rrr.exe", "7dd36aa863ed40ede1b09ae505e478cc", 9362761),
+	ENGLISH_ENTRY("rockyroams", "Rocky.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 16978200),
+	ENGLISH_ENTRY("rodequest2", "RQ2.exe", "12c03a3c782237821acd590fd91af4c5", 4192097),
+	ENGLISH_ENTRY("ronbeforethelegacy", "RONlegacy.exe", "0b7529a76f38283d6e850b8d56526fc1", 4792872),
+	ENGLISH_ENTRY("ronsixteen", "16c.exe", "06a03fe35791b0578068ab1873455463", 2467851),
+	ENGLISH_ENTRY("rontimeoutintro", "ronTOintro.exe", "95b7dd55f6e15c8a2118856ed9fe8ff9", 2804752),
+	ENGLISH_ENTRY("roomoffear", "RoomofFear_Oct.exe", "495d45fb8adfd49690ae3b97921feec6", 17366083),
+	ENGLISH_ENTRY("rootofallevil", "RootOfAllEvil.exe", "c4f5b7b29be90ba0f8128298afb917de", 3957834),
+	ENGLISH_ENTRY("rosauradocelestialrescuefromdespair", "RosauraMAGS.exe", "3c5bd1713959ff469cb46ebe5542cfcf", 13190949),
+	ENGLISH_ENTRY("rotnbelusebiusarrival", "RoNXXL.exe", "465f972675db2da6040518221af5b0ba", 9426141),
+	ENGLISH_ENTRY("rotnbelusebiusarrival", "ronextra.exe", "465f972675db2da6040518221af5b0ba", 9958019),
+	ENGLISH_ENTRY("rowengoestowork", "Rowen.exe", "a1cef60926235b85bd0e1866b19e0dc7", 3791058),
+	ENGLISH_ENTRY("rs15", "rs15.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 13638597),
+	ENGLISH_ENTRY("rudeawakening", "RudeAwakening.exe", "0710e2ec71042617f565c01824f0cf3c", 8038257),
+	ENGLISH_ENTRY("ryansdayout", "Ryan's Day out.exe", "06a03fe35791b0578068ab1873455463", 2573584),
+	ENGLISH_ENTRY("saddsonissein", "Issein.exe", "3e8667bab45f2e5d7237db53ab376400", 4070795),
+	ENGLISH_ENTRY("salazarsevilplan", "Jonny Smallvalley.exe", "a524cbb1c51589903c4043b98917f1d9", 64646627),
+	ENGLISH_ENTRY("sammysquest", "Sammy's Quest.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 7924985),
+	ENGLISH_ENTRY("santaclausdown", "scdown.exe", "f120690b506dd63cd7d1112ea6af2f77", 14385095),
+	ENGLISH_ENTRY("santassidekick", "Xmas.exe", "0710e2ec71042617f565c01824f0cf3c", 1921077),
+	ENGLISH_ENTRY("satanquest", "Satan.exe", "70cd70d2fc7b2a8716fc58fc9deaf259", 4779276),
+	ENGLISH_ENTRY("satchsquest", "Satch's.exe", "465f972675db2da6040518221af5b0ba", 1928613),
+	ENGLISH_ENTRY("saturdayschool", "ss.exe", "b216ee957dd677023e02d900281a02d6", 1588546),
+	ENGLISH_ENTRY("saw", "Saw.exe", "34a66a5033b70f4050cbe5e33a45f747", 2452460),
+	ENGLISH_ENTRY("saw", "Saw.exe", "f120690b506dd63cd7d1112ea6af2f77", 60869310),
+	ENGLISH_ENTRY("saw2", "Saw2.exe", "615e806856b7730afadf1fea9a756b70", 45338514),
+	ENGLISH_ENTRY("scaredstiffa", "Scared Stiff.exe", "18b284c22010850f79bc5c20054a70c4", 57878023),
+	ENGLISH_ENTRY("scarymaze", "Scary Maze.exe", "01823d511cc00f4de6fd920eb543c6e7", 5380554),
+	ENGLISH_ENTRY("schwarzweissrot", "SchwarzWeissRot - Englisch.exe", "495d45fb8adfd49690ae3b97921feec6", 82849166),
+	ENGLISH_ENTRY("schwarzweissrot", "SchwarzWeissRot.exe", "495d45fb8adfd49690ae3b97921feec6", 82913128),
+	ENGLISH_ENTRY("scnider", "scnider.exe", "3128b9f90e2f954ba704414ae854d10b", 1189237),
+	ENGLISH_ENTRY("scytheisland", "Scythe.exe", "0500aacb6c176d47ac0f8158f055db83", 7119760),
+	ENGLISH_ENTRY("searchforsanitydemo", "sfs.exe", "308d35bc34e9df29d8acce615593e3e7", 9097147),
+	ENGLISH_ENTRY("seashells", "Shells.exe", "0500aacb6c176d47ac0f8158f055db83", 6355325),
+	ENGLISH_ENTRY("seasongreetings2002", "xmas2002.exe", "97d700529f5cc826f230c27acf81adfd", 4263336),
+	ENGLISH_ENTRY("secretquestremake", "secretquest.exe", "f120690b506dd63cd7d1112ea6af2f77", 2121159),
+	ENGLISH_ENTRY("secrets", "Secrets.exe", "06a03fe35791b0578068ab1873455463", 36176884),
+	ENGLISH_ENTRY("seega16engl5", "house_eng_5.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 1746878),
+	ENGLISH_ENTRY("seegame15", "housesitting_18.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 1746919),
+	ENGLISH_ENTRY("sevendoors", "7DOORS.exe", "18b284c22010850f79bc5c20054a70c4", 113716886),
+	ENGLISH_ENTRY("sga", "StarGA.exe", "0710e2ec71042617f565c01824f0cf3c", 45738298),
+	ENGLISH_ENTRY("shadesofgreye", "Shades of Greye.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 16125855),
+	ENGLISH_ENTRY("shadowsoftheempiretd", "sote_td.exe", "b8cd640b45c5a79c33c7a8a8fe32ebe2", 63299246),
+	ENGLISH_ENTRY("shailadusithlenqute", "Shai-la Enquete.exe", "a524cbb1c51589903c4043b98917f1d9", 7489302),
+	ENGLISH_ENTRY("shailaofthesith", "Shaila_of_the_Sith.exe", "a524cbb1c51589903c4043b98917f1d9", 76170347),
+	ENGLISH_ENTRY("shem", "Shem.exe", "0710e2ec71042617f565c01824f0cf3c", 8866401),
+	ENGLISH_ENTRY("sherlock", "Sherlock.exe", "615e73fc1874e92d60a1996c2330ea36", 19108029),
+	ENGLISH_ENTRY("shiftersboxoutsidein", "Box.exe", "fc17e9b3ab53f6b4841e2a4af5c782ff", 24471804),
+	ENGLISH_ENTRY("shivahdemo", "shivahDemo.exe", "6e3d6225dee662ff6450a3bfa942773b", 20897850),
+	ENGLISH_ENTRY("shoot", "Shoot.exe", "1275885401b7d2ece491e704535707d9", 4327626),
+	ENGLISH_ENTRY("shootmyvalentine", "Valentine.exe", "06a03fe35791b0578068ab1873455463", 2859760),
+	ENGLISH_ENTRY("shortcut", "ShortCut.exe", "95b7dd55f6e15c8a2118856ed9fe8ff9", 4415830),
+	ENGLISH_ENTRY("shrivel", "Shrivel.exe", "12c6a846b5ba9a5dde4a1b804b3e86e9", 58873190),
+	ENGLISH_ENTRY("shunday", "Shunday.exe", "82da2565c456dcfb265ded6fe3189c0b", 4937129),
+	ENGLISH_ENTRY("sierraquest1", "SierraQuest1.exe", "465f972675db2da6040518221af5b0ba", 1275381),
+	ENGLISH_ENTRY("silentknightii", "SilentKnight2.exe", "465f972675db2da6040518221af5b0ba", 39941166),
+	ENGLISH_ENTRY("silentknightv11", "Silent Knight.exe", "465f972675db2da6040518221af5b0ba", 47414163),
+	ENGLISH_ENTRY("simonthesorcerer3demo20", "Simon3.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 8189928),
+	ENGLISH_ENTRY("skippysavestheday", "First Game Test.exe", "06a03fe35791b0578068ab1873455463", 10473902),
+	ENGLISH_ENTRY("slaythedragon", "dragon.exe", "3c5bd1713959ff469cb46ebe5542cfcf", 2917672),
+	ENGLISH_ENTRY("sleepyisland", "Sleepy Island.exe", "465f972675db2da6040518221af5b0ba", 20270790),
+	ENGLISH_ENTRY("slimequestforpizza", "slime.exe", "95b7dd55f6e15c8a2118856ed9fe8ff9", 1661109),
+	ENGLISH_ENTRY("slugprincess", "SlugPrincess.exe", "28f82e420b82d07651b68114f90223c8", 12132209),
+	ENGLISH_ENTRY("sma21", "sma21.exe", "02094e217c23e1d40a84891ee95010cb", 7093110),
+	ENGLISH_ENTRY("sma31", "sma31.exe", "4d17844029d8910fbaae1bdc99e250f2", 4961734),
+	ENGLISH_ENTRY("sma4", "smavier.exe", "02094e217c23e1d40a84891ee95010cb", 2447360),
+	ENGLISH_ENTRY("smavi", "sma6.exe", "64fcaf7da0b257ea831f89c54be0ad72", 3735081),
+	ENGLISH_ENTRY("smileysquest", "Smiley.exe", "90413e9ae57e222f8913b09d2bc847bc", 4938049),
+	ENGLISH_ENTRY("smileysquest2", "mags.exe", "3128b9f90e2f954ba704414ae854d10b", 2108492),
+	ENGLISH_ENTRY("smoothhide", "SmoothHide.exe", "b142b43c146c25443a1d155d441a6a81", 10006680),
+	ENGLISH_ENTRY("snakeamagsgame", "Snake.exe", "f120690b506dd63cd7d1112ea6af2f77", 2110526),
+	ENGLISH_ENTRY("snakesofavalon", "snakes.exe", "464fbeef013ac949e2011551048928cd", 52601238),
+	ENGLISH_ENTRY("snakesonaplane", "SOAP.exe", "06a03fe35791b0578068ab1873455463", 1589975),
+	ENGLISH_ENTRY("sniperandspotterservingthemotherland", "sniper and spotter 2.exe", "7a3096ac0237cb6aa8e1718e28caf039", 134215997),
+	ENGLISH_ENTRY("sonicandfriendsinclubhouse", "Sonic and friends.exe", "71989c04f1b9812a0df87bc4f5915d4b", 50429335),
+	ENGLISH_ENTRY("sosk", "Sosk.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 12338591),
+	ENGLISH_ENTRY("sovietunterzoegersdorfsectorii", "suz2prog.exe", "47a774ff828be0ca227ee58e7dc61467", 43921618),
+	ENGLISH_ENTRY("sowjetunterzgersdorf", "suzoeg.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 79618213),
+	ENGLISH_ENTRY("spacefreakers", "Space Freakers v2.exe", "7a3096ac0237cb6aa8e1718e28caf039", 64527091),
+	ENGLISH_ENTRY("spacelynxes", "SpaceLynxes.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 6593042),
+	ENGLISH_ENTRY("spacepirates", "Space Pirates.exe", "95dcf736be87cf7d40bf64d5b078c4b7", 3006210),
+	ENGLISH_ENTRY("spacepoolalpha", "SpacePool.exe", "ef1d6fdc83c91a1a8de9eaf2630737b7", 3055777),
+	ENGLISH_ENTRY("spacequest45", "SQ4,5.exe", "5cd8db602cedc8f04cd3ca290a4a2693", 6886082),
+	ENGLISH_ENTRY("spacequest55demoags", "SQ5.5.exe", "465f972675db2da6040518221af5b0ba", 16342443),
+	ENGLISH_ENTRY("spacequestiiivgapreview", "SQ3VGADEMO.exe", "64fcaf7da0b257ea831f89c54be0ad72", 3630019),
+	ENGLISH_ENTRY("spacerangers", "SpaceRangersEp46.exe", "4f6c7ec127e8b0ce077abb357903612f", 41103057),
+	ENGLISH_ENTRY("spacerangersep52", "SpaceRangers52Grisli.exe", "4f6c7ec127e8b0ce077abb357903612f", 208346458),
+	ENGLISH_ENTRY("spacewar", "Spacewar.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 2270669),
+	ENGLISH_ENTRY("spacewarepisode2strikba", "Space.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 4084181),
+	ENGLISH_ENTRY("spellbound", "Spellbound.exe", "588e5b40901f9c85df35ac60b9417eac", 8809110),
+	ENGLISH_ENTRY("spilakassinn", "Splakassinn.exe", "06a03fe35791b0578068ab1873455463", 2658189),
+	ENGLISH_ENTRY("spooks", "Spooks.exe", "0710e2ec71042617f565c01824f0cf3c", 22888238),
+	ENGLISH_ENTRY("spoonsiiitheunauthorizededition", "spoonsIII.exe", "2ca80bd50763378b72cd1e1cf25afac3", 16298983),
+	ENGLISH_ENTRY("spotthedifference", "Spot the Difference.exe", "0b7529a76f38283d6e850b8d56526fc1", 933452),
+	ENGLISH_ENTRY("sqm11", "SQM1.exe", "465f972675db2da6040518221af5b0ba", 1001506),
+	ENGLISH_ENTRY("sqm12", "SQM 1x2.exe", "465f972675db2da6040518221af5b0ba", 755146),
+	ENGLISH_ENTRY("sqm13", "SQM 1x3.exe", "465f972675db2da6040518221af5b0ba", 1435210),
+	ENGLISH_ENTRY("sqm14", "SQM 1x4.exe", "465f972675db2da6040518221af5b0ba", 1383567),
+	ENGLISH_ENTRY("sqm16", "SQM 1x6.exe", "465f972675db2da6040518221af5b0ba", 1400100),
+	ENGLISH_ENTRY("sproutsofevil", "Sprouts of evil.exe", "bdd1df0484e296faa348ffcb03e16273", 22329944),
+	ENGLISH_ENTRY("sqkubikgetready", "SQ Kubik.exe", "4fb72c890984548ed6782063f2230942", 2184808),
+	ENGLISH_ENTRY("sqmania1", "SQMania1.exe", "465f972675db2da6040518221af5b0ba", 831674),
+	ENGLISH_ENTRY("sqmania2remakeeng", "SQM2 RMK.exe", "465f972675db2da6040518221af5b0ba", 3029288),
+	ENGLISH_ENTRY("sqmaniaep5", "SQ Mania Ep5.exe", "a524cbb1c51589903c4043b98917f1d9", 2896204),
+	ENGLISH_ENTRY("sram2cinomehsrevengedemo", "SRAM2.exe", "e3a33d139d90f2e695292a618753b8a5", 296499943),
+	ENGLISH_ENTRY("stablepeteandthejoust", "StablePete.exe", "b142b43c146c25443a1d155d441a6a81", 30048075),
+	ENGLISH_ENTRY("stablepeteandthejoust", "StablePete.exe", "b142b43c146c25443a1d155d441a6a81", 30046740),
+	ENGLISH_ENTRY("stairquest", "Stair Quest.exe", "e0aeab6a2c479fde167c4c43c3abb8ca", 4550699),
+	ENGLISH_ENTRY("stanamespiepisode1", "NEW.exe", "f120690b506dd63cd7d1112ea6af2f77", 19194728),
+	ENGLISH_ENTRY("stansrevenge", "Gameisle.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 915036),
+	ENGLISH_ENTRY("starshipcaramba", "karamba.exe", "465f972675db2da6040518221af5b0ba", 21540340),
+	ENGLISH_ENTRY("starshipposeidon", "Starship Poseidon.exe", "5a9abb3094d0b3f4bc09c0c77fbb8024", 4163873),
+	ENGLISH_ENTRY("start", "CC1.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 18627665),
+	ENGLISH_ENTRY("startreknewton", "Anomaly.exe", "721e8a1dce90fc3ee31cade9a50d9e75", 8750111),
+	ENGLISH_ENTRY("stediddyip1employment", "stediddy1.exe", "5872fea5a958bc74c2d9ca7b2d196c42", 27136166),
+	ENGLISH_ENTRY("stickmeni", "stick.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 2399329),
+	ENGLISH_ENTRY("stickythestickfigurepart1thecrimsonhouse", "Crimson House Files.exe", "3b095a7872e04769d04ab45e9c1b66eb", 3610653),
+	ENGLISH_ENTRY("stinkymcpoopoo", "grok.exe", "9cf51833e787cc919837d9a8bd8fc14c", 1046039),
+	ENGLISH_ENTRY("stranded", "Stranded.exe", "18b284c22010850f79bc5c20054a70c4", 39791629),
+	ENGLISH_ENTRY("stranger", "Stranger.exe", "0500aacb6c176d47ac0f8158f055db83", 5854099),
+	ENGLISH_ENTRY("strangerinstickworld", "game1.exe", "a524cbb1c51589903c4043b98917f1d9", 42525810),
+	ENGLISH_ENTRY("strangerthings", "StrangerThings.exe", "cc19db728abbcf657db6b76afb0e92d1", 43636017),
+	ENGLISH_ENTRY("supaevil", "SupaEvil.exe", "0710e2ec71042617f565c01824f0cf3c", 7602318),
+	ENGLISH_ENTRY("supergirl", "Supergirl.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 12108982),
+	ENGLISH_ENTRY("superjazzmandemo", "SJMdemo.exe", "0710e2ec71042617f565c01824f0cf3c", 5214882),
+	ENGLISH_ENTRY("superracing", "Super Racing.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 3660473),
+	ENGLISH_ENTRY("surreality", "Surreality.exe", "3128b9f90e2f954ba704414ae854d10b", 10773443),
+	ENGLISH_ENTRY("sweed", "SWeed.exe", "be65afc1ea59889c05e4e4cc143b3dbc", 2171942),
+	ENGLISH_ENTRY("sword", "Sword.exe", "0500aacb6c176d47ac0f8158f055db83", 1847692),
+	ENGLISH_ENTRY("sydneyfindsemployment", "sydney.exe", "06a03fe35791b0578068ab1873455463", 17351738),
+	ENGLISH_ENTRY("sydneytreadsthecatwalk", "sydney two.exe", "615e806856b7730afadf1fea9a756b70", 31480339),
+	ENGLISH_ENTRY("symplokelaleyendadegustavobuenocapitulo1", "Symploke.exe", "ff20c8c9dda8379607db87e7726909c6", 29996616),
+	ENGLISH_ENTRY("tales", "Tales.exe", "4f6c7ec127e8b0ce077abb357903612f", 112930701),
+	ENGLISH_ENTRY("talesofchickenry", "Chickenry.exe", "aabdafae8b57dfc48fdf158a72326c23", 50338519),
+	ENGLISH_ENTRY("tao", "Tao through space and time AGS.exe", "7a3096ac0237cb6aa8e1718e28caf039", 35930047),
+	ENGLISH_ENTRY("tarthenia", "Tarthenia.exe", "a524cbb1c51589903c4043b98917f1d9", 1047988125),
+	ENGLISH_ENTRY("teamwork", "teamwork.exe", "96f83f7decb523d0c621646828cad249", 3741039),
+	ENGLISH_ENTRY("templeofspheres", "Spheres.exe", "e9475a2e453039ca51c8c319a8c8255a", 7117373),
+	ENGLISH_ENTRY("tenhumstombpart1", "tomb.exe", "0710e2ec71042617f565c01824f0cf3c", 1252175),
+	ENGLISH_ENTRY("terrorofthevampire", "TERRVAMP.exe", "efd2b2abf965c4b50bea79a419b82cf1", 5164804),
+	ENGLISH_ENTRY("test", "Living Nightmare.exe", "95dcf736be87cf7d40bf64d5b078c4b7", 3356797),
+	ENGLISH_ENTRY("test5", "who07.exe", "465f972675db2da6040518221af5b0ba", 1889598),
+	ENGLISH_ENTRY("textparsergame", "tparsergame.exe", "06a03fe35791b0578068ab1873455463", 2061002),
+	ENGLISH_ENTRY("thatday", "ThatDay.exe", "b142b43c146c25443a1d155d441a6a81", 9534366),
+	ENGLISH_ENTRY("the30minutewar", "7DG.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 1659319),
+	ENGLISH_ENTRY("the7thsense", "7thSense.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 17972183),
+	ENGLISH_ENTRY("theadventureofthehero", "The Adventure of the Hero.exe", "5d20aab40290fc72ec84393464913df2", 4408710),
+	ENGLISH_ENTRY("theadventuresoffatman", "Fatman.exe", "853cef07077feadd0f2ccd55c5bd747b", 56375090),
+	ENGLISH_ENTRY("theadventuresofturquoisem", "The Adventures Of Turquoise Mcdonald.exe", "06a03fe35791b0578068ab1873455463", 2883450),
+	ENGLISH_ENTRY("theassassin", "the-assassin.exe", "e3962995a70923a8d5a8f1cf8f932eee", 29043438),
+	ENGLISH_ENTRY("theawakening", "The Awakening.exe", "0241777c2537fc5d077c05cde10bfa9f", 13613585),
+	ENGLISH_ENTRY("thebadneighbours", "Bad neighbour.exe", "06a03fe35791b0578068ab1873455463", 9672173),
+	ENGLISH_ENTRY("thebar", "one room game.exe", "465f972675db2da6040518221af5b0ba", 11660587),
+	ENGLISH_ENTRY("thebrokenbrain", "Brain.exe", "95b7dd55f6e15c8a2118856ed9fe8ff9", 1092293),
+	ENGLISH_ENTRY("thebunker", "The Bunker.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 12391058),
+	ENGLISH_ENTRY("thecadaversynod", "The cadaver synod.exe", "36f44e064eab15e502caeb60fd09f52d", 37438749),
+	ENGLISH_ENTRY("thecan", "TheCan.exe", "82da2565c456dcfb265ded6fe3189c0b", 72388782),
+	ENGLISH_ENTRY("thecell", "The Cell.exe", "b142b43c146c25443a1d155d441a6a81", 21422530),
+	ENGLISH_ENTRY("thecell", "Cell.exe", "0b7529a76f38283d6e850b8d56526fc1", 811527),
+	ENGLISH_ENTRY("thechrysalis", "Mygame.exe", "22b9c6d170613eb01afa1697b1b75cdb", 28926604),
+	ENGLISH_ENTRY("thecrackwelllegacy", "Crackwell.exe", "06a03fe35791b0578068ab1873455463", 2990976),
+	ENGLISH_ENTRY("thecube", "The Cube.exe", "97d700529f5cc826f230c27acf81adfd", 2029985),
+	ENGLISH_ENTRY("thecurioussilence", "silence.exe", "495d45fb8adfd49690ae3b97921feec6", 8039714),
+	ENGLISH_ENTRY("thecurseoflife", "TheCurse.exe", "90413e9ae57e222f8913b09d2bc847bc", 9651875),
+	ENGLISH_ENTRY("thedayofdarkness", "DayODark.exe", "465f972675db2da6040518221af5b0ba", 1082758),
+	ENGLISH_ENTRY("thedeathoflukesimpson", "LukeDead.exe", "06a03fe35791b0578068ab1873455463", 3233789),
+	ENGLISH_ENTRY("thedevilsshroudpart1", "DevilTorino256.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 16661573),
+	ENGLISH_ENTRY("thedigitalspell", "Digital.exe", "4d17844029d8910fbaae1bdc99e250f2", 14657385),
+	ENGLISH_ENTRY("thedusseldorfconspiracy", "dusseldorf.exe", "465f972675db2da6040518221af5b0ba", 60887427),
+	ENGLISH_ENTRY("thedwarvendaggerofblitz", "teste2.exe", "06a03fe35791b0578068ab1873455463", 9874658),
+	ENGLISH_ENTRY("theelevator", "Elevator.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 6563864),
+	ENGLISH_ENTRY("theenergizer", "TheEnergizer.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 54539625),
+	ENGLISH_ENTRY("theepicadventures", "Epic adventures.exe", "a524cbb1c51589903c4043b98917f1d9", 17723648),
+	ENGLISH_ENTRY("theeverbeginningtale", "RRS.exe", "36f8b37f85f446e9aaccb18d85660cde", 5006033),
+	ENGLISH_ENTRY("theexecutionofanneboleyn", "TheExecutionOfAnneBoleyn.exe", "6ee67d23067b0499eb8c6a1a9aabff8c", 8549540),
+	ENGLISH_ENTRY("thefarm", "the farm.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 88858865),
+	ENGLISH_ENTRY("theficklehandsoffate", "Game.exe", "2bf7a3a5f0a22a140350e29bb1ac7cfb", 4105398),
+	ENGLISH_ENTRY("thefind", "The Find.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 3476394),
+	ENGLISH_ENTRY("thegourmet", "The Gourmet.exe", "c48d0beedcdc1b05e9e25dcd60de46a9", 49995478),
+	ENGLISH_ENTRY("thegreatcasserolecaper", "TGCC.exe", "6ee842f73649ced615c44d4eb303687c", 10902276),
+	ENGLISH_ENTRY("thegreatstrokeoff", "GSO.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 84337184),
+	ENGLISH_ENTRY("thegruglegends", "Grug.exe", "c6acb1705dd30f82ba026e92d6af831e", 85947629),
+	ENGLISH_ENTRY("thehamlet", "hamlet.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 4252451),
+	ENGLISH_ENTRY("thehauntedhouse", "HH.exe", "97d700529f5cc826f230c27acf81adfd", 29221222),
+	ENGLISH_ENTRY("theheist", "The Heist.exe", "261d108f9213356a351b35b54867f342", 13502430),
+	ENGLISH_ENTRY("thehobbitriseofthedragonking", "The Hobbit.exe", "338fa79960d40689063af31c671b8729", 113862075),
+	ENGLISH_ENTRY("thehousethatatemysoul", "THTFMD.exe", "f120690b506dd63cd7d1112ea6af2f77", 3930376),
+	ENGLISH_ENTRY("thehuntforgoldbeard", "The hunt for Goldbeard.exe", "a524cbb1c51589903c4043b98917f1d9", 4043188),
+	ENGLISH_ENTRY("thehuntforshaunbinda", "For Lisa Creed Made By Dan man.exe", "fd91d116e5adc4328cb22fab0b940e4d", 30753829),
+	ENGLISH_ENTRY("thehuntforshaunbindadeluxeedition", "For Lisa Creed Made By Dan man.exe", "5d6e936eaee9316e756bfe33ef8d3a19", 34290389),
+	ENGLISH_ENTRY("theiraqiparadox", "0203.exe", "b25674056fe8cc0b7bf0a4409c5c5bfc", 2976283),
+	ENGLISH_ENTRY("thejackyard", "The Jackyard.exe", "45d092881ef70b288382426a10251df3", 101417484),
+	ENGLISH_ENTRY("thejourneyhome", "Part1.exe", "9cf51833e787cc919837d9a8bd8fc14c", 8355767),
+	ENGLISH_ENTRY("thejourneyofiesir", "The Journey of Iesir.exe", "376a3f162c7940d990325c53edc20fed", 70444514),
+	ENGLISH_ENTRY("thelastharvest", "The Last Harvest.exe", "f120690b506dd63cd7d1112ea6af2f77", 6253816),
+	ENGLISH_ENTRY("thelastsupperawhodunnit", "THE LAST SUPPER, A WHODUNNIT.exe", "37500274a7882e8087042cc6ec851e0c", 13447848),
+	ENGLISH_ENTRY("theloneloserdemo", "DEMO (English).exe", "0500aacb6c176d47ac0f8158f055db83", 6082095),
+	ENGLISH_ENTRY("thelongtrip", "longtrip.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 184362586),
+	ENGLISH_ENTRY("themajesticconspiracy", "Majestic.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 17929647),
+	ENGLISH_ENTRY("themarionette", "marionette.exe", "ff3d6e4edfca8b4f4f1c6cbf8e2781a6", 88408446),
+	ENGLISH_ENTRY("themccarthychronicleschapter1", "McCarthy.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 29488543),
+	ENGLISH_ENTRY("themcreedcasebytk", "McReedCase.exe", "4bcbc24015114752b3c7971128704689", 2982436),
+	ENGLISH_ENTRY("themysteriesofstiegomoors", "mystery.exe", "0710e2ec71042617f565c01824f0cf3c", 12062769),
+	ENGLISH_ENTRY("themysteryofhauntedhollow", "magic1.exe", "3128b9f90e2f954ba704414ae854d10b", 3338806),
+	ENGLISH_ENTRY("thenetherworld", "netherworld.exe", "465f972675db2da6040518221af5b0ba", 2253033),
+	ENGLISH_ENTRY("thenextcurse", "TNC.exe", "88cf59aad15ca331ab0f854e16c84df3", 4125146),
+	ENGLISH_ENTRY("theoraclev11", "The Oracle.exe", "f120690b506dd63cd7d1112ea6af2f77", 7490474),
+	ENGLISH_ENTRY("thepark", "park.exe", "97d700529f5cc826f230c27acf81adfd", 709265),
+	ENGLISH_ENTRY("theperfectmurder", "Tamz.exe", "9cf51833e787cc919837d9a8bd8fc14c", 4527709),
+	ENGLISH_ENTRY("thephantominheritance", "Phantom.exe", "ec04c7917c003d9e07d4514ff25bf365", 27558669),
+	ENGLISH_ENTRY("thequestfortheholysalsa", "TheQuestForTheHolySalsa.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 38506266),
+	ENGLISH_ENTRY("thequesttozooloo", "Zooloo.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 14619530),
+	ENGLISH_ENTRY("theroadtomurder", "lbb.exe", "465f972675db2da6040518221af5b0ba", 1020984),
+	ENGLISH_ENTRY("therobolovers", "The Robolovers.exe", "618d7dce9631229b4579340b964c6810", 63850620),
+	ENGLISH_ENTRY("therotaryclub", "The Rotary Club.exe", "01823d511cc00f4de6fd920eb543c6e7", 9641709),
+	ENGLISH_ENTRY("thesearch", "s??rts.exe", "465f972675db2da6040518221af5b0ba", 5465638),
+	ENGLISH_ENTRY("thesecretofchunkysalsa", "TSOCS.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 3096950),
+	ENGLISH_ENTRY("thesecretofgoldenriver", "tsotgr.exe", "06a03fe35791b0578068ab1873455463", 8397455),
+	ENGLISH_ENTRY("thesecretofhuttongrammarschool", "1g1w.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 6584420),
+	ENGLISH_ENTRY("thesecretofmountmonkey", "Mmonk.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 6386620),
+	ENGLISH_ENTRY("thesecretplan1runningtostandstill", "thesecretplan1.exe", "bb59de174d70797d774dec76a171352d", 447931405),
+	ENGLISH_ENTRY("theshortestjourney", "The Shortest Journey.exe", "7c70226b560d6d9ffd9e165d6fbddd7e", 21503346),
+	ENGLISH_ENTRY("thesmallestpoints", "The Smallest Points.exe", "fd642138b7e6374ce0a0b9a1b0510500", 29534364),
+	ENGLISH_ENTRY("thesnaplock", "The Snaplock.exe", "7a3096ac0237cb6aa8e1718e28caf039", 31519102),
+	ENGLISH_ENTRY("thespoons", "Spoons.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 3652176),
+	ENGLISH_ENTRY("thestarryskyaboveme", "The Starry Sky Above Me.exe", "618d7dce9631229b4579340b964c6810", 14082659),
+	ENGLISH_ENTRY("thestring", "String.exe", "90413e9ae57e222f8913b09d2bc847bc", 36963577),
+	ENGLISH_ENTRY("thesundownmystery", "Sundown.exe", "a08ab253c4d2f255b9139f2aa5fe7006", 31839270),
+	ENGLISH_ENTRY("thetombofthemoon", "TotM.exe", "f120690b506dd63cd7d1112ea6af2f77", 1632811),
+	ENGLISH_ENTRY("thetrap", "Darcy.exe", "0500aacb6c176d47ac0f8158f055db83", 1164147),
+	ENGLISH_ENTRY("thetreasuredmedallion", "The Treasured Medallion.exe", "504df40bf50a0859e3dc15b000dab5f6", 1091122652),
+	ENGLISH_ENTRY("thetreasureoflochinch", "LochInch.exe", "6e861b1f476ff7cdf036082abb271329", 4091983),
+	ENGLISH_ENTRY("theuncertaintymachine", "TUMv11.exe", "b25674056fe8cc0b7bf0a4409c5c5bfc", 20672955),
+	ENGLISH_ENTRY("theuncertaintymachine", "TUMv11.exe", "b25674056fe8cc0b7bf0a4409c5c5bfc", 20670414),
+	ENGLISH_ENTRY("theupliftmofopartyplan", "MI5 Bob.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 4092850),
+	ENGLISH_ENTRY("thevacuum", "Spacefiles.exe", "d0ba73645e3cbf8ccd65121417f9895f", 14805166),
+	ENGLISH_ENTRY("thewitch", "Witch.exe", "f120690b506dd63cd7d1112ea6af2f77", 2693486),
+	ENGLISH_ENTRY("thisgame", "thisgame.exe", "74aad8dfd71ed2ae9574a60be7610c43", 6271585),
+	ENGLISH_ENTRY("threeguyswalkintoheaven", "Three Guys Walk Into Heaven.exe", "c45653d1c856f002ceb59a5b865ab187", 2896291),
+	ENGLISH_ENTRY("tilepuzzlegame", "Puzzle01.exe", "615e73fc1874e92d60a1996c2330ea36", 2819964),
+	ENGLISH_ENTRY("tiltor", "Tiltor.exe", "f120690b506dd63cd7d1112ea6af2f77", 17561878),
+	ENGLISH_ENTRY("timegentlemenpleasedemo", "TGP.exe", "86a5359bac7c88f0dfa060478800dd61", 29686006),
+	ENGLISH_ENTRY("timequest", "gam.exe", "465f972675db2da6040518221af5b0ba", 5669007),
+	ENGLISH_ENTRY("timequest2", "TimeQ2.exe", "465f972675db2da6040518221af5b0ba", 5838823),
+	ENGLISH_ENTRY("timesinkofchronos", "Timesink.exe", "2bc8f994a7d1e05ed45f35abf2128231", 127528679),
+	ENGLISH_ENTRY("timothylande", "Timothy Lande.exe", "0500aacb6c176d47ac0f8158f055db83", 13874628),
+	ENGLISH_ENTRY("tmateundescanso", "tomate.exe", "3128b9f90e2f954ba704414ae854d10b", 8865274),
+	ENGLISH_ENTRY("tmntturtlesintime", "Turtles.exe", "465f972675db2da6040518221af5b0ba", 2309552),
+	ENGLISH_ENTRY("tomhanksaway", "Tom Hanks Away.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 1589035),
+	ENGLISH_ENTRY("toomanykittens", "Too Many Kittens.exe", "089fab88e6e1075a2f5b271f6f5b3c57", 3926440),
+	ENGLISH_ENTRY("totalhangoverextreamzz", "hangover.exe", "72a1e963da14255d2b7523133f7147d9", 1837194),
+	ENGLISH_ENTRY("tq", "TQ.exe", "465f972675db2da6040518221af5b0ba", 2420457),
+	ENGLISH_ENTRY("trappedinabuilding", "T I A B.exe", "722c8bd17ace161f1bba2d9d92806eaf", 5370873),
+	ENGLISH_ENTRY("trevordaisoninouterspace", "TrevorDaison.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 22641402),
+	ENGLISH_ENTRY("trexandmusclesambigtroubleinspf", "Trex and Muscle Sam.exe", "91696f9333f36bdba272220c644c72e7", 120822652),
+	ENGLISH_ENTRY("trilbysnotes", "notes.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 5736960),
+	ENGLISH_ENTRY("trilbytheartoftheft", "artoftheft.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 8940823),
+	ENGLISH_ENTRY("trivialpassyouit", "Trivial Pass You It.exe", "01823d511cc00f4de6fd920eb543c6e7", 2737077),
+	ENGLISH_ENTRY("tuberainbow", "Tube Rainbow.exe", "03c8c45bd00daca1a9d75d1133df5640", 5669127),
+	ENGLISH_ENTRY("tvbrder", "TvaBroder.exe", "7a669a96e488653db661d285bbc12783", 17875297),
+	ENGLISH_ENTRY("twelvethirteen", "1213.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 2942386),
+	ENGLISH_ENTRY("twelvethirteenepisode2", "1213_ep2.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 3602361),
+	ENGLISH_ENTRY("twelvethirteenepisode3", "1213_ep3.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 3205606),
+	ENGLISH_ENTRY("twentiesflappersvsthemummy", "Twenties Flappers vs The Mummy.exe", "a524cbb1c51589903c4043b98917f1d9", 15042196),
+	ENGLISH_ENTRY("twoofakind", "toak.exe", "465f972675db2da6040518221af5b0ba", 24644765),
+	ENGLISH_ENTRY("uglyfiles", "ugly.exe", "0394af1c29e1060fcdbacf2a3dd9b231", 4169486),
+	ENGLISH_ENTRY("ulitsadimitrova", "ulitsa.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 291828379),
+	ENGLISH_ENTRY("unboundver10", "Unbound.exe", "900b277d7e1601c65b42868cd7fae662", 10448702),
+	ENGLISH_ENTRY("unfinished", "mags.exe", "0710e2ec71042617f565c01824f0cf3c", 12092514),
+	ENGLISH_ENTRY("unganeedsmumba", "UNGA needs MUMBA.exe", "2ca6bb6d5b2710ac89fea7d69c2eaf77", 5470102),
+	ENGLISH_ENTRY("unintelligentdesign", "UD.exe", "5ca1bc01c5a45388bd5c84ef36077361", 6019596),
+	ENGLISH_ENTRY("unprofev10", "Un Profe.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 3465541),
+	ENGLISH_ENTRY("untilihaveyou", "Until I Have You.exe", "cda1d7e36993dd55ba5513c1c43e5b2b", 457842687),
+	ENGLISH_ENTRY("updatequest", "U-Quest.exe", "06a03fe35791b0578068ab1873455463", 1776804),
+	ENGLISH_ENTRY("utopiaoftyrant", "Utopia_of_a_Tyrant.exe", "f8a42e09e40a7ab1cd2a21f74a5e0980", 80966652),
+	ENGLISH_ENTRY("vacationquestthing", "MGA.exe", "95b7dd55f6e15c8a2118856ed9fe8ff9", 943647),
+	ENGLISH_ENTRY("valhallaextinction", "MAGSjuly2016.exe", "95864ae16f51c512985007dca83c1370", 4464850),
+	ENGLISH_ENTRY("valis", "valis 0.70.exe", "0710e2ec71042617f565c01824f0cf3c", 4348394),
+	ENGLISH_ENTRY("vankairbreak", "Airbreak.exe", "28567bd2dc355a02a0ba58749e753f87", 23126775),
+	ENGLISH_ENTRY("vegetablepatchextreemturbo", "VPET.exe", "0b7529a76f38283d6e850b8d56526fc1", 2656540),
+	ENGLISH_ENTRY("veggietales3d", "Veggie Tales 3D.exe", "089fab88e6e1075a2f5b271f6f5b3c57", 5645075),
+	ENGLISH_ENTRY("veteranshootout", "Vet kill.exe", "0710e2ec71042617f565c01824f0cf3c", 3641458),
+	ENGLISH_ENTRY("vicwreckleshalloweencostume", "vic.exe", "01d0e6bd812abaa307bcb10fc2193416", 2913241),
+	ENGLISH_ENTRY("virtualpiano10", "Synth.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 1419081),
+	ENGLISH_ENTRY("vohaulsrevengeii", "SQ XII.exe", "465f972675db2da6040518221af5b0ba", 17313307),
+	ENGLISH_ENTRY("vpxt2", "VPET!2!.exe", "0b7529a76f38283d6e850b8d56526fc1", 12933096),
+	ENGLISH_ENTRY("waitingfortheloop", "WaitingForTheLoop.exe", "0241777c2537fc5d077c05cde10bfa9f", 51273604),
+	ENGLISH_ENTRY("wallyweaseldemo", "WallyDemo.exe", "95b7dd55f6e15c8a2118856ed9fe8ff9", 12579444),
+	ENGLISH_ENTRY("waltersasteroid", "HDGame.exe", "465f972675db2da6040518221af5b0ba", 8390872),
+	ENGLISH_ENTRY("warthogs", "Warthogs.exe", "9c49b6fa0460f36d6e7558281f142683", 12448793),
+	ENGLISH_ENTRY("washedashore", "Achtung!.exe", "06a03fe35791b0578068ab1873455463", 7926840),
+	ENGLISH_ENTRY("washedashoredeluxe", "Washed.exe", "06a03fe35791b0578068ab1873455463", 2771873),
+	ENGLISH_ENTRY("wasted", "Wasted.exe", "f120690b506dd63cd7d1112ea6af2f77", 27870661),
+	ENGLISH_ENTRY("waterquest", "KOSTAS.exe", "f120690b506dd63cd7d1112ea6af2f77", 12403015),
+	ENGLISH_ENTRY("wcedit", "walkcyclist.exe", "1e81f0cba7e94fb658acd8e24ff1089f", 1861346),
+	ENGLISH_ENTRY("wearevectors", "WAV.exe", "a524cbb1c51589903c4043b98917f1d9", 5851536),
+	ENGLISH_ENTRY("welcometodarklake", "mystery.exe", "18b284c22010850f79bc5c20054a70c4", 5438912),
+	ENGLISH_ENTRY("wet", "Wet.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 1271457),
+	ENGLISH_ENTRY("what", "what!.exe", "08cb9ad3be9f966132d0c17f0dee471c", 48181831),
+	ENGLISH_ENTRY("whatisthatthing", "somtin.exe", "0500aacb6c176d47ac0f8158f055db83", 1289618),
+	ENGLISH_ENTRY("whatlinusbruckmansees", "LinusBruckman.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 320171493),
+	ENGLISH_ENTRY("wherebedragons", "Where Be Dragons.exe", "d8ccbb83c73ca8520b19412ce0d8de10", 2607599),
+	ENGLISH_ENTRY("wheredidsamgo", "WDSG.exe", "0710e2ec71042617f565c01824f0cf3c", 4921841),
+	ENGLISH_ENTRY("wheresmhatma", "WMHM.exe", "25f919423520b921a041ec854e3a0217", 51766424),
+	ENGLISH_ENTRY("whowantstoliveagain", "Bond.exe", "465f972675db2da6040518221af5b0ba", 2497443),
+	ENGLISH_ENTRY("whowantstoliveforever", "WWtLF.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 6917937),
+	ENGLISH_ENTRY("williamsnightmare", "Killer.exe", "0b7529a76f38283d6e850b8d56526fc1", 3991683),
+	ENGLISH_ENTRY("willowhouse", "Game.exe", "5bc696cf7178870b21db6ac87972befd", 132161306),
+	ENGLISH_ENTRY("willy", "Willy.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 3403804),
+	ENGLISH_ENTRY("winnersdontdodrugs", "windrugs.exe", "ff3358d8f2726d544aadfde4f1ec8407", 2573704),
+	ENGLISH_ENTRY("winterrose", "Winter Rose.exe", "0500aacb6c176d47ac0f8158f055db83", 37444693),
+	ENGLISH_ENTRY("witch", "witch.exe", "06a03fe35791b0578068ab1873455463", 10110407),
+	ENGLISH_ENTRY("witchnight", "wnight.exe", "9cf51833e787cc919837d9a8bd8fc14c", 2792150),
+	ENGLISH_ENTRY("witness", "Witness!.exe", "0710e2ec71042617f565c01824f0cf3c", 803884),
+	ENGLISH_ENTRY("wizardhood", "wiz.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 3693530),
+	ENGLISH_ENTRY("woo", "Woo.exe", "06a03fe35791b0578068ab1873455463", 4771204),
+	ENGLISH_ENTRY("woolyrockbottom", "Wooly.exe", "261d108f9213356a351b35b54867f342", 3409152),
+	ENGLISH_ENTRY("worldofwarcraftquest", "IMBA.exe", "3a96a134156aeccee37daae9a7d5232d", 31743641),
+	ENGLISH_ENTRY("worm", "Worm.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 40704028),
+	ENGLISH_ENTRY("wrathofthesolonoids", "verb.exe", "0500aacb6c176d47ac0f8158f055db83", 3582078),
+	ENGLISH_ENTRY("yoda", "Yoda.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 2461339),
+	ENGLISH_ENTRY("yourgame", "Newgame.exe", "949f7440e3692b7366c2029979dee9a0", 9635719),
+	ENGLISH_ENTRY("yourlate", "Your late.exe", "02635a77ab660023f59519c91329f7f5", 2719997),
+	ENGLISH_ENTRY("zakmckracken", "Zak2.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 8686711),
+	ENGLISH_ENTRY("zombieattackdemo", "ZADemo.exe", "82da2565c456dcfb265ded6fe3189c0b", 20958555),
+	ENGLISH_ENTRY("zombiefish", "FZombie.exe", "3128b9f90e2f954ba704414ae854d10b", 4220305),
+	ENGLISH_ENTRY("zooreal", "zoo_real.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 24184795),
+	ENGLISH_ENTRY("zugzwang", "Zugzwang.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 17209702),
+
 	{ AD_TABLE_END_MARKER }
 };
 


Commit: ef8a01baeee1b55365b64a4c5b871f57575ff001
    https://github.com/scummvm/scummvm/commit/ef8a01baeee1b55365b64a4c5b871f57575ff001
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix compiler warnings

Changed paths:
    engines/ags/events.cpp
    engines/ags/plugins/ags_creditz/ags_creditz.cpp
    engines/ags/plugins/ags_creditz/ags_creditz.h
    engines/ags/plugins/ags_pal_render/ags_pal_render.cpp


diff --git a/engines/ags/events.cpp b/engines/ags/events.cpp
index 3bff16c296..492210eb9f 100644
--- a/engines/ags/events.cpp
+++ b/engines/ags/events.cpp
@@ -86,7 +86,7 @@ int EventsManager::readKey() {
 	Common::KeyState keyState = _pendingKeys.pop();
 
 	int code = getScancode(keyState.keycode) << 8;
-	if (keyState.ascii >= 0 && keyState.ascii <= 127)
+	if (keyState.ascii <= 127)
 		code = keyState.ascii;
 
 	return code;
diff --git a/engines/ags/plugins/ags_creditz/ags_creditz.cpp b/engines/ags/plugins/ags_creditz/ags_creditz.cpp
index 28bc707fae..f88ea7ebf5 100644
--- a/engines/ags/plugins/ags_creditz/ags_creditz.cpp
+++ b/engines/ags/plugins/ags_creditz/ags_creditz.cpp
@@ -77,18 +77,18 @@ int AGSCreditz::IsCreditScrollingFinished(const ScriptMethodParams &params) {
 }
 
 void AGSCreditz::SetCreditImage(const ScriptMethodParams &params) {
-	PARAMS5(int, ID, int, Slot, int, center, int, xpos, int, pixtonext);
+	//PARAMS5(int, ID, int, Slot, int, center, int, xpos, int, pixtonext);
 }
 
 void AGSCreditz::PauseScroll(const ScriptMethodParams &params) {
-	PARAMS1(int, onoff);
+	//PARAMS1(int, onoff);
 }
 
 void AGSCreditz::ScrollReset(const ScriptMethodParams &params) {
 }
 
 void AGSCreditz::SetEmptyLineHeight(const ScriptMethodParams &params) {
-	PARAMS1(int, Height);
+	//PARAMS1(int, Height);
 }
 
 int AGSCreditz::GetEmptyLineHeight(const ScriptMethodParams &params) {
@@ -96,17 +96,17 @@ int AGSCreditz::GetEmptyLineHeight(const ScriptMethodParams &params) {
 }
 
 void AGSCreditz::SetStaticCredit(const ScriptMethodParams &params) {
-	PARAMS8(int, ID, int, x, int, y, int, creditfont, int, creditcolour, int, centered, int, generateoutline, string, credit);
+	//PARAMS8(int, ID, int, x, int, y, int, creditfont, int, creditcolour, int, centered, int, generateoutline, string, credit);
 
 }
 
 string AGSCreditz::GetStaticCredit(const ScriptMethodParams &params) {
-	PARAMS1(int, ID);
+	//PARAMS1(int, ID);
 	return nullptr;
 }
 
 void AGSCreditz::StartEndStaticCredits(const ScriptMethodParams &params) {
-	PARAMS2(int, onoff, int, res);
+	//PARAMS2(int, onoff, int, res);
 }
 
 int AGSCreditz::GetCurrentStaticCredit(const ScriptMethodParams &params) {
@@ -114,26 +114,26 @@ int AGSCreditz::GetCurrentStaticCredit(const ScriptMethodParams &params) {
 }
 
 void AGSCreditz::SetDefaultStaticDelay(const ScriptMethodParams &params) {
-	PARAMS1(int, Cyclesperchar);
+	//PARAMS1(int, Cyclesperchar);
 }
 
 void AGSCreditz::SetStaticPause(const ScriptMethodParams &params) {
-	PARAMS2(int, ID, int, length);
+	//PARAMS2(int, ID, int, length);
 }
 
 void AGSCreditz::SetStaticCreditTitle(const ScriptMethodParams &params) {
-	PARAMS8(int, ID, int, x, int, y, int, titlefont, int, titlecolour, int, centered, int, generateoutline, string, title);
+	//PARAMS8(int, ID, int, x, int, y, int, titlefont, int, titlecolour, int, centered, int, generateoutline, string, title);
 }
 
 void AGSCreditz::ShowStaticCredit(const ScriptMethodParams &params) {
-	PARAMS6(int, ID, int, time, int, style, int, transtime, int, sound, int, resolution);
+	//PARAMS6(int, ID, int, time, int, style, int, transtime, int, sound, int, resolution);
 }
 
 void AGSCreditz::StaticReset(const ScriptMethodParams &params) {
 }
 
 string AGSCreditz::GetStaticCreditTitle(const ScriptMethodParams &params) {
-	PARAMS1(int, ID);
+	//PARAMS1(int, ID);
 	return nullptr;
 }
 
@@ -166,7 +166,7 @@ void AGSCreditz11::AGS_EngineStartup(IAGSEngine *engine) {
 void AGSCreditz11::SetCredit(const ScriptMethodParams &params) {
 	PARAMS7(int, ID, string, credit, int, colour, int, font, int, center, int, xpos, int, generateoutline);
 
-	if (ID >= _state->_credits[0].size())
+	if (ID >= (int)_state->_credits[0].size())
 		_state->_credits[0].resize(ID + 1);
 
 	Credit &c = _state->_credits[0][ID];
@@ -176,6 +176,7 @@ void AGSCreditz11::SetCredit(const ScriptMethodParams &params) {
 	c._x = xpos;
 	c._isSet = true;
 	c._outline = generateoutline;
+	c._color = colour;
 }
 
 void AGSCreditz11::ScrollCredits(const ScriptMethodParams &params) {
@@ -205,7 +206,7 @@ void AGSCreditz11::ScrollCredits(const ScriptMethodParams &params) {
 	}
 }
 
-const string AGSCreditz11::GetCredit(const ScriptMethodParams &params) {
+string AGSCreditz11::GetCredit(const ScriptMethodParams &params) {
 	PARAMS1(int, ID);
 
 	return (_state->_credits[0][ID]._text == IMAGE_TEXT) ?
@@ -243,8 +244,6 @@ void AGSCreditz20::SetCredit(const ScriptMethodParams &params) {
 		c._outline = true;
 }
 
-
-
 } // namespace AGSCreditz
 } // namespace Plugins
 } // namespace AGS3
diff --git a/engines/ags/plugins/ags_creditz/ags_creditz.h b/engines/ags/plugins/ags_creditz/ags_creditz.h
index baf0b73897..d49bddbdf5 100644
--- a/engines/ags/plugins/ags_creditz/ags_creditz.h
+++ b/engines/ags/plugins/ags_creditz/ags_creditz.h
@@ -155,7 +155,7 @@ private:
 
 	static void SetCredit(const ScriptMethodParams &params);
 	static void ScrollCredits(const ScriptMethodParams &params);
-	static const string GetCredit(const ScriptMethodParams &params);
+	static string GetCredit(const ScriptMethodParams &params);
 public:
 	AGSCreditz11();
 };
diff --git a/engines/ags/plugins/ags_pal_render/ags_pal_render.cpp b/engines/ags/plugins/ags_pal_render/ags_pal_render.cpp
index 58f89b6eb3..f0f15c35f0 100644
--- a/engines/ags/plugins/ags_pal_render/ags_pal_render.cpp
+++ b/engines/ags/plugins/ags_pal_render/ags_pal_render.cpp
@@ -1130,9 +1130,9 @@ int DrawReflections(int id, int charobj = 0) {
 	//Initialize stuff
 	BITMAP *charsprite = nullptr;
 	BITMAP *charsprite2 = nullptr;
-	AGSCharacter *currchar;
+	AGSCharacter *currchar = nullptr;
 	AGSObject *currobj;
-	int cox, coy, coz = 0;
+	int cox = 0, coy = 0, coz = 0;
 	int scale = 0;
 	//Get character, and their sprite.
 	if (charobj == 0) {
@@ -1273,7 +1273,7 @@ int DrawReflections(int id, int charobj = 0) {
 
 int DrawTransSprite(int spriteId, int bg, int translevel, int mask = 0, int blendmode = 0, int use_objpal = 0) {
 	BITMAP *maskspr = nullptr;
-	unsigned char **maskarray;
+	unsigned char **maskarray = nullptr;
 	if (mask > 0) maskspr = engine->GetSpriteGraphic(mask);
 	if (!maskspr && mask > 0) {
 		char maskerr [100];
@@ -1327,8 +1327,8 @@ int DrawTransSprite(int spriteId, int bg, int translevel, int mask = 0, int blen
 
 int DrawTranslucentOverlay(int spriteId, int translevel, int ox, int oy, int mask = 0, int blendmode = 0) {
 	if (translevel == 0) return 0;
-	BITMAP *maskspr;
-	unsigned char **maskarray;
+	BITMAP *maskspr = nullptr;
+	unsigned char **maskarray = nullptr;
 	// Get a reference to the screen we'll draw onto
 	BITMAP *virtsc = engine->GetVirtualScreen();
 	//BITMAP *clutspr = engine->GetSpriteGraphic (clutslot);


Commit: f646ceb88974cd11e10642ed8d6edf2256392c69
    https://github.com/scummvm/scummvm/commit/f646ceb88974cd11e10642ed8d6edf2256392c69
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Add listing of some pre-2.5 games to game scanner

Changed paths:
    engines/ags/tests/game_scanner.cpp
    engines/ags/tests/game_scanner.h


diff --git a/engines/ags/tests/game_scanner.cpp b/engines/ags/tests/game_scanner.cpp
index 73e8580349..acbc39bf41 100644
--- a/engines/ags/tests/game_scanner.cpp
+++ b/engines/ags/tests/game_scanner.cpp
@@ -41,9 +41,18 @@ extern GameSetupStruct game;
 void GameScanner::scan() {
 	detectClashes();
 
-	Common::FSNode folder("."); //ConfMan.get("path"));
+	Common::FSNode folder(".");
 	scanFolder(folder);
 
+	if (!_oldGames.empty()) {
+		debug("// Pre 2.5 games that aren't supported");
+		for (EntryArray::iterator it = _oldGames.begin(); it != _oldGames.end(); ++it) {
+			debug("UNSUPPORTED_ENTRY(\"\", \"%s\", \"%s\", %u),",
+				it->_filename.c_str(), it->_md5.c_str(), it->_filesize);
+		}
+		debug("");
+	}
+
 	Common::HashMap<Common::String, bool> gameDescs;
 	for (EntryArray::iterator it = _games.begin(); it != _games.end(); ++it) {
 		if (!gameDescs.contains(it->_id))
@@ -112,18 +121,28 @@ void GameScanner::scanFile(const Common::String &filename) {
 		return;
 
 	AGS::Shared::HError err = preload_game_data();
-	if (!err)
-		return;
-
-	// Add an entry for the found game
-	Entry e;
-	e._filename = fsNode.getName();
-	e._filesize = size;
-	e._gameName = game.gamename;
-	e._id = convertGameNameToId(e._gameName);
-	e._md5 = md5;
-
-	_games.push_back(e);
+	if (!err) {
+		if (err->Code() == AGS::Shared::kMGFErr_FormatVersionTooOld) {
+			Entry e;
+			e._filename = fsNode.getName();
+			e._filename.toLowercase();
+			e._filesize = size;
+			e._md5 = md5;
+
+			_oldGames.push_back(e);
+		}
+	} else {
+		// Add an entry for the found game
+		Entry e;
+		e._filename = fsNode.getName();
+		e._filename.toLowercase();
+		e._filesize = size;
+		e._gameName = game.gamename;
+		e._id = convertGameNameToId(e._gameName);
+		e._md5 = md5;
+
+		_games.push_back(e);
+	}
 } 
 
 Common::String GameScanner::convertGameNameToId(const Common::String &name) {
@@ -131,7 +150,7 @@ Common::String GameScanner::convertGameNameToId(const Common::String &name) {
 
 	for (uint idx = 0; idx < name.size(); ++idx) {
 		char c = name[idx];
-		if (Common::isAlnum(c))
+		if (Common::isDigit(c) || (tolower(c) >= 'a' && tolower(c) <= 'z'))
 			result += tolower(c);
 	}
 
diff --git a/engines/ags/tests/game_scanner.h b/engines/ags/tests/game_scanner.h
index b87a41190c..bf9d70059f 100644
--- a/engines/ags/tests/game_scanner.h
+++ b/engines/ags/tests/game_scanner.h
@@ -41,6 +41,7 @@ class GameScanner {
 private:
 	typedef Common::Array<Entry> EntryArray;
 	EntryArray _games;
+	EntryArray _oldGames;
 private:
 	/**
 	 * Scan a folder for AGS games


Commit: 8a5a0e30cd783e864ce3dcc6a23d64bd2ab327a5
    https://github.com/scummvm/scummvm/commit/8a5a0e30cd783e864ce3dcc6a23d64bd2ab327a5
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: In progress adding pre-2.5 AGS game detection entries

Changed paths:
    engines/ags/detection_tables.h


diff --git a/engines/ags/detection_tables.h b/engines/ags/detection_tables.h
index 2374d76e9c..a3e650f20e 100644
--- a/engines/ags/detection_tables.h
+++ b/engines/ags/detection_tables.h
@@ -26,7 +26,71 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "ags", "Adventure Game Studio Game" },
 
 	// Pre-2.5 games that aren't supported by the current AGS engine
+	{ "6da", "The 6 Day Assassin" },
+	{ "achristmastale", "A Christmas Tale" },
+	{ "adayinthefuture", "A Day In The Future" },
+	{ "adventuregame", "Adventure Game" },
+	{ "bertthenewsreader", "Bert the Newsreader" },
+	{ "bookofspells1", "Book of Spells 1" },
+	{ "bookofspells2", "Book of Spells 2" },
+	{ "bookofspells3", "Book of Spells 3" },
+	{ "bluecupontherun", "BLUECUP - on the run" },
+	{ "calsoon", "Calsoon" },
+	{ "demonslayer1", "Demon Slayer 1" },
+	{ "demonslayer2", "Demon Slayer 2" },
+	{ "demonslayer3", "Demon Slayer 3" },
+	{ "dirkchafberg", "Dirk Chafberg" },
+	{ "earwigisangry", "Earwig Is Angry!" },
+	{ "erniesbigadventure1", "Ernie's Big Adventure" },
+	{ "erniesbigadventure2", "Ernie's Big Adventure 2" },
+	{ "eyesofthejadesphinx", "Eyes of the Jade Sphinx" },
+	{ "gaeafallen", "Gaea Fallen" },
+	{ "grannyzombiekiller", "Granny Zombiekiller in: Mittens Murder Mystery" },
+	{ "gregsmountainousadventure", "Greg's Mountainous Adventure" },
+	{ "hermit", "Hermit" },
+	{ "jamesbondage", "James Bondage" },
+	{ "jinglebells", "Jingle Bells" },
+	{ "larryvales1", "Larry Vales: Traffic Division" },
+	{ "larryvales2", "Larry Vales II: Dead Girls are Easy" },
+	{ "lassi", "Lassi and Roger" },
+	{ "littlejonnyevil", "Little Jonny Evil" },
+	{ "littlewillie", "Little Willie" },
+	{ "ludwig", "VonLudwig" },
+	{ "momsquest", "Mom's Quest" },
+	{ "monkeyplank", "Monkey Plank" },
+	{ "moosewars", "Moose Wars: Desire For More Cows" },
+	{ "murder", "Murder" },
+	{ "nightoftheplumber", "Night of the Plumber" },
+	{ "novomestro", "Novo Mestro" },
+	{ "permanentdaylight", "Permanent Daylight" },
+	{ "perpetrator", "Perpetrator" },
+	{ "pointblank", "Point Blank" },
+	{ "pornquest", "Porn Quest" },
 	{ "qfg412", "Quest for Glory 4 1/2" },
+	{ "raymondskeys", "Raymond's Keys" },
+	{ "richardlonghurst", "Richard Longhurst and the Box That At" },
+	{ "rickylonghurst", "Ricky Longhurst and the Box that Ate Time" },
+	{ "robblanc1", "Rob Blanc I: Better Days of a Defender of the Universe" },
+	{ "robblanc2", "Rob Blanc II: Planet of the Pasteurised Pestilence" },
+	{ "robblanc3", "Rob Blanc III: The Temporal Terrorists" },
+	{ "rodekill", "Rode Kill: A Day In the Life" },
+	{ "rodequest", "Rode Quest" },
+	{ "samthepiratemonkey", "Sam The Pirate Monkey" },
+	{ "slackerquest", "Slacker Quest" },
+	{ "snailquest1", "Snail Quest" },
+	{ "snailquest2", "Snail Quest 2" },
+	{ "snailquest3", "Snail Quest 3" },
+	{ "sol", "Sol" },
+	{ "space", "Space" },
+	{ "superdisk", "Superdisk" },
+	{ "thecrownofgold", "The Crown of Gold" },
+	{ "theisland", "The Island" },
+	{ "thendor", "Thendor" },
+	{ "thewarp", "The Warp" },
+	{ "tulliesworld1", "Tullie's World 1: The Roving of Candale" },
+	{ "tvquest", "TV Quest" },
+	{ "waitkey", "WaitKey();" },
+	{ "winfry", "Winfry" },
 
 	// Post-2.5 games that are likely supported by the AGS engine
 	{ "5daysastranger", "5 Days A Stranger" },
@@ -53,6 +117,8 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "qfi", "Quest for Infamy" },
 	{ "resonance", "Resonance" },
 	{ "unavowed", "Unavowed" },
+	{ "whokilledkennyrogers", "Who Killed Kenny Rogers" },
+	{ "winfry", "Winfry" },
 
 	// Unsorted games
 	{ "10waysfromsunday", "10 Ways from Sunday" },
@@ -442,7 +508,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "gnrblexags", "Gnrblex_AGS" },
 	{ "goneboatfishin", "Gone Boat Fishin'" },
 	{ "goodmorningmrgingerbread", "Good Morning, Mr. Gingerbread!" },
-	{ "goodsantabadsanta", "GoodSanta, BadSanta" },
+	{ "goodsantabadsanta", "Good Santa, Bad Santa" },
 	{ "gotalight", "Got a Light?" },
 	{ "gpslostadventure", "G P's Lost Adventure" },
 	{ "graveyard", "Graveyard" },
@@ -890,7 +956,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "schwarzweissrot", "SchwarzWeissRot" },
 	{ "scnider", "Scnider" },
 	{ "scytheisland", "Scythe Island" },
-	{ "searchforsanitydemo", "Search for Sanity Demo" },
+	{ "searchforsanity", "Search for Sanity" },
 	{ "seashells", "Seashells" },
 	{ "seasongreetings2002", "Season Greetings 2002" },
 	{ "secretquestremake", "Secret Quest Remake" },
@@ -921,10 +987,10 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "sleepyisland", "Sleepy Island" },
 	{ "slimequestforpizza", "Slime-Quest for Pizza" },
 	{ "slugprincess", "SlugPrincess" },
-	{ "sma21", "SMA 2.1" },
-	{ "sma31", "SMA 3.1" },
-	{ "sma4", "SMA 4" },
-	{ "smavi", "SMA VI" },
+	{ "sma2", "Second Moon Adventure Part 2" },
+	{ "sma3", "Second Moon Adventure Part 3 - Rest In Peace" },
+	{ "sma4", "Second Moon Adventure Part 4" },
+	{ "sma6", "Second Moon Adventure Part VI" },
 	{ "smileysquest", "Smiley's Quest" },
 	{ "smileysquest2", "Smiley's Quest 2" },
 	{ "smoothhide", "Smooth Hide" },
@@ -1152,7 +1218,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "wcedit", "WCEdit...             " },
 	{ "wearevectors", "We Are Vectors" },
 	{ "welcometodarklake", "Welcome to Dark Lake" },
-	{ "wet", "WET " },
+	{ "wet", "WET" },
 	{ "what", "what!" },
 	{ "whatisthatthing", "what is that thing" },
 	{ "whatlinusbruckmansees", "What Linus Bruckman Sees" },
@@ -1190,8 +1256,14 @@ const PlainGameDescriptor GAME_NAMES[] = {
 #define UNSUPPORTED_ENTRY(ID, FILENAME, MD5, SIZE) \
 	{{ ID, nullptr, AD_ENTRY1s(FILENAME, MD5, SIZE), Common::EN_ANY, \
 	Common::kPlatformUnknown, ADGF_UNSTABLE, GUIO0() }, nullptr }
+#define UNSUPPORTED_DEMO(ID, FILENAME, MD5, SIZE) \
+	{{ ID, "Demo", AD_ENTRY1s(FILENAME, MD5, SIZE), Common::EN_ANY, \
+	Common::kPlatformUnknown, ADGF_UNSTABLE | ADGF_DEMO, GUIO0() }, nullptr }
+
 #define ENGLISH_ENTRY(ID, FILENAME, MD5, SIZE) \
 	UNSUPPORTED_ENTRY(ID, FILENAME, MD5, SIZE)
+#define ENGLISH_DEMO(ID, FILENAME, MD5, SIZE) \
+	UNSUPPORTED_DEMO(ID, FILENAME, MD5, SIZE)
 
 #define ENGLISH_PLUGIN(ID, FILENAME, MD5, SIZE, PLUGIN_ARR) \
 	{{ ID, nullptr, AD_ENTRY1s(FILENAME, MD5, SIZE), Common::EN_ANY, \
@@ -1202,8 +1274,111 @@ static const PluginVersion AGSCREDITZ_11[] = { { "agscreditz", 11 }, { nullptr,
 
 const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	// Pre-2.5 games that aren't supported by the current AGS engine
+	UNSUPPORTED_ENTRY("6da", "6da.exe", "9027912819f3a319ed9de0fd855310c3", 1608073),
+	UNSUPPORTED_DEMO("achristmastale", "tale.exe", "094135f05cf14fc3903e0d3697911a4e", 1484122),
+	UNSUPPORTED_ENTRY("adayinthefuture", "space.exe", "ecd0793124fbc9b89c6d11162e3b5851", 4120328),
+	UNSUPPORTED_ENTRY("adventuregame", "adventure.exe", "221637e5d62e2ca3cc146846ab0b2e49", 5533207),
+	UNSUPPORTED_ENTRY("bertthenewsreader", "bert.exe", "80bdce9a1052e896c7cba6a4334cecce", 2814934),
+	UNSUPPORTED_ENTRY("bookofspells1", "ac2game.dat", "fe66cb08bcffd094c159cd4ee72bacd3", 3442073),
+	UNSUPPORTED_ENTRY("bookofspells2", "ac2game.dat", "9df87a8e5bbcc7206b001c0b8316b7f9", 3263169),
+	UNSUPPORTED_ENTRY("bookofspells3", "ac2game.dat", "9f0181393bdceb2c0bbdb06634714023", 4806518),
+	UNSUPPORTED_ENTRY("bluecupontherun", "ac2game.dat", "c290455f00f630c8a52c7eceb7c663eb", 1995708),
+	UNSUPPORTED_ENTRY("calsoon", "calsoon.exe", "5477f4ed8f860427d1492548b677073c", 2865508),
+	UNSUPPORTED_ENTRY("demonslayer1", "mags.exe", "1f0edcb7fa3f8e2b1dd60fa6c0bce60f", 3820347),
+	UNSUPPORTED_ENTRY("demonslayer2", "bert.exe", "0c057c5e6df6f45772286986ab7b7a5b", 1726766),
+	UNSUPPORTED_ENTRY("demonslayer3", "tiler.exe", "426e34f40e0dc5285af3fb5fc32a220e", 2586532),
+	UNSUPPORTED_ENTRY("dirkchafberg", "ac2game.dat", "be7bec4a433beb5085184b64119351c8", 1906822),
+	UNSUPPORTED_ENTRY("earwigisangry", "earwig.exe", "04eedea9846d380d6d9a120f657daa43", 2371856),
+	UNSUPPORTED_ENTRY("erniesbigadventure1", "magsjune.exe", "fc5f54dcfc82d3b991f670490a316958", 8814849),
+	UNSUPPORTED_ENTRY("erniesbigadventure2", "magsjuly.exe", "2fd8ca69f236ae1ad46edab4ba26a33d", 6647578),
+	UNSUPPORTED_ENTRY("eyesofthejadesphinx", "jade.exe", "f2fe94ab604612e4595f3c79b0245529", 10763660),
+	UNSUPPORTED_ENTRY("gaeafallen", "gaea_fallen.exe", "80bdce9a1052e896c7cba6a4334cecce", 11273205),
+	UNSUPPORTED_ENTRY("grannyzombiekiller", "mags.exe", "0c057c5e6df6f45772286986ab7b7a5b", 12855495),
+	UNSUPPORTED_ENTRY("gregsmountainousadventure", "mags.exe", "80a17966fc547849d43646acf89de296", 2112993),
+	UNSUPPORTED_ENTRY("hermit", "hermit.exe", "4689069dd6b241e38311d0586e610a8d", 13995403),
+	UNSUPPORTED_ENTRY("jamesbondage", "jbdos.exe", "1f0edcb7fa3f8e2b1dd60fa6c0bce60f", 2056737),
+	UNSUPPORTED_ENTRY("jinglebells", "jinglebells.exe", "385a593828b1edb194e984ce55cda65e", 1620588),
+	UNSUPPORTED_ENTRY("larryvales1", "larryvtd.exe", "610b7a3d1fd90f24d2218aa26b29d8ca", 3129645),
+	UNSUPPORTED_ENTRY("larryvales2", "dead.exe", "be48a6b0b81a71d34a41930623c065f1", 3946993),
+	UNSUPPORTED_ENTRY("lassi", "lassi.exe", "ed778afb4f46c3f2a70d330532a83a2f", 3681914),
+	UNSUPPORTED_ENTRY("littlejonnyevil", "lje.exe", "e93037e8efc7abc19b8978903ef5b409", 2133182),
+	UNSUPPORTED_ENTRY("littlewillie", "ac2game.dat", "239b11ab644222c67d981494766a3c25", 254128),
+	UNSUPPORTED_ENTRY("ludwig", "ludwig.exe", "727a30f9244441ad57a76086f4faa779", 3658869),
+	UNSUPPORTED_ENTRY("momsquest", "mom's quest.exe", "73f87b30f84e9c34ab09ec8dd7ae109d", 3173896),
+	UNSUPPORTED_ENTRY("monkeyplank", "plank.exe", "1f0edcb7fa3f8e2b1dd60fa6c0bce60f", 815948),
+	UNSUPPORTED_ENTRY("moosewars", "moose.exe", "f4585823c1b4ce97d78c8acb433bec52", 1448684),
+	UNSUPPORTED_ENTRY("murder", "murder.exe", "221637e5d62e2ca3cc146846ab0b2e49", 935799),
+	UNSUPPORTED_ENTRY("nightoftheplumber", "night of the plumber.exe", "1f0edcb7fa3f8e2b1dd60fa6c0bce60f", 1703896),
+	UNSUPPORTED_ENTRY("novomestro", "novo.exe", "07f9921784124d9e09f39bb831e06131", 1122507),
+	UNSUPPORTED_ENTRY("permanentdaylight", "daylight.exe", "07f9921784124d9e09f39bb831e06131", 1799958),
+	UNSUPPORTED_ENTRY("perpetrator", "ac2game.dat", "56ef979be112e122e24d0cc8caea4ea4", 994303),
+	UNSUPPORTED_DEMO("pointblank", "future.exe", "385a593828b1edb194e984ce55cda65e", 1379714),
+	UNSUPPORTED_ENTRY("pornquest", "porn.exe", "04eedea9846d380d6d9a120f657daa43", 1012323),
 	UNSUPPORTED_ENTRY("qfg412", "qfg.exe", "8b21668ca462b0b6b35df43c5902b074", 26674790),
-
+	UNSUPPORTED_ENTRY("qfg412", "qfg.exe",  "9027912819f3a319ed9de0fd855310c3", 26954823),
+	UNSUPPORTED_ENTRY("raymondskeys", "keys.exe", "e016cb68731d0e38fe97905dbf0d5b36", 1032178),
+	UNSUPPORTED_ENTRY("richardlonghurst", "rlbat-win.exe", "04eedea9846d380d6d9a120f657daa43", 7935723),
+	UNSUPPORTED_ENTRY("rickylonghurst", "bleach.exe", "9027912819f3a319ed9de0fd855310c3", 1174829),
+	UNSUPPORTED_ENTRY("robblanc1", "ac2game.dat", "29c2ced2f2e6ad764e4249b4e4c45bba", 920415),
+	UNSUPPORTED_ENTRY("robblanc2", "ac2game.dat", "dd6c52e5a6e9b70efef4654769f11c69", 2056386),
+	UNSUPPORTED_ENTRY("robblanc3", "ac2game.dat", "8f8264de3c1bd91e26b84fe37fb5e53e", 2828959),
+	UNSUPPORTED_ENTRY("rodekill", "rodekill.exe", "72f3c950b4d9d14580a11db885a63310", 11995954),
+	UNSUPPORTED_ENTRY("rodequest", "rodequest1.exe", "72f3c950b4d9d14580a11db885a63310", 1196458),
+	UNSUPPORTED_ENTRY("samthepiratemonkey", "monkey.exe", "73f87b30f84e9c34ab09ec8dd7ae109d", 1401414),
+	UNSUPPORTED_ENTRY("slackerquest", "ac2game.dat", "e0998f2d2e14a55aae2291fdfab1ce7d", 1306492),
+	UNSUPPORTED_ENTRY("snailquest1", "snailquest.exe", "dd69243e3cc9e955215e0d556301b58e", 1095860),
+	UNSUPPORTED_ENTRY("snailquest2", "sq2.exe", "1bccd2edef19abc99e9683519d80c0e0", 955614),
+	UNSUPPORTED_ENTRY("snailquest3", "sq3.exe", "1bccd2edef19abc99e9683519d80c0e0", 1501892),
+	UNSUPPORTED_ENTRY("sol", "sol.exe", "73f87b30f84e9c34ab09ec8dd7ae109d", 4702799),
+	UNSUPPORTED_ENTRY("space", "space.exe", "094135f05cf14fc3903e0d3697911a4e", 3790026),
+	UNSUPPORTED_ENTRY("superdisk", "superdisk.exe", "80bdce9a1052e896c7cba6a4334cecce", 1304065),
+	UNSUPPORTED_ENTRY("thecrownofgold", "the crown of gold.exe", "e407143be000e44f113ba5ff1fbd17f9", 1971515),
+	UNSUPPORTED_ENTRY("theisland", "island.exe", "e93037e8efc7abc19b8978903ef5b409", 1814801),
+	UNSUPPORTED_ENTRY("thendor", "ac2game.dat",  "b9c2ad76574c08bbcfd56eb1b49d2cd3", 8580708),
+	UNSUPPORTED_ENTRY("thewarp", "warp.exe", "9027912819f3a319ed9de0fd855310c3", 881957),
+	UNSUPPORTED_ENTRY("tulliesworld1", "candale.exe", "1c21bdb52bcafcafe988b30fd6bb4126", 3936603),
+	UNSUPPORTED_ENTRY("tvquest", "mags.exe", "fc5f54dcfc82d3b991f670490a316958", 1318019),
+	UNSUPPORTED_DEMO("waitkey", "ac2game.dat", "8ddf3744922101e33305dfcd06e3b682", 445197),
+	UNSUPPORTED_ENTRY("whokilledkennyrogers", "mags.exe", "ed778afb4f46c3f2a70d330532a83a2f", 1240103),
+	UNSUPPORTED_ENTRY("winfry", "fry.exe", "73f87b30f84e9c34ab09ec8dd7ae109d", 4164041),
+#ifdef TODO
+	UNSUPPORTED_ENTRY("", "carver2.exe", "ed778afb4f46c3f2a70d330532a83a2f", 6265594),
+	UNSUPPORTED_ENTRY("", "dem four.exe", "426e34f40e0dc5285af3fb5fc32a220e", 5110674),
+	UNSUPPORTED_ENTRY("", "mags.exe", "0c057c5e6df6f45772286986ab7b7a5b", 12855495),
+	UNSUPPORTED_ENTRY("", "qfc.exe", "04eedea9846d380d6d9a120f657daa43", 2038696),
+	UNSUPPORTED_ENTRY("", "qfc.exe", "04eedea9846d380d6d9a120f657daa43", 2038696),
+	UNSUPPORTED_ENTRY("", "rollinfoy.exe", "19f4045333d9c823a5439d0447d55985", 3454107),
+	UNSUPPORTED_ENTRY("", "tom mato's grand wing-ding.exe", "73f87b30f84e9c34ab09ec8dd7ae109d", 2735158),
+	UNSUPPORTED_ENTRY("", "fart.exe", "fc5f54dcfc82d3b991f670490a316958", 1138006),
+	UNSUPPORTED_ENTRY("", "thetower.exe", "9027912819f3a319ed9de0fd855310c3", 3431385),
+	UNSUPPORTED_ENTRY("", "mtg.exe", "ed778afb4f46c3f2a70d330532a83a2f", 1618544),
+	UNSUPPORTED_ENTRY("", "assassin.exe", "73f87b30f84e9c34ab09ec8dd7ae109d", 2659741),
+	UNSUPPORTED_ENTRY("", "burns.exe", "094135f05cf14fc3903e0d3697911a4e", 2120885),
+	UNSUPPORTED_ENTRY("", "ripp.exe", "426e34f40e0dc5285af3fb5fc32a220e", 10489586),
+	UNSUPPORTED_ENTRY("", "indy.exe", "094135f05cf14fc3903e0d3697911a4e", 1545150),
+	UNSUPPORTED_ENTRY("", "aaron.exe", "1c21bdb52bcafcafe988b30fd6bb4126", 1788404),
+	UNSUPPORTED_ENTRY("", "adventure.exe", "221637e5d62e2ca3cc146846ab0b2e49", 5533207),
+	UNSUPPORTED_ENTRY("", "bq2.exe", "1c21bdb52bcafcafe988b30fd6bb4126", 2540006),
+	UNSUPPORTED_ENTRY("", "comp.exe", "094135f05cf14fc3903e0d3697911a4e", 2054366),
+	UNSUPPORTED_ENTRY("", "dart.exe", "ed778afb4f46c3f2a70d330532a83a2f", 736848),
+	UNSUPPORTED_ENTRY("", "burro.exe", "1f0edcb7fa3f8e2b1dd60fa6c0bce60f", 2209309),
+	UNSUPPORTED_ENTRY("", "exile.exe", "aad0a09714fab4de51e5488da48fd5d4", 13421451),
+	UNSUPPORTED_ENTRY("", "firewall demo.exe", "2fd8ca69f236ae1ad46edab4ba26a33d", 2839412),
+	UNSUPPORTED_ENTRY("", "lupo.exe", "19f4045333d9c823a5439d0447d55985", 1856459),
+	UNSUPPORTED_ENTRY("", "0112.men in brown.exe", "426e34f40e0dc5285af3fb5fc32a220e", 2072392),
+	UNSUPPORTED_ENTRY("", "moose.exe", "f4585823c1b4ce97d78c8acb433bec52", 1448684),
+	UNSUPPORTED_ENTRY("", "greywin.exe", "80bdce9a1052e896c7cba6a4334cecce", 1283447),
+	UNSUPPORTED_ENTRY("", "mtsodos.exe", "1f0edcb7fa3f8e2b1dd60fa6c0bce60f", 777967),
+	UNSUPPORTED_ENTRY("", "mtsowin.exe", "73f87b30f84e9c34ab09ec8dd7ae109d", 1076035),
+	UNSUPPORTED_ENTRY("", "nw1demo.exe", "1f0edcb7fa3f8e2b1dd60fa6c0bce60f", 1539596),
+	UNSUPPORTED_ENTRY("", "odysseus.exe", "426e34f40e0dc5285af3fb5fc32a220e", 2799113),
+	UNSUPPORTED_ENTRY("", "pd.exe", "ecd0793124fbc9b89c6d11162e3b5851", 3853394),
+	UNSUPPORTED_ENTRY("", "pqwin.exe", "73f87b30f84e9c34ab09ec8dd7ae109d", 2500089),
+	UNSUPPORTED_ENTRY("", "moonsdt.exe", "9027912819f3a319ed9de0fd855310c3", 1276725),
+	UNSUPPORTED_ENTRY("", "stickmen.exe", "094135f05cf14fc3903e0d3697911a4e", 2145142),
+	UNSUPPORTED_ENTRY("", "teamwork.exe", "538274077115c6d8b4a0927dd3cceeac", 1096149),
+	UNSUPPORTED_ENTRY("", "blackjack.exe", "73f87b30f84e9c34ab09ec8dd7ae109d", 1153092),
+#endif
 	// Post-2.5 games that are likely supported by the AGS engine
 	ENGLISH_ENTRY("5daysastranger", "5days.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 4440143),
 	ENGLISH_ENTRY("7daysaskeptic", "7days.exe", "465f972675db2da6040518221af5b0ba", 4693374),
@@ -1632,7 +1807,7 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("gnrblexags", "Gnrblex_AGS.exe", "476a1a39d43ea27577eacf907173e2c1", 85038656),
 	ENGLISH_ENTRY("goneboatfishin", "Gone Boat Fishin'.exe", "bdd1df0484e296faa348ffcb03e16273", 72936045),
 	ENGLISH_ENTRY("goodmorningmrgingerbread", "mister_gingerbread.exe", "b42f80733b6bd1ded5e29be2c683afa8", 7084332),
-	ENGLISH_ENTRY("goodsantabadsanta", "X-Mags.exe", "71ca0d6c1c699595f28a2125948d4a84", 1966547),
+	ENGLISH_ENTRY("goodsantabadsanta", "x-mags.exe", "71ca0d6c1c699595f28a2125948d4a84", 1966547),
 	ENGLISH_ENTRY("gotalight", "gotalight.exe", "daa21f03e41b5d3e7fd7558be3f8616e", 4019593),
 	ENGLISH_ENTRY("gpslostadventure", "G.P.s Lost Adventure [Wells8892].exe", "06a03fe35791b0578068ab1873455463", 4181945),
 	ENGLISH_ENTRY("graveyard", "Graveyard.exe", "955b711b21d7a2df6af1bb0cccccbb08", 13699789),
@@ -2092,7 +2267,7 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("schwarzweissrot", "SchwarzWeissRot.exe", "495d45fb8adfd49690ae3b97921feec6", 82913128),
 	ENGLISH_ENTRY("scnider", "scnider.exe", "3128b9f90e2f954ba704414ae854d10b", 1189237),
 	ENGLISH_ENTRY("scytheisland", "Scythe.exe", "0500aacb6c176d47ac0f8158f055db83", 7119760),
-	ENGLISH_ENTRY("searchforsanitydemo", "sfs.exe", "308d35bc34e9df29d8acce615593e3e7", 9097147),
+	ENGLISH_DEMO("searchforsanity", "sfs.exe", "308d35bc34e9df29d8acce615593e3e7", 9097147),
 	ENGLISH_ENTRY("seashells", "Shells.exe", "0500aacb6c176d47ac0f8158f055db83", 6355325),
 	ENGLISH_ENTRY("seasongreetings2002", "xmas2002.exe", "97d700529f5cc826f230c27acf81adfd", 4263336),
 	ENGLISH_ENTRY("secretquestremake", "secretquest.exe", "f120690b506dd63cd7d1112ea6af2f77", 2121159),
@@ -2123,10 +2298,10 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("sleepyisland", "Sleepy Island.exe", "465f972675db2da6040518221af5b0ba", 20270790),
 	ENGLISH_ENTRY("slimequestforpizza", "slime.exe", "95b7dd55f6e15c8a2118856ed9fe8ff9", 1661109),
 	ENGLISH_ENTRY("slugprincess", "SlugPrincess.exe", "28f82e420b82d07651b68114f90223c8", 12132209),
-	ENGLISH_ENTRY("sma21", "sma21.exe", "02094e217c23e1d40a84891ee95010cb", 7093110),
-	ENGLISH_ENTRY("sma31", "sma31.exe", "4d17844029d8910fbaae1bdc99e250f2", 4961734),
+	ENGLISH_ENTRY("sma2", "sma21.exe", "02094e217c23e1d40a84891ee95010cb", 7093110),
+	ENGLISH_ENTRY("sma3", "sma31.exe", "4d17844029d8910fbaae1bdc99e250f2", 4961734),
 	ENGLISH_ENTRY("sma4", "smavier.exe", "02094e217c23e1d40a84891ee95010cb", 2447360),
-	ENGLISH_ENTRY("smavi", "sma6.exe", "64fcaf7da0b257ea831f89c54be0ad72", 3735081),
+	ENGLISH_ENTRY("sma6", "sma6.exe", "64fcaf7da0b257ea831f89c54be0ad72", 3735081),
 	ENGLISH_ENTRY("smileysquest", "Smiley.exe", "90413e9ae57e222f8913b09d2bc847bc", 4938049),
 	ENGLISH_ENTRY("smileysquest2", "mags.exe", "3128b9f90e2f954ba704414ae854d10b", 2108492),
 	ENGLISH_ENTRY("smoothhide", "SmoothHide.exe", "b142b43c146c25443a1d155d441a6a81", 10006680),


Commit: 5023339db964d11242c6f6f44078aaa748abcf0f
    https://github.com/scummvm/scummvm/commit/5023339db964d11242c6f6f44078aaa748abcf0f
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: More pre 2.5 detection entries

Changed paths:
    engines/ags/detection_tables.h


diff --git a/engines/ags/detection_tables.h b/engines/ags/detection_tables.h
index a3e650f20e..5d73045d4b 100644
--- a/engines/ags/detection_tables.h
+++ b/engines/ags/detection_tables.h
@@ -27,68 +27,110 @@ const PlainGameDescriptor GAME_NAMES[] = {
 
 	// Pre-2.5 games that aren't supported by the current AGS engine
 	{ "6da", "The 6 Day Assassin" },
+	{ "aaronsepicjourney", "Aaron's Epic Journey" },
+	{ "aceduswell", "Ace Duswell - Where's The Ace" },
 	{ "achristmastale", "A Christmas Tale" },
 	{ "adayinthefuture", "A Day In The Future" },
 	{ "adventuregame", "Adventure Game" },
+	{ "asapadventure", "ASAP Adventure" },
 	{ "bertthenewsreader", "Bert the Newsreader" },
+	{ "bobsquest2", "Bob's Quest 2: The quest for the AGS Blue cup award " },
 	{ "bookofspells1", "Book of Spells 1" },
 	{ "bookofspells2", "Book of Spells 2" },
 	{ "bookofspells3", "Book of Spells 3" },
 	{ "bluecupontherun", "BLUECUP - on the run" },
 	{ "calsoon", "Calsoon" },
+	{ "carverisland1", "The Secret of Carver Island" },
+	{ "carverisland2", "Carver Island 2: Mrs. Rodriguez's Revenge" },
+	{ "chamber", "Chamber" },
+	{ "compensation", "Compensation" },
+	{ "darts", "Darts" },
 	{ "demonslayer1", "Demon Slayer 1" },
 	{ "demonslayer2", "Demon Slayer 2" },
 	{ "demonslayer3", "Demon Slayer 3" },
+	{ "demonslayer4", "Demon Slayer 4" },
+	{ "deepbright", "Deepbright" },
 	{ "dirkchafberg", "Dirk Chafberg" },
 	{ "earwigisangry", "Earwig Is Angry!" },
+	{ "eclair1", "Eclair 1" },
+	{ "eclair2", "Eclair 2" },
+	{ "elburro", "El Burro" },
 	{ "erniesbigadventure1", "Ernie's Big Adventure" },
 	{ "erniesbigadventure2", "Ernie's Big Adventure 2" },
+	{ "exile", "Exile" },
 	{ "eyesofthejadesphinx", "Eyes of the Jade Sphinx" },
+	{ "firewall", "Firewall" },
+	{ "floyd", "Floyd" },
 	{ "gaeafallen", "Gaea Fallen" },
+	{ "gorthor", "Gorther of the Cave People" },
 	{ "grannyzombiekiller", "Granny Zombiekiller in: Mittens Murder Mystery" },
 	{ "gregsmountainousadventure", "Greg's Mountainous Adventure" },
+	{ "greysgreytadv", "Mr. Grey's Greyt Adventure" },
 	{ "hermit", "Hermit" },
 	{ "jamesbondage", "James Bondage" },
 	{ "jinglebells", "Jingle Bells" },
+	{ "kidnapped", "Kidnapped" },
 	{ "larryvales1", "Larry Vales: Traffic Division" },
 	{ "larryvales2", "Larry Vales II: Dead Girls are Easy" },
+	{ "larryvales3", "Larry Vales III: Time Heals All 'Burns" },
 	{ "lassi", "Lassi and Roger" },
+	{ "lassiandrogermeetgod", "Lassi and Roger Meet God" },
+	{ "lassiquesti", "Lassi Quest I" },
 	{ "littlejonnyevil", "Little Jonny Evil" },
 	{ "littlewillie", "Little Willie" },
+	{ "lsl2remake", "Leisure Suit Larry 2 Point and Click" },
 	{ "ludwig", "VonLudwig" },
+	{ "lupoinutile", "Lupo Inutile" },
+	{ "mafio", "Mafio" },
+	{ "meninbrown", "Men In Brown" },
+	{ "midtownshootout", "Anton Ulvfot's Mid-Town Shootout" },
 	{ "momsquest", "Mom's Quest" },
 	{ "monkeyplank", "Monkey Plank" },
 	{ "moosewars", "Moose Wars: Desire For More Cows" },
 	{ "murder", "Murder" },
+	{ "nicholaswolfe1", "Nicholas Wolfe part I: Framed" },
 	{ "nightoftheplumber", "Night of the Plumber" },
 	{ "novomestro", "Novo Mestro" },
+	{ "odysseus", "The Trials of Odysseus Kent" },
 	{ "permanentdaylight", "Permanent Daylight" },
 	{ "perpetrator", "Perpetrator" },
+	{ "pizzaquest", "Pizza Quest" },
 	{ "pointblank", "Point Blank" },
 	{ "pornquest", "Porn Quest" },
+	{ "qfc", "Quest For Colours" },
 	{ "qfg412", "Quest for Glory 4 1/2" },
+	{ "racingmanager", "Racing Manager" },
 	{ "raymondskeys", "Raymond's Keys" },
+	{ "red", "Red" },
 	{ "richardlonghurst", "Richard Longhurst and the Box That At" },
 	{ "rickylonghurst", "Ricky Longhurst and the Box that Ate Time" },
+	{ "ripp", "RIPP" },
 	{ "robblanc1", "Rob Blanc I: Better Days of a Defender of the Universe" },
 	{ "robblanc2", "Rob Blanc II: Planet of the Pasteurised Pestilence" },
 	{ "robblanc3", "Rob Blanc III: The Temporal Terrorists" },
 	{ "rodekill", "Rode Kill: A Day In the Life" },
 	{ "rodequest", "Rode Quest" },
+	{ "rollinfoy", "Rollinfoy" },
 	{ "samthepiratemonkey", "Sam The Pirate Monkey" },
+	{ "secondmoonadv1", "Second Moon Adventure Part 1 - Night" },
 	{ "slackerquest", "Slacker Quest" },
 	{ "snailquest1", "Snail Quest" },
 	{ "snailquest2", "Snail Quest 2" },
 	{ "snailquest3", "Snail Quest 3" },
 	{ "sol", "Sol" },
 	{ "space", "Space" },
+	{ "stickmen", "Stickmen" },
 	{ "superdisk", "Superdisk" },
 	{ "thecrownofgold", "The Crown of Gold" },
+	{ "theinexperiencedassassin", "The Inexperienced Assassin" },
 	{ "theisland", "The Island" },
 	{ "thendor", "Thendor" },
+	{ "thetower", "The Tower" },
 	{ "thewarp", "The Warp" },
+	{ "tommato", "Tom Mato's Grand Wing-Ding" },
 	{ "tulliesworld1", "Tullie's World 1: The Roving of Candale" },
 	{ "tvquest", "TV Quest" },
+	{ "uishowoff", "Interface Show-off" },
 	{ "waitkey", "WaitKey();" },
 	{ "winfry", "Winfry" },
 
@@ -128,10 +170,11 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "3piggiesalpha", "3piggiesAlpha" },
 	{ "46memorylane", "46 Memory Lane" },
 	{ "4ofclubs", "4 of Clubs" },
+	{ "5oclocklock", "5-O'clock Lock" },
 	{ "6daysasacrifice", "6 Days A Sacrifice" },
 	{ "6mornings", "6mornings" },
 	{ "aazor", "Aazor" },
-	{ "abducted", "ABDUCTED" },
+	{ "abducted", "Abducted" },
 	{ "absent", "Absent" },
 	{ "absentparti", "Absent - Part I" },
 	{ "access", "_Access" },
@@ -163,6 +206,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "agsdarts", "AGS Darts" },
 	{ "agsinvaders", "AGS Invaders" },
 	{ "agsjukebox", "AGS JukeBox" },
+	{ "agsmittensshooter", "AGS Mittens Shooter" },
 	{ "agsmoduletester", "Ags Module Tester" },
 	{ "agsyahtzee2", "AGS Yahtzee 2" },
 	{ "agsyathzee", "AGS Yathzee" },
@@ -272,6 +316,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "boom", "Boom" },
 	{ "bowserquirkquest", "Bowser Quirk Quest" },
 	{ "box", "Box" },
+	{ "boxfight", "Boxfight" },
 	{ "boyindahood", "Boy in da hood" },
 	{ "bradbradsonkeyquest", "Brad Bradson: Key Quest" },
 	{ "breakdownbyonedollar", "Breakdown by OneDollar" },
@@ -316,7 +361,6 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "cirquedezale", "Cirque de Zale" },
 	{ "claire", "Claire" },
 	{ "classnotesv11", "Class Notes v1.1" },
-	{ "clex", "Clex" },
 	{ "clipl2heblinna", "Clip l2heb linna" },
 	{ "clubofevil", "Club of Evil" },
 	{ "coeldeckaflightgame", "Coel Decka Flight Game" },
@@ -337,6 +381,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "cosmosquestiii", "Cosmos Quest III" },
 	{ "cougarsquestforfreedom", "Cougar's Quest for Freedom" },
 	{ "counterfeit", "Counterfeit" },
+	{ "coupdecup", "Coup de Cup" },
 	{ "cow", "cow" },
 	{ "coyote", "Coyote" },
 	{ "craftofevil", "Craft Of Evil" },
@@ -460,7 +505,6 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "feuersturmkapitel2", "Feuersturm - Kapitel 2" },
 	{ "feuersturmkapitel3", "Feuersturm - Kapitel 3" },
 	{ "fifa2003pro", "Fifa2003Pro" },
-	{ "fight", "Fight" },
 	{ "fightgame", "Fight Game" },
 	{ "fireflystory3d", "Firefly story 3D" },
 	{ "flamebarrel", "Flame Barrel" },
@@ -514,6 +558,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "graveyard", "Graveyard" },
 	{ "gremlin", "Gremlin" },
 	{ "grizzlygooseofgosse", "Grizzly Goose of Gosse" },
+	{ "grok", "Grok" },
 	{ "grr", "Grr!" },
 	{ "guardiansofgold", "Guardians of Gold" },
 	{ "guyslug", "Guy Slug" },
@@ -558,7 +603,6 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "huongjiaoping", "Huong Jiao Ping" },
 	{ "huxzadventure", "Huxz Adventure" },
 	{ "hydeandseek", "Hyde and Seek" },
-	{ "iaman00b11omgwtflol", "i am a n00b!!1!!1!OMG WTF LOL" },
 	{ "iamjason", "IAMJASON" },
 	{ "iforgot", "I forgot..." },
 	{ "igs", "IGS" },
@@ -599,6 +643,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "joesmiserablelife", "Joe's Miserable Life" },
 	{ "johnharrissafrakincse", "John Harris ?s a f?ra? kincse" },
 	{ "johnjebediahgunelisoladisepheret", "John Jebediah Gun e l'Isola di Sepheret" },
+	{ "johnlosthiskey", "John Lost his key" },
 	{ "johnnyrocket", "Johnny_Rocket" },
 	{ "johnsinclairvoodooinlondon", "John Sinclair - Voodoo in London" },
 	{ "jonnysmallvalley", "Jonny Smallvalley" },
@@ -701,16 +746,16 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "maniacmansionmania02", "Maniac Mansion Mania 02" },
 	{ "mardsrevengebytk", "Mard's Revenge by TK" },
 	{ "martyausdemall", "Marty aus dem All" },
-	{ "mastersofsound", "MASTERS OF SOUND" },
+	{ "mastersofsound", "Masters of Sound" },
 	{ "matttothefuture", "Matt to the Future" },
 	{ "medicaltheoriesofdrkur", "Medical Theories of Dr Kur" },
 	{ "mego2008silvesteredition", "Me Go 2008: Silvester Edition" },
 	{ "megoaway", "Me Go... Away!" },
 	{ "megocannibaljungle", "Me Go Cannibal Jungle!" },
 	{ "megostore", "Me Go Store!" },
-	{ "melrinthediscipleordeal", "Melrin: The disciple ordeal" },
-	{ "melrinthedragonmenace", "Melrin: The Dragon Menace" },
-	{ "melrinthependantquest", "Melrin: The Pendant Quest" },
+	{ "melrin1", "Melrin: The Disciple Ordeal" },
+	{ "melrin2", "Melrin: The Pendant Quest" },
+	{ "melrin3", "Melrin: The Dragon Menace" },
 	{ "meltdrake3chapter1", "Melt & Drake 3 Chapter 1" },
 	{ "memoriesfade", "Memories Fade" },
 	{ "meninhats", "Men In Hats" },
@@ -765,7 +810,6 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "necroquest", "Necroquest" },
 	{ "nedysadventure", "Nedy's adventure" },
 	{ "nekusnewtrip", "Neku's new trip" },
-	{ "newgame", "New Game" },
 	{ "nellycootalotv15", "Nelly Cootalot v1.5" },
 	{ "neofeud", "Neofeud" },
 	{ "nesquest", "NES Quest" },
@@ -854,7 +898,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "postmansquest", "Postman's Quest" },
 	{ "powernap", "Power Nap" },
 	{ "powerunlimited", "Power Unlimited" },
-	{ "pqtadventure", "PQTADVENTURE" },
+	{ "pqtadventure", "PQT Adventure" },
 	{ "practicescript", "Practice Script" },
 	{ "predatorspreyforplants", "Predators Prey For Plants" },
 	{ "princessandallthekingdom", "Princess and all the kingdom" },
@@ -917,10 +961,10 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "roadofdestiny", "Road of Destiny" },
 	{ "roadracer", "Road Racer" },
 	{ "roastmothergoose", "Roast Mother Goose" },
-	{ "robbertredfordsavestheday", "Robbert Redford saves the day" },
 	{ "robbingtheprincess", "Robbing The Princess" },
-	{ "robertredford3", "Robert Redford 3" },
-	{ "robertredfordsavestheday", "Robert Redford saves the day" },
+	{ "robertredford1", "Robert Redford saves the day Ep 1" },
+	{ "robertredford2", "Robert Redford saves the day Ep 2" },
+	{ "robertredford3", "Robert Redford saves the day Ep 3" },
 	{ "robmassacreofchainsawness", "Rob: Massacre of Chainsawness" },
 	{ "robotragedy", "Robotragedy" },
 	{ "robotragedy2", "Robotragedy 2" },
@@ -964,9 +1008,9 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "seega16engl5", "seega16_engl_5" },
 	{ "seegame15", "seegame15" },
 	{ "sevendoors", "Seven  Doors" },
-	{ "sga", "SGA" },
+	{ "stargateadv", "Stargate Adventure" },
 	{ "shadesofgreye", "Shades of Greye" },
-	{ "shadowsoftheempiretd", "Shadows of the Empire - TD" },
+	{ "shadowsoftheempire", "Shadows of the Empire" },
 	{ "shailadusithlenqute", "Shai-la du Sith : l'Enqu?te" },
 	{ "shailaofthesith", "Shai-la of the Sith" },
 	{ "shem", "Shem" },
@@ -1006,9 +1050,9 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "spacelynxes", "Space Lynxes" },
 	{ "spacepirates", "Space Pirates" },
 	{ "spacepoolalpha", "Space Pool Alpha" },
+	{ "spacequest3vgapreview", "Space Quest III VGA Preview" },
 	{ "spacequest45", "Space Quest 4.5" },
 	{ "spacequest55demoags", "Space Quest 5.5 demo (AGS)" },
-	{ "spacequestiiivgapreview", "Space Quest III VGA Preview" },
 	{ "sqm11", "Space Quest Mania 1x1" },
 	{ "sqm12", "Space Quest Mania 1x2" },
 	{ "sqm13", "Space Quest Mania 1x3" },
@@ -1040,7 +1084,6 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "stediddyip1employment", "Stediddy IP1 - Employment" },
 	{ "stickmeni", "Stickmen I" },
 	{ "stickythestickfigurepart1thecrimsonhouse", "Sticky the Stick Figure Part 1: The Crimson House" },
-	{ "stinkymcpoopoo", "Stinky McPooPoo" },
 	{ "stranded", "STRANDED" },
 	{ "stranger", "Stranger" },
 	{ "strangerinstickworld", "Stranger in Stickworld" },
@@ -1117,8 +1160,8 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "thejourneyhome", "The Journey Home" },
 	{ "thejourneyofiesir", "The Journey of Iesir" },
 	{ "thelastharvest", "The Last Harvest" },
-	{ "thelastsupperawhodunnit", "THE LAST SUPPER, A WHODUNNIT" },
-	{ "theloneloserdemo", "The Lone Loser - DEMO" },
+	{ "thelastsupperawhodunnit", "The Last Supper, A Whodunnit" },
+	{ "theloneloser", "The Lone Loser" },
 	{ "thelongtrip", "The Long Trip" },
 	{ "themajesticconspiracy", "The Majestic Conspiracy" },
 	{ "themarionette", "The Marionette" },
@@ -1129,6 +1172,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "thenetherworld", "The Netherworld" },
 	{ "thenextcurse", "The Next Curse" },
 	{ "theoraclev11", "The Oracle v1.1" },
+	{ "thepaparazziprince", "The Paparazzi Prince; and the Quest for Headlines" },
 	{ "thepark", "The Park" },
 	{ "theperfectmurder", "The Perfect Murder" },
 	{ "thephantominheritance", "The Phantom Inheritance" },
@@ -1186,7 +1230,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "twelvethirteenepisode3", "Twelve Thirteen, episode 3" },
 	{ "twentiesflappersvsthemummy", "Twenties Flappers vs The Mummy" },
 	{ "twoofakind", "Two of a Kind" },
-	{ "uglyfiles", "UGLY FILES" },
+	{ "uglyfiles", "Ugly Files" },
 	{ "ulitsadimitrova", "Ulitsa Dimitrova" },
 	{ "unboundver10", "Unbound Ver 1.0" },
 	{ "unfinished", "unfinished" },
@@ -1208,7 +1252,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "vohaulsrevengeii", "Vohaul's revenge II" },
 	{ "vpxt2", "V  P  x  T  !  2  !" },
 	{ "waitingfortheloop", "Waiting For the Loop" },
-	{ "wallyweaseldemo", "Wally Weasel Demo" },
+	{ "wallyweasel", "The Wacky World of Wally Weasel" },
 	{ "waltersasteroid", "Walters-Asteroid" },
 	{ "warthogs", "Warthogs" },
 	{ "washedashore", "Washed Ashore" },
@@ -1229,7 +1273,6 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "whowantstoliveforever", "Who wants to live forever?" },
 	{ "williamsnightmare", "Williams Nightmare" },
 	{ "willowhouse", "Willow House" },
-	{ "willy", "Willy" },
 	{ "winnersdontdodrugs", "Winners Dont' Do Drugs" },
 	{ "winterrose", "Winter Rose" },
 	{ "witch", "Witch" },
@@ -1242,7 +1285,6 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "worm", "Worm" },
 	{ "wrathofthesolonoids", "Wrath of the Solonoids " },
 	{ "yoda", "Yoda" },
-	{ "yourgame", "Your Game" },
 	{ "yourlate", "Your late!" },
 	{ "zakmckracken", "Zak McKracken" },
 	{ "zombieattackdemo", "Zombie Attack Demo" },
@@ -1275,110 +1317,118 @@ static const PluginVersion AGSCREDITZ_11[] = { { "agscreditz", 11 }, { nullptr,
 const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	// Pre-2.5 games that aren't supported by the current AGS engine
 	UNSUPPORTED_ENTRY("6da", "6da.exe", "9027912819f3a319ed9de0fd855310c3", 1608073),
+	UNSUPPORTED_ENTRY("aaronsepicjourney", "aaron.exe", "1c21bdb52bcafcafe988b30fd6bb4126", 1788404),
+	UNSUPPORTED_ENTRY("aceduswell", "ace.exe", "be48a6b0b81a71d34a41930623c065f1", 3103822),
 	UNSUPPORTED_DEMO("achristmastale", "tale.exe", "094135f05cf14fc3903e0d3697911a4e", 1484122),
 	UNSUPPORTED_ENTRY("adayinthefuture", "space.exe", "ecd0793124fbc9b89c6d11162e3b5851", 4120328),
 	UNSUPPORTED_ENTRY("adventuregame", "adventure.exe", "221637e5d62e2ca3cc146846ab0b2e49", 5533207),
+	UNSUPPORTED_ENTRY("asapadventure", "asap.exe", "8f80c91d160e333ab7f6be5208ea0533", 1405072),
 	UNSUPPORTED_ENTRY("bertthenewsreader", "bert.exe", "80bdce9a1052e896c7cba6a4334cecce", 2814934),
+	UNSUPPORTED_ENTRY("blackjack", "blackjack.exe", "73f87b30f84e9c34ab09ec8dd7ae109d", 1153092),
+	UNSUPPORTED_ENTRY("bluecupontherun", "ac2game.dat", "c290455f00f630c8a52c7eceb7c663eb", 1995708),
+	UNSUPPORTED_ENTRY("bobsquest2", "bq2.exe", "1c21bdb52bcafcafe988b30fd6bb4126", 2540006),
 	UNSUPPORTED_ENTRY("bookofspells1", "ac2game.dat", "fe66cb08bcffd094c159cd4ee72bacd3", 3442073),
 	UNSUPPORTED_ENTRY("bookofspells2", "ac2game.dat", "9df87a8e5bbcc7206b001c0b8316b7f9", 3263169),
 	UNSUPPORTED_ENTRY("bookofspells3", "ac2game.dat", "9f0181393bdceb2c0bbdb06634714023", 4806518),
-	UNSUPPORTED_ENTRY("bluecupontherun", "ac2game.dat", "c290455f00f630c8a52c7eceb7c663eb", 1995708),
 	UNSUPPORTED_ENTRY("calsoon", "calsoon.exe", "5477f4ed8f860427d1492548b677073c", 2865508),
+	UNSUPPORTED_ENTRY("carverisland1", "secret.exe", "8f80c91d160e333ab7f6be5208ea0533", 3116071),
+	UNSUPPORTED_ENTRY("carverisland2", "carver2.exe", "ed778afb4f46c3f2a70d330532a83a2f", 6265594),
+	UNSUPPORTED_ENTRY("chamber", "indy.exe", "094135f05cf14fc3903e0d3697911a4e", 1545150),
+	UNSUPPORTED_ENTRY("compensation", "comp.exe", "094135f05cf14fc3903e0d3697911a4e", 2054366),
+	UNSUPPORTED_ENTRY("darts", "dart.exe", "ed778afb4f46c3f2a70d330532a83a2f", 736848),
+	UNSUPPORTED_DEMO("deepbright", "tc.exe", "8f80c91d160e333ab7f6be5208ea0533", 3022557),
 	UNSUPPORTED_ENTRY("demonslayer1", "mags.exe", "1f0edcb7fa3f8e2b1dd60fa6c0bce60f", 3820347),
 	UNSUPPORTED_ENTRY("demonslayer2", "bert.exe", "0c057c5e6df6f45772286986ab7b7a5b", 1726766),
 	UNSUPPORTED_ENTRY("demonslayer3", "tiler.exe", "426e34f40e0dc5285af3fb5fc32a220e", 2586532),
+	UNSUPPORTED_ENTRY("demonslayer4", "dem four.exe", "426e34f40e0dc5285af3fb5fc32a220e", 5110674),
 	UNSUPPORTED_ENTRY("dirkchafberg", "ac2game.dat", "be7bec4a433beb5085184b64119351c8", 1906822),
 	UNSUPPORTED_ENTRY("earwigisangry", "earwig.exe", "04eedea9846d380d6d9a120f657daa43", 2371856),
+	UNSUPPORTED_ENTRY("eclair1", "eclair 1.exe", "9fa0358760f1f1bffddd080532f586f0", 1864283),
+	UNSUPPORTED_ENTRY("eclair2", "eclair 2.exe", "9fa0358760f1f1bffddd080532f586f0", 5644093),
+	UNSUPPORTED_ENTRY("elburro", "burro.exe", "1f0edcb7fa3f8e2b1dd60fa6c0bce60f", 2209309),
 	UNSUPPORTED_ENTRY("erniesbigadventure1", "magsjune.exe", "fc5f54dcfc82d3b991f670490a316958", 8814849),
 	UNSUPPORTED_ENTRY("erniesbigadventure2", "magsjuly.exe", "2fd8ca69f236ae1ad46edab4ba26a33d", 6647578),
+	UNSUPPORTED_ENTRY("exile", "exile.exe", "aad0a09714fab4de51e5488da48fd5d4", 13421451),
 	UNSUPPORTED_ENTRY("eyesofthejadesphinx", "jade.exe", "f2fe94ab604612e4595f3c79b0245529", 10763660),
+	UNSUPPORTED_DEMO("firewall", "firewall demo.exe", "2fd8ca69f236ae1ad46edab4ba26a33d", 2839412),
+	UNSUPPORTED_ENTRY("floyd", "floyd.exe", "9ef5bffe7b85377751c25af806345794", 5477588),
 	UNSUPPORTED_ENTRY("gaeafallen", "gaea_fallen.exe", "80bdce9a1052e896c7cba6a4334cecce", 11273205),
+	UNSUPPORTED_ENTRY("gorthor", "fart.exe", "fc5f54dcfc82d3b991f670490a316958", 1138006),
 	UNSUPPORTED_ENTRY("grannyzombiekiller", "mags.exe", "0c057c5e6df6f45772286986ab7b7a5b", 12855495),
 	UNSUPPORTED_ENTRY("gregsmountainousadventure", "mags.exe", "80a17966fc547849d43646acf89de296", 2112993),
+	UNSUPPORTED_ENTRY("greysgreytadv", "greywin.exe", "80bdce9a1052e896c7cba6a4334cecce", 1283447),
 	UNSUPPORTED_ENTRY("hermit", "hermit.exe", "4689069dd6b241e38311d0586e610a8d", 13995403),
 	UNSUPPORTED_ENTRY("jamesbondage", "jbdos.exe", "1f0edcb7fa3f8e2b1dd60fa6c0bce60f", 2056737),
 	UNSUPPORTED_ENTRY("jinglebells", "jinglebells.exe", "385a593828b1edb194e984ce55cda65e", 1620588),
+	UNSUPPORTED_ENTRY("kidnapped", "ac2game.dat", "27daca01ccbbbaf02bf6b4b85d5990b4", 1205017),
 	UNSUPPORTED_ENTRY("larryvales1", "larryvtd.exe", "610b7a3d1fd90f24d2218aa26b29d8ca", 3129645),
 	UNSUPPORTED_ENTRY("larryvales2", "dead.exe", "be48a6b0b81a71d34a41930623c065f1", 3946993),
+	UNSUPPORTED_DEMO("larryvales3", "burns.exe", "094135f05cf14fc3903e0d3697911a4e", 2120885),
 	UNSUPPORTED_ENTRY("lassi", "lassi.exe", "ed778afb4f46c3f2a70d330532a83a2f", 3681914),
+	UNSUPPORTED_ENTRY("lassiandrogermeetgod", "mtg.exe", "ed778afb4f46c3f2a70d330532a83a2f", 1618544),
+	UNSUPPORTED_ENTRY("lassiquesti", "lassi.exe", "c391c6676099032440b206189babe76e", 1700368),
 	UNSUPPORTED_ENTRY("littlejonnyevil", "lje.exe", "e93037e8efc7abc19b8978903ef5b409", 2133182),
 	UNSUPPORTED_ENTRY("littlewillie", "ac2game.dat", "239b11ab644222c67d981494766a3c25", 254128),
+	UNSUPPORTED_ENTRY("lsl2remake", "Larry 2 Point and Click.exe", "a567a00ba22eed9f8640af6e9bd01768", 2381674),
 	UNSUPPORTED_ENTRY("ludwig", "ludwig.exe", "727a30f9244441ad57a76086f4faa779", 3658869),
+	UNSUPPORTED_ENTRY("lupoinutile", "lupo.exe", "19f4045333d9c823a5439d0447d55985", 1856459),
+	UNSUPPORTED_ENTRY("mafio", "crimetim.exe", "be48a6b0b81a71d34a41930623c065f1", 1303660),
+	UNSUPPORTED_ENTRY("meninbrown", "0112.men in brown.exe", "426e34f40e0dc5285af3fb5fc32a220e", 2072392),
+	UNSUPPORTED_ENTRY("midtownshootout", "mtsowin.exe", "73f87b30f84e9c34ab09ec8dd7ae109d", 1076035),
 	UNSUPPORTED_ENTRY("momsquest", "mom's quest.exe", "73f87b30f84e9c34ab09ec8dd7ae109d", 3173896),
 	UNSUPPORTED_ENTRY("monkeyplank", "plank.exe", "1f0edcb7fa3f8e2b1dd60fa6c0bce60f", 815948),
+	UNSUPPORTED_ENTRY("moose", "moose.exe", "f4585823c1b4ce97d78c8acb433bec52", 1448684),
 	UNSUPPORTED_ENTRY("moosewars", "moose.exe", "f4585823c1b4ce97d78c8acb433bec52", 1448684),
 	UNSUPPORTED_ENTRY("murder", "murder.exe", "221637e5d62e2ca3cc146846ab0b2e49", 935799),
+	UNSUPPORTED_DEMO("nicholaswolfe1", "nw1demo.exe", "1f0edcb7fa3f8e2b1dd60fa6c0bce60f", 1539596),
 	UNSUPPORTED_ENTRY("nightoftheplumber", "night of the plumber.exe", "1f0edcb7fa3f8e2b1dd60fa6c0bce60f", 1703896),
 	UNSUPPORTED_ENTRY("novomestro", "novo.exe", "07f9921784124d9e09f39bb831e06131", 1122507),
+	UNSUPPORTED_ENTRY("odysseus", "odysseus.exe", "426e34f40e0dc5285af3fb5fc32a220e", 2799113),
 	UNSUPPORTED_ENTRY("permanentdaylight", "daylight.exe", "07f9921784124d9e09f39bb831e06131", 1799958),
 	UNSUPPORTED_ENTRY("perpetrator", "ac2game.dat", "56ef979be112e122e24d0cc8caea4ea4", 994303),
+	UNSUPPORTED_ENTRY("pizzaquest", "pqwin.exe", "73f87b30f84e9c34ab09ec8dd7ae109d", 2500089),
 	UNSUPPORTED_DEMO("pointblank", "future.exe", "385a593828b1edb194e984ce55cda65e", 1379714),
 	UNSUPPORTED_ENTRY("pornquest", "porn.exe", "04eedea9846d380d6d9a120f657daa43", 1012323),
+	UNSUPPORTED_ENTRY("qfc", "qfc.exe", "04eedea9846d380d6d9a120f657daa43", 2038696),
 	UNSUPPORTED_ENTRY("qfg412", "qfg.exe", "8b21668ca462b0b6b35df43c5902b074", 26674790),
-	UNSUPPORTED_ENTRY("qfg412", "qfg.exe",  "9027912819f3a319ed9de0fd855310c3", 26954823),
+	UNSUPPORTED_ENTRY("qfg412", "qfg.exe", "9027912819f3a319ed9de0fd855310c3", 26954823),
+	UNSUPPORTED_ENTRY("racingmanager", "raceman.exe", "465f972675db2da6040518221af5b0ba", 15971689),
 	UNSUPPORTED_ENTRY("raymondskeys", "keys.exe", "e016cb68731d0e38fe97905dbf0d5b36", 1032178),
+	UNSUPPORTED_ENTRY("red", "red.exe", "be48a6b0b81a71d34a41930623c065f1", 1101194),
 	UNSUPPORTED_ENTRY("richardlonghurst", "rlbat-win.exe", "04eedea9846d380d6d9a120f657daa43", 7935723),
 	UNSUPPORTED_ENTRY("rickylonghurst", "bleach.exe", "9027912819f3a319ed9de0fd855310c3", 1174829),
+	UNSUPPORTED_ENTRY("ripp", "ripp.exe", "426e34f40e0dc5285af3fb5fc32a220e", 10489586),
 	UNSUPPORTED_ENTRY("robblanc1", "ac2game.dat", "29c2ced2f2e6ad764e4249b4e4c45bba", 920415),
 	UNSUPPORTED_ENTRY("robblanc2", "ac2game.dat", "dd6c52e5a6e9b70efef4654769f11c69", 2056386),
 	UNSUPPORTED_ENTRY("robblanc3", "ac2game.dat", "8f8264de3c1bd91e26b84fe37fb5e53e", 2828959),
 	UNSUPPORTED_ENTRY("rodekill", "rodekill.exe", "72f3c950b4d9d14580a11db885a63310", 11995954),
 	UNSUPPORTED_ENTRY("rodequest", "rodequest1.exe", "72f3c950b4d9d14580a11db885a63310", 1196458),
+	UNSUPPORTED_ENTRY("rollinfoy", "rollinfoy.exe", "19f4045333d9c823a5439d0447d55985", 3454107),
 	UNSUPPORTED_ENTRY("samthepiratemonkey", "monkey.exe", "73f87b30f84e9c34ab09ec8dd7ae109d", 1401414),
+	UNSUPPORTED_ENTRY("secondmoonadv1", "moonsdt.exe", "9027912819f3a319ed9de0fd855310c3", 1276725),
 	UNSUPPORTED_ENTRY("slackerquest", "ac2game.dat", "e0998f2d2e14a55aae2291fdfab1ce7d", 1306492),
 	UNSUPPORTED_ENTRY("snailquest1", "snailquest.exe", "dd69243e3cc9e955215e0d556301b58e", 1095860),
 	UNSUPPORTED_ENTRY("snailquest2", "sq2.exe", "1bccd2edef19abc99e9683519d80c0e0", 955614),
 	UNSUPPORTED_ENTRY("snailquest3", "sq3.exe", "1bccd2edef19abc99e9683519d80c0e0", 1501892),
 	UNSUPPORTED_ENTRY("sol", "sol.exe", "73f87b30f84e9c34ab09ec8dd7ae109d", 4702799),
 	UNSUPPORTED_ENTRY("space", "space.exe", "094135f05cf14fc3903e0d3697911a4e", 3790026),
+	UNSUPPORTED_ENTRY("stickmen", "stickmen.exe", "094135f05cf14fc3903e0d3697911a4e", 2145142),
 	UNSUPPORTED_ENTRY("superdisk", "superdisk.exe", "80bdce9a1052e896c7cba6a4334cecce", 1304065),
+	UNSUPPORTED_ENTRY("teamwork", "teamwork.exe", "538274077115c6d8b4a0927dd3cceeac", 1096149),
 	UNSUPPORTED_ENTRY("thecrownofgold", "the crown of gold.exe", "e407143be000e44f113ba5ff1fbd17f9", 1971515),
+	UNSUPPORTED_ENTRY("theinexperiencedassassin", "assassin.exe", "73f87b30f84e9c34ab09ec8dd7ae109d", 2659741),
 	UNSUPPORTED_ENTRY("theisland", "island.exe", "e93037e8efc7abc19b8978903ef5b409", 1814801),
 	UNSUPPORTED_ENTRY("thendor", "ac2game.dat",  "b9c2ad76574c08bbcfd56eb1b49d2cd3", 8580708),
+	UNSUPPORTED_ENTRY("thetower", "thetower.exe", "9027912819f3a319ed9de0fd855310c3", 3431385),
 	UNSUPPORTED_ENTRY("thewarp", "warp.exe", "9027912819f3a319ed9de0fd855310c3", 881957),
+	UNSUPPORTED_ENTRY("tommato", "tom mato's grand wing-ding.exe", "73f87b30f84e9c34ab09ec8dd7ae109d", 2735158),
 	UNSUPPORTED_ENTRY("tulliesworld1", "candale.exe", "1c21bdb52bcafcafe988b30fd6bb4126", 3936603),
 	UNSUPPORTED_ENTRY("tvquest", "mags.exe", "fc5f54dcfc82d3b991f670490a316958", 1318019),
+	UNSUPPORTED_DEMO("uishowoff", "pd.exe", "ecd0793124fbc9b89c6d11162e3b5851", 3853394),
 	UNSUPPORTED_DEMO("waitkey", "ac2game.dat", "8ddf3744922101e33305dfcd06e3b682", 445197),
 	UNSUPPORTED_ENTRY("whokilledkennyrogers", "mags.exe", "ed778afb4f46c3f2a70d330532a83a2f", 1240103),
 	UNSUPPORTED_ENTRY("winfry", "fry.exe", "73f87b30f84e9c34ab09ec8dd7ae109d", 4164041),
-#ifdef TODO
-	UNSUPPORTED_ENTRY("", "carver2.exe", "ed778afb4f46c3f2a70d330532a83a2f", 6265594),
-	UNSUPPORTED_ENTRY("", "dem four.exe", "426e34f40e0dc5285af3fb5fc32a220e", 5110674),
-	UNSUPPORTED_ENTRY("", "mags.exe", "0c057c5e6df6f45772286986ab7b7a5b", 12855495),
-	UNSUPPORTED_ENTRY("", "qfc.exe", "04eedea9846d380d6d9a120f657daa43", 2038696),
-	UNSUPPORTED_ENTRY("", "qfc.exe", "04eedea9846d380d6d9a120f657daa43", 2038696),
-	UNSUPPORTED_ENTRY("", "rollinfoy.exe", "19f4045333d9c823a5439d0447d55985", 3454107),
-	UNSUPPORTED_ENTRY("", "tom mato's grand wing-ding.exe", "73f87b30f84e9c34ab09ec8dd7ae109d", 2735158),
-	UNSUPPORTED_ENTRY("", "fart.exe", "fc5f54dcfc82d3b991f670490a316958", 1138006),
-	UNSUPPORTED_ENTRY("", "thetower.exe", "9027912819f3a319ed9de0fd855310c3", 3431385),
-	UNSUPPORTED_ENTRY("", "mtg.exe", "ed778afb4f46c3f2a70d330532a83a2f", 1618544),
-	UNSUPPORTED_ENTRY("", "assassin.exe", "73f87b30f84e9c34ab09ec8dd7ae109d", 2659741),
-	UNSUPPORTED_ENTRY("", "burns.exe", "094135f05cf14fc3903e0d3697911a4e", 2120885),
-	UNSUPPORTED_ENTRY("", "ripp.exe", "426e34f40e0dc5285af3fb5fc32a220e", 10489586),
-	UNSUPPORTED_ENTRY("", "indy.exe", "094135f05cf14fc3903e0d3697911a4e", 1545150),
-	UNSUPPORTED_ENTRY("", "aaron.exe", "1c21bdb52bcafcafe988b30fd6bb4126", 1788404),
-	UNSUPPORTED_ENTRY("", "adventure.exe", "221637e5d62e2ca3cc146846ab0b2e49", 5533207),
-	UNSUPPORTED_ENTRY("", "bq2.exe", "1c21bdb52bcafcafe988b30fd6bb4126", 2540006),
-	UNSUPPORTED_ENTRY("", "comp.exe", "094135f05cf14fc3903e0d3697911a4e", 2054366),
-	UNSUPPORTED_ENTRY("", "dart.exe", "ed778afb4f46c3f2a70d330532a83a2f", 736848),
-	UNSUPPORTED_ENTRY("", "burro.exe", "1f0edcb7fa3f8e2b1dd60fa6c0bce60f", 2209309),
-	UNSUPPORTED_ENTRY("", "exile.exe", "aad0a09714fab4de51e5488da48fd5d4", 13421451),
-	UNSUPPORTED_ENTRY("", "firewall demo.exe", "2fd8ca69f236ae1ad46edab4ba26a33d", 2839412),
-	UNSUPPORTED_ENTRY("", "lupo.exe", "19f4045333d9c823a5439d0447d55985", 1856459),
-	UNSUPPORTED_ENTRY("", "0112.men in brown.exe", "426e34f40e0dc5285af3fb5fc32a220e", 2072392),
-	UNSUPPORTED_ENTRY("", "moose.exe", "f4585823c1b4ce97d78c8acb433bec52", 1448684),
-	UNSUPPORTED_ENTRY("", "greywin.exe", "80bdce9a1052e896c7cba6a4334cecce", 1283447),
-	UNSUPPORTED_ENTRY("", "mtsodos.exe", "1f0edcb7fa3f8e2b1dd60fa6c0bce60f", 777967),
-	UNSUPPORTED_ENTRY("", "mtsowin.exe", "73f87b30f84e9c34ab09ec8dd7ae109d", 1076035),
-	UNSUPPORTED_ENTRY("", "nw1demo.exe", "1f0edcb7fa3f8e2b1dd60fa6c0bce60f", 1539596),
-	UNSUPPORTED_ENTRY("", "odysseus.exe", "426e34f40e0dc5285af3fb5fc32a220e", 2799113),
-	UNSUPPORTED_ENTRY("", "pd.exe", "ecd0793124fbc9b89c6d11162e3b5851", 3853394),
-	UNSUPPORTED_ENTRY("", "pqwin.exe", "73f87b30f84e9c34ab09ec8dd7ae109d", 2500089),
-	UNSUPPORTED_ENTRY("", "moonsdt.exe", "9027912819f3a319ed9de0fd855310c3", 1276725),
-	UNSUPPORTED_ENTRY("", "stickmen.exe", "094135f05cf14fc3903e0d3697911a4e", 2145142),
-	UNSUPPORTED_ENTRY("", "teamwork.exe", "538274077115c6d8b4a0927dd3cceeac", 1096149),
-	UNSUPPORTED_ENTRY("", "blackjack.exe", "73f87b30f84e9c34ab09ec8dd7ae109d", 1153092),
-#endif
+
 	// Post-2.5 games that are likely supported by the AGS engine
 	ENGLISH_ENTRY("5daysastranger", "5days.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 4440143),
 	ENGLISH_ENTRY("7daysaskeptic", "7days.exe", "465f972675db2da6040518221af5b0ba", 4693374),
@@ -1415,6 +1465,7 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("46memorylane", "diyu.exe", "e3962995a70923a8d5a8f1cf8f932eee", 66686277),
 	ENGLISH_ENTRY("4ofclubs", "4ofClubs.exe", "06a03fe35791b0578068ab1873455463", 5909169),
 	ENGLISH_ENTRY("5daysastranger", "5days.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 4614351),
+	ENGLISH_ENTRY("5oclocklock", "DadGame.exe", "3018c5443291aec823bc63342ce4c58b", 6073887),
 	ENGLISH_ENTRY("6daysasacrifice", "6das.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 7993899),
 	ENGLISH_ENTRY("6mornings", "project2.exe", "e7dac058b9bc0b42d489e474c2ddec84", 11595240),
 	ENGLISH_ENTRY("7daysaskeptic", "7days.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 4863356),
@@ -1451,6 +1502,7 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("agsdarts", "AGS Darts.exe", "434c43a5e1ba2a11c1bde723ffeae719", 47771575),
 	ENGLISH_ENTRY("agsinvaders", "AGS-Invaders.exe", "f120690b506dd63cd7d1112ea6af2f77", 1394435),
 	ENGLISH_ENTRY("agsjukebox", "JukeBox2.exe", "a7aef57e360306c9377164f38d317ccb", 2914973),
+	ENGLISH_ENTRY("agsmittensshooter", "Clex.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 1381575),
 	ENGLISH_ENTRY("agsmoduletester", "V1.0 Source.exe", "95b7dd55f6e15c8a2118856ed9fe8ff9", 2020344),
 	ENGLISH_ENTRY("agsyahtzee2", "AGS Yahtzee 2.exe", "9e995c04d8642d6182d492c54a90b188", 71217276),
 	ENGLISH_ENTRY("agsyathzee", "AGS Yathzee.exe", "434c43a5e1ba2a11c1bde723ffeae719", 37295758),
@@ -1566,6 +1618,7 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("boom", "boom.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 934966),
 	ENGLISH_ENTRY("bowserquirkquest", "Bowser Quirk Quest.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 3046623),
 	ENGLISH_ENTRY("box", "Box.exe", "0b7529a76f38283d6e850b8d56526fc1", 748638),
+	ENGLISH_ENTRY("boxfight", "boxen.exe", "3128b9f90e2f954ba704414ae854d10b", 3132938),
 	ENGLISH_ENTRY("boyindahood", "Boy in da hood.exe", "afe40dc1416dd51e896ee0444d799f07", 12260759),
 	ENGLISH_ENTRY("bradbradsonkeyquest", "BADness.exe", "0500aacb6c176d47ac0f8158f055db83", 1190580),
 	ENGLISH_ENTRY("breakdownbyonedollar", "Breakdown.exe", "710ac163c281a5a539ffe2386264b990", 5273352),
@@ -1578,7 +1631,7 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("bunnyquest", "BunnyQuest.exe", "28f82e420b82d07651b68114f90223c8", 1154928),
 	ENGLISH_ENTRY("burymeinthesand", "buryme.exe", "f10516e88ec858700804ee69d041aead", 24252498),
 	ENGLISH_ENTRY("butcherstanys", "Stanys.exe", "97d700529f5cc826f230c27acf81adfd", 1404933),
-	ENGLISH_ENTRY("bytheswordconspiracy", "bts.exe", "7dc7f61f79ba7a77d4ef8168bfd3d173", 60246329),
+	ENGLISH_DEMO("bytheswordconspiracy", "bts.exe", "7dc7f61f79ba7a77d4ef8168bfd3d173", 60246329),
 	ENGLISH_ENTRY("calebsdrunkenadventure", "Calebdru.exe", "0b7529a76f38283d6e850b8d56526fc1", 15484923),
 	ENGLISH_ENTRY("calsoon2", "Looncalsoon.exe", "97d700529f5cc826f230c27acf81adfd", 18981033),
 	ENGLISH_ENTRY("capricorn", "capricorn.exe", "06a03fe35791b0578068ab1873455463", 4817076),
@@ -1611,7 +1664,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("cirquedezale", "cirque.exe", "3128b9f90e2f954ba704414ae854d10b", 8547131),
 	ENGLISH_ENTRY("claire", "Claire.exe", "b25674056fe8cc0b7bf0a4409c5c5bfc", 2781456),
 	ENGLISH_ENTRY("classnotesv11", "ClassNotes.exe", "0710e2ec71042617f565c01824f0cf3c", 5706836),
-	ENGLISH_ENTRY("clex", "Clex.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 1381575),
 	ENGLISH_ENTRY("clipl2heblinna", "Clip goes to town.exe", "0710e2ec71042617f565c01824f0cf3c", 1690928),
 	ENGLISH_ENTRY("clubofevil", "Club of Evil.exe", "65f53f81071dab6b3ab8363e4c76d12e", 11838011),
 	ENGLISH_ENTRY("coeldeckaflightgame", "coell deca.exe", "a524cbb1c51589903c4043b98917f1d9", 5497572),
@@ -1632,6 +1684,7 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("cosmosquestiii", "CQ3.exe", "18b284c22010850f79bc5c20054a70c4", 8674790),
 	ENGLISH_ENTRY("cougarsquestforfreedom", "chra.exe", "0500aacb6c176d47ac0f8158f055db83", 12654043),
 	ENGLISH_ENTRY("counterfeit", "Counterfeit.exe", "ef1645ccd3d16691ec3908c91f340c34", 2232297),
+	ENGLISH_ENTRY("coupdecup", "Newgame.exe", "949f7440e3692b7366c2029979dee9a0", 9635719),
 	ENGLISH_ENTRY("cow", "cow.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 134670383),
 	ENGLISH_ENTRY("coyote", "Coyote.exe", "a524cbb1c51589903c4043b98917f1d9", 33124533),
 	ENGLISH_ENTRY("craftofevil", "Craft Of Evil.exe", "4c1d9a74c4acf6771aab4be704bf0797", 22409329),
@@ -1758,7 +1811,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("feuersturmkapitel2", "fs2.exe", "06a03fe35791b0578068ab1873455463", 7043558),
 	ENGLISH_ENTRY("feuersturmkapitel3", "feuersturm3.exe", "206478d4d39e16571682b2cddf01a78f", 7826524),
 	ENGLISH_ENTRY("fifa2003pro", "Soccer.exe", "475da5decb9ad2a11e64e2e2e891d8e0", 2524958),
-	ENGLISH_ENTRY("fight", "boxen.exe", "3128b9f90e2f954ba704414ae854d10b", 3132938),
 	ENGLISH_ENTRY("fightgame", "Fight Game.exe", "463f79e5db4013d1b3be647edd7e338d", 1871790),
 	ENGLISH_ENTRY("fightgame", "Fight Game.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 3551992),
 	ENGLISH_ENTRY("fireflystory3d", "FFS 3D.exe", "27343924ddad3be0b97bdcaa71858b1b", 2254453),
@@ -1857,7 +1909,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("huongjiaoping", "hotpot.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 47237302),
 	ENGLISH_ENTRY("huxzadventure", "Huxsadv.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 2053897),
 	ENGLISH_ENTRY("hydeandseek", "Hyde and Seek.exe", "c2f495a688dc19e66362657dee9aa895", 28066547),
-	ENGLISH_ENTRY("iaman00b11omgwtflol", "DadGame.exe", "3018c5443291aec823bc63342ce4c58b", 6073887),
 	ENGLISH_ENTRY("iamjason", "IAMJASON.exe", "e8985d9ffbfa1eda77f2eb8d1331944a", 4843842),
 	ENGLISH_ENTRY("iforgot", "Forgot.exe", "6aa30185326552359c7865e55c045a74", 7743871),
 	ENGLISH_ENTRY("igs", "IGS.exe", "95b7dd55f6e15c8a2118856ed9fe8ff9", 1204802),
@@ -1900,6 +1951,7 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("joesmiserablelife", "Joe's Miserable Life.exe", "1b9f13d430bb15bf30d0fd044358db68", 36705304),
 	ENGLISH_ENTRY("johnharrissafrakincse", "totp.exe", "74dc062c5f68f3d70da911f2db5737b6", 36463878),
 	ENGLISH_ENTRY("johnjebediahgunelisoladisepheret", "JJG.exe", "a28cb95e1769ba1bfa48f850390746c2", 88957123),
+	ENGLISH_ENTRY("johnlosthiskey", "Newgame.exe", "0b7529a76f38283d6e850b8d56526fc1", 1453831),
 	ENGLISH_ENTRY("johnnyrocket", "Rocket.exe", "a524cbb1c51589903c4043b98917f1d9", 10366294),
 	ENGLISH_ENTRY("johnsinclairvoodooinlondon", "John Sinclair - Voodoo in London.exe", "d72e72697a755c7de395b0f6c8cbbf0d", 56795991),
 	ENGLISH_ENTRY("jonnysmallvalley", "Jonny Smallvalley.exe", "01d0e6bd812abaa307bcb10fc2193416", 34437869),
@@ -2010,9 +2062,9 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("megoaway", "Me Go Store II.exe", "06a03fe35791b0578068ab1873455463", 6640781),
 	ENGLISH_ENTRY("megocannibaljungle", "mgcj.exe", "06a03fe35791b0578068ab1873455463", 7127871),
 	ENGLISH_ENTRY("megostore", "Me Go Store.exe", "90413e9ae57e222f8913b09d2bc847bc", 2961962),
-	ENGLISH_ENTRY("melrinthediscipleordeal", "Melrin.exe", "803e65c28364b6bf44b7c4610fcdaa5a", 12822475),
-	ENGLISH_ENTRY("melrinthedragonmenace", "Melrin3.exe", "803e65c28364b6bf44b7c4610fcdaa5a", 5802221),
-	ENGLISH_ENTRY("melrinthependantquest", "Melrin2.exe", "803e65c28364b6bf44b7c4610fcdaa5a", 4372768),
+	ENGLISH_ENTRY("melrin1", "Melrin.exe", "803e65c28364b6bf44b7c4610fcdaa5a", 12822475),
+	ENGLISH_ENTRY("melrin2", "Melrin2.exe", "803e65c28364b6bf44b7c4610fcdaa5a", 4372768),
+	ENGLISH_ENTRY("melrin3", "Melrin3.exe", "803e65c28364b6bf44b7c4610fcdaa5a", 5802221),
 	ENGLISH_ENTRY("meltdrake3chapter1", "CaK3.exe", "97d700529f5cc826f230c27acf81adfd", 6044911),
 	ENGLISH_ENTRY("memoriesfade", "MemoriesFade.exe", "d5d028212a242a9841feff24ec3db3c9", 7996519),
 	ENGLISH_ENTRY("meninhats", "GAME.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 1646510),
@@ -2069,7 +2121,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("nedysadventure", "Nedy.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 6463558),
 	ENGLISH_ENTRY("nekusnewtrip", "nnt.exe", "c0c1865c3c8369e034095a725ca1ddbf", 35012412),
 	ENGLISH_ENTRY("nekusnewtrip", "square enix.exe", "a524cbb1c51589903c4043b98917f1d9", 10630694),
-	ENGLISH_ENTRY("newgame", "Newgame.exe", "0b7529a76f38283d6e850b8d56526fc1", 1453831),
 	ENGLISH_ENTRY("nellycootalotv15", "Nelly Cootalot.exe", "18b284c22010850f79bc5c20054a70c4", 108256323),
 	ENGLISH_ENTRY("neofeud", "Neofeud Demo.exe", "6e861b1f476ff7cdf036082abb271329", 1886913453),
 	ENGLISH_ENTRY("nesquest", "NES Quest.exe", "8b72036706da98095057df615d07460b", 20881972),
@@ -2225,10 +2276,10 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("roadofdestiny", "ROD.exe", "618d7dce9631229b4579340b964c6810", 30127308),
 	ENGLISH_ENTRY("roadracer", "TR_Bryvis.exe", "cebb3ac5c3d2df939e7f0ec8f2975b64", 25080647),
 	ENGLISH_ENTRY("roastmothergoose", "RMG.exe", "00328f4f1e7729144483107b96b11df8", 46474982),
-	ENGLISH_ENTRY("robbertredfordsavestheday", "GAME.exe", "02635a77ab660023f59519c91329f7f5", 6537985),
 	ENGLISH_ENTRY("robbingtheprincess", "Princess.exe", "ac461eb75959761fe159917607c246b4", 5793384),
+	ENGLISH_ENTRY("robertredford1", "GAME.exe", "02635a77ab660023f59519c91329f7f5", 6537985),
+	ENGLISH_ENTRY("robertredford2", "ROBERT2.exe", "02635a77ab660023f59519c91329f7f5", 13075066),
 	ENGLISH_ENTRY("robertredford3", "game.exe", "71ca0d6c1c699595f28a2125948d4a84", 10846423),
-	ENGLISH_ENTRY("robertredfordsavestheday", "ROBERT2.exe", "02635a77ab660023f59519c91329f7f5", 13075066),
 	ENGLISH_ENTRY("robmassacreofchainsawness", "Chainsaw.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 1153384),
 	ENGLISH_ENTRY("robotragedy", "Robotragedy.exe", "465f972675db2da6040518221af5b0ba", 130585260),
 	ENGLISH_ENTRY("robotragedy2", "Robotragedy 2.exe", "465f972675db2da6040518221af5b0ba", 256955387),
@@ -2245,7 +2296,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("rootofallevil", "RootOfAllEvil.exe", "c4f5b7b29be90ba0f8128298afb917de", 3957834),
 	ENGLISH_ENTRY("rosauradocelestialrescuefromdespair", "RosauraMAGS.exe", "3c5bd1713959ff469cb46ebe5542cfcf", 13190949),
 	ENGLISH_ENTRY("rotnbelusebiusarrival", "RoNXXL.exe", "465f972675db2da6040518221af5b0ba", 9426141),
-	ENGLISH_ENTRY("rotnbelusebiusarrival", "ronextra.exe", "465f972675db2da6040518221af5b0ba", 9958019),
 	ENGLISH_ENTRY("rowengoestowork", "Rowen.exe", "a1cef60926235b85bd0e1866b19e0dc7", 3791058),
 	ENGLISH_ENTRY("rs15", "rs15.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 13638597),
 	ENGLISH_ENTRY("rudeawakening", "RudeAwakening.exe", "0710e2ec71042617f565c01824f0cf3c", 8038257),
@@ -2275,9 +2325,9 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("seega16engl5", "house_eng_5.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 1746878),
 	ENGLISH_ENTRY("seegame15", "housesitting_18.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 1746919),
 	ENGLISH_ENTRY("sevendoors", "7DOORS.exe", "18b284c22010850f79bc5c20054a70c4", 113716886),
-	ENGLISH_ENTRY("sga", "StarGA.exe", "0710e2ec71042617f565c01824f0cf3c", 45738298),
+	ENGLISH_ENTRY("stargateadv", "StarGA.exe", "0710e2ec71042617f565c01824f0cf3c", 45738298),
 	ENGLISH_ENTRY("shadesofgreye", "Shades of Greye.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 16125855),
-	ENGLISH_ENTRY("shadowsoftheempiretd", "sote_td.exe", "b8cd640b45c5a79c33c7a8a8fe32ebe2", 63299246),
+	ENGLISH_DEMO("shadowsoftheempire", "sote_td.exe", "b8cd640b45c5a79c33c7a8a8fe32ebe2", 63299246),
 	ENGLISH_ENTRY("shailadusithlenqute", "Shai-la Enquete.exe", "a524cbb1c51589903c4043b98917f1d9", 7489302),
 	ENGLISH_ENTRY("shailaofthesith", "Shaila_of_the_Sith.exe", "a524cbb1c51589903c4043b98917f1d9", 76170347),
 	ENGLISH_ENTRY("shem", "Shem.exe", "0710e2ec71042617f565c01824f0cf3c", 8866401),
@@ -2317,9 +2367,9 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("spacelynxes", "SpaceLynxes.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 6593042),
 	ENGLISH_ENTRY("spacepirates", "Space Pirates.exe", "95dcf736be87cf7d40bf64d5b078c4b7", 3006210),
 	ENGLISH_ENTRY("spacepoolalpha", "SpacePool.exe", "ef1d6fdc83c91a1a8de9eaf2630737b7", 3055777),
+	ENGLISH_ENTRY("spacequest3vgapreview", "SQ3VGADEMO.exe", "64fcaf7da0b257ea831f89c54be0ad72", 3630019),
 	ENGLISH_ENTRY("spacequest45", "SQ4,5.exe", "5cd8db602cedc8f04cd3ca290a4a2693", 6886082),
 	ENGLISH_ENTRY("spacequest55demoags", "SQ5.5.exe", "465f972675db2da6040518221af5b0ba", 16342443),
-	ENGLISH_ENTRY("spacequestiiivgapreview", "SQ3VGADEMO.exe", "64fcaf7da0b257ea831f89c54be0ad72", 3630019),
 	ENGLISH_ENTRY("spacerangers", "SpaceRangersEp46.exe", "4f6c7ec127e8b0ce077abb357903612f", 41103057),
 	ENGLISH_ENTRY("spacerangersep52", "SpaceRangers52Grisli.exe", "4f6c7ec127e8b0ce077abb357903612f", 208346458),
 	ENGLISH_ENTRY("spacewar", "Spacewar.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 2270669),
@@ -2352,7 +2402,7 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("stediddyip1employment", "stediddy1.exe", "5872fea5a958bc74c2d9ca7b2d196c42", 27136166),
 	ENGLISH_ENTRY("stickmeni", "stick.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 2399329),
 	ENGLISH_ENTRY("stickythestickfigurepart1thecrimsonhouse", "Crimson House Files.exe", "3b095a7872e04769d04ab45e9c1b66eb", 3610653),
-	ENGLISH_ENTRY("stinkymcpoopoo", "grok.exe", "9cf51833e787cc919837d9a8bd8fc14c", 1046039),
+	ENGLISH_ENTRY("grok", "grok.exe", "9cf51833e787cc919837d9a8bd8fc14c", 1046039),
 	ENGLISH_ENTRY("stranded", "Stranded.exe", "18b284c22010850f79bc5c20054a70c4", 39791629),
 	ENGLISH_ENTRY("stranger", "Stranger.exe", "0500aacb6c176d47ac0f8158f055db83", 5854099),
 	ENGLISH_ENTRY("strangerinstickworld", "game1.exe", "a524cbb1c51589903c4043b98917f1d9", 42525810),
@@ -2431,9 +2481,9 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("thejourneyofiesir", "The Journey of Iesir.exe", "376a3f162c7940d990325c53edc20fed", 70444514),
 	ENGLISH_ENTRY("thelastharvest", "The Last Harvest.exe", "f120690b506dd63cd7d1112ea6af2f77", 6253816),
 	ENGLISH_ENTRY("thelastsupperawhodunnit", "THE LAST SUPPER, A WHODUNNIT.exe", "37500274a7882e8087042cc6ec851e0c", 13447848),
-	ENGLISH_ENTRY("theloneloserdemo", "DEMO (English).exe", "0500aacb6c176d47ac0f8158f055db83", 6082095),
+	ENGLISH_DEMO("theloneloser", "DEMO (English).exe", "0500aacb6c176d47ac0f8158f055db83", 6082095),
 	ENGLISH_ENTRY("thelongtrip", "longtrip.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 184362586),
-	ENGLISH_ENTRY("themajesticconspiracy", "Majestic.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 17929647),
+	ENGLISH_ENTRY("themajesticconspiracy", "majestic.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 17929647),
 	ENGLISH_ENTRY("themarionette", "marionette.exe", "ff3d6e4edfca8b4f4f1c6cbf8e2781a6", 88408446),
 	ENGLISH_ENTRY("themccarthychronicleschapter1", "McCarthy.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 29488543),
 	ENGLISH_ENTRY("themcreedcasebytk", "McReedCase.exe", "4bcbc24015114752b3c7971128704689", 2982436),
@@ -2442,6 +2492,7 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("thenetherworld", "netherworld.exe", "465f972675db2da6040518221af5b0ba", 2253033),
 	ENGLISH_ENTRY("thenextcurse", "TNC.exe", "88cf59aad15ca331ab0f854e16c84df3", 4125146),
 	ENGLISH_ENTRY("theoraclev11", "The Oracle.exe", "f120690b506dd63cd7d1112ea6af2f77", 7490474),
+	ENGLISH_ENTRY("thepaparazziprince", "Willy.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 3403804),
 	ENGLISH_ENTRY("thepark", "park.exe", "97d700529f5cc826f230c27acf81adfd", 709265),
 	ENGLISH_ENTRY("theperfectmurder", "Tamz.exe", "9cf51833e787cc919837d9a8bd8fc14c", 4527709),
 	ENGLISH_ENTRY("thephantominheritance", "Phantom.exe", "ec04c7917c003d9e07d4514ff25bf365", 27558669),
@@ -2522,7 +2573,7 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("vohaulsrevengeii", "SQ XII.exe", "465f972675db2da6040518221af5b0ba", 17313307),
 	ENGLISH_ENTRY("vpxt2", "VPET!2!.exe", "0b7529a76f38283d6e850b8d56526fc1", 12933096),
 	ENGLISH_ENTRY("waitingfortheloop", "WaitingForTheLoop.exe", "0241777c2537fc5d077c05cde10bfa9f", 51273604),
-	ENGLISH_ENTRY("wallyweaseldemo", "WallyDemo.exe", "95b7dd55f6e15c8a2118856ed9fe8ff9", 12579444),
+	ENGLISH_DEMO("wallyweasel", "WallyDemo.exe", "95b7dd55f6e15c8a2118856ed9fe8ff9", 12579444),
 	ENGLISH_ENTRY("waltersasteroid", "HDGame.exe", "465f972675db2da6040518221af5b0ba", 8390872),
 	ENGLISH_ENTRY("warthogs", "Warthogs.exe", "9c49b6fa0460f36d6e7558281f142683", 12448793),
 	ENGLISH_ENTRY("washedashore", "Achtung!.exe", "06a03fe35791b0578068ab1873455463", 7926840),
@@ -2543,7 +2594,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("whowantstoliveforever", "WWtLF.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 6917937),
 	ENGLISH_ENTRY("williamsnightmare", "Killer.exe", "0b7529a76f38283d6e850b8d56526fc1", 3991683),
 	ENGLISH_ENTRY("willowhouse", "Game.exe", "5bc696cf7178870b21db6ac87972befd", 132161306),
-	ENGLISH_ENTRY("willy", "Willy.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 3403804),
 	ENGLISH_ENTRY("winnersdontdodrugs", "windrugs.exe", "ff3358d8f2726d544aadfde4f1ec8407", 2573704),
 	ENGLISH_ENTRY("winterrose", "Winter Rose.exe", "0500aacb6c176d47ac0f8158f055db83", 37444693),
 	ENGLISH_ENTRY("witch", "witch.exe", "06a03fe35791b0578068ab1873455463", 10110407),
@@ -2556,7 +2606,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("worm", "Worm.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 40704028),
 	ENGLISH_ENTRY("wrathofthesolonoids", "verb.exe", "0500aacb6c176d47ac0f8158f055db83", 3582078),
 	ENGLISH_ENTRY("yoda", "Yoda.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 2461339),
-	ENGLISH_ENTRY("yourgame", "Newgame.exe", "949f7440e3692b7366c2029979dee9a0", 9635719),
 	ENGLISH_ENTRY("yourlate", "Your late.exe", "02635a77ab660023f59519c91329f7f5", 2719997),
 	ENGLISH_ENTRY("zakmckracken", "Zak2.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 8686711),
 	ENGLISH_ENTRY("zombieattackdemo", "ZADemo.exe", "82da2565c456dcfb265ded6fe3189c0b", 20958555),


Commit: 85cba02c6095c93a3a2379f02315d03af3df53ad
    https://github.com/scummvm/scummvm/commit/85cba02c6095c93a3a2379f02315d03af3df53ad
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Further groupings for detection table

Changed paths:
    engines/ags/detection_tables.h


diff --git a/engines/ags/detection_tables.h b/engines/ags/detection_tables.h
index 5d73045d4b..9ab7ffe7c2 100644
--- a/engines/ags/detection_tables.h
+++ b/engines/ags/detection_tables.h
@@ -134,35 +134,24 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "waitkey", "WaitKey();" },
 	{ "winfry", "Winfry" },
 
-	// Post-2.5 games that are likely supported by the AGS engine
-	{ "5daysastranger", "5 Days A Stranger" },
-	{ "7daysaskeptic", "7 Days A Skeptic" },
-	{ "atotk", "A Tale Of Two Kingdoms" },
-	{ "bcremake", "Black Cauldron Remake" },
+	// AGDI games. They get their own grouping because they're just that awesome
+	{ "kq1agdi", "King's Quest I: Quest for the Crown Remake" },
+	{ "kq2agdi", "King's Quest II: Romancing The Stones" },
+	{ "kq3agdi", "King's Quest III Redux: To Heir is Human" },
+	{ "qfg2agdi", "Quest for Glory II: Trial By Fire" },
+	{ "mage", "Mage's Initiation: Reign of the Elements" },
+
+	// Comercial games
 	{ "blackwell1", "The Blackwell Legacy" },
 	{ "blackwell2", "Blackwell Unbound" },
 	{ "blackwell3", "The Blackwell Convergence" },
 	{ "blackwell4", "The Blackwell Deception" },
 	{ "blackwell5", "The Blackwell Epiphany" },
-	{ "blackwellconvergence", "Blackwell Convergence" },
-	{ "blackwelllegacydemo", "Blackwell Legacy Demo" },
-	{ "blackwellunbounddemo", "Blackwell Unbound Demo" },
 	{ "geminirue", "Gemini Rue" },
-	{ "goldenwake", "A Golden Wake" },
-	{ "kathyrain", "Kathy Rain" },
-	{ "kq1agdi", "King's Quest I: Quest for the Crown Remake" },
-	{ "kq2agdi", "King's Quest II: Romancing The Stones" },
-	{ "kq3agdi", "King's Quest III Redux: To Heir is Human" },
-	{ "mage", "Mage's Initiation: Reign of the Elements" },
-	{ "oott", "Order of the Thorne: The King's Challenge" },
 	{ "primordia", "Primordia" },
-	{ "qfi", "Quest for Infamy" },
 	{ "resonance", "Resonance" },
-	{ "unavowed", "Unavowed" },
-	{ "whokilledkennyrogers", "Who Killed Kenny Rogers" },
-	{ "winfry", "Winfry" },
 
-	// Unsorted games
+	// Post-2.5 games that are likely supported by the AGS engine
 	{ "10waysfromsunday", "10 Ways from Sunday" },
 	{ "1dayamosquito", "1 day a mosquito" },
 	{ "2034acaftercanadaii", "2034 A.C. (After Canada) II" },
@@ -170,9 +159,11 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "3piggiesalpha", "3piggiesAlpha" },
 	{ "46memorylane", "46 Memory Lane" },
 	{ "4ofclubs", "4 of Clubs" },
+	{ "5daysastranger", "5 Days A Stranger" },
 	{ "5oclocklock", "5-O'clock Lock" },
 	{ "6daysasacrifice", "6 Days A Sacrifice" },
 	{ "6mornings", "6mornings" },
+	{ "7daysaskeptic", "7 Days A Skeptic" },
 	{ "aazor", "Aazor" },
 	{ "abducted", "Abducted" },
 	{ "absent", "Absent" },
@@ -256,6 +247,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "ataleofbetrayal", "A Tale Of Betrayal" },
 	{ "ataleoftwokingdoms", "A Tale of Two Kingdoms" },
 	{ "atapi", "Atapi" },
+	{ "atotk", "A Tale Of Two Kingdoms" },
 	{ "atotkjukebox", "ATOTK jukebox" },
 	{ "atreatandsometricks", "A Treat and Some Tricks" },
 	{ "aunaturel", "Au Naturel" },
@@ -279,6 +271,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "barnrunnerholiday2", "Barn Runner: Holiday 2" },
 	{ "bartsquestfortv", "Bart's Quest For TV" },
 	{ "battlewarriors", "Battle Warriors" },
+	{ "bcremake", "Black Cauldron Remake" },
 	{ "beacon", "Beacon" },
 	{ "bear", "Bear" },
 	{ "beasts", "Beasts" },
@@ -305,6 +298,9 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "blackmailinbrooklyn", "Blackmail In Brooklyn" },
 	{ "blackmorph", "Black Morph" },
 	{ "blackuddertodoubloonornottodoubloon", "Blackudder: To Doubloon or not to Doubloon" },
+	{ "blackwellconvergence", "Blackwell Convergence" },
+	{ "blackwelllegacydemo", "Blackwell Legacy Demo" },
+	{ "blackwellunbounddemo", "Blackwell Unbound Demo" },
 	{ "bluemoon", "Blue Moon" },
 	{ "boardquest", "Board Quest" },
 	{ "bob", "BOB" },
@@ -550,6 +546,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "glitchquestnofun", "Glitch Quest (nofun)" },
 	{ "gnomeshomebrewingadventure", "Gnome's Homebrewing Adventure" },
 	{ "gnrblexags", "Gnrblex_AGS" },
+	{ "goldenwake", "A Golden Wake" },
 	{ "goneboatfishin", "Gone Boat Fishin'" },
 	{ "goodmorningmrgingerbread", "Good Morning, Mr. Gingerbread!" },
 	{ "goodsantabadsanta", "Good Santa, Bad Santa" },
@@ -654,6 +651,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "justignorethem", "Just Ignore Them" },
 	{ "kanjigakusei", "Kanji Gakusei" },
 	{ "kartquestv053", "Kart-Quest - v0.53" },
+	{ "kathyrain", "Kathy Rain" },
 	{ "keptoshi", "Keptosh I" },
 	{ "keys", "Keys" },
 	{ "killereye", "Killer Eye" },
@@ -841,6 +839,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "oneweekoneroom", "One Week One Room" },
 	{ "onleavingthebuilding", "On Leaving The Building" },
 	{ "onlythegooddieyoungenglishversion", "Only The Good Die Young - english version" },
+	{ "oott", "Order of the Thorne: The King's Challenge" },
 	{ "openquest", "OpenQuest!" },
 	{ "operationnovi", "Operation Novi" },
 	{ "operationsavebluecup", "Operation Save Blue Cup" },
@@ -923,6 +922,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "purityofthesurf", "Purity of the Surf" },
 	{ "puzzlebotsdemo", "Puzzle Bots Demo" },
 	{ "pxenophobe", "PXenophobe" },
+	{ "qfi", "Quest for Infamy" },
 	{ "quantumnauts", "QUANTUMNAUTS" },
 	{ "questfighter", "Quest Fighter" },
 	{ "questfighterii", "Quest Fighter II" },
@@ -1008,7 +1008,6 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "seega16engl5", "seega16_engl_5" },
 	{ "seegame15", "seegame15" },
 	{ "sevendoors", "Seven  Doors" },
-	{ "stargateadv", "Stargate Adventure" },
 	{ "shadesofgreye", "Shades of Greye" },
 	{ "shadowsoftheempire", "Shadows of the Empire" },
 	{ "shailadusithlenqute", "Shai-la du Sith : l'Enqu?te" },
@@ -1053,11 +1052,6 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "spacequest3vgapreview", "Space Quest III VGA Preview" },
 	{ "spacequest45", "Space Quest 4.5" },
 	{ "spacequest55demoags", "Space Quest 5.5 demo (AGS)" },
-	{ "sqm11", "Space Quest Mania 1x1" },
-	{ "sqm12", "Space Quest Mania 1x2" },
-	{ "sqm13", "Space Quest Mania 1x3" },
-	{ "sqm14", "Space Quest Mania 1x4" },
-	{ "sqm16", "Space Quest Mania 1x6" },
 	{ "spacerangers", "Space Rangers " },
 	{ "spacerangersep52", "Space Rangers Ep 52" },
 	{ "spacewar", "Space war" },
@@ -1069,6 +1063,11 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "spotthedifference", "Spot The Difference" },
 	{ "sproutsofevil", "Sprouts of evil" },
 	{ "sqkubikgetready", "SQ Kubik (Get ready?)" },
+	{ "sqm11", "Space Quest Mania 1x1" },
+	{ "sqm12", "Space Quest Mania 1x2" },
+	{ "sqm13", "Space Quest Mania 1x3" },
+	{ "sqm14", "Space Quest Mania 1x4" },
+	{ "sqm16", "Space Quest Mania 1x6" },
 	{ "sqmania1", "SQ Mania #1" },
 	{ "sqmania2remakeeng", "SQ Mania 2 Remake (ENG)" },
 	{ "sqmaniaep5", "SQ Mania Ep5" },
@@ -1077,6 +1076,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "stairquest", "Stair Quest" },
 	{ "stanamespiepisode1", "Stan Ames PI, Episode 1" },
 	{ "stansrevenge", "Stan's Revenge" },
+	{ "stargateadv", "Stargate Adventure" },
 	{ "starshipcaramba", "Starship Caramba" },
 	{ "starshipposeidon", "Starship Poseidon" },
 	{ "start", "Start" },
@@ -1232,6 +1232,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "twoofakind", "Two of a Kind" },
 	{ "uglyfiles", "Ugly Files" },
 	{ "ulitsadimitrova", "Ulitsa Dimitrova" },
+	{ "unavowed", "Unavowed" },
 	{ "unboundver10", "Unbound Ver 1.0" },
 	{ "unfinished", "unfinished" },
 	{ "unganeedsmumba", "UNGA needs MUMBA" },
@@ -1269,10 +1270,12 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "wherebedragons", "Where Be Dragons?" },
 	{ "wheredidsamgo", "Where did Sam go?" },
 	{ "wheresmhatma", "Where's M' Hat Ma?" },
+	{ "whokilledkennyrogers", "Who Killed Kenny Rogers" },
 	{ "whowantstoliveagain", "Who wants to live again?" },
 	{ "whowantstoliveforever", "Who wants to live forever?" },
 	{ "williamsnightmare", "Williams Nightmare" },
 	{ "willowhouse", "Willow House" },
+	{ "winfry", "Winfry" },
 	{ "winnersdontdodrugs", "Winners Dont' Do Drugs" },
 	{ "winterrose", "Winter Rose" },
 	{ "witch", "Witch" },
@@ -1316,10 +1319,17 @@ static const PluginVersion AGSCREDITZ_11[] = { { "agscreditz", 11 }, { nullptr,
 
 const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	// Pre-2.5 games that aren't supported by the current AGS engine
+	UNSUPPORTED_DEMO("achristmastale", "tale.exe", "094135f05cf14fc3903e0d3697911a4e", 1484122),
+	UNSUPPORTED_DEMO("deepbright", "tc.exe", "8f80c91d160e333ab7f6be5208ea0533", 3022557),
+	UNSUPPORTED_DEMO("firewall", "firewall demo.exe", "2fd8ca69f236ae1ad46edab4ba26a33d", 2839412),
+	UNSUPPORTED_DEMO("larryvales3", "burns.exe", "094135f05cf14fc3903e0d3697911a4e", 2120885),
+	UNSUPPORTED_DEMO("nicholaswolfe1", "nw1demo.exe", "1f0edcb7fa3f8e2b1dd60fa6c0bce60f", 1539596),
+	UNSUPPORTED_DEMO("pointblank", "future.exe", "385a593828b1edb194e984ce55cda65e", 1379714),
+	UNSUPPORTED_DEMO("uishowoff", "pd.exe", "ecd0793124fbc9b89c6d11162e3b5851", 3853394),
+	UNSUPPORTED_DEMO("waitkey", "ac2game.dat", "8ddf3744922101e33305dfcd06e3b682", 445197),
 	UNSUPPORTED_ENTRY("6da", "6da.exe", "9027912819f3a319ed9de0fd855310c3", 1608073),
 	UNSUPPORTED_ENTRY("aaronsepicjourney", "aaron.exe", "1c21bdb52bcafcafe988b30fd6bb4126", 1788404),
 	UNSUPPORTED_ENTRY("aceduswell", "ace.exe", "be48a6b0b81a71d34a41930623c065f1", 3103822),
-	UNSUPPORTED_DEMO("achristmastale", "tale.exe", "094135f05cf14fc3903e0d3697911a4e", 1484122),
 	UNSUPPORTED_ENTRY("adayinthefuture", "space.exe", "ecd0793124fbc9b89c6d11162e3b5851", 4120328),
 	UNSUPPORTED_ENTRY("adventuregame", "adventure.exe", "221637e5d62e2ca3cc146846ab0b2e49", 5533207),
 	UNSUPPORTED_ENTRY("asapadventure", "asap.exe", "8f80c91d160e333ab7f6be5208ea0533", 1405072),
@@ -1336,7 +1346,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	UNSUPPORTED_ENTRY("chamber", "indy.exe", "094135f05cf14fc3903e0d3697911a4e", 1545150),
 	UNSUPPORTED_ENTRY("compensation", "comp.exe", "094135f05cf14fc3903e0d3697911a4e", 2054366),
 	UNSUPPORTED_ENTRY("darts", "dart.exe", "ed778afb4f46c3f2a70d330532a83a2f", 736848),
-	UNSUPPORTED_DEMO("deepbright", "tc.exe", "8f80c91d160e333ab7f6be5208ea0533", 3022557),
 	UNSUPPORTED_ENTRY("demonslayer1", "mags.exe", "1f0edcb7fa3f8e2b1dd60fa6c0bce60f", 3820347),
 	UNSUPPORTED_ENTRY("demonslayer2", "bert.exe", "0c057c5e6df6f45772286986ab7b7a5b", 1726766),
 	UNSUPPORTED_ENTRY("demonslayer3", "tiler.exe", "426e34f40e0dc5285af3fb5fc32a220e", 2586532),
@@ -1350,7 +1359,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	UNSUPPORTED_ENTRY("erniesbigadventure2", "magsjuly.exe", "2fd8ca69f236ae1ad46edab4ba26a33d", 6647578),
 	UNSUPPORTED_ENTRY("exile", "exile.exe", "aad0a09714fab4de51e5488da48fd5d4", 13421451),
 	UNSUPPORTED_ENTRY("eyesofthejadesphinx", "jade.exe", "f2fe94ab604612e4595f3c79b0245529", 10763660),
-	UNSUPPORTED_DEMO("firewall", "firewall demo.exe", "2fd8ca69f236ae1ad46edab4ba26a33d", 2839412),
 	UNSUPPORTED_ENTRY("floyd", "floyd.exe", "9ef5bffe7b85377751c25af806345794", 5477588),
 	UNSUPPORTED_ENTRY("gaeafallen", "gaea_fallen.exe", "80bdce9a1052e896c7cba6a4334cecce", 11273205),
 	UNSUPPORTED_ENTRY("gorthor", "fart.exe", "fc5f54dcfc82d3b991f670490a316958", 1138006),
@@ -1363,7 +1371,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	UNSUPPORTED_ENTRY("kidnapped", "ac2game.dat", "27daca01ccbbbaf02bf6b4b85d5990b4", 1205017),
 	UNSUPPORTED_ENTRY("larryvales1", "larryvtd.exe", "610b7a3d1fd90f24d2218aa26b29d8ca", 3129645),
 	UNSUPPORTED_ENTRY("larryvales2", "dead.exe", "be48a6b0b81a71d34a41930623c065f1", 3946993),
-	UNSUPPORTED_DEMO("larryvales3", "burns.exe", "094135f05cf14fc3903e0d3697911a4e", 2120885),
 	UNSUPPORTED_ENTRY("lassi", "lassi.exe", "ed778afb4f46c3f2a70d330532a83a2f", 3681914),
 	UNSUPPORTED_ENTRY("lassiandrogermeetgod", "mtg.exe", "ed778afb4f46c3f2a70d330532a83a2f", 1618544),
 	UNSUPPORTED_ENTRY("lassiquesti", "lassi.exe", "c391c6676099032440b206189babe76e", 1700368),
@@ -1380,14 +1387,12 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	UNSUPPORTED_ENTRY("moose", "moose.exe", "f4585823c1b4ce97d78c8acb433bec52", 1448684),
 	UNSUPPORTED_ENTRY("moosewars", "moose.exe", "f4585823c1b4ce97d78c8acb433bec52", 1448684),
 	UNSUPPORTED_ENTRY("murder", "murder.exe", "221637e5d62e2ca3cc146846ab0b2e49", 935799),
-	UNSUPPORTED_DEMO("nicholaswolfe1", "nw1demo.exe", "1f0edcb7fa3f8e2b1dd60fa6c0bce60f", 1539596),
 	UNSUPPORTED_ENTRY("nightoftheplumber", "night of the plumber.exe", "1f0edcb7fa3f8e2b1dd60fa6c0bce60f", 1703896),
 	UNSUPPORTED_ENTRY("novomestro", "novo.exe", "07f9921784124d9e09f39bb831e06131", 1122507),
 	UNSUPPORTED_ENTRY("odysseus", "odysseus.exe", "426e34f40e0dc5285af3fb5fc32a220e", 2799113),
 	UNSUPPORTED_ENTRY("permanentdaylight", "daylight.exe", "07f9921784124d9e09f39bb831e06131", 1799958),
 	UNSUPPORTED_ENTRY("perpetrator", "ac2game.dat", "56ef979be112e122e24d0cc8caea4ea4", 994303),
 	UNSUPPORTED_ENTRY("pizzaquest", "pqwin.exe", "73f87b30f84e9c34ab09ec8dd7ae109d", 2500089),
-	UNSUPPORTED_DEMO("pointblank", "future.exe", "385a593828b1edb194e984ce55cda65e", 1379714),
 	UNSUPPORTED_ENTRY("pornquest", "porn.exe", "04eedea9846d380d6d9a120f657daa43", 1012323),
 	UNSUPPORTED_ENTRY("qfc", "qfc.exe", "04eedea9846d380d6d9a120f657daa43", 2038696),
 	UNSUPPORTED_ENTRY("qfg412", "qfg.exe", "8b21668ca462b0b6b35df43c5902b074", 26674790),
@@ -1424,51 +1429,49 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	UNSUPPORTED_ENTRY("tommato", "tom mato's grand wing-ding.exe", "73f87b30f84e9c34ab09ec8dd7ae109d", 2735158),
 	UNSUPPORTED_ENTRY("tulliesworld1", "candale.exe", "1c21bdb52bcafcafe988b30fd6bb4126", 3936603),
 	UNSUPPORTED_ENTRY("tvquest", "mags.exe", "fc5f54dcfc82d3b991f670490a316958", 1318019),
-	UNSUPPORTED_DEMO("uishowoff", "pd.exe", "ecd0793124fbc9b89c6d11162e3b5851", 3853394),
-	UNSUPPORTED_DEMO("waitkey", "ac2game.dat", "8ddf3744922101e33305dfcd06e3b682", 445197),
 	UNSUPPORTED_ENTRY("whokilledkennyrogers", "mags.exe", "ed778afb4f46c3f2a70d330532a83a2f", 1240103),
 	UNSUPPORTED_ENTRY("winfry", "fry.exe", "73f87b30f84e9c34ab09ec8dd7ae109d", 4164041),
 
-	// Post-2.5 games that are likely supported by the AGS engine
-	ENGLISH_ENTRY("5daysastranger", "5days.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 4440143),
-	ENGLISH_ENTRY("7daysaskeptic", "7days.exe", "465f972675db2da6040518221af5b0ba", 4693374),
-	ENGLISH_ENTRY("atotk", "atotk.exe", "37cf2d4d07842d45b59c6dd9387c1ee7", 42872046),
-	ENGLISH_ENTRY("atotk", "atotk.exe", "37cf2d4d07842d45b59c6dd9387c1ee7", 42740200),
-	ENGLISH_PLUGIN("bcremake", "bc.exe", "0710e2ec71042617f565c01824f0cf3c", 7683255, AGSCREDITZ_11),
+	// AGDI games. They get their own grouping because they're just that awesome
+	ENGLISH_ENTRY("kq1agdi", "kq1vga.exe", "688f1807c9d8df26fc0f174dc756054e", 8278611),  // 4.1c
+	ENGLISH_ENTRY("kq2agdi", "kq2vga.exe", "40cfb7563df7dacf6530b19289a4745b", 12563246),	// 3.1
+	ENGLISH_ENTRY("kq2agdi", "kq2vga.exe", "40cfb7563df7dacf6530b19289a4745b", 12574643),  // 3.1c
+	ENGLISH_ENTRY("kq3agdi", "kq3redux.exe", "e569fb2ceabdc4a1609348c23ebc0821", 11986266),  // 1.1
+	ENGLISH_ENTRY("qfg2agdi", "qfg2vga.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 20470902),
+	ENGLISH_ENTRY("qfg2agdi", "qfg2vga.exe", "582e26533cf784011c7565e89905d3c4", 18224373),
+
+	// Comercial games
 	ENGLISH_ENTRY("blackwell1", "blackwell1.exe", "605e124cb7e0b56841c471e2d641c224", 18822697), // GOG
 	ENGLISH_ENTRY("blackwell2", "unbound.exe", "5c3a940514d91431e8e1c372018851ca", 14493753), // GOG
 	ENGLISH_ENTRY("blackwell3", "convergence.exe", "2260c1a21aba7ac00baf0100d4ca54f1", 172575801), // GOG
 	ENGLISH_ENTRY("blackwell4", "deception.exe", "b3b192cf20a2f7666ddea3410dbd87cc", 303459336), // GOG
 	ENGLISH_ENTRY("blackwell5", "epiphany.exe", "c1cddd6fcdbcd030beda9f10d4e4270a", 281849897), // GOG
-	ENGLISH_ENTRY("kq1agdi", "kq1vga.exe", "688f1807c9d8df26fc0f174dc756054e", 8278611),  // 4.1c
-	ENGLISH_ENTRY("kq2agdi", "kq2vga.exe", "40cfb7563df7dacf6530b19289a4745b", 12563246),	// 3.1
-	ENGLISH_ENTRY("kq2agdi", "kq2vga.exe", "40cfb7563df7dacf6530b19289a4745b", 12574643),  // 3.1c
-	ENGLISH_ENTRY("kq3agdi", "kq3redux.exe", "e569fb2ceabdc4a1609348c23ebc0821", 11986266),  // 1.1
 	ENGLISH_ENTRY("geminirue", "gemini rue.exe", "f3c0c7d3892bdd8963e8ce017f73de08", 61986506), // GOG
-	ENGLISH_ENTRY("goldenwake", "a-golden-wake.exe", "dbe281d93c914899886e77c09c3c65ec", 130844360), // Steam
-	ENGLISH_ENTRY("kathyrain", "kathyrain.exe", "434e24a12ba3cfb07d7b4b2f0e0bb1bf", 197487159), // Steam
-	ENGLISH_ENTRY("qfi", "qfi.exe", "0702df6e67ef87fd3c51d09303803126", 534847265), // GOG
-	ENGLISH_ENTRY("oott", "OotT-TKC.exe", "11c2421258465cba4bd773c49d918ee3", 467834855), // GOG
 	ENGLISH_ENTRY("primordia", "primordia.exe", "22313e59c3233001488c26f18c80cc08", 973495830), // GOG
 	ENGLISH_ENTRY("primordia", "primordia.exe", "f2edc9c3161f1f538df9b4c59fc89e24", 978377890), // GOG
 	ENGLISH_ENTRY("resonance", "resonance.exe", "2e635c22bcbf0ed3d46f1bcde71812d4", 849404957), // GOG
-	ENGLISH_ENTRY("mage", "ac2game.dat", "2e822f554994f36e0c62da2acda874da", 30492258), // GOG, Mac
-	ENGLISH_ENTRY("unavowed", "ac2game.dat", "b1ff7d96667707daf4266975cea2bf90", 1755457364), // Steam, Mac
 
-	// Unsorted games
+	// Post-2.5 games that are likely supported by the AGS engine
+	ENGLISH_DEMO("bytheswordconspiracy", "bts.exe", "7dc7f61f79ba7a77d4ef8168bfd3d173", 60246329),
+	ENGLISH_DEMO("searchforsanity", "sfs.exe", "308d35bc34e9df29d8acce615593e3e7", 9097147),
+	ENGLISH_DEMO("shadowsoftheempire", "sote_td.exe", "b8cd640b45c5a79c33c7a8a8fe32ebe2", 63299246),
+	ENGLISH_DEMO("theloneloser", "DEMO (English).exe", "0500aacb6c176d47ac0f8158f055db83", 6082095),
+	ENGLISH_DEMO("wallyweasel", "WallyDemo.exe", "95b7dd55f6e15c8a2118856ed9fe8ff9", 12579444),
 	ENGLISH_ENTRY("10waysfromsunday", "10WaysFromSunday.exe", "495d45fb8adfd49690ae3b97921feec6", 11362765),
 	ENGLISH_ENTRY("1dayamosquito", "mosquito.exe", "465f972675db2da6040518221af5b0ba", 2178983),
 	ENGLISH_ENTRY("2034acaftercanadaii", "2034 AC II.exe", "1280ba7c269a68a9505871516319db0c", 35207006),
 	ENGLISH_ENTRY("24hours", "24.exe", "f120690b506dd63cd7d1112ea6af2f77", 1932370),
-	ENGLISH_ENTRY("3piggiesalpha", "Three Little Pigs and a Wolf.exe", "23a67b6de10ec35e9f5a4dfc7d928222", 14180634),
 	ENGLISH_ENTRY("3piggiesalpha", "3piggiesAlpha.exe", "23a67b6de10ec35e9f5a4dfc7d928222", 14181120),
+	ENGLISH_ENTRY("3piggiesalpha", "Three Little Pigs and a Wolf.exe", "23a67b6de10ec35e9f5a4dfc7d928222", 14180634),
 	ENGLISH_ENTRY("46memorylane", "diyu.exe", "e3962995a70923a8d5a8f1cf8f932eee", 66686277),
 	ENGLISH_ENTRY("4ofclubs", "4ofClubs.exe", "06a03fe35791b0578068ab1873455463", 5909169),
 	ENGLISH_ENTRY("5daysastranger", "5days.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 4614351),
+	ENGLISH_ENTRY("5daysastranger", "5days.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 4440143),
 	ENGLISH_ENTRY("5oclocklock", "DadGame.exe", "3018c5443291aec823bc63342ce4c58b", 6073887),
 	ENGLISH_ENTRY("6daysasacrifice", "6das.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 7993899),
 	ENGLISH_ENTRY("6mornings", "project2.exe", "e7dac058b9bc0b42d489e474c2ddec84", 11595240),
 	ENGLISH_ENTRY("7daysaskeptic", "7days.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 4863356),
+	ENGLISH_ENTRY("7daysaskeptic", "7days.exe", "465f972675db2da6040518221af5b0ba", 4693374),
 	ENGLISH_ENTRY("aazor", "aazor.exe", "465f972675db2da6040518221af5b0ba", 4956212),
 	ENGLISH_ENTRY("abducted", "10 MINUTES.exe", "465f972675db2da6040518221af5b0ba", 2687034),
 	ENGLISH_ENTRY("absent", "Absent.exe", "aabdafae8b57dfc48fdf158a72326c23", 39284149),
@@ -1520,8 +1523,8 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("alientimezone", "ATZ.exe", "0710e2ec71042617f565c01824f0cf3c", 2911858),
 	ENGLISH_ENTRY("aloneinthenight", "ALONE.exe", "0710e2ec71042617f565c01824f0cf3c", 9501343),
 	ENGLISH_ENTRY("alphadog", "Alpha_Dog.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 3329253),
-	ENGLISH_ENTRY("alphax", "Project SMASH.exe", "06a03fe35791b0578068ab1873455463", 25377719),
 	ENGLISH_ENTRY("alphax", "alphax.exe", "06a03fe35791b0578068ab1873455463", 17879795),
+	ENGLISH_ENTRY("alphax", "Project SMASH.exe", "06a03fe35791b0578068ab1873455463", 25377719),
 	ENGLISH_ENTRY("alquest1demo", "AlQuest.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 20154310),
 	ENGLISH_ENTRY("alysvsthephantomfelinefoe", "Alys.exe", "3c5bd1713959ff469cb46ebe5542cfcf", 22323495),
 	ENGLISH_ENTRY("amagicstone", "A magic stone.exe", "465f972675db2da6040518221af5b0ba", 5478520),
@@ -1540,11 +1543,11 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("apprentice2", "App2.exe", "465f972675db2da6040518221af5b0ba", 34159191),
 	ENGLISH_ENTRY("apprenticedeluxe", "App.exe", "45ab4f29031b50c8d01d10a269f77ff5", 17488604),
 	ENGLISH_ENTRY("aprofoundjourney", "apj.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 920131),
-	ENGLISH_ENTRY("archeos", "Archeos.exe", "2ff048659aaefd20d342db6428a5f1a0", 6661410),
 	ENGLISH_ENTRY("archeos", "Archeos.exe", "2ff048659aaefd20d342db6428a5f1a0", 6659974),
+	ENGLISH_ENTRY("archeos", "Archeos.exe", "2ff048659aaefd20d342db6428a5f1a0", 6661410),
 	ENGLISH_ENTRY("arewethereyet", "AREwethereyet.exe", "f120690b506dd63cd7d1112ea6af2f77", 1054672),
-	ENGLISH_ENTRY("armageddonmargaret", "Armageddon Margaret.exe", "3128b9f90e2f954ba704414ae854d10b", 2951568),
 	ENGLISH_ENTRY("armageddonmargaret", "AM_Game.exe", "06a03fe35791b0578068ab1873455463", 3640885),
+	ENGLISH_ENTRY("armageddonmargaret", "Armageddon Margaret.exe", "3128b9f90e2f954ba704414ae854d10b", 2951568),
 	ENGLISH_ENTRY("asecondface", "Eye of Geltz.exe", "0e32c4b3380e286dc0cea8550f1c045e", 7061019),
 	ENGLISH_ENTRY("ashortnightmare", "A_Short_Nightmare.exe", "b142b43c146c25443a1d155d441a6a81", 94221930),
 	ENGLISH_ENTRY("asporia", "RPG.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 7094164),
@@ -1555,6 +1558,8 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("ataleofbetrayal", "Mags.exe", "465f972675db2da6040518221af5b0ba", 11071496),
 	ENGLISH_ENTRY("ataleoftwokingdoms", "ATOTK.exe", "37cf2d4d07842d45b59c6dd9387c1ee7", 42785860),
 	ENGLISH_ENTRY("atapi", "Atapi.exe", "dd8586ebefd5c457e29b6b9845a576ea", 34114381),
+	ENGLISH_ENTRY("atotk", "atotk.exe", "37cf2d4d07842d45b59c6dd9387c1ee7", 42740200),
+	ENGLISH_ENTRY("atotk", "atotk.exe", "37cf2d4d07842d45b59c6dd9387c1ee7", 42872046),
 	ENGLISH_ENTRY("atotkjukebox", "Jukebox.exe", "37cf2d4d07842d45b59c6dd9387c1ee7", 1631992),
 	ENGLISH_ENTRY("atreatandsometricks", "A Treat and Some Tricks.exe", "495d45fb8adfd49690ae3b97921feec6", 33708250),
 	ENGLISH_ENTRY("aunaturel", "Au Naturel.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 8499426),
@@ -1578,6 +1583,7 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("barnrunnerholiday2", "Xmas 2.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 31770973),
 	ENGLISH_ENTRY("bartsquestfortv", "Simpsons.exe", "0500aacb6c176d47ac0f8158f055db83", 794013),
 	ENGLISH_ENTRY("battlewarriors", "Battle.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 16314318),
+	ENGLISH_PLUGIN("bcremake", "bc.exe", "0710e2ec71042617f565c01824f0cf3c", 7683255, AGSCREDITZ_11),
 	ENGLISH_ENTRY("beacon", "Beacon.exe", "af0d268193a9220891e983d03141ec58", 24671086),
 	ENGLISH_ENTRY("bear", "Bear.exe", "97020973a2a635fe28eb0ba4bdfaa70b", 3258662),
 	ENGLISH_ENTRY("beasts", "beasts.exe", "0500aacb6c176d47ac0f8158f055db83", 1295435),
@@ -1631,7 +1637,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("bunnyquest", "BunnyQuest.exe", "28f82e420b82d07651b68114f90223c8", 1154928),
 	ENGLISH_ENTRY("burymeinthesand", "buryme.exe", "f10516e88ec858700804ee69d041aead", 24252498),
 	ENGLISH_ENTRY("butcherstanys", "Stanys.exe", "97d700529f5cc826f230c27acf81adfd", 1404933),
-	ENGLISH_DEMO("bytheswordconspiracy", "bts.exe", "7dc7f61f79ba7a77d4ef8168bfd3d173", 60246329),
 	ENGLISH_ENTRY("calebsdrunkenadventure", "Calebdru.exe", "0b7529a76f38283d6e850b8d56526fc1", 15484923),
 	ENGLISH_ENTRY("calsoon2", "Looncalsoon.exe", "97d700529f5cc826f230c27acf81adfd", 18981033),
 	ENGLISH_ENTRY("capricorn", "capricorn.exe", "06a03fe35791b0578068ab1873455463", 4817076),
@@ -1653,8 +1658,8 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("chemin", "chemin.exe", "06a03fe35791b0578068ab1873455463", 3179064),
 	ENGLISH_ENTRY("chezapa", "CHEZAPA.exe", "9cf51833e787cc919837d9a8bd8fc14c", 2870327),
 	ENGLISH_ENTRY("chickchaser", "AMY.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 7968024),
-	ENGLISH_ENTRY("chicken", "Chicken.exe", "f120690b506dd63cd7d1112ea6af2f77", 30627567),
 	ENGLISH_ENTRY("chicken", "chicken.exe", "f120690b506dd63cd7d1112ea6af2f77", 1652888),
+	ENGLISH_ENTRY("chicken", "Chicken.exe", "f120690b506dd63cd7d1112ea6af2f77", 30627567),
 	ENGLISH_ENTRY("chickenfraction", "Chicken.exe", "0500aacb6c176d47ac0f8158f055db83", 3021315),
 	ENGLISH_ENTRY("chinesecheckers", "ChineseCheckers.exe", "06a03fe35791b0578068ab1873455463", 3391826),
 	ENGLISH_ENTRY("christmaspresent", "christmas.exe", "3128b9f90e2f954ba704414ae854d10b", 5644948),
@@ -1700,15 +1705,15 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("dalesfilmquest", "dale.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 2557975),
 	ENGLISH_ENTRY("damsel", "Damsel.exe", "809418706c429cee5d88e8d483c906cc", 77101995),
 	ENGLISH_ENTRY("dancetilyoudrop", "DanceTilYouDrop.exe", "0710e2ec71042617f565c01824f0cf3c", 4822399),
-	ENGLISH_ENTRY("danewguys", "DaNewGuys.exe", "97020973a2a635fe28eb0ba4bdfaa70b", 11998791),
 	ENGLISH_ENTRY("danewguys", "DaNewGuys.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 12115013),
+	ENGLISH_ENTRY("danewguys", "DaNewGuys.exe", "97020973a2a635fe28eb0ba4bdfaa70b", 11998791),
 	ENGLISH_ENTRY("dangerouslandstournamentrpg", "dlrt2.exe", "0710e2ec71042617f565c01824f0cf3c", 21636362),
 	ENGLISH_ENTRY("dannydreadisoncall", "On Call.exe", "ef480ccb0831e452e55456e0ca24c761", 8787649),
 	ENGLISH_ENTRY("darkcave", "DarkCave.exe", "0d48d8b170624e8f33bd7cd7f3ad2052", 5293954),
 	ENGLISH_ENTRY("darkofnight", "D_o_N.exe", "3f7bb944e107f883d183f047d9d7f698", 10261961),
 	ENGLISH_ENTRY("darktimesmerrychristmas", "Dark Times (Merry Christmas).exe", "1b9f13d430bb15bf30d0fd044358db68", 49043355),
-	ENGLISH_ENTRY("darum", "Darum.exe", "0241777c2537fc5d077c05cde10bfa9f", 4082708),
 	ENGLISH_ENTRY("darum", "afterlife.exe", "0241777c2537fc5d077c05cde10bfa9f", 4082712),
+	ENGLISH_ENTRY("darum", "Darum.exe", "0241777c2537fc5d077c05cde10bfa9f", 4082708),
 	ENGLISH_ENTRY("davegeneric", "generic.exe", "a524cbb1c51589903c4043b98917f1d9", 2449830),
 	ENGLISH_ENTRY("davidletterman", "letterman.exe", "615e806856b7730afadf1fea9a756b70", 17019706),
 	ENGLISH_ENTRY("dawnswonderedatagesend", "myGame.exe", "75f4c7f66b1be60af5b2d65f617b91a7", 243406385),
@@ -1750,7 +1755,7 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("dumbassdriversdemo", "dumbass.exe", "f120690b506dd63cd7d1112ea6af2f77", 40580988),
 	ENGLISH_ENTRY("dungeonhands", "DungeonHands.exe", "0a6704159f6f716ac80da91c430430ce", 16276450),
 	ENGLISH_ENTRY("dungeonhands", "DungeonHands.exe", "f80ff6c2348f2bb90d3813719f54c870", 13751518),
-	ENGLISH_ENTRY("duskhunters", "DuskHunters.exe", "3128b9f90e2f954ba704414ae854d10b",3029482),
+	ENGLISH_ENTRY("duskhunters", "DuskHunters.exe", "3128b9f90e2f954ba704414ae854d10b", 3029482),
 	ENGLISH_ENTRY("dusttowater", "Dust to Water.exe", "0e32c4b3380e286dc0cea8550f1c045e", 70459846),
 	ENGLISH_ENTRY("dutyandbeyond", "Deliver.exe", "0710e2ec71042617f565c01824f0cf3c", 28873258),
 	ENGLISH_ENTRY("duzzquest", "DuzzQuest.exe", "3128b9f90e2f954ba704414ae854d10b", 13125200),
@@ -1857,6 +1862,7 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("glitchquestnofun", "GQnofun.exe", "465f972675db2da6040518221af5b0ba", 3181931),
 	ENGLISH_ENTRY("gnomeshomebrewingadventure", "gnomebrew.exe", "abb3aee32ae97a8475626cceefb0664e", 50307521),
 	ENGLISH_ENTRY("gnrblexags", "Gnrblex_AGS.exe", "476a1a39d43ea27577eacf907173e2c1", 85038656),
+	ENGLISH_ENTRY("goldenwake", "a-golden-wake.exe", "dbe281d93c914899886e77c09c3c65ec", 130844360), // Steam
 	ENGLISH_ENTRY("goneboatfishin", "Gone Boat Fishin'.exe", "bdd1df0484e296faa348ffcb03e16273", 72936045),
 	ENGLISH_ENTRY("goodmorningmrgingerbread", "mister_gingerbread.exe", "b42f80733b6bd1ded5e29be2c683afa8", 7084332),
 	ENGLISH_ENTRY("goodsantabadsanta", "x-mags.exe", "71ca0d6c1c699595f28a2125948d4a84", 1966547),
@@ -1865,6 +1871,7 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("graveyard", "Graveyard.exe", "955b711b21d7a2df6af1bb0cccccbb08", 13699789),
 	ENGLISH_ENTRY("gremlin", "Gremlin.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 3962167),
 	ENGLISH_ENTRY("grizzlygooseofgosse", "Goose Fear.exe", "b69b5887e4a33a3b8588d52fed04b730", 32123559),
+	ENGLISH_ENTRY("grok", "grok.exe", "9cf51833e787cc919837d9a8bd8fc14c", 1046039),
 	ENGLISH_ENTRY("grr", "Grr!.exe", "3128b9f90e2f954ba704414ae854d10b", 26753739),
 	ENGLISH_ENTRY("guardiansofgold", "Guardians of Gold.exe", "933200c8f306eccaaa484b1575da8528", 429166629),
 	ENGLISH_ENTRY("guyslug", "GuySlug.exe", "0710e2ec71042617f565c01824f0cf3c", 1959514),
@@ -1913,9 +1920,9 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("iforgot", "Forgot.exe", "6aa30185326552359c7865e55c045a74", 7743871),
 	ENGLISH_ENTRY("igs", "IGS.exe", "95b7dd55f6e15c8a2118856ed9fe8ff9", 1204802),
 	ENGLISH_ENTRY("iiispy", "IIISpy.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 6696286),
-	ENGLISH_ENTRY("illuminationdiminishing", "IlluminationDiminishing.exe", "b142b43c146c25443a1d155d441a6a81", 49006319),
 	ENGLISH_ENTRY("illuminationdiminishing", "IlluminationDiminishing.exe", "b142b43c146c25443a1d155d441a6a81", 21227029),
 	ENGLISH_ENTRY("illuminationdiminishing", "IlluminationDiminishing.exe", "b142b43c146c25443a1d155d441a6a81", 49006279),
+	ENGLISH_ENTRY("illuminationdiminishing", "IlluminationDiminishing.exe", "b142b43c146c25443a1d155d441a6a81", 49006319),
 	ENGLISH_ENTRY("imnotcrazyrightthecell", "I'm not crazy.exe", "9cb3c8dc7a8ab9c44815955696be2677", 3152216),
 	ENGLISH_ENTRY("imnotcrazyrightthewell", "The Well.exe", "9cb3c8dc7a8ab9c44815955696be2677", 5000358),
 	ENGLISH_ENTRY("indianajonescomingofage", "IndyCOA.exe", "90413e9ae57e222f8913b09d2bc847bc", 2368083),
@@ -1962,6 +1969,7 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("justignorethem", "justignorethem.exe", "7a3096ac0237cb6aa8e1718e28caf039", 98544330),
 	ENGLISH_ENTRY("kanjigakusei", "KanjiGakusei.exe", "c1bce0ccfa858f0f5d2fe19997d89b05", 17604764),
 	ENGLISH_ENTRY("kartquestv053", "Kart.exe", "465f972675db2da6040518221af5b0ba", 77317312),
+	ENGLISH_ENTRY("kathyrain", "kathyrain.exe", "434e24a12ba3cfb07d7b4b2f0e0bb1bf", 197487159), // Steam
 	ENGLISH_ENTRY("keptoshi", "Keptosh.exe", "95b7dd55f6e15c8a2118856ed9fe8ff9", 2904848),
 	ENGLISH_ENTRY("keys", "Keys.exe", "75f4c7f66b1be60af5b2d65f617b91a7", 85582285),
 	ENGLISH_ENTRY("killereye", "killereye.exe", "0710e2ec71042617f565c01824f0cf3c", 1009042),
@@ -2038,6 +2046,7 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("lukesexistentialnightmare", "Lukeexit.exe", "95b7dd55f6e15c8a2118856ed9fe8ff9", 653834),
 	ENGLISH_ENTRY("lunarlanderprototype", "LunarLanderPrototype.exe", "495d45fb8adfd49690ae3b97921feec6", 3510282),
 	ENGLISH_ENTRY("lydiaandthemysteryofnellrenomanor", "LydiaW.exe", "615e73fc1874e92d60a1996c2330ea36", 33971307),
+	ENGLISH_ENTRY("mage", "ac2game.dat", "2e822f554994f36e0c62da2acda874da", 30492258), // GOG, Mac
 	ENGLISH_ENTRY("maggieandmax", "Max.exe", "465f972675db2da6040518221af5b0ba", 5759981),
 	ENGLISH_ENTRY("magic8ball", "Magic-8-Ball.exe", "82da2565c456dcfb265ded6fe3189c0b", 4233735),
 	ENGLISH_ENTRY("magicalwhatevergirlrocksoutinthestoneage", "mwg.exe", "b2b99b5b3dcaee0fa292343c5a2c429b", 7784104),
@@ -2116,8 +2125,8 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("mysticseer", "NickOfTime.exe", "f120690b506dd63cd7d1112ea6af2f77", 4460113),
 	ENGLISH_ENTRY("mythicalgambitflawlessfatality", "MGFF.exe", "4887d3dca056a0772741b42f66e018fb", 59711760),
 	ENGLISH_ENTRY("nanobots", "Nanobots.exe", "95dcf736be87cf7d40bf64d5b078c4b7", 41977727),
-	ENGLISH_ENTRY("necroquest", "necroquest01.exe", "6d4adcef07a14b53369d23edf5117252", 12389204),
 	ENGLISH_ENTRY("necroquest", "necroquest01.exe", "2d111a69de0723f337bad661cb006239", 9545924),
+	ENGLISH_ENTRY("necroquest", "necroquest01.exe", "6d4adcef07a14b53369d23edf5117252", 12389204),
 	ENGLISH_ENTRY("nedysadventure", "Nedy.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 6463558),
 	ENGLISH_ENTRY("nekusnewtrip", "nnt.exe", "c0c1865c3c8369e034095a725ca1ddbf", 35012412),
 	ENGLISH_ENTRY("nekusnewtrip", "square enix.exe", "a524cbb1c51589903c4043b98917f1d9", 10630694),
@@ -2152,6 +2161,7 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("oneweekoneroom", "1 week 1 room.exe", "06a03fe35791b0578068ab1873455463", 4275934),
 	ENGLISH_ENTRY("onleavingthebuilding", "On Leaving The Building.exe", "fd68fced8b89792d2e90be87b33d4b19", 64776995),
 	ENGLISH_ENTRY("onlythegooddieyoungenglishversion", "OtGDY_En.exe", "87ccd318a469128530699388f916b86f", 153980124),
+	ENGLISH_ENTRY("oott", "OotT-TKC.exe", "11c2421258465cba4bd773c49d918ee3", 467834855), // GOG
 	ENGLISH_ENTRY("openquest", "OpenQuest.exe", "90413e9ae57e222f8913b09d2bc847bc", 3407165),
 	ENGLISH_ENTRY("operationnovi", "Operation Novi.exe", "465f972675db2da6040518221af5b0ba", 24583968),
 	ENGLISH_ENTRY("operationsavebluecup", "OSBC.exe", "f120690b506dd63cd7d1112ea6af2f77", 3040865),
@@ -2230,12 +2240,13 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("pubmasterquest2", "shogin crystal.exe", "90baefd2f369cebe25f3aa9ad90332d2", 35191110),
 	ENGLISH_ENTRY("pubmastersquest", "Pub Master Quest [Demo].exe", "e1676318c8a040fcf508b817013dc8fe", 23431689),
 	ENGLISH_ENTRY("puddypenguin", "Penguin.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 2328158),
-	ENGLISH_ENTRY("pupupupulaisenseikkailut", "Pupupeli.exe", "23a67b6de10ec35e9f5a4dfc7d928222", 13453697),
 	ENGLISH_ENTRY("pupupupulaisenseikkailut", "Game.exe", "23a67b6de10ec35e9f5a4dfc7d928222", 13431315),
+	ENGLISH_ENTRY("pupupupulaisenseikkailut", "Pupupeli.exe", "23a67b6de10ec35e9f5a4dfc7d928222", 13453697),
 	ENGLISH_ENTRY("purgatorio01", "Purgatorio 0.1.exe", "18b284c22010850f79bc5c20054a70c4", 194293367),
 	ENGLISH_ENTRY("purityofthesurf", "Surf.exe", "71ca0d6c1c699595f28a2125948d4a84", 11315703),
 	ENGLISH_ENTRY("puzzlebotsdemo", "Puzzlebots_Demo.exe", "34b49df9cf6eadb5c3587b3921d5b72f", 354138961),
 	ENGLISH_ENTRY("pxenophobe", "ProjXeno.exe", "465f972675db2da6040518221af5b0ba", 79053486),
+	ENGLISH_ENTRY("qfi", "qfi.exe", "0702df6e67ef87fd3c51d09303803126", 534847265), // GOG
 	ENGLISH_ENTRY("quantumnauts", "QNDEMO.exe", "aeb2dd29e5ff839cb3ee86cf3e87e3ca", 134237367),
 	ENGLISH_ENTRY("questfighter", "Quest Fighter.exe", "21fd0f65dfa48de2b39cb8ec23b30889", 2914128),
 	ENGLISH_ENTRY("questfighterii", "Quest Fighter 2.exe", "4d7d2addcde045dae6e0363a43f9acad", 5219511),
@@ -2271,8 +2282,8 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("returntocivilization", "ReturnTo.exe", "0710e2ec71042617f565c01824f0cf3c", 3280888),
 	ENGLISH_ENTRY("revelation10", "Revelation.exe", "06a03fe35791b0578068ab1873455463", 14512328),
 	ENGLISH_ENTRY("rickyquest", "black.exe", "06a03fe35791b0578068ab1873455463", 3250100),
-	ENGLISH_ENTRY("righteouscity", "RCII.exe", "06a03fe35791b0578068ab1873455463", 39085407),
 	ENGLISH_ENTRY("righteouscity", "RC PI - 3.00.exe", "089fab88e6e1075a2f5b271f6f5b3c57", 19786840),
+	ENGLISH_ENTRY("righteouscity", "RCII.exe", "06a03fe35791b0578068ab1873455463", 39085407),
 	ENGLISH_ENTRY("roadofdestiny", "ROD.exe", "618d7dce9631229b4579340b964c6810", 30127308),
 	ENGLISH_ENTRY("roadracer", "TR_Bryvis.exe", "cebb3ac5c3d2df939e7f0ec8f2975b64", 25080647),
 	ENGLISH_ENTRY("roastmothergoose", "RMG.exe", "00328f4f1e7729144483107b96b11df8", 46474982),
@@ -2317,7 +2328,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("schwarzweissrot", "SchwarzWeissRot.exe", "495d45fb8adfd49690ae3b97921feec6", 82913128),
 	ENGLISH_ENTRY("scnider", "scnider.exe", "3128b9f90e2f954ba704414ae854d10b", 1189237),
 	ENGLISH_ENTRY("scytheisland", "Scythe.exe", "0500aacb6c176d47ac0f8158f055db83", 7119760),
-	ENGLISH_DEMO("searchforsanity", "sfs.exe", "308d35bc34e9df29d8acce615593e3e7", 9097147),
 	ENGLISH_ENTRY("seashells", "Shells.exe", "0500aacb6c176d47ac0f8158f055db83", 6355325),
 	ENGLISH_ENTRY("seasongreetings2002", "xmas2002.exe", "97d700529f5cc826f230c27acf81adfd", 4263336),
 	ENGLISH_ENTRY("secretquestremake", "secretquest.exe", "f120690b506dd63cd7d1112ea6af2f77", 2121159),
@@ -2325,9 +2335,7 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("seega16engl5", "house_eng_5.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 1746878),
 	ENGLISH_ENTRY("seegame15", "housesitting_18.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 1746919),
 	ENGLISH_ENTRY("sevendoors", "7DOORS.exe", "18b284c22010850f79bc5c20054a70c4", 113716886),
-	ENGLISH_ENTRY("stargateadv", "StarGA.exe", "0710e2ec71042617f565c01824f0cf3c", 45738298),
 	ENGLISH_ENTRY("shadesofgreye", "Shades of Greye.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 16125855),
-	ENGLISH_DEMO("shadowsoftheempire", "sote_td.exe", "b8cd640b45c5a79c33c7a8a8fe32ebe2", 63299246),
 	ENGLISH_ENTRY("shailadusithlenqute", "Shai-la Enquete.exe", "a524cbb1c51589903c4043b98917f1d9", 7489302),
 	ENGLISH_ENTRY("shailaofthesith", "Shaila_of_the_Sith.exe", "a524cbb1c51589903c4043b98917f1d9", 76170347),
 	ENGLISH_ENTRY("shem", "Shem.exe", "0710e2ec71042617f565c01824f0cf3c", 8866401),
@@ -2379,22 +2387,23 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("spooks", "Spooks.exe", "0710e2ec71042617f565c01824f0cf3c", 22888238),
 	ENGLISH_ENTRY("spoonsiiitheunauthorizededition", "spoonsIII.exe", "2ca80bd50763378b72cd1e1cf25afac3", 16298983),
 	ENGLISH_ENTRY("spotthedifference", "Spot the Difference.exe", "0b7529a76f38283d6e850b8d56526fc1", 933452),
+	ENGLISH_ENTRY("sproutsofevil", "Sprouts of evil.exe", "bdd1df0484e296faa348ffcb03e16273", 22329944),
+	ENGLISH_ENTRY("sqkubikgetready", "SQ Kubik.exe", "4fb72c890984548ed6782063f2230942", 2184808),
 	ENGLISH_ENTRY("sqm11", "SQM1.exe", "465f972675db2da6040518221af5b0ba", 1001506),
 	ENGLISH_ENTRY("sqm12", "SQM 1x2.exe", "465f972675db2da6040518221af5b0ba", 755146),
 	ENGLISH_ENTRY("sqm13", "SQM 1x3.exe", "465f972675db2da6040518221af5b0ba", 1435210),
 	ENGLISH_ENTRY("sqm14", "SQM 1x4.exe", "465f972675db2da6040518221af5b0ba", 1383567),
 	ENGLISH_ENTRY("sqm16", "SQM 1x6.exe", "465f972675db2da6040518221af5b0ba", 1400100),
-	ENGLISH_ENTRY("sproutsofevil", "Sprouts of evil.exe", "bdd1df0484e296faa348ffcb03e16273", 22329944),
-	ENGLISH_ENTRY("sqkubikgetready", "SQ Kubik.exe", "4fb72c890984548ed6782063f2230942", 2184808),
 	ENGLISH_ENTRY("sqmania1", "SQMania1.exe", "465f972675db2da6040518221af5b0ba", 831674),
 	ENGLISH_ENTRY("sqmania2remakeeng", "SQM2 RMK.exe", "465f972675db2da6040518221af5b0ba", 3029288),
 	ENGLISH_ENTRY("sqmaniaep5", "SQ Mania Ep5.exe", "a524cbb1c51589903c4043b98917f1d9", 2896204),
 	ENGLISH_ENTRY("sram2cinomehsrevengedemo", "SRAM2.exe", "e3a33d139d90f2e695292a618753b8a5", 296499943),
-	ENGLISH_ENTRY("stablepeteandthejoust", "StablePete.exe", "b142b43c146c25443a1d155d441a6a81", 30048075),
 	ENGLISH_ENTRY("stablepeteandthejoust", "StablePete.exe", "b142b43c146c25443a1d155d441a6a81", 30046740),
+	ENGLISH_ENTRY("stablepeteandthejoust", "StablePete.exe", "b142b43c146c25443a1d155d441a6a81", 30048075),
 	ENGLISH_ENTRY("stairquest", "Stair Quest.exe", "e0aeab6a2c479fde167c4c43c3abb8ca", 4550699),
 	ENGLISH_ENTRY("stanamespiepisode1", "NEW.exe", "f120690b506dd63cd7d1112ea6af2f77", 19194728),
 	ENGLISH_ENTRY("stansrevenge", "Gameisle.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 915036),
+	ENGLISH_ENTRY("stargateadv", "StarGA.exe", "0710e2ec71042617f565c01824f0cf3c", 45738298),
 	ENGLISH_ENTRY("starshipcaramba", "karamba.exe", "465f972675db2da6040518221af5b0ba", 21540340),
 	ENGLISH_ENTRY("starshipposeidon", "Starship Poseidon.exe", "5a9abb3094d0b3f4bc09c0c77fbb8024", 4163873),
 	ENGLISH_ENTRY("start", "CC1.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 18627665),
@@ -2402,7 +2411,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("stediddyip1employment", "stediddy1.exe", "5872fea5a958bc74c2d9ca7b2d196c42", 27136166),
 	ENGLISH_ENTRY("stickmeni", "stick.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 2399329),
 	ENGLISH_ENTRY("stickythestickfigurepart1thecrimsonhouse", "Crimson House Files.exe", "3b095a7872e04769d04ab45e9c1b66eb", 3610653),
-	ENGLISH_ENTRY("grok", "grok.exe", "9cf51833e787cc919837d9a8bd8fc14c", 1046039),
 	ENGLISH_ENTRY("stranded", "Stranded.exe", "18b284c22010850f79bc5c20054a70c4", 39791629),
 	ENGLISH_ENTRY("stranger", "Stranger.exe", "0500aacb6c176d47ac0f8158f055db83", 5854099),
 	ENGLISH_ENTRY("strangerinstickworld", "game1.exe", "a524cbb1c51589903c4043b98917f1d9", 42525810),
@@ -2442,8 +2450,8 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("thebunker", "The Bunker.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 12391058),
 	ENGLISH_ENTRY("thecadaversynod", "The cadaver synod.exe", "36f44e064eab15e502caeb60fd09f52d", 37438749),
 	ENGLISH_ENTRY("thecan", "TheCan.exe", "82da2565c456dcfb265ded6fe3189c0b", 72388782),
-	ENGLISH_ENTRY("thecell", "The Cell.exe", "b142b43c146c25443a1d155d441a6a81", 21422530),
 	ENGLISH_ENTRY("thecell", "Cell.exe", "0b7529a76f38283d6e850b8d56526fc1", 811527),
+	ENGLISH_ENTRY("thecell", "The Cell.exe", "b142b43c146c25443a1d155d441a6a81", 21422530),
 	ENGLISH_ENTRY("thechrysalis", "Mygame.exe", "22b9c6d170613eb01afa1697b1b75cdb", 28926604),
 	ENGLISH_ENTRY("thecrackwelllegacy", "Crackwell.exe", "06a03fe35791b0578068ab1873455463", 2990976),
 	ENGLISH_ENTRY("thecube", "The Cube.exe", "97d700529f5cc826f230c27acf81adfd", 2029985),
@@ -2481,7 +2489,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("thejourneyofiesir", "The Journey of Iesir.exe", "376a3f162c7940d990325c53edc20fed", 70444514),
 	ENGLISH_ENTRY("thelastharvest", "The Last Harvest.exe", "f120690b506dd63cd7d1112ea6af2f77", 6253816),
 	ENGLISH_ENTRY("thelastsupperawhodunnit", "THE LAST SUPPER, A WHODUNNIT.exe", "37500274a7882e8087042cc6ec851e0c", 13447848),
-	ENGLISH_DEMO("theloneloser", "DEMO (English).exe", "0500aacb6c176d47ac0f8158f055db83", 6082095),
 	ENGLISH_ENTRY("thelongtrip", "longtrip.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 184362586),
 	ENGLISH_ENTRY("themajesticconspiracy", "majestic.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 17929647),
 	ENGLISH_ENTRY("themarionette", "marionette.exe", "ff3d6e4edfca8b4f4f1c6cbf8e2781a6", 88408446),
@@ -2518,8 +2525,8 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("thetrap", "Darcy.exe", "0500aacb6c176d47ac0f8158f055db83", 1164147),
 	ENGLISH_ENTRY("thetreasuredmedallion", "The Treasured Medallion.exe", "504df40bf50a0859e3dc15b000dab5f6", 1091122652),
 	ENGLISH_ENTRY("thetreasureoflochinch", "LochInch.exe", "6e861b1f476ff7cdf036082abb271329", 4091983),
-	ENGLISH_ENTRY("theuncertaintymachine", "TUMv11.exe", "b25674056fe8cc0b7bf0a4409c5c5bfc", 20672955),
 	ENGLISH_ENTRY("theuncertaintymachine", "TUMv11.exe", "b25674056fe8cc0b7bf0a4409c5c5bfc", 20670414),
+	ENGLISH_ENTRY("theuncertaintymachine", "TUMv11.exe", "b25674056fe8cc0b7bf0a4409c5c5bfc", 20672955),
 	ENGLISH_ENTRY("theupliftmofopartyplan", "MI5 Bob.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 4092850),
 	ENGLISH_ENTRY("thevacuum", "Spacefiles.exe", "d0ba73645e3cbf8ccd65121417f9895f", 14805166),
 	ENGLISH_ENTRY("thewitch", "Witch.exe", "f120690b506dd63cd7d1112ea6af2f77", 2693486),
@@ -2553,6 +2560,7 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("twoofakind", "toak.exe", "465f972675db2da6040518221af5b0ba", 24644765),
 	ENGLISH_ENTRY("uglyfiles", "ugly.exe", "0394af1c29e1060fcdbacf2a3dd9b231", 4169486),
 	ENGLISH_ENTRY("ulitsadimitrova", "ulitsa.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 291828379),
+	ENGLISH_ENTRY("unavowed", "ac2game.dat", "b1ff7d96667707daf4266975cea2bf90", 1755457364), // Steam, Mac
 	ENGLISH_ENTRY("unboundver10", "Unbound.exe", "900b277d7e1601c65b42868cd7fae662", 10448702),
 	ENGLISH_ENTRY("unfinished", "mags.exe", "0710e2ec71042617f565c01824f0cf3c", 12092514),
 	ENGLISH_ENTRY("unganeedsmumba", "UNGA needs MUMBA.exe", "2ca6bb6d5b2710ac89fea7d69c2eaf77", 5470102),
@@ -2573,7 +2581,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("vohaulsrevengeii", "SQ XII.exe", "465f972675db2da6040518221af5b0ba", 17313307),
 	ENGLISH_ENTRY("vpxt2", "VPET!2!.exe", "0b7529a76f38283d6e850b8d56526fc1", 12933096),
 	ENGLISH_ENTRY("waitingfortheloop", "WaitingForTheLoop.exe", "0241777c2537fc5d077c05cde10bfa9f", 51273604),
-	ENGLISH_DEMO("wallyweasel", "WallyDemo.exe", "95b7dd55f6e15c8a2118856ed9fe8ff9", 12579444),
 	ENGLISH_ENTRY("waltersasteroid", "HDGame.exe", "465f972675db2da6040518221af5b0ba", 8390872),
 	ENGLISH_ENTRY("warthogs", "Warthogs.exe", "9c49b6fa0460f36d6e7558281f142683", 12448793),
 	ENGLISH_ENTRY("washedashore", "Achtung!.exe", "06a03fe35791b0578068ab1873455463", 7926840),


Commit: 6efe97aaf9a51a5226d5162a656f252853f98a54
    https://github.com/scummvm/scummvm/commit/6efe97aaf9a51a5226d5162a656f252853f98a54
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Cleanup of demo detection entries

Changed paths:
    engines/ags/detection_tables.h


diff --git a/engines/ags/detection_tables.h b/engines/ags/detection_tables.h
index 9ab7ffe7c2..2a35af767f 100644
--- a/engines/ags/detection_tables.h
+++ b/engines/ags/detection_tables.h
@@ -216,7 +216,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "aloneinthenight", "Alone in the Night" },
 	{ "alphadog", "Alpha Dog" },
 	{ "alphax", "Alpha X" },
-	{ "alquest1demo", "Al-Quest 1 Demo" },
+	{ "alquest1", "Al-Quest 1" },
 	{ "alysvsthephantomfelinefoe", "Alys vs. The Phantom Feline Foe" },
 	{ "amagicstone", "A magic stone" },
 	{ "amotospuf", "Amotos Puf" },
@@ -263,7 +263,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "badluck", "BAD LUCK" },
 	{ "baldysadventure", "Baldy's Adventure" },
 	{ "baltazarthefamiliar", "Baltazar the Familiar" },
-	{ "bananamandemo", "Banana Man Demo" },
+	{ "bananaman", "Banana Man" },
 	{ "bananaracer", "Banana Racer" },
 	{ "barndilemma", "Barn Dilemma" },
 	{ "barnrunner5part1", "Barn Runner 5 (Part 1)" },
@@ -298,9 +298,6 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "blackmailinbrooklyn", "Blackmail In Brooklyn" },
 	{ "blackmorph", "Black Morph" },
 	{ "blackuddertodoubloonornottodoubloon", "Blackudder: To Doubloon or not to Doubloon" },
-	{ "blackwellconvergence", "Blackwell Convergence" },
-	{ "blackwelllegacydemo", "Blackwell Legacy Demo" },
-	{ "blackwellunbounddemo", "Blackwell Unbound Demo" },
 	{ "bluemoon", "Blue Moon" },
 	{ "boardquest", "Board Quest" },
 	{ "bob", "BOB" },
@@ -418,7 +415,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "detention", "Detention" },
 	{ "devochkaquest", "DevochkaQuest" },
 	{ "dgsearchofthebatterie", "DG: search of the batterie" },
-	{ "diamondsintheroughdemo", "Diamonds in the Rough DEMO" },
+	{ "diamondsintherough", "Diamonds in the Rough" },
 	{ "diemaskennyarlathoteps", "Die Masken Nyarlathoteps" },
 	{ "disquiet", "Disquiet" },
 	{ "doctormaze", "DOCTOR MAZE" },
@@ -438,7 +435,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "dreamer", "Dreamer" },
 	{ "dreamsequence", "dream sequence" },
 	{ "drlutztimetravelmachine", "Dr.Lutz Time Travel Machine" },
-	{ "dumbassdriversdemo", "Dumb.Ass Drivers! DEMO" },
+	{ "dumbassdrivers", "Dumb.Ass Drivers!" },
 	{ "dungeonhands", "Dungeon Hands" },
 	{ "duskhunters", "Dusk Hunters" },
 	{ "dusttowater", "Dust to Water" },
@@ -446,7 +443,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "duzzquest", "DuzzQuest" },
 	{ "duzzquest2", "DuzzQuest2" },
 	{ "dysmaton", "Dysmaton" },
-	{ "earlbobbyislookingforaloodemo", "Earl Bobby is looking for a Loo - DEMO" },
+	{ "earlbobbyislookingforaloo", "Earl Bobby is looking for a Loo" },
 	{ "earlbobbyislookingforhisshoes", "Earl Bobby is looking for his Shoes" },
 	{ "earlbobbysballs", "Earl Bobby's Balls" },
 	{ "earlmansinthebreakout", "Earl Mansin: The Breakout" },
@@ -464,7 +461,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "eliminationbyimprovisation", "Elimination by Improvisation" },
 	{ "emeraldeyes", "Emerald Eyes" },
 	{ "emilyenough", "Emily Enough" },
-	{ "emmarodedemo", "Emma Ro?de (DEMO)" },
+	{ "emmarode", "Emma Rode" },
 	{ "emptymindblankfate", "Empty Mind - Blank Fate" },
 	{ "enoworld", "Enoworld" },
 	{ "enterthestory", "Enter The Story" },
@@ -512,7 +509,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "forgettendeath", "Forgetten Death " },
 	{ "fortressofwonders", "Fortress of Wonders" },
 	{ "fountainofunicorns", "Fountain of Unicorns" },
-	{ "fountainofyouthdemo", "Fountain of Youth Demo" },
+	{ "fountainofyouth", "Indiana Jones and the Fountain of Youth" },
 	{ "framed", "Framed!" },
 	{ "frankenpooper", "Frankenpooper" },
 	{ "frankthefarmhandpart1", "Frank the Farmhand Part 1" },
@@ -532,11 +529,11 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "funwithnumbers", "Fun With Numbers" },
 	{ "gabyking", "GabyKing" },
 	{ "gamesgalore", "GAMES GALORE" },
-	{ "gassesuittollis3demo", "Gasse Suit Tollis 3 DEMO" },
+	{ "gassesuittollis3", "Gasse Suit Tollis 3" },
 	{ "gatewayremake", "Gateway Remake" },
 	{ "genbu", "Genbu" },
 	{ "geometricshapes1circleboy", "Geometric Shapes 1: Circleboy" },
-	{ "gesundheitdemo", "Gesundheit! Demo" },
+	{ "gesundheit", "Gesundheit!" },
 	{ "getawayfrompluto", "Get away from PLUTO" },
 	{ "getfood", "Get food" },
 	{ "ghostdream", "Ghostdream" },
@@ -631,7 +628,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "jamesbond", "James Bond" },
 	{ "jamesinneverland", "James in Neverland" },
 	{ "jamesperis", "James Peris" },
-	{ "jamesperis2demo", "James Peris 2 Demo" },
+	{ "jamesperis2", "James Peris 2" },
 	{ "javelincatch", "Javelin Catch" },
 	{ "jimmsquestiii", "Jimm's Quest III" },
 	{ "jimmysday", "Jimmy's Day" },
@@ -659,7 +656,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "killthelights", "Kill The Lights" },
 	{ "kingdomlegends", "Kingdom Legends" },
 	{ "kingsquestiii", "Kings Quest III" },
-	{ "kinkyislanddemo", "Kinky Island DEMO" },
+	{ "kinkyisland", "Kinky Island" },
 	{ "knightquestforgoldenring", "Knight Quest for Golden Ring" },
 	{ "knightsquestiii", "Knight's Quest III" },
 	{ "knightsquestiv", "Knight's Quest IV" },
@@ -683,7 +680,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "laundryday", "Laundry Day" },
 	{ "lavablava", "Lava Blava" },
 	{ "lazaruswantspants", "Lazarus Wants Pants" },
-	{ "lazytownthenewkiddemo", "LazyTown: The New Kid (demo)" },
+	{ "lazytownthenewkid", "LazyTown: The New Kid" },
 	{ "lbstoryofcedrickdusce", "LB: Story of Cedrick DUSCE!" },
 	{ "legendofrovendale", "Legend of Rovendale" },
 	{ "legendofseththebard", "Legend of Seth the Bard" },
@@ -920,7 +917,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "pupupupulaisenseikkailut", "Pupu Pupulaisen Seikkailut" },
 	{ "purgatorio01", "Purgatorio 0.1" },
 	{ "purityofthesurf", "Purity of the Surf" },
-	{ "puzzlebotsdemo", "Puzzle Bots Demo" },
+	{ "puzzlebots", "Puzzle Bots" },
 	{ "pxenophobe", "PXenophobe" },
 	{ "qfi", "Quest for Infamy" },
 	{ "quantumnauts", "QUANTUMNAUTS" },
@@ -1015,7 +1012,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "shem", "Shem" },
 	{ "sherlock", "Sherlock" },
 	{ "shiftersboxoutsidein", "Shifter's Box - Outside In" },
-	{ "shivahdemo", "Shivahdemo" },
+	{ "shivah", "Shivah" },
 	{ "shoot", "Shoot" },
 	{ "shootmyvalentine", "Shoot my Valentine" },
 	{ "shortcut", "ShortCut" },
@@ -1024,7 +1021,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "sierraquest1", "Sierra Quest 1" },
 	{ "silentknightii", "Silent Knight II" },
 	{ "silentknightv11", "Silent Knight v.1.1" },
-	{ "simonthesorcerer3demo20", "Simon the Sorcerer 3 Demo 2.0" },
+	{ "simonthesorcerer3", "Simon the Sorcerer 3" },
 	{ "skippysavestheday", "Skippy Saves The Day" },
 	{ "slaythedragon", "Slay the Dragon" },
 	{ "sleepyisland", "Sleepy Island" },
@@ -1049,9 +1046,9 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "spacelynxes", "Space Lynxes" },
 	{ "spacepirates", "Space Pirates" },
 	{ "spacepoolalpha", "Space Pool Alpha" },
-	{ "spacequest3vgapreview", "Space Quest III VGA Preview" },
+	{ "spacequest3vga", "Space Quest III VGA Preview" },
 	{ "spacequest45", "Space Quest 4.5" },
-	{ "spacequest55demoags", "Space Quest 5.5 demo (AGS)" },
+	{ "spacequest55", "Space Quest 5.5" },
 	{ "spacerangers", "Space Rangers " },
 	{ "spacerangersep52", "Space Rangers Ep 52" },
 	{ "spacewar", "Space war" },
@@ -1071,7 +1068,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "sqmania1", "SQ Mania #1" },
 	{ "sqmania2remakeeng", "SQ Mania 2 Remake (ENG)" },
 	{ "sqmaniaep5", "SQ Mania Ep5" },
-	{ "sram2cinomehsrevengedemo", "SRAM 2 - CINOMEH'S REVENGE (demo)" },
+	{ "sram2", "SRAM 2 - Cinomeh's Revenge" },
 	{ "stablepeteandthejoust", "Stable Pete and the Joust" },
 	{ "stairquest", "Stair Quest" },
 	{ "stanamespiepisode1", "Stan Ames PI, Episode 1" },
@@ -1090,7 +1087,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "strangerthings", "Stranger Things" },
 	{ "supaevil", "Supa-EviL" },
 	{ "supergirl", "Supergirl" },
-	{ "superjazzmandemo", "Super Jazz Man (DEMO)" },
+	{ "superjazzman", "Super Jazz Man" },
 	{ "superracing", "Super Racing" },
 	{ "surreality", "Surreality" },
 	{ "sweed", "Sweed" },
@@ -1206,8 +1203,8 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "threeguyswalkintoheaven", "Three Guys Walk Into Heaven" },
 	{ "tilepuzzlegame", "Tile Puzzle Game" },
 	{ "tiltor", "Tiltor" },
-	{ "timegentlemenpleasedemo", "Time Gentlemen, Please DEMO" },
-	{ "timequest", "Time Quest" },
+	{ "timegentlemenplease", "Time Gentlemen, Please" },
+	{ "timequest1", "Time Quest" },
 	{ "timequest2", "Time Quest 2" },
 	{ "timesinkofchronos", "Timesink of Chronos" },
 	{ "timothylande", "Timothy Lande" },
@@ -1290,7 +1287,7 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "yoda", "Yoda" },
 	{ "yourlate", "Your late!" },
 	{ "zakmckracken", "Zak McKracken" },
-	{ "zombieattackdemo", "Zombie Attack Demo" },
+	{ "zombieattack", "Zombie Attack" },
 	{ "zombiefish", "Zombie Fish" },
 	{ "zooreal", "ZooReal" },
 	{ "zugzwang", "Zugzwang" },
@@ -1452,11 +1449,45 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("resonance", "resonance.exe", "2e635c22bcbf0ed3d46f1bcde71812d4", 849404957), // GOG
 
 	// Post-2.5 games that are likely supported by the AGS engine
+	ENGLISH_DEMO("alquest1", "AlQuest.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 20154310),
+	ENGLISH_DEMO("bananaman", "Banana Man Demo.exe", "615e806856b7730afadf1fea9a756b70", 53524952),
+	ENGLISH_DEMO("blackwell1", "Blackwell Demo.exe", "2eeca6bae968dc61b5ed36561efc0fca", 53342880),
+	ENGLISH_DEMO("blackwell2", "Unbound_Demo.exe", "6ee842f73649ced615c44d4eb303687c", 30057537),
+	ENGLISH_DEMO("blackwell3", "Convergence.exe", "856a6e0e22d2cb4a45d5bbc7245ce5e8", 29935120),
 	ENGLISH_DEMO("bytheswordconspiracy", "bts.exe", "7dc7f61f79ba7a77d4ef8168bfd3d173", 60246329),
+	ENGLISH_DEMO("diamondsintherough", "Diamonds Demo.exe", "14c995189266969d538b31d1df451d3f", 2439365),
+	ENGLISH_DEMO("dumbassdrivers", "dumbass.exe", "f120690b506dd63cd7d1112ea6af2f77", 40580988),
+	ENGLISH_DEMO("earlbobbyislookingforaloo", "Demo.exe", "0e32c4b3380e286dc0cea8550f1c045e", 4221725),
+	ENGLISH_DEMO("emmarode", "Emma Roide.exe", "aefd91a131817036d224fe030e406c6e", 24919443),
+	ENGLISH_DEMO("flashbax", "demo Flashbax.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 5527034),
+	ENGLISH_DEMO("forcemajeureiithezone", "TheZoneDemo.exe", "b63d26c17bf292017f9a708ae9dc38ca", 18414473),
+	ENGLISH_DEMO("fountainofyouth", "foydemo.exe", "f120690b506dd63cd7d1112ea6af2f77", 14372003),
+	ENGLISH_DEMO("gassesuittollis3", "Gst3_demo.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 4270243),
+	ENGLISH_DEMO("gesundheit", "gesundheit.exe", "5554b9e0df6241d25c9a070708e54478", 49666357),
+	ENGLISH_DEMO("hiliaderoleagainsthell", "Dark Trial demo.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 36442694),
+	ENGLISH_DEMO("indycositalianver", "CoSdemo2.1-it.exe", "f120690b506dd63cd7d1112ea6af2f77", 5772985),
+	ENGLISH_DEMO("jamesperis2", "James2.exe", "06a03fe35791b0578068ab1873455463", 35766505),
+	ENGLISH_DEMO("jorry", "JORRY DEMO.exe", "fe5f7dc7785b335aec72a2a834629bad", 124667001),
+	ENGLISH_DEMO("kinkyisland", "KINKY.exe", "f120690b506dd63cd7d1112ea6af2f77", 10628479),
+	ENGLISH_DEMO("lazytownthenewkid", "newkiddemo1.2.exe", "9cb3c8dc7a8ab9c44815955696be2677", 15515508),
+	ENGLISH_DEMO("litnunforgettablememories", "litn_umtechdemo.exe", "f120690b506dd63cd7d1112ea6af2f77", 3507831),
+	ENGLISH_DEMO("mi5thereturnoflechuck", "Demo.exe", "0500aacb6c176d47ac0f8158f055db83", 6235270),
+	ENGLISH_DEMO("neofeud", "Neofeud Demo.exe", "6e861b1f476ff7cdf036082abb271329", 1886913453),
+	ENGLISH_DEMO("pubmastersquest", "Pub Master Quest [Demo].exe", "e1676318c8a040fcf508b817013dc8fe", 23431689),
+	ENGLISH_DEMO("puzzlebots", "Puzzlebots_Demo.exe", "34b49df9cf6eadb5c3587b3921d5b72f", 354138961),
+	ENGLISH_DEMO("quantumnauts", "QNDEMO.exe", "aeb2dd29e5ff839cb3ee86cf3e87e3ca", 134237367),
 	ENGLISH_DEMO("searchforsanity", "sfs.exe", "308d35bc34e9df29d8acce615593e3e7", 9097147),
 	ENGLISH_DEMO("shadowsoftheempire", "sote_td.exe", "b8cd640b45c5a79c33c7a8a8fe32ebe2", 63299246),
+	ENGLISH_DEMO("shivah", "shivahDemo.exe", "6e3d6225dee662ff6450a3bfa942773b", 20897850),
+	ENGLISH_DEMO("simonthesorcerer3", "Simon3.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 8189928),
+	ENGLISH_DEMO("spacequest3vga", "SQ3VGADEMO.exe", "64fcaf7da0b257ea831f89c54be0ad72", 3630019),
+	ENGLISH_DEMO("spacequest55", "SQ5.5.exe", "465f972675db2da6040518221af5b0ba", 16342443),
+	ENGLISH_DEMO("sram2", "SRAM2.exe", "e3a33d139d90f2e695292a618753b8a5", 296499943),
+	ENGLISH_DEMO("superjazzman", "SJMdemo.exe", "0710e2ec71042617f565c01824f0cf3c", 5214882),
 	ENGLISH_DEMO("theloneloser", "DEMO (English).exe", "0500aacb6c176d47ac0f8158f055db83", 6082095),
+	ENGLISH_DEMO("timegentlemenplease", "TGP.exe", "86a5359bac7c88f0dfa060478800dd61", 29686006),
 	ENGLISH_DEMO("wallyweasel", "WallyDemo.exe", "95b7dd55f6e15c8a2118856ed9fe8ff9", 12579444),
+	ENGLISH_DEMO("zombieattack", "ZADemo.exe", "82da2565c456dcfb265ded6fe3189c0b", 20958555),
 	ENGLISH_ENTRY("10waysfromsunday", "10WaysFromSunday.exe", "495d45fb8adfd49690ae3b97921feec6", 11362765),
 	ENGLISH_ENTRY("1dayamosquito", "mosquito.exe", "465f972675db2da6040518221af5b0ba", 2178983),
 	ENGLISH_ENTRY("2034acaftercanadaii", "2034 AC II.exe", "1280ba7c269a68a9505871516319db0c", 35207006),
@@ -1525,7 +1556,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("alphadog", "Alpha_Dog.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 3329253),
 	ENGLISH_ENTRY("alphax", "alphax.exe", "06a03fe35791b0578068ab1873455463", 17879795),
 	ENGLISH_ENTRY("alphax", "Project SMASH.exe", "06a03fe35791b0578068ab1873455463", 25377719),
-	ENGLISH_ENTRY("alquest1demo", "AlQuest.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 20154310),
 	ENGLISH_ENTRY("alysvsthephantomfelinefoe", "Alys.exe", "3c5bd1713959ff469cb46ebe5542cfcf", 22323495),
 	ENGLISH_ENTRY("amagicstone", "A magic stone.exe", "465f972675db2da6040518221af5b0ba", 5478520),
 	ENGLISH_ENTRY("amotospuf", "Amotos.exe", "06a03fe35791b0578068ab1873455463", 10771879),
@@ -1575,7 +1605,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("badluck", "Bad Luck.exe", "f120690b506dd63cd7d1112ea6af2f77", 10618466),
 	ENGLISH_ENTRY("baldysadventure", "Baldy.exe", "ea0d3284542db629f36cb6fc785e07bc", 179358984),
 	ENGLISH_ENTRY("baltazarthefamiliar", "Baltazar.exe", "9cb3c8dc7a8ab9c44815955696be2677", 2867294),
-	ENGLISH_ENTRY("bananamandemo", "Banana Man Demo.exe", "615e806856b7730afadf1fea9a756b70", 53524952),
 	ENGLISH_ENTRY("bananaracer", "BananaRacer.exe", "e93f9dfa8405f1ca9f881d160ab31dc2", 10452233),
 	ENGLISH_ENTRY("barndilemma", "woh.exe", "089fab88e6e1075a2f5b271f6f5b3c57", 2432485),
 	ENGLISH_ENTRY("barnrunner5part1", "Barn Runner 5-1.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 104073543),
@@ -1610,9 +1639,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("blackmailinbrooklyn", "brooklyn.exe", "3192c36199d2b0784f866b28da7106d8", 4913695),
 	ENGLISH_ENTRY("blackmorph", "Liechi.exe", "46859c6f77bdb311266daa589561fa6b", 14476030),
 	ENGLISH_ENTRY("blackuddertodoubloonornottodoubloon", "Blackudder.exe", "338fa79960d40689063af31c671b8729", 87695958),
-	ENGLISH_ENTRY("blackwellconvergence", "Convergence.exe", "856a6e0e22d2cb4a45d5bbc7245ce5e8", 29935120),
-	ENGLISH_ENTRY("blackwelllegacydemo", "Blackwell Demo.exe", "2eeca6bae968dc61b5ed36561efc0fca", 53342880),
-	ENGLISH_ENTRY("blackwellunbounddemo", "Unbound_Demo.exe", "6ee842f73649ced615c44d4eb303687c", 30057537),
 	ENGLISH_ENTRY("bluemoon", "Blue Moon.exe", "95dcf736be87cf7d40bf64d5b078c4b7", 14845997),
 	ENGLISH_ENTRY("boardquest", "Board Quest.exe", "465f972675db2da6040518221af5b0ba", 3930325),
 	ENGLISH_ENTRY("bob", "bob.exe", "0b7529a76f38283d6e850b8d56526fc1", 2874144),
@@ -1732,7 +1758,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("detention", "little.exe", "c16204dc8aa338e3199b2c62da0b33f4", 2362176),
 	ENGLISH_ENTRY("devochkaquest", "DevochkaQuest.exe", "84faea68bf7277610c2229be7b3e74af", 32769660),
 	ENGLISH_ENTRY("dgsearchofthebatterie", "dgsfb.exe", "88cf59aad15ca331ab0f854e16c84df3", 1664209),
-	ENGLISH_ENTRY("diamondsintheroughdemo", "Diamonds Demo.exe", "14c995189266969d538b31d1df451d3f", 2439365),
 	ENGLISH_ENTRY("diemaskennyarlathoteps", "ags_masken.exe", "74dc062c5f68f3d70da911f2db5737b6", 129219473),
 	ENGLISH_ENTRY("disquiet", "Disquiet.exe", "f90f5f612ed5879addfdd8634d093333", 9624101),
 	ENGLISH_ENTRY("doctormaze", "Maze.exe", "825ccacaabe2a3b0cd48d6f8deb42d72", 43934617),
@@ -1752,7 +1777,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("dreamer", "LittleDreamer.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 62151801),
 	ENGLISH_ENTRY("dreamsequence", "dreamseq.ags", "97d700529f5cc826f230c27acf81adfd", 4724470),
 	ENGLISH_ENTRY("drlutztimetravelmachine", "Dr.Lutz Machine.exe", "2bc8f994a7d1e05ed45f35abf2128231", 12602529),
-	ENGLISH_ENTRY("dumbassdriversdemo", "dumbass.exe", "f120690b506dd63cd7d1112ea6af2f77", 40580988),
 	ENGLISH_ENTRY("dungeonhands", "DungeonHands.exe", "0a6704159f6f716ac80da91c430430ce", 16276450),
 	ENGLISH_ENTRY("dungeonhands", "DungeonHands.exe", "f80ff6c2348f2bb90d3813719f54c870", 13751518),
 	ENGLISH_ENTRY("duskhunters", "DuskHunters.exe", "3128b9f90e2f954ba704414ae854d10b", 3029482),
@@ -1761,7 +1785,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("duzzquest", "DuzzQuest.exe", "3128b9f90e2f954ba704414ae854d10b", 13125200),
 	ENGLISH_ENTRY("duzzquest2", "DuzzQuest2.exe", "8911d942c1a71458370d37ca3e5bfdda", 59088366),
 	ENGLISH_ENTRY("dysmaton", "Dysmaton.exe", "6e861b1f476ff7cdf036082abb271329", 140513956),
-	ENGLISH_ENTRY("earlbobbyislookingforaloodemo", "Demo.exe", "0e32c4b3380e286dc0cea8550f1c045e", 4221725),
 	ENGLISH_ENTRY("earlbobbyislookingforhisshoes", "Bobby's Shoes.exe", "bb59de174d70797d774dec76a171352d", 12735626),
 	ENGLISH_ENTRY("earlbobbysballs", "Bobby's Balls.exe", "bb59de174d70797d774dec76a171352d", 4006605),
 	ENGLISH_ENTRY("earlmansinthebreakout", "Earl Mansin.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 108987401),
@@ -1779,7 +1802,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("eliminationbyimprovisation", "Stu2.exe", "9cf51833e787cc919837d9a8bd8fc14c", 971446),
 	ENGLISH_ENTRY("emeraldeyes", "Emerald.exe", "f120690b506dd63cd7d1112ea6af2f77", 2849945),
 	ENGLISH_ENTRY("emilyenough", "EE.exe", "97020973a2a635fe28eb0ba4bdfaa70b", 3141963),
-	ENGLISH_ENTRY("emmarodedemo", "Emma Roide.exe", "aefd91a131817036d224fe030e406c6e", 24919443),
 	ENGLISH_ENTRY("emptymindblankfate", "EMBF.exe", "18b284c22010850f79bc5c20054a70c4", 75732051),
 	ENGLISH_ENTRY("enoworld", "Enoworld.exe", "465f972675db2da6040518221af5b0ba", 16151170),
 	ENGLISH_ENTRY("enterthestory", "Enter The Story.exe", "0514661a4ba6772cf0db0cf839fc7003", 19589742),
@@ -1820,15 +1842,12 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("fightgame", "Fight Game.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 3551992),
 	ENGLISH_ENTRY("fireflystory3d", "FFS 3D.exe", "27343924ddad3be0b97bdcaa71858b1b", 2254453),
 	ENGLISH_ENTRY("flamebarrel", "Flame barrel.exe", "06a03fe35791b0578068ab1873455463", 2298745),
-	ENGLISH_ENTRY("flashbax", "demo Flashbax.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 5527034),
 	ENGLISH_ENTRY("flowergirl", "flowergirl.exe", "9cb3c8dc7a8ab9c44815955696be2677", 62544543),
 	ENGLISH_ENTRY("fluxworld", "FluxWorld.exe", "06a03fe35791b0578068ab1873455463", 5614789),
-	ENGLISH_ENTRY("forcemajeureiithezone", "TheZoneDemo.exe", "b63d26c17bf292017f9a708ae9dc38ca", 18414473),
 	ENGLISH_ENTRY("forfrogssakegetthefrogout", "Frog2.exe", "0241777c2537fc5d077c05cde10bfa9f", 6723366),
 	ENGLISH_ENTRY("forgettendeath", "ForgettenDeath.exe", "06a03fe35791b0578068ab1873455463", 19427130),
 	ENGLISH_ENTRY("fortressofwonders", "Fortress.exe", "465f972675db2da6040518221af5b0ba", 4474304),
 	ENGLISH_ENTRY("fountainofunicorns", "pmvi.exe", "465f972675db2da6040518221af5b0ba", 3038012),
-	ENGLISH_ENTRY("fountainofyouthdemo", "foydemo.exe", "f120690b506dd63cd7d1112ea6af2f77", 14372003),
 	ENGLISH_ENTRY("framed", "Jhum.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 4572587),
 	ENGLISH_ENTRY("frankenpooper", "frankenpooper.exe", "fb3b0f6bad923958d9d9198daea125e6", 24372899),
 	ENGLISH_ENTRY("frankthefarmhandpart1", "Frank.exe", "0006c0a95a5f35ca0d275adecf9dfa1d", 22602166),
@@ -1848,11 +1867,9 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("funwithnumbers", "fwn.exe", "a524cbb1c51589903c4043b98917f1d9", 18743833),
 	ENGLISH_ENTRY("gabyking", "GabyKing.exe", "1fd15cc387812c04447d89729b24b097", 2289131),
 	ENGLISH_ENTRY("gamesgalore", "gamesgalore.exe", "f120690b506dd63cd7d1112ea6af2f77", 7620552),
-	ENGLISH_ENTRY("gassesuittollis3demo", "Gst3_demo.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 4270243),
 	ENGLISH_ENTRY("gatewayremake", "Gateway Remake.exe", "0241777c2537fc5d077c05cde10bfa9f", 210991212),
 	ENGLISH_ENTRY("genbu", "Genbu.exe", "64fcaf7da0b257ea831f89c54be0ad72", 1892238),
 	ENGLISH_ENTRY("geometricshapes1circleboy", "Circle1.exe", "06a03fe35791b0578068ab1873455463", 2389129),
-	ENGLISH_ENTRY("gesundheitdemo", "gesundheit.exe", "5554b9e0df6241d25c9a070708e54478", 49666357),
 	ENGLISH_ENTRY("getawayfrompluto", "Get away.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 755529),
 	ENGLISH_ENTRY("getfood", "getfood.exe", "495d45fb8adfd49690ae3b97921feec6", 10600153),
 	ENGLISH_ENTRY("ghostdream", "Ghostdream.exe", "05594881531d62e4575545f3c8fd2576", 225600520),
@@ -1900,7 +1917,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("hiddenplains", "eureka02.exe", "6afafd26476d17a5e2a8e41f690d3720", 384360829),
 	ENGLISH_ENTRY("hiddentreasureryansfortune", "HiddenTRF.exe", "504df40bf50a0859e3dc15b000dab5f6", 7345149),
 	ENGLISH_ENTRY("hide", "Hide.exe", "6e861b1f476ff7cdf036082abb271329", 13701886),
-	ENGLISH_ENTRY("hiliaderoleagainsthell", "Dark Trial demo.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 36442694),
 	ENGLISH_ENTRY("him", "twin.exe", "6b4ceb9e327ac99479c08d825461f4cb", 23721672),
 	ENGLISH_ENTRY("hitchhikersguidetothegalaxyremake", "HHGTG.exe", "e003041f4332f136920e636e39d3e127", 34956191),
 	ENGLISH_ENTRY("hitthefreak", "HTF.EXE", "f3a13b2d6c2e0fe04c6f466062920e23", 3103477),
@@ -1926,7 +1942,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("imnotcrazyrightthecell", "I'm not crazy.exe", "9cb3c8dc7a8ab9c44815955696be2677", 3152216),
 	ENGLISH_ENTRY("imnotcrazyrightthewell", "The Well.exe", "9cb3c8dc7a8ab9c44815955696be2677", 5000358),
 	ENGLISH_ENTRY("indianajonescomingofage", "IndyCOA.exe", "90413e9ae57e222f8913b09d2bc847bc", 2368083),
-	ENGLISH_ENTRY("indycositalianver", "CoSdemo2.1-it.exe", "f120690b506dd63cd7d1112ea6af2f77", 5772985),
 	ENGLISH_ENTRY("infectionepii", "Infection_Ep_II_AGS.exe", "a524cbb1c51589903c4043b98917f1d9", 23691417),
 	ENGLISH_ENTRY("infectionitheship", "Infection I.exe", "7132ff7d6b0bc1e9f3e4bd4755390626", 25974295),
 	ENGLISH_ENTRY("inferno", "inf.exe", "97d700529f5cc826f230c27acf81adfd", 8783105),
@@ -1949,7 +1964,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("jamesbond", "platform2.exe", "949f7440e3692b7366c2029979dee9a0", 4467701),
 	ENGLISH_ENTRY("jamesinneverland", "JamesNeverland.exe", "06a03fe35791b0578068ab1873455463", 36488607),
 	ENGLISH_ENTRY("jamesperis", "James1.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 85631684),
-	ENGLISH_ENTRY("jamesperis2demo", "James2.exe", "06a03fe35791b0578068ab1873455463", 35766505),
 	ENGLISH_ENTRY("javelincatch", "JvlnCtch.exe", "3421b46ff95c5885603086c39a038a20", 1626263),
 	ENGLISH_ENTRY("jimmsquestiii", "JQ3.EXE", "0b7529a76f38283d6e850b8d56526fc1", 4930906),
 	ENGLISH_ENTRY("jimmysday", "jimmy.exe", "089fab88e6e1075a2f5b271f6f5b3c57", 13419394),
@@ -1962,7 +1976,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("johnnyrocket", "Rocket.exe", "a524cbb1c51589903c4043b98917f1d9", 10366294),
 	ENGLISH_ENTRY("johnsinclairvoodooinlondon", "John Sinclair - Voodoo in London.exe", "d72e72697a755c7de395b0f6c8cbbf0d", 56795991),
 	ENGLISH_ENTRY("jonnysmallvalley", "Jonny Smallvalley.exe", "01d0e6bd812abaa307bcb10fc2193416", 34437869),
-	ENGLISH_ENTRY("jorry", "JORRY DEMO.exe", "fe5f7dc7785b335aec72a2a834629bad", 124667001),
 	ENGLISH_ENTRY("juliusdangerous2", "Julius Dangerous 2.exe", "e2d4a98de69b1f8e6462c387710a441a", 146931732),
 	ENGLISH_ENTRY("juliusdangerousandthespaceinvaders", "Julius Dangerous.exe", "ddaf3807f1fe16b2813ff832b4fb471a", 83137140),
 	ENGLISH_ENTRY("justanotherpointnclickadventure", "Advent.exe", "6a98b4cc2f5a55421248be53f15a6a99", 9582620),
@@ -1977,7 +1990,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("killthelights", "Kill The Lights.exe", "9b54ea3557373188d8388ec4d1ae5eed", 20416736),
 	ENGLISH_ENTRY("kingdomlegends", "Kingdom Legends.exe", "06a03fe35791b0578068ab1873455463", 2254139),
 	ENGLISH_ENTRY("kingsquestiii", "KQ3.exe", "f120690b506dd63cd7d1112ea6af2f77", 5883843),
-	ENGLISH_ENTRY("kinkyislanddemo", "KINKY.exe", "f120690b506dd63cd7d1112ea6af2f77", 10628479),
 	ENGLISH_ENTRY("knightquestforgoldenring", "KQuestGoldRing.exe", "f120690b506dd63cd7d1112ea6af2f77", 2582542),
 	ENGLISH_ENTRY("knightsquestiii", "KQ3TOM.exe", "0710e2ec71042617f565c01824f0cf3c", 8408641),
 	ENGLISH_ENTRY("knightsquestiv", "MAGSQuest.exe", "0500aacb6c176d47ac0f8158f055db83", 4074151),
@@ -2001,7 +2013,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("laundryday", "Laundry Day.exe", "06a03fe35791b0578068ab1873455463", 2456888),
 	ENGLISH_ENTRY("lavablava", "Rumble.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 2294674),
 	ENGLISH_ENTRY("lazaruswantspants", "pants.exe", "9cf51833e787cc919837d9a8bd8fc14c", 1311852),
-	ENGLISH_ENTRY("lazytownthenewkiddemo", "newkiddemo1.2.exe", "9cb3c8dc7a8ab9c44815955696be2677", 15515508),
 	ENGLISH_ENTRY("lbstoryofcedrickdusce", "lifeboat.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 3563681),
 	ENGLISH_ENTRY("legendofrovendale", "Vampire.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 10018497),
 	ENGLISH_ENTRY("legendofseththebard", "LOSTB 1.48.exe", "a524cbb1c51589903c4043b98917f1d9", 10669482),
@@ -2021,7 +2032,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("likeafox", "likeafox.exe", "c7916b82f00c94013a3f7706b4d333c6", 2707737),
 	ENGLISH_ENTRY("limbo", "Limbo Adventure.exe", "7c10efb8990fb48ded51fbcd88a6bf17", 30800724),
 	ENGLISH_ENTRY("limeylizardwastewizard", "LLWW.exe", "fab982fd31570655ac3b1858bd8265e4", 33755872),
-	ENGLISH_ENTRY("litnunforgettablememories", "litn_umtechdemo.exe", "f120690b506dd63cd7d1112ea6af2f77", 3507831),
 	ENGLISH_ENTRY("littlegirlinunderland", "Underland.exe", "06a03fe35791b0578068ab1873455463", 10125940),
 	ENGLISH_ENTRY("livingnightmaredeluxe", "Living Nightmare.exe", "4415d633ea1a2dcd03ff0eff43f182ee", 9997554),
 	ENGLISH_ENTRY("livingnightmareendlessdream", "LNED.exe", "4415d633ea1a2dcd03ff0eff43f182ee", 10671309),
@@ -2082,7 +2092,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("meta", "META.exe", "06a03fe35791b0578068ab1873455463", 10113135),
 	ENGLISH_ENTRY("meteorfamily20", "Meteor Family.exe", "06a03fe35791b0578068ab1873455463", 5759077),
 	ENGLISH_ENTRY("meteorheadrecycled", "Meteorhead.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 5081311),
-	ENGLISH_ENTRY("mi5thereturnoflechuck", "Demo.exe", "0500aacb6c176d47ac0f8158f055db83", 6235270),
 	ENGLISH_ENTRY("mibaddaytobedead", "Monkey.exe", "f120690b506dd63cd7d1112ea6af2f77", 2117238),
 	ENGLISH_ENTRY("micarnivalofthedamned", "MI-COD.exe", "90413e9ae57e222f8913b09d2bc847bc", 5114086),
 	ENGLISH_ENTRY("mickeymauserpart1", "MM.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 12076323),
@@ -2131,7 +2140,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("nekusnewtrip", "nnt.exe", "c0c1865c3c8369e034095a725ca1ddbf", 35012412),
 	ENGLISH_ENTRY("nekusnewtrip", "square enix.exe", "a524cbb1c51589903c4043b98917f1d9", 10630694),
 	ENGLISH_ENTRY("nellycootalotv15", "Nelly Cootalot.exe", "18b284c22010850f79bc5c20054a70c4", 108256323),
-	ENGLISH_ENTRY("neofeud", "Neofeud Demo.exe", "6e861b1f476ff7cdf036082abb271329", 1886913453),
 	ENGLISH_ENTRY("nesquest", "NES Quest.exe", "8b72036706da98095057df615d07460b", 20881972),
 	ENGLISH_ENTRY("news", "WI-AA.exe", "06a03fe35791b0578068ab1873455463", 29631312),
 	ENGLISH_ENTRY("nickitandrun", "NIAREnglish.exe", "b25674056fe8cc0b7bf0a4409c5c5bfc", 14180082),
@@ -2238,16 +2246,13 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("proxecto", "proxec.exe", "465f972675db2da6040518221af5b0ba", 2636209),
 	ENGLISH_ENTRY("psychopomp", "psychopomp.exe", "b142b43c146c25443a1d155d441a6a81", 23721476),
 	ENGLISH_ENTRY("pubmasterquest2", "shogin crystal.exe", "90baefd2f369cebe25f3aa9ad90332d2", 35191110),
-	ENGLISH_ENTRY("pubmastersquest", "Pub Master Quest [Demo].exe", "e1676318c8a040fcf508b817013dc8fe", 23431689),
 	ENGLISH_ENTRY("puddypenguin", "Penguin.exe", "f3a13b2d6c2e0fe04c6f466062920e23", 2328158),
 	ENGLISH_ENTRY("pupupupulaisenseikkailut", "Game.exe", "23a67b6de10ec35e9f5a4dfc7d928222", 13431315),
 	ENGLISH_ENTRY("pupupupulaisenseikkailut", "Pupupeli.exe", "23a67b6de10ec35e9f5a4dfc7d928222", 13453697),
 	ENGLISH_ENTRY("purgatorio01", "Purgatorio 0.1.exe", "18b284c22010850f79bc5c20054a70c4", 194293367),
 	ENGLISH_ENTRY("purityofthesurf", "Surf.exe", "71ca0d6c1c699595f28a2125948d4a84", 11315703),
-	ENGLISH_ENTRY("puzzlebotsdemo", "Puzzlebots_Demo.exe", "34b49df9cf6eadb5c3587b3921d5b72f", 354138961),
 	ENGLISH_ENTRY("pxenophobe", "ProjXeno.exe", "465f972675db2da6040518221af5b0ba", 79053486),
 	ENGLISH_ENTRY("qfi", "qfi.exe", "0702df6e67ef87fd3c51d09303803126", 534847265), // GOG
-	ENGLISH_ENTRY("quantumnauts", "QNDEMO.exe", "aeb2dd29e5ff839cb3ee86cf3e87e3ca", 134237367),
 	ENGLISH_ENTRY("questfighter", "Quest Fighter.exe", "21fd0f65dfa48de2b39cb8ec23b30889", 2914128),
 	ENGLISH_ENTRY("questfighterii", "Quest Fighter 2.exe", "4d7d2addcde045dae6e0363a43f9acad", 5219511),
 	ENGLISH_ENTRY("questforcinema", "Questforcinema.exe", "465f972675db2da6040518221af5b0ba", 2670632),
@@ -2341,7 +2346,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("shem", "Shem.exe", "0710e2ec71042617f565c01824f0cf3c", 8866401),
 	ENGLISH_ENTRY("sherlock", "Sherlock.exe", "615e73fc1874e92d60a1996c2330ea36", 19108029),
 	ENGLISH_ENTRY("shiftersboxoutsidein", "Box.exe", "fc17e9b3ab53f6b4841e2a4af5c782ff", 24471804),
-	ENGLISH_ENTRY("shivahdemo", "shivahDemo.exe", "6e3d6225dee662ff6450a3bfa942773b", 20897850),
 	ENGLISH_ENTRY("shoot", "Shoot.exe", "1275885401b7d2ece491e704535707d9", 4327626),
 	ENGLISH_ENTRY("shootmyvalentine", "Valentine.exe", "06a03fe35791b0578068ab1873455463", 2859760),
 	ENGLISH_ENTRY("shortcut", "ShortCut.exe", "95b7dd55f6e15c8a2118856ed9fe8ff9", 4415830),
@@ -2350,7 +2354,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("sierraquest1", "SierraQuest1.exe", "465f972675db2da6040518221af5b0ba", 1275381),
 	ENGLISH_ENTRY("silentknightii", "SilentKnight2.exe", "465f972675db2da6040518221af5b0ba", 39941166),
 	ENGLISH_ENTRY("silentknightv11", "Silent Knight.exe", "465f972675db2da6040518221af5b0ba", 47414163),
-	ENGLISH_ENTRY("simonthesorcerer3demo20", "Simon3.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 8189928),
 	ENGLISH_ENTRY("skippysavestheday", "First Game Test.exe", "06a03fe35791b0578068ab1873455463", 10473902),
 	ENGLISH_ENTRY("slaythedragon", "dragon.exe", "3c5bd1713959ff469cb46ebe5542cfcf", 2917672),
 	ENGLISH_ENTRY("sleepyisland", "Sleepy Island.exe", "465f972675db2da6040518221af5b0ba", 20270790),
@@ -2375,9 +2378,7 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("spacelynxes", "SpaceLynxes.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 6593042),
 	ENGLISH_ENTRY("spacepirates", "Space Pirates.exe", "95dcf736be87cf7d40bf64d5b078c4b7", 3006210),
 	ENGLISH_ENTRY("spacepoolalpha", "SpacePool.exe", "ef1d6fdc83c91a1a8de9eaf2630737b7", 3055777),
-	ENGLISH_ENTRY("spacequest3vgapreview", "SQ3VGADEMO.exe", "64fcaf7da0b257ea831f89c54be0ad72", 3630019),
 	ENGLISH_ENTRY("spacequest45", "SQ4,5.exe", "5cd8db602cedc8f04cd3ca290a4a2693", 6886082),
-	ENGLISH_ENTRY("spacequest55demoags", "SQ5.5.exe", "465f972675db2da6040518221af5b0ba", 16342443),
 	ENGLISH_ENTRY("spacerangers", "SpaceRangersEp46.exe", "4f6c7ec127e8b0ce077abb357903612f", 41103057),
 	ENGLISH_ENTRY("spacerangersep52", "SpaceRangers52Grisli.exe", "4f6c7ec127e8b0ce077abb357903612f", 208346458),
 	ENGLISH_ENTRY("spacewar", "Spacewar.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 2270669),
@@ -2397,7 +2398,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("sqmania1", "SQMania1.exe", "465f972675db2da6040518221af5b0ba", 831674),
 	ENGLISH_ENTRY("sqmania2remakeeng", "SQM2 RMK.exe", "465f972675db2da6040518221af5b0ba", 3029288),
 	ENGLISH_ENTRY("sqmaniaep5", "SQ Mania Ep5.exe", "a524cbb1c51589903c4043b98917f1d9", 2896204),
-	ENGLISH_ENTRY("sram2cinomehsrevengedemo", "SRAM2.exe", "e3a33d139d90f2e695292a618753b8a5", 296499943),
 	ENGLISH_ENTRY("stablepeteandthejoust", "StablePete.exe", "b142b43c146c25443a1d155d441a6a81", 30046740),
 	ENGLISH_ENTRY("stablepeteandthejoust", "StablePete.exe", "b142b43c146c25443a1d155d441a6a81", 30048075),
 	ENGLISH_ENTRY("stairquest", "Stair Quest.exe", "e0aeab6a2c479fde167c4c43c3abb8ca", 4550699),
@@ -2417,7 +2417,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("strangerthings", "StrangerThings.exe", "cc19db728abbcf657db6b76afb0e92d1", 43636017),
 	ENGLISH_ENTRY("supaevil", "SupaEvil.exe", "0710e2ec71042617f565c01824f0cf3c", 7602318),
 	ENGLISH_ENTRY("supergirl", "Supergirl.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 12108982),
-	ENGLISH_ENTRY("superjazzmandemo", "SJMdemo.exe", "0710e2ec71042617f565c01824f0cf3c", 5214882),
 	ENGLISH_ENTRY("superracing", "Super Racing.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 3660473),
 	ENGLISH_ENTRY("surreality", "Surreality.exe", "3128b9f90e2f954ba704414ae854d10b", 10773443),
 	ENGLISH_ENTRY("sweed", "SWeed.exe", "be65afc1ea59889c05e4e4cc143b3dbc", 2171942),
@@ -2534,8 +2533,7 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("threeguyswalkintoheaven", "Three Guys Walk Into Heaven.exe", "c45653d1c856f002ceb59a5b865ab187", 2896291),
 	ENGLISH_ENTRY("tilepuzzlegame", "Puzzle01.exe", "615e73fc1874e92d60a1996c2330ea36", 2819964),
 	ENGLISH_ENTRY("tiltor", "Tiltor.exe", "f120690b506dd63cd7d1112ea6af2f77", 17561878),
-	ENGLISH_ENTRY("timegentlemenpleasedemo", "TGP.exe", "86a5359bac7c88f0dfa060478800dd61", 29686006),
-	ENGLISH_ENTRY("timequest", "gam.exe", "465f972675db2da6040518221af5b0ba", 5669007),
+	ENGLISH_ENTRY("timequest1", "gam.exe", "465f972675db2da6040518221af5b0ba", 5669007),
 	ENGLISH_ENTRY("timequest2", "TimeQ2.exe", "465f972675db2da6040518221af5b0ba", 5838823),
 	ENGLISH_ENTRY("timesinkofchronos", "Timesink.exe", "2bc8f994a7d1e05ed45f35abf2128231", 127528679),
 	ENGLISH_ENTRY("timothylande", "Timothy Lande.exe", "0500aacb6c176d47ac0f8158f055db83", 13874628),
@@ -2615,7 +2613,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("yoda", "Yoda.exe", "a01a9639ce30bdcd5bf82e528b51fa06", 2461339),
 	ENGLISH_ENTRY("yourlate", "Your late.exe", "02635a77ab660023f59519c91329f7f5", 2719997),
 	ENGLISH_ENTRY("zakmckracken", "Zak2.exe", "e88fd6a23a5e498d7b0d50e3bb914085", 8686711),
-	ENGLISH_ENTRY("zombieattackdemo", "ZADemo.exe", "82da2565c456dcfb265ded6fe3189c0b", 20958555),
 	ENGLISH_ENTRY("zombiefish", "FZombie.exe", "3128b9f90e2f954ba704414ae854d10b", 4220305),
 	ENGLISH_ENTRY("zooreal", "zoo_real.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 24184795),
 	ENGLISH_ENTRY("zugzwang", "Zugzwang.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 17209702),


Commit: 46fdf3bf50f94eed710b3add74c68eea3b84aa47
    https://github.com/scummvm/scummvm/commit/46fdf3bf50f94eed710b3add74c68eea3b84aa47
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Savegame screenshots now exclude in-game save dialogs

Changed paths:
    engines/ags/ags.cpp
    engines/ags/engine/ac/game.cpp


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index a294f47614..d1d707a941 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -390,11 +390,13 @@ void AGSEngine::setGraphicsMode(size_t w, size_t h) {
 }
 
 bool AGSEngine::canLoadGameStateCurrently() {
-	return !::AGS3::thisroom.Options.SaveLoadDisabled && !::AGS3::inside_script;
+	return !::AGS3::thisroom.Options.SaveLoadDisabled &&
+		!::AGS3::inside_script && !AGS3::play.fast_forward;
 }
 
 bool AGSEngine::canSaveGameStateCurrently() {
-	return !::AGS3::thisroom.Options.SaveLoadDisabled && !::AGS3::inside_script;
+	return !::AGS3::thisroom.Options.SaveLoadDisabled &&
+		!::AGS3::inside_script && !AGS3::play.fast_forward;
 }
 
 Common::Error AGSEngine::loadGameState(int slot) {
diff --git a/engines/ags/engine/ac/game.cpp b/engines/ags/engine/ac/game.cpp
index af2bf4e48b..f3aa47e3ab 100644
--- a/engines/ags/engine/ac/game.cpp
+++ b/engines/ags/engine/ac/game.cpp
@@ -70,6 +70,7 @@
 #include "ags/engine/ac/dynobj/cc_audioclip.h"
 #include "ags/engine/ac/dynobj/scriptcamera.h"
 #include "ags/engine/debugging/debug_log.h"
+#include "ags/engine/debugging/debugger.h"
 #include "ags/shared/debugging/out.h"
 #include "ags/engine/device/mousew32.h"
 #include "ags/shared/font/fonts.h"
@@ -1020,6 +1021,11 @@ void create_savegame_screenshot(Bitmap *&screenShot) {
 	// WORKAROUND: AGS originally only creates savegames if the game flags
 	// that it supports it. But we want it all the time for ScummVM GMM
 	if (/*game.options[OPT_SAVESCREENSHOT] */true) {
+		// Render the view without any UI elements
+		int old_flags = debug_flags;
+		debug_flags |= DBG_NOIFACE;
+		construct_game_scene(true);
+
 		int usewid = data_to_game_coord(play.screenshot_width);
 		int usehit = data_to_game_coord(play.screenshot_height);
 		const Rect &viewport = play.GetMainViewport();
@@ -1032,6 +1038,10 @@ void create_savegame_screenshot(Bitmap *&screenShot) {
 			quit("!Invalid game.screenshot_width/height, must be from 16x16 to screen res");
 
 		screenShot = CopyScreenIntoBitmap(usewid, usehit);
+
+		// Restore original screen
+		debug_flags = old_flags;
+		construct_game_scene(true);
 	}
 }
 


Commit: 5e8e40ddc604999b07facec5870274635925365b
    https://github.com/scummvm/scummvm/commit/5e8e40ddc604999b07facec5870274635925365b
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Cleanup of qfg2 vga detection entries

Changed paths:
    engines/ags/detection_tables.h


diff --git a/engines/ags/detection_tables.h b/engines/ags/detection_tables.h
index 2a35af767f..83ebaf7b11 100644
--- a/engines/ags/detection_tables.h
+++ b/engines/ags/detection_tables.h
@@ -1436,6 +1436,7 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("kq3agdi", "kq3redux.exe", "e569fb2ceabdc4a1609348c23ebc0821", 11986266),  // 1.1
 	ENGLISH_ENTRY("qfg2agdi", "qfg2vga.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 20470902),
 	ENGLISH_ENTRY("qfg2agdi", "qfg2vga.exe", "582e26533cf784011c7565e89905d3c4", 18224373),
+	ENGLISH_ENTRY("qfg2agdi", "Game.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 5408433),
 
 	// Comercial games
 	ENGLISH_ENTRY("blackwell1", "blackwell1.exe", "605e124cb7e0b56841c471e2d641c224", 18822697), // GOG
@@ -2256,8 +2257,6 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("questfighter", "Quest Fighter.exe", "21fd0f65dfa48de2b39cb8ec23b30889", 2914128),
 	ENGLISH_ENTRY("questfighterii", "Quest Fighter 2.exe", "4d7d2addcde045dae6e0363a43f9acad", 5219511),
 	ENGLISH_ENTRY("questforcinema", "Questforcinema.exe", "465f972675db2da6040518221af5b0ba", 2670632),
-	ENGLISH_ENTRY("questforglory2vga", "Game.exe", "3b7cceb3e4bdb031dc5d8f290936e94b", 5408433),
-	ENGLISH_ENTRY("questforgloryii", "Qfg2vga.exe", "6cddccb3744ec5c6af7c398fb7b3b11c", 20523688),
 	ENGLISH_ENTRY("questforjesus", "QuestForJesus.exe", "495d45fb8adfd49690ae3b97921feec6", 3973088),
 	ENGLISH_ENTRY("questforpalette", "Palette Quest.exe", "0710e2ec71042617f565c01824f0cf3c", 754395),
 	ENGLISH_ENTRY("questforthebluecup", "Quest for the Cup.exe", "9cb3c8dc7a8ab9c44815955696be2677", 8760015),


Commit: 47b2538384b4a7a66f9214bbb4e4a0af9cd98499
    https://github.com/scummvm/scummvm/commit/47b2538384b4a7a66f9214bbb4e4a0af9cd98499
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Added AGS contributors to credits.pl

Changed paths:
    devtools/credits.pl


diff --git a/devtools/credits.pl b/devtools/credits.pl
index 880113f08a..6f348c7753 100755
--- a/devtools/credits.pl
+++ b/devtools/credits.pl
@@ -558,9 +558,48 @@ begin_credits("Credits");
 
 			begin_section("AGS");
 				add_person("Paul Gilbert", "dreammaster", "");
+				add_person("Thierry Crozat", "criezy", "");
+				add_person("Chris Jones", "Pumaman", "Creator");
+				add_person("Alan Van Drake", "", "AGS");
+				add_person("Benjamin Penney", "", "AGS");
+				add_person("Benoit Pierre", "", "AGS");
+				add_person("Bernhard Rosenkraenzer", "", "AGS");
+				add_person("Cristian Morales Vega", "", "AGS");
+				add_person("Edward Rudd", "", "AGS");
+				add_person("Erico Vieira Porto", "", "AGS");
+				add_person("Ferdinand Thiessen", "", "AGS");
+				add_person("Francesco Ariis", "", "AGS");
+				add_person("Gilad Shaham", "", "AGS");
+				add_person("Ivan Mogilko", "", "AGS");
+				add_person("Janet Gilbert", "", "AGS");
+				add_person("Jochen Schleu", "", "AGS");
+				add_person("Joe Lee", "", "AGS");
+				add_person("John Steele Scott", "", "AGS");
+				add_person("Martin Sedlak", "", "AGS");
+				add_person("Matthew Gambrell", "", "AGS");
+				add_person("Michael Rittenhouse", "", "AGS");
+				add_person("Morgan Willcock", "", "AGS");
+				add_person("Nick Sonneveld", "", "AGS");
+				add_person("Ori Avtalion", "", "AGS");
+				add_person("Paul Wilkinson", "", "AGS");
+				add_person("Per Olav Flaten", "", "AGS");
+				add_person("Piotr Wieczorek", "", "AGS");
+				add_person("Ryan O'Connor", "", "AGS");
+				add_person("Scott Baker", "", "AGS");
+				add_person("Shane Stevens", "", "AGS");
+				add_person("Shawn R. Walker", "", "AGS");
+				add_person("Stefano Collavini", "", "AGS");
+				add_person("Steve McCrea", "", "AGS");
+				add_person("Steven Poulton", "", "AGS");
+				add_person("Sunit Das", "", "AGS");
+				add_person("Tobias Hansen", "", "AGS");
+				add_person("Tom Vandepoele", "", "AGS");
+				add_person("Tzach Shabtay", "", "AGS");
+				add_person("", "rofl0r", "AGS");
 				add_person("", "AGA", "AgsCreditz");
 			end_section();
 
+
 			begin_section("Avalanche");
 				add_person("Peter Bozsó", "uruk", "");
 				add_person("Arnaud Boutonné", "Strangerke", "");


Commit: 88fbbbad64fc48e38709348cb6e8f2d0b1ca6386
    https://github.com/scummvm/scummvm/commit/88fbbbad64fc48e38709348cb6e8f2d0b1ca6386
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Minor detection table cleanups

Changed paths:
    engines/ags/detection_tables.h


diff --git a/engines/ags/detection_tables.h b/engines/ags/detection_tables.h
index 83ebaf7b11..10c16f54b5 100644
--- a/engines/ags/detection_tables.h
+++ b/engines/ags/detection_tables.h
@@ -112,7 +112,6 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "rodequest", "Rode Quest" },
 	{ "rollinfoy", "Rollinfoy" },
 	{ "samthepiratemonkey", "Sam The Pirate Monkey" },
-	{ "secondmoonadv1", "Second Moon Adventure Part 1 - Night" },
 	{ "slackerquest", "Slacker Quest" },
 	{ "snailquest1", "Snail Quest" },
 	{ "snailquest2", "Snail Quest 2" },
@@ -924,8 +923,6 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "questfighter", "Quest Fighter" },
 	{ "questfighterii", "Quest Fighter II" },
 	{ "questforcinema", "QuestForCinema" },
-	{ "questforglory2vga", "Quest For Glory 2 VGA" },
-	{ "questforgloryii", "Quest for Glory II" },
 	{ "questforjesus", "Quest for Jesus" },
 	{ "questforpalette", "Quest for Palette" },
 	{ "questforthebluecup", "Quest for the Blue Cup" },
@@ -1019,14 +1016,15 @@ const PlainGameDescriptor GAME_NAMES[] = {
 	{ "shrivel", "Shrivel" },
 	{ "shunday", "Shunday" },
 	{ "sierraquest1", "Sierra Quest 1" },
-	{ "silentknightii", "Silent Knight II" },
-	{ "silentknightv11", "Silent Knight v.1.1" },
+	{ "silentknight1", "Silent Knight" },
+	{ "silentknight2", "Silent Knight II" },
 	{ "simonthesorcerer3", "Simon the Sorcerer 3" },
 	{ "skippysavestheday", "Skippy Saves The Day" },
 	{ "slaythedragon", "Slay the Dragon" },
 	{ "sleepyisland", "Sleepy Island" },
 	{ "slimequestforpizza", "Slime-Quest for Pizza" },
 	{ "slugprincess", "SlugPrincess" },
+	{ "sma1", "Second Moon Adventure Part 1 - Night" },
 	{ "sma2", "Second Moon Adventure Part 2" },
 	{ "sma3", "Second Moon Adventure Part 3 - Rest In Peace" },
 	{ "sma4", "Second Moon Adventure Part 4" },
@@ -1407,7 +1405,7 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	UNSUPPORTED_ENTRY("rodequest", "rodequest1.exe", "72f3c950b4d9d14580a11db885a63310", 1196458),
 	UNSUPPORTED_ENTRY("rollinfoy", "rollinfoy.exe", "19f4045333d9c823a5439d0447d55985", 3454107),
 	UNSUPPORTED_ENTRY("samthepiratemonkey", "monkey.exe", "73f87b30f84e9c34ab09ec8dd7ae109d", 1401414),
-	UNSUPPORTED_ENTRY("secondmoonadv1", "moonsdt.exe", "9027912819f3a319ed9de0fd855310c3", 1276725),
+	UNSUPPORTED_ENTRY("sma1", "moonsdt.exe", "9027912819f3a319ed9de0fd855310c3", 1276725),
 	UNSUPPORTED_ENTRY("slackerquest", "ac2game.dat", "e0998f2d2e14a55aae2291fdfab1ce7d", 1306492),
 	UNSUPPORTED_ENTRY("snailquest1", "snailquest.exe", "dd69243e3cc9e955215e0d556301b58e", 1095860),
 	UNSUPPORTED_ENTRY("snailquest2", "sq2.exe", "1bccd2edef19abc99e9683519d80c0e0", 955614),
@@ -2351,8 +2349,8 @@ const AGSGameDescription GAME_DESCRIPTIONS[] = {
 	ENGLISH_ENTRY("shrivel", "Shrivel.exe", "12c6a846b5ba9a5dde4a1b804b3e86e9", 58873190),
 	ENGLISH_ENTRY("shunday", "Shunday.exe", "82da2565c456dcfb265ded6fe3189c0b", 4937129),
 	ENGLISH_ENTRY("sierraquest1", "SierraQuest1.exe", "465f972675db2da6040518221af5b0ba", 1275381),
-	ENGLISH_ENTRY("silentknightii", "SilentKnight2.exe", "465f972675db2da6040518221af5b0ba", 39941166),
-	ENGLISH_ENTRY("silentknightv11", "Silent Knight.exe", "465f972675db2da6040518221af5b0ba", 47414163),
+	ENGLISH_ENTRY("silentknight1", "Silent Knight.exe", "465f972675db2da6040518221af5b0ba", 47414163),
+	ENGLISH_ENTRY("silentknight2", "SilentKnight2.exe", "465f972675db2da6040518221af5b0ba", 39941166),
 	ENGLISH_ENTRY("skippysavestheday", "First Game Test.exe", "06a03fe35791b0578068ab1873455463", 10473902),
 	ENGLISH_ENTRY("slaythedragon", "dragon.exe", "3c5bd1713959ff469cb46ebe5542cfcf", 2917672),
 	ENGLISH_ENTRY("sleepyisland", "Sleepy Island.exe", "465f972675db2da6040518221af5b0ba", 20270790),


Commit: 9c74ac0f97d91d52d4d6676c46111dae00b1ea64
    https://github.com/scummvm/scummvm/commit/9c74ac0f97d91d52d4d6676c46111dae00b1ea64
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Show md5 when AGS game found in fallbackDetect

Changed paths:
    engines/ags/detection.cpp
    engines/ags/detection.h


diff --git a/engines/ags/detection.cpp b/engines/ags/detection.cpp
index d1afbb2716..98e00590a6 100644
--- a/engines/ags/detection.cpp
+++ b/engines/ags/detection.cpp
@@ -22,6 +22,7 @@
 
 #include "base/plugins.h"
 #include "common/file.h"
+#include "common/md5.h"
 #include "ags/detection.h"
 #include "ags/detection_tables.h"
 
@@ -90,13 +91,21 @@ ADDetectedGame AGSMetaEngineDetection::fallbackDetect(const FileMap &allFiles, c
 
 		if (AGS3::isAGSFile(f)) {
 			_filename = filename;
+			f.seek(0);
+			_md5 = Common::computeStreamMD5AsString(f, 5000);
 
 			AGS::g_fallbackDesc.desc.gameId = _gameid.c_str();
 			AGS::g_fallbackDesc.desc.extra = _extra.c_str();
 			AGS::g_fallbackDesc.desc.filesDescriptions[0].fileName = _filename.c_str();
 			AGS::g_fallbackDesc.desc.filesDescriptions[0].fileSize = f.size();
+			AGS::g_fallbackDesc.desc.filesDescriptions[0].md5 = _md5.c_str();
 
-			return ADDetectedGame(&AGS::g_fallbackDesc.desc);
+			ADDetectedGame game(&AGS::g_fallbackDesc.desc);
+			game.matchedFiles[_filename].md5 = _md5;
+			game.matchedFiles[_filename].size = f.size();
+
+			game.hasUnknownFiles = true;
+			return game;
 		}
 	}
 
diff --git a/engines/ags/detection.h b/engines/ags/detection.h
index 892a758edf..6b8c759f9a 100644
--- a/engines/ags/detection.h
+++ b/engines/ags/detection.h
@@ -48,6 +48,7 @@ class AGSMetaEngineDetection : public AdvancedMetaEngineDetection {
 	mutable Common::String _gameid;
 	mutable Common::String _extra;
 	mutable Common::String _filename;
+	mutable Common::String _md5;
 
 public:
 	AGSMetaEngineDetection();


Commit: 211e5d7e90233425f2be2e8e4571928914605e52
    https://github.com/scummvm/scummvm/commit/211e5d7e90233425f2be2e8e4571928914605e52
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Further separate methods in  two AgsCreditz classes

Changed paths:
    engines/ags/plugins/ags_creditz/ags_creditz.cpp
    engines/ags/plugins/ags_creditz/ags_creditz.h


diff --git a/engines/ags/plugins/ags_creditz/ags_creditz.cpp b/engines/ags/plugins/ags_creditz/ags_creditz.cpp
index f88ea7ebf5..a840159af7 100644
--- a/engines/ags/plugins/ags_creditz/ags_creditz.cpp
+++ b/engines/ags/plugins/ags_creditz/ags_creditz.cpp
@@ -33,25 +33,33 @@ IAGSEngine *AGSCreditz::_engine;
 AGSCreditz::AGSCreditz() {
 	_state = new State();
 	_engine = nullptr;
-
-	DLL_METHOD(AGS_GetPluginName);
 }
 
 AGSCreditz::~AGSCreditz() {
 	delete _state;
 }
 
+/*------------------------------------------------------------------*/
+
+const char *IMAGE_TEXT = "*i*m*a*g*e*";
+
+AGSCreditz11::AGSCreditz11() : AGSCreditz() {
+	_version = VERSION_11;
+
+	DLL_METHOD(AGS_GetPluginName);
+	DLL_METHOD(AGS_EngineStartup);
+}
 
-const char *AGSCreditz::AGS_GetPluginName() {
-	if (_version == VERSION_11)
-		return "AGSCreditz v1.1 by AJA";
-	else
-		return "AGSCreditz 2.0 (by Dima Software: AJA)";
+const char *AGSCreditz11::AGS_GetPluginName() {
+	return "AGSCreditz v1.1 by AJA";
 }
 
-void AGSCreditz::AGS_EngineStartup(IAGSEngine *engine) {
+void AGSCreditz11::AGS_EngineStartup(IAGSEngine *engine) {
 	_engine = engine;
 
+	SCRIPT_METHOD(SetCredit);
+	SCRIPT_METHOD(ScrollCredits);
+	SCRIPT_METHOD(GetCredit);
 	SCRIPT_METHOD(IsCreditScrollingFinished);
 	SCRIPT_METHOD(SetCreditImage);
 	SCRIPT_METHOD(PauseScroll);
@@ -72,114 +80,187 @@ void AGSCreditz::AGS_EngineStartup(IAGSEngine *engine) {
 	SCRIPT_METHOD(IsStaticCreditsFinished);
 }
 
-int AGSCreditz::IsCreditScrollingFinished(const ScriptMethodParams &params) {
+void AGSCreditz11::SetCredit(const ScriptMethodParams &params) {
+	PARAMS7(int, ID, string, credit, int, colour, int, font, int, center, int, xpos, int, generateoutline);
+
+	if (ID >= (int)_state->_credits[0].size())
+		_state->_credits[0].resize(ID + 1);
+
+	Credit &c = _state->_credits[0][ID];
+	c._text = credit;
+	c._fontSlot = font;
+	c._center = center;
+	c._x = xpos;
+	c._isSet = true;
+	c._outline = generateoutline;
+	c._color = colour;
+}
+
+void AGSCreditz11::ScrollCredits(const ScriptMethodParams &params) {
+	PARAMS7(int, onoff, int, speed, int, fromY, int, toY, int, isautom, int, wait, int, resolution);
+
+	if (onoff == 1) {
+		_state->_creditsRunning = true;
+		_state->_seqSettings[0].speed = speed;
+		_state->_seqSettings[0].endwait = wait;
+		_state->_seqSettings[0].startpoint = fromY;
+		_state->_seqSettings[0].endpoint = toY;
+		_state->_seqSettings[0].automatic = isautom;
+
+		_engine->GetScreenDimensions(&_state->_screenWidth,
+			&_state->_screenHeight, &_state->_screenColorDepth);
+		if (_state->_screenWidth == 320) {
+			_state->_resolutionFlag = (resolution != 2) ? 1 : 0;
+		} else if (_state->_screenWidth == 640) {
+			_state->_resolutionFlag = (resolution != 1) ? 1 : 0;
+		}
+
+	} else if (onoff == 0) {
+		_state->_creditsRunning = false;
+
+	} else {
+		_engine->AbortGame("ScrollCredits: OnOff value must be 1 or 0!");
+	}
+}
+
+string AGSCreditz11::GetCredit(const ScriptMethodParams &params) {
+	PARAMS1(int, ID);
+
+	return (_state->_credits[0][ID]._text == IMAGE_TEXT) ?
+		"image" : _state->_credits[0][ID]._text.c_str();
+}
+
+int AGSCreditz11::IsCreditScrollingFinished(const ScriptMethodParams &params) {
 	return true;
 }
 
-void AGSCreditz::SetCreditImage(const ScriptMethodParams &params) {
+void AGSCreditz11::SetCreditImage(const ScriptMethodParams &params) {
 	//PARAMS5(int, ID, int, Slot, int, center, int, xpos, int, pixtonext);
 }
 
-void AGSCreditz::PauseScroll(const ScriptMethodParams &params) {
+void AGSCreditz11::PauseScroll(const ScriptMethodParams &params) {
 	//PARAMS1(int, onoff);
 }
 
-void AGSCreditz::ScrollReset(const ScriptMethodParams &params) {
+void AGSCreditz11::ScrollReset(const ScriptMethodParams &params) {
 }
 
-void AGSCreditz::SetEmptyLineHeight(const ScriptMethodParams &params) {
+void AGSCreditz11::SetEmptyLineHeight(const ScriptMethodParams &params) {
 	//PARAMS1(int, Height);
 }
 
-int AGSCreditz::GetEmptyLineHeight(const ScriptMethodParams &params) {
+int AGSCreditz11::GetEmptyLineHeight(const ScriptMethodParams &params) {
 	return 0;
 }
 
-void AGSCreditz::SetStaticCredit(const ScriptMethodParams &params) {
+void AGSCreditz11::SetStaticCredit(const ScriptMethodParams &params) {
 	//PARAMS8(int, ID, int, x, int, y, int, creditfont, int, creditcolour, int, centered, int, generateoutline, string, credit);
 
 }
 
-string AGSCreditz::GetStaticCredit(const ScriptMethodParams &params) {
+string AGSCreditz11::GetStaticCredit(const ScriptMethodParams &params) {
 	//PARAMS1(int, ID);
 	return nullptr;
 }
 
-void AGSCreditz::StartEndStaticCredits(const ScriptMethodParams &params) {
+void AGSCreditz11::StartEndStaticCredits(const ScriptMethodParams &params) {
 	//PARAMS2(int, onoff, int, res);
 }
 
-int AGSCreditz::GetCurrentStaticCredit(const ScriptMethodParams &params) {
+int AGSCreditz11::GetCurrentStaticCredit(const ScriptMethodParams &params) {
 	return 0;
 }
 
-void AGSCreditz::SetDefaultStaticDelay(const ScriptMethodParams &params) {
+void AGSCreditz11::SetDefaultStaticDelay(const ScriptMethodParams &params) {
 	//PARAMS1(int, Cyclesperchar);
 }
 
-void AGSCreditz::SetStaticPause(const ScriptMethodParams &params) {
+void AGSCreditz11::SetStaticPause(const ScriptMethodParams &params) {
 	//PARAMS2(int, ID, int, length);
 }
 
-void AGSCreditz::SetStaticCreditTitle(const ScriptMethodParams &params) {
+void AGSCreditz11::SetStaticCreditTitle(const ScriptMethodParams &params) {
 	//PARAMS8(int, ID, int, x, int, y, int, titlefont, int, titlecolour, int, centered, int, generateoutline, string, title);
 }
 
-void AGSCreditz::ShowStaticCredit(const ScriptMethodParams &params) {
+void AGSCreditz11::ShowStaticCredit(const ScriptMethodParams &params) {
 	//PARAMS6(int, ID, int, time, int, style, int, transtime, int, sound, int, resolution);
 }
 
-void AGSCreditz::StaticReset(const ScriptMethodParams &params) {
+void AGSCreditz11::StaticReset(const ScriptMethodParams &params) {
 }
 
-string AGSCreditz::GetStaticCreditTitle(const ScriptMethodParams &params) {
+string AGSCreditz11::GetStaticCreditTitle(const ScriptMethodParams &params) {
 	//PARAMS1(int, ID);
 	return nullptr;
 }
 
-void AGSCreditz::SetStaticCreditImage(const ScriptMethodParams &params) {
+void AGSCreditz11::SetStaticCreditImage(const ScriptMethodParams &params) {
 //int ID, int x, int y, int Slot, int Hcentered, int Vcentered, int time) {
 }
 
-int AGSCreditz::IsStaticCreditsFinished(const ScriptMethodParams &params) {
+int AGSCreditz11::IsStaticCreditsFinished(const ScriptMethodParams &params) {
 	return true;
 }
 
 /*------------------------------------------------------------------*/
 
-const char *IMAGE_TEXT = "*i*m*a*g*e*";
-
-AGSCreditz11::AGSCreditz11() {
-	_version = VERSION_11;
+AGSCreditz20::AGSCreditz20() : AGSCreditz() {
+	_version = VERSION_20;
 
+	DLL_METHOD(AGS_GetPluginName);
 	DLL_METHOD(AGS_EngineStartup);
 }
 
-void AGSCreditz11::AGS_EngineStartup(IAGSEngine *engine) {
-	AGSCreditz::AGS_EngineStartup(engine);
+const char *AGSCreditz20::AGS_GetPluginName() {
+	return "AGSCreditz v1.1 by AJA";
+}
+
+void AGSCreditz20::AGS_EngineStartup(IAGSEngine *engine) {
+	_engine = engine;
 
 	SCRIPT_METHOD(SetCredit);
 	SCRIPT_METHOD(ScrollCredits);
 	SCRIPT_METHOD(GetCredit);
+	SCRIPT_METHOD(IsCreditScrollingFinished);
+	SCRIPT_METHOD(SetCreditImage);
+	SCRIPT_METHOD(PauseScroll);
+	SCRIPT_METHOD(ScrollReset);
+	SCRIPT_METHOD(SetEmptyLineHeight);
+	SCRIPT_METHOD(GetEmptyLineHeight);
+	SCRIPT_METHOD(SetStaticCredit);
+	SCRIPT_METHOD(GetStaticCredit);
+	SCRIPT_METHOD(StartEndStaticCredits);
+	SCRIPT_METHOD(GetCurrentStaticCredit);
+	SCRIPT_METHOD(SetDefaultStaticDelay);
+	SCRIPT_METHOD(SetStaticPause);
+	SCRIPT_METHOD(SetStaticCreditTitle);
+	SCRIPT_METHOD(ShowStaticCredit);
+	SCRIPT_METHOD(StaticReset);
+	SCRIPT_METHOD(GetStaticCreditTitle);
+	SCRIPT_METHOD(SetStaticCreditImage);
+	SCRIPT_METHOD(IsStaticCreditsFinished);
 }
 
-void AGSCreditz11::SetCredit(const ScriptMethodParams &params) {
-	PARAMS7(int, ID, string, credit, int, colour, int, font, int, center, int, xpos, int, generateoutline);
+void AGSCreditz20::SetCredit(const ScriptMethodParams &params) {
+	PARAMS7(int, sequence, int, line, string, credit, int, x_pos, int, font, int, color, int, gen_outline);
 
-	if (ID >= (int)_state->_credits[0].size())
-		_state->_credits[0].resize(ID + 1);
+	assert(sequence >= 0 && sequence <= 10);
+	if (line >= (int)_state->_credits[sequence].size())
+		_state->_credits[sequence].resize(line + 1);
 
-	Credit &c = _state->_credits[0][ID];
+	Credit &c = _state->_credits[sequence][line];
 	c._text = credit;
 	c._fontSlot = font;
-	c._center = center;
-	c._x = xpos;
+	c._color = color;
+	c._x = x_pos;
 	c._isSet = true;
-	c._outline = generateoutline;
-	c._color = colour;
+	if (gen_outline > 0)
+		c._outline = true;
 }
 
-void AGSCreditz11::ScrollCredits(const ScriptMethodParams &params) {
+
+void AGSCreditz20::ScrollCredits(const ScriptMethodParams &params) {
 	PARAMS7(int, onoff, int, speed, int, fromY, int, toY, int, isautom, int, wait, int, resolution);
 
 	if (onoff == 1) {
@@ -206,42 +287,84 @@ void AGSCreditz11::ScrollCredits(const ScriptMethodParams &params) {
 	}
 }
 
-string AGSCreditz11::GetCredit(const ScriptMethodParams &params) {
+string AGSCreditz20::GetCredit(const ScriptMethodParams &params) {
 	PARAMS1(int, ID);
 
 	return (_state->_credits[0][ID]._text == IMAGE_TEXT) ?
 		"image" : _state->_credits[0][ID]._text.c_str();
 }
 
-/*------------------------------------------------------------------*/
+int AGSCreditz20::IsCreditScrollingFinished(const ScriptMethodParams &params) {
+	return true;
+}
 
-AGSCreditz20::AGSCreditz20() {
-	_version = VERSION_20;
+void AGSCreditz20::SetCreditImage(const ScriptMethodParams &params) {
+	//PARAMS5(int, ID, int, Slot, int, center, int, xpos, int, pixtonext);
+}
 
-	DLL_METHOD(AGS_EngineStartup);
+void AGSCreditz20::PauseScroll(const ScriptMethodParams &params) {
+	//PARAMS1(int, onoff);
 }
 
-void AGSCreditz20::AGS_EngineStartup(IAGSEngine *engine) {
-	AGSCreditz::AGS_EngineStartup(engine);
+void AGSCreditz20::ScrollReset(const ScriptMethodParams &params) {
+}
 
-	SCRIPT_METHOD(SetCredit);
+void AGSCreditz20::SetEmptyLineHeight(const ScriptMethodParams &params) {
+	//PARAMS1(int, Height);
 }
 
-void AGSCreditz20::SetCredit(const ScriptMethodParams &params) {
-	PARAMS7(int, sequence, int, line, string, credit, int, x_pos, int, font, int, color, int, gen_outline);
+int AGSCreditz20::GetEmptyLineHeight(const ScriptMethodParams &params) {
+	return 0;
+}
 
-	assert(sequence >= 0 && sequence <= 10);
-	if (line >= (int)_state->_credits[sequence].size())
-		_state->_credits[sequence].resize(line + 1);
+void AGSCreditz20::SetStaticCredit(const ScriptMethodParams &params) {
+	//PARAMS8(int, ID, int, x, int, y, int, creditfont, int, creditcolour, int, centered, int, generateoutline, string, credit);
 
-	Credit &c = _state->_credits[sequence][line];
-	c._text = credit;
-	c._fontSlot = font;
-	c._color = color;
-	c._x = x_pos;
-	c._isSet = true;
-	if (gen_outline > 0)
-		c._outline = true;
+}
+
+string AGSCreditz20::GetStaticCredit(const ScriptMethodParams &params) {
+	//PARAMS1(int, ID);
+	return nullptr;
+}
+
+void AGSCreditz20::StartEndStaticCredits(const ScriptMethodParams &params) {
+	//PARAMS2(int, onoff, int, res);
+}
+
+int AGSCreditz20::GetCurrentStaticCredit(const ScriptMethodParams &params) {
+	return 0;
+}
+
+void AGSCreditz20::SetDefaultStaticDelay(const ScriptMethodParams &params) {
+	//PARAMS1(int, Cyclesperchar);
+}
+
+void AGSCreditz20::SetStaticPause(const ScriptMethodParams &params) {
+	//PARAMS2(int, ID, int, length);
+}
+
+void AGSCreditz20::SetStaticCreditTitle(const ScriptMethodParams &params) {
+	//PARAMS8(int, ID, int, x, int, y, int, titlefont, int, titlecolour, int, centered, int, generateoutline, string, title);
+}
+
+void AGSCreditz20::ShowStaticCredit(const ScriptMethodParams &params) {
+	//PARAMS6(int, ID, int, time, int, style, int, transtime, int, sound, int, resolution);
+}
+
+void AGSCreditz20::StaticReset(const ScriptMethodParams &params) {
+}
+
+string AGSCreditz20::GetStaticCreditTitle(const ScriptMethodParams &params) {
+	//PARAMS1(int, ID);
+	return nullptr;
+}
+
+void AGSCreditz20::SetStaticCreditImage(const ScriptMethodParams &params) {
+	//int ID, int x, int y, int Slot, int Hcentered, int Vcentered, int time) {
+}
+
+int AGSCreditz20::IsStaticCreditsFinished(const ScriptMethodParams &params) {
+	return true;
 }
 
 } // namespace AGSCreditz
diff --git a/engines/ags/plugins/ags_creditz/ags_creditz.h b/engines/ags/plugins/ags_creditz/ags_creditz.h
index d49bddbdf5..fb5bcbb7a2 100644
--- a/engines/ags/plugins/ags_creditz/ags_creditz.h
+++ b/engines/ags/plugins/ags_creditz/ags_creditz.h
@@ -121,11 +121,19 @@ protected:
 	static Version _version;
 	static State *_state;
 	static IAGSEngine *_engine;
-protected:
+public:
+	AGSCreditz();
+	~AGSCreditz();
+};
+
+class AGSCreditz11 : public AGSCreditz {
+private:
 	static const char *AGS_GetPluginName();
 	static void AGS_EngineStartup(IAGSEngine *engine);
 
-	// Shared Script methods
+	static void SetCredit(const ScriptMethodParams &params);
+	static void ScrollCredits(const ScriptMethodParams &params);
+	static string GetCredit(const ScriptMethodParams &params);
 	static int IsCreditScrollingFinished(const ScriptMethodParams &params);
 	static void SetCreditImage(const ScriptMethodParams &params);
 	static void PauseScroll(const ScriptMethodParams &params);
@@ -144,27 +152,37 @@ protected:
 	static string GetStaticCreditTitle(const ScriptMethodParams &params);
 	static void SetStaticCreditImage(const ScriptMethodParams &params);
 	static int IsStaticCreditsFinished(const ScriptMethodParams &params);
-public:
-	AGSCreditz();
-	~AGSCreditz();
-};
 
-class AGSCreditz11 : public AGSCreditz {
-private:
-	static void AGS_EngineStartup(IAGSEngine *engine);
-
-	static void SetCredit(const ScriptMethodParams &params);
-	static void ScrollCredits(const ScriptMethodParams &params);
-	static string GetCredit(const ScriptMethodParams &params);
 public:
 	AGSCreditz11();
 };
 
 class AGSCreditz20 : public AGSCreditz {
 private:
+	static const char *AGS_GetPluginName();
 	static void AGS_EngineStartup(IAGSEngine *engine);
 
 	static void SetCredit(const ScriptMethodParams &params);
+	static void ScrollCredits(const ScriptMethodParams &params);
+	static string GetCredit(const ScriptMethodParams &params);
+	static int IsCreditScrollingFinished(const ScriptMethodParams &params);
+	static void SetCreditImage(const ScriptMethodParams &params);
+	static void PauseScroll(const ScriptMethodParams &params);
+	static void ScrollReset(const ScriptMethodParams &params);
+	static void SetEmptyLineHeight(const ScriptMethodParams &params);
+	static int GetEmptyLineHeight(const ScriptMethodParams &params);
+	static void SetStaticCredit(const ScriptMethodParams &params);
+	static string GetStaticCredit(const ScriptMethodParams &params);
+	static void StartEndStaticCredits(const ScriptMethodParams &params);
+	static int GetCurrentStaticCredit(const ScriptMethodParams &params);
+	static void SetDefaultStaticDelay(const ScriptMethodParams &params);
+	static void SetStaticPause(const ScriptMethodParams &params);
+	static void SetStaticCreditTitle(const ScriptMethodParams &params);
+	static void ShowStaticCredit(const ScriptMethodParams &params);
+	static void StaticReset(const ScriptMethodParams &params);
+	static string GetStaticCreditTitle(const ScriptMethodParams &params);
+	static void SetStaticCreditImage(const ScriptMethodParams &params);
+	static int IsStaticCreditsFinished(const ScriptMethodParams &params);
 public:
 	AGSCreditz20();
 };


Commit: 9ea3e804c89ffb6a37f0e56a5ba94dfa4ccb14aa
    https://github.com/scummvm/scummvm/commit/9ea3e804c89ffb6a37f0e56a5ba94dfa4ccb14aa
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Implemented AGSCreditz overall script methods

Changed paths:
    engines/ags/plugins/ags_creditz/ags_creditz.cpp
    engines/ags/plugins/ags_creditz/ags_creditz.h


diff --git a/engines/ags/plugins/ags_creditz/ags_creditz.cpp b/engines/ags/plugins/ags_creditz/ags_creditz.cpp
index a840159af7..9100cc5aa8 100644
--- a/engines/ags/plugins/ags_creditz/ags_creditz.cpp
+++ b/engines/ags/plugins/ags_creditz/ags_creditz.cpp
@@ -93,7 +93,7 @@ void AGSCreditz11::SetCredit(const ScriptMethodParams &params) {
 	c._x = xpos;
 	c._isSet = true;
 	c._outline = generateoutline;
-	c._color = colour;
+	c._colorHeight = colour;
 }
 
 void AGSCreditz11::ScrollCredits(const ScriptMethodParams &params) {
@@ -213,33 +213,59 @@ AGSCreditz20::AGSCreditz20() : AGSCreditz() {
 }
 
 const char *AGSCreditz20::AGS_GetPluginName() {
-	return "AGSCreditz v1.1 by AJA";
+	return "AGSCreditz 2.0 (by Dima Software: AJA)";
 }
 
 void AGSCreditz20::AGS_EngineStartup(IAGSEngine *engine) {
 	_engine = engine;
 
+	SCRIPT_METHOD(RunCreditSequence);
 	SCRIPT_METHOD(SetCredit);
-	SCRIPT_METHOD(ScrollCredits);
 	SCRIPT_METHOD(GetCredit);
-	SCRIPT_METHOD(IsCreditScrollingFinished);
+	SCRIPT_METHOD(CreditsSettings);
+	SCRIPT_METHOD(SequenceSettings);
+	SCRIPT_METHOD(IsSequenceFinished);
+	SCRIPT_METHOD(PauseScrolling);
 	SCRIPT_METHOD(SetCreditImage);
-	SCRIPT_METHOD(PauseScroll);
-	SCRIPT_METHOD(ScrollReset);
-	SCRIPT_METHOD(SetEmptyLineHeight);
-	SCRIPT_METHOD(GetEmptyLineHeight);
+	SCRIPT_METHOD(ResetSequence);
+
 	SCRIPT_METHOD(SetStaticCredit);
-	SCRIPT_METHOD(GetStaticCredit);
-	SCRIPT_METHOD(StartEndStaticCredits);
-	SCRIPT_METHOD(GetCurrentStaticCredit);
-	SCRIPT_METHOD(SetDefaultStaticDelay);
-	SCRIPT_METHOD(SetStaticPause);
 	SCRIPT_METHOD(SetStaticCreditTitle);
+	SCRIPT_METHOD(SetStaticPause);
+	SCRIPT_METHOD(RunStaticCreditSequence);
+	SCRIPT_METHOD(IsStaticSequenceFinished);
 	SCRIPT_METHOD(ShowStaticCredit);
-	SCRIPT_METHOD(StaticReset);
-	SCRIPT_METHOD(GetStaticCreditTitle);
-	SCRIPT_METHOD(SetStaticCreditImage);
-	SCRIPT_METHOD(IsStaticCreditsFinished);
+	SCRIPT_METHOD(SetStaticImage);
+	SCRIPT_METHOD(GetCurrentStaticCredit);
+}
+
+void AGSCreditz20::RunCreditSequence(const ScriptMethodParams &params) {
+	PARAMS1(int, sequence);
+
+	if (!_state->_creditsRunning) {
+		_state->_seqSettings[sequence].finished = false;
+		_state->_creditsRunning = true;
+		_state->_creditSequence = sequence;
+
+		_engine->GetScreenDimensions(&_state->_screenWidth, &_state->_screenHeight,
+			&_state->_screenColorDepth);
+
+		if (_state->_seqSettings[sequence].automatic) {
+			calculateSequenceHeight(sequence);
+			_state->_yPos = _state->_screenHeight + 1;
+		} else {
+			_state->_yPos = _state->_seqSettings[sequence].startpoint;
+		}
+
+		_state->_speedPoint = 0;
+		_state->_timer = 0;
+		draw();
+	} else {
+		_state->_paused = false;
+		_state->_creditsRunning = false;
+		_state->_creditSequence = -1;
+		_state->_seqSettings[sequence].finished = true;
+	}
 }
 
 void AGSCreditz20::SetCredit(const ScriptMethodParams &params) {
@@ -252,119 +278,205 @@ void AGSCreditz20::SetCredit(const ScriptMethodParams &params) {
 	Credit &c = _state->_credits[sequence][line];
 	c._text = credit;
 	c._fontSlot = font;
-	c._color = color;
+	c._colorHeight = color;
 	c._x = x_pos;
 	c._isSet = true;
 	if (gen_outline > 0)
 		c._outline = true;
 }
 
+string AGSCreditz20::GetCredit(const ScriptMethodParams &params) {
+	PARAMS2(int, sequence, int, ID);
 
-void AGSCreditz20::ScrollCredits(const ScriptMethodParams &params) {
-	PARAMS7(int, onoff, int, speed, int, fromY, int, toY, int, isautom, int, wait, int, resolution);
+	return _state->_credits[sequence][ID]._text.c_str();
+}
 
-	if (onoff == 1) {
-		_state->_creditsRunning = true;
-		_state->_seqSettings[0].speed = speed;
-		_state->_seqSettings[0].endwait = wait;
-		_state->_seqSettings[0].startpoint = fromY;
-		_state->_seqSettings[0].endpoint = toY;
-		_state->_seqSettings[0].automatic = isautom;
+void AGSCreditz20::CreditsSettings(const ScriptMethodParams &params) {
+	PARAMS1(int, emptylineheight);
 
-		_engine->GetScreenDimensions(&_state->_screenWidth,
-			&_state->_screenHeight, &_state->_screenColorDepth);
-		if (_state->_screenWidth == 320) {
-			_state->_resolutionFlag = (resolution != 2) ? 1 : 0;
-		} else if (_state->_screenWidth == 640) {
-			_state->_resolutionFlag = (resolution != 1) ? 1 : 0;
-		}
+	if (emptylineheight >= 0)
+		_state->_emptyLineHeight = emptylineheight;
+}
 
-	} else if (onoff == 0) {
-		_state->_creditsRunning = false;
+void AGSCreditz20::SequenceSettings(const ScriptMethodParams &params) {
+	PARAMS6(int, sequence, int, startpoint, int, endpoint, int, speed, int, automatic, int, endwait);
 
-	} else {
-		_engine->AbortGame("ScrollCredits: OnOff value must be 1 or 0!");
-	}
+	_state->_seqSettings[sequence].startpoint = startpoint;
+	_state->_seqSettings[sequence].endpoint = endpoint;
+	_state->_seqSettings[sequence].speed = speed;
+	_state->_seqSettings[sequence].automatic = automatic;
+	_state->_seqSettings[sequence].endwait = endwait;
 }
 
-string AGSCreditz20::GetCredit(const ScriptMethodParams &params) {
-	PARAMS1(int, ID);
+int AGSCreditz20::IsSequenceFinished(const ScriptMethodParams &params) {
+	PARAMS1(int, sequence);
 
-	return (_state->_credits[0][ID]._text == IMAGE_TEXT) ?
-		"image" : _state->_credits[0][ID]._text.c_str();
+	if (_state->_seqSettings[sequence].finished) {
+		_state->_seqSettings[sequence].finished = false;
+		return 1;
+	}
+
+	return 0;
 }
 
-int AGSCreditz20::IsCreditScrollingFinished(const ScriptMethodParams &params) {
-	return true;
+void AGSCreditz20::PauseScrolling(const ScriptMethodParams &params) {
+	if (_state->_creditsRunning) {
+		_state->_paused = !_state->_paused;
+	}
 }
 
 void AGSCreditz20::SetCreditImage(const ScriptMethodParams &params) {
-	//PARAMS5(int, ID, int, Slot, int, center, int, xpos, int, pixtonext);
-}
+	PARAMS5(int, sequence, int, line, int, xPos, int, slot, int, height);
 
-void AGSCreditz20::PauseScroll(const ScriptMethodParams &params) {
-	//PARAMS1(int, onoff);
-}
+	assert(sequence >= 0 && sequence <= 10);
+	if (line >= (int)_state->_credits[sequence].size())
+		_state->_credits[sequence].resize(line + 1);
 
-void AGSCreditz20::ScrollReset(const ScriptMethodParams &params) {
+	_state->_credits[sequence][line]._image = true;
+	_state->_credits[sequence][line]._isSet = true;
+	_state->_credits[sequence][line]._x = xPos;
+	_state->_credits[sequence][line]._fontSlot = slot;
+	_state->_credits[sequence][line]._colorHeight = height;
 }
 
-void AGSCreditz20::SetEmptyLineHeight(const ScriptMethodParams &params) {
-	//PARAMS1(int, Height);
-}
+void AGSCreditz20::ResetSequence(const ScriptMethodParams &params) {
+	PARAMS1(int, seqtype);
 
-int AGSCreditz20::GetEmptyLineHeight(const ScriptMethodParams &params) {
-	return 0;
+	for (int i = 0; i < 10; ++i) {
+		if (seqtype != 2)
+			// Scrolling
+			_state->_credits[i].clear();
+		else
+			// Static
+			_state->_stCredits[i].clear();
+	}
 }
 
 void AGSCreditz20::SetStaticCredit(const ScriptMethodParams &params) {
-	//PARAMS8(int, ID, int, x, int, y, int, creditfont, int, creditcolour, int, centered, int, generateoutline, string, credit);
+	PARAMS8(int, sequence, int, id, string, credit, int, xPos, int, yPos,
+		int, font, int, color, int, genOutline);
 
-}
+	assert(sequence >= 0 && sequence <= 10);
+	if (id >= (int)_state->_stCredits[sequence].size())
+		_state->_stCredits[sequence].resize(id + 1);
 
-string AGSCreditz20::GetStaticCredit(const ScriptMethodParams &params) {
-	//PARAMS1(int, ID);
-	return nullptr;
-}
+	_state->_stCredits[sequence][id].credit = credit;
+	_state->_stCredits[sequence][id].x = xPos;
+	_state->_stCredits[sequence][id].y = yPos;
+	_state->_stCredits[sequence][id].font = font;
+	_state->_stCredits[sequence][id].color = color;
 
-void AGSCreditz20::StartEndStaticCredits(const ScriptMethodParams &params) {
-	//PARAMS2(int, onoff, int, res);
+	if (genOutline > 0)
+		_state->_stCredits[sequence][id].outline = true;
 }
 
-int AGSCreditz20::GetCurrentStaticCredit(const ScriptMethodParams &params) {
-	return 0;
-}
+void AGSCreditz20::SetStaticCreditTitle(const ScriptMethodParams &params) {
+	PARAMS8(int, sequence, int, id, string, title, int, xPos, int, yPos,
+		int, font, int, color, int, genOutline);
 
-void AGSCreditz20::SetDefaultStaticDelay(const ScriptMethodParams &params) {
-	//PARAMS1(int, Cyclesperchar);
+	assert(sequence >= 0 && sequence < 10);
+	if (id >= (int)_state->_stCredits[sequence].size())
+		_state->_stCredits[sequence].resize(id + 1);
+
+	_state->_stCredits[sequence][id].title = title;
+	_state->_stCredits[sequence][id].title_x = xPos;
+	_state->_stCredits[sequence][id].title_y = yPos;
+	_state->_stCredits[sequence][id].title_font = font;
+	_state->_stCredits[sequence][id].title_color = color;
+
+	if (genOutline > 0)
+		_state->_stCredits[sequence][id].title_outline = true;
 }
 
 void AGSCreditz20::SetStaticPause(const ScriptMethodParams &params) {
-	//PARAMS2(int, ID, int, length);
+	PARAMS3(int, sequence, int, id, int, length);
+
+	assert(sequence >= 0 && sequence <= 10);
+	if (id >= (int)_state->_stCredits[sequence].size())
+		_state->_stCredits[sequence].resize(id + 1);
+
+	_state->_stCredits[sequence][id].pause = length;
 }
 
-void AGSCreditz20::SetStaticCreditTitle(const ScriptMethodParams &params) {
-	//PARAMS8(int, ID, int, x, int, y, int, titlefont, int, titlecolour, int, centered, int, generateoutline, string, title);
+void AGSCreditz20::RunStaticCreditSequence(const ScriptMethodParams &params) {
+	PARAMS2(int, sequence, int, speed);
+
+	if (!_state->_creditsRunning) {
+		_state->_stSeqSettings[sequence].finished = false;
+		_state->_stSeqSettings[sequence].speed = speed;
+		_state->_creditSequence = sequence;
+		_state->_staticCredits = true;
+		_state->_creditsRunning = true;
+		_state->_currentStatic = 1;
+		_state->_timer = 0;
+		draw();
+
+	} else {
+		_state->_staticCredits = false;
+		_state->_creditSequence = -1;
+		_state->_stSeqSettings[sequence].finished = false;
+		_state->_creditsRunning = false;
+		_state->_currentStatic = 0;
+		_state->_timer = 0;
+	}
 }
 
-void AGSCreditz20::ShowStaticCredit(const ScriptMethodParams &params) {
-	//PARAMS6(int, ID, int, time, int, style, int, transtime, int, sound, int, resolution);
+int AGSCreditz20::IsStaticSequenceFinished(const ScriptMethodParams &params) {
+	PARAMS1(int, sequence);
+
+	int result = (_state->_stSeqSettings[sequence].finished) ? 1 : 0;
+	_state->_stSeqSettings[sequence].finished = false;
+
+	return result;
 }
 
-void AGSCreditz20::StaticReset(const ScriptMethodParams &params) {
+void AGSCreditz20::ShowStaticCredit(const ScriptMethodParams &params) {
+	PARAMS6(int, sequence, int, id, int, time, int, style,
+		int, styleSettings1, int, styleSettings2);
+
+	_state->_creditSequence = sequence;
+	_state->_creditsRunning = true;
+	_state->_staticCredits = true;
+	_state->_singleStatic.id = id;
+	_state->_singleStatic.time = time;
+	_state->_singleStatic.style = style;
+	_state->_singleStatic.settings1 = styleSettings1;
+	_state->_singleStatic.settings2 = styleSettings2;
+	_state->_singleStatic.bool_ = true;
+	_state->_stSeqSettings[sequence].finished = false;
+	_state->_timer = 0;
+	_state->_timer2 = 0;
+	_state->_numChars = 0;
+	draw();
+}
+
+void AGSCreditz20::SetStaticImage(const ScriptMethodParams &params) {
+	PARAMS6(int, sequence, int, id, int, slot, int, xPos, int, yPos, int, length);
+
+	assert(sequence >= 0 && sequence < 10);
+	if (id >= (int)_state->_stCredits[sequence].size())
+		_state->_stCredits[sequence].resize(id + 1);
+
+	_state->_stCredits[sequence][id].image = true;
+	_state->_stCredits[sequence][id].image_slot = slot;
+	_state->_stCredits[sequence][id].x = xPos;
+	_state->_stCredits[sequence][id].y = yPos;
+	_state->_stCredits[sequence][id].image_time = length;
 }
 
-string AGSCreditz20::GetStaticCreditTitle(const ScriptMethodParams &params) {
-	//PARAMS1(int, ID);
-	return nullptr;
+int AGSCreditz20::GetCurrentStaticCredit(const ScriptMethodParams &params) {
+	int result = -1;
+	if (_state->_creditsRunning && _state->_staticCredits)
+		result = _state->_currentStatic;
+
+	return result;
 }
 
-void AGSCreditz20::SetStaticCreditImage(const ScriptMethodParams &params) {
-	//int ID, int x, int y, int Slot, int Hcentered, int Vcentered, int time) {
+int AGSCreditz20::calculateSequenceHeight(int sequence) {
+	return 0;
 }
 
-int AGSCreditz20::IsStaticCreditsFinished(const ScriptMethodParams &params) {
-	return true;
+void AGSCreditz20::draw() {
 }
 
 } // namespace AGSCreditz
diff --git a/engines/ags/plugins/ags_creditz/ags_creditz.h b/engines/ags/plugins/ags_creditz/ags_creditz.h
index fb5bcbb7a2..df3f373b30 100644
--- a/engines/ags/plugins/ags_creditz/ags_creditz.h
+++ b/engines/ags/plugins/ags_creditz/ags_creditz.h
@@ -37,7 +37,7 @@ struct Credit {
 	int _x = 0;
 	int _y = 0;
 	int _fontSlot = 0;
-	int _color = 0;
+	int _colorHeight = 0;
 	int _center = 0;
 	bool _isSet = false;
 	bool _image = false;
@@ -83,7 +83,7 @@ struct SingleStatic {
 	int id = 0;
 	int time = 0;
 	int style = 0;
-	int settings = 01;
+	int settings1 = 01;
 	int settings2 = 0;
 	bool bool_ = false;
 };
@@ -162,27 +162,28 @@ private:
 	static const char *AGS_GetPluginName();
 	static void AGS_EngineStartup(IAGSEngine *engine);
 
+	static void RunCreditSequence(const ScriptMethodParams &params);
 	static void SetCredit(const ScriptMethodParams &params);
-	static void ScrollCredits(const ScriptMethodParams &params);
 	static string GetCredit(const ScriptMethodParams &params);
-	static int IsCreditScrollingFinished(const ScriptMethodParams &params);
+	static void CreditsSettings(const ScriptMethodParams &params);
+	static void SequenceSettings(const ScriptMethodParams &params);
+	static int IsSequenceFinished(const ScriptMethodParams &params);
+	static void PauseScrolling(const ScriptMethodParams &params);
 	static void SetCreditImage(const ScriptMethodParams &params);
-	static void PauseScroll(const ScriptMethodParams &params);
-	static void ScrollReset(const ScriptMethodParams &params);
-	static void SetEmptyLineHeight(const ScriptMethodParams &params);
-	static int GetEmptyLineHeight(const ScriptMethodParams &params);
+	static void ResetSequence(const ScriptMethodParams &params);
+
 	static void SetStaticCredit(const ScriptMethodParams &params);
-	static string GetStaticCredit(const ScriptMethodParams &params);
-	static void StartEndStaticCredits(const ScriptMethodParams &params);
-	static int GetCurrentStaticCredit(const ScriptMethodParams &params);
-	static void SetDefaultStaticDelay(const ScriptMethodParams &params);
-	static void SetStaticPause(const ScriptMethodParams &params);
 	static void SetStaticCreditTitle(const ScriptMethodParams &params);
+	static void SetStaticPause(const ScriptMethodParams &params);
+	static void RunStaticCreditSequence(const ScriptMethodParams &params);
+	static int IsStaticSequenceFinished(const ScriptMethodParams &params);
 	static void ShowStaticCredit(const ScriptMethodParams &params);
-	static void StaticReset(const ScriptMethodParams &params);
-	static string GetStaticCreditTitle(const ScriptMethodParams &params);
-	static void SetStaticCreditImage(const ScriptMethodParams &params);
-	static int IsStaticCreditsFinished(const ScriptMethodParams &params);
+	static void SetStaticImage(const ScriptMethodParams &params);
+	static int GetCurrentStaticCredit(const ScriptMethodParams &params);
+
+private:
+	static int calculateSequenceHeight(int sequence);
+	static void draw();
 public:
 	AGSCreditz20();
 };


Commit: a24e8b175a2888cf1e58cd6f301cab4dde00a66e
    https://github.com/scummvm/scummvm/commit/a24e8b175a2888cf1e58cd6f301cab4dde00a66e
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Methods to read/write arrays that have safe save/load methods

Changed paths:
    engines/ags/engine/game/savegame_components.cpp
    engines/ags/lib/allegro/color.cpp
    engines/ags/lib/allegro/color.h
    engines/ags/shared/util/stream.h


diff --git a/engines/ags/engine/game/savegame_components.cpp b/engines/ags/engine/game/savegame_components.cpp
index 72a8c179cc..6aa01c7457 100644
--- a/engines/ags/engine/game/savegame_components.cpp
+++ b/engines/ags/engine/game/savegame_components.cpp
@@ -207,8 +207,7 @@ HSaveError WriteGameState(PStream out) {
 	// Game base
 	game.WriteForSavegame(out);
 	// Game palette
-	// TODO: probably no need to save this for hi/true-res game
-	out->WriteArray(palette, sizeof(color), 256);
+	out->SafeWriteArray(palette, PALETTE_COUNT);
 
 	if (loaded_game_file_version <= kGameVersion_272) {
 		// Global variables
@@ -297,7 +296,7 @@ HSaveError ReadGameState(PStream in, int32_t cmp_ver, const PreservedParams &pp,
 	// Game base
 	game.ReadFromSavegame(in);
 	// Game palette
-	in->ReadArray(palette, sizeof(color), 256);
+	in->SafeReadArray(palette, PALETTE_COUNT);
 
 	if (loaded_game_file_version <= kGameVersion_272) {
 		// Legacy interaction global variables
diff --git a/engines/ags/lib/allegro/color.cpp b/engines/ags/lib/allegro/color.cpp
index 0ae8c76b3f..3c8e7af253 100644
--- a/engines/ags/lib/allegro/color.cpp
+++ b/engines/ags/lib/allegro/color.cpp
@@ -24,6 +24,7 @@
 #include "ags/lib/allegro/system.h"
 #include "ags/lib/allegro/aintern.h"
 #include "ags/shared/core/types.h"
+#include "ags/shared/util/stream.h"
 #include "common/textconsole.h"
 #include "common/system.h"
 #include "graphics/palette.h"
@@ -49,6 +50,20 @@ int _rgb_a_shift_32 = 0;
 RGB_MAP *rgb_map;
 COLOR_MAP *color_map;
 
+void color::readFromFile(AGS::Shared::Stream *file) {
+	r = file->ReadByte();
+	g = file->ReadByte();
+	b = file->ReadByte();
+	filler = file->ReadByte();
+}
+
+void color::writeToFile(AGS::Shared::Stream *file) const {
+	file->WriteByte(r);
+	file->WriteByte(g);
+	file->WriteByte(b);
+	file->WriteByte(filler);
+}
+
 
 void set_color(int idx, const RGB *p) {
 	_current_palette[idx] = *p;
diff --git a/engines/ags/lib/allegro/color.h b/engines/ags/lib/allegro/color.h
index db793f2fad..8c9922502e 100644
--- a/engines/ags/lib/allegro/color.h
+++ b/engines/ags/lib/allegro/color.h
@@ -39,11 +39,20 @@ namespace AGS3 {
 
 class BITMAP;
 
+namespace AGS {
+namespace Shared {
+class Stream;
+} // namespace Shared
+} // namespace AGS
+
 #include "common/pack-start.h"  // START STRUCT PACKING
 
 struct color {
 	byte r, g, b;
 	byte filler;
+
+	void readFromFile(AGS::Shared::Stream *file);
+	void writeToFile(AGS::Shared::Stream *file) const;
 } PACKED_STRUCT;
 
 typedef color RGB;
diff --git a/engines/ags/shared/util/stream.h b/engines/ags/shared/util/stream.h
index 5489cde190..281c56dcda 100644
--- a/engines/ags/shared/util/stream.h
+++ b/engines/ags/shared/util/stream.h
@@ -83,6 +83,18 @@ public:
 
 	// Fill the requested number of bytes with particular value
 	size_t WriteByteCount(uint8_t b, size_t count);
+
+	template<class T>
+	inline void SafeReadArray(T *arr, size_t count) {
+		for (size_t i = 0; i < count; ++i, ++arr)
+			arr->readFromFile(this);
+	}
+
+	template<class T>
+	inline void SafeWriteArray(const T *arr, size_t count) {
+		for (size_t i = 0; i < count; ++i, ++arr)
+			arr->writeToFile(this);
+	}
 };
 
 class ScummVMReadStream : public Common::SeekableReadStream {


Commit: 0c2adad99d141412eb2aa4254e8de3e8438782be
    https://github.com/scummvm/scummvm/commit/0c2adad99d141412eb2aa4254e8de3e8438782be
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Further cleaning up read/write structure arrays

Changed paths:
    engines/ags/engine/ac/game.cpp
    engines/ags/shared/ac/gamesetupstructbase.cpp
    engines/ags/shared/game/room_file.cpp
    engines/ags/shared/util/compress.cpp


diff --git a/engines/ags/engine/ac/game.cpp b/engines/ags/engine/ac/game.cpp
index f3aa47e3ab..abd02ed02e 100644
--- a/engines/ags/engine/ac/game.cpp
+++ b/engines/ags/engine/ac/game.cpp
@@ -1226,7 +1226,7 @@ void ReadCharacterExtras_Aligned(Stream *in) {
 }
 
 void restore_game_palette(Stream *in) {
-	in->ReadArray(&palette[0], sizeof(color), 256);
+	in->SafeReadArray(&palette[0], PALETTE_COUNT);
 }
 
 void restore_game_dialogs(Stream *in) {
diff --git a/engines/ags/shared/ac/gamesetupstructbase.cpp b/engines/ags/shared/ac/gamesetupstructbase.cpp
index 8c665fb5f5..24fd031bd3 100644
--- a/engines/ags/shared/ac/gamesetupstructbase.cpp
+++ b/engines/ags/shared/ac/gamesetupstructbase.cpp
@@ -155,7 +155,7 @@ void GameSetupStructBase::ReadFromFile(Stream *in) {
 	}
 	in->Read(&paluses[0], 256);
 	// colors are an array of chars
-	in->Read(&defpal[0], sizeof(color) * 256);
+	in->SafeReadArray(&defpal[0], PALETTE_COUNT);
 	numviews = in->ReadInt32();
 	numcharacters = in->ReadInt32();
 	playercharacter = in->ReadInt32();
@@ -199,7 +199,7 @@ void GameSetupStructBase::WriteToFile(Stream *out) {
 	out->WriteArrayOfInt32(options, 100);
 	out->Write(&paluses[0], 256);
 	// colors are an array of chars
-	out->Write(&defpal[0], sizeof(color) * 256);
+	out->SafeWriteArray(&defpal[0], PALETTE_COUNT);
 	out->WriteInt32(numviews);
 	out->WriteInt32(numcharacters);
 	out->WriteInt32(playercharacter);
diff --git a/engines/ags/shared/game/room_file.cpp b/engines/ags/shared/game/room_file.cpp
index b39bb7059d..11f5baf9fe 100644
--- a/engines/ags/shared/game/room_file.cpp
+++ b/engines/ags/shared/game/room_file.cpp
@@ -675,7 +675,7 @@ HRoomFileError UpdateRoomData(RoomStruct *room, RoomFileVersion data_ver, bool g
 	}
 
 	// sync bpalettes[0] with room.pal
-	memcpy(room->BgFrames[0].Palette, room->Palette, sizeof(color) * 256);
+	memcpy(room->BgFrames[0].Palette, room->Palette, sizeof(color) * PALETTE_COUNT);
 	return HRoomFileError::None();
 }
 
diff --git a/engines/ags/shared/util/compress.cpp b/engines/ags/shared/util/compress.cpp
index 0b8a455966..b9d423c445 100644
--- a/engines/ags/shared/util/compress.cpp
+++ b/engines/ags/shared/util/compress.cpp
@@ -295,7 +295,7 @@ void save_lzw(Stream *out, const Bitmap *bmpp, const color *pall) {
 	// Now open same file for reading, and begin writing compressed data into required output stream
 	lz_temp_s = ci_fopen(lztempfnm);
 	soff_t temp_sz = lz_temp_s->GetLength();
-	out->WriteArray(&pall[0], sizeof(color), 256);
+	out->SafeWriteArray(&pall[0], PALETTE_COUNT);
 	out->WriteInt32(temp_sz);
 	soff_t gobacto = out->GetPosition();
 
@@ -321,7 +321,7 @@ void load_lzw(Stream *in, Bitmap **dst_bmp, int dst_bpp, color *pall) {
 	unsigned char *membuffer;
 	int           arin;
 
-	in->Read(&pall[0], sizeof(color) * 256);
+	in->SafeReadArray(&pall[0], PALETTE_COUNT);
 	maxsize = in->ReadInt32();
 	uncompsiz = in->ReadInt32();
 


Commit: 6fa72f4b4965af81df9ea74ad52edc1455851bdd
    https://github.com/scummvm/scummvm/commit/6fa72f4b4965af81df9ea74ad52edc1455851bdd
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix savegame magic number to match standalone savegames

Changed paths:
    engines/ags/engine/ac/richgamemedia.h


diff --git a/engines/ags/engine/ac/richgamemedia.h b/engines/ags/engine/ac/richgamemedia.h
index 7c650edc5f..02cc2ee9ae 100644
--- a/engines/ags/engine/ac/richgamemedia.h
+++ b/engines/ags/engine/ac/richgamemedia.h
@@ -31,7 +31,7 @@ namespace AGS3 {
 // Windows Vista Rich Save Games, modified to be platform-agnostic
 
 #define RM_MAXLENGTH    1024
-#define RM_MAGICNUMBER  MKTAG('R', 'G', 'M', 'H')
+#define RM_MAGICNUMBER  MKTAG('H', 'M', 'G', 'R')
 
 // Forward declaration
 namespace AGS {


Commit: 298a266c373f76257ba69ebe7f57251afa9ec1a8
    https://github.com/scummvm/scummvm/commit/298a266c373f76257ba69ebe7f57251afa9ec1a8
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Starting to add AgsCreditz 2.0 support methods

Changed paths:
    engines/ags/plugins/ags_creditz/ags_creditz.cpp
    engines/ags/plugins/ags_creditz/ags_creditz.h


diff --git a/engines/ags/plugins/ags_creditz/ags_creditz.cpp b/engines/ags/plugins/ags_creditz/ags_creditz.cpp
index 9100cc5aa8..bf56f30036 100644
--- a/engines/ags/plugins/ags_creditz/ags_creditz.cpp
+++ b/engines/ags/plugins/ags_creditz/ags_creditz.cpp
@@ -472,8 +472,42 @@ int AGSCreditz20::GetCurrentStaticCredit(const ScriptMethodParams &params) {
 	return result;
 }
 
-int AGSCreditz20::calculateSequenceHeight(int sequence) {
-	return 0;
+void AGSCreditz20::calculateSequenceHeight(int sequence) {
+	int height, creditHeight, dum;
+	height = 0;
+
+	for (uint currentCredit = 0; currentCredit < _state->_credits[sequence].size();
+			++currentCredit) {
+
+		if (_state->_credits[sequence][currentCredit]._isSet) {
+			if (_state->_credits[sequence][currentCredit]._image) {
+				if (_state->_credits[sequence][currentCredit]._colorHeight < 0)
+					creditHeight = _engine->GetSpriteHeight(_state->_credits[sequence][currentCredit]._fontSlot);
+				else
+					creditHeight = _state->_credits[sequence][currentCredit]._colorHeight;
+			} else {
+				_engine->GetTextExtent(_state->_credits[sequence][currentCredit]._fontSlot,
+					_state->_credits[sequence][currentCredit]._text.c_str(),
+					&dum, &creditHeight);
+			}
+
+			height += creditHeight;
+		} else {
+			height += VGACheck(_state->_emptyLineHeight);
+		}
+	}
+
+	_state->_calculatedSequenceHeight = height;
+}
+
+int AGSCreditz20::VGACheck(int value) {
+	int screenX, dum;
+	_engine->GetScreenDimensions(&screenX, &dum, &dum);
+
+	if (screenX == 640)
+		return value * 2;
+	else
+		return value;
 }
 
 void AGSCreditz20::draw() {
diff --git a/engines/ags/plugins/ags_creditz/ags_creditz.h b/engines/ags/plugins/ags_creditz/ags_creditz.h
index df3f373b30..d56583256b 100644
--- a/engines/ags/plugins/ags_creditz/ags_creditz.h
+++ b/engines/ags/plugins/ags_creditz/ags_creditz.h
@@ -182,7 +182,8 @@ private:
 	static int GetCurrentStaticCredit(const ScriptMethodParams &params);
 
 private:
-	static int calculateSequenceHeight(int sequence);
+	static void calculateSequenceHeight(int sequence);
+	static int VGACheck(int value);
 	static void draw();
 public:
 	AGSCreditz20();


Commit: f1830f63d7338e92ed56c45bc1966ded0b7e0210
    https://github.com/scummvm/scummvm/commit/f1830f63d7338e92ed56c45bc1966ded0b7e0210
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: SHow GUI error dialog for unsupported games

Changed paths:
    engines/ags/ags.cpp
    engines/ags/engine/ac/route_finder.cpp
    engines/ags/engine/platform/linux/acpllnx.cpp


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index d1d707a941..0a3cbfcdc1 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -368,7 +368,7 @@ Common::Error AGSEngine::run() {
 		// Do shutdown stuff
 		::AGS3::quit_free();
 
-		return result ? Common::kUnknownError : Common::kNoError;
+		return Common::kNoError;
 	}
 #ifdef USE_CUSTOM_EXCEPTION_HANDLER
 	else {
diff --git a/engines/ags/engine/ac/route_finder.cpp b/engines/ags/engine/ac/route_finder.cpp
index 421f08cb54..ba69558cd5 100644
--- a/engines/ags/engine/ac/route_finder.cpp
+++ b/engines/ags/engine/ac/route_finder.cpp
@@ -119,7 +119,8 @@ void init_pathfinder(GameDataVersion game_file_version) {
 }
 
 void shutdown_pathfinder() {
-	route_finder_impl->shutdown_pathfinder();
+	if (route_finder_impl)
+		route_finder_impl->shutdown_pathfinder();
 }
 
 void set_wallscreen(Bitmap *wallscreen) {
diff --git a/engines/ags/engine/platform/linux/acpllnx.cpp b/engines/ags/engine/platform/linux/acpllnx.cpp
index 966ef23e09..87e78d7140 100644
--- a/engines/ags/engine/platform/linux/acpllnx.cpp
+++ b/engines/ags/engine/platform/linux/acpllnx.cpp
@@ -21,6 +21,7 @@
  */
 
 #include "ags/shared/core/platform.h"
+#include "ags/ags.h"
 
 #if AGS_PLATFORM_OS_LINUX
 
@@ -81,15 +82,15 @@ int AGSLinux::CDPlayerCommand(int cmdd, int datt) {
 }
 
 void AGSLinux::DisplayAlert(const char *text, ...) {
-	char displbuf[2000];
 	va_list ap;
 	va_start(ap, text);
-	vsprintf(displbuf, text, ap);
+	Common::String msg = Common::String::vformat(text, ap);
 	va_end(ap);
+
 	if (_logToStdErr)
-		debug("ERROR: %s\n", displbuf);
+		debug("ERROR: %s\n", msg.c_str());
 	else
-		debug("ERROR: %s\n", displbuf);
+		::AGS::g_vm->GUIError(msg);
 }
 
 size_t BuildXDGPath(char *destPath, size_t destSize) {


Commit: 0589f9a817ec7b56ff9d1b739b419a16e80534a0
    https://github.com/scummvm/scummvm/commit/0589f9a817ec7b56ff9d1b739b419a16e80534a0
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
GRAPHICS: Support 24-bit surfaces as dest for blitFrom

Changed paths:
    graphics/managed_surface.cpp


diff --git a/graphics/managed_surface.cpp b/graphics/managed_surface.cpp
index b2b4a33368..f3e6e7923c 100644
--- a/graphics/managed_surface.cpp
+++ b/graphics/managed_surface.cpp
@@ -253,9 +253,9 @@ void ManagedSurface::blitFromInner(const Surface &src, const Common::Rect &srcRe
 		return;
 
 	if (format != src.format) {
-		// When the pixel format differs, the destination must be 2 or 4 bytes per pixel,
-		// and the source be 2/4 bytes as well or be paletted
-		assert(format.bytesPerPixel == 2 || format.bytesPerPixel == 4);
+		// When the pixel format differs, the destination must be non-paletted
+		assert(format.bytesPerPixel == 2 || format.bytesPerPixel == 3
+			|| format.bytesPerPixel == 4);
 		assert(src.format.bytesPerPixel == 2 || src.format.bytesPerPixel == 4
 			|| (src.format.bytesPerPixel == 1 && srcPalette));
 	}
@@ -322,8 +322,13 @@ void ManagedSurface::blitFromInner(const Surface &src, const Common::Rect &srcRe
 				destPixel = format.ARGBToColor(0xff, rDest, gDest, bDest);
 				if (format.bytesPerPixel == 2)
 					*(uint16 *)destVal = destPixel;
-				else
+				else if (format.bytesPerPixel == 4)
 					*(uint32 *)destVal = destPixel;
+				else {
+					destVal[0] = rDest;
+					destVal[1] = gDest;
+					destVal[2] = bDest;
+				}
 			}
 		}
 	}


Commit: 6a5bb2c48f73287d41f1fd840f22f38eb706307b
    https://github.com/scummvm/scummvm/commit/6a5bb2c48f73287d41f1fd840f22f38eb706307b
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix starting up early 2.5 paletted games

Changed paths:
    engines/ags/lib/allegro/gfx.cpp
    engines/ags/lib/allegro/gfx.h
    engines/ags/shared/gfx/image.cpp


diff --git a/engines/ags/lib/allegro/gfx.cpp b/engines/ags/lib/allegro/gfx.cpp
index b66bedf23a..ffa5872ec8 100644
--- a/engines/ags/lib/allegro/gfx.cpp
+++ b/engines/ags/lib/allegro/gfx.cpp
@@ -153,7 +153,11 @@ BITMAP *create_bitmap_ex(int color_depth, int width, int height) {
 		error("Invalid color depth");
 	}
 
-	return new Surface(width, height, format);
+	BITMAP *bitmap = new Surface(width, height, format);
+	if (color_depth == 8)
+		add_palette_if_needed(bitmap->getSurface());
+
+	return bitmap;
 }
 
 BITMAP *create_sub_bitmap(BITMAP *parent, int x, int y, int width, int height) {
@@ -216,12 +220,11 @@ int bitmap_color_depth(BITMAP *bmp) {
 }
 
 int bitmap_mask_color(BITMAP *bmp) {
-	assert(bmp->format.bytesPerPixel > 1);
 	return TRANSPARENT_COLOR(*bmp);
 }
 
-void add_palette_if_needed(Graphics::ManagedSurface &src, Graphics::ManagedSurface &dest) {
-	if (src.format.bytesPerPixel == 1 && dest.format.bytesPerPixel > 1) {
+void add_palette_if_needed(Graphics::ManagedSurface &surf) {
+	if (surf.format.bytesPerPixel == 1) {
 		byte pal[PALETTE_SIZE];
 		palette_to_rgb8(_current_palette, pal);
 
@@ -230,7 +233,7 @@ void add_palette_if_needed(Graphics::ManagedSurface &src, Graphics::ManagedSurfa
 		pal[1] = 0;
 		pal[2] = 0xff;
 
-		src.setPalette(pal, 0, PALETTE_COUNT);
+		surf.setPalette(pal, 0, PALETTE_COUNT);
 	}
 }
 
@@ -238,7 +241,7 @@ void blit(const BITMAP *src, BITMAP *dest, int src_x, int src_y, int dst_x, int
 	Graphics::ManagedSurface &srcS = **src;
 	Graphics::ManagedSurface &destS = **dest;
 
-	add_palette_if_needed(srcS, destS);
+	add_palette_if_needed(srcS);
 
 	if (dynamic_cast<Graphics::Screen *>(&destS) != nullptr) {
 		destS.blitFrom(srcS, Common::Rect(src_x, src_y, src_x + width, src_y + height),
@@ -254,7 +257,7 @@ void stretch_blit(const BITMAP *src, BITMAP *dest, int source_x, int source_y, i
 	Graphics::ManagedSurface &srcS = **src;
 	Graphics::ManagedSurface &destS = **dest;
 
-	add_palette_if_needed(srcS, destS);
+	add_palette_if_needed(srcS);
 
 	destS.transBlitFrom(srcS, Common::Rect(source_x, source_y, source_x + source_width, source_y + source_height),
 		Common::Rect(dest_x, dest_y, dest_x + dest_width, dest_y + dest_height));
@@ -264,7 +267,7 @@ void masked_blit(const BITMAP *src, BITMAP *dest, int src_x, int src_y, int dst_
 	Graphics::ManagedSurface &srcS = **src;
 	Graphics::ManagedSurface &destS = **dest;
 
-	add_palette_if_needed(srcS, destS);
+	add_palette_if_needed(srcS);
 
 	destS.blitFrom(srcS, Common::Rect(src_x, src_y, src_x + width, src_y + height), Common::Point(dst_x, dst_y));
 }
@@ -274,7 +277,7 @@ void masked_stretch_blit(const BITMAP *src, BITMAP *dest, int source_x, int sour
 	Graphics::ManagedSurface &srcS = **src;
 	Graphics::ManagedSurface &destS = **dest;
 
-	add_palette_if_needed(srcS, destS);
+	add_palette_if_needed(srcS);
 
 	destS.transBlitFrom(srcS, Common::Rect(source_x, source_y, source_x + source_width, source_y + source_height),
 		Common::Rect(dest_x, dest_y, dest_x + dest_width, dest_y + dest_height));
@@ -284,7 +287,7 @@ void draw_sprite(BITMAP *bmp, const BITMAP *sprite, int x, int y) {
 	Graphics::ManagedSurface &bmpS = **bmp;
 	Graphics::ManagedSurface &spriteS = **sprite;
 
-	add_palette_if_needed(spriteS, bmpS);
+	add_palette_if_needed(spriteS);
 
 	bmpS.transBlitFrom(spriteS, Common::Point(x, y), TRANSPARENT_COLOR(spriteS));
 }
@@ -293,7 +296,7 @@ void stretch_sprite(BITMAP *bmp, const BITMAP *sprite, int x, int y, int w, int
 	Graphics::ManagedSurface &bmpS = **bmp;
 	Graphics::ManagedSurface &spriteS = **sprite;
 
-	add_palette_if_needed(spriteS, bmpS);
+	add_palette_if_needed(spriteS);
 
 	bmpS.transBlitFrom(spriteS, Common::Rect(0, 0, sprite->w, sprite->h),
 		Common::Rect(x, y, x + w, y + h));
@@ -343,7 +346,7 @@ void draw_sprite_h_flip(BITMAP *bmp, const BITMAP *sprite, int x, int y) {
 	Graphics::ManagedSurface &bmpS = **bmp;
 	Graphics::ManagedSurface &spriteS = **sprite;
 
-	add_palette_if_needed(spriteS, bmpS);
+	add_palette_if_needed(spriteS);
 	bmpS.transBlitFrom(spriteS, Common::Point(x, y), (uint)-1, true);
 }
 
diff --git a/engines/ags/lib/allegro/gfx.h b/engines/ags/lib/allegro/gfx.h
index b5006e55af..dfa900e46a 100644
--- a/engines/ags/lib/allegro/gfx.h
+++ b/engines/ags/lib/allegro/gfx.h
@@ -291,6 +291,7 @@ AL_FUNC(void, stretch_sprite, (BITMAP *bmp, const BITMAP *sprite, int x, int y,
 extern void clear_to_color(BITMAP *bitmap, int color);
 extern int bitmap_color_depth(BITMAP *bmp);
 extern int bitmap_mask_color(BITMAP *bmp);
+extern void add_palette_if_needed(Graphics::ManagedSurface &surf);
 extern void blit(const BITMAP *src, BITMAP *dest, int src_x, int src_y, int dst_x, int dst_y, int width, int height);
 extern void masked_blit(const BITMAP *src, BITMAP *dest, int src_x, int src_y, int dst_x, int dst_y, int width, int height);
 extern void stretch_blit(const BITMAP *src, BITMAP *dest, int source_x, int source_y, int source_width, int source_height,
diff --git a/engines/ags/shared/gfx/image.cpp b/engines/ags/shared/gfx/image.cpp
index 055dcba4e0..b29c6d8c61 100644
--- a/engines/ags/shared/gfx/image.cpp
+++ b/engines/ags/shared/gfx/image.cpp
@@ -111,28 +111,23 @@ int save_bitmap(Common::WriteStream &out, BITMAP *bmp, const RGB *pal) {
 	const Graphics::PixelFormat requiredFormat_3byte(3, 8, 8, 8, 0, 0, 8, 16, 0);
 #endif
 
-	Graphics::ManagedSurface &src = bmp->getSurface();
-	Graphics::Surface *tmp = nullptr;
-	const Graphics::Surface *surface;
+	const Graphics::ManagedSurface &src = bmp->getSurface();
+	Graphics::ManagedSurface surface(bmp->w, bmp->h, requiredFormat_3byte);
+	surface.rawBlitFrom(bmp->getSurface(), Common::Rect(0, 0, src.w, src.h),
+		Common::Point(0, 0), src.getPalette());
 
-	if (bmp->format == requiredFormat_3byte) {
-		surface = &src.rawSurface();
-	} else {
-		surface = tmp = src.rawSurface().convertTo(requiredFormat_3byte);
-	}
-
-	int dstPitch = surface->w * 3;
+	int dstPitch = surface.w * 3;
 	int extraDataLength = (dstPitch % 4) ? 4 - (dstPitch % 4) : 0;
 	int padding = 0;
 
 	out.writeByte('B');
 	out.writeByte('M');
-	out.writeUint32LE(surface->h * dstPitch + 54);
+	out.writeUint32LE(surface.h * dstPitch + 54);
 	out.writeUint32LE(0);
 	out.writeUint32LE(54);
 	out.writeUint32LE(40);
-	out.writeUint32LE(surface->w);
-	out.writeUint32LE(surface->h);
+	out.writeUint32LE(surface.w);
+	out.writeUint32LE(surface.h);
 	out.writeUint16LE(1);
 	out.writeUint16LE(24);
 	out.writeUint32LE(0);
@@ -142,17 +137,11 @@ int save_bitmap(Common::WriteStream &out, BITMAP *bmp, const RGB *pal) {
 	out.writeUint32LE(0);
 	out.writeUint32LE(0);
 
-	for (uint y = surface->h; y-- > 0;) {
-		out.write((const void *)surface->getBasePtr(0, y), dstPitch);
+	for (uint y = surface.h; y-- > 0;) {
+		out.write((const void *)surface.getBasePtr(0, y), dstPitch);
 		out.write(&padding, extraDataLength);
 	}
 
-	// free tmp surface
-	if (tmp) {
-		tmp->free();
-		delete tmp;
-	}
-
 	return true;
 }
 


Commit: de985f566ec34a27fdec9d5205dda857bed15f43
    https://github.com/scummvm/scummvm/commit/de985f566ec34a27fdec9d5205dda857bed15f43
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Remove unused local

Changed paths:
    engines/ags/ags.cpp


diff --git a/engines/ags/ags.cpp b/engines/ags/ags.cpp
index 0a3cbfcdc1..486a4e522c 100644
--- a/engines/ags/ags.cpp
+++ b/engines/ags/ags.cpp
@@ -363,7 +363,7 @@ Common::Error AGSEngine::run() {
 	if (usetup.disable_exception_handling)
 #endif
 	{
-		int result = AGS3::initialize_engine(startup_opts);
+		AGS3::initialize_engine(startup_opts);
 
 		// Do shutdown stuff
 		::AGS3::quit_free();


Commit: 515d592a48e77def684f0286c028a2201f59b068
    https://github.com/scummvm/scummvm/commit/515d592a48e77def684f0286c028a2201f59b068
Author: Paul Gilbert (dreammaster at scummvm.org)
Date: 2021-02-06T16:37:31-08:00

Commit Message:
AGS: Fix std::unordered_map insert to ignore duplicates

Changed paths:
    engines/ags/lib/std/map.h


diff --git a/engines/ags/lib/std/map.h b/engines/ags/lib/std/map.h
index b64afd9f98..fec3fbc66e 100644
--- a/engines/ags/lib/std/map.h
+++ b/engines/ags/lib/std/map.h
@@ -197,6 +197,11 @@ template<class Key, class Val, class HashFunc = Common::Hash<Key>,
 class unordered_map : public Common::HashMap<Key, Val, HashFunc, EqualFunc> {
 public:
 	pair<Key, Val> insert(pair<Key, Val> elem) {
+		// unordered_map doesn't replace already existing keys
+		if (this->contains(elem.first))
+			return pair<Key, Val>(elem.first, this->operator[](elem.first));
+
+		// Add item to map
 		this->operator[](elem.first) = elem.second;
 		return elem;
 	}




More information about the Scummvm-git-logs mailing list