update for C++17 compliance, update to latest 2sf, add WINE cross-compile makefiles
update for C++17 compliance, update to latest 2sf, add WINE cross-compile makefiles

--- a/src/.gitignore
+++ b/src/.gitignore
@@ -4,3 +4,11 @@
 *.release
 *.aps
 .vs
+*.obj
+*.o
+*.dll
+*.exp
+*.lib
+*.d
+*.swp
+

--- /dev/null
+++ b/src/GNUmakefile.msvc
@@ -1,1 +1,26 @@
+all: in_xsf_framework.lib in_2sf.dll in_gsf.dll in_ncsf.dll in_snsf.dll
 
+in_xsf_framework.lib:
+	$(MAKE) -C in_xsf_framework
+
+in_2sf.dll: in_xsf_framework.lib
+	$(MAKE) -C in_2sf
+
+in_gsf.dll: in_xsf_framework.lib
+	$(MAKE) -C in_gsf
+
+in_ncsf.dll: in_xsf_framework.lib
+	$(MAKE) -C in_ncsf
+
+in_snsf.dll: in_xsf_framework.lib
+	$(MAKE) -C in_snsf
+
+clean: FORCE
+	$(MAKE) -C in_xsf_framework clean
+	$(MAKE) -C in_2sf clean
+	$(MAKE) -C in_gsf clean
+	$(MAKE) -C in_ncsf clean
+	$(MAKE) -C in_snsf clean
+
+FORCE:
+

--- /dev/null
+++ b/src/in_2sf/GNUmakefile
@@ -1,1 +1,9 @@
+../in_2sf.dll: $(patsubst %.cpp, %.obj, $(wildcard desmume/*.cpp desmume/*/*.cpp spu/*.cpp *.cpp)) ../in_xsf_framework.lib
+	$(WINE) link.exe /nologo /dll /machine:x86 user32.lib libucrt.lib libvcruntime.lib libcmt.lib libcpmt.lib /out:$@ $^
 
+%.obj: %.cpp $(wildcard desmume/*.h ../in_xsf_framework/*.h) GNUmakefile
+	$(WINE) cl.exe /nologo /std:c++latest /MT /DUNICODE /D_UNICODE /DNDEBUG /O2 /EHsc /I ../in_xsf_framework /I ../in_xsf_framework/zlib /I spu /I desmume /c /Fo$@ $<
+
+clean:
+	rm -f ../in_2sf.dll ../in_2sf.exp ../in_2sf.lib *.obj desmume/*.obj desmume/*/*.obj
+

--- a/src/in_2sf/desmume/MMU.cpp
+++ b/src/in_2sf/desmume/MMU.cpp
@@ -129,7 +129,7 @@
 		/* 3X*/	DUP16(0x00007FFF),
 		/* 4X*/	DUP16(0x00FFFFFF),
 		/* 5X*/	DUP16(0x000007FF),
-		/* 6X*/	DUP16(0x00FFFFFF),
+		/* 6X*/	DUP16(0x000FFFFF),
 		/* 7X*/	DUP16(0x000007FF),
 		/* 8X*/	DUP16(0x00000003),
 		/* 9X*/	DUP16(0x00000003),
@@ -147,10 +147,10 @@
 		/* 2X*/	DUP16(0x003FFFFF),
 		/* 3X*/	DUP8(0x00007FFF),
 				DUP8(0x0000FFFF),
-		/* 4X*/	DUP8(0x00FFFFFF),
+		/* 4X*/	DUP8(0x0000FFFF),
 				DUP8(0x0000FFFF),
 		/* 5X*/	DUP16(0x00000003),
-		/* 6X*/	DUP16(0x00FFFFFF),
+		/* 6X*/	DUP16(0x000FFFFF),
 		/* 7X*/	DUP16(0x00000003),
 		/* 8X*/	DUP16(0x00000003),
 		/* 9X*/	DUP16(0x00000003),
@@ -671,8 +671,8 @@
 	MMU_VRAMmapRefreshBank(VRAM_BANK_C);
 	MMU_VRAMmapRefreshBank(VRAM_BANK_D);
 
-	//printf(vramConfiguration.describe().c_str());
-	//printf("vram remapped at vcount=%d\n",nds.VCount);
+	//fprintf(stderr, vramConfiguration.describe().c_str());
+	//fprintf(stderr, "vram remapped at vcount=%d\n",nds.VCount);
 
 	// -------------------------------
 	// set up arm9 mirrorings
@@ -1065,7 +1065,7 @@
 	T1WriteLong(MMU.MMU_MEM[TEST_PROCNUM][0x40], 0x1A4, val);
 
 	// Launch DMA if start flag was set to "DS Cart"
-	//printf("triggering card dma\n");
+	//fprintf(stderr, "triggering card dma\n");
 	triggerDma(EDMAMode_Card);
 }
 
@@ -1185,7 +1185,7 @@
 	int32_t diff = (nds.timerCycle[proc][timerIndex] - nds_timer) & 0xFFFFFFFF;
 	assert(diff >= 0);
 	if (diff < 0)
-		printf("NEW EMULOOP BAD NEWS PLEASE REPORT: TIME READ DIFF < 0 (%d) (%d) (%d)\n", diff, timerIndex, MMU.timerMODE[proc][timerIndex]);
+		fprintf(stderr, "NEW EMULOOP BAD NEWS PLEASE REPORT: TIME READ DIFF < 0 (%d) (%d) (%d)\n", diff, timerIndex, MMU.timerMODE[proc][timerIndex]);
 
 	int32_t units = diff / (1 << MMU.timerMODE[proc][timerIndex]);
 	int32_t ret;
@@ -1195,7 +1195,7 @@
 	// whichever instruction setup this counter should advance nds_timer (I think?) and the division should truncate down to 65535 immediately
 	else if (units > 65536)
 	{
-		printf("NEW EMULOOP BAD NEWS PLEASE REPORT: UNITS %d:%d = %d\n", proc, timerIndex, units);
+		fprintf(stderr, "NEW EMULOOP BAD NEWS PLEASE REPORT: UNITS %d:%d = %d\n", proc, timerIndex, units);
 		ret = 0;
 	}
 	else
@@ -1251,7 +1251,7 @@
 
 	ret |= (this->gxfifo_irq & 0x3) << 30; // user's irq flags
 
-	//printf("vc=%03d Returning gxstat read: %08X\n",nds.VCount,ret);
+	//fprintf(stderr, "vc=%03d Returning gxstat read: %08X\n",nds.VCount,ret);
 
 	return ret;
 }
@@ -1266,13 +1266,13 @@
 		//mtxStack[0].position = 0;
 		this->se = 0; // clear stack error flag
 	}
-	//printf("gxstat write: %08X while gxfifo.size=%d\n",val,gxFIFO.size);
+	//fprintf(stderr, "gxstat write: %08X while gxfifo.size=%d\n",val,gxFIFO.size);
 }
 
 // this could be inlined...
 void MMU_struct_new::write_dma(int proc, int size, uint32_t _adr, uint32_t val)
 {
-	//printf("%08lld -- write_dma: %d %d %08X %08X\n",nds_timer,proc,size,_adr,val);
+	//fprintf(stderr, "%08lld -- write_dma: %d %d %08X %08X\n",nds_timer,proc,size,_adr,val);
 	uint32_t adr = _adr - _REG_DMA_CONTROL_MIN;
 	uint32_t chan = adr / 12;
 	uint32_t regnum = (adr - chan * 12) >> 2;
@@ -1288,7 +1288,7 @@
 	uint32_t regnum = (adr - chan * 12) >> 2;
 
 	uint32_t temp = MMU_new.dma[proc][chan].regs[regnum]->read(size, adr);
-	//printf("%08lld --  read_dma: %d %d %08X = %08X\n",nds_timer,proc,size,_adr,temp);
+	//fprintf(stderr, "%08lld --  read_dma: %d %d %08X = %08X\n",nds_timer,proc,size,_adr,temp);
 
 	return temp;
 }
@@ -1305,7 +1305,7 @@
 
 void DmaController::write32(uint32_t val)
 {
-	//printf("dma %d,%d WRITE %08X\n",procnum,chan,val);
+	//fprintf(stderr, "dma %d,%d WRITE %08X\n",procnum,chan,val);
 	this->wordcount = val & 0x1FFFFF;
 	uint8_t wasEnable = this->enable;
 	uint32_t valhi = val >> 16;
@@ -1332,7 +1332,7 @@
 		this->daddr = this->daddr_user;
 	}
 
-	//printf("dma %d,%d set to startmode %d with wordcount set to: %08X\n",procnum,chan,_startmode,wordcount);
+	//fprintf(stderr, "dma %d,%d set to startmode %d with wordcount set to: %08X\n",procnum,chan,_startmode,wordcount);
 	// analyze enabling and startmode.
 	// note that we only do this if the dma was freshly enabled.
 	// we should probably also only be latching these other regs in that case too..
@@ -1463,7 +1463,7 @@
 	// need to figure out what to do about this
 	if (bogarted)
 	{
-		printf("YOUR GAME IS BOGARTED!!! PLEASE REPORT!!!\n");
+		fprintf(stderr, "YOUR GAME IS BOGARTED!!! PLEASE REPORT!!!\n");
 		assert(false);
 		return;
 	}
@@ -1580,7 +1580,7 @@
 	ret |= this->sar << 23;
 	ret |= this->dar << 21;
 	ret |= this->wordcount;
-	//printf("dma %d,%d READ  %08X\n",procnum,chan,ret);
+	//fprintf(stderr, "dma %d,%d READ  %08X\n",procnum,chan,ret);
 	return ret;
 }
 
@@ -1621,30 +1621,30 @@
 		switch (adr)
 		{
 			case REG_SQRTCNT:
-				printf("ERROR 8bit SQRTCNT WRITE\n");
+				fprintf(stderr, "ERROR 8bit SQRTCNT WRITE\n");
 				return;
 			case REG_SQRTCNT + 1:
-				printf("ERROR 8bit SQRTCNT1 WRITE\n");
+				fprintf(stderr, "ERROR 8bit SQRTCNT1 WRITE\n");
 				return;
 			case REG_SQRTCNT + 2:
-				printf("ERROR 8bit SQRTCNT2 WRITE\n");
+				fprintf(stderr, "ERROR 8bit SQRTCNT2 WRITE\n");
 				return;
 			case REG_SQRTCNT + 3:
-				printf("ERROR 8bit SQRTCNT3 WRITE\n");
+				fprintf(stderr, "ERROR 8bit SQRTCNT3 WRITE\n");
 				return;
 
 #if 1
 			case REG_DIVCNT:
-				printf("ERROR 8bit DIVCNT WRITE\n");
+				fprintf(stderr, "ERROR 8bit DIVCNT WRITE\n");
 				return;
 			case REG_DIVCNT + 1:
-				printf("ERROR 8bit DIVCNT+1 WRITE\n");
+				fprintf(stderr, "ERROR 8bit DIVCNT+1 WRITE\n");
 				return;
 			case REG_DIVCNT + 2:
-				printf("ERROR 8bit DIVCNT+2 WRITE\n");
+				fprintf(stderr, "ERROR 8bit DIVCNT+2 WRITE\n");
 				return;
 			case REG_DIVCNT + 3:
-				printf("ERROR 8bit DIVCNT+3 WRITE\n");
+				fprintf(stderr, "ERROR 8bit DIVCNT+3 WRITE\n");
 				return;
 #endif
 
@@ -1734,12 +1734,12 @@
 			case REG_DIVNUMER:
 			case REG_DIVNUMER + 2:
 			case REG_DIVNUMER + 4:
-				printf("DIV: 16 write NUMER %08X. PLEASE REPORT! \n", val);
+				fprintf(stderr, "DIV: 16 write NUMER %08X. PLEASE REPORT! \n", val);
 				break;
 			case REG_DIVDENOM:
 			case REG_DIVDENOM + 2:
 			case REG_DIVDENOM + 4:
-				printf("DIV: 16 write DENOM %08X. PLEASE REPORT! \n", val);
+				fprintf(stderr, "DIV: 16 write DENOM %08X. PLEASE REPORT! \n", val);
 				break;
 #endif
 			case REG_SQRTCNT:
@@ -2024,10 +2024,10 @@
 
 			// sqrtcnt isnt big enough for these to exist. but they'd probably return 0 so its ok
 			case REG_SQRTCNT + 2:
-				printf("ERROR 8bit SQRTCNT+2 READ\n");
+				fprintf(stderr, "ERROR 8bit SQRTCNT+2 READ\n");
 				return 0;
 			case REG_SQRTCNT + 3:
-				printf("ERROR 8bit SQRTCNT+3 READ\n");
+				fprintf(stderr, "ERROR 8bit SQRTCNT+3 READ\n");
 				return 0;
 
 			// Nostalgia's options menu requires that these work
@@ -2038,10 +2038,10 @@
 
 			// divcnt isnt big enough for these to exist. but they'd probably return 0 so its ok
 			case REG_DIVCNT + 2:
-				printf("ERROR 8bit DIVCNT+2 READ\n");
+				fprintf(stderr, "ERROR 8bit DIVCNT+2 READ\n");
 				return 0;
 			case REG_DIVCNT + 3:
-				printf("ERROR 8bit DIVCNT+3 READ\n");
+				fprintf(stderr, "ERROR 8bit DIVCNT+3 READ\n");
 				return 0;
 		}
 	}
@@ -2077,14 +2077,14 @@
 				return MMU_new.sqrt.read16();
 			// sqrtcnt isnt big enough for this to exist. but it'd probably return 0 so its ok
 			case REG_SQRTCNT + 2:
-				printf("ERROR 16bit SQRTCNT+2 READ\n");
+				fprintf(stderr, "ERROR 16bit SQRTCNT+2 READ\n");
 				return 0;
 
 			case REG_DIVCNT:
 				return MMU_new.div.read16();
 			// divcnt isnt big enough for this to exist. but it'd probably return 0 so its ok
 			case REG_DIVCNT + 2:
-				printf("ERROR 16bit DIVCNT+2 READ\n");
+				fprintf(stderr, "ERROR 16bit DIVCNT+2 READ\n");
 				return 0;
 
 			case REG_IME:
@@ -2255,7 +2255,7 @@
 				break;
 
 			case REG_HALTCNT:
-				//printf("halt 0x%02X\n", val);
+				//fprintf(stderr, "halt 0x%02X\n", val);
 				switch (val)
 				{
 					case 0xC0:
@@ -2310,11 +2310,11 @@
 			case REG_DISPA_VCOUNT:
 				if (nds.VCount >= 202 && nds.VCount <= 212)
 				{
-					printf("VCOUNT set to %i (previous value %i)\n", val, nds.VCount);
+					fprintf(stderr, "VCOUNT set to %i (previous value %i)\n", val, nds.VCount);
 					nds.VCount = val;
 				}
 				else
-					printf("Attempt to set VCOUNT while not within 202-212 (%i), ignored\n", nds.VCount);
+					fprintf(stderr, "Attempt to set VCOUNT while not within 202-212 (%i), ignored\n", nds.VCount);
 				return;
 
 			case REG_EXMEMCNT:
@@ -2379,7 +2379,7 @@
 								// our totally pathetic register handling, only the one thing we've wanted so far
 								if (MMU.powerMan_Reg[0] & PM_SYSTEM_PWR)
 								{
-									printf("SYSTEM POWERED OFF VIA ARM7 SPI POWER DEVICE\n");
+									fprintf(stderr, "SYSTEM POWERED OFF VIA ARM7 SPI POWER DEVICE\n");
 									execute = false;
 								}
 							}
@@ -2413,7 +2413,7 @@
 						}
 
 						int channel = (MMU.SPI_CMD & 0x70) >> 4;
-						//printf("%08X\n",channel);
+						//fprintf(stderr, "%08X\n",channel);
 						switch (channel)
 						{
 							case TSC_MEASURE_TEMP1:

--- a/src/in_2sf/desmume/MMU.h
+++ b/src/in_2sf/desmume/MMU.h
@@ -322,7 +322,7 @@
 		// an extra 128KB for blank memory, directly after arm9_lcd, so that
 		// we can easily map things to the end of arm9_lcd to represent
 		// an unmapped state
-		uint8_t blank_memory[0x20000];
+		uint8_t blank_memory[0x100000 - 0xA4000];
 	};
 #include "PACKED_END.h"
 

--- a/src/in_2sf/desmume/NDSSystem.cpp
+++ b/src/in_2sf/desmume/NDSSystem.cpp
@@ -38,18 +38,13 @@
 NDSSystem nds;
 static std::unique_ptr<CFIRMWARE> firmware;
 
-namespace DLDI
-{
-	bool tryPatch(void *data, size_t size);
-}
-
 int NDS_Init()
 {
 	MMU_Init();
 	nds.VCount = 0;
 
 	// got to print this somewhere..
-	printf("%s\n", EMU_DESMUME_NAME_AND_VERSION());
+	fprintf(stderr, "%s\n", EMU_DESMUME_NAME_AND_VERSION());
 
 	armcpu_new(&NDS_ARM7, 1);
 	armcpu_new(&NDS_ARM9, 0);
@@ -230,7 +225,7 @@
 				}
 #ifndef NDEBUG
 				if (ctr > 1)
-					printf("yikes!!!!! please report!\n");
+					fprintf(stderr, "yikes!!!!! please report!\n");
 #endif
 			}
 
@@ -267,7 +262,7 @@
 
 	void exec()
 	{
-		//printf("exec from TSequenceItem_DMA: %d %d\n",procnum,chan);
+		//fprintf(stderr, "exec from TSequenceItem_DMA: %d %d\n",procnum,chan);
 		this->controller->exec();
 	}
 };
@@ -453,7 +448,7 @@
 
 static void execHardware_hstart_vblankStart()
 {
-	//printf("--------VBLANK!!!--------\n");
+	//fprintf(stderr, "--------VBLANK!!!--------\n");
 
 	// fire vblank interrupts if necessary
 	for (int i = 0; i < 2; ++i)
@@ -794,7 +789,7 @@
 			uint64_t next = sequencer.findNext();
 			next = std::min(next, nds_timer + kMaxWork); // lets set an upper limit for now
 
-			//printf("%d\n", next - nds_timer);
+			//fprintf(stderr, "%d\n", next - nds_timer);
 
 			sequencer.reschedule = false;
 
@@ -838,7 +833,7 @@
 
 	if (masked && MMU.reg_IME[PROCNUM] && !ARMPROC.CPSR.bits.I)
 	{
-		//printf("Executing IRQ on procnum %d with IF = %08X and IE = %08X\n",PROCNUM,IF,IE);
+		//fprintf(stderr, "Executing IRQ on procnum %d with IF = %08X and IE = %08X\n",PROCNUM,IF,IE);
 		armcpu_irqException(&ARMPROC);
 	}
 }

--- a/src/in_2sf/desmume/NDSSystem.h
+++ b/src/in_2sf/desmume/NDSSystem.h
@@ -21,6 +21,7 @@
 #include <memory>
 #include <string>
 #include <cstring>
+#include <stdlib.h>
 #include "armcpu.h"
 #include "MMU.h"
 #include "SPU.h"
@@ -289,8 +290,34 @@
 		strcpy(this->Firmware, "firmware.bin");
 		NDS_FillDefaultFirmwareConfigData(&this->InternalFirmConf);
 
-		for (int i = 0; i < 16; ++i)
-			this->spu_muteChannels[i] = false;
+    bool solo = false;
+    static char* soloEnv = strdup("SOLO_2SF_n");
+    static char* muteEnv = strdup("MUTE_2SF_n");
+		for (int i = 0; i < 16; ++i) {
+      if (i < 10) {
+        soloEnv[9] = '0' + i;
+      } else {
+        soloEnv[9] = 'A' + (i - 10);
+      }
+      char* soloVal = getenv(soloEnv);
+      if (soloVal && soloVal[0] == '1') {
+        solo = true;
+        this->spu_muteChannels[i] = false;
+      } else {
+        this->spu_muteChannels[i] = true;
+      }
+    }
+    if (!solo) {
+      for (int i = 0; i < 16; ++i) {
+        if (i < 10) {
+          muteEnv[9] = '0' + i;
+        } else {
+          muteEnv[9] = 'A' + (i - 10);
+        }
+        char* muteVal = getenv(muteEnv);
+        this->spu_muteChannels[i] = muteVal && muteVal[0] == '1';
+      }
+    }
 
 #ifdef HAVE_JIT
 		// zero 06-sep-2012 - shouldnt be defaulting this to true for now, since the jit is buggy.

--- a/src/in_2sf/desmume/SPU.cpp
+++ b/src/in_2sf/desmume/SPU.cpp
@@ -1,1542 +1,1481 @@
 /*
-	Copyright (C) 2006 yopyop
-	Copyright (C) 2006 Theo Berkau
-	Copyright (C) 2008-2012 DeSmuME team
-
-	Ideas borrowed from Stephane Dallongeville's SCSP core
-
-	This file is free software: you can redistribute it and/or modify
-	it under the terms of the GNU General Public License as published by
-	the Free Software Foundation, either version 2 of the License, or
-	(at your option) any later version.
-
-	This file is distributed in the hope that it will be useful,
-	but WITHOUT ANY WARRANTY; without even the implied warranty of
-	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-	GNU General Public License for more details.
-
-	You should have received a copy of the GNU General Public License
-	along with the this software.  If not, see <http://www.gnu.org/licenses/>.
-*/
+   Copyright (C) 2006 yopyop
+   Copyright (C) 2006 Theo Berkau
+   Copyright (C) 2008-2017 DeSmuME team
+
+   Ideas borrowed from Stephane Dallongeville's SCSP core
+
+   This file is free software: you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation, either version 2 of the License, or
+   (at your option) any later version.
+
+   This file is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with the this software.  If not, see <http://www.gnu.org/licenses/>.
+   */
 
 #include "XSFCommon.h"
-
+#include "../spu/samplecache.h"
+#include "../spu/interpolator.h"
+
+#define _USE_MATH_DEFINES
+#include <math.h>
+#ifndef M_PI
+#define M_PI 3.1415926535897932386
+#endif
+
+#include <stdlib.h>
+#include <string.h>
 #include <queue>
 #include <vector>
-#include <cstdlib>
-#include <cstring>
-#ifndef M_PI
-static const double M_PI = 3.14159265358979323846;
-#endif
+
 #include "MMU.h"
 #include "SPU.h"
 #include "mem.h"
 #include "readwrite.h"
 #include "armcpu.h"
 #include "NDSSystem.h"
+#include "emufile.h"
 #include "matrix.h"
-
-static inline int16_t read16(uint32_t addr) { return _MMU_read16<ARMCPU_ARM7,MMU_AT_DEBUG>(addr); }
-static inline uint8_t read08(uint32_t addr) { return _MMU_read08<ARMCPU_ARM7,MMU_AT_DEBUG>(addr); }
-static inline int8_t read_s8(uint32_t addr) { return _MMU_read08<ARMCPU_ARM7,MMU_AT_DEBUG>(addr); }
-
-static const int K_ADPCM_LOOPING_RECOVERY_INDEX = 99999;
-static const int COSINE_INTERPOLATION_RESOLUTION = 8192;
-
-static auto synchronizer = std::unique_ptr<ISynchronizingAudioBuffer>(metaspu_construct(ESynchMethod_N));
-
-std::unique_ptr<SPU_struct> SPU_core, SPU_user;
+#include "utils/bits.h"
+
+static inline s16 read16(u32 addr) { return (s16)_MMU_read16<ARMCPU_ARM7,MMU_AT_DEBUG>(addr); }
+static inline u8 read08(u32 addr) { return _MMU_read08<ARMCPU_ARM7,MMU_AT_DEBUG>(addr); }
+static inline s8 read_s8(u32 addr) { return (s8)_MMU_read08<ARMCPU_ARM7,MMU_AT_DEBUG>(addr); }
+
+#define K_ADPCM_LOOPING_RECOVERY_INDEX 99999
+#define COSINE_INTERPOLATION_RESOLUTION 8192
+
+SPU_struct *SPU_core = 0;
 int SPU_currentCoreNum = SNDCORE_DUMMY;
 static int volume = 100;
+static SampleCache sampleCache;
 
 static size_t buffersize = 0;
-static ESynchMode synchmode = ESynchMode_DualSynchAsynch;
-static ESynchMethod synchmethod = ESynchMethod_N;
-
-static int SNDCoreId = -1;
-static SoundInterface_struct *SNDCore = nullptr;
+static ESynchMode synchmode = ESynchMode_Synchronous;
+static ESynchMethod synchmethod = ESynchMethod_0;
+static ISynchronizingAudioBuffer* synchronizer = metaspu_construct(synchmethod);
+
+static int SNDCoreId=-1;
+static SoundInterface_struct *SNDCore=NULL;
 extern SoundInterface_struct *SNDCoreList[];
 
 static const int format_shift[] = { 2, 1, 3, 0 };
-
-static const int8_t indextbl[8] =
-{
-	-1, -1, -1, -1, 2, 4, 6, 8
+static const u8 volume_shift[] = { 0, 1, 2, 4 };
+
+static const s8 indextbl[8] = { -1, -1, -1, -1, 2, 4, 6, 8 };
+
+static const u16 adpcmtbl[89] = {
+  0x0007, 0x0008, 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x000E, 0x0010,
+  0x0011, 0x0013, 0x0015, 0x0017, 0x0019, 0x001C, 0x001F, 0x0022, 0x0025,
+  0x0029, 0x002D, 0x0032, 0x0037, 0x003C, 0x0042, 0x0049, 0x0050, 0x0058,
+  0x0061, 0x006B, 0x0076, 0x0082, 0x008F, 0x009D, 0x00AD, 0x00BE, 0x00D1,
+  0x00E6, 0x00FD, 0x0117, 0x0133, 0x0151, 0x0173, 0x0198, 0x01C1, 0x01EE,
+  0x0220, 0x0256, 0x0292, 0x02D4, 0x031C, 0x036C, 0x03C3, 0x0424, 0x048E,
+  0x0502, 0x0583, 0x0610, 0x06AB, 0x0756, 0x0812, 0x08E0, 0x09C3, 0x0ABD,
+  0x0BD0, 0x0CFF, 0x0E4C, 0x0FBA, 0x114C, 0x1307, 0x14EE, 0x1706, 0x1954,
+  0x1BDC, 0x1EA5, 0x21B6, 0x2515, 0x28CA, 0x2CDF, 0x315B, 0x364B, 0x3BB9,
+  0x41B2, 0x4844, 0x4F7E, 0x5771, 0x602F, 0x69CE, 0x7462, 0x7FFF
 };
 
-static const uint16_t adpcmtbl[89] =
-{
-	0x0007, 0x0008, 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x000E, 0x0010,
-	0x0011, 0x0013, 0x0015, 0x0017, 0x0019, 0x001C, 0x001F, 0x0022, 0x0025,
-	0x0029, 0x002D, 0x0032, 0x0037, 0x003C, 0x0042, 0x0049, 0x0050, 0x0058,
-	0x0061, 0x006B, 0x0076, 0x0082, 0x008F, 0x009D, 0x00AD, 0x00BE, 0x00D1,
-	0x00E6, 0x00FD, 0x0117, 0x0133, 0x0151, 0x0173, 0x0198, 0x01C1, 0x01EE,
-	0x0220, 0x0256, 0x0292, 0x02D4, 0x031C, 0x036C, 0x03C3, 0x0424, 0x048E,
-	0x0502, 0x0583, 0x0610, 0x06AB, 0x0756, 0x0812, 0x08E0, 0x09C3, 0x0ABD,
-	0x0BD0, 0x0CFF, 0x0E4C, 0x0FBA, 0x114C, 0x1307, 0x14EE, 0x1706, 0x1954,
-	0x1BDC, 0x1EA5, 0x21B6, 0x2515, 0x28CA, 0x2CDF, 0x315B, 0x364B, 0x3BB9,
-	0x41B2, 0x4844, 0x4F7E, 0x5771, 0x602F, 0x69CE, 0x7462, 0x7FFF
+static const s16 wavedutytbl[8][8] = {
+  { -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, 0x7FFF },
+  { -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, 0x7FFF, 0x7FFF },
+  { -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF },
+  { -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF },
+  { -0x7FFF, -0x7FFF, -0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF },
+  { -0x7FFF, -0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF },
+  { -0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF },
+  { -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF }
 };
 
-static const int16_t wavedutytbl[8][8] = {
-	{ -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, 0x7FFF },
-	{ -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, 0x7FFF, 0x7FFF },
-	{ -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF },
-	{ -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF },
-	{ -0x7FFF, -0x7FFF, -0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF },
-	{ -0x7FFF, -0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF },
-	{ -0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF },
-	{ -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF }
-};
-
-static int32_t precalcdifftbl[89][16];
-static uint8_t precalcindextbl[89][8];
-static double cos_lut[COSINE_INTERPOLATION_RESOLUTION];
-
 static const double ARM7_CLOCK = 33513982;
 
-static const double samples_per_hline = (DESMUME_SAMPLE_RATE / 59.8261f) / 263.0f;
+double DESMUME_SAMPLE_RATE = 48000;
+static double samples_per_hline = (DESMUME_SAMPLE_RATE / 59.8261f) / 263.0f;
+static double sampleLength = DESMUME_SAMPLE_RATE / 32728.498;
+
+void SetDesmumeSampleRate(double rate) {
+  DESMUME_SAMPLE_RATE = rate;
+  sampleLength = DESMUME_SAMPLE_RATE / 32728.498;
+  samples_per_hline = (DESMUME_SAMPLE_RATE / 59.8261f) / 263.0f;
+  for (int i = 0; i < 16; i++) {
+    channel_struct *chan = &SPU_core->channels[i];
+  }
+}
 
 static double samples = 0;
 
-template<typename T> static inline T MinMax(T val, T min, T max)
-{
-	if (val < min)
-		return min;
-	else if (val > max)
-		return max;
-	else
-		return val;
+template<typename T>
+static FORCEINLINE T MinMax(T val, T min, T max)
+{
+  if (val < min)
+    return min;
+  else if (val > max)
+    return max;
+
+  return val;
 }
 
 //--------------external spu interface---------------
 
-int SPU_ChangeSoundCore(int coreid, int Buffersize)
-{
-	buffersize = Buffersize;
-
-	SPU_user.reset();
-
-	// Make sure the old core is freed
-	if (SNDCore)
-		SNDCore->DeInit();
-
-	// So which core do we want?
-	if (coreid == SNDCORE_DEFAULT)
-		coreid = 0; // Assume we want the first one
-
-	SPU_currentCoreNum = coreid;
-
-	// Go through core list and find the id
-	for (int i = 0; SNDCoreList[i]; ++i)
-		if (SNDCoreList[i]->id == coreid)
-		{
-			// Set to current core
-			SNDCore = SNDCoreList[i];
-			break;
-		}
-
-	SNDCoreId = coreid;
-
-	// If the user picked the dummy core, disable the user spu
-	if (SNDCore == &SNDDummy)
-		return 0;
-
-	// If the core wasnt found in the list for some reason, disable the user spu
-	if (!SNDCore)
-		return -1;
-
-	// Since it failed, instead of it being fatal, disable the user spu
-	if (SNDCore->Init(buffersize * 2) == -1)
-	{
-		SNDCore = nullptr;
-		return -1;
-	}
-
-	SNDCore->SetVolume(volume);
-
-	SPU_SetSynchMode(synchmode, synchmethod);
-
-	return 0;
-}
-
-void SPU_ReInit()
-{
-	SPU_Init(SNDCoreId, buffersize);
-}
-
-int SPU_Init(int coreid, int Buffersize)
-{
-	// Build the cosine interpolation LUT
-	int i;
-	for (i = 0; i < COSINE_INTERPOLATION_RESOLUTION; ++i)
-		cos_lut[i] = (1.0 - std::cos((static_cast<double>(i) / COSINE_INTERPOLATION_RESOLUTION) * M_PI)) * 0.5;
-
-	SPU_core.reset(new SPU_struct(std::ceil(samples_per_hline)));
-	SPU_Reset();
-
-	int j;
-	// create adpcm decode accelerator lookups
-	for (i = 0; i < 16; ++i)
-		for (j = 0; j < 89; ++j)
-		{
-			precalcdifftbl[j][i] = ((i & 0x7) * 2 + 1) * adpcmtbl[j] / 8;
-			if (i & 0x8)
-				precalcdifftbl[j][i] = -precalcdifftbl[j][i];
-		}
-	for (i = 0; i < 8; ++i)
-		for (j = 0; j < 89; ++j)
-			precalcindextbl[j][i] = MinMax(j + indextbl[i], 0, 88);
-
-	return SPU_ChangeSoundCore(coreid, Buffersize);
-}
-
-void SPU_CloneUser()
-{
-	if (SPU_user)
-	{
-		memcpy(SPU_user->channels, SPU_core->channels, sizeof(SPU_core->channels));
-		SPU_user->regs = SPU_core->regs;
-	}
-}
-
-void SPU_SetSynchMode(ESynchMode mode, ESynchMethod method)
-{
-	synchmode = mode;
-	if (synchmethod != method)
-	{
-		synchmethod = method;
-		// grr does this need to be locked? spu might need a lock method
-		// or maybe not, maybe the platform-specific code that calls this function can deal with it.
-		synchronizer.reset(metaspu_construct(synchmethod));
-	}
-
-	SPU_user.reset();
-
-	if (synchmode == ESynchMode_DualSynchAsynch)
-	{
-		SPU_user.reset(new SPU_struct(buffersize));
-		SPU_CloneUser();
-	}
-}
-
-void SPU_Reset()
-{
-	SPU_core->reset();
-
-	if (SPU_user)
-	{
-		if (SNDCore)
-		{
-			SNDCore->DeInit();
-			SNDCore->Init(SPU_user->bufsize * 2);
-			SNDCore->SetVolume(volume);
-		}
-		SPU_user->reset();
-	}
-
-	// zero - 09-apr-2010: this concerns me, regarding savestate synch.
-	// After 0.9.6, lets experiment with removing it and just properly zapping the spu instead
-	// Reset Registers
-	for (int i = 0x400; i < 0x51D; ++i)
-		T1WriteByte(MMU.ARM7_REG, i, 0);
-
-	samples = 0;
+int SPU_ChangeSoundCore(int coreid, int buffersize)
+{
+  int i;
+
+  ::buffersize = buffersize;
+
+  // Make sure the old core is freed
+  if (SNDCore)
+    SNDCore->DeInit();
+
+  // So which core do we want?
+  if (coreid == SNDCORE_DEFAULT)
+    coreid = 0; // Assume we want the first one
+
+  SPU_currentCoreNum = coreid;
+
+  // Go through core list and find the id
+  for (i = 0; SNDCoreList[i] != NULL; i++)
+  {
+    if (SNDCoreList[i]->id == coreid)
+    {
+      // Set to current core
+      SNDCore = SNDCoreList[i];
+      break;
+    }
+  }
+
+  SNDCoreId = coreid;
+
+  //If the user picked the dummy core, disable the user spu
+  if(SNDCore == &SNDDummy)
+    return 0;
+
+  //If the core wasnt found in the list for some reason, disable the user spu
+  if (SNDCore == NULL)
+    return -1;
+
+  // Since it failed, instead of it being fatal, disable the user spu
+  if (SNDCore->Init(buffersize * 2) == -1)
+  {
+    SNDCore = 0;
+    return -1;
+  }
+
+  SNDCore->SetVolume(volume);
+
+  SPU_SetSynchMode(synchmode,synchmethod);
+
+  return 0;
+}
+
+SoundInterface_struct *SPU_SoundCore()
+{
+  return SNDCore;
+}
+
+void SPU_ReInit(bool fakeBoot)
+{
+  SPU_Init(SNDCoreId, buffersize);
+
+  // Firmware set BIAS to 0x200
+  if (fakeBoot)
+    SPU_WriteWord(0x04000504, 0x0200);
+}
+
+int SPU_Init(int coreid, int buffersize)
+{
+  SPU_core = new SPU_struct((int)ceil(samples_per_hline));
+  SPU_Reset();
+
+  SPU_SetSynchMode(synchmode, synchmethod);
+
+  return SPU_ChangeSoundCore(coreid, buffersize);
+}
+
+void SPU_Pause(int pause)
+{
+  if (SNDCore == NULL) return;
+
+  if(pause)
+    SNDCore->MuteAudio();
+  else
+    SNDCore->UnMuteAudio();
+}
+
+void SPU_SetSynchMode(int mode, int method)
+{
+  synchmode = (ESynchMode)mode;
+  if(synchmethod != (ESynchMethod)method)
+  {
+    synchmethod = (ESynchMethod)method;
+    delete synchronizer;
+    //grr does this need to be locked? spu might need a lock method
+    // or maybe not, maybe the platform-specific code that calls this function can deal with it.
+    synchronizer = metaspu_construct(synchmethod);
+  }
+}
+
+void SPU_ClearOutputBuffer()
+{
+  if(SNDCore && SNDCore->ClearBuffer)
+    SNDCore->ClearBuffer();
+}
+
+void SPU_SetVolume(int volume)
+{
+  ::volume = volume;
+  if (SNDCore)
+    SNDCore->SetVolume(volume);
+}
+
+
+void SPU_Reset(void)
+{
+  int i;
+
+  SPU_core->reset();
+
+  //zero - 09-apr-2010: this concerns me, regarding savestate synch.
+  //After 0.9.6, lets experiment with removing it and just properly zapping the spu instead
+  // Reset Registers
+  for (i = 0x400; i < 0x51D; i++)
+    T1WriteByte(MMU.ARM7_REG, i, 0);
+
+  samples = 0;
 }
 
 //------------------------------------------
 
 void SPU_struct::reset()
 {
-	memset(&this->sndbuf[0], 0, bufsize * 2 * 4);
-	memset(&this->outbuf[0], 0, bufsize * 2 * 2);
-
-	memset(this->channels, 0, sizeof(channel_struct) * 16);
-
-	reconstruct(&this->regs);
-
-	for (int i = 0; i < 16; ++i)
-		this->channels[i].num = i;
-}
-
-SPU_struct::SPU_struct(int Buffersize) : bufpos(0), buflength(0), sndbuf(new int32_t[Buffersize * 2]), outbuf(new int16_t[Buffersize * 2]), bufsize(Buffersize)
-{
-	this->reset();
-}
-
-void SPU_DeInit()
-{
-	if (SNDCore)
-		SNDCore->DeInit();
-	SNDCore = nullptr;
-
-	SPU_core.reset();
-	SPU_user.reset();
+  memset(sndbuf,0,bufsize*2*4);
+  memset(outbuf,0,bufsize*2*2);
+
+  memset((void *)channels, 0, sizeof(channel_struct) * 16);
+
+  reconstruct(&regs);
+
+  for(int i = 0; i < 16; i++)
+  {
+    channels[i].num = i;
+  }
+}
+
+SPU_struct::SPU_struct(int buffersize)
+  : bufpos(0)
+  , buflength(0)
+  , sndbuf(0)
+  , outbuf(0)
+    , bufsize(buffersize)
+{
+  sndbuf = new s32[buffersize*2];
+  outbuf = new s16[buffersize*2];
+  reset();
+}
+
+SPU_struct::~SPU_struct()
+{
+  if(sndbuf) delete[] sndbuf;
+  if(outbuf) delete[] outbuf;
+}
+
+void SPU_DeInit(void)
+{
+  if(SNDCore)
+    SNDCore->DeInit();
+  SNDCore = 0;
+
+  delete SPU_core; SPU_core=0;
 }
 
 //////////////////////////////////////////////////////////////////////////////
 
 void SPU_struct::ShutUp()
 {
-	for (int i = 0; i < 16; ++i)
-		this->channels[i].status = CHANSTAT_STOPPED;
-}
-
-static inline void adjust_channel_timer(channel_struct *chan)
-{
-	chan->sampinc = (ARM7_CLOCK / (DESMUME_SAMPLE_RATE * 2)) / (0x10000 - chan->timer);
+  for(int i=0;i<16;i++)
+    channels[i].status = CHANSTAT_STOPPED;
+}
+
+static FORCEINLINE void adjust_channel_timer(channel_struct *chan)
+{
+  chan->sampinc = (((double)ARM7_CLOCK) / (DESMUME_SAMPLE_RATE * 2)) / (double)(0x10000 - chan->timer);
 }
 
 void SPU_struct::KeyProbe(int chan_num)
 {
-	channel_struct &thischan = this->channels[chan_num];
-	if (thischan.status == CHANSTAT_STOPPED)
-	{
-		if (thischan.keyon && this->regs.masteren)
-			this->KeyOn(chan_num);
-	}
-	else if (thischan.status == CHANSTAT_PLAY)
-	{
-		if (!thischan.keyon || !this->regs.masteren)
-			this->KeyOff(chan_num);
-	}
+  channel_struct &thischan = channels[chan_num];
+  if(thischan.status == CHANSTAT_STOPPED)
+  {
+    if(thischan.keyon && regs.masteren)
+      KeyOn(chan_num);
+  }
+  else if(thischan.status == CHANSTAT_PLAY)
+  {
+    if(!thischan.keyon || !regs.masteren)
+      KeyOff(chan_num);
+  }
 }
 
 void SPU_struct::KeyOff(int channel)
 {
-	//printf("keyoff%d\n",channel);
-	channel_struct &thischan = this->channels[channel];
-	thischan.status = CHANSTAT_STOPPED;
+  channel_struct &thischan = channels[channel];
+  thischan.status = CHANSTAT_STOPPED;
 }
 
 void SPU_struct::KeyOn(int channel)
 {
-	channel_struct &thischan = this->channels[channel];
-	thischan.status = CHANSTAT_PLAY;
-
-	thischan.totlength = thischan.length + thischan.loopstart;
-	adjust_channel_timer(&thischan);
-
-	//printf("keyon %d totlength:%d\n",channel,thischan.totlength);
-
-	//LOG("Channel %d key on: vol = %d, datashift = %d, hold = %d, pan = %d, waveduty = %d, repeat = %d, format = %d, source address = %07X,"
-	//		"timer = %04X, loop start = %04X, length = %06X, MMU.ARM7_REG[0x501] = %02X\n", channel, chan->vol, chan->datashift, chan->hold,
-	//		chan->pan, chan->waveduty, chan->repeat, chan->format, chan->addr, chan->timer, chan->loopstart, chan->length, T1ReadByte(MMU.ARM7_REG, 0x501));
-
-	switch (thischan.format)
-	{
-		case 0: // 8-bit
-			//hischan.loopstart = thischan.loopstart << 2;
-			//hischan.length = (thischan.length << 2) + thischan.loopstart;
-			thischan.sampcnt = -3;
-			break;
-		case 1: // 16-bit
-			//thischan.loopstart = thischan.loopstart << 1;
-			//thischan.length = (thischan.length << 1) + thischan.loopstart;
-			thischan.sampcnt = -3;
-			break;
-		case 2: // ADPCM
-			thischan.pcm16b = read16(thischan.addr);
-			thischan.pcm16b_last = thischan.pcm16b;
-			thischan.index = read08(thischan.addr + 2) & 0x7F;
-			thischan.lastsampcnt = 7;
-			thischan.sampcnt = -3;
-			thischan.loop_index = K_ADPCM_LOOPING_RECOVERY_INDEX;
-			//thischan.loopstart = thischan.loopstart << 3;
-			//hischan.length = (thischan.length << 3) + thischan.loopstart;
-			break;
-		case 3: // PSG
-			thischan.sampcnt = -1;
-			thischan.x = 0x7FFF;
-	}
-
-	thischan.double_totlength_shifted = thischan.totlength << format_shift[thischan.format];
-
-	if (thischan.format != 3 && fEqual(thischan.double_totlength_shifted, 0.0))
-	{
-		printf("INFO: Stopping channel %d due to zero length\n", channel);
-		thischan.status = CHANSTAT_STOPPED;
-	}
+  channel_struct &thischan = channels[channel];
+  thischan.status = CHANSTAT_PLAY;
+
+  thischan.totlength = thischan.length + thischan.loopstart;
+  adjust_channel_timer(&thischan);
+
+  switch(thischan.format)
+  {
+    case 0: // 8-bit
+      thischan.sampcnt = -3;
+      break;
+    case 1: // 16-bit
+      thischan.sampcnt = -3;
+      break;
+    case 2: // ADPCM
+      {
+        thischan.pcm16b = (s16)read16(thischan.addr);
+        thischan.pcm16b_last = thischan.pcm16b;
+        thischan.index = read08(thischan.addr + 2) & 0x7F;;
+        thischan.lastsampcnt = 7;
+        thischan.sampcnt = -3;
+        thischan.loop_index = K_ADPCM_LOOPING_RECOVERY_INDEX;
+        break;
+      }
+    case 3: // PSG
+      {
+        thischan.sampcnt = -1;
+        thischan.x = 0x7FFF;
+        break;
+      }
+    default: break;
+  }
+
+  thischan.double_totlength_shifted = (double)(thischan.totlength << format_shift[thischan.format]);
+
+  if(thischan.format != 3)
+  {
+    if(thischan.double_totlength_shifted == 0)
+    {
+      thischan.status = CHANSTAT_STOPPED;
+    }
+  }
 }
 
 //////////////////////////////////////////////////////////////////////////////
 
-template<typename T> static inline void SETBYTE(uint32_t which, T &oldval, uint8_t newval) { oldval = (oldval & (~(0xFF << (which * 8)))) | (newval << (which * 8)); }
-static inline uint8_t GETBYTE(uint32_t which, uint32_t val) { return (val >> (which * 8)) & 0xFF; }
-
-uint8_t SPU_ReadByte(uint32_t addr)
-{
-	addr &= 0xFFF;
-	return SPU_core->ReadByte(addr);
-}
-uint16_t SPU_ReadWord(uint32_t addr)
-{
-	addr &= 0xFFF;
-	return SPU_core->ReadWord(addr);
-}
-uint32_t SPU_ReadLong(uint32_t addr)
-{
-	addr &= 0xFFF;
-	return SPU_core->ReadLong(addr);
-}
-
-uint16_t SPU_struct::ReadWord(uint32_t addr)
-{
-	return this->ReadByte(addr) | (this->ReadByte(addr + 1) << 8);
-}
-
-uint32_t SPU_struct::ReadLong(uint32_t addr)
-{
-	return this->ReadByte(addr) | (this->ReadByte(addr + 1) << 8) | (this->ReadByte(addr + 2) << 16) | (ReadByte(addr + 3) << 24);
-}
-
-uint8_t SPU_struct::ReadByte(uint32_t addr)
-{
-	switch (addr)
-	{
-		// SOUNDCNT
-		case 0x500:
-			return this->regs.mastervol;
-		case 0x501:
-			return this->regs.ctl_left | (this->regs.ctl_right << 2) | (this->regs.ctl_ch1bypass << 4) | (this->regs.ctl_ch3bypass << 5) | (this->regs.masteren << 7);
-		case 0x502:
-		case 0x503:
-			return 0;
-
-		// SOUNDBIAS
-		case 0x504:
-			return this->regs.soundbias & 0xFF;
-		case 0x505:
-			return (this->regs.soundbias >> 8) & 0xFF;
-		case 0x506:
-		case 0x507:
-			return 0;
-
-		// SNDCAP0CNT/SNDCAP1CNT
-		case 0x508:
-		case 0x509:
-		{
-			uint32_t which = addr - 0x508;
-			return this->regs.cap[which].add | (this->regs.cap[which].source << 1) | (this->regs.cap[which].oneshot << 2) | (this->regs.cap[which].bits8 << 3)
-				//| (regs.cap[which].active<<7); //? which is right? need test
-				| (this->regs.cap[which].runtime.running << 7);
-		}
-
-		// SNDCAP0DAD
-		case 0x510:
-			return GETBYTE(0, this->regs.cap[0].dad);
-		case 0x511:
-			return GETBYTE(1, this->regs.cap[0].dad);
-		case 0x512:
-			return GETBYTE(2, this->regs.cap[0].dad);
-		case 0x513:
-			return GETBYTE(3, this->regs.cap[0].dad);
-
-		// SNDCAP0LEN
-		case 0x514:
-			return GETBYTE(0, this->regs.cap[0].len);
-		case 0x515:
-			return GETBYTE(1, this->regs.cap[0].len);
-		case 0x516:
-		case 0x517:
-			return 0; //not used
-
-		// SNDCAP1DAD
-		case 0x518:
-			return GETBYTE(0, this->regs.cap[1].dad);
-		case 0x519:
-			return GETBYTE(1, this->regs.cap[1].dad);
-		case 0x51A:
-			return GETBYTE(2, this->regs.cap[1].dad);
-		case 0x51B:
-			return GETBYTE(3, this->regs.cap[1].dad);
-
-		// SNDCAP1LEN
-		case 0x51C:
-			return GETBYTE(0, this->regs.cap[1].len);
-		case 0x51D:
-			return GETBYTE(1, this->regs.cap[1].len);
-		case 0x51E:
-		case 0x51F:
-			return 0; //not used
-
-		default:
-		{
-			// individual channel regs
-
-			uint32_t chan_num = (addr >> 4) & 0xF;
-			if (chan_num > 0xF)
-				return 0;
-			channel_struct &thischan = this->channels[chan_num];
-
-			switch (addr & 0xF)
-			{
-				case 0x0:
-					return thischan.vol;
-				case 0x1:
-				{
-					uint8_t ret = thischan.datashift;
-					if (ret == 4)
-						ret = 3;
-					ret |= thischan.hold << 7;
-					return ret;
-				}
-				case 0x2:
-					return thischan.pan;
-				case 0x3:
-					return thischan.waveduty | (thischan.repeat << 3) | (thischan.format << 5) | (thischan.status == CHANSTAT_PLAY ? 0x80 : 0);
-				case 0x4:
-					return 0; //return GETBYTE(0, thischan.addr); //not readable
-				case 0x5:
-					return 0; //return GETBYTE(1, thischan.addr); //not readable
-				case 0x6:
-					return 0; //return GETBYTE(2, thischan.addr); //not readable
-				case 0x7:
-					return 0; //return GETBYTE(3, thischan.addr); //not readable
-				case 0x8:
-					return GETBYTE(0, thischan.timer);
-				case 0x9:
-					return GETBYTE(1, thischan.timer);
-				case 0xA:
-					return GETBYTE(0, thischan.loopstart);
-				case 0xB:
-					return GETBYTE(1, thischan.loopstart);
-				case 0xC:
-					return 0; //return GETBYTE(0, thischan.length); //not readable
-				case 0xD:
-					return 0; //return GETBYTE(1, thischan.length); //not readable
-				case 0xE:
-					return 0; //return GETBYTE(2, thischan.length); //not readable
-				case 0xF:
-					return 0; //return GETBYTE(3, thischan.length); //not readable
-				default:
-					return 0; //impossible
-			} // switch on individual channel regs
-		} // default case
-	} // switch on address
+u8 SPU_struct::ReadByte(u32 addr)
+{
+  //individual channel regs
+  if ((addr & 0x0F00) == 0x0400)
+  {
+    u32 chan_num = (addr >> 4) & 0xF;
+    const channel_struct& thischan = channels[chan_num];
+
+    switch (addr & 0xF)
+    {
+      case 0x0: return thischan.vol;
+      case 0x1: return (thischan.volumeDiv | (thischan.hold << 7));
+      case 0x2: return thischan.pan;
+      case 0x3: return (	thischan.waveduty
+                    | (thischan.repeat << 3)
+                    | (thischan.format << 5)
+                    | ((thischan.status == CHANSTAT_PLAY)?0x80:0)
+                    );
+      case 0x8: return thischan.timer >> 0;
+      case 0x9: return thischan.timer >> 8;
+      case 0xA: return thischan.loopstart >> 0;
+      case 0xB: return thischan.loopstart >> 8;
+    }
+    return 0;
+  }
+
+  switch(addr)
+  {
+    //SOUNDCNT
+    case 0x500: return regs.mastervol;
+    case 0x501: return (regs.ctl_left
+                    | (regs.ctl_right << 2)
+                    | (regs.ctl_ch1bypass << 4)
+                    | (regs.ctl_ch3bypass << 5)
+                    | (regs.masteren << 7)
+                    );
+
+                //SOUNDBIAS
+    case 0x504: return regs.soundbias >> 0;
+    case 0x505: return regs.soundbias >> 8;
+
+                //SNDCAP0CNT/SNDCAP1CNT
+    case 0x508:
+    case 0x509:
+                {
+                  u32 which = (addr - 0x508);
+                  return regs.cap[which].add
+                    | (regs.cap[which].source << 1)
+                    | (regs.cap[which].oneshot << 2)
+                    | (regs.cap[which].bits8 << 3)
+                    | (regs.cap[which].runtime.running << 7);
+                }
+
+                //SNDCAP0DAD
+    case 0x510: return regs.cap[0].dad >> 0;
+    case 0x511: return regs.cap[0].dad >> 8;
+    case 0x512: return regs.cap[0].dad >> 16;
+    case 0x513: return regs.cap[0].dad >> 24;
+
+                //SNDCAP0LEN
+    case 0x514: return regs.cap[0].len >> 0;
+    case 0x515: return regs.cap[0].len >> 8;
+
+                //SNDCAP1DAD
+    case 0x518: return regs.cap[1].dad >> 0;
+    case 0x519: return regs.cap[1].dad >> 8;
+    case 0x51A: return regs.cap[1].dad >> 16;
+    case 0x51B: return regs.cap[1].dad >> 24;
+
+                //SNDCAP1LEN
+    case 0x51C: return regs.cap[1].len >> 0;
+    case 0x51D: return regs.cap[1].len >> 8;
+  } //switch on address
+
+  return 0;
+}
+
+u16 SPU_struct::ReadWord(u32 addr)
+{
+  //individual channel regs
+  if ((addr & 0x0F00) == 0x0400)
+  {
+    u32 chan_num = (addr >> 4) & 0xF;
+    const channel_struct& thischan = channels[chan_num];
+
+    switch (addr & 0xF)
+    {
+      case 0x0: return	(thischan.vol
+                    | (thischan.volumeDiv << 8)
+                    | (thischan.hold << 15)
+                    );
+      case 0x2: return	(thischan.pan
+                    | (thischan.waveduty << 8)
+                    | (thischan.repeat << 11)
+                    | (thischan.format << 13)
+                    | ((thischan.status == CHANSTAT_PLAY)?(1 << 15):0)
+                    );
+      case 0x8: return thischan.timer;
+      case 0xA: return thischan.loopstart;
+    } //switch on individual channel regs
+    return 0;
+  }
+
+  switch(addr)
+  {
+    //SOUNDCNT
+    case 0x500: return	(regs.mastervol
+                    | (regs.ctl_left << 8)
+                    | (regs.ctl_right << 10)
+                    | (regs.ctl_ch1bypass << 12)
+                    | (regs.ctl_ch3bypass << 13)
+                    | (regs.masteren << 15)
+                    );
+
+                //SOUNDBIAS
+    case 0x504: return regs.soundbias;
+
+                //SNDCAP0CNT/SNDCAP1CNT
+    case 0x508:
+                {
+                  u8 val0 =	regs.cap[0].add
+                    | (regs.cap[0].source << 1)
+                    | (regs.cap[0].oneshot << 2)
+                    | (regs.cap[0].bits8 << 3)
+                    | (regs.cap[0].runtime.running << 7);
+                  u8 val1 =	regs.cap[1].add
+                    | (regs.cap[1].source << 1)
+                    | (regs.cap[1].oneshot << 2)
+                    | (regs.cap[1].bits8 << 3)
+                    | (regs.cap[1].runtime.running << 7);
+                  return (u16)(val0 | (val1 << 8));
+                }
+
+                //SNDCAP0DAD
+    case 0x510: return regs.cap[0].dad >> 0;
+    case 0x512: return regs.cap[0].dad >> 16;
+
+                //SNDCAP0LEN
+    case 0x514: return regs.cap[0].len;
+
+                //SNDCAP1DAD
+    case 0x518: return regs.cap[1].dad >> 0;
+    case 0x51A: return regs.cap[1].dad >> 16;
+
+                //SNDCAP1LEN
+    case 0x51C: return regs.cap[1].len;
+  } //switch on address
+
+  return 0;
+}
+
+u32 SPU_struct::ReadLong(u32 addr)
+{
+  //individual channel regs
+  if ((addr & 0x0F00) == 0x0400)
+  {
+    u32 chan_num = (addr >> 4) & 0xF;
+    channel_struct &thischan=channels[chan_num];
+
+    switch (addr & 0xF)
+    {
+      case 0x0: return	(thischan.vol
+                    | (thischan.volumeDiv << 8)
+                    | (thischan.hold << 15)
+                    | (thischan.pan << 16)
+                    | (thischan.waveduty << 24)
+                    | (thischan.repeat << 27)
+                    | (thischan.format << 29)
+                    | ((thischan.status == CHANSTAT_PLAY)?(1 << 31):0)
+                    );
+      case 0x8: return (thischan.timer | (thischan.loopstart << 16));
+    } //switch on individual channel regs
+    return 0;
+  }
+
+  switch(addr)
+  {
+    //SOUNDCNT
+    case 0x500: return	(regs.mastervol
+                    | (regs.ctl_left << 8)
+                    | (regs.ctl_right << 10)
+                    | (regs.ctl_ch1bypass << 12)
+                    | (regs.ctl_ch3bypass << 13)
+                    | (regs.masteren << 15)
+                    );
+
+                //SOUNDBIAS
+    case 0x504: return (u32)regs.soundbias;
+
+                //SNDCAP0CNT/SNDCAP1CNT
+    case 0x508:
+                {
+                  u8 val0 =	regs.cap[0].add
+                    | (regs.cap[0].source << 1)
+                    | (regs.cap[0].oneshot << 2)
+                    | (regs.cap[0].bits8 << 3)
+                    | (regs.cap[0].runtime.running << 7);
+                  u8 val1 =	regs.cap[1].add
+                    | (regs.cap[1].source << 1)
+                    | (regs.cap[1].oneshot << 2)
+                    | (regs.cap[1].bits8 << 3)
+                    | (regs.cap[1].runtime.running << 7);
+                  return (u32)(val0 | (val1 << 8));
+                }
+
+                //SNDCAP0DAD
+    case 0x510: return regs.cap[0].dad;
+
+                //SNDCAP0LEN
+    case 0x514: return (u32)regs.cap[0].len;
+
+                //SNDCAP1DAD
+    case 0x518: return regs.cap[1].dad;
+
+                //SNDCAP1LEN
+    case 0x51C: return (u32)regs.cap[1].len;
+  } //switch on address
+
+  return 0;
 }
 
 SPUFifo::SPUFifo()
 {
-	this->reset();
+  reset();
 }
 
 void SPUFifo::reset()
 {
-	this->head = this->tail = this->size = 0;
-}
-
-void SPUFifo::enqueue(int16_t val)
-{
-	if (this->size == 16)
-		return;
-	this->buffer[this->tail] = val;
-	++this->tail;
-	this->tail &= 15;
-	++this->size;
-}
-
-int16_t SPUFifo::dequeue()
-{
-	if (!this->size)
-		return 0;
-	++this->head;
-	this->head &= 15;
-	int16_t ret = this->buffer[this->head];
-	--this->size;
-	return ret;
+  head = tail = size = 0;
+}
+
+void SPUFifo::enqueue(s16 val)
+{
+  if(size==16) return;
+  buffer[tail] = val;
+  tail++;
+  tail &= 15;
+  size++;
+}
+
+s16 SPUFifo::dequeue()
+{
+  if(size==0) return 0;
+  head++;
+  head &= 15;
+  s16 ret = buffer[head];
+  size--;
+  return ret;
 }
 
 void SPU_struct::ProbeCapture(int which)
 {
-	// VERY UNTESTED -- HOW MUCH OF THIS RESETS, AND WHEN?
-
-	if (!this->regs.cap[which].active)
-	{
-		this->regs.cap[which].runtime.running = 0;
-		return;
-	}
-
-	REGS::CAP &cap = this->regs.cap[which];
-	cap.runtime.running = 1;
-	cap.runtime.curdad = cap.dad;
-	uint32_t len = cap.len;
-	if (!len)
-		len = 1;
-	cap.runtime.maxdad = cap.dad + len * 4;
-	cap.runtime.sampcnt = 0;
-	cap.runtime.fifo.reset();
-}
-
-void SPU_struct::WriteByte(uint32_t addr, uint8_t val)
-{
-	switch (addr)
-	{
-		// SOUNDCNT
-		case 0x500:
-			this->regs.mastervol = val & 0x7F;
-			break;
-		case 0x501:
-			this->regs.ctl_left = val & 3;
-			this->regs.ctl_right = (val >> 2) & 3;
-			this->regs.ctl_ch1bypass = (val >> 4) & 1;
-			this->regs.ctl_ch3bypass = (val >> 5) & 1;
-			this->regs.masteren = (val >> 7) & 1;
-			for (int i = 0; i < 16; ++i)
-				this->KeyProbe(i);
-			break;
-		case 0x502:
-		case 0x503:
-			break; // not used
-
-		// SOUNDBIAS
-		case 0x504:
-			SETBYTE(0, this->regs.soundbias, val);
-			break;
-		case 0x505:
-			SETBYTE(1, this->regs.soundbias, val & 3);
-			break;
-		case 0x506:
-		case 0x507:
-			break; // these dont answer anyway
-
-		// SNDCAP0CNT/SNDCAP1CNT
-		case 0x508:
-		case 0x509:
-		{
-			uint32_t which = addr - 0x508;
-			this->regs.cap[which].add = static_cast<uint8_t>(BIT0(val));
-			this->regs.cap[which].source = static_cast<uint8_t>(BIT1(val));
-			this->regs.cap[which].oneshot = static_cast<uint8_t>(BIT2(val));
-			this->regs.cap[which].bits8 = static_cast<uint8_t>(BIT3(val));
-			this->regs.cap[which].active = static_cast<uint8_t>(BIT7(val));
-			this->ProbeCapture(which);
-			break;
-		}
-
-		// SNDCAP0DAD
-		case 0x510:
-			SETBYTE(0, this->regs.cap[0].dad, val);
-			break;
-		case 0x511:
-			SETBYTE(1, this->regs.cap[0].dad, val);
-			break;
-		case 0x512:
-			SETBYTE(2, this->regs.cap[0].dad, val);
-			break;
-		case 0x513:
-			SETBYTE(3, this->regs.cap[0].dad, val & 7);
-			break;
-
-		// SNDCAP0LEN
-		case 0x514:
-			SETBYTE(0, this->regs.cap[0].len, val);
-			break;
-		case 0x515:
-			SETBYTE(1, this->regs.cap[0].len, val);
-			break;
-		case 0x516:
-		case 0x517:
-			break; // not used
-
-		// SNDCAP1DAD
-		case 0x518:
-			SETBYTE(0, this->regs.cap[1].dad, val);
-			break;
-		case 0x519:
-			SETBYTE(1, this->regs.cap[1].dad, val);
-			break;
-		case 0x51A:
-			SETBYTE(2, this->regs.cap[1].dad, val);
-			break;
-		case 0x51B:
-			SETBYTE(3, this->regs.cap[1].dad, val & 7);
-			break;
-
-		// SNDCAP1LEN
-		case 0x51C:
-			SETBYTE(0, this->regs.cap[1].len, val);
-			break;
-		case 0x51D:
-			SETBYTE(1, this->regs.cap[1].len, val);
-			break;
-		case 0x51E:
-		case 0x51F:
-			break; // not used
-
-		default:
-		{
-			// individual channel regs
-
-			uint32_t chan_num = (addr >> 4) & 0xF;
-			if (chan_num>0xF)
-				break;
-			channel_struct &thischan = this->channels[chan_num];
-
-			switch (addr & 0xF)
-			{
-				case 0x0:
-					thischan.vol = val & 0x7F;
-					break;
-				case 0x1:
-					thischan.datashift = val & 0x3;
-					if (thischan.datashift == 3)
-						thischan.datashift = 4;
-					thischan.hold = (val >> 7) & 0x1;
-					break;
-				case 0x2:
-					thischan.pan = val & 0x7F;
-					break;
-				case 0x3:
-					thischan.waveduty = val & 0x7;
-					thischan.repeat = (val >> 3) & 0x3;
-					thischan.format = (val >> 5) & 0x3;
-					thischan.keyon = static_cast<uint8_t>(BIT7(val));
-					this->KeyProbe(chan_num);
-					break;
-				case 0x4:
-					SETBYTE(0, thischan.addr, val);
-					break;
-				case 0x5:
-					SETBYTE(1, thischan.addr, val);
-					break;
-				case 0x6:
-					SETBYTE(2, thischan.addr, val);
-					break;
-				case 0x7:
-					SETBYTE(3, thischan.addr, val & 0x7);
-					break; // only 27 bits of this register are used
-				case 0x8:
-					SETBYTE(0, thischan.timer, val);
-					adjust_channel_timer(&thischan);
-					break;
-				case 0x9:
-					SETBYTE(1, thischan.timer, val);
-					adjust_channel_timer(&thischan);
-					break;
-				case 0xA:
-					SETBYTE(0, thischan.loopstart, val);
-					break;
-				case 0xB:
-					SETBYTE(1, thischan.loopstart, val);
-					break;
-				case 0xC:
-					SETBYTE(0, thischan.length, val);
-					break;
-				case 0xD:
-					SETBYTE(1, thischan.length, val);
-					break;
-				case 0xE:
-					SETBYTE(2, thischan.length, val & 0x3F);
-					break; // only 22 bits of this register are used
-				case 0xF:
-					SETBYTE(3, thischan.length, 0);
-					break;
-			} // switch on individual channel regs
-		} // default case
-	} // switch on address
-}
-
-void SPU_WriteByte(uint32_t addr, uint8_t val)
-{
-	//printf("%08X: chan:%02X reg:%02X val:%02X\n",addr,(addr>>4)&0xF,addr&0xF,val);
-	addr &= 0xFFF;
-
-	SPU_core->WriteByte(addr, val);
-	if (SPU_user)
-		SPU_user->WriteByte(addr, val);
+  //VERY UNTESTED -- HOW MUCH OF THIS RESETS, AND WHEN?
+
+  if(!regs.cap[which].active)
+  {
+    regs.cap[which].runtime.running = 0;
+    return;
+  }
+
+  REGS::CAP &cap = regs.cap[which];
+  cap.runtime.running = 1;
+  cap.runtime.curdad = cap.dad;
+  u32 len = cap.len;
+  if(len==0) len=1;
+  cap.runtime.maxdad = cap.dad + len*4;
+  cap.runtime.sampcnt = 0;
+  cap.runtime.fifo.reset();
+}
+
+void SPU_struct::WriteByte(u32 addr, u8 val)
+{
+  //individual channel regs
+  if ((addr & 0x0F00) == 0x0400)
+  {
+    u8 chan_num = (addr >> 4) & 0xF;
+    channel_struct &thischan = channels[chan_num];
+
+    switch (addr & 0x000F)
+    {
+      case 0x0: thischan.vol = (val & 0x7F); break;
+      case 0x1:
+                thischan.volumeDiv = (val & 0x03);
+                thischan.hold = (val >> 7) & 0x01;
+                break;
+      case 0x2: thischan.pan = (val & 0x7F); break;
+      case 0x3:
+                thischan.waveduty = (val & 0x07);
+                thischan.repeat = (val >> 3) & 0x03;
+                thischan.format = (val >> 5) & 0x03;
+                thischan.keyon = (val >> 7) & 0x01;
+                KeyProbe(chan_num);
+                break;
+      case 0x4: thischan.addr &= 0xFFFFFF00; thischan.addr |= (val & 0xFC); break;
+      case 0x5: thischan.addr &= 0xFFFF00FF; thischan.addr |= (val << 8); break;
+      case 0x6: thischan.addr &= 0xFF00FFFF; thischan.addr |= (val << 16); break;
+      case 0x7: thischan.addr &= 0x00FFFFFF; thischan.addr |= ((val&7) << 24); break; //only 27 bits of this register are used
+      case 0x8: thischan.timer &= 0xFF00; thischan.timer |= (val << 0); adjust_channel_timer(&thischan); break;
+      case 0x9: thischan.timer &= 0x00FF; thischan.timer |= (val << 8); adjust_channel_timer(&thischan); break;
+
+      case 0xA: thischan.loopstart &= 0xFF00; thischan.loopstart |= (val << 0); break;
+      case 0xB: thischan.loopstart &= 0x00FF; thischan.loopstart |= (val << 8); break;
+      case 0xC: thischan.length &= 0xFFFFFF00; thischan.length |= (val << 0); break;
+      case 0xD: thischan.length &= 0xFFFF00FF; thischan.length |= (val << 8); break;
+      case 0xE: thischan.length &= 0xFF00FFFF; thischan.length |= ((val & 0x3F) << 16); //only 22 bits of this register are used
+      case 0xF: break;
+
+    } //switch on individual channel regs
+
+    return;
+  }
+
+  switch(addr)
+  {
+    //SOUNDCNT
+    case 0x500: regs.mastervol = (val & 0x7F); break;
+    case 0x501:
+                regs.ctl_left  = (val >> 0) & 3;
+                regs.ctl_right = (val >> 2) & 3;
+                regs.ctl_ch1bypass = (val >> 4) & 1;
+                regs.ctl_ch3bypass = (val >> 5) & 1;
+                regs.masteren = (val >> 7) & 1;
+                break;
+
+                //SOUNDBIAS
+    case 0x504: regs.soundbias &= 0xFF00; regs.soundbias |= (val << 0); break;
+    case 0x505: regs.soundbias &= 0x00FF; regs.soundbias |= ((val&3) << 8); break;
+
+                //SNDCAP0CNT/SNDCAP1CNT
+    case 0x508:
+    case 0x509:
+                {
+                  u32 which = (addr - 0x508);
+                  regs.cap[which].add = BIT0(val);
+                  regs.cap[which].source = BIT1(val);
+                  regs.cap[which].oneshot = BIT2(val);
+                  regs.cap[which].bits8 = BIT3(val);
+                  regs.cap[which].active = BIT7(val);
+                  ProbeCapture(which);
+                  break;
+                }
+
+                //SNDCAP0DAD
+    case 0x510: regs.cap[0].dad &= 0xFFFFFF00; regs.cap[0].dad |= (val & 0xFC); break;
+    case 0x511: regs.cap[0].dad &= 0xFFFF00FF; regs.cap[0].dad |= (val << 8); break;
+    case 0x512: regs.cap[0].dad &= 0xFF00FFFF; regs.cap[0].dad |= (val << 16); break;
+    case 0x513: regs.cap[0].dad &= 0x00FFFFFF; regs.cap[0].dad |= ((val&7) << 24); break;
+
+                //SNDCAP0LEN
+    case 0x514: regs.cap[0].len &= 0xFF00; regs.cap[0].len |= (val << 0); break;
+    case 0x515: regs.cap[0].len &= 0x00FF; regs.cap[0].len |= (val << 8); break;
+
+                //SNDCAP1DAD
+    case 0x518: regs.cap[1].dad &= 0xFFFFFF00; regs.cap[1].dad |= (val & 0xFC); break;
+    case 0x519: regs.cap[1].dad &= 0xFFFF00FF; regs.cap[1].dad |= (val << 8); break;
+    case 0x51A: regs.cap[1].dad &= 0xFF00FFFF; regs.cap[1].dad |= (val << 16); break;
+    case 0x51B: regs.cap[1].dad &= 0xFF000000; regs.cap[1].dad |= ((val&7) << 24); break;
+
+                //SNDCAP1LEN
+    case 0x51C: regs.cap[1].len &= 0xFF00; regs.cap[1].len |= (val << 0); break;
+    case 0x51D: regs.cap[1].len &= 0x00FF; regs.cap[1].len |= (val << 8); break;
+  } //switch on address
+}
+
+void SPU_struct::WriteWord(u32 addr, u16 val)
+{
+  //individual channel regs
+  if ((addr & 0x0F00) == 0x0400)
+  {
+    u32 chan_num = (addr >> 4) & 0xF;
+    channel_struct &thischan=channels[chan_num];
+
+    switch (addr & 0xF)
+    {
+      case 0x0:
+        thischan.vol = (val & 0x7F);
+        thischan.volumeDiv = (val >> 8) & 0x3;
+        thischan.hold = (val >> 15) & 0x1;
+        break;
+      case 0x2:
+        thischan.pan = (val & 0x7F);
+        thischan.waveduty = (val >> 8) & 0x7;
+        thischan.repeat = (val >> 11) & 0x3;
+        thischan.format = (val >> 13) & 0x3;
+        thischan.keyon = (val >> 15) & 0x1;
+        KeyProbe(chan_num);
+        break;
+      case 0x4: thischan.addr &= 0xFFFF0000; thischan.addr |= (val & 0xFFFC); break;
+      case 0x6: thischan.addr &= 0x0000FFFF; thischan.addr |= ((val & 0x07FF) << 16); break;
+      case 0x8: thischan.timer = val; adjust_channel_timer(&thischan); break;
+      case 0xA: thischan.loopstart = val; break;
+      case 0xC: thischan.length &= 0xFFFF0000; thischan.length |= (val << 0); break;
+      case 0xE: thischan.length &= 0x0000FFFF; thischan.length |= ((val & 0x003F) << 16); break;
+    } //switch on individual channel regs
+    return;
+  }
+
+  switch (addr)
+  {
+    //SOUNDCNT
+    case 0x500:
+      regs.mastervol = (val & 0x7F);
+      regs.ctl_left  = (val >> 8) & 0x03;
+      regs.ctl_right = (val >> 10) & 0x03;
+      regs.ctl_ch1bypass = (val >> 12) & 0x01;
+      regs.ctl_ch3bypass = (val >> 13) & 0x01;
+      regs.masteren = (val >> 15) & 0x01;
+      for(u8 i=0; i<16; i++)
+        KeyProbe(i);
+      break;
+
+      //SOUNDBIAS
+    case 0x504: regs.soundbias = (val & 0x3FF); break;
+
+                //SNDCAP0CNT/SNDCAP1CNT
+    case 0x508:
+                {
+                  regs.cap[0].add = BIT0(val);
+                  regs.cap[0].source = BIT1(val);
+                  regs.cap[0].oneshot = BIT2(val);
+                  regs.cap[0].bits8 = BIT3(val);
+                  regs.cap[0].active = BIT7(val);
+                  ProbeCapture(0);
+
+                  regs.cap[1].add = BIT8(val);
+                  regs.cap[1].source = BIT9(val);
+                  regs.cap[1].oneshot = BIT10(val);
+                  regs.cap[1].bits8 = BIT11(val);
+                  regs.cap[1].active = BIT15(val);
+                  ProbeCapture(1);
+                  break;
+                }
+
+                //SNDCAP0DAD
+    case 0x510: regs.cap[0].dad &= 0xFFFF0000; regs.cap[0].dad |= (val & 0xFFFC); break;
+    case 0x512: regs.cap[0].dad &= 0x0000FFFF; regs.cap[0].dad |= ((val & 0x07FF) << 16); break;
+
+                //SNDCAP0LEN
+    case 0x514: regs.cap[0].len = val; break;
+
+                //SNDCAP1DAD
+    case 0x518: regs.cap[1].dad &= 0xFFFF0000; regs.cap[1].dad |= (val & 0xFFFC); break;
+    case 0x51A: regs.cap[1].dad &= 0x0000FFFF; regs.cap[1].dad |= ((val & 0x07FF) << 16); break;
+
+                //SNDCAP1LEN
+    case 0x51C: regs.cap[1].len = val; break;
+  } //switch on address
+}
+
+void SPU_struct::WriteLong(u32 addr, u32 val)
+{
+  //individual channel regs
+  if ((addr & 0x0F00) == 0x0400)
+  {
+    u32 chan_num = (addr >> 4) & 0xF;
+    channel_struct &thischan=channels[chan_num];
+
+    switch (addr & 0xF)
+    {
+      case 0x0:
+        thischan.vol = val & 0x7F;
+        thischan.volumeDiv = (val >> 8) & 0x3;
+        thischan.hold = (val >> 15) & 0x1;
+        thischan.pan = (val >> 16) & 0x7F;
+        thischan.waveduty = (val >> 24) & 0x7;
+        thischan.repeat = (val >> 27) & 0x3;
+        thischan.format = (val >> 29) & 0x3;
+        thischan.keyon = (val >> 31) & 0x1;
+        KeyProbe(chan_num);
+        break;
+
+      case 0x4: thischan.addr = (val & 0x07FFFFFC); break;
+      case 0x8:
+                thischan.timer = (val & 0xFFFF);
+                thischan.loopstart = ((val >> 16) & 0xFFFF);
+                adjust_channel_timer(&thischan);
+                break;
+
+      case 0xC: thischan.length = (val & 0x003FFFFF); break; //only 22 bits of this register are used
+    } //switch on individual channel regs
+    return;
+  }
+
+  switch(addr)
+  {
+    //SOUNDCNT
+    case 0x500:
+      regs.mastervol = (val & 0x7F);
+      regs.ctl_left  = ((val >> 8) & 3);
+      regs.ctl_right = ((val>>10) & 3);
+      regs.ctl_ch1bypass = ((val >> 12) & 1);
+      regs.ctl_ch3bypass = ((val >> 13) & 1);
+      regs.masteren = ((val >> 15) & 1);
+      for(u8 i=0; i<16; i++)
+        KeyProbe(i);
+      break;
+
+      //SOUNDBIAS
+    case 0x504: regs.soundbias = (val & 0x3FF);
+
+                //SNDCAP0CNT/SNDCAP1CNT
+    case 0x508:
+                regs.cap[0].add = BIT0(val);
+                regs.cap[0].source = BIT1(val);
+                regs.cap[0].oneshot = BIT2(val);
+                regs.cap[0].bits8 = BIT3(val);
+                regs.cap[0].active = BIT7(val);
+                ProbeCapture(0);
+
+                regs.cap[1].add = BIT8(val);
+                regs.cap[1].source = BIT9(val);
+                regs.cap[1].oneshot = BIT10(val);
+                regs.cap[1].bits8 = BIT11(val);
+                regs.cap[1].active = BIT15(val);
+                ProbeCapture(1);
+                break;
+
+                //SNDCAP0DAD
+    case 0x510: regs.cap[0].dad = (val & 0x07FFFFFC); break;
+
+                //SNDCAP0LEN
+    case 0x514: regs.cap[0].len = (val & 0xFFFF); break;
+
+                //SNDCAP1DAD
+    case 0x518: regs.cap[1].dad = (val & 0x07FFFFFC); break;
+
+                //SNDCAP1LEN
+    case 0x51C: regs.cap[1].len = (val & 0xFFFF); break;
+  } //switch on address
 }
 
 //////////////////////////////////////////////////////////////////////////////
 
-void SPU_struct::WriteWord(uint32_t addr, uint16_t val)
-{
-	this->WriteByte(addr, val & 0xFF);
-	this->WriteByte(addr + 1, (val >> 8) & 0xFF);
-}
-
-void SPU_WriteWord(uint32_t addr, uint16_t val)
-{
-	//printf("%08X: chan:%02X reg:%02X val:%04X\n",addr,(addr>>4)&0xF,addr&0xF,val);
-	addr &= 0xFFF;
-
-	SPU_core->WriteWord(addr, val);
-	if (SPU_user)
-		SPU_user->WriteWord(addr, val);
+static FORCEINLINE void FetchPSGData(channel_struct *chan, s32 *data)
+{
+  if (chan->sampcnt < 0)
+  {
+    *data = 0;
+    return;
+  }
+
+  if(chan->num < 8)
+  {
+    *data = 0;
+  }
+  else if(chan->num < 14)
+  {
+    *data = (s32)wavedutytbl[chan->waveduty][(sputrunc(chan->sampcnt)) & 0x7];
+  }
+  else
+  {
+    if(chan->lastsampcnt == sputrunc(chan->sampcnt))
+    {
+      *data = (s32)chan->psgnoise_last;
+      return;
+    }
+
+    u32 max = sputrunc(chan->sampcnt);
+    for(u32 i = chan->lastsampcnt; i < max; i++)
+    {
+      if(chan->x & 0x1)
+      {
+        chan->x = (chan->x >> 1) ^ 0x6000;
+        chan->psgnoise_last = -0x7FFF;
+      }
+      else
+      {
+        chan->x >>= 1;
+        chan->psgnoise_last = 0x7FFF;
+      }
+    }
+
+    chan->lastsampcnt = sputrunc(chan->sampcnt);
+
+    *data = (s32)chan->psgnoise_last;
+  }
 }
 
 //////////////////////////////////////////////////////////////////////////////
 
-void SPU_struct::WriteLong(uint32_t addr, uint32_t val)
-{
-	this->WriteByte(addr,val & 0xFF);
-	this->WriteByte(addr + 1,(val >> 8) & 0xFF);
-	this->WriteByte(addr + 2,(val >> 16) & 0xFF);
-	this->WriteByte(addr + 3,(val >> 24) & 0xFF);
-}
-
-void SPU_WriteLong(uint32_t addr, uint32_t val)
-{
-	//printf("%08X: chan:%02X reg:%02X val:%08X\n",addr,(addr>>4)&0xF,addr&0xF,val);
-	addr &= 0xFFF;
-
-	SPU_core->WriteLong(addr, val);
-	if (SPU_user)
-		SPU_user->WriteLong(addr, val);
+static FORCEINLINE void MixL(SPU_struct* SPU, channel_struct *chan, s32 data)
+{
+  data = spumuldiv7(data, chan->vol) >> volume_shift[chan->volumeDiv];
+  SPU->sndbuf[SPU->bufpos<<1] += data;
+}
+
+static FORCEINLINE void MixR(SPU_struct* SPU, channel_struct *chan, s32 data)
+{
+  data = spumuldiv7(data, chan->vol) >> volume_shift[chan->volumeDiv];
+  SPU->sndbuf[(SPU->bufpos<<1)+1] += data;
+}
+
+static FORCEINLINE void MixLR(SPU_struct* SPU, channel_struct *chan, s32 data)
+{
+  data = spumuldiv7(data, chan->vol) >> volume_shift[chan->volumeDiv];
+  SPU->sndbuf[SPU->bufpos<<1] += spumuldiv7(data, 127 - chan->pan);
+  SPU->sndbuf[(SPU->bufpos<<1)+1] += spumuldiv7(data, chan->pan);
 }
 
 //////////////////////////////////////////////////////////////////////////////
 
-static inline int32_t Interpolate(int32_t a, int32_t b, double ratio, SPUInterpolationMode INTERPOLATE_MODE)
-{
-	double sampleA = static_cast<double>(a);
-	double sampleB = static_cast<double>(b);
-	ratio = ratio - u32floor(ratio);
-
-	switch (INTERPOLATE_MODE)
-	{
-		case SPUInterpolation_Cosine:
-			// Cosine Interpolation Formula:
-			// ratio2 = (1 - cos(ratio * M_PI)) / 2
-			// sampleI = sampleA * (1 - ratio2) + sampleB * ratio2
-			return s32floor((cos_lut[static_cast<unsigned>(ratio * COSINE_INTERPOLATION_RESOLUTION)] * (sampleB - sampleA)) + sampleA);
-
-		case SPUInterpolation_Linear:
-			// Linear Interpolation Formula:
-			// sampleI = sampleA * (1 - ratio) + sampleB * ratio
-			return s32floor((ratio * (sampleB - sampleA)) + sampleA);
-
-		default:
-			break;
-	}
-
-	return a;
+template<int FORMAT> static FORCEINLINE void TestForLoop(SPU_struct *SPU, channel_struct *chan)
+{
+  const int shift = (FORMAT == 0 ? 2 : 1);
+
+  chan->sampcnt += chan->sampinc;
+
+  if (chan->sampcnt > chan->double_totlength_shifted)
+  {
+    // Do we loop? Or are we done?
+    if (chan->repeat == 1)
+    {
+      while (chan->sampcnt > chan->double_totlength_shifted) {
+        chan->sampcnt -= chan->double_totlength_shifted - (double)(chan->loopstart << shift);
+      }
+    }
+    else
+    {
+      SPU->KeyOff(chan->num);
+      SPU->bufpos = SPU->buflength;
+    }
+  }
+}
+
+static FORCEINLINE void TestForLoop2(SPU_struct *SPU, channel_struct *chan)
+{
+  // Minimum length (the sum of PNT+LEN) is 4 words (16 bytes),
+  // smaller values (0..3 words) are causing hang-ups
+  // (busy bit remains set infinite, but no sound output occurs).
+  // fix: 7th Dragon (JP) - http://sourceforge.net/p/desmume/bugs/1357/
+  if (chan->totlength < 4) return;
+
+  chan->sampcnt += chan->sampinc;
+
+  if (chan->sampcnt > chan->double_totlength_shifted)
+  {
+    // Do we loop? Or are we done?
+    if (chan->repeat == 1)
+    {
+      double step = (chan->double_totlength_shifted - (double)(chan->loopstart << 3));
+
+      while (chan->sampcnt > chan->double_totlength_shifted) chan->sampcnt -= step;
+
+      if(chan->loop_index == K_ADPCM_LOOPING_RECOVERY_INDEX)
+      {
+        chan->pcm16b = (s16)read16(chan->addr);
+        chan->index = read08(chan->addr+2) & 0x7F;
+        chan->lastsampcnt = 7;
+      }
+      else
+      {
+        chan->pcm16b = chan->loop_pcm16b;
+        chan->index = chan->loop_index;
+        chan->lastsampcnt = (chan->loopstart << 3);
+      }
+    }
+    else
+    {
+      chan->status = CHANSTAT_STOPPED;
+      SPU->KeyOff(chan->num);
+      SPU->bufpos = SPU->buflength;
+    }
+  }
+}
+
+template<int CHANNELS> FORCEINLINE static void SPU_Mix(SPU_struct* SPU, channel_struct *chan, s32 data)
+{
+  switch(CHANNELS)
+  {
+    case 0: MixL(SPU, chan, data); break;
+    case 1: MixLR(SPU, chan, data); break;
+    case 2: MixR(SPU, chan, data); break;
+  }
+  SPU->lastdata = data;
+}
+
+//WORK
+  template<int FORMAT, int CHANNELS>
+FORCEINLINE static void ____SPU_ChanUpdate(SPU_struct* const SPU, channel_struct* const chan)
+{
+  for (; SPU->bufpos < SPU->buflength; SPU->bufpos++)
+  {
+    if(CHANNELS != -1)
+    {
+      s32 data;
+      if (chan->sampcnt < 0) {
+        data = 0;
+      } else if (FORMAT == 3) {
+        FetchPSGData(chan, &data);
+      } else {
+        const SampleData& sample = sampleCache.getSample(chan->addr, chan->loopstart, chan->length, SampleData::Format(FORMAT));
+        data = sample.sampleAt(chan->sampcnt, IInterpolator::allInterpolators[CommonSettings.spuInterpolationMode]);
+      }
+      SPU_Mix<CHANNELS>(SPU, chan, data);
+    }
+
+    switch(FORMAT) {
+      case 0: case 1: TestForLoop<FORMAT>(SPU, chan); break;
+      case 2: TestForLoop2(SPU, chan); break;
+      case 3: chan->sampcnt += chan->sampinc; break;
+    }
+  }
+}
+
+template<int FORMAT>
+FORCEINLINE static void ___SPU_ChanUpdate(const bool actuallyMix, SPU_struct* const SPU, channel_struct* const chan)
+{
+  if(!actuallyMix)
+    ____SPU_ChanUpdate<FORMAT,-1>(SPU,chan);
+  else if (chan->pan == 0)
+    ____SPU_ChanUpdate<FORMAT,0>(SPU,chan);
+  else if (chan->pan == 127)
+    ____SPU_ChanUpdate<FORMAT,2>(SPU,chan);
+  else
+    ____SPU_ChanUpdate<FORMAT,1>(SPU,chan);
+}
+
+FORCEINLINE static void _SPU_ChanUpdate(const bool actuallyMix, SPU_struct* const SPU, channel_struct* const chan)
+{
+  switch(chan->format)
+  {
+    case 0: ___SPU_ChanUpdate<0>(actuallyMix, SPU, chan); break;
+    case 1: ___SPU_ChanUpdate<1>(actuallyMix, SPU, chan); break;
+    case 2: ___SPU_ChanUpdate<2>(actuallyMix, SPU, chan); break;
+    case 3: ___SPU_ChanUpdate<3>(actuallyMix, SPU, chan); break;
+    default: assert(false);
+  }
+}
+
+//ENTERNEW
+static void SPU_MixAudio_Advanced(bool actuallyMix, SPU_struct *SPU, int length)
+{
+  //the advanced spu function correctly handles all sound control mixing options, as well as capture
+  //this code is not entirely optimal, as it relies on sort of manhandling the core mixing functions
+  //in order to get the results it needs.
+
+  //THIS IS MAX HACKS!!!!
+  //AND NEEDS TO BE REWRITTEN ALONG WITH THE DEEPEST PARTS OF THE SPU
+  //ONCE WE KNOW THAT IT WORKS
+
+  //BIAS gets ignored since our spu is still not bit perfect,
+  //and it doesnt matter for purposes of capture
+
+  //-----------DEBUG CODE
+  bool skipcap = false;
+  //-----------------
+
+  s32 samp0[2] = {0,0};
+
+  //believe it or not, we are going to do this one sample at a time.
+  //like i said, it is slower.
+  for (int samp = 0; samp < length; samp++)
+  {
+    SPU->sndbuf[0] = 0;
+    SPU->sndbuf[1] = 0;
+    SPU->buflength = 1;
+
+    s32 capmix[2] = {0,0};
+    s32 mix[2] = {0,0};
+    s32 chanout[16];
+    s32 submix[32];
+    static int tsamp = 0;
+    ++tsamp;
+
+    //generate each channel, and helpfully mix it at the same time
+    for (int i = 0; i < 16; i++)
+    {
+      channel_struct *chan = &SPU->channels[i];
+
+      if (chan->status == CHANSTAT_PLAY)
+      {
+        SPU->bufpos = 0;
+
+        bool bypass = false;
+        if (i==1 && SPU->regs.ctl_ch1bypass) bypass=true;
+        if (i==3 && SPU->regs.ctl_ch3bypass) bypass=true;
+
+
+        //output to mixer unless we are bypassed.
+        //dont output to mixer if the user muted us
+        bool outputToMix = true;
+        if (CommonSettings.spu_muteChannels[i]) outputToMix = false;
+        if (bypass) outputToMix = false;
+        bool outputToCap = outputToMix;
+        if (CommonSettings.spu_captureMuted && !bypass) outputToCap = true;
+
+        //channels 1 and 3 should probably always generate their audio
+        //internally at least, just in case they get used by the spu output
+        bool domix = outputToCap || outputToMix || i==1 || i==3;
+
+        //clear the output buffer since this is where _SPU_ChanUpdate wants to accumulate things
+        SPU->sndbuf[0] = SPU->sndbuf[1] = 0;
+
+        //get channel's next output sample.
+        _SPU_ChanUpdate(domix, SPU, chan);
+        chanout[i] = SPU->lastdata >> volume_shift[chan->volumeDiv];
+
+        //save the panned results
+        submix[i*2] = SPU->sndbuf[0];
+        submix[i*2+1] = SPU->sndbuf[1];
+
+        //send sample to our capture mix
+        if (outputToCap)
+        {
+          capmix[0] += submix[i*2];
+          capmix[1] += submix[i*2+1];
+        }
+
+        //send sample to our main mixer
+        if (outputToMix)
+        {
+          mix[0] += submix[i*2];
+          mix[1] += submix[i*2+1];
+        }
+      }
+      else
+      {
+        chanout[i] = 0;
+        submix[i*2] = 0;
+        submix[i*2+1] = 0;
+      }
+    } //foreach channel
+
+    s32 mixout[2] = {mix[0],mix[1]};
+    s32 capmixout[2] = {capmix[0],capmix[1]};
+    s32 sndout[2];
+    s32 capout[2];
+
+    //create SPU output
+    switch (SPU->regs.ctl_left)
+    {
+      case SPU_struct::REGS::LOM_LEFT_MIXER: sndout[0] = mixout[0]; break;
+      case SPU_struct::REGS::LOM_CH1: sndout[0] = submix[1*2+0]; break;
+      case SPU_struct::REGS::LOM_CH3: sndout[0] = submix[3*2+0]; break;
+      case SPU_struct::REGS::LOM_CH1_PLUS_CH3: sndout[0] = submix[1*2+0] + submix[3*2+0]; break;
+    }
+    switch (SPU->regs.ctl_right)
+    {
+      case SPU_struct::REGS::ROM_RIGHT_MIXER: sndout[1] = mixout[1]; break;
+      case SPU_struct::REGS::ROM_CH1: sndout[1] = submix[1*2+1]; break;
+      case SPU_struct::REGS::ROM_CH3: sndout[1] = submix[3*2+1]; break;
+      case SPU_struct::REGS::ROM_CH1_PLUS_CH3: sndout[1] = submix[1*2+1] + submix[3*2+1]; break;
+    }
+
+
+    //generate capture output ("capture bugs" from gbatek are not emulated)
+    if (SPU->regs.cap[0].source == 0)
+      capout[0] = capmixout[0]; //cap0 = L-mix
+    else if (SPU->regs.cap[0].add)
+      capout[0] = chanout[0] + chanout[1]; //cap0 = ch0+ch1
+    else capout[0] = chanout[0]; //cap0 = ch0
+
+    if (SPU->regs.cap[1].source == 0)
+      capout[1] = capmixout[1]; //cap1 = R-mix
+    else if (SPU->regs.cap[1].add)
+      capout[1] = chanout[2] + chanout[3]; //cap1 = ch2+ch3
+    else capout[1] = chanout[2]; //cap1 = ch2
+
+    capout[0] = MinMax(capout[0],-0x8000,0x7FFF);
+    capout[1] = MinMax(capout[1],-0x8000,0x7FFF);
+
+    //write the output sample where it is supposed to go
+    if (samp == 0)
+    {
+      samp0[0] = sndout[0];
+      samp0[1] = sndout[1];
+    }
+    else
+    {
+      SPU->sndbuf[samp*2+0] = sndout[0];
+      SPU->sndbuf[samp*2+1] = sndout[1];
+    }
+
+    for (int capchan = 0; capchan < 2; capchan++)
+    {
+      if (SPU->regs.cap[capchan].runtime.running)
+      {
+        SPU_struct::REGS::CAP& cap = SPU->regs.cap[capchan];
+        u32 last = sputrunc(cap.runtime.sampcnt);
+        cap.runtime.sampcnt += SPU->channels[1+2*capchan].sampinc;
+        u32 curr = sputrunc(cap.runtime.sampcnt);
+        for (u32 j = last; j < curr; j++)
+        {
+          //so, this is a little strange. why go through a fifo?
+          //it seems that some games will set up a reverb effect by capturing
+          //to the nearly same address as playback, but ahead by a couple.
+          //So, playback will always end up being what was captured a couple of samples ago.
+          //This system counts on playback always having read ahead 16 samples.
+          //In that case, playback will end up being what was processed at one entire buffer length ago,
+          //since the 16 samples would have read ahead before they got captured over
+
+          //It's actually the source channels which should have a fifo, but we are
+          //not going to take the hit in speed and complexity. Save it for a future rewrite.
+          //Instead, what we do here is delay the capture by 16 samples to create a similar effect.
+          //Subjectively, it seems to be working.
+
+          //Don't do anything until the fifo is filled, so as to delay it
+          if (cap.runtime.fifo.size < 16)
+          {
+            cap.runtime.fifo.enqueue(capout[capchan]);
+            continue;
+          }
+
+          //(actually capture sample from fifo instead of most recently generated)
+          u32 multiplier;
+          s32 sample = cap.runtime.fifo.dequeue();
+          cap.runtime.fifo.enqueue(capout[capchan]);
+
+          if (cap.bits8)
+          {
+            s8 sample8 = sample >> 8;
+            if (skipcap) _MMU_write08<1,MMU_AT_DMA>(cap.runtime.curdad,0);
+            else _MMU_write08<1,MMU_AT_DMA>(cap.runtime.curdad,sample8);
+            cap.runtime.curdad++;
+            multiplier = 4;
+          }
+          else
+          {
+            s16 sample16 = sample;
+            if (skipcap) _MMU_write16<1,MMU_AT_DMA>(cap.runtime.curdad,0);
+            else _MMU_write16<1,MMU_AT_DMA>(cap.runtime.curdad,sample16);
+            cap.runtime.curdad+=2;
+            multiplier = 2;
+          }
+
+          if (cap.runtime.curdad >= cap.runtime.maxdad)
+          {
+            cap.runtime.curdad = cap.dad;
+            cap.runtime.sampcnt -= cap.len*multiplier;
+          }
+        } //sampinc loop
+      } //if capchan running
+    } //capchan loop
+  } //main sample loop
+
+  SPU->sndbuf[0] = samp0[0];
+  SPU->sndbuf[1] = samp0[1];
+}
+
+//ENTER
+static void SPU_MixAudio(bool actuallyMix, SPU_struct *SPU, int length)
+{
+  if (actuallyMix)
+  {
+    memset(SPU->sndbuf, 0, length*4*2);
+    memset(SPU->outbuf, 0, length*2*2);
+  }
+
+  SPU_MixAudio_Advanced(actuallyMix, SPU, length);
+
+  //we used to bail out if speakers were disabled.
+  //this is technically wrong. sound may still be captured, or something.
+  //in all likelihood, any game doing this probably master disabled the SPU also
+  //so, optimization of this case is probably not necessary.
+  //later, we'll just silence the output
+  bool speakers = T1ReadWord(MMU.ARM7_REG, 0x304) & 0x01;
+
+  u8 vol = SPU->regs.mastervol;
+
+  // convert from 32-bit->16-bit
+  if (actuallyMix && speakers) {
+    for (int i = 0; i < length*2; i++)
+    {
+      // Apply Master Volume
+      SPU->sndbuf[i] = spumuldiv7(SPU->sndbuf[i], vol);
+      s16 outsample = MinMax(SPU->sndbuf[i],-0x8000,0x7FFF);
+      SPU->outbuf[i] = outsample;
+    }
+  }
 }
 
 //////////////////////////////////////////////////////////////////////////////
 
-static inline void Fetch8BitData(const channel_struct *const chan, int32_t *const data, SPUInterpolationMode INTERPOLATE_MODE)
-{
-	if (chan->sampcnt < 0)
-	{
-		*data = 0;
-		return;
-	}
-
-	uint32_t loc = u32floor(chan->sampcnt);
-	if (INTERPOLATE_MODE != SPUInterpolation_None)
-	{
-		int32_t a = static_cast<int32_t>(read_s8(chan->addr + loc) << 8);
-		if (loc < (chan->totlength << 2) - 1)
-		{
-			int32_t b = static_cast<int32_t>(read_s8(chan->addr + loc + 1) << 8);
-			a = Interpolate(a, b, chan->sampcnt, INTERPOLATE_MODE);
-		}
-		*data = a;
-	}
-	else
-		*data = static_cast<int32_t>(read_s8(chan->addr + loc) << 8);
-}
-
-static inline void Fetch16BitData(const channel_struct *const chan, int32_t *const data, SPUInterpolationMode INTERPOLATE_MODE)
-{
-	if (chan->sampcnt < 0)
-	{
-		*data = 0;
-		return;
-	}
-
-	if (INTERPOLATE_MODE != SPUInterpolation_None)
-	{
-		uint32_t loc = u32floor(chan->sampcnt);
-
-		int32_t a = static_cast<int32_t>(read16(loc * 2 + chan->addr));
-		if (loc < (chan->totlength << 1) - 1)
-		{
-			int32_t b = static_cast<int32_t>(read16(loc * 2 + chan->addr + 2));
-			a = Interpolate(a, b, chan->sampcnt, INTERPOLATE_MODE);
-		}
-		*data = a;
-	}
-	else
-		*data = read16(chan->addr + u32floor(chan->sampcnt) * 2);
-}
-
-static inline void FetchADPCMData(channel_struct *const chan, int32_t *const data, SPUInterpolationMode INTERPOLATE_MODE)
-{
-	if (chan->sampcnt < 8)
-	{
-		*data = 0;
-		return;
-	}
-
-	// No sense decoding, just return the last sample
-	if (chan->lastsampcnt != u32floor(chan->sampcnt))
-	{
-		uint32_t endExclusive = u32floor(chan->sampcnt + 1);
-		for (uint32_t i = chan->lastsampcnt + 1; i < endExclusive; ++i)
-		{
-			uint32_t shift = (i & 1) << 2;
-			uint32_t data4bit = static_cast<uint32_t>(read08(chan->addr + (i >> 1))) >> shift;
-
-			int32_t diff = precalcdifftbl[chan->index][data4bit & 0xF];
-			chan->index = precalcindextbl[chan->index][data4bit & 0x7];
-
-			chan->pcm16b_last = chan->pcm16b;
-			chan->pcm16b = MinMax(chan->pcm16b+diff, -0x8000, 0x7FFF);
-
-			if (i == static_cast<uint32_t>(chan->loopstart << 3))
-			{
-				if (chan->loop_index != K_ADPCM_LOOPING_RECOVERY_INDEX)
-					printf("over-snagging\n");
-				chan->loop_pcm16b = chan->pcm16b;
-				chan->loop_index = chan->index;
-			}
-		}
-
-		chan->lastsampcnt = u32floor(chan->sampcnt);
-	}
-
-	if (INTERPOLATE_MODE != SPUInterpolation_None)
-		*data = Interpolate(static_cast<int32_t>(chan->pcm16b_last), static_cast<int32_t>(chan->pcm16b), chan->sampcnt, INTERPOLATE_MODE);
-	else
-		*data = static_cast<int32_t>(chan->pcm16b);
-}
-
-static inline void FetchPSGData(channel_struct *chan, int32_t *data)
-{
-	if (chan->sampcnt < 0)
-	{
-		*data = 0;
-		return;
-	}
-
-	if (chan->num < 8)
-		*data = 0;
-	else if (chan->num < 14)
-		*data = static_cast<int32_t>(wavedutytbl[chan->waveduty][u32floor(chan->sampcnt) & 0x7]);
-	else
-	{
-		if (chan->lastsampcnt == u32floor(chan->sampcnt))
-		{
-			*data = static_cast<int32_t>(chan->psgnoise_last);
-			return;
-		}
-
-		uint32_t max = u32floor(chan->sampcnt);
-		for (uint32_t i = chan->lastsampcnt; i < max; ++i)
-		{
-			if (chan->x & 0x1)
-			{
-				chan->x = (chan->x >> 1) ^ 0x6000;
-				chan->psgnoise_last = -0x7FFF;
-			}
-			else
-			{
-				chan->x >>= 1;
-				chan->psgnoise_last = 0x7FFF;
-			}
-		}
-
-		chan->lastsampcnt = u32floor(chan->sampcnt);
-
-		*data = static_cast<int32_t>(chan->psgnoise_last);
-	}
-}
-
-//////////////////////////////////////////////////////////////////////////////
-
-static inline void MixL(SPU_struct *SPU, channel_struct *chan, int32_t data)
-{
-	data = spumuldiv7(data, chan->vol) >> chan->datashift;
-	SPU->sndbuf[SPU->bufpos << 1] += data;
-}
-
-static inline void MixR(SPU_struct *SPU, channel_struct *chan, int32_t data)
-{
-	data = spumuldiv7(data, chan->vol) >> chan->datashift;
-	SPU->sndbuf[(SPU->bufpos << 1) + 1] += data;
-}
-
-static inline void MixLR(SPU_struct *SPU, channel_struct *chan, int32_t data)
-{
-	data = spumuldiv7(data, chan->vol) >> chan->datashift;
-	SPU->sndbuf[SPU->bufpos << 1] += spumuldiv7(data, 127 - chan->pan);
-	SPU->sndbuf[(SPU->bufpos << 1) + 1] += spumuldiv7(data, chan->pan);
-}
-
-//////////////////////////////////////////////////////////////////////////////
-
-static inline void TestForLoop(SPU_struct *SPU, channel_struct *chan, int FORMAT)
-{
-	int shift = !FORMAT ? 2 : 1;
-
-	chan->sampcnt += chan->sampinc;
-
-	if (chan->sampcnt > chan->double_totlength_shifted)
-	{
-		// Do we loop? Or are we done?
-		if (chan->repeat == 1)
-		{
-			while (chan->sampcnt > chan->double_totlength_shifted)
-				chan->sampcnt -= chan->double_totlength_shifted - static_cast<double>(chan->loopstart << shift);
-			//chan->sampcnt = (double)(chan->loopstart << shift);
-		}
-		else
-		{
-			SPU->KeyOff(chan->num);
-			SPU->bufpos = SPU->buflength;
-		}
-	}
-}
-
-static inline void TestForLoop2(SPU_struct *SPU, channel_struct *chan)
-{
-	chan->sampcnt += chan->sampinc;
-
-	if (chan->sampcnt > chan->double_totlength_shifted)
-	{
-		// Do we loop? Or are we done?
-		if (chan->repeat == 1)
-		{
-			while (chan->sampcnt > chan->double_totlength_shifted)
-				chan->sampcnt -= chan->double_totlength_shifted - static_cast<double>(chan->loopstart << 3);
-
-			if (chan->loop_index == K_ADPCM_LOOPING_RECOVERY_INDEX)
-			{
-				chan->pcm16b = read16(chan->addr);
-				chan->index = read08(chan->addr + 2) & 0x7F;
-				chan->lastsampcnt = 7;
-			}
-			else
-			{
-				chan->pcm16b = chan->loop_pcm16b;
-				chan->index = chan->loop_index;
-				chan->lastsampcnt = chan->loopstart << 3;
-			}
-		}
-		else
-		{
-			chan->status = CHANSTAT_STOPPED;
-			SPU->KeyOff(chan->num);
-			SPU->bufpos = SPU->buflength;
-		}
-	}
-}
-
-static inline void SPU_Mix(SPU_struct *SPU, channel_struct *chan, int32_t data, int CHANNELS)
-{
-	switch (CHANNELS)
-	{
-		case 0:
-			MixL(SPU, chan, data);
-			break;
-		case 1:
-			MixLR(SPU, chan, data);
-			break;
-		case 2:
-			MixR(SPU, chan, data);
-	}
-	SPU->lastdata = data;
-}
-
-// WORK
-static inline void ____SPU_ChanUpdate(SPU_struct *const SPU, channel_struct *const chan, int FORMAT, SPUInterpolationMode INTERPOLATE_MODE, int CHANNELS)
-{
-	for (; SPU->bufpos < SPU->buflength; ++SPU->bufpos)
-	{
-		if (CHANNELS != -1)
-		{
-			int32_t data = 0;
-			switch (FORMAT)
-			{
-				case 0:
-					Fetch8BitData(chan, &data, INTERPOLATE_MODE);
-					break;
-				case 1:
-					Fetch16BitData(chan, &data, INTERPOLATE_MODE);
-					break;
-				case 2:
-					FetchADPCMData(chan, &data, INTERPOLATE_MODE);
-					break;
-				case 3:
-					FetchPSGData(chan, &data);
-			}
-			SPU_Mix(SPU, chan, data, CHANNELS);
-		}
-
-		switch (FORMAT)
-		{
-			case 0:
-			case 1:
-				TestForLoop(SPU, chan, FORMAT);
-				break;
-			case 2:
-				TestForLoop2(SPU, chan);
-				break;
-			case 3:
-				chan->sampcnt += chan->sampinc;
-		}
-	}
-}
-
-static inline void ___SPU_ChanUpdate(bool actuallyMix, SPU_struct *const SPU, channel_struct *const chan, int FORMAT, SPUInterpolationMode INTERPOLATE_MODE)
-{
-	if (!actuallyMix)
-		____SPU_ChanUpdate(SPU, chan, FORMAT, INTERPOLATE_MODE, -1);
-	else if (!chan->pan)
-		____SPU_ChanUpdate(SPU, chan, FORMAT, INTERPOLATE_MODE, 0);
-	else if (chan->pan == 127)
-		____SPU_ChanUpdate(SPU, chan, FORMAT, INTERPOLATE_MODE, 2);
-	else
-		____SPU_ChanUpdate(SPU, chan, FORMAT, INTERPOLATE_MODE, 1);
-}
-
-static inline void __SPU_ChanUpdate(bool actuallyMix, SPU_struct *const SPU, channel_struct *const chan, SPUInterpolationMode INTERPOLATE_MODE)
-{
-	switch (chan->format)
-	{
-		case 0:
-			___SPU_ChanUpdate(actuallyMix, SPU, chan, 0, INTERPOLATE_MODE);
-			break;
-		case 1:
-			___SPU_ChanUpdate(actuallyMix, SPU, chan, 1, INTERPOLATE_MODE);
-			break;
-		case 2:
-			___SPU_ChanUpdate(actuallyMix, SPU, chan, 2, INTERPOLATE_MODE);
-			break;
-		case 3:
-			___SPU_ChanUpdate(actuallyMix, SPU, chan, 3, INTERPOLATE_MODE);
-			break;
-		default:
-			assert(false);
-	}
-}
-
-static inline void _SPU_ChanUpdate(bool actuallyMix, SPU_struct *const SPU, channel_struct *const chan)
-{
-	switch (CommonSettings.spuInterpolationMode)
-	{
-		case SPUInterpolation_None:
-			__SPU_ChanUpdate(actuallyMix, SPU, chan, SPUInterpolation_None);
-			break;
-		case SPUInterpolation_Linear:
-			__SPU_ChanUpdate(actuallyMix, SPU, chan, SPUInterpolation_Linear);
-			break;
-		case SPUInterpolation_Cosine:
-			__SPU_ChanUpdate(actuallyMix, SPU, chan, SPUInterpolation_Cosine);
-			break;
-	}
-}
-
-// ENTERNEW
-static void SPU_MixAudio_Advanced(bool, SPU_struct *SPU, int length)
-{
-	// the advanced spu function correctly handles all sound control mixing options, as well as capture
-	// this code is not entirely optimal, as it relies on sort of manhandling the core mixing functions
-	// in order to get the results it needs.
-
-	// THIS IS MAX HACKS!!!!
-	// AND NEEDS TO BE REWRITTEN ALONG WITH THE DEEPEST PARTS OF THE SPU
-	// ONCE WE KNOW THAT IT WORKS
-
-	// BIAS gets ignored since our spu is still not bit perfect,
-	// and it doesnt matter for purposes of capture
-
-	// -----------DEBUG CODE
-	bool skipcap = false;
-	// -----------------
-
-	int32_t samp0[] = { 0, 0 };
-
-	// believe it or not, we are going to do this one sample at a time.
-	// like i said, it is slower.
-	for (int samp = 0; samp < length; ++samp)
-	{
-		SPU->sndbuf[0] = SPU->sndbuf[1] = 0;
-		SPU->buflength = 1;
-
-		int32_t capmix[] = { 0, 0 }, mix[] = { 0, 0 };
-		int32_t chanout[16];
-		int32_t submix[32];
-
-		// generate each channel, and helpfully mix it at the same time
-		for (int i = 0; i < 16; ++i)
-		{
-			channel_struct *chan = &SPU->channels[i];
-
-			if (chan->status == CHANSTAT_PLAY)
-			{
-				SPU->bufpos = 0;
-
-				bool bypass = false;
-				if (i == 1 && SPU->regs.ctl_ch1bypass)
-					bypass = true;
-				if (i == 3 && SPU->regs.ctl_ch3bypass)
-					bypass = true;
-
-				// output to mixer unless we are bypassed.
-				// dont output to mixer if the user muted us
-				bool outputToMix = true;
-				if (CommonSettings.spu_muteChannels[i])
-					outputToMix = false;
-				if (bypass)
-					outputToMix = false;
-				bool outputToCap = outputToMix;
-				if (CommonSettings.spu_captureMuted && !bypass)
-					outputToCap = true;
-
-				// channels 1 and 3 should probably always generate their audio
-				// internally at least, just in case they get used by the spu output
-				bool domix = outputToCap || outputToMix || i == 1 || i == 3;
-
-				// clear the output buffer since this is where _SPU_ChanUpdate wants to accumulate things
-				SPU->sndbuf[0] = SPU->sndbuf[1] = 0;
-
-				// get channel's next output sample.
-				_SPU_ChanUpdate(domix, SPU, chan);
-				chanout[i] = SPU->lastdata >> chan->datashift;
-
-				// save the panned results
-				submix[i * 2] = SPU->sndbuf[0];
-				submix[i * 2 + 1] = SPU->sndbuf[1];
-
-				// send sample to our capture mix
-				if (outputToCap)
-				{
-					capmix[0] += submix[i * 2];
-					capmix[1] += submix[i * 2 + 1];
-				}
-
-				// send sample to our main mixer
-				if (outputToMix)
-				{
-					mix[0] += submix[i * 2];
-					mix[1] += submix[i * 2 + 1];
-				}
-			}
-			else
-				chanout[i] = submix[i * 2] = submix[i * 2 + 1] = 0;
-		} // foreach channel
-
-		int32_t mixout[] = { mix[0], mix[1] };
-		int32_t capmixout[] = { capmix[0], capmix[1] };
-		int32_t sndout[] = { 0, 0 };
-		int32_t capout[2];
-
-		// create SPU output
-		switch (SPU->regs.ctl_left)
-		{
-			case SPU_struct::REGS::LOM_LEFT_MIXER:
-				sndout[0] = mixout[0];
-				break;
-			case SPU_struct::REGS::LOM_CH1:
-				sndout[0] = submix[2];
-				break;
-			case SPU_struct::REGS::LOM_CH3:
-				sndout[0] = submix[6];
-				break;
-			case SPU_struct::REGS::LOM_CH1_PLUS_CH3:
-				sndout[0] = submix[2] + submix[6];
-		}
-		switch (SPU->regs.ctl_right)
-		{
-			case SPU_struct::REGS::ROM_RIGHT_MIXER:
-				sndout[1] = mixout[1];
-				break;
-			case SPU_struct::REGS::ROM_CH1:
-				sndout[1] = submix[3];
-				break;
-			case SPU_struct::REGS::ROM_CH3:
-				sndout[1] = submix[7];
-				break;
-			case SPU_struct::REGS::ROM_CH1_PLUS_CH3:
-				sndout[1] = submix[3] + submix[7];
-		}
-
-		// generate capture output ("capture bugs" from gbatek are not emulated)
-		if (!SPU->regs.cap[0].source)
-			capout[0] = capmixout[0]; // cap0 = L-mix
-		else if (SPU->regs.cap[0].add)
-			capout[0] = chanout[0] + chanout[1]; // cap0 = ch0+ch1
-		else
-			capout[0] = chanout[0]; // cap0 = ch0
-
-		if (!SPU->regs.cap[1].source)
-			capout[1] = capmixout[1]; // cap1 = R-mix
-		else if (SPU->regs.cap[1].add)
-			capout[1] = chanout[2] + chanout[3]; // cap1 = ch2+ch3
-		else
-			capout[1] = chanout[2]; // cap1 = ch2
-
-		capout[0] = MinMax(capout[0], -0x8000, 0x7FFF);
-		capout[1] = MinMax(capout[1], -0x8000, 0x7FFF);
-
-		// write the output sample where it is supposed to go
-		if (!samp)
-		{
-			samp0[0] = sndout[0];
-			samp0[1] = sndout[1];
-		}
-		else
-		{
-			SPU->sndbuf[samp * 2] = sndout[0];
-			SPU->sndbuf[samp * 2 + 1] = sndout[1];
-		}
-
-		for (int capchan = 0; capchan < 2; ++capchan)
-		{
-			if (SPU->regs.cap[capchan].runtime.running)
-			{
-				SPU_struct::REGS::CAP &cap = SPU->regs.cap[capchan];
-				uint32_t last = u32floor(cap.runtime.sampcnt);
-				cap.runtime.sampcnt += SPU->channels[2 * capchan + 1].sampinc;
-				uint32_t curr = u32floor(cap.runtime.sampcnt);
-				for (uint32_t j = last; j < curr; ++j)
-				{
-					// so, this is a little strange. why go through a fifo?
-					// it seems that some games will set up a reverb effect by capturing
-					// to the nearly same address as playback, but ahead by a couple.
-					// So, playback will always end up being what was captured a couple of samples ago.
-					// This system counts on playback always having read ahead 16 samples.
-					// In that case, playback will end up being what was processed at one entire buffer length ago,
-					// since the 16 samples would have read ahead before they got captured over
-
-					// It's actually the source channels which should have a fifo, but we are
-					// not going to take the hit in speed and complexity. Save it for a future rewrite.
-					// Instead, what we do here is delay the capture by 16 samples to create a similar effect.
-					// Subjectively, it seems to be working.
-
-					// Don't do anything until the fifo is filled, so as to delay it
-					if (cap.runtime.fifo.size < 16)
-					{
-						cap.runtime.fifo.enqueue(static_cast<int16_t>(capout[capchan]));
-						continue;
-					}
-
-					// (actually capture sample from fifo instead of most recently generated)
-					int32_t sample = cap.runtime.fifo.dequeue();
-					cap.runtime.fifo.enqueue(static_cast<int16_t>(capout[capchan]));
-
-					uint32_t multiplier;
-					if (cap.bits8)
-					{
-						int8_t sample8 = static_cast<int8_t>(sample >> 8);
-						if (skipcap)
-							_MMU_write08<1, MMU_AT_DMA>(cap.runtime.curdad, 0);
-						else
-							_MMU_write08<1, MMU_AT_DMA>(cap.runtime.curdad, sample8);
-						++cap.runtime.curdad;
-						multiplier = 4;
-					}
-					else
-					{
-						int16_t sample16 = static_cast<int16_t>(sample);
-						if (skipcap)
-							_MMU_write16<1, MMU_AT_DMA>(cap.runtime.curdad, 0);
-						else
-							_MMU_write16<1, MMU_AT_DMA>(cap.runtime.curdad, sample16);
-						cap.runtime.curdad += 2;
-						multiplier = 2;
-					}
-
-					if (cap.runtime.curdad >= cap.runtime.maxdad)
-					{
-						cap.runtime.curdad = cap.dad;
-						cap.runtime.sampcnt -= cap.len * multiplier;
-					}
-				} // sampinc loop
-			} // if capchan running
-		} // capchan loop
-	} // main sample loop
-
-	SPU->sndbuf[0] = samp0[0];
-	SPU->sndbuf[1] = samp0[1];
-}
-
-// ENTER
-static void SPU_MixAudio(bool actuallyMix, SPU_struct *SPU, int length)
-{
-	if (actuallyMix)
-	{
-		memset(&SPU->sndbuf[0], 0, length * 4 * 2);
-		memset(&SPU->outbuf[0], 0, length * 2 * 2);
-	}
-
-	// we used to use master enable here, and do nothing if audio is disabled.
-	// now, master enable is emulated better..
-	// but for a speed optimization we will still do it
-	if (!SPU->regs.masteren)
-		return;
-
-	bool advanced = CommonSettings.spu_advanced;
-
-	// branch here so that slow computers don't have to take the advanced (slower) codepath.
-	// it remainds to be seen exactly how much slower it is
-	// if it isnt much slower then we should refactor everything to be simpler, once it is working
-	if (advanced && SPU == SPU_core.get())
-		SPU_MixAudio_Advanced(actuallyMix, SPU, length);
-	else
-	{
-		// non-advanced mode
-		for (int i = 0; i < 16; ++i)
-		{
-			channel_struct *chan = &SPU->channels[i];
-
-			if (chan->status != CHANSTAT_PLAY)
-				continue;
-
-			SPU->bufpos = 0;
-			SPU->buflength = length;
-
-			// Mix audio
-			_SPU_ChanUpdate(!CommonSettings.spu_muteChannels[i] && actuallyMix, SPU, chan);
-		}
-	}
-
-	// we used to bail out if speakers were disabled.
-	// this is technically wrong. sound may still be captured, or something.
-	// in all likelihood, any game doing this probably master disabled the SPU also
-	// so, optimization of this case is probably not necessary.
-	// later, we'll just silence the output
-	bool speakers = T1ReadWord(MMU.ARM7_REG, 0x304) & 0x01;
-
-	uint8_t vol = SPU->regs.mastervol;
-
-	// convert from 32-bit->16-bit
-	if (actuallyMix && speakers)
-		for (int i = 0; i < length * 2; ++i)
-		{
-			// Apply Master Volume
-			SPU->sndbuf[i] = spumuldiv7(SPU->sndbuf[i], vol);
-			int16_t outsample = static_cast<int16_t>(MinMax(SPU->sndbuf[i], -0x8000, 0x7FFF));
-			SPU->outbuf[i] = outsample;
-		}
-}
-
-//////////////////////////////////////////////////////////////////////////////
-
-// emulates one hline of the cpu core.
-// this will produce a variable number of samples, calculated to keep a 44100hz output
-// in sync with the emulator framerate
+
+//emulates one hline of the cpu core.
+//this will produce a variable number of samples, calculated to keep a 44100hz output
+//in sync with the emulator framerate
 int spu_core_samples = 0;
 void SPU_Emulate_core()
 {
-	bool needToMix = true;
-
-	samples += samples_per_hline;
-	spu_core_samples = static_cast<int>(samples);
-	samples -= spu_core_samples;
-
-	// We don't need to mix audio for Dual Synch/Asynch mode since we do this
-	// later in SPU_Emulate_user(). Disable mixing here to speed up processing.
-	// However, recording still needs to mix the audio, so make sure we're also
-	// not recording before we disable mixing.
-	if (synchmode == ESynchMode_DualSynchAsynch)
-		needToMix = false;
-
-	SPU_MixAudio(needToMix, SPU_core.get(), spu_core_samples);
-
-	if (!SNDCore)
-		return;
-
-	if (SNDCore->FetchSamples)
-		SNDCore->FetchSamples(&SPU_core->outbuf[0], spu_core_samples, synchmode, synchronizer.get());
-	else
-		SPU_DefaultFetchSamples(&SPU_core->outbuf[0], spu_core_samples, synchmode, synchronizer.get());
-}
-
-void SPU_Emulate_user(bool /*mix*/)
-{
-	static std::vector<int16_t> postProcessBuffer;
-	static size_t postProcessBufferSize = 0;
-	size_t processedSampleCount = 0;
-
-	if (!SNDCore)
-		return;
-
-	// Check to see how many free samples are available.
-	// If there are some, fill up the output buffer.
-	size_t freeSampleCount = SNDCore->GetAudioSpace();
-	if (!freeSampleCount)
-		return;
-
-	//printf("mix %i samples\n", audiosize);
-	if (freeSampleCount > buffersize)
-		freeSampleCount = buffersize;
-
-	// If needed, resize the post-process buffer to guarantee that
-	// we can store all the sound data.
-	if (postProcessBufferSize < freeSampleCount * 2 * sizeof(int16_t))
-	{
-		postProcessBufferSize = freeSampleCount * 2 * sizeof(int16_t);
-		postProcessBuffer.resize(postProcessBufferSize);
-	}
-
-	if (SNDCore->PostProcessSamples)
-		processedSampleCount = SNDCore->PostProcessSamples(&postProcessBuffer[0], freeSampleCount, synchmode, synchronizer.get());
-	else
-		processedSampleCount = SPU_DefaultPostProcessSamples(&postProcessBuffer[0], freeSampleCount, synchmode, synchronizer.get());
-
-	SNDCore->UpdateAudio(&postProcessBuffer[0], processedSampleCount);
-}
-
-void SPU_DefaultFetchSamples(int16_t *sampleBuffer, size_t sampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer)
-{
-	if (synchMode == ESynchMode_Synchronous)
-		theSynchronizer->enqueue_samples(sampleBuffer, sampleCount);
-}
-
-size_t SPU_DefaultPostProcessSamples(int16_t *postProcessBuffer, size_t requestedSampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer)
-{
-	size_t processedSampleCount = 0;
-
-	switch (synchMode)
-	{
-		case ESynchMode_DualSynchAsynch:
-			if (SPU_user)
-			{
-				SPU_MixAudio(true, SPU_user.get(), requestedSampleCount);
-				memcpy(postProcessBuffer, &SPU_user->outbuf[0], requestedSampleCount * 2 * sizeof(int16_t));
-				processedSampleCount = requestedSampleCount;
-			}
-			break;
-
-		case ESynchMode_Synchronous:
-			processedSampleCount = theSynchronizer->output_samples(postProcessBuffer, requestedSampleCount);
-	}
-
-	return processedSampleCount;
+  bool needToMix = true;
+  SoundInterface_struct *soundProcessor = SPU_SoundCore();
+
+  samples += samples_per_hline;
+  spu_core_samples = (int)(samples);
+  samples -= spu_core_samples;
+
+  SPU_MixAudio(needToMix, SPU_core, spu_core_samples);
+
+  if (soundProcessor == NULL)
+  {
+    return;
+  }
+
+  if (soundProcessor->FetchSamples != NULL)
+  {
+    soundProcessor->FetchSamples(SPU_core->outbuf, spu_core_samples, synchmode, synchronizer);
+  }
+  else
+  {
+    SPU_DefaultFetchSamples(SPU_core->outbuf, spu_core_samples, synchmode, synchronizer);
+  }
+}
+
+void SPU_Emulate_user(bool mix)
+{
+  static s16 *postProcessBuffer = NULL;
+  static size_t postProcessBufferSize = 0;
+  size_t freeSampleCount = 0;
+  size_t processedSampleCount = 0;
+  SoundInterface_struct *soundProcessor = SPU_SoundCore();
+
+  if (soundProcessor == NULL)
+  {
+    return;
+  }
+
+  // Check to see how many free samples are available.
+  // If there are some, fill up the output buffer.
+  freeSampleCount = soundProcessor->GetAudioSpace();
+  if (freeSampleCount == 0)
+  {
+    return;
+  }
+
+  if (freeSampleCount > buffersize)
+  {
+    freeSampleCount = buffersize;
+  }
+
+  // If needed, resize the post-process buffer to guarantee that
+  // we can store all the sound data.
+  if (postProcessBufferSize < freeSampleCount * 2 * sizeof(s16))
+  {
+    postProcessBufferSize = freeSampleCount * 2 * sizeof(s16);
+    postProcessBuffer = (s16 *)realloc(postProcessBuffer, postProcessBufferSize);
+  }
+
+  if (soundProcessor->PostProcessSamples != NULL)
+  {
+    processedSampleCount = soundProcessor->PostProcessSamples(postProcessBuffer, freeSampleCount, synchmode, synchronizer);
+  }
+  else
+  {
+    processedSampleCount = SPU_DefaultPostProcessSamples(postProcessBuffer, freeSampleCount, synchmode, synchronizer);
+  }
+
+  soundProcessor->UpdateAudio(postProcessBuffer, processedSampleCount);
+}
+
+void SPU_DefaultFetchSamples(s16 *sampleBuffer, size_t sampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer)
+{
+  theSynchronizer->enqueue_samples(sampleBuffer, sampleCount);
+}
+
+size_t SPU_DefaultPostProcessSamples(s16 *postProcessBuffer, size_t requestedSampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer)
+{
+  return theSynchronizer->output_samples(postProcessBuffer, requestedSampleCount);
 }
 
 //////////////////////////////////////////////////////////////////////////////
 // Dummy Sound Interface
 //////////////////////////////////////////////////////////////////////////////
 
-int SNDDummyInit(int) { return 0; }
+int SNDDummyInit(int buffersize);
+void SNDDummyDeInit();
+void SNDDummyUpdateAudio(s16 *buffer, u32 num_samples);
+u32 SNDDummyGetAudioSpace();
+void SNDDummyMuteAudio();
+void SNDDummyUnMuteAudio();
+void SNDDummySetVolume(int volume);
+void SNDDummyClearBuffer();
+void SNDDummyFetchSamples(s16 *sampleBuffer, size_t sampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer);
+size_t SNDDummyPostProcessSamples(s16 *postProcessBuffer, size_t requestedSampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer);
+
+SoundInterface_struct SNDDummy = {
+  SNDCORE_DUMMY,
+  "Dummy Sound Interface",
+  SNDDummyInit,
+  SNDDummyDeInit,
+  SNDDummyUpdateAudio,
+  SNDDummyGetAudioSpace,
+  SNDDummyMuteAudio,
+  SNDDummyUnMuteAudio,
+  SNDDummySetVolume,
+  SNDDummyClearBuffer,
+  SNDDummyFetchSamples,
+  SNDDummyPostProcessSamples
+};
+
+int SNDDummyInit(int buffersize) { return 0; }
 void SNDDummyDeInit() {}
-void SNDDummyUpdateAudio(int16_t *, uint32_t) { }
-uint32_t SNDDummyGetAudioSpace() { return DESMUME_SAMPLE_RATE / 60 + 5; }
+void SNDDummyUpdateAudio(s16 *buffer, u32 num_samples) { }
+u32 SNDDummyGetAudioSpace() { return DESMUME_SAMPLE_RATE/60 + 5; }
 void SNDDummyMuteAudio() {}
 void SNDDummyUnMuteAudio() {}
-void SNDDummySetVolume(int) {}
+void SNDDummySetVolume(int volume) {}
 void SNDDummyClearBuffer() {}
-void SNDDummyFetchSamples(int16_t *, size_t, ESynchMode, ISynchronizingAudioBuffer *) { }
-size_t SNDDummyPostProcessSamples(int16_t *, size_t, ESynchMode, ISynchronizingAudioBuffer *) { return 0; }
-
-SoundInterface_struct SNDDummy =
-{
-	SNDCORE_DUMMY,
-	"Dummy Sound Interface",
-	SNDDummyInit,
-	SNDDummyDeInit,
-	SNDDummyUpdateAudio,
-	SNDDummyGetAudioSpace,
-	SNDDummyMuteAudio,
-	SNDDummyUnMuteAudio,
-	SNDDummySetVolume,
-	SNDDummyClearBuffer,
-	SNDDummyFetchSamples,
-	SNDDummyPostProcessSamples
-};
-
+void SNDDummyFetchSamples(s16 *sampleBuffer, size_t sampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer) {}
+size_t SNDDummyPostProcessSamples(s16 *postProcessBuffer, size_t requestedSampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer) { return 0; }
+
+

--- a/src/in_2sf/desmume/SPU.h
+++ b/src/in_2sf/desmume/SPU.h
@@ -1,6 +1,6 @@
 /*
 	Copyright 2006 Theo Berkau
-	Copyright (C) 2006-2010 DeSmuME team
+	Copyright (C) 2006-2015 DeSmuME team
 
 	This file is free software: you can redistribute it and/or modify
 	it under the terms of the GNU General Public License as published by
@@ -16,50 +16,58 @@
 	along with the this software.  If not, see <http://www.gnu.org/licenses/>.
 */
 
-#pragma once
-
-#include <memory>
+#ifndef SPU_H
+#define SPU_H
+
 #include <iosfwd>
 #include <string>
-#include <cassert>
+#include <assert.h>
+#include <stdio.h>
+#include <memory>
+
 #include "types.h"
 #include "matrix.h"
-#include "emufile.h"
 #include "metaspu/metaspu.h"
 
-const int SNDCORE_DEFAULT = -1;
-const int SNDCORE_DUMMY = 0;
-
-const uint8_t CHANSTAT_STOPPED = 0;
-const uint8_t CHANSTAT_PLAY = 1;
-
-inline int32_t spumuldiv7(int32_t val, uint8_t multiplier)
-{
+class EMUFILE;
+
+#define SNDCORE_DEFAULT         -1
+#define SNDCORE_DUMMY           0
+
+#define CHANSTAT_STOPPED          0
+#define CHANSTAT_PLAY             1
+
+
+//who made these static? theyre used in multiple places.
+FORCEINLINE u32 sputrunc(float f) { return u32floor(f); }
+FORCEINLINE u32 sputrunc(double d) { return u32floor(d); }
+FORCEINLINE s32 spumuldiv7(s32 val, u8 multiplier) {
 	assert(multiplier <= 127);
-	return multiplier == 127 ? val : ((val * multiplier) >> 7);
+	return (multiplier == 127) ? val : ((val * multiplier) >> 7);
 }
 
 enum SPUInterpolationMode
 {
-	SPUInterpolation_None,
-	SPUInterpolation_Linear,
-	SPUInterpolation_Cosine
+	SPUInterpolation_None   = 0,
+	SPUInterpolation_Linear = 1,
+	SPUInterpolation_Cosine = 2,
+	SPUInterpolation_Sharp  = 3
 };
 
 struct SoundInterface_struct
 {
-	int id;
-	const char *Name;
-	int (*Init)(int buffersize);
-	void (*DeInit)();
-	void (*UpdateAudio)(int16_t *buffer, uint32_t num_samples);
-	uint32_t (*GetAudioSpace)();
-	void (*MuteAudio)();
-	void (*UnMuteAudio)();
-	void (*SetVolume)(int volume);
-	void (*ClearBuffer)();
-	void (*FetchSamples)(int16_t *sampleBuffer, size_t sampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer);
-	size_t (*PostProcessSamples)(int16_t *postProcessBuffer, size_t requestedSampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer);
+   int id;
+   const char *Name;
+   int (*Init)(int buffersize);
+   void (*DeInit)();
+   void (*UpdateAudio)(s16 *buffer, u32 num_samples);
+   u32 (*GetAudioSpace)();
+   void (*MuteAudio)();
+   void (*UnMuteAudio)();
+   void (*SetVolume)(int volume);
+   void (*ClearBuffer)();
+   void (*FetchSamples)(s16 *sampleBuffer, size_t sampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer);
+   size_t (*PostProcessSamples)(s16 *postProcessBuffer, size_t requestedSampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer);
 };
 
 extern SoundInterface_struct SNDDummy;
@@ -68,43 +76,69 @@
 
 struct channel_struct
 {
-	channel_struct() { }
-	uint32_t num;
-	uint8_t vol;
-	uint8_t datashift;
-	uint8_t hold;
-	uint8_t pan;
-	uint8_t waveduty;
-	uint8_t repeat;
-	uint8_t format;
-	uint8_t keyon;
-	uint8_t status;
-	uint32_t addr;
-	uint16_t timer;
-	uint16_t loopstart;
-	uint32_t length;
-	uint32_t totlength;
-	double double_totlength_shifted;
-	double sampcnt;
-	double sampinc;
-	// ADPCM specific
-	uint32_t lastsampcnt;
-	int16_t pcm16b, pcm16b_last;
-	int16_t loop_pcm16b;
-	int32_t index;
-	int loop_index;
-	uint16_t x;
-	int16_t psgnoise_last;
+	channel_struct() :	num(0),
+						vol(0),
+						volumeDiv(0),
+						hold(0),
+						pan(0),
+						waveduty(0),
+						repeat(0),
+						format(0),
+						keyon(0),
+						status(0),
+						addr(0),
+						timer(0),
+						loopstart(0),
+						length(0),
+						totlength(0),
+						double_totlength_shifted(0.0),
+						sampcnt(0.0),
+						sampinc(0.0),
+						lastsampcnt(0),
+						pcm16b(0),
+						pcm16b_last(0),
+						loop_pcm16b(0),
+						index(0),
+						loop_index(0),
+						x(0),
+						psgnoise_last(0)
+	{}
+	u32 num;
+   u8 vol;
+   u8 volumeDiv;
+   u8 hold;
+   u8 pan;
+   u8 waveduty;
+   u8 repeat;
+   u8 format;
+   u8 keyon;
+   u8 status;
+   u32 addr;
+   u16 timer;
+   u16 loopstart;
+   u32 length;
+   u32 totlength;
+   double double_totlength_shifted;
+   double sampcnt;
+   double sampinc;
+   // ADPCM specific
+   u32 lastsampcnt;
+   s16 pcm16b, pcm16b_last;
+   s16 loop_pcm16b;
+   s32 index;
+   int loop_index;
+   u16 x;
+   s16 psgnoise_last;
 };
 
 class SPUFifo
 {
 public:
 	SPUFifo();
-	void enqueue(int16_t val);
-	int16_t dequeue();
-	int16_t buffer[16];
-	int32_t head, tail, size;
+	void enqueue(s16 val);
+	s16 dequeue();
+	s16 buffer[16];
+	s32 head,tail,size;
 	void reset();
 };
 
@@ -112,99 +146,123 @@
 {
 public:
 	SPU_struct(int buffersize);
-	uint32_t bufpos;
-	uint32_t buflength;
-	std::unique_ptr<int32_t[]> sndbuf;
-	int32_t lastdata; //the last sample that a channel generated
-	std::unique_ptr<int16_t[]> outbuf;
-	uint32_t bufsize;
-	channel_struct channels[16];
-
-	// registers
-	struct REGS
-	{
-		REGS() : mastervol(0), ctl_left(0), ctl_right(0), ctl_ch1bypass(0), ctl_ch3bypass(0), masteren(0), soundbias(0) { }
-
-		uint8_t mastervol;
-		uint8_t ctl_left, ctl_right;
-		uint8_t ctl_ch1bypass, ctl_ch3bypass;
-		uint8_t masteren;
-		uint16_t soundbias;
-
-		enum LeftOutputMode
-		{
-			LOM_LEFT_MIXER,
-			LOM_CH1,
-			LOM_CH3,
-			LOM_CH1_PLUS_CH3
-		};
-
-		enum RightOutputMode
-		{
-			ROM_RIGHT_MIXER,
-			ROM_CH1,
-			ROM_CH3,
-			ROM_CH1_PLUS_CH3
-		};
-
-		struct CAP
-		{
-			CAP() : add(0), source(0), oneshot(0), bits8(0), active(0), dad(0), len(0) { }
-			uint8_t add, source, oneshot, bits8, active;
-			uint32_t dad;
-			uint16_t len;
-			struct Runtime
-			{
-				Runtime() : running(0), curdad(0), maxdad(0) { }
-				uint8_t running;
-				uint32_t curdad;
-				uint32_t maxdad;
-				double sampcnt;
-				SPUFifo fifo;
-			} runtime;
-		} cap[2];
-	} regs;
-
-	void reset();
-	void KeyOff(int channel);
-	void KeyOn(int channel);
-	void KeyProbe(int channel);
-	void ProbeCapture(int which);
-	void WriteByte(uint32_t addr, uint8_t val);
-	uint8_t ReadByte(uint32_t addr);
-	uint16_t ReadWord(uint32_t addr);
-	uint32_t ReadLong(uint32_t addr);
-	void WriteWord(uint32_t addr, uint16_t val);
-	void WriteLong(uint32_t addr, uint32_t val);
-
-	// kills all channels but leaves SPU otherwise running normally
-	void ShutUp();
-};
+   u32 bufpos;
+   u32 buflength;
+   s32 *sndbuf;
+   s32 lastdata; //the last sample that a channel generated
+   s16 *outbuf;
+   u32 bufsize;
+   channel_struct channels[16];
+
+   //registers
+   struct REGS {
+	   REGS()
+			: mastervol(0)
+			, ctl_left(0)
+			, ctl_right(0)
+			, ctl_ch1bypass(0)
+			, ctl_ch3bypass(0)
+			, masteren(0)
+			, soundbias(0)
+	   {}
+
+	   u8 mastervol;
+	   u8 ctl_left, ctl_right;
+	   u8 ctl_ch1bypass, ctl_ch3bypass;
+	   u8 masteren;
+	   u16 soundbias;
+
+	   enum LeftOutputMode
+	   {
+		   LOM_LEFT_MIXER=0, LOM_CH1=1, LOM_CH3=2, LOM_CH1_PLUS_CH3=3
+	   };
+
+	   enum RightOutputMode
+	   {
+		   ROM_RIGHT_MIXER=0, ROM_CH1=1, ROM_CH3=2, ROM_CH1_PLUS_CH3=3
+	   };
+
+	   struct CAP {
+		   CAP()
+			   : add(0), source(0), oneshot(0), bits8(0), active(0), dad(0), len(0)
+		   {}
+		   u8 add, source, oneshot, bits8, active;
+		   u32 dad;
+		   u16 len;
+		   struct Runtime {
+			   Runtime()
+				   : running(0), curdad(0), maxdad(0)
+			   {}
+			   u8 running;
+			   u32 curdad;
+			   u32 maxdad;
+			   double sampcnt;
+			   SPUFifo fifo;
+		   } runtime;
+	   } cap[2];
+   } regs;
+
+   void reset();
+   ~SPU_struct();
+   void KeyOff(int channel);
+   void KeyOn(int channel);
+   void KeyProbe(int channel);
+   void ProbeCapture(int which);
+   void WriteByte(u32 addr, u8 val);
+   void WriteWord(u32 addr, u16 val);
+   void WriteLong(u32 addr, u32 val);
+   u8 ReadByte(u32 addr);
+   u16 ReadWord(u32 addr);
+   u32 ReadLong(u32 addr);
+   bool isSPU(u32 addr) { return ((addr >= 0x04000400) && (addr < 0x04000520)); }
+
+   //kills all channels but leaves SPU otherwise running normally
+   void ShutUp();
+};
+
+extern SPU_struct *SPU_core;
+extern int spu_core_samples;
 
 int SPU_ChangeSoundCore(int coreid, int buffersize);
-
-void SPU_ReInit();
+SoundInterface_struct *SPU_SoundCore();
+
+void SPU_ReInit(bool fakeBoot = false);
 int SPU_Init(int coreid, int buffersize);
-void SPU_SetSynchMode(ESynchMode mode, ESynchMethod method);
-void SPU_Reset();
-void SPU_DeInit();
+void SPU_Pause(int pause);
+void SPU_SetVolume(int volume);
+void SPU_SetSynchMode(int mode, int method);
+void SPU_ClearOutputBuffer(void);
+void SPU_Reset(void);
+void SPU_DeInit(void);
 void SPU_KeyOn(int channel);
-void SPU_WriteByte(uint32_t addr, uint8_t val);
-void SPU_WriteWord(uint32_t addr, uint16_t val);
-void SPU_WriteLong(uint32_t addr, uint32_t val);
-uint8_t SPU_ReadByte(uint32_t addr);
-uint16_t SPU_ReadWord(uint32_t addr);
-uint32_t SPU_ReadLong(uint32_t addr);
-void SPU_Emulate_core();
+static FORCEINLINE void SPU_WriteByte(u32 addr, u8 val)
+{
+	addr &= 0xFFF;
+
+	SPU_core->WriteByte(addr,val);
+}
+static FORCEINLINE void SPU_WriteWord(u32 addr, u16 val)
+{
+	addr &= 0xFFF;
+
+	SPU_core->WriteWord(addr,val);
+}
+static FORCEINLINE void SPU_WriteLong(u32 addr, u32 val)
+{
+	addr &= 0xFFF;
+
+	SPU_core->WriteLong(addr,val);
+}
+static FORCEINLINE u8 SPU_ReadByte(u32 addr) { return SPU_core->ReadByte(addr & 0x0FFF); }
+static FORCEINLINE u16 SPU_ReadWord(u32 addr) { return SPU_core->ReadWord(addr & 0x0FFF); }
+static FORCEINLINE u32 SPU_ReadLong(u32 addr) { return SPU_core->ReadLong(addr & 0x0FFF); }
+void SPU_Emulate_core(void);
 void SPU_Emulate_user(bool mix = true);
-void SPU_DefaultFetchSamples(int16_t *sampleBuffer, size_t sampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer);
-size_t SPU_DefaultPostProcessSamples(int16_t *postProcessBuffer, size_t requestedSampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer);
-
-extern std::unique_ptr<SPU_struct> SPU_core, SPU_user;
-extern int spu_core_samples;
-
-// we should make this configurable eventually
-// but at least defining it somewhere is probably a step in the right direction
-const int DESMUME_SAMPLE_RATE = 44100;
-//#define DESMUME_SAMPLE_RATE 48000
-
+void SPU_DefaultFetchSamples(s16 *sampleBuffer, size_t sampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer);
+size_t SPU_DefaultPostProcessSamples(s16 *postProcessBuffer, size_t requestedSampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer);
+
+extern double DESMUME_SAMPLE_RATE;
+void SetDesmumeSampleRate(double rate);
+
+#endif
+

--- a/src/in_2sf/desmume/arm_instructions.cpp
+++ b/src/in_2sf/desmume/arm_instructions.cpp
@@ -2997,13 +2997,13 @@
 	uint32_t stateMask = PROCNUM?v4T_STATE_MASK : v5TE_STATE_MASK;
 
 	if (operand & unallocMask)
-		printf("ARM%c: MSR_CPSR_REG UNPREDICTABLE UNALLOC (operand %08X)\n", PROCNUM ? '7' : '9', operand);
+		fprintf(stderr, "ARM%c: MSR_CPSR_REG UNPREDICTABLE UNALLOC (operand %08X)\n", PROCNUM ? '7' : '9', operand);
 	if (cpu->CPSR.bits.mode != USR) // Privileged mode
 	{
 		if (BIT16(i))
 			armcpu_switchMode(cpu, operand & 0x1F);
 		if (operand & stateMask)
-			printf("ARM%c: MSR_CPSR_REG UNPREDICTABLE STATE (operand %08X)\n", PROCNUM ? '7' : '9', operand);
+			fprintf(stderr, "ARM%c: MSR_CPSR_REG UNPREDICTABLE STATE (operand %08X)\n", PROCNUM ? '7' : '9', operand);
 		else
 			mask = byte_mask & (userMask | privMask);
 	}
@@ -3021,7 +3021,7 @@
 
 TEMPLATE static uint32_t FASTCALL OP_MSR_SPSR(uint32_t i)
 {
-	//printf("OP_MSR_SPSR\n");
+	//fprintf(stderr, "OP_MSR_SPSR\n");
 	uint32_t operand = cpu->R[REG_POS(i, 0)];
 	OP_MSR_SPSR_(operand);
 	return 1;
@@ -3029,7 +3029,7 @@
 
 TEMPLATE static uint32_t FASTCALL OP_MSR_CPSR_IMM_VAL(uint32_t i)
 {
-	//printf("OP_MSR_CPSR_IMM_VAL\n");
+	//fprintf(stderr, "OP_MSR_CPSR_IMM_VAL\n");
 	IMM_VALUE;
 	OP_MSR_CPSR_(shift_op);
 	return 1;
@@ -3037,7 +3037,7 @@
 
 TEMPLATE static uint32_t FASTCALL OP_MSR_SPSR_IMM_VAL(uint32_t i)
 {
-	//printf("OP_MSR_SPSR_IMM_VAL\n");
+	//fprintf(stderr, "OP_MSR_SPSR_IMM_VAL\n");
 	IMM_VALUE;
 	OP_MSR_SPSR_(shift_op);
 	return 1;
@@ -3701,7 +3701,7 @@
 // -----------------------------------------------------------------------------
 TEMPLATE static uint32_t FASTCALL OP_LDREX(uint32_t i)
 {
-	printf("LDREX\n");
+	fprintf(stderr, "LDREX\n");
 	uint32_t adr = cpu->R[REG_POS(i, 16)];
 	cpu->R[REG_POS(i, 12)] = ROR(READ32(cpu->mem_if->data, adr), 8 * (adr & 3));
 	return MMU_aluMemAccessCycles<PROCNUM,32, MMU_AD_READ>(3, adr);
@@ -4288,7 +4288,7 @@
 // -----------------------------------------------------------------------------
 TEMPLATE static uint32_t FASTCALL OP_STREX(uint32_t i)
 {
-	printf("STREX\n");
+	fprintf(stderr, "STREX\n");
 	uint32_t adr = cpu->R[REG_POS(i, 16)];
 	WRITE32(cpu->mem_if->data, adr, cpu->R[REG_POS(i, 0)]);
 	cpu->R[REG_POS(i, 12)] = 0;
@@ -5012,7 +5012,7 @@
 	{
 		if (cpu->CPSR.bits.mode == USR || cpu->CPSR.bits.mode == SYS)
 		{
-			printf("ERROR1\n");
+			fprintf(stderr, "ERROR1\n");
 			return 1;
 		}
 		oldmode = armcpu_switchMode(cpu, SYS);
@@ -5064,7 +5064,7 @@
 	{
 		if (cpu->CPSR.bits.mode == USR || cpu->CPSR.bits.mode == SYS)
 		{
-			printf("ERROR1\n");
+			fprintf(stderr, "ERROR1\n");
 			return 1;
 		}
 		oldmode = armcpu_switchMode(cpu, SYS);
@@ -5116,7 +5116,7 @@
 	{
 		if (cpu->CPSR.bits.mode == USR || cpu->CPSR.bits.mode == SYS)
 		{
-			printf("ERROR1\n");
+			fprintf(stderr, "ERROR1\n");
 			return 1;
 		}
 		oldmode = armcpu_switchMode(cpu, SYS);
@@ -5174,7 +5174,7 @@
 	{
 		if (cpu->CPSR.bits.mode == USR || cpu->CPSR.bits.mode == SYS)
 		{
-			printf("ERROR1\n");
+			fprintf(stderr, "ERROR1\n");
 			return 1;
 		}
 		oldmode = armcpu_switchMode(cpu, SYS);
@@ -5233,7 +5233,7 @@
 	{
 		if (cpu->CPSR.bits.mode == USR || cpu->CPSR.bits.mode == SYS)
 		{
-			printf("ERROR1\n");
+			fprintf(stderr, "ERROR1\n");
 			return 1;
 		}
 		oldmode = armcpu_switchMode(cpu, SYS);
@@ -5289,7 +5289,7 @@
 	{
 		if (cpu->CPSR.bits.mode == USR || cpu->CPSR.bits.mode == SYS)
 		{
-			printf("ERROR1\n");
+			fprintf(stderr, "ERROR1\n");
 			return 1;
 		}
 		oldmode = armcpu_switchMode(cpu, SYS);
@@ -5348,7 +5348,7 @@
 	{
 		if (cpu->CPSR.bits.mode == USR || cpu->CPSR.bits.mode == SYS)
 		{
-			printf("ERROR1\n");
+			fprintf(stderr, "ERROR1\n");
 			return 1;
 		}
 		oldmode = armcpu_switchMode(cpu, SYS);
@@ -5359,7 +5359,7 @@
 	if (BIT15(i))
 	{
 		if (BIT_N(i, REG_POS(i, 16)))
-			printf("error1_1\n");
+			fprintf(stderr, "error1_1\n");
 		uint32_t tmp = READ32(cpu->mem_if->data, start);
 		registres[15] = tmp & (0XFFFFFFFC | (BIT0(tmp) << 1));
 		c += MMU_memAccessCycles<PROCNUM, 32, MMU_AD_READ>(start);
@@ -5409,7 +5409,7 @@
 	{
 		if (cpu->CPSR.bits.mode == USR || cpu->CPSR.bits.mode == SYS)
 		{
-			printf("ERROR1\n");
+			fprintf(stderr, "ERROR1\n");
 			return 1;
 		}
 		oldmode = armcpu_switchMode(cpu, SYS);
@@ -5420,7 +5420,7 @@
 	if (BIT15(i))
 	{
 		if (BIT_N(i, REG_POS(i, 16)))
-			printf("error1_2\n");
+			fprintf(stderr, "error1_2\n");
 		start -= 4;
 		uint32_t tmp = READ32(cpu->mem_if->data, start);
 		c += MMU_memAccessCycles<PROCNUM, 32, MMU_AD_READ>(start);
@@ -5811,7 +5811,7 @@
 	uint32_t addr = cpu->R[REG_POS(i, 16)];
 	uint32_t index;
 
-	//printf("%s POST\n", BIT5(i)?"STRD":"LDRD");
+	//fprintf(stderr, "%s POST\n", BIT5(i)?"STRD":"LDRD");
 	/* I bit - immediate or register */
 	if (BIT22(i))
 		index = IMM_OFF;
@@ -5853,7 +5853,7 @@
 	uint32_t addr = cpu->R[REG_POS(i, 16)];
 	uint32_t index;
 
-	//printf("%s PRE\n", BIT5(i)?"STRD":"LDRD");
+	//fprintf(stderr, "%s PRE\n", BIT5(i)?"STRD":"LDRD");
 	// I bit - immediate or register
 	if (BIT22(i))
 		index = IMM_OFF;
@@ -6059,7 +6059,7 @@
 	if (cpu->swi_tab && !bypassBuiltinSWI)
 	{
 		swinum &= 0x1F;
-		//printf("%d ARM SWI %d \n",PROCNUM,swinum);
+		//fprintf(stderr, "%d ARM SWI %d \n",PROCNUM,swinum);
 		return cpu->swi_tab[swinum]() + 3;
 	}
 	else
@@ -6105,7 +6105,7 @@
 	/*
 	static uint32_t last_bkpt = 0xFFFFFFFF;
 	if(i != last_bkpt)
-		printf("ARM OP_BKPT triggered\n");
+		fprintf(stderr, "ARM OP_BKPT triggered\n");
 	last_bkpt = i;
 
 	//this is not 100% correctly emulated, but it does the job
@@ -6113,7 +6113,7 @@
 	return 4;
 	*/
 
-	printf("ARM OP_BKPT triggered\n");
+	fprintf(stderr, "ARM OP_BKPT triggered\n");
 	Status_Reg tmp = cpu->CPSR;
 	armcpu_switchMode(cpu, ABT); // enter abt mode
 	cpu->R[14] = cpu->instruct_adr + 4;

--- a/src/in_2sf/desmume/arm_jit.cpp
+++ b/src/in_2sf/desmume/arm_jit.cpp
@@ -34,7 +34,7 @@
 #include "instruction_attributes.h"
 #include "MMU.h"
 #include "MMU_timing.h"
-#include "utils/AsmJit/asmjit.h"
+#include "utils/AsmJit/AsmJit.h"
 #include "arm_jit.h"
 #include "bios.h"
 
@@ -56,14 +56,14 @@
 	GpVar txt = c.newGpVar(kVarTypeIntPtr); \
 	GpVar data = c.newGpVar(kVarTypeIntPtr); \
 	GpVar io = c.newGpVar(kVarTypeInt32); \
-	c.lea(io, x86::dword_ptr_abs(stdout)); \
+	c.lea(io, x86::dword_ptr_abs(stderr)); \
 	c.lea(txt, x86::dword_ptr_abs(&buf)); \
 	c.mov(data, *reinterpret_cast<GpVar *>(&val)); \
-	auto prn = c.addCall(imm_ptr(fprintf), ASMJIT_CALL_CONV, FuncBuilder3<void, void *, void *, uint32_t>()); \
+	auto prn = c.addCall(imm_ptr(fprintf), ASMJIT_STDLIB_CALL_CONV, FuncBuilder3<void, void *, void *, uint32_t>()); \
 	prn->setArg(0, io); \
 	prn->setArg(1, txt); \
 	prn->setArg(2, data); \
-	auto prn_flush = c.addCall(imm_ptr(fflush), ASMJIT_CALL_CONV, FuncBuilder1<void, void *>()); \
+	auto prn_flush = c.addCall(imm_ptr(fflush), ASMJIT_STDLIB_CALL_CONV, FuncBuilder1<void, void *>()); \
 	prn_flush->setArg(0, io); \
 }
 #else
@@ -194,9 +194,9 @@
 DS_ALIGN(4096) static uint8_t scratchpad[1 << 25];
 static uint8_t *scratchptr;
 
-struct ASMJIT_API StaticCodeGenerator : public Context
-{
-	StaticCodeGenerator()
+struct StaticCodeSetup
+{
+	StaticCodeSetup()
 	{
 		scratchptr = scratchpad;
 		int align = reinterpret_cast<uintptr_t>(scratchpad) & (sysconf(_SC_PAGESIZE) - 1);
@@ -207,32 +207,10 @@
 			abort();
 		}
 	}
-
-	uint32_t generate(void **dest, Assembler *assembler)
-	{
-		uintptr_t size = assembler->getCodeSize();
-		if (!size)
-		{
-			*dest = nullptr;
-			return kErrorNoFunction;
-		}
-		if (size > reinterpret_cast<uintptr_t>(scratchpad + sizeof(scratchpad) - scratchptr))
-		{
-			fprintf(stderr, "Out of memory for asmjit. Clearing code cache.\n");
-			arm_jit_reset(true);
-			// If arm_jit_reset didn't involve recompiling op_cmp, we could keep the current function.
-			*dest = nullptr;
-			return kErrorOk;
-		}
-		void *p = scratchptr;
-		size = assembler->relocCode(p);
-		scratchptr += size;
-		*dest = p;
-		return kErrorOk;
-	}
 };
 
-static StaticCodeGenerator codegen;
+static StaticCodeSetup setup;
+static StaticRuntime codegen(scratchpad, sizeof(scratchpad));
 static X86Compiler c(&codegen);
 #else
 static JitRuntime runtime;
@@ -280,7 +258,7 @@
 // sequencer.reschedule = true;
 #define changeCPSR \
 { \
-	auto ctxCPSR = c.addCall(imm_ptr(NDS_Reschedule), ASMJIT_CALL_CONV, FuncBuilder0<void>()); \
+	auto ctxCPSR = c.addCall(imm_ptr(NDS_Reschedule), ASMJIT_STDLIB_CALL_CONV, FuncBuilder0<void>()); \
 }
 
 #if PROFILER_JIT_LEVEL > 0
@@ -417,7 +395,7 @@
 	c.mov(SPSR, cpu_ptr(SPSR.val)); \
 	c.mov(tmp, SPSR); \
 	c.and_(tmp, 0x1F); \
-	auto ctx = c.addCall(imm_ptr(armcpu_switchMode), ASMJIT_CALL_CONV, FuncBuilder2<void, void *, uint8_t>()); \
+	auto ctx = c.addCall(imm_ptr(armcpu_switchMode), ASMJIT_STDLIB_CALL_CONV, FuncBuilder2<void, void *, uint8_t>()); \
 	ctx->setArg(0, bb_cpu); \
 	ctx->setArg(1, tmp); \
 	c.mov(cpu_ptr(CPSR.val), SPSR); \
@@ -1187,10 +1165,10 @@
 //   QADD / QDADD / QSUB / QDSUB
 // -----------------------------------------------------------------------------
 // TODO
-static int OP_QADD(uint32_t i) { printf("JIT: unimplemented OP_QADD\n"); return 0; }
-static int OP_QSUB(uint32_t i) { printf("JIT: unimplemented OP_QSUB\n"); return 0; }
-static int OP_QDADD(uint32_t i) { printf("JIT: unimplemented OP_QDADD\n"); return 0; }
-static int OP_QDSUB(uint32_t i) { printf("JIT: unimplemented OP_QDSUB\n"); return 0; }
+static int OP_QADD(uint32_t i) { fprintf(stderr, "JIT: unimplemented OP_QADD\n"); return 0; }
+static int OP_QSUB(uint32_t i) { fprintf(stderr, "JIT: unimplemented OP_QSUB\n"); return 0; }
+static int OP_QDADD(uint32_t i) { fprintf(stderr, "JIT: unimplemented OP_QDADD\n"); return 0; }
+static int OP_QDSUB(uint32_t i) { fprintf(stderr, "JIT: unimplemented OP_QDSUB\n"); return 0; }
 
 // -----------------------------------------------------------------------------
 //   MUL
@@ -1423,7 +1401,7 @@
 			{ \
 				c.mov(mode, rhs); \
 				c.and_(mode, 0x1F); \
-				auto ctx = c.addCall(imm_ptr(armcpu_switchMode), ASMJIT_CALL_CONV, \
+				auto ctx = c.addCall(imm_ptr(armcpu_switchMode), ASMJIT_STDLIB_CALL_CONV, \
 					FuncBuilder2<void, void *, uint8_t>()); \
 				ctx->setArg(0, bb_cpu); \
 				ctx->setArg(1, mode); \
@@ -1492,7 +1470,7 @@
 		/* armcpu_switchMode */ \
 		c.mov(mode, rhs); \
 		c.and_(mode, 0x1F); \
-		auto ctx = c.addCall(imm_ptr(armcpu_switchMode), ASMJIT_CALL_CONV, \
+		auto ctx = c.addCall(imm_ptr(armcpu_switchMode), ASMJIT_STDLIB_CALL_CONV, \
 			FuncBuilder2<void, void *, uint8_t>()); \
 		ctx->setArg(0, bb_cpu); \
 		ctx->setArg(1, mode); \
@@ -1925,12 +1903,12 @@
 
 	if (Rd_num == 14)
 	{
-		printf("OP_LDRD_STRD_POST_INDEX: use R14!!!!\n");
+		fprintf(stderr, "OP_LDRD_STRD_POST_INDEX: use R14!!!!\n");
 		return 0; // TODO: exception
 	}
 	if (Rd_num & 0x1)
 	{
-		printf("OP_LDRD_STRD_POST_INDEX: ERROR!!!!\n");
+		fprintf(stderr, "OP_LDRD_STRD_POST_INDEX: ERROR!!!!\n");
 		return 0; // TODO: exception
 	}
 	GpVar Rd = c.newGpVar(kVarTypeInt32);
@@ -1966,12 +1944,12 @@
 
 	if (Rd_num == 14)
 	{
-		printf("OP_LDRD_STRD_OFFSET_PRE_INDEX: use R14!!!!\n");
+		fprintf(stderr, "OP_LDRD_STRD_OFFSET_PRE_INDEX: use R14!!!!\n");
 		return 0; // TODO: exception
 	}
 	if (Rd_num & 0x1)
 	{
-		printf("OP_LDRD_STRD_OFFSET_PRE_INDEX: ERROR!!!!\n");
+		fprintf(stderr, "OP_LDRD_STRD_OFFSET_PRE_INDEX: ERROR!!!!\n");
 		return 0; // TODO: exception
 	}
 	GpVar Rd = c.newGpVar(kVarTypeInt32);
@@ -2089,7 +2067,7 @@
 #define LDM_INLINE inline
 #endif
 
-template<int PROCNUM, bool store, int dir> static LDM_INLINE FASTCALL uint32_t OP_LDM_STM_generic(uint32_t adr, uint64_t regs, int n)
+template<int PROCNUM, bool store, int dir> static LDM_INLINE LDM_FASTCALL uint32_t OP_LDM_STM_generic(uint32_t adr, uint64_t regs, int n)
 {
 	uint32_t cycles = 0;
 	adr &= ~3;
@@ -2112,7 +2090,7 @@
 #define ADV_CYCLES
 #endif
 
-template<int PROCNUM, bool store, int dir> static LDM_INLINE FASTCALL uint32_t OP_LDM_STM_other(uint32_t adr, uint64_t regs, int n)
+template<int PROCNUM, bool store, int dir> static LDM_INLINE LDM_FASTCALL uint32_t OP_LDM_STM_other(uint32_t adr, uint64_t regs, int n)
 {
 	uint32_t cycles = 0;
 	adr &= ~3;
@@ -2142,7 +2120,7 @@
 	return cycles;
 }
 
-template<int PROCNUM, bool store, int dir, bool null_compiled> static FORCEINLINE FASTCALL uint32_t OP_LDM_STM_main(uint32_t adr, uint64_t regs, int n, uint8_t *ptr, uint32_t cycles)
+template<int PROCNUM, bool store, int dir, bool null_compiled> static FORCEINLINE LDM_FASTCALL uint32_t OP_LDM_STM_main(uint32_t adr, uint64_t regs, int n, uint8_t *ptr, uint32_t cycles)
 {
 #ifdef ENABLE_ADVANCED_TIMING
 	cycles = 0;
@@ -2188,7 +2166,7 @@
 #undef ADV_CYCLES
 }
 
-template<int PROCNUM, bool store, int dir> static uint32_t FASTCALL OP_LDM_STM(uint32_t adr, uint64_t regs, int n)
+template<int PROCNUM, bool store, int dir> static uint32_t LDM_FASTCALL OP_LDM_STM(uint32_t adr, uint64_t regs, int n)
 {
 	// TODO use classify_adr?
 	uint32_t cycles;
@@ -2227,7 +2205,8 @@
 	return OP_LDM_STM_main<PROCNUM, store, dir, store>(adr, regs, n, ptr, cycles);
 }
 
-typedef uint32_t FASTCALL (*LDMOpFunc)(uint32_t, uint64_t, int);
+typedef uint32_t LDM_FASTCALL (*LDMOpFunc)(uint32_t, uint64_t, int);
+
 static const LDMOpFunc op_ldm_stm_tab[2][2][2] =
 {
 	{
@@ -2260,7 +2239,7 @@
 		GpVar regs_hi = c.newGpVar(kVarTypeInt32);
 		c.mov(regs_lo, get_reg_list(bitmask, dir) & 0xFFFFFFFF);
 		c.mov(regs_hi, get_reg_list(bitmask, dir) >> 32);
-		auto ctx = c.addCall(imm_ptr(op_ldm_stm_tab[PROCNUM][store][dir > 0]), ASMJIT_CALL_CONV,
+		auto ctx = c.addCall(imm_ptr(op_ldm_stm_tab[PROCNUM][store][dir > 0]), ASMJIT_STDLIB_CALL_CONV,
 			FuncBuilder4<uint32_t, uint32_t, uint32_t, uint32_t, int>());
 		ctx->setArg(0, adr);
 		ctx->setArg(1, regs_lo);
@@ -2339,7 +2318,7 @@
 	uint32_t pop = popcount(bitmask);
 	bool bit15 = !!BIT15(i);
 
-	//printf("ARM%c: %s R%d:%08X, bitmask %02X\n", PROCNUM?'7':'9', (store?"STM":"LDM"), REG_POS(i, 16), cpu->R[REG_POS(i, 16)], bitmask);
+	//fprintf(stderr, "ARM%c: %s R%d:%08X, bitmask %02X\n", PROCNUM?'7':'9', (store?"STM":"LDM"), REG_POS(i, 16), cpu->R[REG_POS(i, 16)], bitmask);
 	uint32_t adr_first = cpu->R[REG_POS(i, 16)];
 
 	GpVar adr = c.newGpVar(kVarTypeInt32);
@@ -2351,10 +2330,10 @@
 
 	if (!bit15 || store)
 	{
-		//if((cpu->CPSR.bits.mode==USR)||(cpu->CPSR.bits.mode==SYS)) { printf("ERROR1\n"); return 1; }
+		//if((cpu->CPSR.bits.mode==USR)||(cpu->CPSR.bits.mode==SYS)) { fprintf(stderr, "ERROR1\n"); return 1; }
 		//oldmode = armcpu_switchMode(cpu, SYS);
 		c.mov(oldmode, SYS);
-		auto ctx = c.addCall(imm_ptr(armcpu_switchMode), ASMJIT_CALL_CONV,
+		auto ctx = c.addCall(imm_ptr(armcpu_switchMode), ASMJIT_STDLIB_CALL_CONV,
 			FuncBuilder2<uint32_t, uint8_t *, uint8_t>());
 		ctx->setArg(0, bb_cpu);
 		ctx->setArg(1, oldmode);
@@ -2366,7 +2345,7 @@
 	if (!bit15 || store)
 	{
 		//armcpu_switchMode(cpu, oldmode);
-		auto ctx = c.addCall(imm_ptr(armcpu_switchMode), ASMJIT_CALL_CONV,
+		auto ctx = c.addCall(imm_ptr(armcpu_switchMode), ASMJIT_STDLIB_CALL_CONV,
 			FuncBuilder2<void, uint8_t *, uint8_t>());
 		ctx->setArg(0, bb_cpu);
 		ctx->setArg(1, oldmode);
@@ -2487,7 +2466,7 @@
 // -----------------------------------------------------------------------------
 #define maskPrecalc \
 { \
-	auto ctxM = c.addCall(imm_ptr(maskPrecalc), ASMJIT_CALL_CONV, FuncBuilder0<void>()); \
+	auto ctxM = c.addCall(imm_ptr(maskPrecalc), ASMJIT_STDLIB_CALL_CONV, FuncBuilder0<void>()); \
 }
 static int OP_MCR(uint32_t i)
 {
@@ -2498,12 +2477,12 @@
 	if (cpnum != 15)
 	{
 		// TODO - exception?
-		printf("JIT: MCR P%i, 0, R%i, C%i, C%i, %i, %i (don't allocated coprocessor)\n", cpnum, REG_POS(i, 12), REG_POS(i, 16), REG_POS(i, 0), (i >> 21) & 0x7, (i >> 5) & 0x7);
+		fprintf(stderr, "JIT: MCR P%i, 0, R%i, C%i, C%i, %i, %i (don't allocated coprocessor)\n", cpnum, REG_POS(i, 12), REG_POS(i, 16), REG_POS(i, 0), (i >> 21) & 0x7, (i >> 5) & 0x7);
 		return 2;
 	}
 	if (REG_POS(i, 12) == 15)
 	{
-		printf("JIT: MCR Rd=R15\n");
+		fprintf(stderr, "JIT: MCR Rd=R15\n");
 		return 2;
 	}
 
@@ -2723,7 +2702,7 @@
 
 	if (bUnknown)
 	{
-		//printf("Unknown MCR command: MRC P15, 0, R%i, C%i, C%i, %i, %i\n", REG_POS(i, 12), CRn, CRm, opcode1, opcode2);
+		//fprintf(stderr, "Unknown MCR command: MRC P15, 0, R%i, C%i, C%i, %i, %i\n", REG_POS(i, 12), CRn, CRm, opcode1, opcode2);
 		return 1;
 	}
 
@@ -2738,7 +2717,7 @@
 	uint32_t cpnum = REG_POS(i, 8);
 	if (cpnum != 15)
 	{
-		printf("MRC P%i, 0, R%i, C%i, C%i, %i, %i (don't allocated coprocessor)\n", cpnum, REG_POS(i, 12), REG_POS(i, 16), REG_POS(i, 0), (i>>21)&0x7, (i>>5)&0x7);
+		fprintf(stderr, "MRC P%i, 0, R%i, C%i, C%i, %i, %i (don't allocated coprocessor)\n", cpnum, REG_POS(i, 12), REG_POS(i, 16), REG_POS(i, 0), (i>>21)&0x7, (i>>5)&0x7);
 		return 2;
 	}
 
@@ -2928,7 +2907,7 @@
 
 	if (bUnknown)
 	{
-		//printf("Unknown MRC command: MRC P15, 0, R%i, C%i, C%i, %i, %i\n", REG_POS(i, 12), CRn, CRm, opcode1, opcode2);
+		//fprintf(stderr, "Unknown MRC command: MRC P15, 0, R%i, C%i, C%i, %i, %i\n", REG_POS(i, 12), CRn, CRm, opcode1, opcode2);
 		return 1;
 	}
 
@@ -2956,7 +2935,7 @@
 		// TODO:
 		return 0;
 #else
-		auto ctx = c.addCall(imm_ptr(ARM_swi_tab[PROCNUM][swinum]), ASMJIT_CALL_CONV, FuncBuilder0<uint32_t>());
+		auto ctx = c.addCall(imm_ptr(ARM_swi_tab[PROCNUM][swinum]), ASMJIT_STDLIB_CALL_CONV, FuncBuilder0<uint32_t>());
 		ctx->setRet(0, bb_cycles);
 		c.add(bb_cycles, 3);
 		return 1;
@@ -2970,7 +2949,7 @@
 	c.mov(oldCPSR, CPSR);
 	JIT_COMMENT("enter SVC mode");
 	c.mov(mode, imm(SVC));
-	auto ctx = c.addCall(imm_ptr(armcpu_switchMode), ASMJIT_CALL_CONV, FuncBuilder2<void, void *, uint8_t>());
+	auto ctx = c.addCall(imm_ptr(armcpu_switchMode), ASMJIT_STDLIB_CALL_CONV, FuncBuilder2<void, void *, uint8_t>());
 	ctx->setArg(0, bb_cpu);
 	ctx->setArg(1, mode);
 	c.unuse(mode);
@@ -2996,7 +2975,7 @@
 // -----------------------------------------------------------------------------
 //   BKPT
 // -----------------------------------------------------------------------------
-static int OP_BKPT(uint32_t i) { printf("JIT: unimplemented OP_BKPT\n"); return 0; }
+static int OP_BKPT(uint32_t i) { fprintf(stderr, "JIT: unimplemented OP_BKPT\n"); return 0; }
 
 // -----------------------------------------------------------------------------
 //   THUMB
@@ -3625,7 +3604,7 @@
 	uint32_t pop = popcount(bitmask);
 
 	//if (BIT_N(i, _REG_NUM(i, 8)))
-	//	printf("WARNING - %sIA with Rb in Rlist (THUMB)\n", store?"STM":"LDM");
+	//	fprintf(stderr, "WARNING - %sIA with Rb in Rlist (THUMB)\n", store?"STM":"LDM");
 
 	GpVar adr = c.newGpVar(kVarTypeInt32);
 	c.mov(adr, reg_pos_thumb(8));
@@ -4025,7 +4004,7 @@
 
 	if (!JIT_MAPPED(start_adr & 0x0FFFFFFF, PROCNUM))
 	{
-		printf("JIT: use unmapped memory address %08X\n", start_adr);
+		fprintf(stderr, "JIT: use unmapped memory address %08X\n", start_adr);
 		execute = false;
 		return 1;
 	}
@@ -4156,7 +4135,7 @@
 #endif
 	c.endFunc();
 
-	ArmOpCompiled f = static_cast<ArmOpCompiled>(c.make());
+	ArmOpCompiled f = (ArmOpCompiled)(c.make());
 	if (c.getError())
 	{
 		fprintf(stderr, "JIT error: %s\n", ErrorUtil::asString(c.getError()));
@@ -4205,13 +4184,14 @@
 #ifdef HAVE_STATIC_CODE_BUFFER
 	scratchptr = scratchpad;
 #endif
-	printf("CPU mode: %s\n", enable ? "JIT" : "Interpreter");
+	fprintf(stderr, "CPU mode: %s\n", enable ? "JIT" : "Interpreter");
 
 	if (enable)
 	{
-		printf("JIT max block size %d instruction(s)\n", CommonSettings.jit_max_block_size);
+		fprintf(stderr, "JIT max block size %d instruction(s)\n", CommonSettings.jit_max_block_size);
 #ifdef MAPPED_JIT_FUNCS
 		// these pointers are allocated by asmjit and need freeing
+#ifndef HAVE_STATIC_CODE_BUFFER
 		#define JITFREE(x)  for (size_t iii = 0; iii < ARRAY_SIZE((x)); ++iii) if ((x)[iii]) runtime.getMemMgr()->release(reinterpret_cast<void *>((x)[iii])); memset((x), 0, sizeof((x)));
 			JITFREE(JIT.MAIN_MEM);
 			JITFREE(JIT.SWIRAM);
@@ -4223,6 +4203,7 @@
 			JITFREE(JIT.ARM7_WIRAM);
 			JITFREE(JIT.ARM7_WRAM);
 		#undef JITFREE
+#endif
 
 		memset(recompile_counts, 0, sizeof(recompile_counts));
 		init_jit_mem();
@@ -4268,7 +4249,7 @@
 void arm_jit_close()
 {
 #if PROFILER_JIT_LEVEL > 0
-	printf("Generating profile report...");
+	fprintf(stderr, "Generating profile report...");
 
 	for (uint8_t proc = 0; proc < 2; ++proc)
 	{
@@ -4393,7 +4374,7 @@
 		}
 #endif
 	}
-	printf(" done.\n");
+	fprintf(stderr, " done.\n");
 #endif
 }
 #endif // HAVE_JIT

--- a/src/in_2sf/desmume/arm_jit.h
+++ b/src/in_2sf/desmume/arm_jit.h
@@ -27,7 +27,7 @@
 void arm_jit_sync();
 template<int PROCNUM> uint32_t arm_jit_compile();
 
-#if defined(_WINDOWS) || defined(DESMUME_COCOA)
+#if defined(_WINDOWS) || defined(DESMUME_COCOA) || defined(HAVE_JIT)
 # define MAPPED_JIT_FUNCS
 #endif
 

--- a/src/in_2sf/desmume/armcpu.cpp
+++ b/src/in_2sf/desmume/armcpu.cpp
@@ -139,7 +139,7 @@
 			armcpu->SPSR_und = armcpu->SPSR;
 			break;
 		default:
-			printf("switchMode: WRONG mode %02X\n",mode);
+			fprintf(stderr, "switchMode: WRONG mode %02X\n",mode);
 	}
 
 	switch (mode)
@@ -275,7 +275,7 @@
 	cpu->changeCPSR();
 	cpu->R[15] = cpu->intVector + number;
 	cpu->next_instruction = cpu->R[15];
-	printf("armcpu_exception!\n");
+	fprintf(stderr, "armcpu_exception!\n");
 
 	// HOW DOES THIS WORTK WITHOUT A PREFETCH, LIKE IRQ BELOW?
 	// I REALLY WISH WE DIDNT PREFETCH BEFORE EXECUTING
@@ -329,7 +329,7 @@
 
 	//cFetch = armcpu_prefetch(&ARMPROC);
 
-	//printf("%d: %08X\n",PROCNUM,ARMPROC.instruct_adr);
+	//fprintf(stderr, "%d: %08X\n",PROCNUM,ARMPROC.instruct_adr);
 
 	if (!ARMPROC.CPSR.bits.T)
 	{

--- a/src/in_2sf/desmume/armcpu.h
+++ b/src/in_2sf/desmume/armcpu.h
@@ -209,7 +209,7 @@
 	int stalled;
 
 #if defined(_M_X64) || defined(__x86_64__)
-	u8 cond_table[16 * 16];
+	uint8_t cond_table[16 * 16];
 #endif
 };
 

--- a/src/in_2sf/desmume/bios.cpp
+++ b/src/in_2sf/desmume/bios.cpp
@@ -23,6 +23,17 @@
 
 #define cpu (&ARMPROC)
 #define TEMPLATE template<int PROCNUM>
+
+struct CompressionHeader
+{
+public:
+	CompressionHeader(u32 _value) : value(_value) {}
+	u32 DataSize() const { return value&15; }
+	u32 Type() const { return (value>>4)&15; }
+	u32 DecompressedSize() const { return value>>24; }
+private:
+	u32 value;
+};
 
 static const uint16_t getsinetbl[] =
 {
@@ -673,7 +684,7 @@
 {
 	uint32_t source = cpu->R[0];
 	uint32_t dest = cpu->R[1];
-	uint32_t header = _MMU_read08<PROCNUM>(source);
+	uint32_t header = _MMU_read32<PROCNUM>(source);
 	source += 4;
 
 	if (!(source & 0xe000000) || !((source + ((header >> 8) & 0x1fffff)) & 0xe000000))
@@ -688,7 +699,7 @@
 	int len = header >> 8;
 
 	uint32_t mask = 0x80000000;
-	uint32_t data = _MMU_read08<PROCNUM>(source);
+	uint32_t data = _MMU_read32<PROCNUM>(source);
 	source += 4;
 
 	int pos = 0;
@@ -738,7 +749,7 @@
 				{
 					byteCount = 0;
 					byteShift = 0;
-					_MMU_write08<PROCNUM>(dest, writeValue & 0xFF);
+					_MMU_write32<PROCNUM>(dest, writeValue);
 					writeValue = 0;
 					dest += 4;
 					len -= 4;
@@ -748,7 +759,7 @@
 			if (!mask)
 			{
 				mask = 0x80000000;
-				data = _MMU_read08<PROCNUM>(source);
+				data = _MMU_read32<PROCNUM>(source);
 				source += 4;
 			}
 		}
@@ -801,7 +812,7 @@
 					{
 						byteCount = 0;
 						byteShift = 0;
-						_MMU_write08<PROCNUM>(dest, writeValue & 0xFF);
+						_MMU_write32<PROCNUM>(dest, writeValue);
 						dest += 4;
 						writeValue = 0;
 						len -= 4;
@@ -815,7 +826,7 @@
 			if (!mask)
 			{
 				mask = 0x80000000;
-				data = _MMU_read08<PROCNUM>(source);
+				data = _MMU_read32<PROCNUM>(source);
 				source += 4;
 			}
 		}
@@ -856,7 +867,7 @@
 	}
 
 	int revbits = 8 - bits;
-	uint32_t base = _MMU_read08<PROCNUM>(header + 4);
+	uint32_t base = _MMU_read32<PROCNUM>(header + 4);
 	int addBase = base & 0x80000000 ? 1 : 0;
 	base &= 0x7fffffff;
 
@@ -875,21 +886,21 @@
 		{
 			if (bitcount >= 8)
 				break;
-			uint32_t d = b & mask;
-			uint32_t temp = d >> bitcount;
-			if (!temp && addBase)
-				temp += base;
+      uint32_t temp = b & mask;
+      if (temp || addBase) {
+        temp += base;
+      }
 			data |= temp << bitwritecount;
 			bitwritecount += dataSize;
 			if (bitwritecount >= 32)
 			{
-				_MMU_write08<PROCNUM>(dest, data);
+				_MMU_write32<PROCNUM>(dest, data);
 				dest += 4;
 				data = 0;
 				bitwritecount = 0;
 			}
-			mask <<= bits;
 			bitcount += bits;
+      b >>= bits;
 		}
 	}
 	return 1;
@@ -899,13 +910,15 @@
 {
 	uint32_t source = cpu->R[0];
 	uint32_t dest = cpu->R[1];
-	uint32_t header = _MMU_read08<PROCNUM>(source);
+	CompressionHeader header(_MMU_read32<PROCNUM>(source));
 	source += 4;
 
-	if (!(source & 0xe000000) || !((source + ((header >> 8) & 0x1fffff)) & 0xe000000))
-		return 0;
-
-	int len = header >> 8;
+	int len = header.DecompressedSize();
+
+  if (PROCNUM == ARMCPU_ARM7) {
+    if (!(source & 0xe000000) || !((source + (len & 0x1fffff)) & 0xe000000))
+      return 0;
+  }
 
 	uint8_t data = _MMU_read08<PROCNUM>(source++);
 	_MMU_write08<PROCNUM>(dest++, data);
@@ -925,13 +938,10 @@
 {
 	uint32_t source = cpu->R[0];
 	uint32_t dest = cpu->R[1];
-	uint32_t header = _MMU_read08<PROCNUM>(source);
+	CompressionHeader header(_MMU_read32<PROCNUM>(source));
 	source += 4;
 
-	if (!(source & 0xe000000) || !((source + ((header >> 8) & 0x1fffff)) & 0xe000000))
-		return 0;
-
-	int len = header >> 8;
+	int len = header.DecompressedSize();
 
 	uint16_t data = _MMU_read16<PROCNUM>(source);
 	source += 2;
@@ -957,9 +967,15 @@
 	return 1;
 }
 
-TEMPLATE static uint32_t setHaltCR()
-{
-	_MMU_write08<PROCNUM>(0x4000300+cpu->proc_ID, cpu->R[0] & 0xFF);
+TEMPLATE static uint32_t CustomPost()
+{
+  _MMU_write08<PROCNUM>(REG_POSTFLG, cpu->R[0]);
+  return 1;
+}
+
+TEMPLATE static uint32_t CustomHalt()
+{
+	_MMU_write08<PROCNUM>(REG_HALTCNT, cpu->R[2]);
 	return 1;
 }
 
@@ -968,7 +984,7 @@
 	// ds returns garbage according to gbatek, but we must protect ourselves
 	if (cpu->R[0] >= ARRAY_SIZE(getsinetbl))
 	{
-		printf("Invalid SWI getSineTab: %08X\n", cpu->R[0]);
+		fprintf(stderr, "Invalid SWI getSineTab: %08X\n", cpu->R[0]);
 		return 1;
 	}
 
@@ -981,7 +997,7 @@
 	// ds returns garbage according to gbatek, but we must protect ourselves
 	if (cpu->R[0] >= ARRAY_SIZE(getpitchtbl))
 	{
-		printf("Invalid SWI getPitchTab: %08X\n", cpu->R[0]);
+		fprintf(stderr, "Invalid SWI getPitchTab: %08X\n", cpu->R[0]);
 		return 1;
 	}
 
@@ -994,7 +1010,7 @@
 	// ds returns garbage according to gbatek, but we must protect ourselves
 	if (cpu->R[0] >= ARRAY_SIZE(getvoltbl))
 	{
-		printf("Invalid SWI getVolumeTab: %08X\n", cpu->R[0]);
+		fprintf(stderr, "Invalid SWI getVolumeTab: %08X\n", cpu->R[0]);
 		return 1;
 	}
 
@@ -1097,7 +1113,7 @@
 		bios_nop<ARMCPU_ARM9>,             // 0x1C
 		bios_nop<ARMCPU_ARM9>,             // 0x1D
 		bios_nop<ARMCPU_ARM9>,             // 0x1E
-		setHaltCR<ARMCPU_ARM9>,            // 0x1F
+		CustomPost<ARMCPU_ARM9>,           // 0x1F
 	},
 	{
 		bios_nop<ARMCPU_ARM7>,             // 0x00
@@ -1122,7 +1138,7 @@
 		UnCompHuffman<ARMCPU_ARM7>,        // 0x13
 		RLUnCompWram<ARMCPU_ARM7>,         // 0x14
 		RLUnCompVram<ARMCPU_ARM7>,         // 0x15
-		Diff8bitUnFilterWram<ARMCPU_ARM7>, // 0x16
+		bios_nop<ARMCPU_ARM7>,             // 0x16
 		bios_nop<ARMCPU_ARM7>,             // 0x17
 		bios_nop<ARMCPU_ARM7>,             // 0x18
 		bios_nop<ARMCPU_ARM7>,             // 0x19
@@ -1131,7 +1147,7 @@
 		getVolumeTab<ARMCPU_ARM7>,         // 0x1C
 		getBootProcs<ARMCPU_ARM7>,         // 0x1D
 		bios_nop<ARMCPU_ARM7>,             // 0x1E
-		setHaltCR<ARMCPU_ARM7>,            // 0x1F
+		CustomHalt<ARMCPU_ARM7>,           // 0x1F
 	}
 };
 

--- a/src/in_2sf/desmume/cp15.cpp
+++ b/src/in_2sf/desmume/cp15.cpp
@@ -24,7 +24,7 @@
 
 bool armcp15_t::reset(armcpu_t *c)
 {
-	//printf("CP15 Reset\n");
+	//fprintf(stderr, "CP15 Reset\n");
 	this->cpu = c;
 	this->IDCode = 0x41059461;
 	this->cacheType = 0x0F0D2112;
@@ -225,7 +225,7 @@
 {
 	if (!this->cpu)
 	{
-		printf("ERROR: cp15 don\'t allocated\n");
+		fprintf(stderr, "ERROR: cp15 don\'t allocated\n");
 		return false;
 	}
 	if (this->cpu->CPSR.bits.mode == USR)
@@ -371,7 +371,7 @@
 {
 	if (!this->cpu)
 	{
-		printf("ERROR: cp15 don\'t allocated\n");
+		fprintf(stderr, "ERROR: cp15 don\'t allocated\n");
 		return false;
 	}
 	if (this->cpu->CPSR.bits.mode == USR)

--- a/src/in_2sf/desmume/mc.cpp
+++ b/src/in_2sf/desmume/mc.cpp
@@ -115,7 +115,7 @@
 			// copy User Settings 1 to User Settings 0 area
 			memcpy(&mc->data[0x3FE00], &mc->data[0x3FF00], 0x100);
 
-			printf("Firmware: save config");
+			fprintf(stderr, "Firmware: save config");
 			FILE *fp = fopen(mc->userfile, "wb");
 			if (fp)
 			{
@@ -124,15 +124,15 @@
 					if (fwrite(&mc->data[0x0002A], 1, 0x1D6, fp) == 0x1D6) // WiFi Settings
 					{
 						if (fwrite(&mc->data[0x3FA00], 1, 0x300, fp) == 0x300)  // WiFi AP Settings
-							printf(" - done\n");
+							fprintf(stderr, " - done\n");
 						else
-							printf(" - failed\n");
+							fprintf(stderr, " - failed\n");
 					}
 				}
 				fclose(fp);
 			}
 			else
-				printf(" - failed\n");
+				fprintf(stderr, " - failed\n");
 		}
 
 		mc->write_enable = false;
@@ -235,7 +235,7 @@
 				break;
 
 			default:
-				printf("Unhandled FW command: %02X\n", data);
+				fprintf(stderr, "Unhandled FW command: %02X\n", data);
 		}
 	}
 
@@ -468,7 +468,7 @@
 		fseek(fsrc, 0, SEEK_END);
 		uint32_t fsize = ftell(fsrc);
 		fseek(fsrc, 0, SEEK_SET);
-		//printf("Open %s file (size %i bytes)\n", fname, fsize);
+		//fprintf(stderr, "Open %s file (size %i bytes)\n", fname, fsize);
 
 		auto in_buf = std::unique_ptr<uint8_t[]>(new uint8_t[fsize]);
 
@@ -480,18 +480,18 @@
 			uint32_t size = 0;
 			if (!no_gba_unpackSAV(&in_buf[0], fsize, &out_buf[0], size))
 			{
-				//printf("New size %i byte(s)\n", size);
+				//fprintf(stderr, "New size %i byte(s)\n", size);
 				size = no_gba_savTrim(&out_buf[0], size);
-				//printf("--- new size after trim %i byte(s)\n", size);
+				//fprintf(stderr, "--- new size after trim %i byte(s)\n", size);
 				size = no_gba_fillLeft(size);
-				//printf("--- new size after fill %i byte(s)\n", size);
+				//fprintf(stderr, "--- new size after fill %i byte(s)\n", size);
 				raw_applyUserSettings(size);
 				this->data.resize(size);
 				for (uint32_t tt = 0; tt < size; ++tt)
 					this->data[tt] = out_buf[tt];
 
 				//dump back out as a dsv, just to keep things sane
-				printf("---- Loaded no$GBA save\n");
+				fprintf(stderr, "---- Loaded no$GBA save\n");
 
 				fclose(fsrc);
 				return true;
@@ -516,7 +516,7 @@
 	if (inf->fail())
 	{
 		// no dsv found; we need to try auto-importing a file with .sav extension
-		printf("DeSmuME .dsv save file not found. Trying to load an old raw .sav file.\n");
+		fprintf(stderr, "DeSmuME .dsv save file not found. Trying to load an old raw .sav file.\n");
 
 		// change extension to sav
 		char tmp[MAX_PATH];
@@ -527,7 +527,7 @@
 		inf.reset(new EMUFILE_FILE(tmp, "rb"));
 		if (inf->fail())
 		{
-			printf("Missing save file %s\n", this->filename.c_str());
+			fprintf(stderr, "Missing save file %s\n", this->filename.c_str());
 			return;
 		}
 
@@ -545,7 +545,7 @@
 		if (cmp)
 		{
 			// maybe it is a misnamed raw save file. try loading it that way
-			printf("Not a DeSmuME .dsv save file. Trying to load as raw.\n");
+			fprintf(stderr, "Not a DeSmuME .dsv save file. Trying to load as raw.\n");
 			if (!this->load_no_gba(this->filename.c_str()))
 				this->load_raw(this->filename.c_str());
 			return;
@@ -557,7 +557,7 @@
 		read32le(&version, inf.get());
 		if (version)
 		{
-			printf("Unknown save file format\n");
+			fprintf(stderr, "Unknown save file format\n");
 			return;
 		}
 		inf->fseek(-24, SEEK_CUR);

--- a/src/in_2sf/desmume/mc.h
+++ b/src/in_2sf/desmume/mc.h
@@ -24,7 +24,7 @@
 #include <cstdio>
 #include "types.h"
 #include "emufile.h"
-#include "windowsh_wrapper.h"
+//#include "windowsh_wrapper.h"
 
 #define MAX_SAVE_TYPES 13
 #define MC_TYPE_AUTODETECT      0x0

--- a/src/in_2sf/desmume/metaspu/SndOut.cpp
+++ /dev/null
@@ -1,227 +1,1 @@
-/* SPU2-X, A plugin for Emulating the Sound Processing Unit of the Playstation 2
- * Developed and maintained by the Pcsx2 Development Team.
- *
- * Original portions from SPU2ghz are (c) 2008 by David Quintana [gigaherz]
- *
- * SPU2-X is free software: you can redistribute it and/or modify it under the terms
- * of the GNU Lesser General Public License as published by the Free Software Found-
- * ation, either version 3 of the License, or (at your option) any later version.
- *
- * SPU2-X is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
- * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
- * PURPOSE.  See the GNU Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with SPU2-X.  If not, see <http://www.gnu.org/licenses/>.
- */
 
-#include <cassert>
-#include "../types.h"
-#include "SndOut.h"
-
-//----------------
-static const int SndOutLatencyMS = 160;
-static bool timeStretchDisabled = false;
-//----------------
-
-StereoOut32 StereoOut32::Empty;
-
-StereoOut32::StereoOut32(const StereoOut16 &src) : Left(src.Left), Right(src.Right)
-{
-}
-
-StereoOut32::StereoOut32(const StereoOutFloat &src) : Left(static_cast<int32_t>(src.Left * 2147483647.0f)), Right(static_cast<int32_t>(src.Right * 2147483647.0f))
-{
-}
-
-StereoOut16 StereoOut32::DownSample() const
-{
-	return StereoOut16((Left >> SndOutVolumeShift) & 0xFFFF, (Right >> SndOutVolumeShift) & 0xFFFF);
-}
-
-std::unique_ptr<StereoOut32[]> SndBuffer::m_buffer;
-int32_t SndBuffer::m_size;
-int32_t SndBuffer::m_rpos;
-int32_t SndBuffer::m_wpos;
-int32_t SndBuffer::m_data;
-
-bool SndBuffer::m_underrun_freeze;
-std::unique_ptr<StereoOut32[]> SndBuffer::sndTempBuffer;
-int SndBuffer::sndTempProgress = 0;
-
-inline int GetAlignedBufferSize(int comp)
-{
-	return (comp + SndOutPacketSize - 1) & ~(SndOutPacketSize - 1);
-}
-
-// Returns true if there is data to be output, or false if no data
-// is available to be copied.
-bool SndBuffer::CheckUnderrunStatus(int &nSamples, int &quietSampleCount)
-{
-	quietSampleCount = 0;
-	if (m_underrun_freeze)
-	{
-		int toFill = static_cast<int>(m_size * (timeStretchDisabled ? 0.50f : 0.1f));
-		toFill = GetAlignedBufferSize(toFill);
-
-		// toFill is now aligned to a SndOutPacket
-
-		if (m_data < toFill)
-		{
-			quietSampleCount = nSamples;
-			return false;
-		}
-
-		m_underrun_freeze = false;
-		//TODO
-		//if( MsgOverruns() )
-			printf(" * SPU2 > Underrun compensation (%d packets buffered)\n", toFill / SndOutPacketSize);
-		lastPct = 0.0; // normalize timestretcher
-	}
-	else if (m_data < nSamples)
-	{
-		nSamples = m_data;
-		quietSampleCount = SndOutPacketSize - m_data;
-		m_underrun_freeze = true;
-
-		if (!timeStretchDisabled)
-			timeStretchUnderrun();
-
-		return !!nSamples;
-	}
-
-	return true;
-}
-
-void SndBuffer::_InitFail()
-{
-	// If a failure occurs, just initialize the NoSound driver.  This'll allow
-	// the game to emulate properly (hopefully), albeit without sound.
-	//OutputModule = FindOutputModuleById( NullOut.GetIdent() );
-	//mods[OutputModule]->Init();
-}
-
-void SndBuffer::_WriteSamples(StereoOut32 *bData, int nSamples)
-{
-	int free = m_size - m_data;
-	m_predictData = 0;
-
-	assert(m_data <= m_size);
-
-	// Problem:
-	//  If the SPU2 gets out of sync with the SndOut device, the writepos of the
-	//  circular buffer will overtake the readpos, leading to a prolonged period
-	//  of hopscotching read/write accesses (ie, lots of staticy crap sound for
-	//  several seconds).
-	//
-	// Compromise:
-	//  When an overrun occurs, we adapt by discarding a portion of the buffer.
-	//  The older portion of the buffer is discarded rather than incoming data,
-	//  so that the overall audio synchronization is better.
-
-	if (free < nSamples)
-	{
-		// Buffer overrun!
-		// Dump samples from the read portion of the buffer instead of dropping
-		// the newly written stuff.
-
-		int32_t comp;
-
-		if (!timeStretchDisabled)
-			comp = timeStretchOverrun();
-		else
-		{
-			// Toss half the buffer plus whatever's being written anew:
-			comp = GetAlignedBufferSize((m_size + nSamples) / 2);
-			if (comp > m_size - SndOutPacketSize)
-				comp = m_size - SndOutPacketSize;
-		}
-
-		m_data -= comp;
-		m_rpos = (m_rpos + comp) % m_size;
-		//TODO
-		//if( MsgOverruns() )
-			printf(" * SPU2 > Overrun Compensation (%d packets tossed)\n", comp / SndOutPacketSize);
-		lastPct = 0.0; // normalize the timestretcher
-	}
-
-	// copy in two phases, since there's a chance the packet
-	// wraps around the buffer (it'd be nice to deal in packets only, but
-	// the timestretcher and DSP options require flexibility).
-
-	int endPos = m_wpos + nSamples;
-	int secondCopyLen = endPos - m_size;
-	StereoOut32 *wposbuffer = &m_buffer[m_wpos];
-
-	m_data += nSamples;
-	if (secondCopyLen > 0)
-	{
-		nSamples -= secondCopyLen;
-		memcpy(m_buffer.get(), &bData[nSamples], secondCopyLen * sizeof(*bData));
-		m_wpos = secondCopyLen;
-	}
-	else
-		m_wpos += nSamples;
-
-	memcpy(wposbuffer, bData, nSamples * sizeof(*bData));
-}
-
-void SndBuffer::Init()
-{
-	// initialize sound buffer
-	// Buffer actually attempts to run ~50%, so allocate near double what
-	// the requested latency is:
-
-	m_rpos = m_wpos = m_data = 0;
-
-	try
-	{
-		float latencyMS = SndOutLatencyMS * (timeStretchDisabled ? 1.5f : 2.0f);
-		m_size = GetAlignedBufferSize(static_cast<int>(latencyMS * SampleRate / 1000.0f));
-		m_buffer.reset(new StereoOut32[m_size]);
-		m_underrun_freeze = false;
-
-		sndTempBuffer.reset(new StereoOut32[SndOutPacketSize]);
-	}
-	catch(const std::bad_alloc &)
-	{
-		// out of memory exception (most likely)
-
-		printf("Out of memory error occurred while initializing SPU2.");
-		_InitFail();
-		return;
-	}
-
-	// clear buffers!
-	// Fixes loopy sounds on emu resets.
-	memset(sndTempBuffer.get(), 0, sizeof(StereoOut32) * SndOutPacketSize);
-
-	sndTempProgress = 0;
-
-	soundtouchInit(); // initializes the timestretching
-
-	// some crap
-	//spdif_set51(mods[OutputModule]->Is51Out());
-
-	// initialize module
-	//if( mods[OutputModule]->Init() == -1 ) _InitFail();
-}
-
-void SndBuffer::Write(const StereoOut32 &Sample)
-{
-	//if(mods[OutputModule] == &NullOut) // null output doesn't need buffering or stretching! :p
-	//	return;
-
-	sndTempBuffer[sndTempProgress++] = Sample;
-
-	// If we haven't accumulated a full packet yet, do nothing more:
-	if (sndTempProgress < SndOutPacketSize)
-		return;
-	sndTempProgress = 0;
-
-	if( !timeStretchDisabled )
-		timeStretchWrite();
-	else
-		_WriteSamples(sndTempBuffer.get(), SndOutPacketSize);
-}
-

--- a/src/in_2sf/desmume/metaspu/SndOut.h
+++ /dev/null
@@ -1,215 +1,1 @@
-/* SPU2-X, A plugin for Emulating the Sound Processing Unit of the Playstation 2
- * Developed and maintained by the Pcsx2 Development Team.
- *
- * Original portions from SPU2ghz are (c) 2008 by David Quintana [gigaherz]
- *
- * SPU2-X is free software: you can redistribute it and/or modify it under the terms
- * of the GNU Lesser General Public License as published by the Free Software Found-
- * ation, either version 3 of the License, or (at your option) any later version.
- *
- * SPU2-X is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
- * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
- * PURPOSE.  See the GNU Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with SPU2-X.  If not, see <http://www.gnu.org/licenses/>.
- */
 
-#pragma once
-
-#include <memory>
-#include <algorithm>
-#include "../types.h"
-
-struct StereoOut16;
-struct StereoOutFloat;
-
-struct StereoOut32
-{
-	static StereoOut32 Empty;
-
-	int32_t Left, Right;
-
-	StereoOut32() : Left(0), Right(0)
-	{
-	}
-
-	StereoOut32(int32_t left, int32_t right) : Left(left), Right(right)
-	{
-	}
-
-	StereoOut32(const StereoOut16 &src);
-	explicit StereoOut32(const StereoOutFloat &src);
-
-	StereoOut16 DownSample() const;
-
-	StereoOut32 operator+(const StereoOut32 &right) const
-	{
-		return StereoOut32(this->Left + right.Left, this->Right + right.Right);
-	}
-
-	StereoOut32 operator/(int src) const
-	{
-		return StereoOut32(this->Left / src, this->Right / src);
-	}
-};
-
-// Number of stereo samples per SndOut block.
-// All drivers must work in units of this size when communicating with
-// SndOut.
-const int SndOutPacketSize = 512;
-
-// edit - zeromus 23-oct-2009
-// this is hardcoded differently for metaspu
-const int SndOutVolumeShift = 0;
-
-// Samplerate of the SPU2. For accurate playback we need to match this
-// exactly.  Trying to scale samplerates and maintain SPU2's Ts timing accuracy
-// is too problematic. :)
-// this is hardcoded differently for metaspu
-// edit - zeromus 23-oct-2009
-//const int SampleRate = 48000;
-//const int SampleRate = 44100;
-// edit - nitsuja: make it use the global sample rate define
-#include "../SPU.h"
-const int SampleRate = DESMUME_SAMPLE_RATE;
-
-struct StereoOut16
-{
-	int16_t Left, Right;
-
-	StereoOut16() : Left(0), Right(0)
-	{
-	}
-
-	StereoOut16(const StereoOut32 &src) : Left(src.Left & 0xFFFF), Right(src.Right & 0xFFFF)
-	{
-	}
-
-	StereoOut16(int16_t left, int16_t right) : Left(left), Right(right)
-	{
-	}
-
-	void ResampleFrom(const StereoOut32 &src)
-	{
-		// Use StereoOut32's built in conversion
-		*this = src.DownSample();
-	}
-};
-
-struct StereoOutFloat
-{
-	float Left, Right;
-
-	StereoOutFloat() : Left(0.0f), Right(0.0f)
-	{
-	}
-
-	explicit StereoOutFloat(const StereoOut32 &src) : Left(src.Left / 2147483647.0f), Right(src.Right / 2147483647.0f)
-	{
-	}
-
-	explicit StereoOutFloat(int32_t left, int32_t right) : Left(left / 2147483647.0f), Right(right / 2147483647.0f)
-	{
-	}
-
-	StereoOutFloat(float left, float right) : Left(left), Right(right)
-	{
-	}
-};
-
-// Developer Note: This is a static class only (all static members).
-class SndBuffer
-{
-private:
-	static bool m_underrun_freeze;
-	static int32_t m_predictData;
-	static float lastPct;
-
-	static std::unique_ptr<StereoOut32[]> sndTempBuffer;
-
-	static int sndTempProgress;
-
-	static std::unique_ptr<StereoOut32[]> m_buffer;
-	static int32_t m_size;
-	static int32_t m_rpos;
-	static int32_t m_wpos;
-	static int32_t m_data;
-
-	static float lastEmergencyAdj;
-	static float cTempo;
-	static float eTempo;
-	static int freezeTempo;
-
-	static void _InitFail();
-	static void _WriteSamples(StereoOut32 *bData, int nSamples);
-	static bool CheckUnderrunStatus(int &nSamples, int &quietSampleCount);
-
-	static void soundtouchInit();
-	static void timeStretchWrite();
-	static void timeStretchUnderrun();
-	static int32_t timeStretchOverrun();
-
-	static void PredictDataWrite(int samples);
-	static float GetStatusPct();
-	static void UpdateTempoChange();
-
-public:
-	static void Init();
-	static void Write(const StereoOut32 &Sample);
-
-	// Note: When using with 32 bit output buffers, the user of this function is responsible
-	// for shifting the values to where they need to be manually.  The fixed point depth of
-	// the sample output is determined by the SndOutVolumeShift, which is the number of bits
-	// to shift right to get a 16 bit result.
-	template<typename T> static void ReadSamples(T *bData)
-	{
-		int nSamples = SndOutPacketSize;
-
-		// Problem:
-		//  If the SPU2 gets even the least bit out of sync with the SndOut device,
-		//  the readpos of the circular buffer will overtake the writepos,
-		//  leading to a prolonged period of hopscotching read/write accesses (ie,
-		//  lots of staticy crap sound for several seconds).
-		//
-		// Fix:
-		//  If the read position overtakes the write position, abort the
-		//  transfer immediately and force the SndOut driver to wait until
-		//  the read buffer has filled up again before proceeding.
-		//  This will cause one brief hiccup that can never exceed the user's
-		//  set buffer length in duration.
-
-		int quietSamples;
-		if (CheckUnderrunStatus(nSamples, quietSamples))
-		{
-			assert(nSamples <= SndOutPacketSize);
-
-			// [Air] [TODO]: This loop is probably a candidate for SSE2 optimization.
-
-			int endPos = m_rpos + nSamples;
-			int secondCopyLen = endPos - m_size;
-			const StereoOut32 *rposbuffer = &m_buffer[m_rpos];
-
-			m_data -= nSamples;
-
-			if (secondCopyLen > 0)
-			{
-				nSamples -= secondCopyLen;
-				for (int i = 0; i < secondCopyLen; ++i)
-					bData[nSamples + i].ResampleFrom(m_buffer[i]);
-				m_rpos = secondCopyLen;
-			}
-			else
-				m_rpos += nSamples;
-
-			for (int i = 0; i < nSamples; ++i)
-				bData[i].ResampleFrom(rposbuffer[i]);
-		}
-
-		// If quietSamples != 0 it means we have an underrun...
-		// Let's just dull out some silence, because that's usually the least
-		// painful way of dealing with underruns:
-		memset(bData, 0, quietSamples * sizeof(T));
-	}
-};
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/AAFilter.cpp
+++ /dev/null
@@ -1,156 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// FIR low-pass (anti-alias) filter with filter coefficient design routine and
-/// MMX optimization.
-///
-/// Anti-alias filter is used to prevent folding of high frequencies when
-/// transposing the sample rate with interpolation.
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2006/02/05 16:44:06 $
-// File revision : $Revision: 1.9 $
-//
-// $Id: AAFilter.cpp,v 1.9 2006/02/05 16:44:06 Olli Exp $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#include "XSFCommon.h"
-
-#include <vector>
-#include <cassert>
-#include "AAFilter.h"
-
-using namespace soundtouch;
-
-#ifndef M_PI
-static const double M_PI = 3.14159265358979323846;
-#endif
-
-/*****************************************************************************
- *
- * Implementation of the class 'AAFilter'
- *
- *****************************************************************************/
-
-AAFilter::AAFilter(const uint32_t len)
-{
-	this->pFIR.reset(FIRFilter::newInstance());
-	this->cutoffFreq = 0.5;
-	this->setLength(len);
-}
-
-// Sets new anti-alias filter cut-off edge frequency, scaled to
-// sampling frequency (nyquist frequency = 0.5).
-// The filter will cut frequencies higher than the given frequency.
-void AAFilter::setCutoffFreq(double newCutoffFreq)
-{
-	this->cutoffFreq = newCutoffFreq;
-	this->calculateCoeffs();
-}
-
-// Sets number of FIR filter taps
-void AAFilter::setLength(uint32_t newLength)
-{
-	this->length = newLength;
-	this->calculateCoeffs();
-}
-
-// Calculates coefficients for a low-pass FIR filter using Hamming window
-void AAFilter::calculateCoeffs()
-{
-	assert(this->length > 0);
-	assert(!(this->length % 4));
-	assert(this->cutoffFreq >= 0);
-	assert(this->cutoffFreq <= 0.5);
-
-	auto work = std::vector<double>(this->length);
-	auto coeffs = std::vector<SAMPLETYPE>(this->length);
-
-	double fc2 = 2.0 * this->cutoffFreq;
-	double wc = M_PI * fc2;
-	double tempCoeff = 2 * M_PI / this->length;
-
-	double sum = 0.0;
-	for (uint32_t i = 0; i < this->length; ++i)
-	{
-		double cntTemp = i - (this->length / 2);
-
-		double temp = cntTemp * wc, h;
-		if (!fEqual(temp, 0.0))
-			h = fc2 * std::sin(temp) / temp; // sinc function
-		else
-			h = 1.0;
-		double w = 0.54 + 0.46 * std::cos(tempCoeff * cntTemp); // hamming window
-
-		temp = w * h;
-		work[i] = temp;
-
-		// calc net sum of coefficients
-		sum += temp;
-	}
-
-	// ensure the sum of coefficients is larger than zero
-	assert(sum > 0);
-
-	// ensure we've really designed a lowpass filter...
-	assert(work[this->length / 2] > 0);
-	assert(work[this->length / 2 + 1] > -1e-6);
-	assert(work[this->length / 2 - 1] > -1e-6);
-
-	// Calculate a scaling coefficient in such a way that the result can be
-	// divided by 16384
-	double scaleCoeff = 16384.0 / sum;
-
-	for (uint32_t i = 0; i < this->length; ++i)
-	{
-		// scale & round to nearest integer
-		double temp = work[i] * scaleCoeff;
-		temp += temp >= 0 ? 0.5 : -0.5;
-		// ensure no overfloods
-		assert(temp >= -32768 && temp <= 32767);
-		coeffs[i] = static_cast<SAMPLETYPE>(temp);
-	}
-
-	// Set coefficients. Use divide factor 14 => divide result by 2^14 = 16384
-	this->pFIR->setCoefficients(&coeffs[0], length, 14);
-}
-
-// Applies the filter to the given sequence of samples.
-// Note : The amount of outputted samples is by value of 'filter length'
-// smaller than the amount of input samples.
-uint32_t AAFilter::evaluate(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples, uint32_t numChannels) const
-{
-	return this->pFIR->evaluate(dest, src, numSamples, numChannels);
-}
-
-uint32_t AAFilter::getLength() const
-{
-	return this->pFIR->getLength();
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/AAFilter.h
+++ /dev/null
@@ -1,85 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// Sampled sound tempo changer/time stretch algorithm. Changes the sound tempo
-/// while maintaining the original pitch by using a time domain WSOLA-like method
-/// with several performance-increasing tweaks.
-///
-/// Anti-alias filter is used to prevent folding of high frequencies when
-/// transposing the sample rate with interpolation.
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2006/02/05 16:44:06 $
-// File revision : $Revision: 1.10 $
-//
-// $Id: AAFilter.h,v 1.10 2006/02/05 16:44:06 Olli Exp $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#pragma once
-
-#include "FIRFilter.h"
-
-namespace soundtouch
-{
-
-class AAFilter
-{
-protected:
-	std::unique_ptr<FIRFilter> pFIR;
-
-	/// Low-pass filter cut-off frequency, negative = invalid
-	double cutoffFreq;
-
-	/// num of filter taps
-	uint32_t length;
-
-	/// Calculate the FIR coefficients realizing the given cutoff-frequency
-	void calculateCoeffs();
-
-public:
-	AAFilter(uint32_t length);
-
-	/// Sets new anti-alias filter cut-off edge frequency, scaled to sampling
-	/// frequency (nyquist frequency = 0.5). The filter will cut off the
-	/// frequencies than that.
-	void setCutoffFreq(double newCutoffFreq);
-
-	/// Sets number of FIR filter taps, i.e. ~filter complexity
-	void setLength(uint32_t newLength);
-
-	uint32_t getLength() const;
-
-	/// Applies the filter to the given sequence of samples.
-	/// Note : The amount of outputted samples is by value of 'filter length'
-	/// smaller than the amount of input samples.
-	uint32_t evaluate(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples, uint32_t numChannels) const;
-};
-
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/FIFOSampleBuffer.cpp
+++ /dev/null
@@ -1,227 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// A buffer class for temporarily storaging sound samples, operates as a
-/// first-in-first-out pipe.
-///
-/// Samples are added to the end of the sample buffer with the 'putSamples'
-/// function, and are received from the beginning of the buffer by calling
-/// the 'receiveSamples' function. The class automatically removes the
-/// outputted samples from the buffer, as well as grows the buffer size
-/// whenever necessary.
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2012-11-08 16:53:01 -0200 (qui, 08 nov 2012) $
-// File revision : $Revision: 4 $
-//
-// $Id: FIFOSampleBuffer.cpp 160 2012-11-08 18:53:01Z oparviai $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#include <stdexcept>
-#include <cstring>
-#include "FIFOSampleBuffer.h"
-
-using namespace soundtouch;
-
-// Constructor
-FIFOSampleBuffer::FIFOSampleBuffer(int32_t numChannels)
-{
-	assert(numChannels > 0);
-	this->sizeInBytes = 0; // reasonable initial value
-	this->buffer = nullptr;
-	this->bufferUnaligned.reset();
-	this->samplesInBuffer = 0;
-	this->bufferPos = 0;
-	this->channels = numChannels;
-	this->ensureCapacity(32); // allocate initial capacity
-}
-
-// Sets number of channels, 1 = mono, 2 = stereo
-void FIFOSampleBuffer::setChannels(int32_t numChannels)
-{
-	assert(numChannels > 0);
-	uint32_t usedBytes = this->channels * this->samplesInBuffer;
-	this->channels = numChannels;
-	this->samplesInBuffer = usedBytes / this->channels;
-}
-
-// if output location pointer 'bufferPos' isn't zero, 'rewinds' the buffer and
-// zeroes this pointer by copying samples from the 'bufferPos' pointer
-// location on to the beginning of the buffer.
-void FIFOSampleBuffer::rewind()
-{
-	if (this->buffer && this->bufferPos)
-	{
-		memmove(this->buffer, this->ptrBegin(), sizeof(SAMPLETYPE) * this->channels * this->samplesInBuffer);
-		this->bufferPos = 0;
-	}
-}
-
-// Adds 'numSamples' pcs of samples from the 'samples' memory position to
-// the sample buffer.
-void FIFOSampleBuffer::putSamples(const SAMPLETYPE *samples, uint32_t nSamples)
-{
-	memcpy(this->ptrEnd(nSamples), samples, sizeof(SAMPLETYPE) * nSamples * this->channels);
-	this->samplesInBuffer += nSamples;
-}
-
-// Increases the number of samples in the buffer without copying any actual
-// samples.
-//
-// This function is used to update the number of samples in the sample buffer
-// when accessing the buffer directly with 'ptrEnd' function. Please be
-// careful though!
-void FIFOSampleBuffer::putSamples(uint32_t nSamples)
-{
-	uint32_t req = this->samplesInBuffer + nSamples;
-	this->ensureCapacity(req);
-	this->samplesInBuffer += nSamples;
-}
-
-// Returns a pointer to the end of the used part of the sample buffer (i.e.
-// where the new samples are to be inserted). This function may be used for
-// inserting new samples into the sample buffer directly. Please be careful!
-//
-// Parameter 'slackCapacity' tells the function how much free capacity (in
-// terms of samples) there _at least_ should be, in order to the caller to
-// succesfully insert all the required samples to the buffer. When necessary,
-// the function grows the buffer size to comply with this requirement.
-//
-// When using this function as means for inserting new samples, also remember
-// to increase the sample count afterwards, by calling  the
-// 'putSamples(numSamples)' function.
-SAMPLETYPE *FIFOSampleBuffer::ptrEnd(uint32_t slackCapacity)
-{
-	this->ensureCapacity(this->samplesInBuffer + slackCapacity);
-	return &this->buffer[this->samplesInBuffer * this->channels];
-}
-
-// Returns a pointer to the beginning of the currently non-outputted samples.
-// This function is provided for accessing the output samples directly.
-// Please be careful!
-//
-// When using this function to output samples, also remember to 'remove' the
-// outputted samples from the buffer by calling the
-// 'receiveSamples(numSamples)' function
-SAMPLETYPE *FIFOSampleBuffer::ptrBegin()
-{
-	assert(this->buffer);
-	return &this->buffer[this->bufferPos * this->channels];
-}
-
-// Ensures that the buffer has enought capacity, i.e. space for _at least_
-// 'capacityRequirement' number of samples. The buffer is grown in steps of
-// 4 kilobytes to eliminate the need for frequently growing up the buffer,
-// as well as to round the buffer size up to the virtual memory page size.
-void FIFOSampleBuffer::ensureCapacity(uint32_t capacityRequirement)
-{
-	if (capacityRequirement > this->getCapacity())
-	{
-		// enlarge the buffer in 4kbyte steps (round up to next 4k boundary)
-		this->sizeInBytes = (capacityRequirement * this->channels * sizeof(SAMPLETYPE) + 4095) & static_cast<uint32_t>(-4096);
-		assert(!(this->sizeInBytes % 2));
-		auto tempUnaligned = std::unique_ptr<SAMPLETYPE[]>(new SAMPLETYPE[(this->sizeInBytes + 16) / sizeof(SAMPLETYPE)]);
-		// Align the buffer to begin at 16byte cache line boundary for optimal performance
-		SAMPLETYPE *temp = reinterpret_cast<SAMPLETYPE *>(SOUNDTOUCH_ALIGN_POINTER_16(tempUnaligned.get()));
-		if (samplesInBuffer)
-			memcpy(temp, this->ptrBegin(), samplesInBuffer * this->channels * sizeof(SAMPLETYPE));
-		this->buffer = temp;
-		this->bufferUnaligned = std::move(tempUnaligned);
-		this->bufferPos = 0;
-	}
-	else
-		// simply rewind the buffer (if necessary)
-		this->rewind();
-}
-
-// Returns the current buffer capacity in terms of samples
-uint32_t FIFOSampleBuffer::getCapacity() const
-{
-	return this->sizeInBytes / (this->channels * sizeof(SAMPLETYPE));
-}
-
-// Returns the number of samples currently in the buffer
-uint32_t FIFOSampleBuffer::numSamples() const
-{
-	return this->samplesInBuffer;
-}
-
-// Output samples from beginning of the sample buffer. Copies demanded number
-// of samples to output and removes them from the sample buffer. If there
-// are less than 'numsample' samples in the buffer, returns all available.
-//
-// Returns number of samples copied.
-uint32_t FIFOSampleBuffer::receiveSamples(SAMPLETYPE *output, uint32_t maxSamples)
-{
-	uint32_t num = maxSamples > this->samplesInBuffer ? this->samplesInBuffer : maxSamples;
-
-	memcpy(output, this->ptrBegin(), this->channels * sizeof(SAMPLETYPE) * num);
-	return this->receiveSamples(num);
-}
-
-// Removes samples from the beginning of the sample buffer without copying them
-// anywhere. Used to reduce the number of samples in the buffer, when accessing
-// the sample buffer with the 'ptrBegin' function.
-uint32_t FIFOSampleBuffer::receiveSamples(uint32_t maxSamples)
-{
-	if (maxSamples >= this->samplesInBuffer)
-	{
-		uint32_t temp = this->samplesInBuffer;
-		this->samplesInBuffer = 0;
-		return temp;
-	}
-
-	this->samplesInBuffer -= maxSamples;
-	this->bufferPos += maxSamples;
-
-	return maxSamples;
-}
-
-// Returns nonzero if the sample buffer is empty
-bool FIFOSampleBuffer::isEmpty() const
-{
-	return !this->samplesInBuffer;
-}
-
-// Clears the sample buffer
-void FIFOSampleBuffer::clear()
-{
-	this->samplesInBuffer = 0;
-	this->bufferPos = 0;
-}
-
-/// allow trimming (downwards) amount of samples in pipeline.
-/// Returns adjusted amount of samples
-uint32_t FIFOSampleBuffer::adjustAmountOfSamples(uint32_t numSmpls)
-{
-	if (numSmpls < this->samplesInBuffer)
-		this->samplesInBuffer = numSmpls;
-	return this->samplesInBuffer;
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/FIFOSampleBuffer.h
+++ /dev/null
@@ -1,173 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// A buffer class for temporarily storaging sound samples, operates as a
-/// first-in-first-out pipe.
-///
-/// Samples are added to the end of the sample buffer with the 'putSamples'
-/// function, and are received from the beginning of the buffer by calling
-/// the 'receiveSamples' function. The class automatically removes the
-/// output samples from the buffer as well as grows the storage size
-/// whenever necessary.
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2012-06-13 16:29:53 -0300 (qua, 13 jun 2012) $
-// File revision : $Revision: 4 $
-//
-// $Id: FIFOSampleBuffer.h 143 2012-06-13 19:29:53Z oparviai $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#pragma once
-
-#include <memory>
-#include "FIFOSamplePipe.h"
-
-namespace soundtouch
-{
-
-/// Sample buffer working in FIFO (first-in-first-out) principle. The class takes
-/// care of storage size adjustment and data moving during input/output operations.
-///
-/// Notice that in case of stereo audio, one sample is considered to consist of
-/// both channel data.
-class FIFOSampleBuffer : public FIFOSamplePipe
-{
-private:
-	/// Sample buffer.
-	SAMPLETYPE *buffer;
-
-	// Raw unaligned buffer memory. 'buffer' is made aligned by pointing it to first
-	// 16-byte aligned location of this buffer
-	std::unique_ptr<SAMPLETYPE[]> bufferUnaligned;
-
-	/// Sample buffer size in bytes
-	uint32_t sizeInBytes;
-
-	/// How many samples are currently in buffer.
-	uint32_t samplesInBuffer;
-
-	/// Channels, 1=mono, 2=stereo.
-	uint32_t channels;
-
-	/// Current position pointer to the buffer. This pointer is increased when samples are
-	/// removed from the pipe so that it's necessary to actually rewind buffer (move data)
-	/// only new data when is put to the pipe.
-	uint32_t bufferPos;
-
-	/// Rewind the buffer by moving data from position pointed by 'bufferPos' to real
-	/// beginning of the buffer.
-	void rewind();
-
-	/// Ensures that the buffer has capacity for at least this many samples.
-	void ensureCapacity(uint32_t capacityRequirement);
-
-	/// Returns current capacity.
-	uint32_t getCapacity() const;
-
-public:
-	/// Constructor
-	FIFOSampleBuffer(int32_t numChannels = 2     ///< Number of channels, 1=mono, 2=stereo.
-                                              ///< Default is stereo.
-                     );
-
-	/// Returns a pointer to the beginning of the output samples.
-	/// This function is provided for accessing the output samples directly.
-	/// Please be careful for not to corrupt the book-keeping!
-	///
-	/// When using this function to output samples, also remember to 'remove' the
-	/// output samples from the buffer by calling the
-	/// 'receiveSamples(numSamples)' function
-	SAMPLETYPE *ptrBegin();
-
-	/// Returns a pointer to the end of the used part of the sample buffer (i.e.
-	/// where the new samples are to be inserted). This function may be used for
-	/// inserting new samples into the sample buffer directly. Please be careful
-	/// not corrupt the book-keeping!
-	///
-	/// When using this function as means for inserting new samples, also remember
-	/// to increase the sample count afterwards, by calling  the
-	/// 'putSamples(numSamples)' function.
-	SAMPLETYPE *ptrEnd(
-                uint32_t slackCapacity   ///< How much free capacity (in samples) there _at least_
-                                         ///< should be so that the caller can succesfully insert the
-                                         ///< desired samples to the buffer. If necessary, the function
-                                         ///< grows the buffer size to comply with this requirement.
-                );
-
-	/// Adds 'numSamples' pcs of samples from the 'samples' memory position to
-	/// the sample buffer.
-	void putSamples(const SAMPLETYPE *samples,  ///< Pointer to samples.
-                            uint32_t numSamples                         ///< Number of samples to insert.
-                            );
-
-	/// Adjusts the book-keeping to increase number of samples in the buffer without
-	/// copying any actual samples.
-	///
-	/// This function is used to update the number of samples in the sample buffer
-	/// when accessing the buffer directly with 'ptrEnd' function. Please be
-	/// careful though!
-	void putSamples(uint32_t numSamples   ///< Number of samples been inserted.
-                            );
-
-	/// Output samples from beginning of the sample buffer. Copies requested samples to
-	/// output buffer and removes them from the sample buffer. If there are less than
-	/// 'numsample' samples in the buffer, returns all that available.
-	///
-	/// \return Number of samples returned.
-	uint32_t receiveSamples(SAMPLETYPE *output, ///< Buffer where to copy output samples.
-                                uint32_t maxSamples                 ///< How many samples to receive at max.
-                                );
-
-	/// Adjusts book-keeping so that given number of samples are removed from beginning of the
-	/// sample buffer without copying them anywhere.
-	///
-	/// Used to reduce the number of samples in the buffer when accessing the sample buffer directly
-	/// with 'ptrBegin' function.
-	uint32_t receiveSamples(uint32_t maxSamples   ///< Remove this many samples from the beginning of pipe.
-                                );
-
-	/// Returns number of samples currently available.
-	uint32_t numSamples() const;
-
-	/// Sets number of channels, 1 = mono, 2 = stereo.
-	void setChannels(int32_t numChannels);
-
-	/// Returns nonzero if there aren't any samples available for outputting.
-	bool isEmpty() const;
-
-	/// Clears all the samples.
-	void clear();
-
-	/// allow trimming (downwards) amount of samples in pipeline.
-	/// Returns adjusted amount of samples
-	uint32_t adjustAmountOfSamples(uint32_t numSamples);
-};
-
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/FIFOSamplePipe.h
+++ /dev/null
@@ -1,217 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// 'FIFOSamplePipe' : An abstract base class for classes that manipulate sound
-/// samples by operating like a first-in-first-out pipe: New samples are fed
-/// into one end of the pipe with the 'putSamples' function, and the processed
-/// samples are received from the other end with the 'receiveSamples' function.
-///
-/// 'FIFOProcessor' : A base class for classes the do signal processing with
-/// the samples while operating like a first-in-first-out pipe. When samples
-/// are input with the 'putSamples' function, the class processes them
-/// and moves the processed samples to the given 'output' pipe object, which
-/// may be either another processing stage, or a fifo sample buffer object.
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2012-06-13 16:29:53 -0300 (qua, 13 jun 2012) $
-// File revision : $Revision: 4 $
-//
-// $Id: FIFOSamplePipe.h 143 2012-06-13 19:29:53Z oparviai $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#pragma once
-
-#include <cassert>
-#include "STTypes.h"
-
-namespace soundtouch
-{
-
-/// Abstract base class for FIFO (first-in-first-out) sample processing classes.
-class FIFOSamplePipe
-{
-public:
-	// virtual default destructor
-	virtual ~FIFOSamplePipe() { }
-
-	/// Returns a pointer to the beginning of the output samples.
-	/// This function is provided for accessing the output samples directly.
-	/// Please be careful for not to corrupt the book-keeping!
-	///
-	/// When using this function to output samples, also remember to 'remove' the
-	/// output samples from the buffer by calling the
-	/// 'receiveSamples(numSamples)' function
-	virtual SAMPLETYPE *ptrBegin() = 0;
-
-	/// Adds 'numSamples' pcs of samples from the 'samples' memory position to
-	/// the sample buffer.
-	virtual void putSamples(const SAMPLETYPE *samples,  ///< Pointer to samples.
-                            uint32_t numSamples         ///< Number of samples to insert.
-                            ) = 0;
-
-	// Moves samples from the 'other' pipe instance to this instance.
-	void moveSamples(FIFOSamplePipe &other  ///< Other pipe instance where from the receive the data.
-         )
-	{
-		int oNumSamples = other.numSamples();
-
-		this->putSamples(other.ptrBegin(), oNumSamples);
-		other.receiveSamples(oNumSamples);
-	}
-
-	/// Output samples from beginning of the sample buffer. Copies requested samples to
-	/// output buffer and removes them from the sample buffer. If there are less than
-	/// 'numsample' samples in the buffer, returns all that available.
-	///
-	/// \return Number of samples returned.
-	virtual uint32_t receiveSamples(SAMPLETYPE *output, ///< Buffer where to copy output samples.
-                                uint32_t maxSamples                 ///< How many samples to receive at max.
-                                ) = 0;
-
-	/// Adjusts book-keeping so that given number of samples are removed from beginning of the
-	/// sample buffer without copying them anywhere.
-	///
-	/// Used to reduce the number of samples in the buffer when accessing the sample buffer directly
-	/// with 'ptrBegin' function.
-	virtual uint32_t receiveSamples(uint32_t maxSamples   ///< Remove this many samples from the beginning of pipe.
-                                ) = 0;
-
-	/// Returns number of samples currently available.
-	virtual uint32_t numSamples() const = 0;
-
-	// Returns nonzero if there aren't any samples available for outputting.
-	virtual bool isEmpty() const = 0;
-
-	/// Clears all the samples.
-	virtual void clear() = 0;
-
-	/// allow trimming (downwards) amount of samples in pipeline.
-	/// Returns adjusted amount of samples
-	virtual uint32_t adjustAmountOfSamples(uint32_t numSamples) = 0;
-};
-
-/// Base-class for sound processing routines working in FIFO principle. With this base
-/// class it's easy to implement sound processing stages that can be chained together,
-/// so that samples that are fed into beginning of the pipe automatically go through
-/// all the processing stages.
-///
-/// When samples are input to this class, they're first processed and then put to
-/// the FIFO pipe that's defined as output of this class. This output pipe can be
-/// either other processing stage or a FIFO sample buffer.
-class FIFOProcessor :public FIFOSamplePipe
-{
-protected:
-	/// Internal pipe where processed samples are put.
-	FIFOSamplePipe *output;
-
-	/// Sets output pipe.
-	void setOutPipe(FIFOSamplePipe *pOutput)
-	{
-		assert(!this->output);
-		assert(pOutput);
-		this->output = pOutput;
-	}
-
-	/// Constructor. Doesn't define output pipe; it has to be set be
-	/// 'setOutPipe' function.
-	FIFOProcessor()
-	{
-		this->output = nullptr;
-	}
-
-	/// Constructor. Configures output pipe.
-	FIFOProcessor(FIFOSamplePipe *pOutput   ///< Output pipe.
-                 )
-	{
-		this->output = pOutput;
-	}
-
-	/// Destructor.
-	virtual ~FIFOProcessor()
-	{
-	}
-
-	/// Returns a pointer to the beginning of the output samples.
-	/// This function is provided for accessing the output samples directly.
-	/// Please be careful for not to corrupt the book-keeping!
-	///
-	/// When using this function to output samples, also remember to 'remove' the
-	/// output samples from the buffer by calling the
-	/// 'receiveSamples(numSamples)' function
-	virtual SAMPLETYPE *ptrBegin()
-	{
-		return this->output->ptrBegin();
-	}
-
-public:
-	/// Output samples from beginning of the sample buffer. Copies requested samples to
-	/// output buffer and removes them from the sample buffer. If there are less than
-	/// 'numsample' samples in the buffer, returns all that available.
-	///
-	/// \return Number of samples returned.
-	virtual uint32_t receiveSamples(SAMPLETYPE *outBuffer, ///< Buffer where to copy output samples.
-                                uint32_t maxSamples                    ///< How many samples to receive at max.
-                                )
-	{
-		return this->output->receiveSamples(outBuffer, maxSamples);
-	}
-
-	/// Adjusts book-keeping so that given number of samples are removed from beginning of the
-	/// sample buffer without copying them anywhere.
-	///
-	/// Used to reduce the number of samples in the buffer when accessing the sample buffer directly
-	/// with 'ptrBegin' function.
-	virtual uint32_t receiveSamples(uint32_t maxSamples   ///< Remove this many samples from the beginning of pipe.
-                                )
-	{
-		return this->output->receiveSamples(maxSamples);
-	}
-
-	/// Returns number of samples currently available.
-	virtual uint32_t numSamples() const
-	{
-		return this->output->numSamples();
-	}
-
-	/// Returns nonzero if there aren't any samples available for outputting.
-	virtual bool isEmpty() const
-	{
-		return this->output->isEmpty();
-	}
-
-	/// allow trimming (downwards) amount of samples in pipeline.
-	/// Returns adjusted amount of samples
-	virtual uint32_t adjustAmountOfSamples(uint32_t numSmpls)
-	{
-		return this->output->adjustAmountOfSamples(numSmpls);
-	}
-};
-
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/FIRFilter.cpp
+++ /dev/null
@@ -1,220 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// General FIR digital filter routines with MMX optimization.
-///
-/// Note : MMX optimized functions reside in a separate, platform-specific file,
-/// e.g. 'mmx_win.cpp' or 'mmx_gcc.cpp'
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2011-09-02 15:56:11 -0300 (sex, 02 set 2011) $
-// File revision : $Revision: 4 $
-//
-// $Id: FIRFilter.cpp 131 2011-09-02 18:56:11Z oparviai $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#include <stdexcept>
-#include <cstring>
-#include <cassert>
-#include <cmath>
-#include "FIRFilter.h"
-#include "cpu_detect.h"
-
-using namespace soundtouch;
-
-/*****************************************************************************
- *
- * Implementation of the class 'FIRFilter'
- *
- *****************************************************************************/
-
-FIRFilter::FIRFilter()
-{
-	this->resultDivFactor = 0;
-	this->resultDivider = 0;
-	this->length = 0;
-	this->lengthDiv8 = 0;
-	this->filterCoeffs.reset();
-}
-
-FIRFilter::~FIRFilter()
-{
-}
-
-// Usual C-version of the filter routine for stereo sound
-uint32_t FIRFilter::evaluateFilterStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples) const
-{
-#ifdef SOUNDTOUCH_FLOAT_SAMPLES
-	// when using floating point samples, use a scaler instead of a divider
-	// because division is much slower operation than multiplying.
-	double dScaler = 1.0 / this->resultDivider;
-#endif
-
-	assert(this->length);
-	assert(!!src);
-	assert(!!dest);
-	assert(!!filterCoeffs);
-
-	uint32_t end = 2 * (numSamples - this->length);
-
-	for (uint32_t j = 0; j < end; j += 2)
-	{
-		LONG_SAMPLETYPE suml = 0, sumr = 0;
-		const SAMPLETYPE *ptr = &src[j];
-
-		for (uint32_t i = 0; i < length; i += 4)
-		{
-			// loop is unrolled by factor of 4 here for efficiency
-			suml += ptr[2 * i] * filterCoeffs[i] + ptr[2 * i + 2] * filterCoeffs[i + 1] + ptr[2 * i + 4] * filterCoeffs[i + 2] + ptr[2 * i + 6] * filterCoeffs[i + 3];
-			sumr += ptr[2 * i + 1] * filterCoeffs[i] + ptr[2 * i + 3] * filterCoeffs[i + 1] + ptr[2 * i + 5] * filterCoeffs[i + 2] + ptr[2 * i + 7] * filterCoeffs[i + 3];
-		}
-
-#ifdef  SOUNDTOUCH_INTEGER_SAMPLES
-		suml >>= this->resultDivFactor;
-		sumr >>= this->resultDivFactor;
-		// saturate to 16 bit integer limits
-		suml = suml < -32768 ? -32768 : (suml > 32767 ? 32767 : suml);
-		// saturate to 16 bit integer limits
-		sumr = sumr < -32768 ? -32768 : (sumr > 32767 ? 32767 : sumr);
-#else
-		suml *= dScaler;
-		sumr *= dScaler;
-#endif //  SOUNDTOUCH_INTEGER_SAMPLES
-		dest[j] = static_cast<SAMPLETYPE>(suml);
-		dest[j + 1] = static_cast<SAMPLETYPE>(sumr);
-	}
-	return numSamples - this->length;
-}
-
-// Usual C-version of the filter routine for mono sound
-uint32_t FIRFilter::evaluateFilterMono(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples) const
-{
-#ifdef SOUNDTOUCH_FLOAT_SAMPLES
-	// when using floating point samples, use a scaler instead of a divider
-	// because division is much slower operation than multiplying.
-	double dScaler = 1.0 / this->resultDivider;
-#endif
-
-	assert(this->length);
-
-	uint32_t end = numSamples - length;
-	for (uint32_t j = 0; j < end; ++j)
-	{
-		LONG_SAMPLETYPE sum = 0;
-		for (uint32_t i = 0; i < length; i += 4)
-		{
-			// loop is unrolled by factor of 4 here for efficiency
-			sum += src[i] * filterCoeffs[i] + src[i + 1] * filterCoeffs[i + 1] + src[i + 2] * filterCoeffs[i + 2] + src[i + 3] * filterCoeffs[i + 3];
-		}
-#ifdef SOUNDTOUCH_INTEGER_SAMPLES
-		sum >>= this->resultDivFactor;
-		// saturate to 16 bit integer limits
-		sum = sum < -32768 ? -32768 : (sum > 32767 ? 32767 : sum);
-#else
-		sum *= dScaler;
-#endif // SOUNDTOUCH_INTEGER_SAMPLES
-		dest[j] = static_cast<SAMPLETYPE>(sum);
-		++src;
-	}
-	return end;
-}
-
-// Set filter coeffiecients and length.
-//
-// Throws an exception if filter length isn't divisible by 8
-void FIRFilter::setCoefficients(const SAMPLETYPE *coeffs, uint32_t newLength, uint32_t uResultDivFactor)
-{
-	assert(newLength > 0);
-	if (newLength % 8)
-		throw std::runtime_error("FIR filter length not divisible by 8");
-
-	this->lengthDiv8 = newLength / 8;
-	this->length = this->lengthDiv8 * 8;
-	assert(this->length == newLength);
-
-	this->resultDivFactor = uResultDivFactor;
-	this->resultDivider = static_cast<SAMPLETYPE>(std::pow(2.0, static_cast<double>(this->resultDivFactor)));
-
-	this->filterCoeffs.reset(new SAMPLETYPE[this->length]);
-	memcpy(this->filterCoeffs.get(), coeffs, this->length * sizeof(SAMPLETYPE));
-}
-
-uint32_t FIRFilter::getLength() const
-{
-	return this->length;
-}
-
-// Applies the filter to the given sequence of samples.
-//
-// Note : The amount of outputted samples is by value of 'filter_length'
-// smaller than the amount of input samples.
-uint32_t FIRFilter::evaluate(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples, uint32_t numChannels) const
-{
-	assert(numChannels == 1 || numChannels == 2);
-
-	assert(this->length > 0);
-	assert(this->lengthDiv8 * 8 == this->length);
-	if (numSamples < this->length)
-		return 0;
-	if (numChannels == 2)
-		return this->evaluateFilterStereo(dest, src, numSamples);
-	else
-		return this->evaluateFilterMono(dest, src, numSamples);
-}
-
-// Operator 'new' is overloaded so that it automatically creates a suitable instance
-// depending on if we've a MMX-capable CPU available or not.
-void *FIRFilter::operator new(size_t)
-{
-	// Notice! don't use "new FIRFilter" directly, use "newInstance" to create a new instance instead!
-	throw std::runtime_error("Don't use 'new FIRFilter', use 'newInstance' member instead!");
-}
-
-FIRFilter *FIRFilter::newInstance()
-{
-	uint32_t uExtensions = detectCPUextensions();
-
-	// Check if MMX/SSE instruction set extensions supported by CPU
-
-#ifdef SOUNDTOUCH_ALLOW_MMX
-	// MMX routines available only with integer sample types
-	if (uExtensions & SUPPORT_MMX)
-		return ::new FIRFilterMMX;
-	else
-#endif // SOUNDTOUCH_ALLOW_MMX
-#ifdef SOUNDTOUCH_ALLOW_SSE
-	if (uExtensions & SUPPORT_SSE)
-		// SSE support
-		return ::new FIRFilterSSE;
-	else
-#endif // SOUNDTOUCH_ALLOW_SSE
-		// ISA optimizations not supported, use plain C version
-		return ::new FIRFilter;
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/FIRFilter.h
+++ /dev/null
@@ -1,129 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// General FIR digital filter routines with MMX optimization.
-///
-/// Note : MMX optimized functions reside in a separate, platform-specific file,
-/// e.g. 'mmx_win.cpp' or 'mmx_gcc.cpp'
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2011-02-13 17:13:57 -0200 (dom, 13 fev 2011) $
-// File revision : $Revision: 4 $
-//
-// $Id: FIRFilter.h 104 2011-02-13 19:13:57Z oparviai $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#pragma once
-
-#include <memory>
-#include "STTypes.h"
-
-namespace soundtouch
-{
-
-class FIRFilter
-{
-protected:
-	// Number of FIR filter taps
-	uint32_t length;
-	// Number of FIR filter taps divided by 8
-	uint32_t lengthDiv8;
-
-	// Result divider factor in 2^k format
-	uint32_t resultDivFactor;
-
-	// Result divider value.
-	SAMPLETYPE resultDivider;
-
-	// Memory for filter coefficients
-	std::unique_ptr<SAMPLETYPE[]> filterCoeffs;
-
-	virtual uint32_t evaluateFilterStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples) const;
-	virtual uint32_t evaluateFilterMono(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples) const;
-
-public:
-	FIRFilter();
-	virtual ~FIRFilter();
-
-	/// Operator 'new' is overloaded so that it automatically creates a suitable instance
-	/// depending on if we've a MMX-capable CPU available or not.
-	static void *operator new(size_t s);
-
-	static FIRFilter *newInstance();
-
-	/// Applies the filter to the given sequence of samples.
-	/// Note : The amount of outputted samples is by value of 'filter_length'
-	/// smaller than the amount of input samples.
-	///
-	/// \return Number of samples copied to 'dest'.
-	uint32_t evaluate(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples, uint32_t numChannels) const;
-
-	uint32_t getLength() const;
-
-	virtual void setCoefficients(const SAMPLETYPE *coeffs, uint32_t newLength, uint32_t uResultDivFactor);
-};
-
-// Optional subclasses that implement CPU-specific optimizations:
-
-#ifdef SOUNDTOUCH_ALLOW_MMX
-/// Class that implements MMX optimized functions exclusive for 16bit integer samples type.
-class FIRFilterMMX : public FIRFilter
-{
-protected:
-	std::unique_ptr<short[]> filterCoeffsUnalign;
-	short *filterCoeffsAlign;
-
-	virtual uint32_t evaluateFilterStereo(short *dest, const short *src, uint32_t numSamples) const;
-public:
-	FIRFilterMMX();
-	~FIRFilterMMX();
-
-	virtual void setCoefficients(const short *coeffs, uint32_t newLength, uint32_t uResultDivFactor);
-};
-#endif // SOUNDTOUCH_ALLOW_MMX
-
-#ifdef SOUNDTOUCH_ALLOW_SSE
-/// Class that implements SSE optimized functions exclusive for floating point samples type.
-class FIRFilterSSE : public FIRFilter
-{
-protected:
-	std::unique_ptr<float[]> filterCoeffsUnalign;
-	float *filterCoeffsAlign;
-
-	virtual uint32_t evaluateFilterStereo(float *dest, const float *src, uint32_t numSamples) const;
-public:
-	FIRFilterSSE();
-	~FIRFilterSSE();
-
-	virtual void setCoefficients(const float *coeffs, uint32_t newLength, uint32_t uResultDivFactor);
-};
-#endif // SOUNDTOUCH_ALLOW_SSE
-
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/RateTransposer.cpp
+++ /dev/null
@@ -1,528 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// Sample rate transposer. Changes sample rate by using linear interpolation
-/// together with anti-alias filtering (first order interpolation with anti-
-/// alias filtering should be quite adequate for this application)
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2011-09-02 15:56:11 -0300 (sex, 02 set 2011) $
-// File revision : $Revision: 4 $
-//
-// $Id: RateTransposer.cpp 131 2011-09-02 18:56:11Z oparviai $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#include <stdexcept>
-#include "RateTransposer.h"
-
-using namespace soundtouch;
-
-/// A linear samplerate transposer class that uses integer arithmetics.
-/// for the transposing.
-class RateTransposerInteger : public RateTransposer
-{
-protected:
-	int iSlopeCount;
-	int iRate;
-	SAMPLETYPE sPrevSampleL, sPrevSampleR;
-
-	virtual void resetRegisters();
-
-	virtual uint32_t transposeStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples);
-	virtual uint32_t transposeMono(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples);
-
-public:
-	RateTransposerInteger();
-	virtual ~RateTransposerInteger();
-
-	/// Sets new target rate. Normal rate = 1.0, smaller values represent slower
-	/// rate, larger faster rates.
-	virtual void setRate(float newRate);
-};
-
-/// A linear samplerate transposer class that uses floating point arithmetics
-/// for the transposing.
-class RateTransposerFloat : public RateTransposer
-{
-protected:
-	float fSlopeCount;
-	SAMPLETYPE sPrevSampleL, sPrevSampleR;
-
-	virtual void resetRegisters();
-
-	virtual uint32_t transposeStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples);
-	virtual uint32_t transposeMono(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples);
-
-public:
-	RateTransposerFloat();
-	virtual ~RateTransposerFloat();
-};
-
-// Operator 'new' is overloaded so that it automatically creates a suitable instance
-// depending on if we've a MMX/SSE/etc-capable CPU available or not.
-void *RateTransposer::operator new(size_t)
-{
-	// Notice! don't use "new TDStretch" directly, use "newInstance" to create a new instance instead!
-	//assert(false);
-	//return NULL;
-	throw std::runtime_error("Don't use 'new RateTransposer', use 'newInstance' member instead!");
-}
-
-RateTransposer *RateTransposer::newInstance()
-{
-#ifdef SOUNDTOUCH_INTEGER_SAMPLES
-	return ::new RateTransposerInteger;
-#else
-	return ::new RateTransposerFloat;
-#endif
-}
-
-// Constructor
-RateTransposer::RateTransposer() : FIFOProcessor(&outputBuffer)
-{
-	this->numChannels = 2;
-	this->bUseAAFilter = true;
-	this->fRate = 0;
-
-	// Instantiates the anti-alias filter with default tap length
-	// of 32
-	this->pAAFilter.reset(new AAFilter(32));
-}
-
-RateTransposer::~RateTransposer()
-{
-}
-
-/// Enables/disables the anti-alias filter. Zero to disable, nonzero to enable
-void RateTransposer::enableAAFilter(bool newMode)
-{
-	this->bUseAAFilter = newMode;
-}
-
-/// Returns nonzero if anti-alias filter is enabled.
-bool RateTransposer::isAAFilterEnabled() const
-{
-	return this->bUseAAFilter;
-}
-
-AAFilter *RateTransposer::getAAFilter()
-{
-	return this->pAAFilter.get();
-}
-
-// Sets new target iRate. Normal iRate = 1.0, smaller values represent slower
-// iRate, larger faster iRates.
-void RateTransposer::setRate(float newRate)
-{
-	double fCutoff;
-
-	this->fRate = newRate;
-
-	// design a new anti-alias filter
-	if (newRate > 1.0f)
-		fCutoff = 0.5f / newRate;
-	else
-		fCutoff = 0.5f * newRate;
-    this->pAAFilter->setCutoffFreq(fCutoff);
-}
-
-// Adds 'nSamples' pcs of samples from the 'samples' memory position into
-// the input of the object.
-void RateTransposer::putSamples(const SAMPLETYPE *samples, uint32_t nSamples)
-{
-	this->processSamples(samples, nSamples);
-}
-
-// Transposes up the sample rate, causing the observed playback 'rate' of the
-// sound to decrease
-void RateTransposer::upsample(const SAMPLETYPE *src, uint32_t nSamples)
-{
-	// If the parameter 'uRate' value is smaller than 'SCALE', first transpose
-	// the samples and then apply the anti-alias filter to remove aliasing.
-
-	// First check that there's enough room in 'storeBuffer'
-	// (+16 is to reserve some slack in the destination buffer)
-	uint32_t sizeTemp = static_cast<uint32_t>(nSamples / this->fRate + 16.0f);
-
-	// Transpose the samples, store the result into the end of "storeBuffer"
-	uint32_t count = this->transpose(this->storeBuffer.ptrEnd(sizeTemp), src, nSamples);
-	this->storeBuffer.putSamples(count);
-
-	// Apply the anti-alias filter to samples in "store output", output the
-	// result to "dest"
-	uint32_t num = this->storeBuffer.numSamples();
-	count = this->pAAFilter->evaluate(this->outputBuffer.ptrEnd(num), this->storeBuffer.ptrBegin(), num, this->numChannels);
-	this->outputBuffer.putSamples(count);
-
-	// Remove the processed samples from "storeBuffer"
-	this->storeBuffer.receiveSamples(count);
-}
-
-// Transposes down the sample rate, causing the observed playback 'rate' of the
-// sound to increase
-void RateTransposer::downsample(const SAMPLETYPE *src, uint32_t nSamples)
-{
-	// If the parameter 'uRate' value is larger than 'SCALE', first apply the
-	// anti-alias filter to remove high frequencies (prevent them from folding
-	// over the lover frequencies), then transpose. */
-
-	// Add the new samples to the end of the storeBuffer */
-	this->storeBuffer.putSamples(src, nSamples);
-
-	// Anti-alias filter the samples to prevent folding and output the filtered
-	// data to tempBuffer. Note : because of the FIR filter length, the
-	// filtering routine takes in 'filter_length' more samples than it outputs.
-	assert(this->tempBuffer.isEmpty());
-	uint32_t sizeTemp = this->storeBuffer.numSamples();
-
-	uint32_t count = this->pAAFilter->evaluate(this->tempBuffer.ptrEnd(sizeTemp), this->storeBuffer.ptrBegin(), sizeTemp, this->numChannels);
-
-	// Remove the filtered samples from 'storeBuffer'
-	this->storeBuffer.receiveSamples(count);
-
-	// Transpose the samples (+16 is to reserve some slack in the destination buffer)
-	sizeTemp = static_cast<uint32_t>(nSamples / this->fRate + 16.0f);
-	count = this->transpose(this->outputBuffer.ptrEnd(sizeTemp), this->tempBuffer.ptrBegin(), count);
-	this->outputBuffer.putSamples(count);
-}
-
-// Transposes sample rate by applying anti-alias filter to prevent folding.
-// Returns amount of samples returned in the "dest" buffer.
-// The maximum amount of samples that can be returned at a time is set by
-// the 'set_returnBuffer_size' function.
-void RateTransposer::processSamples(const SAMPLETYPE *src, uint32_t nSamples)
-{
-	if (!nSamples)
-		return;
-	assert(this->pAAFilter);
-
-	// If anti-alias filter is turned off, simply transpose without applying
-	// the filter
-	if (!bUseAAFilter)
-	{
-		uint32_t sizeReq = static_cast<uint32_t>(nSamples / this->fRate + 1.0f);
-		uint32_t count = this->transpose(this->outputBuffer.ptrEnd(sizeReq), src, nSamples);
-		this->outputBuffer.putSamples(count);
-		return;
-	}
-
-	// Transpose with anti-alias filter
-	if (this->fRate < 1.0f)
-		this->upsample(src, nSamples);
-	else
-		this->downsample(src, nSamples);
-}
-
-// Transposes the sample rate of the given samples using linear interpolation.
-// Returns the number of samples returned in the "dest" buffer
-uint32_t RateTransposer::transpose(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t nSamples)
-{
-	if (this->numChannels == 2)
-		return this->transposeStereo(dest, src, nSamples);
-	else
-		return this->transposeMono(dest, src, nSamples);
-}
-
-// Sets the number of channels, 1 = mono, 2 = stereo
-void RateTransposer::setChannels(int32_t nChannels)
-{
-	assert(nChannels > 0);
-	if (this->numChannels == nChannels)
-		return;
-
-	assert(nChannels == 1 || nChannels == 2);
-	this->numChannels = nChannels;
-
-	this->storeBuffer.setChannels(this->numChannels);
-	this->tempBuffer.setChannels(this->numChannels);
-	this->outputBuffer.setChannels(this->numChannels);
-
-	// Inits the linear interpolation registers
-	this->resetRegisters();
-}
-
-// Clears all the samples in the object
-void RateTransposer::clear()
-{
-	this->outputBuffer.clear();
-	this->storeBuffer.clear();
-}
-
-// Returns nonzero if there aren't any samples available for outputting.
-bool RateTransposer::isEmpty() const
-{
-	bool res = FIFOProcessor::isEmpty();
-	if (!res)
-		return false;
-	return this->storeBuffer.isEmpty();
-}
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// RateTransposerInteger - integer arithmetic implementation
-//
-
-/// fixed-point interpolation routine precision
-static const int SCALE = 65536;
-
-// Constructor
-RateTransposerInteger::RateTransposerInteger() : RateTransposer()
-{
-	// Notice: use local function calling syntax for sake of clarity,
-	// to indicate the fact that C++ constructor can't call virtual functions.
-	RateTransposerInteger::resetRegisters();
-	RateTransposerInteger::setRate(1.0f);
-}
-
-RateTransposerInteger::~RateTransposerInteger()
-{
-}
-
-void RateTransposerInteger::resetRegisters()
-{
-	this->iSlopeCount = 0;
-	this->sPrevSampleL = this->sPrevSampleR = 0;
-}
-
-// Transposes the sample rate of the given samples using linear interpolation.
-// 'Mono' version of the routine. Returns the number of samples returned in
-// the "dest" buffer
-uint32_t RateTransposerInteger::transposeMono(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t nSamples)
-{
-	if (!nSamples)
-		return 0; // no samples, no work
-
-	unsigned used = 0, i = 0;
-
-	// Process the last sample saved from the previous call first...
-	LONG_SAMPLETYPE temp, vol1;
-	while (this->iSlopeCount <= SCALE)
-	{
-		vol1 = SCALE - this->iSlopeCount;
-		temp = vol1 * this->sPrevSampleL + this->iSlopeCount * src[0];
-		dest[i] = static_cast<SAMPLETYPE>(temp / SCALE);
-		++i;
-		this->iSlopeCount += this->iRate;
-	}
-	// now always (iSlopeCount > SCALE)
-	this->iSlopeCount -= SCALE;
-
-	while (1)
-	{
-		while (this->iSlopeCount > SCALE)
-		{
-			this->iSlopeCount -= SCALE;
-			++used;
-			if (used >= nSamples - 1)
-				goto end;
-		}
-		vol1 = SCALE - this->iSlopeCount;
-		temp = src[used] * vol1 + this->iSlopeCount * src[used + 1];
-		dest[i] = static_cast<SAMPLETYPE>(temp / SCALE);
-		++i;
-		this->iSlopeCount += this->iRate;
-	}
-end:
-	// Store the last sample for the next round
-	this->sPrevSampleL = src[nSamples - 1];
-
-	return i;
-}
-
-// Transposes the sample rate of the given samples using linear interpolation.
-// 'Stereo' version of the routine. Returns the number of samples returned in
-// the "dest" buffer
-uint32_t RateTransposerInteger::transposeStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t nSamples)
-{
-	if (!nSamples)
-		return 0; // no samples, no work
-
-	unsigned used = 0, i = 0;
-
-	// Process the last sample saved from the sPrevSampleLious call first...
-	LONG_SAMPLETYPE temp, vol1;
-	while (this->iSlopeCount <= SCALE)
-	{
-		vol1 = SCALE - this->iSlopeCount;
-		temp = vol1 * this->sPrevSampleL + this->iSlopeCount * src[0];
-		dest[2 * i] = static_cast<SAMPLETYPE>(temp / SCALE);
-		temp = vol1 * this->sPrevSampleR + this->iSlopeCount * src[1];
-		dest[2 * i + 1] = static_cast<SAMPLETYPE>(temp / SCALE);
-		++i;
-		this->iSlopeCount += this->iRate;
-	}
-	// now always (iSlopeCount > SCALE)
-	this->iSlopeCount -= SCALE;
-
-	while (1)
-	{
-		while (this->iSlopeCount > SCALE)
-		{
-			this->iSlopeCount -= SCALE;
-			++used;
-			if (used >= nSamples - 1)
-				goto end;
-		}
-		unsigned srcPos = 2 * used;
-		vol1 = SCALE - this->iSlopeCount;
-		temp = src[srcPos] * vol1 + this->iSlopeCount * src[srcPos + 2];
-		dest[2 * i] = static_cast<SAMPLETYPE>(temp / SCALE);
-		temp = src[srcPos + 1] * vol1 + this->iSlopeCount * src[srcPos + 3];
-		dest[2 * i + 1] = static_cast<SAMPLETYPE>(temp / SCALE);
-		++i;
-		this->iSlopeCount += this->iRate;
-	}
-end:
-	// Store the last sample for the next round
-	this->sPrevSampleL = src[2 * nSamples - 2];
-	this->sPrevSampleR = src[2 * nSamples - 1];
-
-	return i;
-}
-
-// Sets new target iRate. Normal iRate = 1.0, smaller values represent slower
-// iRate, larger faster iRates.
-void RateTransposerInteger::setRate(float newRate)
-{
-	this->iRate = static_cast<int>(newRate * SCALE + 0.5f);
-	RateTransposer::setRate(newRate);
-}
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// RateTransposerFloat - floating point arithmetic implementation
-//
-//////////////////////////////////////////////////////////////////////////////
-
-// Constructor
-RateTransposerFloat::RateTransposerFloat() : RateTransposer()
-{
-	// Notice: use local function calling syntax for sake of clarity,
-	// to indicate the fact that C++ constructor can't call virtual functions.
-	RateTransposerFloat::resetRegisters();
-	RateTransposerFloat::setRate(1.0f);
-}
-
-RateTransposerFloat::~RateTransposerFloat()
-{
-}
-
-void RateTransposerFloat::resetRegisters()
-{
-	this->fSlopeCount = 0;
-	this->sPrevSampleL = this->sPrevSampleR = 0;
-}
-
-// Transposes the sample rate of the given samples using linear interpolation.
-// 'Mono' version of the routine. Returns the number of samples returned in
-// the "dest" buffer
-uint32_t RateTransposerFloat::transposeMono(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t nSamples)
-{
-	unsigned used = 0, i = 0;
-
-	// Process the last sample saved from the previous call first...
-	while (this->fSlopeCount <= 1.0f)
-	{
-		dest[i] = static_cast<SAMPLETYPE>((1.0f - this->fSlopeCount) * this->sPrevSampleL + this->fSlopeCount * src[0]);
-		++i;
-		this->fSlopeCount += this->fRate;
-	}
-	this->fSlopeCount -= 1.0f;
-
-	if (nSamples > 1)
-	{
-		while (1)
-		{
-			while (this->fSlopeCount > 1.0f)
-			{
-				this->fSlopeCount -= 1.0f;
-				++used;
-				if (used >= nSamples - 1)
-					goto end;
-			}
-			dest[i] = static_cast<SAMPLETYPE>((1.0f - this->fSlopeCount) * src[used] + this->fSlopeCount * src[used + 1]);
-			++i;
-			this->fSlopeCount += this->fRate;
-		}
-	}
-end:
-	// Store the last sample for the next round
-	this->sPrevSampleL = src[nSamples - 1];
-
-	return i;
-}
-
-// Transposes the sample rate of the given samples using linear interpolation.
-// 'Mono' version of the routine. Returns the number of samples returned in
-// the "dest" buffer
-uint32_t RateTransposerFloat::transposeStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t nSamples)
-{
-	if (!nSamples)
-		return 0; // no samples, no work
-
-	unsigned used = 0, i = 0;
-
-	// Process the last sample saved from the sPrevSampleLious call first...
-	while (this->fSlopeCount <= 1.0f)
-	{
-		dest[2 * i] = static_cast<SAMPLETYPE>((1.0f - this->fSlopeCount) * this->sPrevSampleL + this->fSlopeCount * src[0]);
-		dest[2 * i + 1] = static_cast<SAMPLETYPE>((1.0f - this->fSlopeCount) * this->sPrevSampleR + this->fSlopeCount * src[1]);
-		++i;
-		this->fSlopeCount += this->fRate;
-	}
-	// now always (iSlopeCount > 1.0f)
-	this->fSlopeCount -= 1.0f;
-
-	if (nSamples > 1)
-	{
-		while (1)
-		{
-			while (this->fSlopeCount > 1.0f)
-			{
-				this->fSlopeCount -= 1.0f;
-				++used;
-				if (used >= nSamples - 1)
-					goto end;
-			}
-			unsigned srcPos = 2 * used;
-
-			dest[2 * i] = static_cast<SAMPLETYPE>((1.0f - this->fSlopeCount) * src[srcPos] + this->fSlopeCount * src[srcPos + 2]);
-			dest[2 * i + 1] = static_cast<SAMPLETYPE>((1.0f - this->fSlopeCount) * src[srcPos + 1] + this->fSlopeCount * src[srcPos + 3]);
-			++i;
-			this->fSlopeCount += this->fRate;
-		}
-	}
-end:
-	// Store the last sample for the next round
-	this->sPrevSampleL = src[2 * nSamples - 2];
-	this->sPrevSampleR = src[2 * nSamples - 1];
-
-	return i;
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/RateTransposer.h
+++ /dev/null
@@ -1,143 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// Sample rate transposer. Changes sample rate by using linear interpolation
-/// together with anti-alias filtering (first order interpolation with anti-
-/// alias filtering should be quite adequate for this application).
-///
-/// Use either of the derived classes of 'RateTransposerInteger' or
-/// 'RateTransposerFloat' for corresponding integer/floating point tranposing
-/// algorithm implementation.
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2009-02-21 13:00:14 -0300 (s�b, 21 fev 2009) $
-// File revision : $Revision: 4 $
-//
-// $Id: RateTransposer.h 63 2009-02-21 16:00:14Z oparviai $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#pragma once
-
-#include "AAFilter.h"
-#include "FIFOSampleBuffer.h"
-
-namespace soundtouch
-{
-
-/// A common linear samplerate transposer class.
-///
-/// Note: Use function "RateTransposer::newInstance()" to create a new class
-/// instance instead of the "new" operator; that function automatically
-/// chooses a correct implementation depending on if integer or floating
-/// arithmetics are to be used.
-class RateTransposer : public FIFOProcessor
-{
-protected:
-	/// Anti-alias filter object
-	std::unique_ptr<AAFilter> pAAFilter;
-
-	float fRate;
-
-	int32_t numChannels;
-
-	/// Buffer for collecting samples to feed the anti-alias filter between
-	/// two batches
-	FIFOSampleBuffer storeBuffer;
-
-	/// Buffer for keeping samples between transposing & anti-alias filter
-	FIFOSampleBuffer tempBuffer;
-
-	/// Output sample buffer
-	FIFOSampleBuffer outputBuffer;
-
-	bool bUseAAFilter;
-
-	virtual void resetRegisters() = 0;
-
-	virtual uint32_t transposeStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples) = 0;
-	virtual uint32_t transposeMono(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples) = 0;
-	uint32_t transpose(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples);
-
-	void downsample(const SAMPLETYPE *src, uint32_t numSamples);
-	void upsample(const SAMPLETYPE *src, uint32_t numSamples);
-
-	/// Transposes sample rate by applying anti-alias filter to prevent folding.
-	/// Returns amount of samples returned in the "dest" buffer.
-	/// The maximum amount of samples that can be returned at a time is set by
-	/// the 'set_returnBuffer_size' function.
-	void processSamples(const SAMPLETYPE *src, uint32_t numSamples);
-
-public:
-	RateTransposer();
-	virtual ~RateTransposer();
-
-	/// Operator 'new' is overloaded so that it automatically creates a suitable instance
-	/// depending on if we're to use integer or floating point arithmetics.
-	static void *operator new(size_t s);
-
-	/// Use this function instead of "new" operator to create a new instance of this class.
-	/// This function automatically chooses a correct implementation, depending on if
-	/// integer ot floating point arithmetics are to be used.
-	static RateTransposer *newInstance();
-
-	/// Returns the output buffer object
-	FIFOSamplePipe *getOutput() { return &this->outputBuffer; }
-
-	/// Returns the store buffer object
-	FIFOSamplePipe *getStore() { return &this->storeBuffer; }
-
-	/// Return anti-alias filter object
-	AAFilter *getAAFilter();
-
-	/// Enables/disables the anti-alias filter. Zero to disable, nonzero to enable
-	void enableAAFilter(bool newMode);
-
-	/// Returns nonzero if anti-alias filter is enabled.
-	bool isAAFilterEnabled() const;
-
-	/// Sets new target rate. Normal rate = 1.0, smaller values represent slower
-	/// rate, larger faster rates.
-	virtual void setRate(float newRate);
-
-	/// Sets the number of channels, 1 = mono, 2 = stereo
-	void setChannels(int32_t channels);
-
-	/// Adds 'numSamples' pcs of samples from the 'samples' memory position into
-	/// the input of the object.
-	void putSamples(const SAMPLETYPE *samples, uint32_t numSamples);
-
-	/// Clears all the samples in the object
-	void clear();
-
-	/// Returns nonzero if there aren't any samples available for outputting.
-	bool isEmpty() const;
-};
-
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/STTypes.h
+++ /dev/null
@@ -1,132 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// Common type definitions for SoundTouch audio processing library.
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2006/02/05 16:44:06 $
-// File revision : $Revision: 1.16 $
-//
-// $Id: STTypes.h,v 1.16 2006/02/05 16:44:06 Olli Exp $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#pragma once
-
-#include <cstdint>
-
-namespace soundtouch
-{
-
-/// Activate these undef's to overrule the possible sampletype
-/// setting inherited from some other header file:
-//#undef SOUNDTOUCH_INTEGER_SAMPLES
-//#undef SOUNDTOUCH_FLOAT_SAMPLES
-
-#if !defined(SOUNDTOUCH_INTEGER_SAMPLES) || !defined(SOUNDTOUCH_FLOAT_SAMPLES)
-/// Choose either 32bit floating point or 16bit integer sampletype
-/// by choosing one of the following defines, unless this selection
-/// has already been done in some other file.
-////
-/// Notes:
-/// - In Windows environment, choose the sample format with the
-///   following defines.
-/// - In GNU environment, the floating point samples are used by
-///   default, but integer samples can be chosen by giving the
-///   following switch to the configure script:
-///       ./configure --enable-integer-samples
-///   However, if you still prefer to select the sample format here
-///   also in GNU environment, then please #undef the INTEGER_SAMPLE
-///   and FLOAT_SAMPLE defines first as in comments above.
-//# define SOUNDTOUCH_INTEGER_SAMPLES 1 //< 16bit integer samples
-# define SOUNDTOUCH_FLOAT_SAMPLES 1 //< 32bit float samples
-#endif
-
-#if defined(_M_IX86) || defined(__i386__) || defined(__x86_64__) || defined(_M_X64)
-/// Define this to allow X86-specific assembler/intrinsic optimizations.
-/// Notice that library contains also usual C++ versions of each of these
-/// these routines, so if you're having difficulties getting the optimized
-/// routines compiled for whatever reason, you may disable these optimizations
-/// to make the library compile.
-# define SOUNDTOUCH_ALLOW_X86_OPTIMIZATIONS 1
-
-/// In GNU environment, allow the user to override this setting by
-/// giving the following switch to the configure script:
-/// ./configure --disable-x86-optimizations
-/// ./configure --enable-x86-optimizations=no
-# ifdef SOUNDTOUCH_DISABLE_X86_OPTIMIZATIONS
-#  undef SOUNDTOUCH_ALLOW_X86_OPTIMIZATIONS
-# endif
-#else
-/// Always disable optimizations when not using a x86 systems.
-# undef SOUNDTOUCH_ALLOW_X86_OPTIMIZATIONS
-#endif
-
-// If defined, allows the SIMD-optimized routines to take minor shortcuts
-// for improved performance. Undefine to require faithfully similar SIMD
-// calculations as in normal C implementation.
-#define SOUNDTOUCH_ALLOW_NONEXACT_SIMD_OPTIMIZATION 1
-
-#ifdef SOUNDTOUCH_INTEGER_SAMPLES
-// 16bit integer sample type
-typedef short SAMPLETYPE;
-// data type for sample accumulation: Use 32bit integer to prevent overflows
-typedef long LONG_SAMPLETYPE;
-
-# ifdef SOUNDTOUCH_FLOAT_SAMPLES
-// check that only one sample type is defined
-#  error "conflicting sample types defined"
-# endif // SOUNDTOUCH_FLOAT_SAMPLES
-
-# ifdef SOUNDTOUCH_ALLOW_X86_OPTIMIZATIONS
-// Allow MMX optimizations
-#  define SOUNDTOUCH_ALLOW_MMX 1
-# endif
-#else
-// floating point samples
-typedef float SAMPLETYPE;
-// data type for sample accumulation: Use double to utilize full precision.
-typedef double LONG_SAMPLETYPE;
-
-# ifdef SOUNDTOUCH_ALLOW_X86_OPTIMIZATIONS
-// Allow SSE optimizations
-#  define SOUNDTOUCH_ALLOW_SSE 1
-# endif
-#endif // SOUNDTOUCH_INTEGER_SAMPLES
-
-// Helper macro for aligning pointer up to next 16-byte boundary
-inline uintptr_t SOUNDTOUCH_ALIGN_POINTER_16(SAMPLETYPE *x) { return (reinterpret_cast<uintptr_t>(x) + 15) & ~static_cast<uintptr_t>(15); }
-
-// When this #define is active, eliminates a clicking sound when the "rate" or "pitch"
-// parameter setting crosses from value <1 to >=1 or vice versa during processing.
-// Default is off as such crossover is untypical case and involves a slight sound
-// quality compromise.
-//#define SOUNDTOUCH_PREVENT_CLICK_AT_RATE_CROSSOVER 1
-
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/SoundTouch.cpp
+++ /dev/null
@@ -1,337 +1,1 @@
-//////////////////////////////////////////////////////////////////////////////
-///
-/// SoundTouch - main class for tempo/pitch/rate adjusting routines.
-///
-/// Notes:
-/// - Initialize the SoundTouch object instance by setting up the sound stream
-///   parameters with functions 'setSampleRate' and 'setChannels', then set
-///   desired tempo/pitch/rate settings with the corresponding functions.
-///
-/// - The SoundTouch class behaves like a first-in-first-out pipeline: The
-///   samples that are to be processed are fed into one of the pipe by calling
-///   function 'putSamples', while the ready processed samples can be read
-///   from the other end of the pipeline with function 'receiveSamples'.
-///
-/// - The SoundTouch processing classes require certain sized 'batches' of
-///   samples in order to process the sound. For this reason the classes buffer
-///   incoming samples until there are enough of samples available for
-///   processing, then they carry out the processing step and consequently
-///   make the processed samples available for outputting.
-///
-/// - For the above reason, the processing routines introduce a certain
-///   'latency' between the input and output, so that the samples input to
-///   SoundTouch may not be immediately available in the output, and neither
-///   the amount of outputtable samples may not immediately be in direct
-///   relationship with the amount of previously input samples.
-///
-/// - The tempo/pitch/rate control parameters can be altered during processing.
-///   Please notice though that they aren't currently protected by semaphores,
-///   so in multi-thread application external semaphore protection may be
-///   required.
-///
-/// - This class utilizes classes 'TDStretch' for tempo change (without modifying
-///   pitch) and 'RateTransposer' for changing the playback rate (that is, both
-///   tempo and pitch in the same ratio) of the sound. The third available control
-///   'pitch' (change pitch but maintain tempo) is produced by a combination of
-///   combining the two other controls.
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2012-06-13 16:29:53 -0300 (qua, 13 jun 2012) $
-// File revision : $Revision: 4 $
-//
-// $Id: SoundTouch.cpp 143 2012-06-13 19:29:53Z oparviai $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#include "XSFCommon.h"
-
-#include <stdexcept>
-#include <cassert>
-#include <cstdlib>
-#include <cstring>
-#include <cstdio>
-#include "SoundTouch.h"
-#include "cpu_detect.h"
-
-using namespace soundtouch;
-
-SoundTouch::SoundTouch()
-{
-	// Initialize rate transposer and tempo changer instances
-
-	this->pRateTransposer.reset(RateTransposer::newInstance());
-	this->pTDStretch.reset(TDStretch::newInstance());
-
-	this->setOutPipe(this->pTDStretch.get());
-
-	this->rate = this->tempo = 0;
-
-	this->virtualPitch = this->virtualRate = this->virtualTempo = 1.0;
-
-	this->calcEffectiveRateAndTempo();
-
-	this->channels = 0;
-	this->bSrateSet = false;
-}
-
-// Sets the number of channels, 1 = mono, 2 = stereo
-void SoundTouch::setChannels(uint32_t numChannels)
-{
-	if (numChannels != 1 && numChannels != 2)
-		throw std::runtime_error("Illegal number of channels");
-	this->channels = numChannels;
-	this->pRateTransposer->setChannels(numChannels);
-	this->pTDStretch->setChannels(numChannels);
-}
-
-// Sets new rate control value. Normal rate = 1.0, smaller values
-// represent slower rate, larger faster rates.
-void SoundTouch::setRate(float newRate)
-{
-	this->virtualRate = newRate;
-	this->calcEffectiveRateAndTempo();
-}
-
-// Sets new tempo control value. Normal tempo = 1.0, smaller values
-// represent slower tempo, larger faster tempo.
-void SoundTouch::setTempo(float newTempo)
-{
-	this->virtualTempo = newTempo;
-	this->calcEffectiveRateAndTempo();
-}
-
-// Calculates 'effective' rate and tempo values from the
-// nominal control values.
-void SoundTouch::calcEffectiveRateAndTempo()
-{
-	float oldTempo = this->tempo;
-	float oldRate = this->rate;
-
-	this->tempo = this->virtualTempo / this->virtualPitch;
-	this->rate = this->virtualPitch * this->virtualRate;
-
-	if (!fEqual(this->rate, oldRate))
-		this->pRateTransposer->setRate(this->rate);
-	if (!fEqual(this->tempo, oldTempo))
-		this->pTDStretch->setTempo(this->tempo);
-
-#ifndef SOUNDTOUCH_PREVENT_CLICK_AT_RATE_CROSSOVER
-	if (this->rate <= 1.0f)
-	{
-		if (this->output != this->pTDStretch.get())
-		{
-			FIFOSamplePipe *tempoOut;
-
-			assert(this->output == this->pRateTransposer.get());
-			// move samples in the current output buffer to the output of pTDStretch
-			tempoOut = this->pTDStretch->getOutput();
-			tempoOut->moveSamples(*this->output);
-			// move samples in pitch transposer's store buffer to tempo changer's input
-			this->pTDStretch->moveSamples(*this->pRateTransposer->getStore());
-
-			this->output = pTDStretch.get();
-		}
-	}
-	else
-#endif
-	{
-		if (this->output != this->pRateTransposer.get())
-		{
-			assert(this->output == this->pTDStretch.get());
-			// move samples in the current output buffer to the output of pRateTransposer
-			FIFOSamplePipe *transOut = this->pRateTransposer->getOutput();
-			transOut->moveSamples(*this->output);
-			// move samples in tempo changer's input to pitch transposer's input
-			this->pRateTransposer->moveSamples(*this->pTDStretch->getInput());
-
-			this->output = this->pRateTransposer.get();
-		}
-	}
-}
-
-// Sets sample rate.
-void SoundTouch::setSampleRate(uint32_t srate)
-{
-	this->bSrateSet = true;
-	// set sample rate, leave other tempo changer parameters as they are.
-	this->pTDStretch->setParameters(srate);
-}
-
-// Adds 'numSamples' pcs of samples from the 'samples' memory position into
-// the input of the object.
-void SoundTouch::putSamples(const SAMPLETYPE *samples, uint32_t nSamples)
-{
-	if (!this->bSrateSet)
-		throw std::runtime_error("SoundTouch : Sample rate not defined");
-	else if (!this->channels)
-		throw std::runtime_error("SoundTouch : Number of channels not defined");
-
-	// Transpose the rate of the new samples if necessary
-	/* Bypass the nominal setting - can introduce a click in sound when tempo/pitch control crosses the nominal value...
-	if (this->rate == 1.0f)
-	{
-		// The rate value is same as the original, simply evaluate the tempo changer.
-		assert(this->output == this->pTDStretch.get());
-		if (!this->pRateTransposer->isEmpty())
-		{
-			// yet flush the last samples in the pitch transposer buffer
-			// (may happen if 'rate' changes from a non-zero value to zero)
-			this->pTDStretch->moveSamples(*this->pRateTransposer);
-		}
-		this->pTDStretch->putSamples(samples, nSamples);
-	}*/
-#ifndef SOUNDTOUCH_PREVENT_CLICK_AT_RATE_CROSSOVER
-	else if (this->rate <= 1.0f)
-	{
-		// transpose the rate down, output the transposed sound to tempo changer buffer
-		assert(this->output == this->pTDStretch.get());
-		this->pRateTransposer->putSamples(samples, nSamples);
-		this->pTDStretch->moveSamples(*this->pRateTransposer);
-	}
-	else
-#endif
-	{
-		assert(this->rate > 1.0f);
-		// evaluate the tempo changer, then transpose the rate up,
-		assert(this->output == this->pRateTransposer.get());
-		this->pTDStretch->putSamples(samples, nSamples);
-		this->pRateTransposer->moveSamples(*this->pTDStretch);
-	}
-}
-
-// Flushes the last samples from the processing pipeline to the output.
-// Clears also the internal processing buffers.
-//
-// Note: This function is meant for extracting the last samples of a sound
-// stream. This function may introduce additional blank samples in the end
-// of the sound stream, and thus it's not recommended to call this function
-// in the middle of a sound stream.
-void SoundTouch::flush()
-{
-	// check how many samples still await processing, and scale
-	// that by tempo & rate to get expected output sample count
-	int32_t nUnprocessed = this->numUnprocessedSamples();
-	nUnprocessed = static_cast<int32_t>(nUnprocessed / (tempo * rate) + 0.5);
-
-	int32_t nOut = this->numSamples(); // ready samples currently in buffer ...
-	nOut += nUnprocessed; // ... and how many we expect there to be in the end
-
-	// "Push" the last active samples out from the processing pipeline by
-	// feeding blank samples into the processing pipeline until new,
-	// processed samples appear in the output (not however, more than
-	// 8ksamples in any case)
-	SAMPLETYPE buff[128] = { 0 };
-	for (int i = 0; i < 128; ++i)
-	{
-		this->putSamples(buff, 64);
-		if (static_cast<int32_t>(this->numSamples()) >= nOut)
-		{
-			// Enough new samples have appeared into the output!
-			// As samples come from processing with bigger chunks, now truncate it
-			// back to maximum "nOut" samples to improve duration accuracy
-			this->adjustAmountOfSamples(nOut);
-
-			// finish
-			break;
-		}
-	}
-
-	// Clear working buffers
-	this->pRateTransposer->clear();
-	this->pTDStretch->clearInput();
-	// yet leave the 'tempoChanger' output intouched as that's where the
-	// flushed samples are!
-}
-
-// Changes a setting controlling the processing system behaviour. See the
-// 'SETTING_...' defines for available setting ID's.
-bool SoundTouch::setSetting(int32_t settingId, int32_t value)
-{
-	int32_t sampleRate, sequenceMs, seekWindowMs, overlapMs;
-
-	// read current tdstretch routine parameters
-	pTDStretch->getParameters(&sampleRate, &sequenceMs, &seekWindowMs, &overlapMs);
-
-	switch (settingId)
-	{
-		case SETTING_USE_AA_FILTER:
-			// enables / disabless anti-alias filter
-			this->pRateTransposer->enableAAFilter(!!value);
-			return true;
-
-		case SETTING_AA_FILTER_LENGTH:
-			// sets anti-alias filter length
-			this->pRateTransposer->getAAFilter()->setLength(value);
-			return true;
-
-		case SETTING_USE_QUICKSEEK:
-			// enables / disables tempo routine quick seeking algorithm
-			this->pTDStretch->enableQuickSeek(!!value);
-			return true;
-
-		case SETTING_SEQUENCE_MS:
-			// change time-stretch sequence duration parameter
-			this->pTDStretch->setParameters(sampleRate, value, seekWindowMs, overlapMs);
-			return true;
-
-		case SETTING_SEEKWINDOW_MS:
-			// change time-stretch seek window length parameter
-			this->pTDStretch->setParameters(sampleRate, sequenceMs, value, overlapMs);
-			return true;
-
-		case SETTING_OVERLAP_MS:
-			// change time-stretch overlap length parameter
-			this->pTDStretch->setParameters(sampleRate, sequenceMs, seekWindowMs, value);
-			return true;
-
-		default:
-			return false;
-	}
-}
-
-// Clears all the samples in the object's output and internal processing
-// buffers.
-void SoundTouch::clear()
-{
-	this->pRateTransposer->clear();
-	this->pTDStretch->clear();
-}
-
-/// Returns number of samples currently unprocessed.
-uint32_t SoundTouch::numUnprocessedSamples() const
-{
-	if (this->pTDStretch)
-	{
-		FIFOSamplePipe *psp = this->pTDStretch->getInput();
-		if (psp)
-			return psp->numSamples();
-	}
-	return 0;
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/SoundTouch.h
+++ /dev/null
@@ -1,239 +1,1 @@
-//////////////////////////////////////////////////////////////////////////////
-///
-/// SoundTouch - main class for tempo/pitch/rate adjusting routines.
-///
-/// Notes:
-/// - Initialize the SoundTouch object instance by setting up the sound stream
-///   parameters with functions 'setSampleRate' and 'setChannels', then set
-///   desired tempo/pitch/rate settings with the corresponding functions.
-///
-/// - The SoundTouch class behaves like a first-in-first-out pipeline: The
-///   samples that are to be processed are fed into one of the pipe by calling
-///   function 'putSamples', while the ready processed samples can be read
-///   from the other end of the pipeline with function 'receiveSamples'.
-///
-/// - The SoundTouch processing classes require certain sized 'batches' of
-///   samples in order to process the sound. For this reason the classes buffer
-///   incoming samples until there are enough of samples available for
-///   processing, then they carry out the processing step and consequently
-///   make the processed samples available for outputting.
-///
-/// - For the above reason, the processing routines introduce a certain
-///   'latency' between the input and output, so that the samples input to
-///   SoundTouch may not be immediately available in the output, and neither
-///   the amount of outputtable samples may not immediately be in direct
-///   relationship with the amount of previously input samples.
-///
-/// - The tempo/pitch/rate control parameters can be altered during processing.
-///   Please notice though that they aren't currently protected by semaphores,
-///   so in multi-thread application external semaphore protection may be
-///   required.
-///
-/// - This class utilizes classes 'TDStretch' for tempo change (without modifying
-///   pitch) and 'RateTransposer' for changing the playback rate (that is, both
-///   tempo and pitch in the same ratio) of the sound. The third available control
-///   'pitch' (change pitch but maintain tempo) is produced by a combination of
-///   combining the two other controls.
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2012-12-28 17:32:59 -0200 (sex, 28 dez 2012) $
-// File revision : $Revision: 4 $
-//
-// $Id: SoundTouch.h 163 2012-12-28 19:32:59Z oparviai $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#pragma once
-
-#include <memory>
-#include "FIFOSamplePipe.h"
-#include "RateTransposer.h"
-#include "TDStretch.h"
-
-namespace soundtouch
-{
-
-/// Soundtouch library version string
-const char *const SOUNDTOUCH_VERSION = "1.7.1";
-
-/// SoundTouch library version id
-const uint32_t SOUNDTOUCH_VERSION_ID = 010701;
-
-// Available setting IDs for the 'setSetting' & 'get_setting' functions:
-
-/// Enable/disable anti-alias filter in pitch transposer (0 = disable)
-const int32_t SETTING_USE_AA_FILTER = 0;
-
-/// Pitch transposer anti-alias filter length (8 .. 128 taps, default = 32)
-const int32_t SETTING_AA_FILTER_LENGTH = 1;
-
-/// Enable/disable quick seeking algorithm in tempo changer routine
-/// (enabling quick seeking lowers CPU utilization but causes a minor sound
-///  quality compromising)
-const int32_t SETTING_USE_QUICKSEEK = 2;
-
-/// Time-stretch algorithm single processing sequence length in milliseconds. This determines
-/// to how long sequences the original sound is chopped in the time-stretch algorithm.
-/// See "STTypes.h" or README for more information.
-const int32_t SETTING_SEQUENCE_MS = 3;
-
-/// Time-stretch algorithm seeking window length in milliseconds for algorithm that finds the
-/// best possible overlapping location. This determines from how wide window the algorithm
-/// may look for an optimal joining location when mixing the sound sequences back together.
-/// See "STTypes.h" or README for more information.
-const int32_t SETTING_SEEKWINDOW_MS = 4;
-
-/// Time-stretch algorithm overlap length in milliseconds. When the chopped sound sequences
-/// are mixed back together, to form a continuous sound stream, this parameter defines over
-/// how long period the two consecutive sequences are let to overlap each other.
-/// See "STTypes.h" or README for more information.
-const int32_t SETTING_OVERLAP_MS = 5;
-
-/// Call "getSetting" with this ID to query nominal average processing sequence
-/// size in samples. This value tells approcimate value how many input samples
-/// SoundTouch needs to gather before it does DSP processing run for the sample batch.
-///
-/// Notices:
-/// - This is read-only parameter, i.e. setSetting ignores this parameter
-/// - Returned value is approximate average value, exact processing batch
-///   size may wary from time to time
-/// - This parameter value is not constant but may change depending on
-///   tempo/pitch/rate/samplerate settings.
-const int32_t SETTING_NOMINAL_INPUT_SEQUENCE = 6;
-
-/// Call "getSetting" with this ID to query nominal average processing output
-/// size in samples. This value tells approcimate value how many output samples
-/// SoundTouch outputs once it does DSP processing run for a batch of input samples.
-///
-/// Notices:
-/// - This is read-only parameter, i.e. setSetting ignores this parameter
-/// - Returned value is approximate average value, exact processing batch
-///   size may wary from time to time
-/// - This parameter value is not constant but may change depending on
-///   tempo/pitch/rate/samplerate settings.
-const int32_t SETTING_NOMINAL_OUTPUT_SEQUENCE = 7;
-
-class SoundTouch : public FIFOProcessor
-{
-private:
-	/// Rate transposer class instance
-	std::unique_ptr<RateTransposer> pRateTransposer;
-
-	/// Time-stretch class instance
-	std::unique_ptr<TDStretch> pTDStretch;
-
-	/// Virtual pitch parameter. Effective rate & tempo are calculated from these parameters.
-	float virtualRate;
-
-	/// Virtual pitch parameter. Effective rate & tempo are calculated from these parameters.
-	float virtualTempo;
-
-	/// Virtual pitch parameter. Effective rate & tempo are calculated from these parameters.
-	float virtualPitch;
-
-	/// Flag: Has sample rate been set?
-	bool bSrateSet;
-
-	/// Calculates effective rate & tempo valuescfrom 'virtualRate', 'virtualTempo' and
-	/// 'virtualPitch' parameters.
-	void calcEffectiveRateAndTempo();
-
-protected:
-	/// Number of channels
-	uint32_t channels;
-
-	/// Effective 'rate' value calculated from 'virtualRate', 'virtualTempo' and 'virtualPitch'
-	float rate;
-
-	/// Effective 'tempo' value calculated from 'virtualRate', 'virtualTempo' and 'virtualPitch'
-	float tempo;
-
-public:
-	SoundTouch();
-
-	/// Sets new rate control value. Normal rate = 1.0, smaller values
-	/// represent slower rate, larger faster rates.
-	void setRate(float newRate);
-
-	/// Sets new tempo control value. Normal tempo = 1.0, smaller values
-	/// represent slower tempo, larger faster tempo.
-	void setTempo(float newTempo);
-
-	/// Sets the number of channels, 1 = mono, 2 = stereo
-	void setChannels(uint32_t numChannels);
-
-	/// Sets sample rate.
-	void setSampleRate(uint32_t srate);
-
-	/// Flushes the last samples from the processing pipeline to the output.
-	/// Clears also the internal processing buffers.
-	//
-	/// Note: This function is meant for extracting the last samples of a sound
-	/// stream. This function may introduce additional blank samples in the end
-	/// of the sound stream, and thus it's not recommended to call this function
-	/// in the middle of a sound stream.
-	void flush();
-
-	/// Adds 'numSamples' pcs of samples from the 'samples' memory position into
-	/// the input of the object. Notice that sample rate _has_to_ be set before
-	/// calling this function, otherwise throws a runtime_error exception.
-	void putSamples(
-            const SAMPLETYPE *samples,  ///< Pointer to sample buffer.
-            uint32_t numSamples                         ///< Number of samples in buffer. Notice
-                                                        ///< that in case of stereo-sound a single sample
-                                                        ///< contains data for both channels.
-            );
-
-	/// Clears all the samples in the object's output and internal processing
-	/// buffers.
-	void clear();
-
-	/// Changes a setting controlling the processing system behaviour. See the
-	/// 'SETTING_...' defines for available setting ID's.
-	///
-	/// \return 'true' if the setting was succesfully changed
-	bool setSetting(int32_t settingId,   ///< Setting ID number. see SETTING_... defines.
-                    int32_t value        ///< New setting value.
-                    );
-
-	/// Returns number of samples currently unprocessed.
-	uint32_t numUnprocessedSamples() const;
-
-	/// Other handy functions that are implemented in the ancestor classes (see
-	/// classes 'FIFOProcessor' and 'FIFOSamplePipe')
-	///
-	/// - receiveSamples() : Use this function to receive 'ready' processed samples from SoundTouch.
-	/// - numSamples()     : Get number of 'ready' samples that can be received with
-	///                      function 'receiveSamples()'
-	/// - isEmpty()        : Returns nonzero if there aren't any 'ready' samples.
-	/// - clear()          : Clears all samples from ready/processing buffers.
-};
-
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/TDStretch.cpp
+++ /dev/null
@@ -1,639 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// Sampled sound tempo changer/time stretch algorithm. Changes the sound tempo
-/// while maintaining the original pitch by using a time domain WSOLA-like
-/// method with several performance-increasing tweaks.
-///
-/// Note : MMX optimized functions reside in a separate, platform-specific
-/// file, e.g. 'mmx_win.cpp' or 'mmx_gcc.cpp'
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2012-11-08 16:53:01 -0200 (qui, 08 nov 2012) $
-// File revision : $Revision: 1.12 $
-//
-// $Id: TDStretch.cpp 160 2012-11-08 18:53:01Z oparviai $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#include "XSFCommon.h"
-
-#include <stdexcept>
-#include <limits>
-#include <cstring>
-#include <cstdlib>
-#include <cassert>
-#include "STTypes.h"
-#include "cpu_detect.h"
-#include "TDStretch.h"
-
-using namespace soundtouch;
-
-/*****************************************************************************
- *
- * Constant definitions
- *
- *****************************************************************************/
-
-// Table for the hierarchical mixing position seeking algorithm
-static const short _scanOffsets[][24] =
-{
-	{ 124, 186, 248, 310, 372, 434, 496, 558, 620, 682, 744, 806, 868, 930, 992, 1054, 1116, 1178, 1240, 1302, 1364, 1426, 1488, 0 },
-	{-100, -75, -50, -25, 25, 50, 75, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
-	{ -20, -15, -10,  -5, 5, 10, 15, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
-	{ -4, -3, -2, -1, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
-	{ 121, 114, 97, 114, 98, 105, 108, 32, 104, 99, 117, 111, 116, 100, 110, 117, 111, 115, 0, 0, 0, 0, 0, 0 }
-};
-
-/*****************************************************************************
- *
- * Implementation of the class 'TDStretch'
- *
- *****************************************************************************/
-
-
-TDStretch::TDStretch() : FIFOProcessor(&outputBuffer)
-{
-	this->bQuickSeek = false;
-	this->channels = 2;
-
-	this->pMidBuffer = nullptr;
-	this->pMidBufferUnaligned.reset();
-	this->overlapLength = 0;
-
-	this->bAutoSeqSetting = true;
-	this->bAutoSeekSetting = true;
-
-	//this->outDebt = 0;
-	this->skipFract = 0;
-
-	this->tempo = 1.0f;
-	this->setParameters(48000, DEFAULT_SEQUENCE_MS, DEFAULT_SEEKWINDOW_MS, DEFAULT_OVERLAP_MS);
-	this->setTempo(1.0f);
-
-	this->clear();
-}
-
-TDStretch::~TDStretch()
-{
-}
-
-// Sets routine control parameters. These control are certain time constants
-// defining how the sound is stretched to the desired duration.
-//
-// 'sampleRate' = sample rate of the sound
-// 'sequenceMS' = one processing sequence length in milliseconds (default = 82 ms)
-// 'seekwindowMS' = seeking window length for scanning the best overlapping
-//      position (default = 28 ms)
-// 'overlapMS' = overlapping length (default = 12 ms)
-
-void TDStretch::setParameters(int32_t aSampleRate, int32_t aSequenceMS, int32_t aSeekWindowMS, int32_t aOverlapMS)
-{
-	// accept only positive parameter values - if zero or negative, use old values instead
-	if (aSampleRate > 0)
-		this->sampleRate = aSampleRate;
-	if (aOverlapMS > 0)
-		this->overlapMs = aOverlapMS;
-
-	if (aSequenceMS > 0)
-	{
-		this->sequenceMs = aSequenceMS;
-		this->bAutoSeqSetting = false;
-	}
-	else if (!aSequenceMS)
-		// if zero, use automatic setting
-		this->bAutoSeqSetting = true;
-
-	if (aSeekWindowMS > 0)
-	{
-		this->seekWindowMs = aSeekWindowMS;
-		this->bAutoSeekSetting = false;
-	}
-	else if (!aSeekWindowMS)
-		// if zero, use automatic setting
-		this->bAutoSeekSetting = true;
-
-	this->calcSeqParameters();
-
-	this->calculateOverlapLength(this->overlapMs);
-
-	// set tempo to recalculate 'sampleReq'
-	this->setTempo(this->tempo);
-}
-
-/// Get routine control parameters, see setParameters() function.
-/// Any of the parameters to this function can be NULL, in such case corresponding parameter
-/// value isn't returned.
-void TDStretch::getParameters(int32_t *pSampleRate, int32_t *pSequenceMs, int32_t *pSeekWindowMs, int32_t *pOverlapMs)
-{
-	if (pSampleRate)
-		*pSampleRate = this->sampleRate;
-
-	if (pSequenceMs)
-		*pSequenceMs = this->bAutoSeqSetting ? USE_AUTO_SEQUENCE_LEN : sequenceMs;
-
-	if (pSeekWindowMs)
-		*pSeekWindowMs = this->bAutoSeekSetting ? USE_AUTO_SEEKWINDOW_LEN : seekWindowMs;
-
-	if (pOverlapMs)
-		*pOverlapMs = this->overlapMs;
-}
-
-// Overlaps samples in 'midBuffer' with the samples in 'pInput'
-void TDStretch::overlapMono(SAMPLETYPE *pOutput, const SAMPLETYPE *pInput) const
-{
-	SAMPLETYPE m1 = 0;
-	SAMPLETYPE m2 = static_cast<SAMPLETYPE>(this->overlapLength);
-
-	for (int32_t i = 0; i < this->overlapLength; ++i)
-	{
-		pOutput[i] = (pInput[i] * m1 + this->pMidBuffer[i] * m2) / this->overlapLength;
-		++m1;
-		--m2;
-	}
-}
-
-void TDStretch::clearMidBuffer()
-{
-	memset(this->pMidBuffer, 0, 2 * sizeof(SAMPLETYPE) * this->overlapLength);
-}
-
-void TDStretch::clearInput()
-{
-	this->inputBuffer.clear();
-	this->clearMidBuffer();
-}
-
-// Clears the sample buffers
-void TDStretch::clear()
-{
-	this->outputBuffer.clear();
-	this->clearInput();
-}
-
-// Enables/disables the quick position seeking algorithm. Zero to disable, nonzero
-// to enable
-void TDStretch::enableQuickSeek(bool enable)
-{
-	this->bQuickSeek = enable;
-}
-
-// Seeks for the optimal overlap-mixing position.
-int32_t TDStretch::seekBestOverlapPosition(const SAMPLETYPE *refPos)
-{
-	if (this->bQuickSeek)
-		return this->seekBestOverlapPositionQuick(refPos);
-	else
-		return this->seekBestOverlapPositionFull(refPos);
-}
-
-// Overlaps samples in 'midBuffer' with the samples in 'pInputBuffer' at position
-// of 'ovlPos'.
-void TDStretch::overlap(SAMPLETYPE *pOutput, const SAMPLETYPE *pInput, uint32_t ovlPos) const
-{
-	if (this->channels == 2)
-		// stereo sound
-		this->overlapStereo(pOutput, pInput + 2 * ovlPos);
-	else
-		// mono sound.
-		this->overlapMono(pOutput, pInput + ovlPos);
-}
-
-// Seeks for the optimal overlap-mixing position. The 'stereo' version of the
-// routine
-//
-// The best position is determined as the position where the two overlapped
-// sample sequences are 'most alike', in terms of the highest cross-correlation
-// value over the overlapping period
-int32_t TDStretch::seekBestOverlapPositionFull(const SAMPLETYPE *refPos)
-{
-	double bestCorr = std::numeric_limits<float>::min();
-	int32_t bestOffs = 0;
-
-	// Scans for the best correlation value by testing each possible position
-	// over the permitted range.
-	for (int32_t i = 0; i < this->seekLength; ++i)
-	{
-		// Calculates correlation value for the mixing position corresponding
-		// to 'i'
-		double corr = this->calcCrossCorr(refPos + this->channels * i, this->pMidBuffer);
-		// heuristic rule to slightly favour values close to mid of the range
-		double tmp = (2.0 * i - this->seekLength) / this->seekLength;
-		corr = (corr + 0.1) * (1.0 - 0.25 * tmp * tmp);
-
-		// Checks for the highest correlation value
-		if (corr > bestCorr)
-		{
-			bestCorr = corr;
-			bestOffs = i;
-		}
-	}
-	// clear cross correlation routine state if necessary (is so e.g. in MMX routines).
-	this->clearCrossCorrState();
-
-	return bestOffs;
-}
-
-// Seeks for the optimal overlap-mixing position. The 'stereo' version of the
-// routine
-//
-// The best position is determined as the position where the two overlapped
-// sample sequences are 'most alike', in terms of the highest cross-correlation
-// value over the overlapping period
-int32_t TDStretch::seekBestOverlapPositionQuick(const SAMPLETYPE *refPos)
-{
-	double bestCorr = std::numeric_limits<float>::min();
-	int32_t bestOffs = _scanOffsets[0][0], corrOffset = 0;
-
-	// Scans for the best correlation value using four-pass hierarchical search.
-	//
-	// The look-up table 'scans' has hierarchical position adjusting steps.
-	// In first pass the routine searhes for the highest correlation with
-	// relatively coarse steps, then rescans the neighbourhood of the highest
-	// correlation with better resolution and so on.
-	for (uint32_t scanCount = 0; scanCount < 4; ++scanCount)
-	{
-		int32_t j = 0;
-		while (_scanOffsets[scanCount][j])
-		{
-			int32_t tempOffset = corrOffset + _scanOffsets[scanCount][j];
-			if (tempOffset >= this->seekLength)
-				break;
-
-			// Calculates correlation value for the mixing position corresponding
-			// to 'tempOffset'
-			double corr = this->calcCrossCorr(refPos + this->channels * tempOffset, this->pMidBuffer);
-			// heuristic rule to slightly favour values close to mid of the range
-			double tmp = (2.0 * tempOffset - this->seekLength) / seekLength;
-			corr = (corr + 0.1) * (1.0 - 0.25 * tmp * tmp);
-
-			// Checks for the highest correlation value
-			if (corr > bestCorr)
-			{
-				bestCorr = corr;
-				bestOffs = tempOffset;
-			}
-			++j;
-		}
-		corrOffset = bestOffs;
-	}
-	// clear cross correlation routine state if necessary (is so e.g. in MMX routines).
-	this->clearCrossCorrState();
-
-	return bestOffs;
-}
-
-/// clear cross correlation routine state if necessary
-void TDStretch::clearCrossCorrState()
-{
-	// default implementation is empty.
-}
-
-/// Calculates processing sequence length according to tempo setting
-void TDStretch::calcSeqParameters()
-{
-	// Adjust tempo param according to tempo, so that variating processing sequence length is used
-	// at varius tempo settings, between the given low...top limits
-	static const double AUTOSEQ_TEMPO_LOW = 0.5; // auto setting low tempo range (-50%)
-	static const double AUTOSEQ_TEMPO_TOP = 2.0; // auto setting top tempo range (+100%)
-
-	// sequence-ms setting values at above low & top tempo
-	static const double AUTOSEQ_AT_MIN = 125.0;
-	static const double AUTOSEQ_AT_MAX = 50.0;
-	static const double AUTOSEQ_K = (AUTOSEQ_AT_MAX - AUTOSEQ_AT_MIN) / (AUTOSEQ_TEMPO_TOP - AUTOSEQ_TEMPO_LOW);
-	static const double AUTOSEQ_C = AUTOSEQ_AT_MIN - AUTOSEQ_K * AUTOSEQ_TEMPO_LOW;
-
-	// seek-window-ms setting values at above low & top tempo
-	static const double AUTOSEEK_AT_MIN = 25.0;
-	static const double AUTOSEEK_AT_MAX = 15.0;
-	static const double AUTOSEEK_K = (AUTOSEEK_AT_MAX - AUTOSEEK_AT_MIN) / (AUTOSEQ_TEMPO_TOP - AUTOSEQ_TEMPO_LOW);
-	static const double AUTOSEEK_C = AUTOSEEK_AT_MIN - AUTOSEEK_K * AUTOSEQ_TEMPO_LOW;
-
-	auto CHECK_LIMITS = [](double x, double mi, double ma) { return x < mi ? mi : (x > ma ? ma : x); };
-
-	if (this->bAutoSeqSetting)
-	{
-		double seq = AUTOSEQ_C + AUTOSEQ_K * this->tempo;
-		seq = CHECK_LIMITS(seq, AUTOSEQ_AT_MAX, AUTOSEQ_AT_MIN);
-		this->sequenceMs = static_cast<int>(seq + 0.5);
-	}
-
-	if (this->bAutoSeekSetting)
-	{
-		double seek = AUTOSEEK_C + AUTOSEEK_K * this->tempo;
-		seek = CHECK_LIMITS(seek, AUTOSEEK_AT_MAX, AUTOSEEK_AT_MIN);
-		this->seekWindowMs = static_cast<int>(seek + 0.5);
-    }
-
-	// Update seek window lengths
-	this->seekWindowLength = (this->sampleRate * this->sequenceMs) / 1000;
-	if (this->seekWindowLength < 2 * this->overlapLength)
-		this->seekWindowLength = 2 * this->overlapLength;
-	this->seekLength = (this->sampleRate * this->seekWindowMs) / 1000;
-}
-
-// Sets new target tempo. Normal tempo = 'SCALE', smaller values represent slower
-// tempo, larger faster tempo.
-void TDStretch::setTempo(float newTempo)
-{
-	this->tempo = newTempo;
-
-	// Calculate new sequence duration
-	this->calcSeqParameters();
-
-	// Calculate ideal skip length (according to tempo value)
-	this->nominalSkip = this->tempo * (this->seekWindowLength - this->overlapLength);
-	int intskip = static_cast<int>(nominalSkip + 0.5f);
-
-	// Calculate how many samples are needed in the 'inputBuffer' to
-	// process another batch of samples
-	this->sampleReq = std::max(intskip + this->overlapLength, this->seekWindowLength) + this->seekLength;
-}
-
-// Sets the number of channels, 1 = mono, 2 = stereo
-void TDStretch::setChannels(int32_t numChannels)
-{
-	assert(numChannels > 0);
-	if (this->channels == numChannels)
-		return;
-	assert(numChannels == 1 || numChannels == 2);
-
-	this->channels = numChannels;
-	this->inputBuffer.setChannels(channels);
-	this->outputBuffer.setChannels(channels);
-}
-
-// Processes as many processing frames of the samples 'inputBuffer', store
-// the result into 'outputBuffer'
-void TDStretch::processSamples()
-{
-	/* Removed this small optimization - can introduce a click to sound when tempo setting
-	   crosses the nominal value
-	if (this->tempo == 1.0f)
-	{
-		// tempo not changed from the original, so bypass the processing
-		this->processNominalTempo();
-		return;
-	}*/
-
-	// Process samples as long as there are enough samples in 'inputBuffer'
-	// to form a processing frame.
-	while (static_cast<int32_t>(this->inputBuffer.numSamples()) >= this->sampleReq)
-	{
-		// If tempo differs from the normal ('SCALE'), scan for the best overlapping
-		// position
-		int32_t offset = this->seekBestOverlapPosition(this->inputBuffer.ptrBegin());
-
-		// Mix the samples in the 'inputBuffer' at position of 'offset' with the
-		// samples in 'midBuffer' using sliding overlapping
-		// ... first partially overlap with the end of the previous sequence
-		// (that's in 'midBuffer')
-		this->overlap(this->outputBuffer.ptrEnd(this->overlapLength), this->inputBuffer.ptrBegin(), offset);
-		this->outputBuffer.putSamples(this->overlapLength);
-
-		// ... then copy sequence samples from 'inputBuffer' to output:
-
-		// length of sequence
-		int temp = this->seekWindowLength - 2 * this->overlapLength;
-
-		// crosscheck that we don't have buffer overflow...
-		if (static_cast<int32_t>(inputBuffer.numSamples()) < offset + temp + this->overlapLength * 2)
-			continue; // just in case, shouldn't really happen
-
-		this->outputBuffer.putSamples(this->inputBuffer.ptrBegin() + this->channels * (offset + this->overlapLength), temp);
-
-		// Copies the end of the current sequence from 'inputBuffer' to
-		// 'midBuffer' for being mixed with the beginning of the next
-		// processing sequence and so on
-		assert(offset + temp + this->overlapLength * 2 <= static_cast<int32_t>(this->inputBuffer.numSamples()));
-		memcpy(this->pMidBuffer, this->inputBuffer.ptrBegin() + this->channels * (offset + this->seekWindowLength - this->overlapLength), this->channels * sizeof(SAMPLETYPE) * this->overlapLength);
-
-		// Remove the processed samples from the input buffer. Update
-		// the difference between integer & nominal skip step to 'skipFract'
-		// in order to prevent the error from accumulating over time.
-		this->skipFract += this->nominalSkip; // real skip size
-		int ovlSkip = static_cast<int>(skipFract); // rounded to integer skip
-		this->skipFract -= ovlSkip; // maintain the fraction part, i.e. real vs. integer skip
-		this->inputBuffer.receiveSamples(ovlSkip);
-	}
-}
-
-// Adds 'numsamples' pcs of samples from the 'samples' memory position into
-// the input of the object.
-void TDStretch::putSamples(const SAMPLETYPE *samples, uint32_t nSamples)
-{
-	// Add the samples into the input buffer
-	this->inputBuffer.putSamples(samples, nSamples);
-	// Process the samples in input buffer
-	this->processSamples();
-}
-
-/// Set new overlap length parameter & reallocate RefMidBuffer if necessary.
-void TDStretch::acceptNewOverlapLength(int32_t newOverlapLength)
-{
-	assert(newOverlapLength >= 0);
-	int32_t prevOvl = this->overlapLength;
-	this->overlapLength = newOverlapLength;
-
-	if (this->overlapLength > prevOvl)
-	{
-		this->pMidBufferUnaligned.reset(new SAMPLETYPE[this->overlapLength * 2 + 16 / sizeof(SAMPLETYPE)]);
-		// ensure that 'pMidBuffer' is aligned to 16 byte boundary for efficiency
-		this->pMidBuffer = reinterpret_cast<SAMPLETYPE *>(SOUNDTOUCH_ALIGN_POINTER_16(this->pMidBufferUnaligned.get()));
-
-		this->clearMidBuffer();
-	}
-}
-
-// Operator 'new' is overloaded so that it automatically creates a suitable instance
-// depending on if we've a MMX/SSE/etc-capable CPU available or not.
-void *TDStretch::operator new(size_t /*s*/)
-{
-	// Notice! don't use "new TDStretch" directly, use "newInstance" to create a new instance instead!
-	//assert(false);
-	//return NULL;
-	throw std::runtime_error("Don't use 'new TDStretch', use 'newInstance' member instead!");
-}
-
-TDStretch *TDStretch::newInstance()
-{
-	uint32_t uExtensions = detectCPUextensions();
-
-	// Check if MMX/SSE instruction set extensions supported by CPU
-
-#ifdef SOUNDTOUCH_ALLOW_MMX
-	// MMX routines available only with integer sample types
-	if (uExtensions & SUPPORT_MMX)
-		return ::new TDStretchMMX;
-	else
-#endif // SOUNDTOUCH_ALLOW_MMX
-#ifdef SOUNDTOUCH_ALLOW_SSE
-	if (uExtensions & SUPPORT_SSE)
-		// SSE support
-		return ::new TDStretchSSE;
-	else
-#endif //  SOUNDTOUCH_ALLOW_SSE
-		// ISA optimizations not supported, use plain C version
-		return ::new TDStretch;
-}
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// Integer arithmetics specific algorithm implementations.
-//
-//////////////////////////////////////////////////////////////////////////////
-
-#ifdef SOUNDTOUCH_INTEGER_SAMPLES
-
-// Overlaps samples in 'midBuffer' with the samples in 'pinput'. The 'Stereo'
-// version of the routine.
-void TDStretch::overlapStereo(short *poutput, const short *pinput) const
-{
-	for (int32_t i = 0; i < this->overlapLength; ++i)
-	{
-		short temp = this->overlapLength - i;
-		int32_t cnt2 = 2 * i;
-		poutput[cnt2] = (pinput[cnt2] * i + this->pMidBuffer[cnt2] * temp) / this->overlapLength;
-		poutput[cnt2 + 1] = (pinput[cnt2 + 1] * i + this->pMidBuffer[cnt2 + 1] * temp) / this->overlapLength;
-	}
-}
-
-// Calculates the x having the closest 2^x value for the given value
-static int _getClosest2Power(double value)
-{
-	return static_cast<int>(std::log(value) / std::log(2.0) + 0.5);
-}
-
-/// Calculates overlap period length in samples.
-/// Integer version rounds overlap length to closest power of 2
-/// for a divide scaling operation.
-void TDStretch::calculateOverlapLength(int32_t aoverlapMs)
-{
-	assert(aoverlapMs >= 0);
-
-	// calculate overlap length so that it's power of 2 - thus it's easy to do
-	// integer division by right-shifting. Term "-1" at end is to account for
-	// the extra most significatnt bit left unused in result by signed multiplication
-	this->overlapDividerBits = _getClosest2Power((this->sampleRate * aoverlapMs) / 1000.0) - 1;
-	if (this->overlapDividerBits > 9)
-		this->overlapDividerBits = 9;
-	if (this->overlapDividerBits < 3)
-		this->overlapDividerBits = 3;
-	int32_t newOvl = static_cast<int32_t>(std::pow(2, this->overlapDividerBits + 1)); // +1 => account for -1 above
-
-	this->acceptNewOverlapLength(newOvl);
-
-	// calculate sloping divider so that crosscorrelation operation won't
-	// overflow 32-bit register. Max. sum of the crosscorrelation sum without
-	// divider would be 2^30*(N^3-N)/3, where N = overlap length
-	this->slopingDivider = (newOvl * newOvl - 1) / 3;
-}
-
-double TDStretch::calcCrossCorr(const short *mixingPos, const short *compare) const
-{
-	long corr = 0, norm = 0;
-	// Same routine for stereo and mono. For stereo, unroll loop for better
-	// efficiency and gives slightly better resolution against rounding.
-	// For mono it same routine, just  unrolls loop by factor of 4
-	for (int32_t i = 0; i < this->overlapLength; i += 4)
-	{
-		corr += (mixingPos[i] * compare[i] + mixingPos[i + 1] * compare[i + 1] + mixingPos[i + 2] * compare[i + 2] + mixingPos[i + 3] * compare[i + 3]) >> this->overlapDividerBits;
-		norm += (mixingPos[i] * mixingPos[i] + mixingPos[i + 1] * mixingPos[i + 1] + mixingPos[i + 2] * mixingPos[i + 2] + mixingPos[i + 3] * mixingPos[i + 3]) >> this->overlapDividerBits;
-	}
-
-	// Normalize result by dividing by sqrt(norm) - this step is easiest
-	// done using floating point operation
-	if (!norm)
-		norm = 1; // to avoid div by zero
-	return corr / std::sqrt(static_cast<double>(norm));
-}
-
-#endif // SOUNDTOUCH_INTEGER_SAMPLES
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// Floating point arithmetics specific algorithm implementations.
-//
-
-#ifdef SOUNDTOUCH_FLOAT_SAMPLES
-
-// Overlaps samples in 'midBuffer' with the samples in 'pInput'
-void TDStretch::overlapStereo(float *pOutput, const float *pInput) const
-{
-	float fScale = 1.0f / this->overlapLength;
-
-	float f1 = 0, f2 = 1.0f;
-
-	for (int32_t i = 0; i < 2 * this->overlapLength; i += 2)
-	{
-		pOutput[i] = pInput[i] * f1 + this->pMidBuffer[i] * f2;
-		pOutput[i + 1] = pInput[i + 1] * f1 + this->pMidBuffer[i + 1] * f2;
-
-		f1 += fScale;
-		f2 -= fScale;
-	}
-}
-
-/// Calculates overlapInMsec period length in samples.
-void TDStretch::calculateOverlapLength(int32_t overlapInMsec)
-{
-	assert(overlapInMsec >= 0);
-	uint32_t newOvl = (this->sampleRate * overlapInMsec) / 1000;
-	if (newOvl < 16)
-		newOvl = 16;
-
-	// must be divisible by 8
-	newOvl -= newOvl % 8;
-
-	this->acceptNewOverlapLength(newOvl);
-}
-
-double TDStretch::calcCrossCorr(const float *mixingPos, const float *compare) const
-{
-	double corr = 0, norm = 0;
-	// Same routine for stereo and mono. For Stereo, unroll by factor of 2.
-	// For mono it's same routine yet unrollsd by factor of 4.
-	for (int32_t i = 0; i < this->channels * this->overlapLength; i += 4)
-	{
-		corr += mixingPos[i] * compare[i] + mixingPos[i + 1] * compare[i + 1];
-
-		norm += mixingPos[i] * mixingPos[i] +  mixingPos[i + 1] * mixingPos[i + 1];
-
-		// unroll the loop for better CPU efficiency:
-		corr += mixingPos[i + 2] * compare[i + 2] + mixingPos[i + 3] * compare[i + 3];
-
-		norm += mixingPos[i + 2] * mixingPos[i + 2] + mixingPos[i + 3] * mixingPos[i + 3];
-	}
-
-	if (norm < 1e-9)
-		norm = 1.0; // to avoid div by zero
-	return corr / std::sqrt(norm);
-}
-
-#endif // SOUNDTOUCH_FLOAT_SAMPLES
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/TDStretch.h
+++ /dev/null
@@ -1,245 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// Sampled sound tempo changer/time stretch algorithm. Changes the sound tempo
-/// while maintaining the original pitch by using a time domain WSOLA-like method
-/// with several performance-increasing tweaks.
-///
-/// Note : MMX/SSE optimized functions reside in separate, platform-specific files
-/// 'mmx_optimized.cpp' and 'sse_optimized.cpp'
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2012-04-01 16:49:30 -0300 (dom, 01 abr 2012) $
-// File revision : $Revision: 4 $
-//
-// $Id: TDStretch.h 137 2012-04-01 19:49:30Z oparviai $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#pragma once
-
-#include <memory>
-#include "FIFOSampleBuffer.h"
-
-namespace soundtouch
-{
-
-/// Default values for sound processing parameters:
-/// Notice that the default parameters are tuned for contemporary popular music
-/// processing. For speech processing applications these parameters suit better:
-///     #define DEFAULT_SEQUENCE_MS     40
-///     #define DEFAULT_SEEKWINDOW_MS   15
-///     #define DEFAULT_OVERLAP_MS      8
-///
-
-/// Giving this value for the sequence length sets automatic parameter value
-/// according to tempo setting (recommended)
-const int32_t USE_AUTO_SEQUENCE_LEN = 0;
-
-/// Default length of a single processing sequence, in milliseconds. This determines to how
-/// long sequences the original sound is chopped in the time-stretch algorithm.
-///
-/// The larger this value is, the lesser sequences are used in processing. In principle
-/// a bigger value sounds better when slowing down tempo, but worse when increasing tempo
-/// and vice versa.
-///
-/// Increasing this value reduces computational burden & vice versa.
-//#define DEFAULT_SEQUENCE_MS 40
-const int32_t DEFAULT_SEQUENCE_MS = USE_AUTO_SEQUENCE_LEN;
-
-/// Giving this value for the seek window length sets automatic parameter value
-/// according to tempo setting (recommended)
-const int32_t USE_AUTO_SEEKWINDOW_LEN = 0;
-
-/// Seeking window default length in milliseconds for algorithm that finds the best possible
-/// overlapping location. This determines from how wide window the algorithm may look for an
-/// optimal joining location when mixing the sound sequences back together.
-///
-/// The bigger this window setting is, the higher the possibility to find a better mixing
-/// position will become, but at the same time large values may cause a "drifting" artifact
-/// because consequent sequences will be taken at more uneven intervals.
-///
-/// If there's a disturbing artifact that sounds as if a constant frequency was drifting
-/// around, try reducing this setting.
-///
-/// Increasing this value increases computational burden & vice versa.
-//#define DEFAULT_SEEKWINDOW_MS       15
-const int32_t DEFAULT_SEEKWINDOW_MS = USE_AUTO_SEEKWINDOW_LEN;
-
-/// Overlap length in milliseconds. When the chopped sound sequences are mixed back together,
-/// to form a continuous sound stream, this parameter defines over how long period the two
-/// consecutive sequences are let to overlap each other.
-///
-/// This shouldn't be that critical parameter. If you reduce the DEFAULT_SEQUENCE_MS setting
-/// by a large amount, you might wish to try a smaller value on this.
-///
-/// Increasing this value increases computational burden & vice versa.
-const int32_t DEFAULT_OVERLAP_MS = 8;
-
-/// Class that does the time-stretch (tempo change) effect for the processed
-/// sound.
-class TDStretch : public FIFOProcessor
-{
-protected:
-	int32_t channels;
-	int32_t sampleReq;
-	float tempo;
-
-	SAMPLETYPE *pMidBuffer;
-	std::unique_ptr<SAMPLETYPE[]> pMidBufferUnaligned;
-	int32_t overlapLength;
-	int32_t seekLength;
-	int32_t seekWindowLength;
-	int32_t overlapDividerBits;
-	int32_t slopingDivider;
-	float nominalSkip;
-	float skipFract;
-	FIFOSampleBuffer outputBuffer;
-	FIFOSampleBuffer inputBuffer;
-	bool bQuickSeek;
-
-	int32_t sampleRate;
-	int32_t sequenceMs;
-	int32_t seekWindowMs;
-	int32_t overlapMs;
-	bool bAutoSeqSetting;
-	bool bAutoSeekSetting;
-
-	void acceptNewOverlapLength(int32_t newOverlapLength);
-
-	virtual void clearCrossCorrState();
-	void calculateOverlapLength(int32_t overlapMs);
-
-	virtual double calcCrossCorr(const SAMPLETYPE *mixingPos, const SAMPLETYPE *compare) const;
-
-	virtual int seekBestOverlapPositionFull(const SAMPLETYPE *refPos);
-	virtual int seekBestOverlapPositionQuick(const SAMPLETYPE *refPos);
-	int32_t seekBestOverlapPosition(const SAMPLETYPE *refPos);
-
-	virtual void overlapStereo(SAMPLETYPE *output, const SAMPLETYPE *input) const;
-	virtual void overlapMono(SAMPLETYPE *output, const SAMPLETYPE *input) const;
-
-	void clearMidBuffer();
-	void overlap(SAMPLETYPE *output, const SAMPLETYPE *input, uint32_t ovlPos) const;
-
-	void calcSeqParameters();
-
-	/// Changes the tempo of the given sound samples.
-	/// Returns amount of samples returned in the "output" buffer.
-	/// The maximum amount of samples that can be returned at a time is set by
-	/// the 'set_returnBuffer_size' function.
-	void processSamples();
-
-public:
-	TDStretch();
-	virtual ~TDStretch();
-
-	/// Operator 'new' is overloaded so that it automatically creates a suitable instance
-	/// depending on if we've a MMX/SSE/etc-capable CPU available or not.
-	static void *operator new(size_t s);
-
-	/// Use this function instead of "new" operator to create a new instance of this class.
-	/// This function automatically chooses a correct feature set depending on if the CPU
-	/// supports MMX/SSE/etc extensions.
-	static TDStretch *newInstance();
-
-	/// Returns the output buffer object
-	FIFOSamplePipe *getOutput() { return &this->outputBuffer; }
-
-	/// Returns the input buffer object
-	FIFOSamplePipe *getInput() { return &this->inputBuffer; }
-
-	/// Sets new target tempo. Normal tempo = 'SCALE', smaller values represent slower
-	/// tempo, larger faster tempo.
-	void setTempo(float newTempo);
-
-	/// Returns nonzero if there aren't any samples available for outputting.
-	virtual void clear();
-
-	/// Clears the input buffer
-	void clearInput();
-
-	/// Sets the number of channels, 1 = mono, 2 = stereo
-	void setChannels(int32_t numChannels);
-
-	/// Enables/disables the quick position seeking algorithm. Zero to disable,
-	/// nonzero to enable
-	void enableQuickSeek(bool enable);
-
-	/// Sets routine control parameters. These control are certain time constants
-	/// defining how the sound is stretched to the desired duration.
-	//
-	/// 'sampleRate' = sample rate of the sound
-	/// 'sequenceMS' = one processing sequence length in milliseconds
-	/// 'seekwindowMS' = seeking window length for scanning the best overlapping
-	///      position
-	/// 'overlapMS' = overlapping length
-	void setParameters(int32_t sampleRate,          ///< Samplerate of sound being processed (Hz)
-                       int32_t sequenceMS = -1,     ///< Single processing sequence length (ms)
-                       int32_t seekwindowMS = -1,   ///< Offset seeking window length (ms)
-                       int32_t overlapMS = -1       ///< Sequence overlapping length (ms)
-                       );
-
-	/// Get routine control parameters, see setParameters() function.
-	/// Any of the parameters to this function can be NULL, in such case corresponding parameter
-	/// value isn't returned.
-	void getParameters(int32_t *pSampleRate, int32_t *pSequenceMs, int32_t *pSeekWindowMs, int32_t *pOverlapMs);
-
-	/// Adds 'numsamples' pcs of samples from the 'samples' memory position into
-	/// the input of the object.
-	virtual void putSamples(
-            const SAMPLETYPE *samples,  ///< Input sample data
-            uint32_t numSamples                         ///< Number of samples in 'samples' so that one sample
-                                                       ///< contains both channels if stereo
-            );
-};
-
-// Implementation-specific class declarations:
-
-#ifdef SOUNDTOUCH_ALLOW_MMX
-/// Class that implements MMX optimized routines for 16bit integer samples type.
-class TDStretchMMX : public TDStretch
-{
-protected:
-	double calcCrossCorr(const short *mixingPos, const short *compare) const;
-	virtual void overlapStereo(short *output, const short *input) const;
-	virtual void clearCrossCorrState();
-};
-#endif /// SOUNDTOUCH_ALLOW_MMX
-
-#ifdef SOUNDTOUCH_ALLOW_SSE
-/// Class that implements SSE optimized routines for floating point samples type.
-class TDStretchSSE : public TDStretch
-{
-protected:
-	double calcCrossCorr(const float *mixingPos, const float *compare) const;
-};
-#endif ///  SOUNDTOUCH_ALLOW_SSE
-
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/cpu_detect.h
+++ /dev/null
@@ -1,58 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// A header file for detecting the Intel MMX instructions set extension.
-///
-/// Please see 'mmx_win.cpp', 'mmx_cpp.cpp' and 'mmx_non_x86.cpp' for the
-/// routine implementations for x86 Windows, x86 gnu version and non-x86
-/// platforms, respectively.
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2006/02/05 16:44:06 $
-// File revision : $Revision: 1.4 $
-//
-// $Id: cpu_detect.h,v 1.4 2006/02/05 16:44:06 Olli Exp $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#pragma once
-
-#include "STTypes.h"
-
-const uint32_t SUPPORT_MMX = 0x0001;
-const uint32_t SUPPORT_3DNOW = 0x0002;
-const uint32_t SUPPORT_SSE = 0x0004;
-
-/// Checks which instruction set extensions are supported by the CPU.
-///
-/// \return A bitmask of supported extensions, see SUPPORT_... defines.
-uint32_t detectCPUextensions();
-
-/// Disables given set of instruction extensions. See SUPPORT_... defines.
-void disableExtensions(uint32_t wDisableMask);
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/cpu_detect_x86_gcc.cpp
+++ /dev/null
@@ -1,139 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// gcc version of the x86 CPU detect routine.
-///
-/// This file is to be compiled on any platform with the GNU C compiler.
-/// Compiler. Please see 'cpu_detect_x86_win.cpp' for the x86 Windows version
-/// of this file.
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2006/02/05 16:44:06 $
-// File revision : $Revision: 1.6 $
-//
-// $Id: cpu_detect_x86_gcc.cpp,v 1.6 2006/02/05 16:44:06 Olli Exp $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#include <stdexcept>
-#include <string>
-#include "cpu_detect.h"
-
-#ifndef __GNUC__
-#error wrong platform - this source code file is for the GNU C compiler.
-#endif
-
-using namespace std;
-
-#include <stdio.h>
-//////////////////////////////////////////////////////////////////////////////
-//
-// processor instructions extension detection routines
-//
-//////////////////////////////////////////////////////////////////////////////
-
-
-// Flag variable indicating whick ISA extensions are disabled (for debugging)
-static uint32_t _dwDisabledISA = 0x00;      // 0xffffffff; //<- use this to disable all extensions
-
-// Disables given set of instruction extensions. See SUPPORT_... defines.
-void disableExtensions(uint32_t dwDisableMask)
-{
-    _dwDisabledISA = dwDisableMask;
-}
-
-
-
-/// Checks which instruction set extensions are supported by the CPU.
-uint32_t detectCPUextensions(void)
-{
-#ifndef __i386__
-    return 0; // always disable extensions on non-x86 platforms.
-#else
-    uint32_t res = 0;
-
-    if (_dwDisabledISA == 0xffffffff) return 0;
-
-    asm volatile(
-        "\n\txor     %%esi, %%esi"       // clear %%esi = result register
-        // check if 'cpuid' instructions is available by toggling eflags bit 21
-
-        "\n\tpushf"                      // save eflags to stack
-        "\n\tpop     %%eax"              // load eax from stack (with eflags)
-        "\n\tmovl    %%eax, %%ecx"       // save the original eflags values to ecx
-        "\n\txor     $0x00200000, %%eax" // toggle bit 21
-        "\n\tpush    %%eax"              // store toggled eflags to stack
-        "\n\tpopf"                       // load eflags from stack
-        "\n\tpushf"                      // save updated eflags to stack
-        "\n\tpop     %%eax"              // load from stack
-        "\n\txor     %%edx, %%edx"       // clear edx for defaulting no mmx
-        "\n\tcmp     %%ecx, %%eax"       // compare to original eflags values
-        "\n\tjz      end"                // jumps to 'end' if cpuid not present
-
-        // cpuid instruction available, test for presence of mmx instructions
-
-        "\n\tmovl    $1, %%eax"
-        "\n\tcpuid"
-//        movl       $0x00800000, %edx   // force enable MMX
-        "\n\ttest    $0x00800000, %%edx"
-        "\n\tjz      end"                // branch if MMX not available
-
-        "\n\tor      $0x01, %%esi"       // otherwise add MMX support bit
-
-        "\n\ttest    $0x02000000, %%edx"
-        "\n\tjz      test3DNow"          // branch if SSE not available
-
-        "\n\tor      $0x08, %%esi"       // otherwise add SSE support bit
-
-    "\n\ttest3DNow:"
-        // test for precense of AMD extensions
-        "\n\tmov     $0x80000000, %%eax"
-        "\n\tcpuid"
-        "\n\tcmp     $0x80000000, %%eax"
-        "\n\tjbe     end"                 // branch if no AMD extensions detected
-
-        // test for precense of 3DNow! extension
-        "\n\tmov     $0x80000001, %%eax"
-        "\n\tcpuid"
-        "\n\ttest    $0x80000000, %%edx"
-        "\n\tjz      end"                  // branch if 3DNow! not detected
-
-        "\n\tor      $0x02, %%esi"         // otherwise add 3DNow support bit
-
-    "\n\tend:"
-
-        "\n\tmov     %%esi, %0"
-
-      : "=r" (res)
-      : /* no inputs */
-      : "%edx", "%eax", "%ecx", "%esi" );
-
-    return res & ~_dwDisabledISA;
-#endif
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/cpu_detect_x86_win.cpp
+++ /dev/null
@@ -1,92 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// Win32 version of the x86 CPU detect routine.
-///
-/// This file is to be compiled in Windows platform with Microsoft Visual C++
-/// Compiler. Please see 'cpu_detect_x86_gcc.cpp' for the gcc compiler version
-/// for all GNU platforms.
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2006/02/05 16:44:06 $
-// File revision : $Revision: 1.10 $
-//
-// $Id: cpu_detect_x86_win.cpp,v 1.10 2006/02/05 16:44:06 Olli Exp $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#include "cpu_detect.h"
-#ifdef _MSC_VER
-#include <intrin.h>
-#endif
-
-#ifndef _WIN32
-#error wrong platform - this source code file is exclusively for Win32 platform
-#endif
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// processor instructions extension detection routines
-//
-//////////////////////////////////////////////////////////////////////////////
-
-// Flag variable indicating whick ISA extensions are disabled (for debugging)
-static uint32_t _dwDisabledISA = 0x00; // 0xffffffff; //<- use this to disable all extensions
-
-// Disables given set of instruction extensions. See SUPPORT_... defines.
-void disableExtensions(uint32_t dwDisableMask)
-{
-	_dwDisabledISA = dwDisableMask;
-}
-
-/// Checks which instruction set extensions are supported by the CPU.
-uint32_t detectCPUextensions()
-{
-	uint32_t res = 0;
-
-	if (_dwDisabledISA == 0xffffffff)
-		return 0;
-
-#ifdef _MSC_VER
-	int CPUInfo[4] = { -1 };
-	__cpuid(CPUInfo, 1);
-	res |= (CPUInfo[3] & (1 << 23)) ? SUPPORT_MMX : 0;
-	res |= (CPUInfo[3] & (1 << 25)) ? SUPPORT_SSE : 0;
-
-	// Test 3Dnow
-	__cpuid(CPUInfo, 0x80000000);
-	if (CPUInfo[0] == 0x80000000)
-	{
-		__cpuid(CPUInfo, 0x80000001);
-		res |= (CPUInfo[3] & (1 << 31)) ? SUPPORT_3DNOW : 0;
-	}
-#endif
-
-	return res & ~_dwDisabledISA;
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/mmx_optimized.cpp
+++ /dev/null
@@ -1,282 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// MMX optimized routines. All MMX optimized functions have been gathered into
-/// this single source code file, regardless to their class or original source
-/// code file, in order to ease porting the library to other compiler and
-/// processor platforms.
-///
-/// The MMX-optimizations are programmed using MMX compiler intrinsics that
-/// are supported both by Microsoft Visual C++ and GCC compilers, so this file
-/// should compile with both toolsets.
-///
-/// NOTICE: If using Visual Studio 6.0, you'll need to install the "Visual C++
-/// 6.0 processor pack" update to support compiler intrinsic syntax. The update
-/// is available for download at Microsoft Developers Network, see here:
-/// http://msdn.microsoft.com/en-us/vstudio/aa718349.aspx
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2012-11-08 16:53:01 -0200 (qui, 08 nov 2012) $
-// File revision : $Revision: 4 $
-//
-// $Id: mmx_optimized.cpp 160 2012-11-08 18:53:01Z oparviai $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#include "STTypes.h"
-
-#ifdef SOUNDTOUCH_ALLOW_MMX
-// MMX routines available only with integer sample type
-
-using namespace soundtouch;
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// implementation of MMX optimized functions of class 'TDStretchMMX'
-//
-//////////////////////////////////////////////////////////////////////////////
-
-#include "TDStretch.h"
-#include <mmintrin.h>
-
-// Calculates cross correlation of two buffers
-double TDStretchMMX::calcCrossCorr(const short *pV1, const short *pV2) const
-{
-	const __m64 *pVec1 = reinterpret_cast<__m64 *>(pV1);
-	const __m64 *pVec2 = reinterpret_cast<__m64 *>(pV2);
-
-	__m64 shifter = _m_from_int(this->overlapDividerBits);
-	__m64 normaccu, accu;
-	normaccu = accu = _mm_setzero_si64();
-
-	// Process 4 parallel sets of 2 * stereo samples or 4 * mono samples
-	// during each round for improved CPU-level parallellization.
-	for (int32_t i = 0; i < this->channels * this->overlapLength / 16; ++i)
-	{
-		// dictionary of instructions:
-		// _m_pmaddwd   : 4*16bit multiply-add, resulting two 32bits = [a0*b0+a1*b1 ; a2*b2+a3*b3]
-		// _mm_add_pi32 : 2*32bit add
-		// _m_psrad     : 32bit right-shift
-
-		__m64 temp = _mm_add_pi32(_mm_madd_pi16(pVec1[0], pVec2[0]), _mm_madd_pi16(pVec1[1], pVec2[1]));
-		__m64 temp2 = _mm_add_pi32(_mm_madd_pi16(pVec1[0], pVec1[0]), _mm_madd_pi16(pVec1[1], pVec1[1]));
-		accu = _mm_add_pi32(accu, _mm_sra_pi32(temp, shifter));
-		normaccu = _mm_add_pi32(normaccu, _mm_sra_pi32(temp2, shifter));
-
-		temp = _mm_add_pi32(_mm_madd_pi16(pVec1[2], pVec2[2]), _mm_madd_pi16(pVec1[3], pVec2[3]));
-		temp2 = _mm_add_pi32(_mm_madd_pi16(pVec1[2], pVec1[2]), _mm_madd_pi16(pVec1[3], pVec1[3]));
-		accu = _mm_add_pi32(accu, _mm_sra_pi32(temp, shifter));
-		normaccu = _mm_add_pi32(normaccu, _mm_sra_pi32(temp2, shifter));
-
-		pVec1 += 4;
-		pVec2 += 4;
-	}
-
-	// copy hi-dword of mm0 to lo-dword of mm1, then sum mmo+mm1
-	// and finally store the result into the variable "corr"
-
-	accu = _mm_add_pi32(accu, _mm_srli_si64(accu, 32));
-	long corr = _m_to_int(accu);
-
-	normaccu = _mm_add_pi32(normaccu, _mm_srli_si64(normaccu, 32));
-	long norm = _m_to_int(normaccu);
-
-	// Clear MMS state
-	_m_empty();
-
-	// Normalize result by dividing by sqrt(norm) - this step is easiest
-	// done using floating point operation
-	if (!norm)
-		norm = 1; // to avoid div by zero
-
-	return corr / std::sqrt(static_cast<double>(norm));
-	// Note: Warning about the missing EMMS instruction is harmless
-	// as it'll be called elsewhere.
-}
-
-void TDStretchMMX::clearCrossCorrState()
-{
-	// Clear MMS state
-	_m_empty();
-	//_asm EMMS;
-}
-
-// MMX-optimized version of the function overlapStereo
-void TDStretchMMX::overlapStereo(short *output, const short *input) const
-{
-	const __m64 *pVinput = reinterpret_cast<const __m64 *>(input);
-	const __m64 *pVMidBuf = reinterpret_cast<const __m64 *>(this->pMidBuffer);
-	__m64 *pVdest = reinterpret_cast<__m64 *>(output);
-
-	// mix1  = mixer values for 1st stereo sample
-	// mix1  = mixer values for 2nd stereo sample
-	// adder = adder for updating mixer values after each round
-
-	__m64 mix1 = _mm_set_pi16(0, this->overlapLength, 0, this->overlapLength);
-	__m64 adder = _mm_set_pi16(1, -1, 1, -1);
-	__m64 mix2 = _mm_add_pi16(mix1, adder);
-	adder = _mm_add_pi16(adder, adder);
-
-	// Overlaplength-division by shifter. "+1" is to account for "-1" deduced in
-	// overlapDividerBits calculation earlier.
-	__m64 shifter = _m_from_int(overlapDividerBits + 1);
-
-	for (int32_t i = 0; i < this->overlapLength / 4; ++i)
-	{
-		// load & shuffle data so that input & mixbuffer data samples are paired
-		__m64 temp1 = _mm_unpacklo_pi16(pVMidBuf[0], pVinput[0]); // = i0l m0l i0r m0r
-		__m64 temp2 = _mm_unpackhi_pi16(pVMidBuf[0], pVinput[0]); // = i1l m1l i1r m1r
-
-		// temp = (temp .* mix) >> shifter
-		temp1 = _mm_sra_pi32(_mm_madd_pi16(temp1, mix1), shifter);
-		temp2 = _mm_sra_pi32(_mm_madd_pi16(temp2, mix2), shifter);
-		pVdest[0] = _mm_packs_pi32(temp1, temp2); // pack 2*2*32bit => 4*16bit
-
-		// update mix += adder
-		mix1 = _mm_add_pi16(mix1, adder);
-		mix2 = _mm_add_pi16(mix2, adder);
-
-		// --- second round begins here ---
-
-		// load & shuffle data so that input & mixbuffer data samples are paired
-		temp1 = _mm_unpacklo_pi16(pVMidBuf[1], pVinput[1]); // = i2l m2l i2r m2r
-		temp2 = _mm_unpackhi_pi16(pVMidBuf[1], pVinput[1]); // = i3l m3l i3r m3r
-
-		// temp = (temp .* mix) >> shifter
-		temp1 = _mm_sra_pi32(_mm_madd_pi16(temp1, mix1), shifter);
-		temp2 = _mm_sra_pi32(_mm_madd_pi16(temp2, mix2), shifter);
-		pVdest[1] = _mm_packs_pi32(temp1, temp2); // pack 2*2*32bit => 4*16bit
-
-		// update mix += adder
-		mix1 = _mm_add_pi16(mix1, adder);
-		mix2 = _mm_add_pi16(mix2, adder);
-
-		pVinput += 2;
-		pVMidBuf += 2;
-		pVdest += 2;
-	}
-
-	_m_empty(); // clear MMS state
-}
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// implementation of MMX optimized functions of class 'FIRFilter'
-//
-//////////////////////////////////////////////////////////////////////////////
-
-#include "FIRFilter.h"
-
-FIRFilterMMX::FIRFilterMMX() : FIRFilter()
-{
-	this->filterCoeffsUnalign.reset();
-}
-
-FIRFilterMMX::~FIRFilterMMX()
-{
-}
-
-// (overloaded) Calculates filter coefficients for MMX routine
-void FIRFilterMMX::setCoefficients(const short *coeffs, uint32_t newLength, uint32_t uResultDivFactor)
-{
-	FIRFilter::setCoefficients(coeffs, newLength, uResultDivFactor);
-
-	// Ensure that filter coeffs array is aligned to 16-byte boundary
-	this->filterCoeffsUnalign.reset(new short[2 * newLength + 8]);
-	this->filterCoeffsAlign = reinterpret_csat<short *>(SOUNDTOUCH_ALIGN_POINTER_16(this->filterCoeffsUnalign.get()));
-
-	// rearrange the filter coefficients for mmx routines
-	for (uint32_t i = 0; i < length; i += 4)
-	{
-		this->filterCoeffsAlign[2 * i ] = coeffs[i];
-		this->filterCoeffsAlign[2 * i + 1] = coeffs[i + 2];
-		this->filterCoeffsAlign[2 * i + 2] = coeffs[i];
-		this->filterCoeffsAlign[2 * i + 3] = coeffs[i + 2];
-
-		this->filterCoeffsAlign[2 * i + 4] = coeffs[i + 1];
-		this->filterCoeffsAlign[2 * i + 5] = coeffs[i + 3];
-		this->filterCoeffsAlign[2 * i + 6] = coeffs[i + 1];
-		this->filterCoeffsAlign[2 * i + 7] = coeffs[i + 3];
-	}
-}
-
-// mmx-optimized version of the filter routine for stereo sound
-uint32_t FIRFilterMMX::evaluateFilterStereo(short *dest, const short *src, uint32_t numSamples) const
-{
-	if (this->length < 2)
-		return 0;
-
-	// Create stack copies of the needed member variables for asm routines :
-	__m64 *pVdest = reinterpret_cast<__m64 *>(dest);
-
-	for (uint32_t i = 0; i < (numSamples - this->length) / 2; ++i)
-	{
-		const __m64 *pVsrc = reinterpret_cast<const __m64 *>(src);
-		const __m64 *pVfilter = reinterpret_cast<const __m64 *>(this->filterCoeffsAlign);
-
-		__m64 accu1, accu2;
-		accu1 = accu2 = _mm_setzero_si64();
-		for (uint32_t j = 0; j < this->lengthDiv8 * 2; ++j)
-		{
-			__m64 temp1 = _mm_unpacklo_pi16(pVsrc[0], pVsrc[1]); // = l2 l0 r2 r0
-			__m64 temp2 = _mm_unpackhi_pi16(pVsrc[0], pVsrc[1]); // = l3 l1 r3 r1
-
-			accu1 = _mm_add_pi32(accu1, _mm_madd_pi16(temp1, pVfilter[0])); // += l2*f2+l0*f0 r2*f2+r0*f0
-			accu1 = _mm_add_pi32(accu1, _mm_madd_pi16(temp2, pVfilter[1])); // += l3*f3+l1*f1 r3*f3+r1*f1
-
-			temp1 = _mm_unpacklo_pi16(pVsrc[1], pVsrc[2]); // = l4 l2 r4 r2
-
-			accu2 = _mm_add_pi32(accu2, _mm_madd_pi16(temp2, pVfilter[0])); // += l3*f2+l1*f0 r3*f2+r1*f0
-			accu2 = _mm_add_pi32(accu2, _mm_madd_pi16(temp1, pVfilter[1])); // += l4*f3+l2*f1 r4*f3+r2*f1
-
-			// accu1 += l2*f2+l0*f0 r2*f2+r0*f0
-			//       += l3*f3+l1*f1 r3*f3+r1*f1
-
-			// accu2 += l3*f2+l1*f0 r3*f2+r1*f0
-			//          l4*f3+l2*f1 r4*f3+r2*f1
-
-			pVfilter += 2;
-			pVsrc += 2;
-		}
-		// accu >>= resultDivFactor
-		accu1 = _mm_srai_pi32(accu1, resultDivFactor);
-		accu2 = _mm_srai_pi32(accu2, resultDivFactor);
-
-		// pack 2*2*32bits => 4*16 bits
-		pVdest[0] = _mm_packs_pi32(accu1, accu2);
-		src += 4;
-		++pVdest;
-	}
-
-	_m_empty(); // clear emms state
-
-	return (numSamples & 0xfffffffe) - this->length;
-}
-
-#endif // SOUNDTOUCH_ALLOW_MMX
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/sse_optimized.cpp
+++ /dev/null
@@ -1,336 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// SSE optimized routines for Pentium-III, Athlon-XP and later CPUs. All SSE
-/// optimized functions have been gathered into this single source
-/// code file, regardless to their class or original source code file, in order
-/// to ease porting the library to other compiler and processor platforms.
-///
-/// The SSE-optimizations are programmed using SSE compiler intrinsics that
-/// are supported both by Microsoft Visual C++ and GCC compilers, so this file
-/// should compile with both toolsets.
-///
-/// NOTICE: If using Visual Studio 6.0, you'll need to install the "Visual C++
-/// 6.0 processor pack" update to support SSE instruction set. The update is
-/// available for download at Microsoft Developers Network, see here:
-/// http://msdn.microsoft.com/en-us/vstudio/aa718349.aspx
-///
-/// If the above URL is expired or removed, go to "http://msdn.microsoft.com" and
-/// perform a search with keywords "processor pack".
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2012-11-08 16:53:01 -0200 (qui, 08 nov 2012) $
-// File revision : $Revision: 4 $
-//
-// $Id: sse_optimized.cpp 160 2012-11-08 18:53:01Z oparviai $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#include <cmath>
-#include "cpu_detect.h"
-#include "STTypes.h"
-
-using namespace soundtouch;
-
-#ifdef SOUNDTOUCH_ALLOW_SSE
-
-// SSE routines available only with float sample type
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// implementation of SSE optimized functions of class 'TDStretchSSE'
-//
-//////////////////////////////////////////////////////////////////////////////
-
-#include "TDStretch.h"
-#include <xmmintrin.h>
-
-// Calculates cross correlation of two buffers
-double TDStretchSSE::calcCrossCorr(const float *pV1, const float *pV2) const
-{
-	// Note. It means a major slow-down if the routine needs to tolerate
-	// unaligned __m128 memory accesses. It's way faster if we can skip
-	// unaligned slots and use _mm_load_ps instruction instead of _mm_loadu_ps.
-	// This can mean up to ~ 10-fold difference (incl. part of which is
-	// due to skipping every second round for stereo sound though).
-	//
-	// Compile-time define SOUNDTOUCH_ALLOW_NONEXACT_SIMD_OPTIMIZATION is provided
-	// for choosing if this little cheating is allowed.
-
-#ifdef SOUNDTOUCH_ALLOW_NONEXACT_SIMD_OPTIMIZATION
-	// Little cheating allowed, return valid correlation only for
-	// aligned locations, meaning every second round for stereo sound.
-
-	#define _MM_LOAD _mm_load_ps
-
-	if (reinterpret_cast<uintptr_t>(pV1) & 15)
-		return -1e50; // skip unaligned locations
-#else
-	// No cheating allowed, use unaligned load & take the resulting
-	// performance hit.
-	#define _MM_LOAD _mm_loadu_ps
-#endif
-
-	// ensure overlapLength is divisible by 8
-	assert(!(overlapLength % 8));
-
-	// Calculates the cross-correlation value between 'pV1' and 'pV2' vectors
-	// Note: pV2 _must_ be aligned to 16-bit boundary, pV1 need not.
-	const float *pVec1 = pV1;
-	const __m128 *pVec2 = reinterpret_cast<const __m128 *>(pV2);
-	__m128 vSum, vNorm;
-	vSum = vNorm = _mm_setzero_ps();
-
-	// Unroll the loop by factor of 4 * 4 operations. Use same routine for
-	// stereo & mono, for mono it just means twice the amount of unrolling.
-	for (int32_t i = 0; i < this->channels * this->overlapLength / 16; ++i)
-	{
-		// vSum += pV1[0..3] * pV2[0..3]
-		__m128 vTemp = _MM_LOAD(pVec1);
-		vSum = _mm_add_ps(vSum, _mm_mul_ps(vTemp, pVec2[0]));
-		vNorm = _mm_add_ps(vNorm, _mm_mul_ps(vTemp, vTemp));
-
-		// vSum += pV1[4..7] * pV2[4..7]
-		vTemp = _MM_LOAD(pVec1 + 4);
-		vSum = _mm_add_ps(vSum, _mm_mul_ps(vTemp, pVec2[1]));
-		vNorm = _mm_add_ps(vNorm, _mm_mul_ps(vTemp, vTemp));
-
-		// vSum += pV1[8..11] * pV2[8..11]
-		vTemp = _MM_LOAD(pVec1 + 8);
-		vSum = _mm_add_ps(vSum, _mm_mul_ps(vTemp, pVec2[2]));
-		vNorm = _mm_add_ps(vNorm, _mm_mul_ps(vTemp, vTemp));
-
-		// vSum += pV1[12..15] * pV2[12..15]
-		vTemp = _MM_LOAD(pVec1 + 12);
-		vSum = _mm_add_ps(vSum, _mm_mul_ps(vTemp, pVec2[3]));
-		vNorm = _mm_add_ps(vNorm, _mm_mul_ps(vTemp, vTemp));
-
-		pVec1 += 16;
-		pVec2 += 4;
-	}
-
-	// return value = vSum[0] + vSum[1] + vSum[2] + vSum[3]
-	float *pvNorm = reinterpret_cast<float *>(&vNorm);
-	double norm = std::sqrt(pvNorm[0] + pvNorm[1] + pvNorm[2] + pvNorm[3]);
-	if (norm < 1e-9)
-		norm = 1.0; // to avoid div by zero
-
-	float *pvSum = reinterpret_cast<float *>(&vSum);
-	return (pvSum[0] + pvSum[1] + pvSum[2] + pvSum[3]) / norm;
-
-	/* This is approximately corresponding routine in C-language:
-	double corr, norm;
-	uint32_t i;
-
-	// Calculates the cross-correlation value between 'pV1' and 'pV2' vectors
-	corr = norm = 0.0;
-	for (i = 0; i < channels * overlapLength / 16; i ++)
-	{
-		corr += pV1[0] * pV2[0] +
-				pV1[1] * pV2[1] +
-				pV1[2] * pV2[2] +
-				pV1[3] * pV2[3] +
-				pV1[4] * pV2[4] +
-				pV1[5] * pV2[5] +
-				pV1[6] * pV2[6] +
-				pV1[7] * pV2[7] +
-				pV1[8] * pV2[8] +
-				pV1[9] * pV2[9] +
-				pV1[10] * pV2[10] +
-				pV1[11] * pV2[11] +
-				pV1[12] * pV2[12] +
-				pV1[13] * pV2[13] +
-				pV1[14] * pV2[14] +
-				pV1[15] * pV2[15];
-
-		for (j = 0; j < 15; j ++) norm += pV1[j] * pV1[j];
-
-		pV1 += 16;
-		pV2 += 16;
-	}
-	return corr / sqrt(norm);*/
-}
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// implementation of SSE optimized functions of class 'FIRFilter'
-//
-//////////////////////////////////////////////////////////////////////////////
-
-#include "FIRFilter.h"
-
-FIRFilterSSE::FIRFilterSSE() : FIRFilter()
-{
-	this->filterCoeffsAlign = nullptr;
-	this->filterCoeffsUnalign.reset();
-}
-
-FIRFilterSSE::~FIRFilterSSE()
-{
-}
-
-// (overloaded) Calculates filter coefficients for SSE routine
-void FIRFilterSSE::setCoefficients(const float *coeffs, uint32_t newLength, uint32_t uResultDivFactor)
-{
-	FIRFilter::setCoefficients(coeffs, newLength, uResultDivFactor);
-
-	// Scale the filter coefficients so that it won't be necessary to scale the filtering result
-	// also rearrange coefficients suitably for SSE
-	// Ensure that filter coeffs array is aligned to 16-byte boundary
-	this->filterCoeffsUnalign.reset(new float[2 * newLength + 4]);
-	this->filterCoeffsAlign = reinterpret_cast<float *>(SOUNDTOUCH_ALIGN_POINTER_16(this->filterCoeffsUnalign.get()));
-
-	float fDivider = static_cast<float>(this->resultDivider);
-
-	// rearrange the filter coefficients for mmx routines
-	for (uint32_t i = 0; i < newLength; ++i)
-		this->filterCoeffsAlign[2 * i] = this->filterCoeffsAlign[2 * i + 1] = coeffs[i] / fDivider;
-}
-
-// SSE-optimized version of the filter routine for stereo sound
-uint32_t FIRFilterSSE::evaluateFilterStereo(float *dest, const float *source, uint32_t numSamples) const
-{
-	int count = static_cast<int>((numSamples - length) & static_cast<uint32_t>(-2));
-
-	assert(!(count % 2));
-
-	if (count < 2)
-		return 0;
-
-	assert(!!source);
-	assert(!!dest);
-	assert(!(length % 8));
-	assert(!!filterCoeffsAlign);
-	assert(!(reinterpret_cast<uintptr_t>(filterCoeffsAlign) % 16));
-
-	// filter is evaluated for two stereo samples with each iteration, thus use of 'j += 2'
-	for (int j = 0; j < count; j += 2)
-	{
-		const float *pSrc = source; // source audio data
-		const __m128 *pFil = reinterpret_cast<const __m128 *>(this->filterCoeffsAlign); // filter coefficients. NOTE: Assumes coefficients are aligned to 16-byte boundary
-		__m128 sum1, sum2;
-		sum1 = sum2 = _mm_setzero_ps();
-
-		for (uint32_t i = 0; i < length / 8; ++i)
-		{
-			// Unroll loop for efficiency & calculate filter for 2*2 stereo samples
-			// at each pass
-
-			// sum1 is accu for 2*2 filtered stereo sound data at the primary sound data offset
-			// sum2 is accu for 2*2 filtered stereo sound data for the next sound sample offset.
-
-			sum1 = _mm_add_ps(sum1, _mm_mul_ps(_mm_loadu_ps(pSrc), pFil[0]));
-			sum2 = _mm_add_ps(sum2, _mm_mul_ps(_mm_loadu_ps(pSrc + 2), pFil[0]));
-
-			sum1 = _mm_add_ps(sum1, _mm_mul_ps(_mm_loadu_ps(pSrc + 4), pFil[1]));
-			sum2 = _mm_add_ps(sum2, _mm_mul_ps(_mm_loadu_ps(pSrc + 6), pFil[1]));
-
-			sum1 = _mm_add_ps(sum1, _mm_mul_ps(_mm_loadu_ps(pSrc + 8) ,  pFil[2]));
-			sum2 = _mm_add_ps(sum2, _mm_mul_ps(_mm_loadu_ps(pSrc + 10), pFil[2]));
-
-			sum1 = _mm_add_ps(sum1, _mm_mul_ps(_mm_loadu_ps(pSrc + 12), pFil[3]));
-			sum2 = _mm_add_ps(sum2, _mm_mul_ps(_mm_loadu_ps(pSrc + 14), pFil[3]));
-
-			pSrc += 16;
-			pFil += 4;
-		}
-
-		// Now sum1 and sum2 both have a filtered 2-channel sample each, but we still need
-		// to sum the two hi- and lo-floats of these registers together.
-
-		// post-shuffle & add the filtered values and store to dest.
-		_mm_storeu_ps(dest, _mm_add_ps(
-			_mm_shuffle_ps(sum1, sum2, _MM_SHUFFLE(1,0,3,2)),   // s2_1 s2_0 s1_3 s1_2
-			_mm_shuffle_ps(sum1, sum2, _MM_SHUFFLE(3,2,1,0))    // s2_3 s2_2 s1_1 s1_0
-		));
-		source += 4;
-		dest += 4;
-	}
-
-	// Ideas for further improvement:
-	// 1. If it could be guaranteed that 'source' were always aligned to 16-byte
-	//    boundary, a faster aligned '_mm_load_ps' instruction could be used.
-	// 2. If it could be guaranteed that 'dest' were always aligned to 16-byte
-	//    boundary, a faster '_mm_store_ps' instruction could be used.
-
-	return count;
-
-	/* original routine in C-language. please notice the C-version has differently
-	   organized coefficients though.
-	double suml1, suml2;
-	double sumr1, sumr2;
-	uint32_t i, j;
-
-	for (j = 0; j < count; j += 2)
-	{
-		const float *ptr;
-		const float *pFil;
-
-		suml1 = sumr1 = 0.0;
-		suml2 = sumr2 = 0.0;
-		ptr = src;
-		pFil = filterCoeffs;
-		for (i = 0; i < lengthLocal; i ++)
-		{
-			// unroll loop for efficiency.
-
-			suml1 += ptr[0] * pFil[0] +
-						ptr[2] * pFil[2] +
-						ptr[4] * pFil[4] +
-						ptr[6] * pFil[6];
-
-			sumr1 += ptr[1] * pFil[1] +
-						ptr[3] * pFil[3] +
-						ptr[5] * pFil[5] +
-						ptr[7] * pFil[7];
-
-			suml2 += ptr[8] * pFil[0] +
-						ptr[10] * pFil[2] +
-						ptr[12] * pFil[4] +
-						ptr[14] * pFil[6];
-
-			sumr2 += ptr[9] * pFil[1] +
-						ptr[11] * pFil[3] +
-						ptr[13] * pFil[5] +
-						ptr[15] * pFil[7];
-
-			ptr += 16;
-			pFil += 8;
-		}
-		dest[0] = (float)suml1;
-		dest[1] = (float)sumr1;
-		dest[2] = (float)suml2;
-		dest[3] = (float)sumr2;
-
-		src += 4;
-		dest += 4;
-	}*/
-}
-
-#endif  // SOUNDTOUCH_ALLOW_SSE
-

--- a/src/in_2sf/desmume/metaspu/Timestretcher.cpp
+++ /dev/null
@@ -1,316 +1,1 @@
-/* SPU2-X, A plugin for Emulating the Sound Processing Unit of the Playstation 2
-* Developed and maintained by the Pcsx2 Development Team.
-*
-* Original portions from SPU2ghz are (c) 2008 by David Quintana [gigaherz]
-*
-* SPU2-X is free software: you can redistribute it and/or modify it under the terms
-* of the GNU Lesser General Public License as published by the Free Software Found-
-* ation, either version 3 of the License, or (at your option) any later version.
-*
-* SPU2-X is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
-* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
-* PURPOSE.  See the GNU Lesser General Public License for more details.
-*
-* You should have received a copy of the GNU Lesser General Public License
-* along with SPU2-X.  If not, see <http://www.gnu.org/licenses/>.
-*/
 
-#include "XSFCommon.h"
-
-#include "../types.h"
-#include "SoundTouch/SoundTouch.h"
-#include "SndOut.h"
-
-static std::unique_ptr<soundtouch::SoundTouch> pSoundTouch;
-static int ts_stats_stretchblocks = 0;
-static int ts_stats_normalblocks = 0;
-static int ts_stats_logcounter = 0;
-
-// data prediction amount, used to "commit" data that hasn't
-// finished timestretch processing.
-int32_t SndBuffer::m_predictData;
-
-// records last buffer status (fill %, range -100 to 100, with 0 being 50% full)
-float SndBuffer::lastPct;
-float SndBuffer::lastEmergencyAdj;
-
-float SndBuffer::cTempo = 1;
-float SndBuffer::eTempo = 1;
-int SndBuffer::freezeTempo = 0;
-
-void SndBuffer::PredictDataWrite(int samples)
-{
-	m_predictData += samples;
-}
-
-// Calculate the buffer status percentage.
-// Returns range from -1.0 to 1.0
-//    1.0 = buffer overflow!
-//    0.0 = buffer nominal (50% full)
-//   -1.0 = buffer underflow!
-float SndBuffer::GetStatusPct()
-{
-	// Get the buffer status of the output driver too, so that we can
-	// obtain a more accurate overall buffer status.
-
-	int drvempty = 0;
-	//int drvempty = mods[OutputModule]->GetEmptySampleCount(); // / 2;
-	//TODO
-
-	//ConLog( "Data %d >>> driver: %d   predict: %d\n", data, drvempty, predictData );
-
-	float result = static_cast<float>(m_data + m_predictData - drvempty) - (m_size / 2);
-	result /= m_size / 2;
-	return result;
-}
-
-void SndBuffer::UpdateTempoChange()
-{
-	if (--freezeTempo > 0)
-		return;
-
-	float statusPct = GetStatusPct();
-	float pctChange = statusPct - lastPct;
-
-	float tempoChange;
-	float emergencyAdj = 0;
-	float newcee = cTempo; // workspace var. for cTempo
-
-	// IMPORTANT!
-	// If you plan to tweak these values, make sure you're using a release build
-	// OUTSIDE THE DEBUGGER to test it!  The Visual Studio debugger can really cause
-	// erratic behavior in the audio buffers, and makes the timestretcher seem a
-	// lot more inconsistent than it really is.
-
-	// We have two factors.
-	//   * Distance from nominal buffer status (50% full)
-	//   * The change from previous update to this update.
-
-	// Prediction based on the buffer change:
-	// (linear seems to work better here)
-
-	tempoChange = pctChange * 0.75f;
-
-	if (statusPct * tempoChange < 0.0f)
-		// only apply tempo change if it is in synch with the buffer status.
-		// In other words, if the buffer is high (over 0%), and is decreasing,
-		// ignore it.  It'll just muck things up.
-
-		tempoChange = 0;
-
-	// Sudden spikes in framerate can cause the nominal buffer status
-	// to go critical, in which case we have to enact an emergency
-	// stretch. The following cubic formulas do that.  Values near
-	// the extremeites give much larger results than those near 0.
-	// And the value is added only this time, and does not accumulate.
-	// (otherwise a large value like this would cause problems down the road)
-
-	// Constants:
-	// Weight - weights the statusPct's "emergency" consideration.
-	//   higher values here will make the buffer perform more drastic
-	//   compensations at the outer edges of the buffer (at -75 or +75%
-	//   or beyond, for example).
-
-	// Range - scales the adjustment to the given range (more or less).
-	//   The actual range is dependent on the weight used, so if you increase
-	//   Weight you'll usually want to decrease Range somewhat to compensate.
-
-	// Prediction based on the buffer fill status:
-
-	float statusWeight = 2.99f;
-	float statusRange = 0.068f;
-
-	// "non-emergency" deadzone:  In this area stretching will be strongly discouraged.
-	// Note: due tot he nature of timestretch latency, it's always a wee bit harder to
-	// cope with low fps (underruns) than it is high fps (overruns).  So to help out a
-	// little, the low-end portions of this check are less forgiving than the high-sides.
-
-	if (cTempo < 0.965f || cTempo > 1.060f || pctChange < -0.38f || pctChange > 0.54f || statusPct < -0.32f || statusPct > 0.39f || eTempo < 0.89f || eTempo > 1.19f)
-		emergencyAdj = std::pow(statusPct * statusWeight, 3.0f) * statusRange;
-
-	// Smooth things out by factoring our previous adjustment into this one.
-	// It helps make the system 'feel' a little smarter by  giving it at least
-	// one packet worth of history to help work off of:
-
-	emergencyAdj = (emergencyAdj * 0.75f) + (lastEmergencyAdj * 0.25f);
-
-	lastEmergencyAdj = emergencyAdj;
-	lastPct = statusPct;
-
-	// Accumulate a fraction of the tempo change into the tempo itself.
-	// This helps the system run "smarter" to games that run consistently
-	// fast or slow by altering the base tempo to something closer to the
-	// game's active speed.  In tests most games normalize within 2 seconds
-	// at 100ms latency, which is pretty good (larger buffers normalize even
-	// quicker).
-
-	newcee += newcee * (tempoChange + emergencyAdj) * 0.03f;
-
-	// Apply tempoChange as a scale of cTempo.  That way the effect is proportional
-	// to the current tempo.  (otherwise tempos rate of change at the extremes would
-	// be too drastic)
-
-	float newTempo = newcee + (emergencyAdj * cTempo);
-
-	// ... and as a final optimization, only stretch if the new tempo is outside
-	// a nominal threshold.  Keep this threshold check small, because it could
-	// cause some serious side effects otherwise. (enlarging the cTempo check above
-	// is usually better/safer)
-	if (newTempo < 0.970f || newTempo > 1.045f)
-	{
-		cTempo = newcee;
-
-		if (newTempo < 0.10f)
-			newTempo = 0.10f;
-		else if (newTempo > 10.0f)
-			newTempo = 10.0f;
-
-		if (cTempo < 0.15f)
-			cTempo = 0.15f;
-		else if (cTempo > 7.5f)
-			cTempo = 7.5f;
-
-		pSoundTouch->setTempo(eTempo = newTempo);
-		++ts_stats_stretchblocks;
-
-		/*ConLog(" * SPU2: [Nominal %d%%] [Emergency: %d%%] (baseTempo: %d%% ) (newTempo: %d%%) (buffer: %d%%)\n",
-			//(relation < 0.0) ? "Normalize" : "",
-			(int)(tempoChange * 100.0 * 0.03),
-			(int)(emergencyAdj * 100.0),
-			(int)(cTempo * 100.0),
-			(int)(newTempo * 100.0),
-			(int)(statusPct * 100.0)
-		);*/
-	}
-	else
-	{
-		// Nominal operation -- turn off stretching.
-		// note: eTempo 'slides' toward 1.0 for smoother audio and better
-		// protection against spikes.
-		if (!fEqual(cTempo, 1.0f))
-		{
-			cTempo = 1.0f;
-			eTempo = (1.0f + eTempo) * 0.5f;
-			pSoundTouch->setTempo(eTempo);
-		}
-		else
-		{
-			if (!fEqual(eTempo, cTempo))
-				pSoundTouch->setTempo(eTempo = cTempo);
-			++ts_stats_normalblocks;
-		}
-	}
-}
-
-void SndBuffer::timeStretchUnderrun()
-{
-	// timeStretcher failed it's job.  We need to slow down the audio some.
-
-	cTempo -= cTempo * 0.12f;
-	eTempo -= eTempo * 0.30f;
-	if (eTempo < 0.1f)
-		eTempo = 0.1f;
-	pSoundTouch->setTempo(eTempo);
-}
-
-int32_t SndBuffer::timeStretchOverrun()
-{
-	// If we overran it means the timestretcher failed.  We need to speed
-	// up audio playback.
-	cTempo += cTempo * 0.12f;
-	eTempo += eTempo * 0.40f;
-	if (eTempo > 7.5f)
-		eTempo = 7.5f;
-	pSoundTouch->setTempo(eTempo);
-
-	// Throw out just a little bit (two packets worth) to help
-	// give the TS some room to work:
-
-	return SndOutPacketSize * 2;
-}
-
-static void CvtPacketToFloat(StereoOut32 *srcdest)
-{
-	StereoOutFloat *dest = reinterpret_cast<StereoOutFloat *>(srcdest);
-	const StereoOut32 *src = srcdest;
-	for (int i = 0; i < SndOutPacketSize; ++i, ++dest, ++src)
-		*dest = static_cast<StereoOutFloat>(*src);
-}
-
-// Parameter note: Size should always be a multiple of 128, thanks!
-static void CvtPacketToInt(StereoOut32 *srcdest, uint32_t size)
-{
-	//jASSUME( (size & 127) == 0 );
-
-	const StereoOutFloat *src = reinterpret_cast<StereoOutFloat *>(srcdest);
-	StereoOut32 *dest = srcdest;
-
-	for (uint32_t i = 0; i < size; ++i, ++dest, ++src)
-		*dest = static_cast<StereoOut32>(*src);
-}
-
-void SndBuffer::timeStretchWrite()
-{
-	bool progress = false;
-
-	// data prediction helps keep the tempo adjustments more accurate.
-	// The timestretcher returns packets in belated "clump" form.
-	// Meaning that most of the time we'll get nothing back, and then
-	// suddenly we'll get several chunks back at once.  Thus we use
-	// data prediction to make the timestretcher more responsive.
-
-	PredictDataWrite(SndOutPacketSize / eTempo);
-	CvtPacketToFloat(sndTempBuffer.get());
-
-	pSoundTouch->putSamples(reinterpret_cast<float *>(sndTempBuffer.get()), SndOutPacketSize);
-
-	int tempProgress;
-	while (tempProgress = pSoundTouch->receiveSamples(reinterpret_cast<float *>(sndTempBuffer.get()), SndOutPacketSize), !!tempProgress)
-	{
-		// Hint: It's assumed that pSoundTouch will return chunks of 128 bytes (it always does as
-		// long as the SSE optimizations are enabled), which means we can do our own SSE opts here.
-
-		CvtPacketToInt(sndTempBuffer.get(), tempProgress);
-		_WriteSamples(sndTempBuffer.get(), tempProgress);
-		progress = true;
-	}
-
-	UpdateTempoChange();
-
-	//TODO
-	//if( MsgOverruns() )
-	{
-		if(progress)
-		{
-			if (++ts_stats_logcounter > 300)
-			{
-				ts_stats_logcounter = 0;
-				printf(" * SPU2 > Timestretch Stats > %d%% of packets stretched.\n", (ts_stats_stretchblocks * 100) / (ts_stats_normalblocks + ts_stats_stretchblocks));
-				ts_stats_normalblocks = ts_stats_stretchblocks = 0;
-			}
-		}
-	}
-}
-
-void SndBuffer::soundtouchInit()
-{
-	pSoundTouch.reset(new soundtouch::SoundTouch());
-	pSoundTouch->setSampleRate(SampleRate);
-	pSoundTouch->setChannels(2);
-
-	pSoundTouch->setSetting(soundtouch::SETTING_USE_QUICKSEEK, 0);
-	pSoundTouch->setSetting(soundtouch::SETTING_USE_AA_FILTER, 0);
-
-	pSoundTouch->setTempo(1);
-
-	// some timestretch management vars:
-
-	cTempo = eTempo = 1.0;
-	lastPct = lastEmergencyAdj = 0;
-
-	// just freeze tempo changes for a while at startup.
-	// the driver buffers are bogus anyway.
-	freezeTempo = 16;
-	m_predictData = 0;
-}
-

--- a/src/in_2sf/desmume/metaspu/metaspu.cpp
+++ b/src/in_2sf/desmume/metaspu/metaspu.cpp
@@ -1,4 +1,4 @@
-/*  Copyright 2009 DeSmuME team
+/*  Copyright 2009-2015 DeSmuME team
 
     This file is part of DeSmuME
 
@@ -17,475 +17,42 @@
     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 */
 
+#include "metaspu.h"
+
 #include <queue>
 #include <vector>
-#include <cmath>
-#include "../types.h"
-#include "metaspu.h"
+#include <list>
+#include <cstring>
+#include <assert.h>
 
-//for pcsx2 method
-//(havent bothered to get it compiling in gcc yet)
-#ifdef _MSC_VER
-#include "SndOut.h"
-#endif
-
-class ZeromusSynchronizer : public ISynchronizingAudioBuffer
+class NullSynchronizer : public ISynchronizingAudioBuffer
 {
 public:
-	ZeromusSynchronizer() : mixqueue_go(false),
-#ifdef NDEBUG
-		adjustobuf(200, 1000)
-#else
-		adjustobuf(22000, 44000)
-#endif
-	{
-	}
+  std::queue<uint32_t> buffer;
+  NullSynchronizer() {}
 
-	bool mixqueue_go;
+	virtual void enqueue_samples(s16* buf, int samples_provided) {
+    for (int i = 0; i < samples_provided * 2; i += 2) {
+      uint16_t left = buf[i];
+      uint16_t right = buf[i + 1];
+      buffer.push(left << 16 | right);
+    }
+  }
 
-	virtual void enqueue_samples(int16_t *buf, int samples_provided)
-	{
-		for (int i = 0; i < samples_provided; ++i)
-		{
-			int16_t left = *buf++;
-			int16_t right = *buf++;
-			this->adjustobuf.enqueue(left, right);
-		}
-	}
-
-	// returns the number of samples actually supplied, which may not match the number requested
-	virtual int output_samples(int16_t *buf, int samples_requested)
-	{
-		int done = 0;
-		if (!this->mixqueue_go)
-		{
-			if (this->adjustobuf.size > 200)
-				this->mixqueue_go = true;
-		}
-		else
-		{
-			for (int i = 0; i < samples_requested; ++i)
-			{
-				if (!this->adjustobuf.size)
-				{
-					this->mixqueue_go = false;
-					break;
-				}
-				++done;
-				int16_t left, right;
-				this->adjustobuf.dequeue(left, right);
-				*buf++ = left;
-				*buf++ = right;
-			}
-		}
-
-		return done;
-	}
-
-private:
-	class Adjustobuf
-	{
-	public:
-		Adjustobuf(int _minLatency, int _maxLatency) : minLatency(_minLatency), maxLatency(_maxLatency), size(0)
-		{
-			this->rollingTotalSize = 0;
-			this->targetLatency = (this->maxLatency + this->minLatency) / 2;
-			this->rate = 1.0f;
-			this->cursor = 0.0f;
-			this->curr[0] = this->curr[1] = 0;
-			this->kAverageSize = 80000;
-		}
-
-		float rate, cursor;
-		int minLatency, targetLatency, maxLatency;
-		std::queue<int16_t> buffer;
-		int size;
-		int16_t curr[2];
-
-		std::queue<int> statsHistory;
-
-		void enqueue(int16_t left, int16_t right)
-		{
-			this->buffer.push(left);
-			this->buffer.push(right);
-			++this->size;
-		}
-
-		int64_t rollingTotalSize;
-
-		uint32_t kAverageSize;
-
-		void addStatistic()
-		{
-			this->statsHistory.push(this->size);
-			this->rollingTotalSize += this->size;
-			if (this->statsHistory.size() > this->kAverageSize)
-			{
-				this->rollingTotalSize -= this->statsHistory.front();
-				this->statsHistory.pop();
-
-				float averageSize = rollingTotalSize / kAverageSize;
-				//static int ctr=0;  ctr++; if((ctr&127)==0) printf("avg size: %f curr size: %d rate: %f\n",averageSize,size,rate);
-				{
-					float targetRate;
-					if (averageSize < this->targetLatency)
-						targetRate = 1.0f - (this->targetLatency - averageSize) / this->kAverageSize;
-					else if (averageSize > this->targetLatency)
-						targetRate = 1.0f + (averageSize - this->targetLatency) / this->kAverageSize;
-					else
-						targetRate = 1.0f;
-
-					//rate = moveValueTowards(rate,targetRate,0.001f);
-					this->rate = targetRate;
-				}
-			}
-		}
-
-		void dequeue(int16_t &left, int16_t &right)
-		{
-			left = right = 0;
-			this->addStatistic();
-			if (!this->size)
-				return;
-			this->cursor += this->rate;
-			while (this->cursor > 1.0f)
-			{
-				this->cursor -= 1.0f;
-				if (this->size > 0)
-				{
-					this->curr[0] = this->buffer.front();
-					this->buffer.pop();
-					this->curr[1] = this->buffer.front();
-					this->buffer.pop();
-					--this->size;
-				}
-			}
-			left = this->curr[0];
-			right = this->curr[1];
-		}
-	} adjustobuf;
+	virtual int output_samples(s16* buf, int samples_requested) {
+    int samples = ((samples_requested < buffer.size()) ? samples_requested : buffer.size()) & ~1;
+    for (int offset = 0, i = 0; i < samples; i++) {
+      uint32_t sample = buffer.front();
+      buffer.pop();
+      buf[offset++] = (sample >> 16) & 0xFFFF;
+      buf[offset++] = sample & 0xFFFF;
+    }
+    return samples;
+  }
 };
 
-class NitsujaSynchronizer : public ISynchronizingAudioBuffer
+ISynchronizingAudioBuffer* metaspu_construct(ESynchMethod method)
 {
-private:
-	struct ssamp
-	{
-		int16_t l, r;
-		ssamp() { }
-		ssamp(int16_t ll, int16_t rr) : l(ll), r(rr) { }
-	};
-
-	std::vector<ssamp> sampleQueue;
-
-	// returns values going between 0 and y-1 in a saw wave pattern, based on x
-	static int pingpong(int x, int y)
-	{
-		x %= 2 * y;
-		if (x >= y)
-			x = 2 * y - x - 1;
-		return x;
-
-		// in case we want to switch to odd buffer sizes for more sharpness
-		//x %= 2*(y-1);
-		//if(x >= y)
-		//	x = 2*(y-1) - x;
-		//return x;
-	}
-
-	static ssamp crossfade(const ssamp &lhs, const ssamp &rhs, int cur, int start, int end)
-	{
-		if (cur <= start)
-			return lhs;
-		if (cur >= end)
-			return rhs;
-
-		// in case we want sine wave interpolation instead of linear here
-		//float ang = 3.14159f * (float)(cur - start) / (float)(end - start);
-		//cur = start + (int)((1-cosf(ang))*0.5f * (end - start));
-
-		int inNum = cur - start;
-		int outNum = end - cur;
-		int denom = end - start;
-
-		int lrv = (lhs.l * outNum + rhs.l * inNum) / denom;
-		int rrv = (lhs.r * outNum + rhs.r * inNum) / denom;
-
-		return ssamp(lrv, rrv);
-	}
-
-	static void emit_sample(int16_t *&outbuf, const ssamp &sample)
-	{
-		*outbuf++ = sample.l;
-		*outbuf++ = sample.r;
-	}
-
-	static void emit_samples(int16_t *&outbuf, const ssamp *samplebuf, int samples)
-	{
-		for (int i = 0; i < samples; ++i)
-			NitsujaSynchronizer::emit_sample(outbuf, samplebuf[i]);
-	}
-
-public:
-	NitsujaSynchronizer() { }
-
-	virtual void enqueue_samples(int16_t *buf, int samples_provided)
-	{
-		for (int i = 0; i < samples_provided; ++i)
-		{
-			this->sampleQueue.push_back(ssamp(buf[0], buf[1]));
-			buf += 2;
-		}
-	}
-
-	virtual int output_samples(int16_t *buf, int samples_requested)
-	{
-		int audiosize = samples_requested;
-		int queued = this->sampleQueue.size();
-
-		// I am too lazy to deal with odd numbers
-		audiosize &= ~1;
-		queued &= ~1;
-
-		if (queued > 0x200 && audiosize > 0) // is there any work to do?
-		{
-			// are we going at normal speed?
-			// or more precisely, are the input and output queues/buffers of similar size?
-			if (queued > 900 || audiosize > queued * 2)
-			{
-				// not normal speed. we have to resample it somehow in this case.
-				if (audiosize <= queued)
-				{
-					// fast forward speed
-					// this is the easy case, just crossfade it and it sounds ok
-					for (int i = 0; i < audiosize; ++i)
-					{
-						int j = i + queued - audiosize;
-						ssamp outsamp = this->crossfade(this->sampleQueue[i], this->sampleQueue[j], i, 0, audiosize);
-						this->emit_sample(buf, outsamp);
-					}
-				}
-				else
-				{
-					// slow motion speed
-					// here we take a very different approach,
-					// instead of crossfading it, we select a single sample from the queue
-					// and make sure that the index we use to select a sample is constantly moving
-					// and that it starts at the first sample in the queue and ends on the last one.
-					//
-					// hopefully the index doesn't move discontinuously or we'll get slight crackling
-					// (there might still be a minor bug here that causes this occasionally)
-					//
-					// here's a diagram of how the index we sample from moves:
-					//
-					// queued (this axis represents the index we sample from. the top means the end of the queue)
-					// ^
-					// |   --> audiosize (this axis represents the output index we write to, right meaning forward in output time/position)
-					// |   A           C       C  end
-					//    A A     B   C C     C
-					//   A   A   A B C   C   C
-					//  A     A A   B     C C
-					// A       A           C
-					// start
-					//
-					// yes, this means we are spending some stretches of time playing the sound backwards,
-					// but the stretches are short enough that this doesn't sound weird.
-					// this lets us avoid most crackling problems due to the endpoints matching up.
-
-					// first calculate a shorter-than-full window
-					// that has minimal slope at the endpoints
-					// (to further reduce crackling, especially in sine waves)
-					int beststart = 0, extraAtEnd = 0;
-					{
-						int bestend = queued;
-						static const int worstdiff = 99999999;
-						int beststartdiff = worstdiff;
-						int bestenddiff = worstdiff;
-						for(int i = 0; i < 128; i += 2)
-						{
-							int diff = std::abs(this->sampleQueue[i].l - this->sampleQueue[i + 1].l) + std::abs(this->sampleQueue[i].r - this->sampleQueue[i + 1].r);
-							if (diff < beststartdiff)
-							{
-								beststartdiff = diff;
-								beststart = i;
-							}
-						}
-						for (int i = queued - 3; i > queued - 3 - 128; i -= 2)
-						{
-							int diff = std::abs(this->sampleQueue[i].l - this->sampleQueue[i + 1].l) + std::abs(this->sampleQueue[i].r - this->sampleQueue[i + 1].r);
-							if (diff < bestenddiff)
-							{
-								bestenddiff = diff;
-								bestend = i+1;
-							}
-						}
-
-						extraAtEnd = queued - bestend;
-						queued = bestend - beststart;
-
-						int oksize = queued;
-						while (oksize + queued * 2 + beststart + extraAtEnd <= samples_requested)
-							oksize += queued * 2;
-						audiosize = oksize;
-
-						for (int x = 0; x < beststart; ++x)
-							this->emit_sample(buf, this->sampleQueue[x]);
-						this->sampleQueue.erase(this->sampleQueue.begin(), this->sampleQueue.begin() + beststart);
-					}
-
-					int midpointX = audiosize >> 1;
-					int midpointY = queued >> 1;
-
-					// all we need to do here is calculate the X position of the leftmost "B" in the above diagram.
-					// TODO: we should calculate it with a simple equation like
-					//   midpointXOffset = min(something,somethingElse);
-					// but it's a little difficult to work it out exactly
-					// so here's a stupid search for the value for now:
-
-					int prevA = 999999;
-					int midpointXOffset = queued / 2;
-					while (true)
-					{
-						int a = std::abs(this->pingpong(midpointX - midpointXOffset, queued) - midpointY) - midpointXOffset;
-						if (((a > 0) != (prevA > 0) || (a < 0) != (prevA < 0)) && prevA != 999999)
-						{
-							if ((a + prevA) & 1) // there's some sort of off-by-one problem with this search since we're moving diagonally...
-								++midpointXOffset; // but this fixes it most of the time...
-							break; // found it
-						}
-						prevA = a;
-						--midpointXOffset;
-						if (midpointXOffset < 0)
-						{
-							midpointXOffset = 0;
-							break; // failed to find it. the two sides probably meet exactly in the center.
-						}
-					}
-
-					int leftMidpointX = midpointX - midpointXOffset;
-					int rightMidpointX = midpointX + midpointXOffset;
-					int leftMidpointY = pingpong(leftMidpointX, queued);
-					int rightMidpointY = (queued - 1) - this->pingpong(audiosize - 1 - rightMidpointX + queued * 2, queued);
-
-					// output the left almost-half of the sound (section "A")
-					for (int x = 0; x < leftMidpointX; ++x)
-					{
-						int i = this->pingpong(x, queued);
-						this->emit_sample(buf, this->sampleQueue[i]);
-					}
-
-					// output the middle stretch (section "B")
-					int y = leftMidpointY;
-					int dyMidLeft = leftMidpointY < midpointY ? 1 : -1;
-					int dyMidRight = rightMidpointY > midpointY ? 1 : -1;
-					for (int x = leftMidpointX; x < midpointX; ++x, y += dyMidLeft)
-						this->emit_sample(buf, this->sampleQueue[y]);
-					for (int x = midpointX; x < rightMidpointX; ++x, y += dyMidRight)
-						this->emit_sample(buf, this->sampleQueue[y]);
-
-					// output the end of the queued sound (section "C")
-					for (int x = rightMidpointX; x < audiosize; ++x)
-					{
-						int i = (queued - 1) - this->pingpong(audiosize - 1 - x + queued * 2, queued);
-						this->emit_sample(buf, sampleQueue[i]);
-					}
-
-					for (int x = 0; x < extraAtEnd; ++x)
-					{
-						int i = queued + x;
-						this->emit_sample(buf, this->sampleQueue[i]);
-					}
-					queued += extraAtEnd;
-					audiosize += beststart + extraAtEnd;
-				} //end else
-
-				this->sampleQueue.erase(this->sampleQueue.begin(), this->sampleQueue.begin() + queued);
-				return audiosize;
-			}
-			else
-			{
-				// normal speed
-				// just output the samples straightforwardly.
-				//
-				// at almost-full speeds (like 50/60 FPS)
-				// what will happen is that we rapidly fluctuate between entering this branch
-				// and entering the "slow motion speed" branch above.
-				// but that's ok! because all of these branches sound similar enough that we can get away with it.
-				// so the two cases actually complement each other.
-
-				if (audiosize >= queued)
-				{
-					this->emit_samples(buf, &this->sampleQueue[0], queued);
-					this->sampleQueue.erase(this->sampleQueue.begin(), this->sampleQueue.begin() + queued);
-					return queued;
-				}
-				else
-				{
-					this->emit_samples(buf, &this->sampleQueue[0], audiosize);
-					this->sampleQueue.erase(this->sampleQueue.begin(), this->sampleQueue.begin() + audiosize);
-					return audiosize;
-				}
-			} //end normal speed
-		} //end if there is any work to do
-		else
-			return 0;
-	} //output_samples
-}; //NitsujaSynchronizer
-
-#ifdef _MSC_VER
-class PCSX2Synchronizer : public ISynchronizingAudioBuffer
-{
-public:
-	std::queue<int16_t> readySamples;
-	PCSX2Synchronizer()
-	{
-		SndBuffer::Init();
-	}
-	virtual void enqueue_samples(int16_t *buf, int samples_provided)
-	{
-		for (int i = 0; i < samples_provided; ++i)
-		{
-			auto so32 = StereoOut32(buf[0], buf[1]);
-			SndBuffer::Write(so32);
-			buf += 2;
-		}
-	}
-
-	virtual int output_samples(int16_t *buf, int samples_requested)
-	{
-		for (int i = 0; i < samples_requested; ++i)
-		{
-			if (!this->readySamples.size())
-			{
-				//SndOutPacketSize
-				StereoOut16 temp[SndOutPacketSize * 2];
-				SndBuffer::ReadSamples(temp);
-				for (int i = 0; i < SndOutPacketSize; ++i)
-				{
-					this->readySamples.push(temp[i].Left);
-					this->readySamples.push(temp[i].Right);
-				}
-			}
-			*buf++ = this->readySamples.front();
-			this->readySamples.pop();
-			*buf++ = this->readySamples.front();
-			this->readySamples.pop();
-		}
-		return samples_requested;
-	}
-};
-#endif
-
-ISynchronizingAudioBuffer *metaspu_construct(ESynchMethod method)
-{
-	switch(method)
-	{
-		case ESynchMethod_N: return new NitsujaSynchronizer();
-		case ESynchMethod_Z: return new ZeromusSynchronizer();
-#ifdef _MSC_VER
-		case ESynchMethod_P: return new PCSX2Synchronizer();
-#endif
-		default: return nullptr;
-	}
+	return new NullSynchronizer();
 }
 

--- a/src/in_2sf/desmume/metaspu/metaspu.h
+++ b/src/in_2sf/desmume/metaspu/metaspu.h
@@ -1,52 +1,53 @@
-/*  Copyright 2009-2010 DeSmuME team
+/*  Copyright 2009-2015 DeSmuME team

+

+	This file is free software: you can redistribute it and/or modify

+	it under the terms of the GNU General Public License as published by

+	the Free Software Foundation, either version 2 of the License, or

+	(at your option) any later version.

+

+	This file is distributed in the hope that it will be useful,

+	but WITHOUT ANY WARRANTY; without even the implied warranty of

+	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the

+	GNU General Public License for more details.

+

+	You should have received a copy of the GNU General Public License

+	along with the this software.  If not, see <http://www.gnu.org/licenses/>.

+*/

+

+//-------------------------

+//this file contains the METASPU system

+//which is designed to handle the task of audio synchronization

+//and is designed to be as portable between multiple emulators

+//-------------------------

+

+

+#ifndef _METASPU_H_

+#define _METASPU_H_

+

+#include <algorithm>

+

+#include "types.h"

+

+class ISynchronizingAudioBuffer

+{

+public:

+	virtual void enqueue_samples(s16* buf, int samples_provided) = 0;

+

+	//returns the number of samples actually supplied, which may not match the number requested

+	virtual int output_samples(s16* buf, int samples_requested) = 0;

+};

+

+enum ESynchMode

+{

+	ESynchMode_Synchronous

+};

+

+enum ESynchMethod

+{

+	ESynchMethod_0, //Null

+};

+

+ISynchronizingAudioBuffer* metaspu_construct(ESynchMethod method);

+

+#endif

 
-	This file is free software: you can redistribute it and/or modify
-	it under the terms of the GNU General Public License as published by
-	the Free Software Foundation, either version 2 of the License, or
-	(at your option) any later version.
-
-	This file is distributed in the hope that it will be useful,
-	but WITHOUT ANY WARRANTY; without even the implied warranty of
-	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-	GNU General Public License for more details.
-
-	You should have received a copy of the GNU General Public License
-	along with the this software.  If not, see <http://www.gnu.org/licenses/>.
-*/
-
-// -------------------------
-// this file contains the METASPU system
-// which is designed to handle the task of audio synchronization
-// and is designed to be as portable between multiple emulators
-// -------------------------
-
-#pragma once
-
-#include "../types.h"
-
-class ISynchronizingAudioBuffer
-{
-public:
-	virtual ~ISynchronizingAudioBuffer() { }
-
-	virtual void enqueue_samples(int16_t *buf, int samples_provided) = 0;
-
-	// returns the number of samples actually supplied, which may not match the number requested
-	virtual int output_samples(int16_t *buf, int samples_requested) = 0;
-};
-
-enum ESynchMode
-{
-	ESynchMode_DualSynchAsynch,
-	ESynchMode_Synchronous
-};
-
-enum ESynchMethod
-{
-	ESynchMethod_N, // nitsuja's
-	ESynchMethod_Z, // zero's
-	ESynchMethod_P // PCSX2 spu2-x
-};
-
-ISynchronizingAudioBuffer *metaspu_construct(ESynchMethod method);
-

--- a/src/in_2sf/desmume/thumb_instructions.cpp
+++ b/src/in_2sf/desmume/thumb_instructions.cpp
@@ -928,7 +928,7 @@
 	// ------	* If <Rn> is the lowest-numbered register specified in <registers>, the original value of <Rn> is stored.
 	// ------	* Otherwise, the stored value of <Rn> is UNPREDICTABLE.
 	if (BIT_N(i, REG_NUM(i, 8)))
-		printf("STMIA with Rb in Rlist\n");
+		fprintf(stderr, "STMIA with Rb in Rlist\n");
 
 	for (uint32_t j = 0; j < 8; ++j)
 		if (BIT_N(i, j))
@@ -940,7 +940,7 @@
 		}
 
 	if (erList)
-		 printf("STMIA with Empty Rlist\n");
+		 fprintf(stderr, "STMIA with Empty Rlist\n");
 
 	cpu->R[REG_NUM(i, 8)] = adr;
 	return MMU_aluMemCycles<PROCNUM>(2, c);
@@ -954,7 +954,7 @@
 	bool erList = true; //Empty Register List
 
 	//if (BIT_N(i, regIndex))
-	//	 printf("LDMIA with Rb in Rlist at %08X\n",cpu->instruct_adr);
+	//	 fprintf(stderr, "LDMIA with Rb in Rlist at %08X\n",cpu->instruct_adr);
 
 	for (uint32_t j = 0; j < 8; ++j)
 		if (BIT_N(i, j))
@@ -966,7 +966,7 @@
 		}
 
 	if (erList)
-		 printf("LDMIA with Empty Rlist\n");
+		 fprintf(stderr, "LDMIA with Empty Rlist\n");
 
 	// ARM_REF:	THUMB: Causes base register write-back, and is not optional
 	// ARM_REF:	If the base register <Rn> is specified in <registers>, the final value of <Rn> is the loaded value
@@ -983,7 +983,7 @@
 
 TEMPLATE static uint32_t FASTCALL OP_BKPT_THUMB(uint32_t)
 {
-	printf("THUMB%c: OP_BKPT triggered\n", PROCNUM?'7':'9');
+	fprintf(stderr, "THUMB%c: OP_BKPT triggered\n", PROCNUM?'7':'9');
 	Status_Reg tmp = cpu->CPSR;
 	armcpu_switchMode(cpu, ABT); // enter abt mode
 	cpu->R[14] = cpu->instruct_adr + 4;
@@ -1023,7 +1023,7 @@
 		//zero 30-jun-2009 - but they say that the ideas 0xFF should crash the device...
 		//uint32_t swinum = cpu->instruction & 0xFF;
 		swinum &= 0x1F;
-		//printf("%d ARM SWI %d\n",PROCNUM,swinum);
+		//fprintf(stderr, "%d ARM SWI %d\n",PROCNUM,swinum);
 		return cpu->swi_tab[swinum]() + 3;
 	}
 	else
@@ -1120,7 +1120,7 @@
 	//----- the instruction are UNPREDICTABLE (because the value read for R15 has bits[1:0]==0b10).
 	if (Rm == 15)
 	{
-		printf("THUMB%c: BX using PC as operand\n", PROCNUM?'7':'9');
+		fprintf(stderr, "THUMB%c: BX using PC as operand\n", PROCNUM?'7':'9');
 		//emu_halt();
 	}
 	cpu->CPSR.bits.T = BIT0(Rm);

--- a/src/in_2sf/desmume/types.h
+++ b/src/in_2sf/desmume/types.h
@@ -18,8 +18,31 @@
 
 #pragma once
 
+#include <windows.h>
 #include <cstddef>
 #include <cstdint>
+#include <cstdio>
+#include <algorithm>
+
+#ifdef max
+#undef max
+#endif
+
+#ifdef min
+#undef min
+#endif
+
+using u64 = uint64_t;
+using s64 = int64_t;
+using u32 = uint32_t;
+using s32 = int32_t;
+using u16 = uint16_t;
+using s16 = int16_t;
+using u8 = uint8_t;
+using s8 = int8_t;
+#ifndef FORCEINLINE
+#define FORCEINLINE inline
+#endif
 
 #ifdef _WINDOWS
 # define HAVE_LIBAGG
@@ -35,6 +58,7 @@
 # ifdef __SSE2__
 #  define ENABLE_SSE2
 # endif
+# define HAVE_JIT
 #endif
 
 #ifdef NOSSE
@@ -48,7 +72,9 @@
 #ifdef _MSC_VER
 # define strcasecmp(x, y) _stricmp(x, y)
 # define strncasecmp(x, y, l) strnicmp(x, y, l)
-# define snprintf _snprintf
+# ifndef snprintf
+#  define snprintf _snprintf
+# endif
 #endif
 
 #ifndef MAX_PATH
@@ -74,17 +100,41 @@
 
 #ifdef __MINGW32__
 # undef FASTCALL
+# undef LDM_FASTCALL
 # define FASTCALL __attribute__((fastcall))
+# define LDM_FASTCALL
 # define ASMJIT_CALL_CONV kX86FuncConvGccFastCall
+# define ASMJIT_STDLIB_CALL_CONV kX86FuncConvCDecl
 #elif defined (__i386__) && !defined(__clang__)
 # define FASTCALL __attribute__((regparm(3)))
+# define LDM_FASTCALL
 # define ASMJIT_CALL_CONV kX86FuncConvGccRegParm3
+# define ASMJIT_STDLIB_CALL_CONV kX86FuncConvCDecl
 #elif defined(_MSC_VER) || defined(__INTEL_COMPILER)
 # define FASTCALL
-# define ASMJIT_CALL_CONV kX86FuncConvCDecl
+# define LDM_FASTCALL
+# ifdef _WIN64
+#  define ASMJIT_CALL_CONV kX86FuncConvW64
+#  define ASMJIT_STDLIB_CALL_CONV kX86FuncConvW64
+# else
+#  define ASMJIT_CALL_CONV kX86FuncConvCDecl
+#  define ASMJIT_STDLIB_CALL_CONV kX86FuncConvCDecl
+# endif
 #else
 # define FASTCALL
-# define ASMJIT_CALL_CONV kX86FuncConvCDecl
+# define LDM_FASTCALL
+# if defined(__amd64__) || defined(__x86_64__)
+#  if defined(_WIN64)
+#   define ASMJIT_CALL_CONV kX86FuncConvW64
+#   define ASMJIT_STDLIB_CALL_CONV kX86FuncConvW64
+#  else
+#   define ASMJIT_CALL_CONV kX86FuncConvU64
+#   define ASMJIT_STDLIB_CALL_CONV kX86FuncConvU64
+#  endif
+# else
+#  define ASMJIT_CALL_CONV kX86FuncConvCDecl
+#  define ASMJIT_STDLIB_CALL_CONV kX86FuncConvCDecl
+# endif
 #endif
 
 /*----------------------*/

--- a/src/in_2sf/desmume/utils/AsmJit/AsmJit.h
+++ b/src/in_2sf/desmume/utils/AsmJit/AsmJit.h
@@ -324,7 +324,7 @@
 //! vendor[12] = '\0';
 //!
 //! // Print a CPU vendor retrieved from CPUID.
-//! ::printf("%s", cpuVendor);
+//! ::fprintf(stderr, "%s", cpuVendor);
 //! ~~~
 
 // ============================================================================

--- a/src/in_2sf/desmume/utils/AsmJit/build.h
+++ b/src/in_2sf/desmume/utils/AsmJit/build.h
@@ -10,7 +10,7 @@
 #ifdef ASMJIT_CONFIG_FILE
 # include ASMJIT_CONFIG_FILE
 #else
-# include "./config.h"
+# include "./Config.h"
 #endif // ASMJIT_CONFIG_FILE
 
 // Turn off deprecation warnings when compiling AsmJit.
@@ -264,7 +264,7 @@
 namespace asmjit { static inline int disabledTrace(...) { return 0; } }
 # ifdef ASMJIT_TRACE
 #  define ASMJIT_TSEC(_Section_) _Section_
-#  define ASMJIT_TLOG ::printf(__VA_ARGS__)
+#  define ASMJIT_TLOG ::fprintf(stderr, __VA_ARGS__)
 # else
 #  define ASMJIT_TSEC(_Section_) do {} while(0)
 #  define ASMJIT_TLOG 0 && ::asmjit::disabledTrace

--- a/src/in_2sf/desmume/utils/AsmJit/x86/x86compiler.cpp
+++ b/src/in_2sf/desmume/utils/AsmJit/x86/x86compiler.cpp
@@ -201,7 +201,7 @@
 
       case kX86FuncConvMsFastCall:
         self->_calleePopsStack = true;
-        self->_passed.set(kX86RegClassGp, IntUtil::mask(R(Cx), R(Cx)));
+        self->_passed.set(kX86RegClassGp, IntUtil::mask(R(Cx), R(Dx)));
         self->_passedOrderGp[0] = R(Cx);
         self->_passedOrderGp[1] = R(Dx);
         break;

--- a/src/in_2sf/desmume/utils/AsmJit/x86/x86scheduler.cpp
+++ b/src/in_2sf/desmume/utils/AsmJit/x86/x86scheduler.cpp
@@ -76,7 +76,7 @@
     Node* next = node_->getNext();
     ASMJIT_ASSERT(node_->getType() == kNodeTypeInst);
 
-    printf("  %s\n", X86Util::getInstInfo(static_cast<InstNode*>(node_)->getCode()).getInstName());
+    fprintf(stderr, "  %s\n", X86Util::getInstInfo(static_cast<InstNode*>(node_)->getCode()).getInstName());
     node_ = next;
   }
 

--- /dev/null
+++ b/src/in_2sf/desmume/utils/bits.h
@@ -1,1 +1,42 @@
+#ifndef BITS_H

+#define BITS_H

+

+#define BIT(n)  (1<<(n))

+

+#define BIT_N(i,n)  (((i)>>(n))&1)

+#define BIT0(i)     ((i)&1)

+#define BIT1(i)     BIT_N(i,1)

+#define BIT2(i)     BIT_N(i,2)

+#define BIT3(i)     BIT_N(i,3)

+#define BIT4(i)     BIT_N(i,4)

+#define BIT5(i)     BIT_N(i,5)

+#define BIT6(i)     BIT_N(i,6)

+#define BIT7(i)     BIT_N(i,7)

+#define BIT8(i)     BIT_N(i,8)

+#define BIT9(i)     BIT_N(i,9)

+#define BIT10(i)     BIT_N(i,10)

+#define BIT11(i)     BIT_N(i,11)

+#define BIT12(i)     BIT_N(i,12)

+#define BIT13(i)     BIT_N(i,13)

+#define BIT14(i)     BIT_N(i,14)

+#define BIT15(i)     BIT_N(i,15)

+#define BIT16(i)     BIT_N(i,16)

+#define BIT17(i)     BIT_N(i,17)

+#define BIT18(i)     BIT_N(i,18)

+#define BIT19(i)     BIT_N(i,19)

+#define BIT20(i)     BIT_N(i,20)

+#define BIT21(i)     BIT_N(i,21)

+#define BIT22(i)     BIT_N(i,22)

+#define BIT23(i)     BIT_N(i,23)

+#define BIT24(i)     BIT_N(i,24)

+#define BIT25(i)     BIT_N(i,25)

+#define BIT26(i)     BIT_N(i,26)

+#define BIT27(i)     BIT_N(i,27)

+#define BIT28(i)     BIT_N(i,28)

+#define BIT29(i)     BIT_N(i,29)

+#define BIT30(i)     BIT_N(i,30)

+#define BIT31(i)    ((i)>>31)

+

+

+#endif

 

--- a/src/in_2sf/desmume/utils/dlditool.cpp
+++ /dev/null
@@ -1,508 +1,1 @@
-/*
-    dlditool - Dynamically Linked Disk Interface patch tool
-    Copyright (C) 2006  Michael Chisholm (Chishm)
 
-	Send all queries to chishm@hotmail.com
-
-    This program is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 2 of the License, or
-    (at your option) any later version.
-
-    This program is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License along
-    with this program; if not, write to the Free Software Foundation, Inc.,
-    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-	* v1.24d - 2010-06-14 - zeromus
-		* Modified for inclusion in desmume
-
-	* v1.24 - 2007-08-02 - SmileyDude
-		* Now using EXIT_SUCCESS and EXIT_FAILURE at the suggestion of MachinShin.
-		* Defined EXIT_NO_DLDI_SECTION for when there is no DLDI section in a file.
-		* Added cast to strcmp() call to appease the compiler.
-
-	* v1.23 - 2007-01-23 - Chishm
-		* Fixed bug when DLDI section doesn't exist
-		* addr_t is now a signed int
-
-	* v1.22 - 2007-01-12 - WinterMute
-		* add search paths for dldi files
-
-	* v1.21 - 2007-01-12 - Chishm
-		* Improved error messages
-
-	* v1.20 - 2007-01-11 - Chishm
-		* Changed offset calculation method
-
-	* v1.10 - 2007-01-07 - Chishm
-		* Removed assumptions about endianess of computer
-			* Word size shouldn't matter now either, except that an int type must be at least 32 bits long
-		* Added *.sc.nds and *.gba.nds file extensions
-		* Improved command line argument parsing
-
-	* v1.01 - 2006-12-30 - Chishm
-		* Minor bugfix parsing 3 arguments
-
-	* v1.00 - 2006-12-25 - Chishm
-		* Original release
-*/
-//#define VERSION "v1.24"
-
-#include <cstdio>
-#include <cstring>
-#include <cctype>
-#include <cerrno>
-#include <cstdlib>
-#include <cstdarg>
-
-#include <cstdint>
-#ifndef _MSC_VER
-# include <unistd.h>
-# include <sys/param.h>
-#else
-#define MAXPATHLEN 1024
-#endif
-
-#include <sys/stat.h>
-
-namespace DLDI
-{
-
-typedef int32_t addr_t;
-typedef unsigned char data_t;
-
-#define FIX_ALL 0x01
-#define FIX_GLUE 0x02
-#define FIX_GOT 0x04
-#define FIX_BSS 0x08
-
-enum DldiOffsets
-{
-	DO_magicString = 0x00, // "\xED\xA5\x8D\xBF Chishm"
-	DO_magicToken = 0x00, // 0xBF8DA5ED
-	DO_magicShortString = 0x04, // " Chishm"
-	DO_version = 0x0C,
-	DO_driverSize = 0x0D,
-	DO_fixSections = 0x0E,
-	DO_allocatedSpace = 0x0F,
-
-	DO_friendlyName = 0x10,
-
-	DO_text_start = 0x40, // Data start
-	DO_data_end = 0x44, // Data end
-	DO_glue_start = 0x48, // Interworking glue start -- Needs address fixing
-	DO_glue_end = 0x4C, // Interworking glue end
-	DO_got_start = 0x50, // GOT start -- Needs address fixing
-	DO_got_end = 0x54, // GOT end
-	DO_bss_start = 0x58, // bss start -- Needs setting to zero
-	DO_bss_end = 0x5C, // bss end
-
-	// IO_INTERFACE data
-	DO_ioType = 0x60,
-	DO_features = 0x64,
-	DO_startup = 0x68,
-	DO_isInserted = 0x6C,
-	DO_readSectors = 0x70,
-	DO_writeSectors = 0x74,
-	DO_clearStatus = 0x78,
-	DO_shutdown = 0x7C,
-	DO_code = 0x80
-};
-
-const data_t dldiMagicString[] = "\xED\xA5\x8D\xBF Chishm";
-const char dldiFileExtension[] = ".dldi";
-
-addr_t readAddr(data_t *mem, addr_t offset)
-{
-	return mem[offset + 0] | (mem[offset + 1] << 8) | (mem[offset + 2] << 16) | (mem[offset + 3] << 24);
-}
-
-void writeAddr(data_t *mem, addr_t offset, addr_t value)
-{
-	mem[offset + 0] = value & 0xFF;
-	mem[offset + 1] = (value >> 8) & 0xFF;
-	mem[offset + 2] = (value >> 16) & 0xFF;
-	mem[offset + 3] = (value >> 24) & 0xFF;
-}
-
-int stringCaseInsensitiveCompare(const char *str1, const char *str2)
-{
-	while (tolower(*str1) == tolower(*str2))
-	{
-		if (!*str1)
-			return 0;
-		++str1;
-		++str2;
-	}
-	return tolower(*str1) - tolower(*str2);
-}
-
-bool stringEndsWith(const char *str, const char *end)
-{
-	if (strlen(str) < strlen(end))
-		return false;
-	const char *strEnd = &str[strlen (str) - strlen(end)];
-	return !stringCaseInsensitiveCompare(strEnd, end);
-}
-
-bool stringStartsWith(const char *str, const char *start)
-{
-	return strstr(str, start) == str;
-}
-
-addr_t quickFind(const data_t *data, const data_t *search, size_t dataLen, size_t searchLen)
-{
-	const int32_t *dataChunk = reinterpret_cast<const int32_t *>(data);
-	int searchChunk = reinterpret_cast<const int32_t *>(search)[0];
-	addr_t dataChunkEnd = static_cast<addr_t>(dataLen / sizeof(int32_t));
-
-	for (addr_t i = 0; i < dataChunkEnd; ++i)
-	{
-		if (dataChunk[i] == searchChunk)
-		{
-			if (i * sizeof(int32_t) + searchLen > dataLen)
-				return -1;
-			if (!memcmp(&data[i * sizeof(int32_t)], search, searchLen))
-				return i * sizeof(int32_t);
-		}
-	}
-
-	return -1;
-}
-
-FILE *openDLDIFile(const char *argv0, char *dldiFileName )
-{
-	// add .dldi extension to filename
-	if (!stringEndsWith(dldiFileName, dldiFileExtension))
-		strcat(dldiFileName, dldiFileExtension);
-
-	printf("Trying \"%s\"\n", dldiFileName);
-	// try opening from current directory
-	FILE *dldiFile = fopen(dldiFileName, "rb");
-
-	if (dldiFile)
-		return dldiFile;
-
-	// check if the filename has a path component
-	// check both slash varieties, win32 understands both
-	// if we have a directory separator don't bother with search paths
-	if (strstr(dldiFileName, "\\"))
-		return nullptr;
-	if (strstr(dldiFileName ,"/"))
-		return nullptr;
-
-	// check for DLDIPATH in environment
-	char *dldiPATH = getenv("DLDIPATH");
-
-	char appPath[MAXPATHLEN];
-	if (dldiPATH)
-	{
-		strcpy(appPath, dldiPATH);
-		if (appPath[strlen(appPath)] != '\\' &&  appPath[strlen(appPath)] != '/')
-			strcat(appPath, "/");
-		strcat(appPath, dldiFileName);
-
-		printf("Trying \"%s\"\n", appPath);
-		dldiFile = fopen(appPath,"rb");
-
-		if (dldiFile)
-			return dldiFile;
-	}
-
-	char *lastSlash = nullptr;
-	char *ptr = const_cast<char *>(argv0);
-
-	while (*(ptr++))
-		if (*ptr == '\\' || * ptr == '/')
-			lastSlash = ptr;
-
-	char appName[MAXPATHLEN];
-	char appPathName[MAXPATHLEN];
-	if (lastSlash)
-	{
-		*(lastSlash++) = '\0';
-		strcpy(appPath, argv0);
-		strcpy(appName, lastSlash);
-		strcat(appPath, "/");
-	}
-	else
-	{
-		strcpy(appPath, "");
-		strcpy(appName, argv0);
-	}
-
-	// finally try in the application path
-	// if argv0 contains a directory separator we have a path component
-
-	if (!strstr(appPath,"\\") && !strstr(appPath,"/"))
-	{
-		// no path in argv0 so search system path
-		char *sysPATH = getenv("PATH");
-		char *thisPATH = sysPATH;
-		printf("Searching system path\n%s\n", sysPATH);
-
-		while (1)
-		{
-			char *nextPATH = strstr(thisPATH, ":" ); // find next PATH separator
-
-			if (nextPATH)
-				*(nextPATH++) = '\0'; // terminate string, point to next component
-
-			strcpy(appPath, thisPATH);
-			strcat(appPath, "/");
-			strcpy(appPathName, appPath);
-			strcat(appPathName, appName); // add application name
-
-			struct stat buf;
-			if (!stat(appPathName, &buf)) // if it exists we found the path
-				break;
-
-			thisPATH = nextPATH;
-			strcpy(appPath, "");// empty path
-			if (!thisPATH)
-				break;
-		}
-	}
-
-	strcat(appPath, "dldi/"); // add dldi folder
-	strcat(appPath, dldiFileName); // add dldi filename to path
-	printf("Trying \"%s\"\n", appPath);
-
-	return fopen(appPath, "rb"); // no more places to check, just return this handle
-}
-
-//  Source File: mpcf.dldi
-//         Time: 6/14/2010 9:38 PM
-// Orig. Offset: 0 / 0x00000000
-//       Length: 1876 / 0x00000754 (bytes)
-static data_t mpcf_dldi[] =
-{
-    0xED, 0xA5, 0x8D, 0xBF, 0x20, 0x43, 0x68, 0x69, 0x73, 0x68, 0x6D, 0x00, 0x01, 0x0B, 0x0C, 0x00,
-    0x47, 0x42, 0x41, 0x20, 0x4D, 0x6F, 0x76, 0x69, 0x65, 0x20, 0x50, 0x6C, 0x61, 0x79, 0x65, 0x72,
-    0x20, 0x28, 0x43, 0x6F, 0x6D, 0x70, 0x61, 0x63, 0x74, 0x20, 0x46, 0x6C, 0x61, 0x73, 0x68, 0x29,
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x80, 0xBF, 0x54, 0x07, 0x80, 0xBF, 0x98, 0x00, 0x80, 0xBF, 0x98, 0x00, 0x80, 0xBF,
-    0x50, 0x07, 0x80, 0xBF, 0x50, 0x07, 0x80, 0xBF, 0x54, 0x07, 0x80, 0xBF, 0x70, 0x07, 0x80, 0xBF,
-    0x4D, 0x50, 0x43, 0x46, 0x13, 0x00, 0x00, 0x00, 0x3C, 0x01, 0x80, 0xBF, 0x98, 0x01, 0x80, 0xBF,
-    0x78, 0x02, 0x80, 0xBF, 0xC8, 0x04, 0x80, 0xBF, 0xC8, 0x01, 0x80, 0xBF, 0x10, 0x07, 0x80, 0xBF,
-    0x0D, 0xC0, 0xA0, 0xE1, 0xF8, 0xDF, 0x2D, 0xE9, 0x04, 0xB0, 0x4C, 0xE2, 0x28, 0xD0, 0x4B, 0xE2,
-    0xF0, 0x6F, 0x9D, 0xE8, 0x1E, 0xFF, 0x2F, 0xE1, 0x10, 0x40, 0x2D, 0xE9, 0x2C, 0x40, 0x9F, 0xE5,
-    0x00, 0x30, 0xD4, 0xE5, 0x00, 0x00, 0x53, 0xE3, 0x24, 0x20, 0x9F, 0xE5, 0x05, 0x00, 0x00, 0x1A,
-    0x00, 0x00, 0x52, 0xE3, 0x1C, 0x00, 0x9F, 0xE5, 0x0F, 0xE0, 0xA0, 0x11, 0x12, 0xFF, 0x2F, 0x11,
-    0x01, 0x30, 0xA0, 0xE3, 0x00, 0x30, 0xC4, 0xE5, 0x10, 0x40, 0xBD, 0xE8, 0x1E, 0xFF, 0x2F, 0xE1,
-    0x54, 0x07, 0x80, 0xBF, 0x00, 0x00, 0x00, 0x00, 0x48, 0x07, 0x80, 0xBF, 0x04, 0xE0, 0x2D, 0xE5,
-    0x40, 0x30, 0x9F, 0xE5, 0x00, 0x00, 0x53, 0xE3, 0x04, 0xD0, 0x4D, 0xE2, 0x38, 0x00, 0x9F, 0xE5,
-    0x38, 0x10, 0x9F, 0xE5, 0x0F, 0xE0, 0xA0, 0x11, 0x13, 0xFF, 0x2F, 0x11, 0x30, 0x00, 0x9F, 0xE5,
-    0x00, 0x30, 0x90, 0xE5, 0x00, 0x00, 0x53, 0xE3, 0x28, 0x30, 0x9F, 0xE5, 0x02, 0x00, 0x00, 0x0A,
-    0x00, 0x00, 0x53, 0xE3, 0x0F, 0xE0, 0xA0, 0x11, 0x13, 0xFF, 0x2F, 0x11, 0x04, 0xD0, 0x8D, 0xE2,
-    0x04, 0xE0, 0x9D, 0xE4, 0x1E, 0xFF, 0x2F, 0xE1, 0x00, 0x00, 0x00, 0x00, 0x48, 0x07, 0x80, 0xBF,
-    0x58, 0x07, 0x80, 0xBF, 0x4C, 0x07, 0x80, 0xBF, 0x00, 0x00, 0x00, 0x00, 0x09, 0x14, 0xA0, 0xE3,
-    0x06, 0x18, 0x81, 0xE2, 0xB0, 0x30, 0xD1, 0xE1, 0x03, 0x30, 0xE0, 0xE1, 0x03, 0x38, 0xA0, 0xE1,
-    0x23, 0x38, 0xA0, 0xE1, 0xFF, 0x30, 0x03, 0xE2, 0xB0, 0x30, 0xC1, 0xE1, 0xB0, 0x20, 0xD1, 0xE1,
-    0x04, 0xE0, 0x2D, 0xE5, 0xAA, 0xCC, 0xA0, 0xE3, 0x55, 0xEC, 0xE0, 0xE3, 0x03, 0x00, 0x52, 0xE1,
-    0xAA, 0xE0, 0x4E, 0xE2, 0x55, 0xC0, 0x8C, 0xE2, 0x00, 0x00, 0xA0, 0xE3, 0x03, 0x00, 0x00, 0x1A,
-    0xB0, 0xE0, 0xC1, 0xE1, 0xB0, 0x30, 0xD1, 0xE1, 0x0C, 0x00, 0x53, 0xE0, 0x01, 0x00, 0xA0, 0x13,
-    0x04, 0xE0, 0x9D, 0xE4, 0x1E, 0xFF, 0x2F, 0xE1, 0x26, 0x35, 0xA0, 0xE3, 0x03, 0x37, 0x83, 0xE2,
-    0x50, 0x20, 0xA0, 0xE3, 0xB0, 0x20, 0xC3, 0xE1, 0xB0, 0x00, 0xD3, 0xE1, 0x00, 0x08, 0xA0, 0xE1,
-    0x20, 0x08, 0xA0, 0xE1, 0xFF, 0x00, 0x00, 0xE2, 0x50, 0x00, 0x50, 0xE3, 0x00, 0x00, 0xA0, 0x13,
-    0x01, 0x00, 0xA0, 0x03, 0x1E, 0xFF, 0x2F, 0xE1, 0x09, 0x34, 0xA0, 0xE3, 0x0E, 0x38, 0x83, 0xE2,
-    0xB0, 0x20, 0xD3, 0xE1, 0x80, 0x00, 0x12, 0xE3, 0x0C, 0x00, 0x00, 0x0A, 0x00, 0x00, 0xA0, 0xE3,
-    0x01, 0x00, 0x00, 0xEA, 0x01, 0x00, 0x50, 0xE1, 0x08, 0x00, 0x00, 0x0A, 0x09, 0x34, 0xA0, 0xE3,
-    0x0E, 0x38, 0x83, 0xE2, 0xB0, 0x20, 0xD3, 0xE1, 0x26, 0x17, 0xA0, 0xE3, 0x96, 0x1C, 0x81, 0xE2,
-    0x80, 0x00, 0x12, 0xE3, 0x01, 0x00, 0x80, 0xE2, 0x80, 0x10, 0x81, 0xE2, 0xF4, 0xFF, 0xFF, 0x1A,
-    0x26, 0x15, 0xA0, 0xE3, 0x03, 0x17, 0x81, 0xE2, 0xB0, 0x30, 0xD1, 0xE1, 0x50, 0x30, 0x13, 0xE2,
-    0x01, 0x00, 0xA0, 0x13, 0x1E, 0xFF, 0x2F, 0x11, 0x26, 0x27, 0xA0, 0xE3, 0x96, 0x2C, 0x82, 0xE2,
-    0x03, 0x00, 0xA0, 0xE1, 0x80, 0x20, 0x82, 0xE2, 0x01, 0x00, 0x00, 0xEA, 0x02, 0x00, 0x50, 0xE1,
-    0x0A, 0x00, 0x00, 0x0A, 0xB0, 0x30, 0xD1, 0xE1, 0x50, 0x30, 0x13, 0xE2, 0x01, 0x00, 0x80, 0xE2,
-    0xF9, 0xFF, 0xFF, 0x0A, 0x26, 0x37, 0xA0, 0xE3, 0x96, 0x3C, 0x83, 0xE2, 0x7F, 0x30, 0x83, 0xE2,
-    0x03, 0x00, 0x50, 0xE1, 0x00, 0x00, 0xA0, 0xC3, 0x01, 0x00, 0xA0, 0xD3, 0x1E, 0xFF, 0x2F, 0xE1,
-    0x03, 0x00, 0xA0, 0xE1, 0x1E, 0xFF, 0x2F, 0xE1, 0xF0, 0x4B, 0x2D, 0xE9, 0x09, 0x34, 0xA0, 0xE3,
-    0x0E, 0x38, 0x83, 0xE2, 0xB0, 0xC0, 0xD3, 0xE1, 0x80, 0x00, 0x1C, 0xE3, 0x10, 0xD0, 0x4D, 0xE2,
-    0x01, 0x90, 0xA0, 0xE1, 0x02, 0xE0, 0xA0, 0xE1, 0x0C, 0x00, 0x00, 0x0A, 0x00, 0xC0, 0xA0, 0xE3,
-    0x01, 0x00, 0x00, 0xEA, 0x01, 0x00, 0x5C, 0xE1, 0x08, 0x00, 0x00, 0x0A, 0x09, 0x34, 0xA0, 0xE3,
-    0x0E, 0x38, 0x83, 0xE2, 0xB0, 0x20, 0xD3, 0xE1, 0x26, 0x17, 0xA0, 0xE3, 0x96, 0x1C, 0x81, 0xE2,
-    0x80, 0x00, 0x12, 0xE3, 0x01, 0xC0, 0x8C, 0xE2, 0x80, 0x10, 0x81, 0xE2, 0xF4, 0xFF, 0xFF, 0x1A,
-    0x26, 0xC5, 0xA0, 0xE3, 0x03, 0xC7, 0x8C, 0xE2, 0xB0, 0x30, 0xDC, 0xE1, 0x50, 0x30, 0x13, 0xE2,
-    0x26, 0x17, 0xA0, 0x03, 0x96, 0x1C, 0x81, 0x02, 0x03, 0x20, 0xA0, 0x01, 0x80, 0x10, 0x81, 0x02,
-    0x02, 0x00, 0x00, 0x0A, 0x0A, 0x00, 0x00, 0xEA, 0x01, 0x00, 0x52, 0xE1, 0x67, 0x00, 0x00, 0x0A,
-    0xB0, 0x30, 0xDC, 0xE1, 0x50, 0x00, 0x13, 0xE3, 0x01, 0x20, 0x82, 0xE2, 0xF9, 0xFF, 0xFF, 0x0A,
-    0x26, 0x37, 0xA0, 0xE3, 0x96, 0x3C, 0x83, 0xE2, 0x7F, 0x30, 0x83, 0xE2, 0x03, 0x00, 0x52, 0xE1,
-    0x5E, 0x00, 0x00, 0xCA, 0xFF, 0x00, 0x59, 0xE3, 0x00, 0x30, 0xA0, 0x83, 0x0C, 0x30, 0x8D, 0x85,
-    0x5E, 0x00, 0x00, 0x9A, 0x00, 0x38, 0xA0, 0xE1, 0x23, 0x38, 0xA0, 0xE1, 0xFF, 0x30, 0x03, 0xE2,
-    0x09, 0x54, 0xA0, 0xE3, 0x04, 0x30, 0x8D, 0xE5, 0x0C, 0x30, 0x9D, 0xE5, 0x20, 0x4C, 0xA0, 0xE1,
-    0x0E, 0xB0, 0xA0, 0xE1, 0x05, 0x60, 0xA0, 0xE1, 0x20, 0x74, 0xA0, 0xE1, 0x05, 0x20, 0xA0, 0xE1,
-    0x20, 0x18, 0xA0, 0xE1, 0x05, 0xC0, 0xA0, 0xE1, 0x05, 0x00, 0xA0, 0xE1, 0x05, 0xE0, 0xA0, 0xE1,
-    0x01, 0x57, 0x85, 0xE2, 0xB0, 0x30, 0xC5, 0xE1, 0x04, 0x30, 0x9D, 0xE5, 0x0F, 0x40, 0x04, 0xE2,
-    0x06, 0x68, 0x86, 0xE2, 0xB0, 0x30, 0xC6, 0xE1, 0xFF, 0x70, 0x07, 0xE2, 0x02, 0x27, 0x82, 0xE2,
-    0xFF, 0x10, 0x01, 0xE2, 0x0A, 0x08, 0x80, 0xE2, 0xE0, 0x40, 0x84, 0xE3, 0x03, 0xC7, 0x8C, 0xE2,
-    0x0E, 0xE8, 0x8E, 0xE2, 0x20, 0x30, 0xA0, 0xE3, 0xB0, 0x70, 0xC2, 0xE1, 0xB0, 0x10, 0xC0, 0xE1,
-    0xB0, 0x40, 0xCC, 0xE1, 0xB0, 0x30, 0xCE, 0xE1, 0x0B, 0x80, 0xA0, 0xE1, 0x01, 0x90, 0x59, 0xE2,
-    0x3E, 0x00, 0x00, 0x3A, 0x26, 0x25, 0xA0, 0xE3, 0x03, 0x27, 0x82, 0xE2, 0xB0, 0x30, 0xD2, 0xE1,
-    0x03, 0x38, 0xA0, 0xE1, 0x23, 0x38, 0xA0, 0xE1, 0xFF, 0x30, 0x03, 0xE2, 0x58, 0x00, 0x53, 0xE3,
-    0x26, 0x17, 0xA0, 0x13, 0x96, 0x1C, 0x81, 0x12, 0x02, 0x00, 0xA0, 0x11, 0x80, 0x10, 0x81, 0x12,
-    0x00, 0x20, 0xA0, 0x13, 0x02, 0x00, 0x00, 0x1A, 0x0D, 0x00, 0x00, 0xEA, 0x01, 0x00, 0x52, 0xE1,
-    0x26, 0x00, 0x00, 0x0A, 0xB0, 0x30, 0xD0, 0xE1, 0x03, 0x38, 0xA0, 0xE1, 0x23, 0x38, 0xA0, 0xE1,
-    0xFF, 0x30, 0x03, 0xE2, 0x58, 0x00, 0x53, 0xE3, 0x01, 0x20, 0x82, 0xE2, 0xF6, 0xFF, 0xFF, 0x1A,
-    0x26, 0x37, 0xA0, 0xE3, 0x96, 0x3C, 0x83, 0xE2, 0x7F, 0x30, 0x83, 0xE2, 0x03, 0x00, 0x52, 0xE1,
-    0x1A, 0x00, 0x00, 0xCA, 0x01, 0x00, 0x18, 0xE3, 0x0B, 0x10, 0xA0, 0x01, 0xFF, 0x20, 0xA0, 0x03,
-    0x09, 0x04, 0xA0, 0x03, 0x0E, 0x00, 0x00, 0x0A, 0x08, 0x10, 0xA0, 0xE1, 0xFF, 0x00, 0xA0, 0xE3,
-    0x09, 0xC4, 0xA0, 0xE3, 0xB0, 0x30, 0xDC, 0xE1, 0x03, 0x38, 0xA0, 0xE1, 0x23, 0x38, 0xA0, 0xE1,
-    0x01, 0x00, 0x40, 0xE2, 0x43, 0x24, 0xA0, 0xE1, 0x01, 0x00, 0x70, 0xE3, 0x01, 0x20, 0xC1, 0xE5,
-    0x00, 0x30, 0xC1, 0xE5, 0x02, 0x10, 0x81, 0xE2, 0xF5, 0xFF, 0xFF, 0x1A, 0x02, 0x8C, 0x88, 0xE2,
-    0xCD, 0xFF, 0xFF, 0xEA, 0x01, 0x20, 0x42, 0xE2, 0xB0, 0x30, 0xD0, 0xE1, 0x01, 0x00, 0x72, 0xE3,
-    0xB2, 0x30, 0xC1, 0xE0, 0xFA, 0xFF, 0xFF, 0x1A, 0x02, 0xBC, 0x8B, 0xE2, 0xC6, 0xFF, 0xFF, 0xEA,
-    0x00, 0x00, 0xA0, 0xE3, 0x10, 0xD0, 0x8D, 0xE2, 0xF0, 0x4B, 0xBD, 0xE8, 0x1E, 0xFF, 0x2F, 0xE1,
-    0x09, 0x38, 0xA0, 0xE1, 0x23, 0x38, 0xA0, 0xE1, 0x0C, 0x30, 0x8D, 0xE5, 0x9C, 0xFF, 0xFF, 0xEA,
-    0x01, 0x00, 0xA0, 0xE3, 0xF6, 0xFF, 0xFF, 0xEA, 0xF0, 0x4B, 0x2D, 0xE9, 0x09, 0x34, 0xA0, 0xE3,
-    0x0E, 0x38, 0x83, 0xE2, 0xB0, 0xC0, 0xD3, 0xE1, 0x80, 0x00, 0x1C, 0xE3, 0x10, 0xD0, 0x4D, 0xE2,
-    0x01, 0x90, 0xA0, 0xE1, 0x02, 0xE0, 0xA0, 0xE1, 0x0C, 0x00, 0x00, 0x0A, 0x00, 0xC0, 0xA0, 0xE3,
-    0x01, 0x00, 0x00, 0xEA, 0x01, 0x00, 0x5C, 0xE1, 0x08, 0x00, 0x00, 0x0A, 0x09, 0x34, 0xA0, 0xE3,
-    0x0E, 0x38, 0x83, 0xE2, 0xB0, 0x20, 0xD3, 0xE1, 0x26, 0x17, 0xA0, 0xE3, 0x96, 0x1C, 0x81, 0xE2,
-    0x80, 0x00, 0x12, 0xE3, 0x01, 0xC0, 0x8C, 0xE2, 0x80, 0x10, 0x81, 0xE2, 0xF4, 0xFF, 0xFF, 0x1A,
-    0x26, 0xC5, 0xA0, 0xE3, 0x03, 0xC7, 0x8C, 0xE2, 0xB0, 0x30, 0xDC, 0xE1, 0x50, 0x30, 0x13, 0xE2,
-    0x26, 0x17, 0xA0, 0x03, 0x96, 0x1C, 0x81, 0x02, 0x03, 0x20, 0xA0, 0x01, 0x80, 0x10, 0x81, 0x02,
-    0x02, 0x00, 0x00, 0x0A, 0x0A, 0x00, 0x00, 0xEA, 0x01, 0x00, 0x52, 0xE1, 0x65, 0x00, 0x00, 0x0A,
-    0xB0, 0x30, 0xDC, 0xE1, 0x50, 0x00, 0x13, 0xE3, 0x01, 0x20, 0x82, 0xE2, 0xF9, 0xFF, 0xFF, 0x0A,
-    0x26, 0x37, 0xA0, 0xE3, 0x96, 0x3C, 0x83, 0xE2, 0x7F, 0x30, 0x83, 0xE2, 0x03, 0x00, 0x52, 0xE1,
-    0x5C, 0x00, 0x00, 0xCA, 0xFF, 0x00, 0x59, 0xE3, 0x00, 0x30, 0xA0, 0x83, 0x0C, 0x30, 0x8D, 0x85,
-    0x5C, 0x00, 0x00, 0x9A, 0x00, 0x38, 0xA0, 0xE1, 0x23, 0x38, 0xA0, 0xE1, 0xFF, 0x30, 0x03, 0xE2,
-    0x09, 0x54, 0xA0, 0xE3, 0x04, 0x30, 0x8D, 0xE5, 0x0C, 0x30, 0x9D, 0xE5, 0x20, 0x4C, 0xA0, 0xE1,
-    0x0E, 0xB0, 0xA0, 0xE1, 0x05, 0x60, 0xA0, 0xE1, 0x20, 0x74, 0xA0, 0xE1, 0x05, 0x20, 0xA0, 0xE1,
-    0x20, 0x18, 0xA0, 0xE1, 0x05, 0xC0, 0xA0, 0xE1, 0x05, 0x00, 0xA0, 0xE1, 0x05, 0xE0, 0xA0, 0xE1,
-    0x01, 0x57, 0x85, 0xE2, 0xB0, 0x30, 0xC5, 0xE1, 0x04, 0x30, 0x9D, 0xE5, 0x0F, 0x40, 0x04, 0xE2,
-    0x06, 0x68, 0x86, 0xE2, 0xB0, 0x30, 0xC6, 0xE1, 0xFF, 0x70, 0x07, 0xE2, 0x02, 0x27, 0x82, 0xE2,
-    0xFF, 0x10, 0x01, 0xE2, 0x0A, 0x08, 0x80, 0xE2, 0xE0, 0x40, 0x84, 0xE3, 0x03, 0xC7, 0x8C, 0xE2,
-    0x0E, 0xE8, 0x8E, 0xE2, 0x30, 0x30, 0xA0, 0xE3, 0xB0, 0x70, 0xC2, 0xE1, 0xB0, 0x10, 0xC0, 0xE1,
-    0xB0, 0x40, 0xCC, 0xE1, 0xB0, 0x30, 0xCE, 0xE1, 0x0B, 0x80, 0xA0, 0xE1, 0x01, 0x90, 0x59, 0xE2,
-    0x3C, 0x00, 0x00, 0x3A, 0x26, 0x25, 0xA0, 0xE3, 0x03, 0x27, 0x82, 0xE2, 0xB0, 0x30, 0xD2, 0xE1,
-    0x03, 0x38, 0xA0, 0xE1, 0x23, 0x38, 0xA0, 0xE1, 0xFF, 0x30, 0x03, 0xE2, 0x58, 0x00, 0x53, 0xE3,
-    0x26, 0x17, 0xA0, 0x13, 0x96, 0x1C, 0x81, 0x12, 0x02, 0x00, 0xA0, 0x11, 0x80, 0x10, 0x81, 0x12,
-    0x00, 0x20, 0xA0, 0x13, 0x02, 0x00, 0x00, 0x1A, 0x0D, 0x00, 0x00, 0xEA, 0x01, 0x00, 0x52, 0xE1,
-    0x24, 0x00, 0x00, 0x0A, 0xB0, 0x30, 0xD0, 0xE1, 0x03, 0x38, 0xA0, 0xE1, 0x23, 0x38, 0xA0, 0xE1,
-    0xFF, 0x30, 0x03, 0xE2, 0x58, 0x00, 0x53, 0xE3, 0x01, 0x20, 0x82, 0xE2, 0xF6, 0xFF, 0xFF, 0x1A,
-    0x26, 0x37, 0xA0, 0xE3, 0x96, 0x3C, 0x83, 0xE2, 0x7F, 0x30, 0x83, 0xE2, 0x03, 0x00, 0x52, 0xE1,
-    0x18, 0x00, 0x00, 0xCA, 0x01, 0x00, 0x18, 0xE3, 0x0B, 0x10, 0xA0, 0x01, 0xFF, 0x20, 0xA0, 0x03,
-    0x09, 0x04, 0xA0, 0x03, 0x0C, 0x00, 0x00, 0x0A, 0x08, 0x10, 0xA0, 0xE1, 0xFF, 0x00, 0xA0, 0xE3,
-    0x09, 0xC4, 0xA0, 0xE3, 0x00, 0x30, 0xD1, 0xE5, 0x01, 0x20, 0xD1, 0xE5, 0x01, 0x00, 0x40, 0xE2,
-    0x02, 0x34, 0x83, 0xE1, 0x01, 0x00, 0x70, 0xE3, 0xB0, 0x30, 0xCC, 0xE1, 0x02, 0x10, 0x81, 0xE2,
-    0xF7, 0xFF, 0xFF, 0x1A, 0x02, 0x8C, 0x88, 0xE2, 0xCF, 0xFF, 0xFF, 0xEA, 0x01, 0x20, 0x42, 0xE2,
-    0xB2, 0x30, 0xD1, 0xE0, 0x01, 0x00, 0x72, 0xE3, 0xB0, 0x30, 0xC0, 0xE1, 0xFA, 0xFF, 0xFF, 0x1A,
-    0x02, 0xBC, 0x8B, 0xE2, 0xC8, 0xFF, 0xFF, 0xEA, 0x00, 0x00, 0xA0, 0xE3, 0x10, 0xD0, 0x8D, 0xE2,
-    0xF0, 0x4B, 0xBD, 0xE8, 0x1E, 0xFF, 0x2F, 0xE1, 0x09, 0x38, 0xA0, 0xE1, 0x23, 0x38, 0xA0, 0xE1,
-    0x0C, 0x30, 0x8D, 0xE5, 0x9E, 0xFF, 0xFF, 0xEA, 0x01, 0x00, 0xA0, 0xE3, 0xF6, 0xFF, 0xFF, 0xEA,
-    0x04, 0xE0, 0x2D, 0xE5, 0x04, 0xD0, 0x4D, 0xE2, 0xAA, 0xFE, 0xFF, 0xEB, 0x04, 0xD0, 0x8D, 0xE2,
-    0x04, 0xE0, 0x9D, 0xE4, 0x1E, 0xFF, 0x2F, 0xE1, 0x0D, 0xC0, 0xA0, 0xE1, 0xF8, 0xDF, 0x2D, 0xE9,
-    0x04, 0xB0, 0x4C, 0xE2, 0x28, 0xD0, 0x4B, 0xE2, 0xF0, 0x6F, 0x9D, 0xE8, 0x1E, 0xFF, 0x2F, 0xE1,
-    0xDC, 0x00, 0x80, 0xBF, 0x98, 0x00, 0x80, 0xBF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00,
-}; //unsigned char mpcf_dldi[1876]
-
-bool tryPatch(void *data, size_t size)
-{
-	// Find the DSDI reserved space in the file
-	addr_t patchOffset = quickFind(static_cast<data_t *>(data), dldiMagicString, size, sizeof(dldiMagicString) / sizeof(char));
-
-	// no DLDI section
-	if (patchOffset < 0)
-		return false;
-
-	data_t *pDH = mpcf_dldi;
-	data_t *pAH = static_cast<data_t *>(data) + patchOffset;
-
-	if (pDH[DO_driverSize] > pAH[DO_allocatedSpace])
-	{
-		printf("Not enough space for patch. Available %d bytes, need %d bytes\n", 1 << pAH[DO_allocatedSpace], 1 << pDH[DO_driverSize]);
-		return false;
-	}
-
-	if (memcmp(&pAH[DO_friendlyName], "Default (No interface)", 22))
-	{
-		printf("Would have been a candidate for auto-patch DLDI, but there was already a patch installed.");
-		return false;
-	}
-
-	//----should be able to patch OK-----
-
-	addr_t memOffset; // Offset of DLDI after the file is loaded into memory
-	addr_t relocationOffset; // Value added to all offsets within the patch to fix it properly
-	addr_t ddmemOffset; // Original offset used in the DLDI file
-	addr_t ddmemStart; // Start of range that offsets can be in the DLDI file
-	addr_t ddmemEnd; // End of range that offsets can be in the DLDI file
-	addr_t ddmemSize; // Size of range that offsets can be in the DLDI file
-
-	addr_t addrIter;
-
-	memOffset = readAddr(pAH, DO_text_start);
-	if (!memOffset)
-		memOffset = readAddr(pAH, DO_startup) - DO_code;
-	ddmemOffset = readAddr(pDH, DO_text_start);
-	relocationOffset = memOffset - ddmemOffset;
-
-	printf("AUTO-PATCHING DLDI to MPCF! Lucky you!\n\n");
-	printf("Old driver:          %s\n", &pAH[DO_friendlyName]);
-	printf("New driver:          %s\n", &pDH[DO_friendlyName]);
-	printf("\n");
-	printf("Position in file:    0x%08X\n", patchOffset);
-	printf("Position in memory:  0x%08X\n", memOffset);
-	printf("Patch base address:  0x%08X\n", ddmemOffset);
-	printf("Relocation offset:   0x%08X\n", relocationOffset);
-	printf("\n");
-
-	ddmemStart = readAddr(pDH, DO_text_start);
-	ddmemSize = 1 << pDH[DO_driverSize];
-	ddmemEnd = ddmemStart + ddmemSize;
-
-	// Remember how much space is actually reserved
-	pDH[DO_allocatedSpace] = pAH[DO_allocatedSpace];
-	// Copy the DLDI patch into the application
-	memcpy(pAH, pDH, sizeof(mpcf_dldi));
-
-	// Fix the section pointers in the header
-	writeAddr(pAH, DO_text_start, readAddr(pAH, DO_text_start) + relocationOffset);
-	writeAddr(pAH, DO_data_end, readAddr(pAH, DO_data_end) + relocationOffset);
-	writeAddr(pAH, DO_glue_start, readAddr(pAH, DO_glue_start) + relocationOffset);
-	writeAddr(pAH, DO_glue_end, readAddr(pAH, DO_glue_end) + relocationOffset);
-	writeAddr(pAH, DO_got_start, readAddr(pAH, DO_got_start) + relocationOffset);
-	writeAddr(pAH, DO_got_end, readAddr(pAH, DO_got_end) + relocationOffset);
-	writeAddr(pAH, DO_bss_start, readAddr(pAH, DO_bss_start) + relocationOffset);
-	writeAddr(pAH, DO_bss_end, readAddr(pAH, DO_bss_end) + relocationOffset);
-	// Fix the function pointers in the header
-	writeAddr(pAH, DO_startup, readAddr(pAH, DO_startup) + relocationOffset);
-	writeAddr(pAH, DO_isInserted, readAddr(pAH, DO_isInserted) + relocationOffset);
-	writeAddr(pAH, DO_readSectors, readAddr(pAH, DO_readSectors) + relocationOffset);
-	writeAddr(pAH, DO_writeSectors, readAddr(pAH, DO_writeSectors) + relocationOffset);
-	writeAddr(pAH, DO_clearStatus, readAddr(pAH, DO_clearStatus) + relocationOffset);
-	writeAddr(pAH, DO_shutdown, readAddr(pAH, DO_shutdown) + relocationOffset);
-
-	if (pDH[DO_fixSections] & FIX_ALL)
-		// Search through and fix pointers within the data section of the file
-		for (addrIter = readAddr(pDH, DO_text_start) - ddmemStart; addrIter < readAddr(pDH, DO_data_end) - ddmemStart; ++addrIter)
-			if (ddmemStart <= readAddr(pAH, addrIter) && readAddr(pAH, addrIter) < ddmemEnd)
-				writeAddr(pAH, addrIter, readAddr(pAH, addrIter) + relocationOffset);
-
-	if (pDH[DO_fixSections] & FIX_GLUE)
-		// Search through and fix pointers within the glue section of the file
-		for (addrIter = readAddr(pDH, DO_glue_start) - ddmemStart; addrIter < readAddr(pDH, DO_glue_end) - ddmemStart; ++addrIter)
-			if (ddmemStart <= readAddr(pAH, addrIter) && readAddr(pAH, addrIter) < ddmemEnd)
-				writeAddr(pAH, addrIter, readAddr(pAH, addrIter) + relocationOffset);
-
-	if (pDH[DO_fixSections] & FIX_GOT)
-		// Search through and fix pointers within the Global Offset Table section of the file
-		for (addrIter = readAddr(pDH, DO_got_start) - ddmemStart; addrIter < readAddr(pDH, DO_got_end) - ddmemStart; ++addrIter)
-			if (ddmemStart <= readAddr(pAH, addrIter) && readAddr(pAH, addrIter) < ddmemEnd)
-				writeAddr(pAH, addrIter, readAddr(pAH, addrIter) + relocationOffset);
-
-	if (pDH[DO_fixSections] & FIX_BSS)
-		// Initialise the BSS to 0
-		memset(&pAH[readAddr(pDH, DO_bss_start) - ddmemStart] , 0, readAddr(pDH, DO_bss_end) - readAddr(pDH, DO_bss_start));
-
-	return true;
-}
-
-} //namespace DLDI
-

--- a/src/in_2sf/desmume/utils/xstring.cpp
+++ /dev/null
@@ -1,48 +1,1 @@
-//taken from fceux on 10/27/08
-//subsequently modified for desmume
 
-/*
-	Copyright (C) 2008-2009 DeSmuME team
-
-	This file is free software: you can redistribute it and/or modify
-	it under the terms of the GNU General Public License as published by
-	the Free Software Foundation, either version 2 of the License, or
-	(at your option) any later version.
-
-	This file is distributed in the hope that it will be useful,
-	but WITHOUT ANY WARRANTY; without even the implied warranty of
-	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-	GNU General Public License for more details.
-
-	You should have received a copy of the GNU General Public License
-	along with the this software.  If not, see <http://www.gnu.org/licenses/>.
-*/
-
-#include <string>
-#include <vector>
-
-#include "xstring.h"
-
-std::vector<std::string> tokenize_str(const std::string &str, const std::string &delims = ", \t")
-{
-	// Skip delims at beginning, find start of first token
-	auto lastPos = str.find_first_not_of(delims, 0);
-	// Find next delimiter @ end of token
-	auto pos = str.find_first_of(delims, lastPos);
-
-	// output vector
-	std::vector<std::string> tokens;
-
-	while (pos != std::string::npos || lastPos != std::string::npos)
-	{
-		// Found a token, add it to the vector.
-		tokens.push_back(str.substr(lastPos, pos - lastPos));
-		// Skip delims.  Note the "not_of". this is beginning of token
-		lastPos = str.find_first_not_of(delims, pos);
-		// Find next delimiter at end of token.
-		pos = str.find_first_of(delims, lastPos);
-	}
-
-	return tokens;
-}
-

--- a/src/in_2sf/desmume/utils/xstring.h
+++ /dev/null
@@ -1,27 +1,1 @@
-//taken from fceux on 27-oct-2008
-//subsequently modified for desmume
 
-/*
-	Copyright (C) 2008-2009 DeSmuME team
-
-	This file is free software: you can redistribute it and/or modify
-	it under the terms of the GNU General Public License as published by
-	the Free Software Foundation, either version 2 of the License, or
-	(at your option) any later version.
-
-	This file is distributed in the hope that it will be useful,
-	but WITHOUT ANY WARRANTY; without even the implied warranty of
-	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-	GNU General Public License for more details.
-
-	You should have received a copy of the GNU General Public License
-	along with the this software.  If not, see <http://www.gnu.org/licenses/>.
-*/
-
-#pragma once
-
-#include <string>
-#include <vector>
-
-std::vector<std::string> tokenize_str(const std::string &str, const std::string &delims);
-

--- a/src/in_2sf/in_2sf.vcxproj
+++ b/src/in_2sf/in_2sf.vcxproj
@@ -80,135 +80,112 @@
     </Link>
   </ItemDefinitionGroup>
   <ItemGroup>
-    <ClCompile Include="desmume\arm_jit.cpp" />
-    <ClCompile Include="desmume\metaspu\SoundTouch\mmx_optimized.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\assembler.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\codegen.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\compiler.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\constpool.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\containers.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\context.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\cpuinfo.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\cputicks.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\error.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\globals.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\logger.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\operand.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\runtime.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\string.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\vmem.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\zone.cpp" />
-    <ClCompile Include="desmume\addons\slot1_retail.cpp" />
-    <ClCompile Include="desmume\armcpu.cpp" />
-    <ClCompile Include="desmume\arm_instructions.cpp" />
-    <ClCompile Include="desmume\bios.cpp" />
-    <ClCompile Include="desmume\cp15.cpp" />
-    <ClCompile Include="desmume\emufile.cpp" />
-    <ClCompile Include="desmume\FIFO.cpp" />
-    <ClCompile Include="desmume\firmware.cpp" />
-    <ClCompile Include="desmume\mc.cpp" />
-    <ClCompile Include="desmume\metaspu\metaspu.cpp" />
-    <ClCompile Include="desmume\metaspu\SndOut.cpp" />
-    <ClCompile Include="desmume\metaspu\SoundTouch\AAFilter.cpp" />
-    <ClCompile Include="desmume\metaspu\SoundTouch\cpu_detect_x86_win.cpp" />
-    <ClCompile Include="desmume\metaspu\SoundTouch\FIFOSampleBuffer.cpp" />
-    <ClCompile Include="desmume\metaspu\SoundTouch\FIRFilter.cpp" />
-    <ClCompile Include="desmume\metaspu\SoundTouch\RateTransposer.cpp" />
-    <ClCompile Include="desmume\metaspu\SoundTouch\SoundTouch.cpp" />
-    <ClCompile Include="desmume\metaspu\SoundTouch\sse_optimized.cpp" />
-    <ClCompile Include="desmume\metaspu\SoundTouch\TDStretch.cpp" />
-    <ClCompile Include="desmume\metaspu\Timestretcher.cpp" />
-    <ClCompile Include="desmume\MMU.cpp" />
-    <ClCompile Include="desmume\NDSSystem.cpp" />
-    <ClCompile Include="desmume\readwrite.cpp" />
-    <ClCompile Include="desmume\slot1.cpp" />
-    <ClCompile Include="desmume\SPU.cpp" />
-    <ClCompile Include="desmume\thumb_instructions.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\x86\x86assembler.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\x86\x86compiler.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\x86\x86context.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\x86\x86cpuinfo.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\x86\x86inst.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\x86\x86operand.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\x86\x86operand_regs.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\x86\x86scheduler.cpp" />
-    <ClCompile Include="desmume\utils\dlditool.cpp" />
-    <ClCompile Include="desmume\utils\xstring.cpp" />
-    <ClCompile Include="desmume\version.cpp" />
+    <ClCompile Include="desmume/mc.cpp" />
+    <ClCompile Include="desmume/bios.cpp" />
+    <ClCompile Include="desmume/MMU.cpp" />
+    <ClCompile Include="desmume/readwrite.cpp" />
+    <ClCompile Include="desmume/FIFO.cpp" />
+    <ClCompile Include="desmume/addons/slot1_retail.cpp" />
+    <ClCompile Include="desmume/armcpu.cpp" />
+    <ClCompile Include="desmume/arm_jit.cpp" />
+    <ClCompile Include="desmume/emufile.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/compiler.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/string.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/constpool.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/assembler.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/error.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/context.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/globals.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/containers.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/codegen.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/cputicks.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/cpuinfo.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/vmem.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/operand.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/zone.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/logger.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/runtime.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/x86/x86cpuinfo.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/x86/x86compiler.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/x86/x86inst.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/x86/x86operand_regs.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/x86/x86assembler.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/x86/x86context.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/x86/x86operand.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/x86/x86scheduler.cpp" />
+    <ClCompile Include="desmume/version.cpp" />
+    <ClCompile Include="desmume/SPU.cpp" />
+    <ClCompile Include="desmume/NDSSystem.cpp" />
+    <ClCompile Include="desmume/metaspu/metaspu.cpp" />
+    <ClCompile Include="desmume/cp15.cpp" />
+    <ClCompile Include="desmume/arm_instructions.cpp" />
+    <ClCompile Include="desmume/thumb_instructions.cpp" />
+    <ClCompile Include="desmume/firmware.cpp" />
+    <ClCompile Include="desmume/slot1.cpp" />
     <ClCompile Include="XSFConfig_2SF.cpp" />
     <ClCompile Include="XSFPlayer_2SF.cpp" />
   </ItemGroup>
   <ItemGroup>
+    <ClInclude Include="desmume\NDSSystem.h" />
+    <ClInclude Include="desmume\emufile.h" />
+    <ClInclude Include="desmume\bits.h" />
+    <ClInclude Include="desmume\types.h" />
     <ClInclude Include="desmume\arm_jit.h" />
-    <ClInclude Include="desmume\instructions.h" />
+    <ClInclude Include="desmume\PACKED_END.h" />
+    <ClInclude Include="desmume\version.h" />
     <ClInclude Include="desmume\instruction_attributes.h" />
+    <ClInclude Include="desmume\registers.h" />
+    <ClInclude Include="desmume\firmware.h" />
+    <ClInclude Include="desmume\utils\bits.h" />
+    <ClInclude Include="desmume\utils\AsmJit\AsmJit.h" />
+    <ClInclude Include="desmume\utils\AsmJit\apiend.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base.h" />
+    <ClInclude Include="desmume\utils\AsmJit\x86.h" />
+    <ClInclude Include="desmume\utils\AsmJit\host.h" />
+    <ClInclude Include="desmume\utils\AsmJit\build.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\context_p.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\vectypes.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\containers.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\zone.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\constpool.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\cpuinfo.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\vmem.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\string.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\logger.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\intutil.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\compiler.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\assembler.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\error.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\operand.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\cputicks.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\globals.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\codegen.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\runtime.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\lock.h" />
+    <ClInclude Include="desmume\utils\AsmJit\Config.h" />
     <ClInclude Include="desmume\utils\AsmJit\apibegin.h" />
-    <ClInclude Include="desmume\utils\AsmJit\apiend.h" />
-    <ClInclude Include="desmume\utils\AsmJit\asmjit.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\assembler.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\codegen.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\compiler.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\constpool.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\containers.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\context_p.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\cpuinfo.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\cputicks.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\error.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\globals.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\intutil.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\lock.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\logger.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\operand.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\runtime.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\string.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\vectypes.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\vmem.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\zone.h" />
-    <ClInclude Include="desmume\utils\AsmJit\build.h" />
-    <ClInclude Include="desmume\utils\AsmJit\config.h" />
-    <ClInclude Include="desmume\utils\AsmJit\host.h" />
-    <ClInclude Include="desmume\utils\AsmJit\x86.h" />
-    <ClInclude Include="desmume\armcpu.h" />
-    <ClInclude Include="desmume\bios.h" />
-    <ClInclude Include="desmume\bits.h" />
-    <ClInclude Include="desmume\cp15.h" />
-    <ClInclude Include="desmume\emufile.h" />
-    <ClInclude Include="desmume\FIFO.h" />
-    <ClInclude Include="desmume\firmware.h" />
-    <ClInclude Include="desmume\matrix.h" />
-    <ClInclude Include="desmume\mc.h" />
-    <ClInclude Include="desmume\mem.h" />
-    <ClInclude Include="desmume\metaspu\metaspu.h" />
-    <ClInclude Include="desmume\metaspu\SndOut.h" />
-    <ClInclude Include="desmume\metaspu\SoundTouch\AAFilter.h" />
-    <ClInclude Include="desmume\metaspu\SoundTouch\cpu_detect.h" />
-    <ClInclude Include="desmume\metaspu\SoundTouch\FIFOSampleBuffer.h" />
-    <ClInclude Include="desmume\metaspu\SoundTouch\FIFOSamplePipe.h" />
-    <ClInclude Include="desmume\metaspu\SoundTouch\FIRFilter.h" />
-    <ClInclude Include="desmume\metaspu\SoundTouch\RateTransposer.h" />
-    <ClInclude Include="desmume\metaspu\SoundTouch\SoundTouch.h" />
-    <ClInclude Include="desmume\metaspu\SoundTouch\STTypes.h" />
-    <ClInclude Include="desmume\metaspu\SoundTouch\TDStretch.h" />
-    <ClInclude Include="desmume\MMU.h" />
-    <ClInclude Include="desmume\MMU_timing.h" />
-    <ClInclude Include="desmume\NDSSystem.h" />
-    <ClInclude Include="desmume\PACKED.h" />
-    <ClInclude Include="desmume\PACKED_END.h" />
-    <ClInclude Include="desmume\readwrite.h" />
-    <ClInclude Include="desmume\registers.h" />
-    <ClInclude Include="desmume\slot1.h" />
-    <ClInclude Include="desmume\SPU.h" />
-    <ClInclude Include="desmume\types.h" />
     <ClInclude Include="desmume\utils\AsmJit\x86\x86assembler.h" />
     <ClInclude Include="desmume\utils\AsmJit\x86\x86compiler.h" />
-    <ClInclude Include="desmume\utils\AsmJit\x86\x86context_p.h" />
-    <ClInclude Include="desmume\utils\AsmJit\x86\x86cpuinfo.h" />
-    <ClInclude Include="desmume\utils\AsmJit\x86\x86inst.h" />
     <ClInclude Include="desmume\utils\AsmJit\x86\x86operand.h" />
     <ClInclude Include="desmume\utils\AsmJit\x86\x86scheduler_p.h" />
-    <ClInclude Include="desmume\utils\xstring.h" />
-    <ClInclude Include="desmume\version.h" />
+    <ClInclude Include="desmume\utils\AsmJit\x86\x86inst.h" />
+    <ClInclude Include="desmume\utils\AsmJit\x86\x86cpuinfo.h" />
+    <ClInclude Include="desmume\utils\AsmJit\x86\x86context_p.h" />
+    <ClInclude Include="desmume\bios.h" />
+    <ClInclude Include="desmume\cp15.h" />
+    <ClInclude Include="desmume\MMU.h" />
+    <ClInclude Include="desmume\readwrite.h" />
+    <ClInclude Include="desmume\mc.h" />
+    <ClInclude Include="desmume\instructions.h" />
+    <ClInclude Include="desmume\metaspu\metaspu.h" />
+    <ClInclude Include="desmume\mem.h" />
+    <ClInclude Include="desmume\PACKED.h" />
+    <ClInclude Include="desmume\matrix.h" />
+    <ClInclude Include="desmume\MMU_timing.h" />
+    <ClInclude Include="desmume\slot1.h" />
+    <ClInclude Include="desmume\FIFO.h" />
+    <ClInclude Include="desmume\SPU.h" />
+    <ClInclude Include="desmume\armcpu.h" />
   </ItemGroup>
   <ItemGroup>
     <None Include="desmume\instruction_tabdef.inc" />
@@ -223,3 +200,4 @@
   <ImportGroup Label="ExtensionTargets">
   </ImportGroup>
 </Project>
+

--- /dev/null
+++ b/src/in_2sf/spu/adpcmdecoder.cpp
@@ -1,1 +1,85 @@
+#include "adpcmdecoder.h"
+#include <iostream>
 
+template <typename T, typename T2>
+static inline T clamp(T2 value, T lower, T upper)
+{
+  return value < lower ? lower : (value > upper ? upper : value);
+}
+
+template <typename T, typename Container>
+static inline T parseInt(const Container& buffer, int offset)
+{
+  uint64_t result = 0;
+  for (int i = sizeof(T) - 1; i >= 0; --i) {
+    result = (result << 8) | uint8_t(buffer[offset + i]);
+  }
+  return T(result);
+}
+
+static const int16_t adpcmIndex[] = { -1, -1, -1, -1, 2, 4, 6, 8, };
+
+static const int16_t adpcmStep[] = {
+      7,     8,     9,    10,    11,    12,    13,    14,    16,    17,
+     19,    21,    23,    25,    28,    31,    34,    37,    41,    45,
+     50,    55,    60,    66,    73,    80,    88,    97,   107,   118,
+    130,   143,   157,   173,   190,   209,   230,   253,   279,   307,
+    337,   371,   408,   449,   494,   544,   598,   658,   724,   796,
+    876,   963,  1060,  1166,  1282,  1411,  1552,  1707,  1878,  2066,
+   2272,  2499,  2749,  3024,  3327,  3660,  4026,  4428,  4871,  5358,
+   5894,  6484,  7132,  7845,  8630,  9493, 10442, 11487, 12635, 13899,
+  15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767,
+};
+static const int16_t maxAdpcmStep = (sizeof(adpcmStep) >> 1) - 1;
+
+AdpcmDecoder::AdpcmDecoder(int16_t initialPredictor, int16_t initialStep)
+: predictor(initialPredictor), index(clamp<int8_t>(initialStep, 0, maxAdpcmStep))
+{
+  // initializers only
+}
+
+int16_t AdpcmDecoder::getNextSample(uint8_t value)
+{
+  int16_t step = adpcmStep[index];
+  int32_t delta = step >> 3;
+  if (value & 0x04) delta += step;
+  if (value & 0x02) delta += step >> 1;
+  if (value & 0x01) delta += step >> 2;
+  if (value & 0x08) delta = -delta;
+  /*
+  // This implementation is simpler and obeys the spec, but it suffers from low-bit rounding
+  // errors that introduce a slow DC drift that causes looping to produce pops.
+  int32_t delta = (int32_t(value & 0x08 ? -step : step) * ((value << 1 & 0x0f) + 0x01)) >> 3;
+  */
+  if (predictor + delta == -0x8000) {
+    predictor = -0x8000;
+  } else {
+    predictor = clamp<int16_t>(predictor + delta, -0x7fff, 0x7fff);
+  }
+  index = clamp<int8_t>(index + adpcmIndex[value & 0x07], 0, maxAdpcmStep);
+  return predictor;
+}
+
+std::vector<int16_t> AdpcmDecoder::decodeFile(const std::vector<char>& data, uint32_t offset, uint32_t length)
+{
+  if (!length) {
+    length = data.size() - offset;
+  }
+  AdpcmDecoder adpcm(parseInt<int16_t>(data, offset), parseInt<int16_t>(data, offset + 2));
+  return adpcm.decode(data, offset + 4, length - 4);
+}
+
+std::vector<int16_t> AdpcmDecoder::decode(const std::vector<char>& data, uint32_t offset, uint32_t length)
+{
+  if (!length) {
+    length = data.size() - offset;
+  }
+  std::vector<int16_t> sample;
+  sample.reserve(length << 1);
+  for (int i = 0; i < length; i++) {
+    sample.push_back(getNextSample(data[offset + i] & 0x0f));
+    sample.push_back(getNextSample(uint8_t(data[offset + i] & 0xf0) >> 4));
+  }
+  return sample;
+}
+

--- /dev/null
+++ b/src/in_2sf/spu/adpcmdecoder.h
@@ -1,1 +1,22 @@
+#ifndef ADPCMDECODER_H
+#define ADPCMDECODER_H
 
+#include <vector>
+#include <cstdint>
+
+class AdpcmDecoder
+{
+private:
+  int16_t predictor;
+  int8_t index;
+
+public:
+  AdpcmDecoder(int16_t initialPredictor, int16_t initialStep);
+  int16_t getNextSample(uint8_t value);
+
+  std::vector<int16_t> decode(const std::vector<char>& data, uint32_t offset = 0, uint32_t length = 0);
+  static std::vector<int16_t> decodeFile(const std::vector<char>& data, uint32_t offset = 0, uint32_t length = 0);
+};
+
+#endif
+

--- /dev/null
+++ b/src/in_2sf/spu/interpolator.cpp
@@ -1,1 +1,86 @@
+#include "interpolator.h"
+#include <cmath>
+#ifndef M_PI
+#define M_PI 3.14159265358979323846
+#endif
 
+static LinearInterpolator* iLin = new LinearInterpolator;
+
+// Keep in the same order as SPUInterpolationMode
+IInterpolator* IInterpolator::allInterpolators[4] = {
+  nullptr,
+  iLin,
+  new CosineInterpolator,
+  new SharpIInterpolator
+};
+
+static inline int32_t lerp(int32_t left, int32_t right, double weight)
+{
+  return (left * (1 - weight)) + (right * weight);
+}
+
+int32_t LinearInterpolator::interpolate(const std::vector<int32_t>& data, double time) const
+{
+  if (time < 0) {
+    return 0;
+  }
+  return lerp(data[time], data[time + 1], time - std::floor(time));
+}
+
+CosineInterpolator::CosineInterpolator()
+{
+  for(int i = 0; i < 8192; i++) {
+    lut[i] = (1.0 - std::cos(M_PI * i / 8192.0) * M_PI) * 0.5;
+  }
+}
+
+int32_t CosineInterpolator::interpolate(const std::vector<int32_t>& data, double time) const
+{
+  if (time < 0) {
+    return 0;
+  }
+  int32_t left = data[time];
+  int32_t right = data[time + 1];
+  double weight = time - std::floor(time);
+  return lut[size_t(weight * 8192)] * (right - left) + right;
+}
+
+int32_t SharpIInterpolator::interpolate(const std::vector<int32_t>& data, double time) const
+{
+  if (time <= 2) {
+    return iLin->interpolate(data, time);
+  }
+
+  size_t index = size_t(time);
+  int left = data[index - 1];
+  int sample = data[index];
+  int right = data[index + 1];
+  if ((sample >= left) == (sample >= right)) {
+    // Always preserve extrema as-is
+    return sample;
+  }
+  int left2 = data[index - 2];
+  int right2 = data[index + 2];
+  double subsample = time - std::floor(time);
+  if ((right > right2) == (right > sample) || (left > left2) == (left > sample)) {
+    // Wider history window is non-monotonic
+    return lerp(sample, right, subsample);
+  }
+
+  // Include a linear interpolation of the surrounding samples to try to smooth out single-sample errors
+  double linear = lerp(left, right, 1.0 + subsample);
+  // Projection approaching from the left
+  double mLeft = sample - left;
+  double pLeft = sample + mLeft * subsample;
+  // Projection approaching from the right
+  double negSubsample = 1 - subsample;
+  double mRight = right - sample;
+  double pRight = right - mRight * negSubsample;
+  int32_t result = (mLeft * negSubsample + mRight * subsample + linear) / 3;
+  if ((left <= result) != (result <= right)) {
+    // If the result isn't monotonic, fall back to linear
+    return lerp(sample, right, subsample);
+  }
+  return result;
+}
+

--- /dev/null
+++ b/src/in_2sf/spu/interpolator.h
@@ -1,1 +1,42 @@
+#ifndef TWOSF2WAV_INTERPOLATOR_H
+#define TWOSF2WAV_INTERPOLATOR_H
 
+#include <vector>
+#include <cstdint>
+
+class IInterpolator
+{
+public:
+  virtual ~IInterpolator() {}
+
+  virtual int32_t interpolate(const std::vector<int32_t>& data, double time) const = 0;
+
+  static IInterpolator* allInterpolators[4];
+};
+
+class LinearInterpolator : public IInterpolator
+{
+public:
+  virtual int32_t interpolate(const std::vector<int32_t>& data, double time) const;
+};
+
+class CosineInterpolator : public IInterpolator
+{
+public:
+  CosineInterpolator();
+
+  virtual int32_t interpolate(const std::vector<int32_t>& data, double time) const;
+
+private:
+  double lut[8192];
+};
+
+class SharpIInterpolator : public IInterpolator
+{
+public:
+  virtual int32_t interpolate(const std::vector<int32_t>& data, double time) const;
+};
+
+
+#endif
+

--- /dev/null
+++ b/src/in_2sf/spu/samplecache.cpp
@@ -1,1 +1,33 @@
+#include "samplecache.h"
 
+static inline constexpr uint64_t makeKey(uint32_t base, uint16_t loop, uint32_t length)
+{
+  return
+    // has to be 32-bit aligned, so 2 low bits aren't needed
+    // has to fit in the memory map, so high 7 bits aren't needed
+    (uint64_t(base & 0x01FFFFFC) >> 2) |
+    // loop uses the full 16 bits
+    uint64_t(loop << 23) |
+    // max length is 21 bits
+    (uint64_t(length & 0x1FFFFF) << 39);
+}
+
+const SampleData& SampleCache::getSample(uint32_t baseAddr, uint16_t loopStartWords, uint32_t loopLengthWords, SampleData::Format format)
+{
+  uint64_t key = makeKey(baseAddr, loopStartWords, loopLengthWords);
+  auto iter = samples.find(key);
+  if (iter == samples.end()) {
+    iter = samples.emplace(
+      std::piecewise_construct,
+      std::forward_as_tuple(key),
+      std::forward_as_tuple(baseAddr, loopStartWords << 2, (loopStartWords + loopLengthWords) << 2, format)
+    ).first;
+  }
+  return iter->second;
+}
+
+void SampleCache::clear()
+{
+  samples.clear();
+}
+

--- /dev/null
+++ b/src/in_2sf/spu/samplecache.h
@@ -1,1 +1,17 @@
+#ifndef TWOSF2WAV_SAMPLECACHE_H
+#define TWOSF2WAV_SAMPLECACHE_H
 
+#include <unordered_map>
+#include "sampledata.h"
+
+class SampleCache {
+public:
+  const SampleData& getSample(uint32_t baseAddr, uint16_t loopStartWords, uint32_t loopLengthWords, SampleData::Format format);
+  void clear();
+
+private:
+  std::unordered_map<uint64_t, SampleData> samples;
+};
+
+#endif
+

--- /dev/null
+++ b/src/in_2sf/spu/sampledata.cpp
@@ -1,1 +1,87 @@
+#include "sampledata.h"
+#include "adpcmdecoder.h"
+#include "interpolator.h"
+#include "../desmume/MMU.h"
 
+SampleData::SampleData()
+: std::vector<int32_t>(), baseAddr(0), loopStart(0), loopLength(0)
+{
+  // initializers only
+}
+
+SampleData::SampleData(uint32_t baseAddr, uint16_t loopStart, uint32_t loopLength, Format format)
+: std::vector<int32_t>(), baseAddr(baseAddr), loopStart(loopStart), loopLength(loopLength)
+{
+  if (format == Pcm8) {
+    loadPcm8();
+  } else if (format == Pcm16) {
+    loadPcm16();
+  } else {
+    loadAdpcm();
+  }
+}
+
+void SampleData::loadPcm8()
+{
+  loopStart += 3;
+  resize(loopStart + (loopLength << 2));
+  for (int i = 3; i < loopStart; i++) {
+    (*this)[i] = int8_t(_MMU_read08<ARMCPU_ARM7, MMU_AT_DEBUG>(baseAddr + i - 3)) << 8;
+  }
+  uint32_t length = loopStart + loopLength;
+  for (int i = loopStart; i < length; i++) {
+    (*this)[i] = (*this)[length + i] = int8_t(_MMU_read08<ARMCPU_ARM7, MMU_AT_DEBUG>(baseAddr + i - 3)) << 8;
+  }
+}
+
+void SampleData::loadPcm16()
+{
+  loopStart >>= 1;
+  loopLength >>= 1;
+  loopStart += 3;
+  resize(loopStart + (loopLength << 2));
+  uint32_t addr = baseAddr;
+  for (int i = 3; i < loopStart; i++) {
+    (*this)[i] = int16_t(_MMU_read16<ARMCPU_ARM7, MMU_AT_DEBUG>(addr));
+    addr += 2;
+  }
+  uint32_t length = loopStart + loopLength;
+  for (int i = loopStart; i < length; i++) {
+    (*this)[i] = (*this)[length + i] = int16_t(_MMU_read16<ARMCPU_ARM7, MMU_AT_DEBUG>(addr));
+    addr += 2;
+  }
+}
+
+void SampleData::loadAdpcm()
+{
+  uint32_t length = loopStart + loopLength;
+  loopStart = ((loopStart - 4) << 1) + 11;
+  loopLength <<= 1;
+  resize(loopStart + (loopLength << 2));
+  AdpcmDecoder adpcm(
+    int16_t(_MMU_read16<ARMCPU_ARM7, MMU_AT_DEBUG>(baseAddr)),
+    int16_t(_MMU_read16<ARMCPU_ARM7, MMU_AT_DEBUG>(baseAddr + 2))
+  );
+  int j = 11;
+  for (int i = 4; i < length; i++) {
+    uint8_t data = uint8_t(_MMU_read08<ARMCPU_ARM7, MMU_AT_DEBUG>(baseAddr + i));
+    (*this)[j++] = adpcm.getNextSample(uint8_t(data & 0x0f));
+    (*this)[j++] = adpcm.getNextSample(uint8_t(data & 0xf0) >> 4);
+  }
+  uint32_t loopEnd = loopStart + loopLength;
+  for (j = loopStart; j < loopEnd; j++) {
+    (*this)[j + loopLength] = (*this)[j];
+  }
+}
+
+int32_t SampleData::sampleAt(double time, IInterpolator* interp) const
+{
+  if (!baseAddr) {
+    return 0;
+  }
+  if (!interp) {
+    return (*this)[uint32_t(time)];
+  }
+  return interp->interpolate(*this, time);
+}
+

--- /dev/null
+++ b/src/in_2sf/spu/sampledata.h
@@ -1,1 +1,39 @@
+#ifndef TWOSF2WAV_SAMPLEDATA_H
+#define TWOSF2WAV_SAMPLEDATA_H
 
+#include <vector>
+#include <cstdint>
+class IInterpolator;
+
+class SampleData : public std::vector<int32_t>
+{
+public:
+  enum Format {
+    Pcm8,
+    Pcm16,
+    Adpcm
+  };
+
+  SampleData();
+  SampleData(uint32_t baseAddr, uint16_t loopStart, uint32_t loopLength, Format format);
+  SampleData(const SampleData&) = default;
+  SampleData(SampleData&&) = default;
+  ~SampleData() = default;
+
+  SampleData& operator=(const SampleData&) = default;
+  SampleData& operator=(SampleData&&) = default;
+
+  int32_t sampleAt(double time, IInterpolator* interp = nullptr) const;
+
+  uint32_t baseAddr;
+  uint16_t loopStart;
+  uint32_t loopLength;
+
+private:
+  void loadPcm8();
+  void loadPcm16();
+  void loadAdpcm();
+};
+
+#endif
+

--- /dev/null
+++ b/src/in_gsf/GNUmakefile
@@ -1,1 +1,9 @@
+../in_gsf.dll: $(patsubst %.cpp, %.obj, $(wildcard vbam/*/*.cpp *.cpp)) ../in_xsf_framework.lib
+	$(WINE) link.exe /nologo /dll /machine:x86 user32.lib libucrt.lib libvcruntime.lib libcmt.lib libcpmt.lib /out:$@ $^
 
+%.obj: %.cpp $(wildcard vbam/*/*.h ../in_xsf_framework/*.h) GNUmakefile
+	$(WINE) cl.exe /nologo /std:c++latest /MT /DUNICODE /D_UNICODE /DNDEBUG /O2 /EHsc /I ../in_xsf_framework /I ../in_xsf_framework/zlib /c /Fo$@ $<
+
+clean:
+	rm -f ../in_gsf.dll ../in_gsf.exp ../in_gsf.lib *.obj vbam/*/*.obj
+

--- /dev/null
+++ b/src/in_ncsf/GNUmakefile
@@ -1,1 +1,9 @@
+../in_ncsf.dll: $(patsubst %.cpp, %.obj, $(wildcard SSEQPlayer/*.cpp *.cpp)) ../in_xsf_framework.lib
+	$(WINE) link.exe /nologo /dll /machine:x86 user32.lib libucrt.lib libvcruntime.lib libcmt.lib libcpmt.lib /out:$@ $^
 
+%.obj: %.cpp $(wildcard SSEQPlayer/*.h ../in_xsf_framework/*.h) GNUmakefile
+	$(WINE) cl.exe /nologo /std:c++latest /MT /DUNICODE /D_UNICODE /DNDEBUG /O2 /EHsc /I ../in_xsf_framework /I ../in_xsf_framework/zlib /I SSEQPlayer /c /Fo$@ $<
+
+clean:
+	rm -f ../in_ncsf.dll ../in_ncsf.exp ../in_ncsf.lib *.obj SSEQPlayer/*.obj
+

--- /dev/null
+++ b/src/in_snsf/GNUmakefile
@@ -1,1 +1,9 @@
+../in_snsf.dll: $(patsubst %.cpp, %.obj, $(wildcard snes9x/*.cpp snes9x/*/*.cpp *.cpp)) ../in_xsf_framework.lib
+	$(WINE) link.exe /nologo /dll /machine:x86 user32.lib libucrt.lib libvcruntime.lib libcmt.lib libcpmt.lib /out:$@ $^
 
+%.obj: %.cpp $(wildcard snes9x/*.h ../in_xsf_framework/*.h) GNUmakefile
+	$(WINE) cl.exe /nologo /std:c++latest /MT /DUNICODE /D_UNICODE /DNDEBUG /O2 /EHsc /I ../in_xsf_framework /I ../in_xsf_framework/zlib /I snes9x /c /Fo$@ $<
+
+clean:
+	rm -f ../in_snsf.dll ../in_snsf.exp ../in_snsf.lib *.obj snes9x/*.obj snes9x/*/*.obj
+

--- /dev/null
+++ b/src/in_xsf_framework/GNUmakefile
@@ -1,1 +1,13 @@
+../in_xsf_framework.lib: $(patsubst %.cpp, %.obj, $(wildcard *.cpp)) $(patsubst %.c, %.obj, $(wildcard zlib/*.c))
+	$(WINE) lib.exe /nologo /out:$@ $^
 
+%.obj: %.c
+	$(WINE) cl.exe /nologo /std:c11 /MT /DUNICODE /D_UNICODE /DNDEBUG /DWINAMP_PLUGIN /O2 /EHsc /c /Fo$@ $<
+
+%.obj: %.cpp $(wildcard *.h) GNUmakefile
+	$(WINE) cl.exe /nologo /std:c++latest /MT /DUNICODE /D_UNICODE /DNDEBUG /DWINAMP_PLUGIN /I zlib /O2 /EHsc /c /Fo$@ $<
+
+clean:
+	rm -f ../in_xsf_framework.lib *.obj zlib/*.obj winamp/*.obj
+
+

--- a/src/in_xsf_framework/TagList.cpp
+++ b/src/in_xsf_framework/TagList.cpp
@@ -9,6 +9,8 @@
 
 #include <algorithm>
 #include "TagList.h"
+
+using namespace std::placeholders;
 
 eq_str TagList::eqstr;
 
@@ -27,7 +29,7 @@
 
 bool TagList::Exists(const std::string &name) const
 {
-	return std::find_if(this->tagsOrder.begin(), this->tagsOrder.end(), std::bind2nd(TagList::eqstr, name)) != this->tagsOrder.end();
+	return std::find_if(this->tagsOrder.begin(), this->tagsOrder.end(), std::bind(TagList::eqstr, _1, name)) != this->tagsOrder.end();
 }
 
 std::string TagList::operator[](const std::string &name) const
@@ -40,7 +42,7 @@
 
 std::string &TagList::operator[](const std::string &name)
 {
-	auto tag = std::find_if(this->tagsOrder.begin(), this->tagsOrder.end(), std::bind2nd(TagList::eqstr, name));
+	auto tag = std::find_if(this->tagsOrder.begin(), this->tagsOrder.end(), std::bind(TagList::eqstr, _1, name));
 	if (tag == this->tagsOrder.end())
 	{
 		this->tagsOrder.push_back(name);
@@ -51,7 +53,7 @@
 
 void TagList::Remove(const std::string &name)
 {
-	auto tagOrder = std::find_if(this->tagsOrder.begin(), this->tagsOrder.end(), std::bind2nd(TagList::eqstr, name));
+	auto tagOrder = std::find_if(this->tagsOrder.begin(), this->tagsOrder.end(), std::bind(TagList::eqstr, _1, name));
 	if (tagOrder != this->tagsOrder.end())
 		this->tagsOrder.erase(tagOrder);
 	if (this->tags.count(name))

--- a/src/in_xsf_framework/XSFConfig_Winamp.cpp
+++ b/src/in_xsf_framework/XSFConfig_Winamp.cpp
@@ -8,8 +8,8 @@
 
 #include "XSFConfig.h"
 #include "XSFCommon.h"
-#include <winamp/in2.h>
-#include <winamp/wa_ipc.h>
+#include "winamp/in2.h"
+#include "winamp/wa_ipc.h"
 
 extern In_Module inMod;
 

--- a/src/in_xsf_framework/XSFFile.cpp
+++ b/src/in_xsf_framework/XSFFile.cpp
@@ -9,7 +9,7 @@
 #include <algorithm>
 #include <functional>
 #include <stdexcept>
-#include <zlib.h>
+#include "zlib.h"
 #include "XSFFile.h"
 #include "XSFCommon.h"
 #include "convert.h"
@@ -25,8 +25,9 @@
 // The whitespace trimming was modified from the following answer on Stack Overflow:
 // http://stackoverflow.com/a/217605
 
-struct IsWhitespace : std::unary_function<char, bool>
-{
+struct IsWhitespace
+{
+  using argument_type = char;;
 	bool operator()(const char &x) const
 	{
 		return x >= 0x01 && x <= 0x20;

--- a/src/in_xsf_framework/XSFPlayer.h
+++ b/src/in_xsf_framework/XSFPlayer.h
@@ -13,7 +13,7 @@
 
 #ifdef WINAMP_PLUGIN
 # include "windowsh_wrapper.h"
-# include <winamp/out.h>
+# include "winamp/out.h"
 #endif
 
 // This is a base class, a player for a specific type of xSF should inherit from this.

--- a/src/in_xsf_framework/eqstr.h
+++ b/src/in_xsf_framework/eqstr.h
@@ -15,9 +15,9 @@
 #include <algorithm>
 #include <climits>
 
-struct eq_str : std::binary_function<std::string, std::string, bool>
+struct eq_str
 {
-	struct eq_char : std::binary_function<char, char, bool>
+	struct eq_char
 	{
 		const char *tab;
 		eq_char(const char *t) : tab(t) { }

--- a/src/in_xsf_framework/in_xsf.cpp
+++ b/src/in_xsf_framework/in_xsf.cpp
@@ -10,8 +10,8 @@
 #include "XSFConfig.h"
 #include "XSFCommon.h"
 #include "windowsh_wrapper.h"
-#include <winamp/in2.h>
-#include <winamp/wa_ipc.h>
+#include "winamp/in2.h"
+#include "winamp/wa_ipc.h"
 
 #if (defined(__GNUC__) || defined(__clang__)) && !defined(_LIBCPP_VERSION)
 std::locale::id std::codecvt<char16_t, char, mbstate_t>::id;

--- a/src/in_xsf_framework/ltstr.h
+++ b/src/in_xsf_framework/ltstr.h
@@ -15,9 +15,9 @@
 #include <algorithm>
 #include <climits>
 
-struct lt_str : std::binary_function<std::string, std::string, bool>
+struct lt_str
 {
-	struct lt_char : std::binary_function<char, char, bool>
+	struct lt_char
 	{
 		const char *tab;
 		lt_char(const char *t) : tab(t) { }

--- /dev/null
+++ b/src/in_xsf_framework/winamp/in2.h
@@ -1,1 +1,138 @@
+#ifndef NULLSOFT_WINAMP_IN2H

+#define NULLSOFT_WINAMP_IN2H

+#include "out.h"

+

+// note: exported symbol is now winampGetInModule2.

+

+#define IN_UNICODE 0x0F000000

+

+#ifdef UNICODE_INPUT_PLUGIN

+#define in_char wchar_t

+#define IN_VER (IN_UNICODE | 0x100)

+#else

+#define in_char char

+#define IN_VER 0x100

+#endif

+

+#define IN_MODULE_FLAG_USES_OUTPUT_PLUGIN 1

+// By default, Winamp assumes that your input plugin wants to use Winamp's EQ, and doesn't do replay gain

+// if you handle any of these yourself (EQ, Replay Gain adjustments), then set these flags accordingly

+#define IN_MODULE_FLAG_EQ 2 // set this if you do your own EQ

+#define IN_MODULE_FLAG_REPLAYGAIN 8 // set this if you adjusted volume for replay gain

+                                                                        // for tracks with no replay gain metadata, you should clear this flag

+                                                                        // UNLESS you handle "non_replaygain" gain adjustment yourself

+#define IN_MODULE_FLAG_REPLAYGAIN_PREAMP 16 // use this if you queried for the replay gain preamp parameter and used it

+                                                                                        // this parameter is new to 5.54

+typedef struct 

+{

+    int version;                // module type (IN_VER)

+    char *description;          // description of module, with version string

+

+    HWND hMainWindow;           // winamp's main window (filled in by winamp)

+    HINSTANCE hDllInstance;     // DLL instance handle (Also filled in by winamp)

+

+    char *FileExtensions;       // "mp3\0Layer 3 MPEG\0mp2\0Layer 2 MPEG\0mpg\0Layer 1 MPEG\0"

+                                // May be altered from Config, so the user can select what they want

+

+    int is_seekable;            // is this stream seekable?

+    int UsesOutputPlug;         // does this plug-in use the output plug-ins? (musn't ever change, ever :)

+                                                    // note that this has turned into a "flags" field

+                                                    // see IN_MODULE_FLAG_*

+

+    void (*Config)(HWND hwndParent); // configuration dialog

+    void (*About)(HWND hwndParent);  // about dialog

+

+    void (*Init)();             // called at program init

+    void (*Quit)();             // called at program quit

+

+#define GETFILEINFO_TITLE_LENGTH 2048

+    void (*GetFileInfo)(const in_char *file, in_char *title, int *length_in_ms); // if file == NULL, current playing is used

+

+#define INFOBOX_EDITED 0

+#define INFOBOX_UNCHANGED 1

+    int (*InfoBox)(const in_char *file, HWND hwndParent);

+

+    int (*IsOurFile)(const in_char *fn);    // called before extension checks, to allow detection of mms://, etc

+    // playback stuff

+    int (*Play)(const in_char *fn);     // return zero on success, -1 on file-not-found, some other value on other (stopping winamp) error

+    void (*Pause)();            // pause stream

+    void (*UnPause)();          // unpause stream

+    int (*IsPaused)();          // ispaused? return 1 if paused, 0 if not

+    void (*Stop)();             // stop (unload) stream

+

+    // time stuff

+    int (*GetLength)();         // get length in ms

+    int (*GetOutputTime)();     // returns current output time in ms. (usually returns outMod->GetOutputTime()

+    void (*SetOutputTime)(int time_in_ms);  // seeks to point in stream (in ms). Usually you signal your thread to seek, which seeks and calls outMod->Flush()..

+

+    // volume stuff

+    void (*SetVolume)(int volume);  // from 0 to 255.. usually just call outMod->SetVolume

+    void (*SetPan)(int pan);    // from -127 to 127.. usually just call outMod->SetPan

+

+    // in-window builtin vis stuff

+

+    void (*SAVSAInit)(int maxlatency_in_ms, int srate);     // call once in Play(). maxlatency_in_ms should be the value returned from outMod->Open()

+    // call after opening audio device with max latency in ms and samplerate

+    void (*SAVSADeInit)();  // call in Stop()

+

+

+    // simple vis supplying mode

+    void (*SAAddPCMData)(void *PCMData, int nch, int bps, int timestamp);

+                                            // sets the spec data directly from PCM data

+                                            // quick and easy way to get vis working :)

+                                            // needs at least 576 samples :)

+

+    // advanced vis supplying mode, only use if you're cool. Use SAAddPCMData for most stuff.

+    int (*SAGetMode)();     // gets csa (the current type (4=ws,2=osc,1=spec))

+                            // use when calling SAAdd()

+    int (*SAAdd)(void *data, int timestamp, int csa); // sets the spec data, filled in by winamp

+

+

+    // vis stuff (plug-in)

+    // simple vis supplying mode

+    void (*VSAAddPCMData)(void *PCMData, int nch, int bps, int timestamp); // sets the vis data directly from PCM data

+                                            // quick and easy way to get vis working :)

+                                            // needs at least 576 samples :)

+

+    // advanced vis supplying mode, only use if you're cool. Use VSAAddPCMData for most stuff.

+    int (*VSAGetMode)(int *specNch, int *waveNch); // use to figure out what to give to VSAAdd

+    int (*VSAAdd)(void *data, int timestamp); // filled in by winamp, called by plug-in

+

+

+    // call this in Play() to tell the vis plug-ins the current output params.

+    void (*VSASetInfo)(int srate, int nch); // <-- Correct (benski, dec 2005).. old declaration had the params backwards

+

+

+    // dsp plug-in processing:

+    // (filled in by winamp, calld by input plug)

+

+    // returns 1 if active (which means that the number of samples returned by dsp_dosamples

+    // could be greater than went in.. Use it to estimate if you'll have enough room in the

+    // output buffer

+    int (*dsp_isactive)();

+

+    // returns number of samples to output. This can be as much as twice numsamples.

+    // be sure to allocate enough buffer for samples, then.

+    int (*dsp_dosamples)(short int *samples, int numsamples, int bps, int nch, int srate);

+

+

+    // eq stuff

+    void (*EQSet)(int on, char data[10], int preamp); // 0-64 each, 31 is +0, 0 is +12, 63 is -12. Do nothing to ignore.

+

+    // info setting (filled in by winamp)

+    void (*SetInfo)(int bitrate, int srate, int stereo, int synched); // if -1, changes ignored? :)

+

+    Out_Module *outMod; // filled in by winamp, optionally used :)

+} In_Module;

+

+// return values from the winampUninstallPlugin(HINSTANCE hdll, HWND parent, int param)

+// which determine if we can uninstall the plugin immediately or on winamp restart

+//

+// uninstall support was added from 5.0+ and uninstall now support from 5.5+

+// it is down to you to ensure that if uninstall now is returned that it will not cause a crash

+// (ie don't use if you've been subclassing the main window)

+#define IN_PLUGIN_UNINSTALL_NOW    0x1

+#define IN_PLUGIN_UNINSTALL_REBOOT 0x0

+

+#endif

 

--- /dev/null
+++ b/src/in_xsf_framework/winamp/out.h
@@ -1,1 +1,74 @@
+#ifndef NULLSOFT_OUTH

+#define NULLSOFT_OUTH

+#include <windows.h>

+#include <stddef.h>

+// ids:

+// waveout: 32

+// gapless: 64

+// xfade: 63

+// disk: 33

+// dsound: 38

+// NULL: 65

+// mm2: 69

+

+#if defined(_MSC_VER) && (_MSC_VER <= 1200)

+typedef int intptr_t;

+#endif

+

+#define OUT_VER 0x10

+

+typedef struct

+{

+    int version;                // module version (OUT_VER)

+    char *description;          // description of module, with version string

+    intptr_t id;                        // module id. each input module gets its own. non-nullsoft modules should

+                                // be >= 65536.

+

+    HWND hMainWindow;           // winamp's main window (filled in by winamp)

+    HINSTANCE hDllInstance;     // DLL instance handle (filled in by winamp)

+

+    void (*Config)(HWND hwndParent); // configuration dialog

+    void (*About)(HWND hwndParent);  // about dialog

+

+    void (*Init)();             // called when loaded

+    void (*Quit)();             // called when unloaded

+

+    int (*Open)(int samplerate, int numchannels, int bitspersamp, int bufferlenms, int prebufferms);

+                    // returns >=0 on success, <0 on failure

+

+                    // NOTENOTENOTE: bufferlenms and prebufferms are ignored in most if not all output plug-ins.

+                    //    ... so don't expect the max latency returned to be what you asked for.

+                    // returns max latency in ms (0 for diskwriters, etc)

+                    // bufferlenms and prebufferms must be in ms. 0 to use defaults.

+                    // prebufferms must be <= bufferlenms

+                    // pass bufferlenms==-666 to tell the output plugin that it's clock is going to be used to sync video

+                    //   out_ds turns off silence-eating when -666 is passed

+

+    void (*Close)();    // close the ol' output device.

+

+    int (*Write)(char *buf, int len);

+                    // 0 on success. Len == bytes to write (<= 8192 always). buf is straight audio data.

+                    // 1 returns not able to write (yet). Non-blocking, always.

+

+    int (*CanWrite)();  // returns number of bytes possible to write at a given time.

+                        // Never will decrease unless you call Write (or Close, heh)

+

+    int (*IsPlaying)(); // non0 if output is still going or if data in buffers waiting to be

+                        // written (i.e. closing while IsPlaying() returns 1 would truncate the song

+

+    int (*Pause)(int pause); // returns previous pause state

+

+    void (*SetVolume)(int volume); // volume is 0-255

+    void (*SetPan)(int pan); // pan is -128 to 128

+

+    void (*Flush)(int t);   // flushes buffers and restarts output at time t (in ms)

+                            // (used for seeking)

+

+    int (*GetOutputTime)(); // returns played time in MS

+    int (*GetWrittenTime)(); // returns time written in MS (used for synching up vis stuff)

+

+} Out_Module;

+

+

+#endif

 

--- /dev/null
+++ b/src/in_xsf_framework/winamp/wa_ipc.h
@@ -1,1 +1,2471 @@
+/*

+** Copyright (C) 1997-2008 Nullsoft, Inc.

+**

+** This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held

+** liable for any damages arising from the use of this software.

+**

+** Permission is granted to anyone to use this software for any purpose, including commercial applications, and to

+** alter it and redistribute it freely, subject to the following restrictions:

+**

+**   1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software.

+**      If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.

+**

+**   2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.

+**

+**   3. This notice may not be removed or altered from any source distribution.

+**

+*/

+

+#ifndef _WA_IPC_H_

+#define _WA_IPC_H_

+

+#include <windows.h>

+#include <stddef.h>

+#if defined(_MSC_VER) && (_MSC_VER <= 1200)

+typedef int intptr_t;

+#endif

+/*

+** This is the modern replacement for the classic 'frontend.h'. Most of these

+** updates are designed for in-process use, i.e. from a plugin.

+**

+*/

+

+/* Most of the IPC_* messages involve sending the message in the form of:

+** result = SendMessage(hwnd_winamp,WM_WA_IPC,(parameter),IPC_*);

+** Where different then this is specified (typically with WM_COPYDATA variants)

+**

+** When you use SendMessage(hwnd_winamp,WM_WA_IPC,(parameter),IPC_*) and specify a IPC_*

+** which is not currently implemented/supported by the Winamp version being used then it

+** will return 1 for 'result'. This is a good way of helping to check if an api being

+** used which returns a function pointer, etc is even going to be valid.

+*/

+

+#define WM_WA_IPC WM_USER

+

+#define WINAMP_VERSION_MAJOR(winampVersion) ((winampVersion & 0x0000FF00) >> 12)

+#define WINAMP_VERSION_MINOR(winampVersion) (winampVersion & 0x000000FF)  // returns, i.e. 0x12 for 5.12 and 0x10 for 5.1...

+

+

+#define IPC_GETVERSION 0

+/* int version = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETVERSION);

+**

+** The version returned will be 0x20yx for Winamp 2.yx.

+** Versions previous to Winamp 2.0 typically (but not always) use 0x1zyx for 1.zx.

+** Just a bit weird but that's the way it goes.

+**

+** For Winamp 5.x it uses the format 0x50yx for Winamp 5.yx

+** e.g.   5.01 -> 0x5001

+**        5.09 -> 0x5009

+**        5.1  -> 0x5010

+**

+** Notes: For 5.02 this api will return the same value as for a 5.01 build.

+**        For 5.07 this api will return the same value as for a 5.06 build.

+*/

+

+

+#define IPC_GETVERSIONSTRING 1

+

+

+#define IPC_GETREGISTEREDVERSION 770

+/* (requires Winamp 5.0+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETREGISTEREDVERSION);

+**

+** This will open the Winamp Preferences and show the Winamp Pro page.

+*/

+

+

+typedef struct {

+  const char *filename;

+  const char *title;

+  int length;

+} enqueueFileWithMetaStruct; // send this to a IPC_PLAYFILE in a non WM_COPYDATA,

+// and you get the nice desired result. if title is NULL, it is treated as a "thing",

+// otherwise it's assumed to be a file (for speed)

+

+typedef struct {

+  const wchar_t *filename;

+  const wchar_t *title;

+  int length;

+} enqueueFileWithMetaStructW;

+

+#define IPC_PLAYFILE 100  // dont be fooled, this is really the same as enqueufile

+#define IPC_ENQUEUEFILE 100

+#define IPC_PLAYFILEW 1100

+#define IPC_ENQUEUEFILEW 1100

+/* This is sent as a WM_COPYDATA with IPC_PLAYFILE as the dwData member and the string

+** of the file / playlist to be enqueued into the playlist editor as the lpData member.

+** This will just enqueue the file or files since you can use this to enqueue a playlist.

+** It will not clear the current playlist or change the playback state.

+**

+** COPYDATASTRUCT cds = {0};

+**   cds.dwData = IPC_ENQUEUEFILE;

+**   cds.lpData = (void*)"c:\\test\\folder\\test.mp3";

+**   cds.cbData = lstrlen((char*)cds.lpData)+1;  // include space for null char

+**   SendMessage(hwnd_winamp,WM_COPYDATA,0,(LPARAM)&cds);

+**

+**

+** With 2.9+ and all of the 5.x versions you can send this as a normal WM_WA_IPC

+** (non WM_COPYDATA) with an enqueueFileWithMetaStruct as the param.

+** If the title member is null then it is treated as a "thing" otherwise it will be

+** assumed to be a file (for speed).

+**

+** enqueueFileWithMetaStruct eFWMS = {0};

+**   eFWMS.filename = "c:\\test\\folder\\test.mp3";

+**   eFWMS.title = "Whipping Good";

+**   eFWMS.length = 300;  // this is the number of seconds for the track

+**   SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&eFWMS,IPC_ENQUEUEFILE);

+*/

+

+

+#define IPC_DELETE 101

+#define IPC_DELETE_INT 1101

+/* SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_DELETE);

+** Use this api to clear Winamp's internal playlist.

+** You should not need to use IPC_DELETE_INT since it is used internally by Winamp when

+** it is dealing with some lame Windows Explorer issues (hard to believe that!).

+*/

+

+

+#define IPC_STARTPLAY 102

+#define IPC_STARTPLAY_INT 1102

+/* SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_STARTPLAY);

+** Sending this will start playback and is almost the same as hitting the play button.

+** The IPC_STARTPLAY_INT version is used internally and you should not need to use it

+** since it won't be any fun.

+*/

+

+

+#define IPC_CHDIR 103

+/* This is sent as a WM_COPYDATA type message with IPC_CHDIR as the dwData value and the

+** directory you want to change to as the lpData member.

+**

+** COPYDATASTRUCT cds = {0};

+**   cds.dwData = IPC_CHDIR;

+**   cds.lpData = (void*)"c:\\download";

+**   cds.cbData = lstrlen((char*)cds.lpData)+1; // include space for null char

+**   SendMessage(hwnd_winamp,WM_COPYDATA,0,(LPARAM)&cds);

+**

+** The above example will make Winamp change to the directory 'C:\download'.

+*/

+

+

+#define IPC_ISPLAYING 104

+/* int res = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_ISPLAYING);

+** This is sent to retrieve the current playback state of Winamp.

+** If it returns 1, Winamp is playing.

+** If it returns 3, Winamp is paused.

+** If it returns 0, Winamp is not playing.

+*/

+

+

+#define IPC_GETOUTPUTTIME 105

+/* int res = SendMessage(hwnd_winamp,WM_WA_IPC,mode,IPC_GETOUTPUTTIME);

+** This api can return two different sets of information about current playback status.

+**

+** If mode = 0 then it will return the position (in ms) of the currently playing track.

+** Will return -1 if Winamp is not playing.

+**

+** If mode = 1 then it will return the current track length (in seconds).

+** Will return -1 if there are no tracks (or possibly if Winamp cannot get the length).

+**

+** If mode = 2 then it will return the current track length (in milliseconds).

+** Will return -1 if there are no tracks (or possibly if Winamp cannot get the length).

+*/

+

+

+#define IPC_JUMPTOTIME 106

+/* (requires Winamp 1.60+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,ms,IPC_JUMPTOTIME);

+** This api sets the current position (in milliseconds) for the currently playing song.

+** The resulting playback position may only be an approximate time since some playback

+** formats do not provide exact seeking e.g. mp3

+** This returns -1 if Winamp is not playing, 1 on end of file, or 0 if it was successful.

+*/

+

+

+#define IPC_GETMODULENAME 109

+#define IPC_EX_ISRIGHTEXE 666

+/* usually shouldnt bother using these, but here goes:

+** send a WM_COPYDATA with IPC_GETMODULENAME, and an internal

+** flag gets set, which if you send a normal WM_WA_IPC message with

+** IPC_EX_ISRIGHTEXE, it returns whether or not that filename

+** matches. lame, I know.

+*/

+

+

+#define IPC_WRITEPLAYLIST 120

+/* (requires Winamp 1.666+)

+** int cur = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_WRITEPLAYLIST);

+**

+** IPC_WRITEPLAYLIST will write the current playlist to '<winampdir>\\Winamp.m3u' and

+** will also return the current playlist position (see IPC_GETLISTPOS).

+**

+** This is kinda obsoleted by some of the newer 2.x api items but it still is good for

+** use with a front-end program (instead of a plug-in) and you want to see what is in the

+** current playlist.

+**

+** This api will only save out extended file information in the #EXTINF entry if Winamp

+** has already read the data such as if the file was played of scrolled into view. If

+** Winamp has not read the data then you will only find the file with its filepath entry

+** (as is the base requirements for a m3u playlist).

+*/

+

+

+#define IPC_SETPLAYLISTPOS 121

+/* (requires Winamp 2.0+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,position,IPC_SETPLAYLISTPOS)

+** IPC_SETPLAYLISTPOS sets the playlist position to the specified 'position'.

+** It will not change playback status or anything else. It will just set the current

+** position in the playlist and will update the playlist view if necessary.

+**

+** If you use SendMessage(hwnd_winamp,WM_COMMAND,MAKEWPARAM(WINAMP_BUTTON2,0),0);

+** after using IPC_SETPLAYLISTPOS then Winamp will start playing the file at 'position'.

+*/

+

+

+#define IPC_SETVOLUME 122

+/* (requires Winamp 2.0+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,volume,IPC_SETVOLUME);

+** IPC_SETVOLUME sets the volume of Winamp (between the range of 0 to 255).

+**

+** If you pass 'volume' as -666 then the message will return the current volume.

+** int curvol = SendMessage(hwnd_winamp,WM_WA_IPC,-666,IPC_SETVOLUME);

+*/

+

+

+#define IPC_GETVOLUME(hwnd_winamp) SendMessage(hwnd_winamp,WM_WA_IPC,-666,IPC_SETVOLUME)

+/* (requires Winamp 2.0+)

+** int curvol = IPC_GETVOLUME(hwnd_winamp);

+** This will return the current volume of Winamp or

+*/

+

+

+#define IPC_SETPANNING 123

+/* (requires Winamp 2.0+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,panning,IPC_SETPANNING);

+** IPC_SETPANNING sets the panning of Winamp from 0 (left) to 255 (right).

+**

+** At least in 5.x+ this works from -127 (left) to 127 (right).

+**

+** If you pass 'panning' as -666 to this api then it will return the current panning.

+** int curpan = SendMessage(hwnd_winamp,WM_WA_IPC,-666,IPC_SETPANNING);

+*/

+

+

+#define IPC_GETLISTLENGTH 124

+/* (requires Winamp 2.0+)

+** int length = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETLISTLENGTH);

+** IPC_GETLISTLENGTH returns the length of the current playlist as the number of tracks.

+*/

+

+

+#define IPC_GETLISTPOS 125

+/* (requires Winamp 2.05+)

+** int pos=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETLISTPOS);

+** IPC_GETLISTPOS returns the current playlist position (which is shown in the playlist

+** editor as a differently coloured text entry e.g is yellow for the classic skin).

+**

+** This api is a lot like IPC_WRITEPLAYLIST but a lot faster since it does not have to

+** write out the whole of the current playlist first.

+*/

+

+

+#define IPC_GETINFO 126

+/* (requires Winamp 2.05+)

+** int inf=SendMessage(hwnd_winamp,WM_WA_IPC,mode,IPC_GETINFO);

+** IPC_GETINFO returns info about the current playing song. The value

+** it returns depends on the value of 'mode'.

+** Mode      Meaning

+** ------------------

+** 0         Samplerate, in kilohertz (i.e. 44)

+** 1         Bitrate  (i.e. 128)

+** 2         Channels (i.e. 2)

+** 3 (5+)    Video LOWORD=w HIWORD=h

+** 4 (5+)    > 65536, string (video description)

+** 5 (5.25+) Samplerate, in hertz (i.e. 44100)

+*/

+

+

+#define IPC_GETEQDATA 127

+/* (requires Winamp 2.05+)

+** int data=SendMessage(hwnd_winamp,WM_WA_IPC,pos,IPC_GETEQDATA);

+** IPC_GETEQDATA queries the status of the EQ.

+** The value returned depends on what 'pos' is set to:

+** Value      Meaning

+** ------------------

+** 0-9        The 10 bands of EQ data. 0-63 (+20db - -20db)

+** 10         The preamp value. 0-63 (+20db - -20db)

+** 11         Enabled. zero if disabled, nonzero if enabled.

+** 12         Autoload. zero if disabled, nonzero if enabled.

+*/

+

+

+#define IPC_SETEQDATA 128

+/* (requires Winamp 2.05+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,pos,IPC_GETEQDATA);

+** SendMessage(hwnd_winamp,WM_WA_IPC,value,IPC_SETEQDATA);

+** IPC_SETEQDATA sets the value of the last position retrieved

+** by IPC_GETEQDATA. This is pretty lame, and we should provide

+** an extended version that lets you do a MAKELPARAM(pos,value).

+** someday...

+

+  new (2.92+):

+    if the high byte is set to 0xDB, then the third byte specifies

+    which band, and the bottom word specifies the value.

+*/

+

+

+#define IPC_ADDBOOKMARK 129

+#define IPC_ADDBOOKMARKW 131

+/* (requires Winamp 2.4+)

+** This is sent as a WM_COPYDATA using IPC_ADDBOOKMARK as the dwData value and the

+** directory you want to change to as the lpData member. This will add the specified

+** file / url to the Winamp bookmark list.

+**

+** COPYDATASTRUCT cds = {0};

+**   cds.dwData = IPC_ADDBOOKMARK;

+**   cds.lpData = (void*)"http://www.blah.com/listen.pls";

+**   cds.cbData = lstrlen((char*)cds.lpData)+1; // include space for null char

+**   SendMessage(hwnd_winamp,WM_COPYDATA,0,(LPARAM)&cds);

+**

+**

+** In Winamp 5.0+ we use this as a normal WM_WA_IPC and the string is null separated as

+** the filename and then the title of the entry.

+**

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(char*)"filename\0title\0",IPC_ADDBOOKMARK);

+**

+** This will notify the library / bookmark editor that a bookmark was added.

+** Note that using this message in this context does not actually add the bookmark.

+** Do not use, it is essentially just a notification type message :)

+*/

+

+

+#define IPC_INSTALLPLUGIN 130

+/* This is not implemented (and is very unlikely to be done due to safety concerns).

+** If it was then you could do a WM_COPYDATA with a path to a .wpz and it would then

+** install the plugin for you.

+**

+** COPYDATASTRUCT cds = {0};

+**   cds.dwData = IPC_INSTALLPLUGIN;

+**   cds.lpData = (void*)"c:\\path\\to\\file.wpz";

+**   cds.cbData = lstrlen((char*)cds.lpData)+1; // include space for null char

+**   SendMessage(hwnd_winamp,WM_COPYDATA,0,(LPARAM)&cds);

+*/

+

+

+#define IPC_RESTARTWINAMP 135

+/* (requires Winamp 2.2+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_RESTARTWINAMP);

+** IPC_RESTARTWINAMP will restart Winamp (isn't that obvious ? :) )

+** If this fails to make Winamp start after closing then there is a good chance one (or

+** more) of the currently installed plugins caused Winamp to crash on exit (either as a

+** silent crash or a full crash log report before it could call itself start again.

+*/

+

+

+#define IPC_ISFULLSTOP 400

+/* (requires winamp 2.7+ I think)

+** int ret=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_ISFULLSTOP);

+** This is useful for when you're an output plugin and you want to see if the stop/close

+** happening is a full stop or if you are just between tracks. This returns non zero if

+** it is a full stop or zero if it is just a new track.

+** benski> i think it's actually the other way around -

+**         !0 for EOF and 0 for user pressing stop

+*/

+

+

+#define IPC_INETAVAILABLE 242

+/* (requires Winamp 2.05+)

+** int val=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_INETAVAILABLE);

+** IPC_INETAVAILABLE will return 1 if an Internet connection is available for Winamp and

+** relates to the internet connection type setting on the main general preferences page

+** in the Winamp preferences.

+*/

+

+

+#define IPC_UPDTITLE 243

+/* (requires Winamp 2.2+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_UPDTITLE);

+** IPC_UPDTITLE will ask Winamp to update the information about the current title and

+** causes GetFileInfo(..) in the input plugin associated with the current playlist entry

+** to be called. This can be called such as when an input plugin is buffering a file so

+** that it can cause the buffer percentage to appear in the playlist.

+*/

+

+

+#define IPC_REFRESHPLCACHE 247

+/* (requires Winamp 2.2+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_REFRESHPLCACHE);

+** IPC_REFRESHPLCACHE will flush the playlist cache buffer and you send this if you want

+** Winamp to go refetch the titles for all of the entries in the current playlist.

+**

+** 5.3+: pass a wchar_t * string in wParam, and it'll do a strnicmp() before clearing the cache

+*/

+

+

+#define IPC_GET_SHUFFLE 250

+/* (requires Winamp 2.4+)

+** int val=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GET_SHUFFLE);

+** IPC_GET_SHUFFLE returns the status of the shuffle option.

+** If set then it will return 1 and if not set then it will return 0.

+*/

+

+

+#define IPC_GET_REPEAT 251

+/* (requires Winamp 2.4+)

+** int val=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GET_REPEAT);

+** IPC_GET_REPEAT returns the status of the repeat option.

+** If set then it will return 1 and if not set then it will return 0.

+*/

+

+

+#define IPC_SET_SHUFFLE 252

+/* (requires Winamp 2.4+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,value,IPC_SET_SHUFFLE);

+** IPC_SET_SHUFFLE sets the status of the shuffle option.

+** If 'value' is 1 then shuffle is turned on.

+** If 'value' is 0 then shuffle is turned off.

+*/

+

+

+#define IPC_SET_REPEAT 253

+/* (requires Winamp 2.4+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,value,IPC_SET_REPEAT);

+** IPC_SET_REPEAT sets the status of the repeat option.

+** If 'value' is 1 then shuffle is turned on.

+** If 'value' is 0 then shuffle is turned off.

+*/

+

+

+#define IPC_ENABLEDISABLE_ALL_WINDOWS 259 // 0xdeadbeef to disable

+/* (requires Winamp 2.9+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,(enable?0:0xdeadbeef),IPC_ENABLEDISABLE_ALL_WINDOWS);

+** Sending this message with 0xdeadbeef as the param will disable all winamp windows and

+** any other values will enable all of the Winamp windows again. When disabled you won't

+** get any response on clicking or trying to do anything to the Winamp windows. If the

+** taskbar icon is shown then you may still have control ;)

+*/

+

+

+#define IPC_GETWND 260

+/* (requires Winamp 2.9+)

+** HWND h=SendMessage(hwnd_winamp,WM_WA_IPC,IPC_GETWND_xxx,IPC_GETWND);

+** returns the HWND of the window specified.

+*/

+  #define IPC_GETWND_EQ 0 // use one of these for the param

+  #define IPC_GETWND_PE 1

+  #define IPC_GETWND_MB 2

+  #define IPC_GETWND_VIDEO 3

+#define IPC_ISWNDVISIBLE 261 // same param as IPC_GETWND

+

+

+/************************************************************************

+***************** in-process only (WE LOVE PLUGINS)

+************************************************************************/

+

+#define IPC_SETSKINW 199

+#define IPC_SETSKIN 200

+/* (requires Winamp 2.04+, only usable from plug-ins (not external apps))

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)"skinname",IPC_SETSKIN);

+** IPC_SETSKIN sets the current skin to "skinname". Note that skinname

+** can be the name of a skin, a skin .zip file, with or without path.

+** If path isn't specified, the default search path is the winamp skins

+** directory.

+*/

+

+

+#define IPC_GETSKIN 201

+#define IPC_GETSKINW 1201

+/* (requires Winamp 2.04+, only usable from plug-ins (not external apps))

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)skinname_buffer,IPC_GETSKIN);

+** IPC_GETSKIN puts the directory where skin bitmaps can be found

+** into  skinname_buffer.

+** skinname_buffer must be MAX_PATH characters in length.

+** When using a .zip'd skin file, it'll return a temporary directory

+** where the ZIP was decompressed.

+*/

+

+

+#define IPC_EXECPLUG 202

+/* (requires Winamp 2.04+, only usable from plug-ins (not external apps))

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)"vis_file.dll",IPC_EXECPLUG);

+** IPC_EXECPLUG executes a visualization plug-in pointed to by WPARAM.

+** the format of this string can be:

+** "vis_whatever.dll"

+** "vis_whatever.dll,0" // (first mod, file in winamp plug-in dir)

+** "C:\\dir\\vis_whatever.dll,1"

+*/

+

+

+#define IPC_GETPLAYLISTFILE 211

+#define IPC_GETPLAYLISTFILEW 214

+/* (requires Winamp 2.04+, only usable from plug-ins (not external apps))

+** char *name=SendMessage(hwnd_winamp,WM_WA_IPC,index,IPC_GETPLAYLISTFILE);

+** IPC_GETPLAYLISTFILE gets the filename of the playlist entry [index].

+** returns a pointer to it. returns NULL on error.

+*/

+

+

+#define IPC_GETPLAYLISTTITLE 212

+#define IPC_GETPLAYLISTTITLEW 213

+/* (requires Winamp 2.04+, only usable from plug-ins (not external apps))

+** char *name=SendMessage(hwnd_winamp,WM_WA_IPC,index,IPC_GETPLAYLISTTITLE);

+**

+** IPC_GETPLAYLISTTITLE gets the title of the playlist entry [index].

+** returns a pointer to it. returns NULL on error.

+*/

+

+

+#define IPC_GETHTTPGETTER 240

+/* retrieves a function pointer to a HTTP retrieval function.

+** if this is unsupported, returns 1 or 0.

+** the function should be:

+** int (*httpRetrieveFile)(HWND hwnd, char *url, char *file, char *dlgtitle);

+** if you call this function, with a parent window, a URL, an output file, and a dialog title,

+** it will return 0 on successful download, 1 on error.

+*/

+

+

+#define IPC_GETHTTPGETTERW 1240

+/* int (*httpRetrieveFileW)(HWND hwnd, char *url, wchar_t *file, wchar_t *dlgtitle); */

+

+

+#define IPC_MBOPEN 241

+/* (requires Winamp 2.05+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_MBOPEN);

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)url,IPC_MBOPEN);

+** IPC_MBOPEN will open a new URL in the minibrowser. if url is NULL, it will open the Minibrowser window.

+*/

+

+

+#define IPC_CHANGECURRENTFILE 245

+/* (requires Winamp 2.05+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)file,IPC_CHANGECURRENTFILE);

+** IPC_CHANGECURRENTFILE will set the current playlist item.

+*/

+

+

+#define IPC_CHANGECURRENTFILEW 1245

+/* (requires Winamp 5.3+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)file,IPC_CHANGECURRENTFILEW);

+** IPC_CHANGECURRENTFILEW will set the current playlist item.

+*/

+

+

+#define IPC_GETMBURL 246

+/* (requires Winamp 2.2+)

+** char buffer[4096]; // Urls can be VERY long

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)buffer,IPC_GETMBURL);

+** IPC_GETMBURL will retrieve the current Minibrowser URL into buffer.

+** buffer must be at least 4096 bytes long.

+*/

+

+

+#define IPC_MBBLOCK 248

+/* (requires Winamp 2.4+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,value,IPC_MBBLOCK);

+**

+** IPC_MBBLOCK will block the Minibrowser from updates if value is set to 1

+*/

+

+

+#define IPC_MBOPENREAL 249

+/* (requires Winamp 2.4+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)url,IPC_MBOPENREAL);

+**

+** IPC_MBOPENREAL works the same as IPC_MBOPEN except that it will works even if

+** IPC_MBBLOCK has been set to 1

+*/

+

+

+#define IPC_ADJUST_OPTIONSMENUPOS 280

+/* (requires Winamp 2.9+)

+** int newpos=SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)adjust_offset,IPC_ADJUST_OPTIONSMENUPOS);

+** moves where winamp expects the Options menu in the main menu. Useful if you wish to insert a

+** menu item above the options/skins/vis menus.

+*/

+

+

+#define IPC_GET_HMENU 281

+/* (requires Winamp 2.9+)

+** HMENU hMenu=SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)0,IPC_GET_HMENU);

+** values for data:

+** 0 : main popup menu

+** 1 : main menubar file menu

+** 2 : main menubar options menu

+** 3 : main menubar windows menu

+** 4 : main menubar help menu

+** other values will return NULL.

+*/

+

+

+#define IPC_GET_EXTENDED_FILE_INFO 290 //pass a pointer to the following struct in wParam

+#define IPC_GET_EXTENDED_FILE_INFO_HOOKABLE 296

+/* (requires Winamp 2.9+)

+** to use, create an extendedFileInfoStruct, point the values filename and metadata to the

+** filename and metadata field you wish to query, and ret to a buffer, with retlen to the

+** length of that buffer, and then SendMessage(hwnd_winamp,WM_WA_IPC,&struct,IPC_GET_EXTENDED_FILE_INFO);

+** the results should be in the buffer pointed to by ret.

+** returns 1 if the decoder supports a getExtendedFileInfo method

+*/

+typedef struct {

+  const char *filename;

+  const char *metadata;

+  char *ret;

+  size_t retlen;

+} extendedFileInfoStruct;

+

+

+#define IPC_GET_BASIC_FILE_INFO 291 //pass a pointer to the following struct in wParam

+typedef struct {

+  const char *filename;

+

+  int quickCheck; // set to 0 to always get, 1 for quick, 2 for default (if 2, quickCheck will be set to 0 if quick wasnot used)

+

+  // filled in by winamp

+  int length;

+  char *title;

+  int titlelen;

+} basicFileInfoStruct;

+

+

+#define IPC_GET_BASIC_FILE_INFOW 1291 //pass a pointer to the following struct in wParam

+typedef struct {

+  const wchar_t *filename;

+

+  int quickCheck; // set to 0 to always get, 1 for quick, 2 for default (if 2, quickCheck will be set to 0 if quick wasnot used)

+

+  // filled in by winamp

+  int length;

+  wchar_t *title;

+  int titlelen;

+} basicFileInfoStructW;

+

+

+#define IPC_GET_EXTLIST 292 //returns doublenull delimited. GlobalFree() it when done. if data is 0, returns raw extlist, if 1, returns something suitable for getopenfilename

+#define IPC_GET_EXTLISTW 1292 // wide char version of above

+

+

+#define IPC_INFOBOX 293

+typedef struct {

+  HWND parent;

+  char *filename;

+} infoBoxParam;

+

+

+#define IPC_INFOBOXW 1293

+typedef struct {

+  HWND parent;

+  const wchar_t *filename;

+} infoBoxParamW;

+

+

+#define IPC_SET_EXTENDED_FILE_INFO 294 //pass a pointer to the a extendedFileInfoStruct in wParam

+/* (requires Winamp 2.9+)

+** to use, create an extendedFileInfoStruct, point the values filename and metadata to the

+** filename and metadata field you wish to write in ret. (retlen is not used). and then

+** SendMessage(hwnd_winamp,WM_WA_IPC,&struct,IPC_SET_EXTENDED_FILE_INFO);

+** returns 1 if the metadata is supported

+** Call IPC_WRITE_EXTENDED_FILE_INFO once you're done setting all the metadata you want to update

+*/

+

+

+#define IPC_WRITE_EXTENDED_FILE_INFO 295

+/* (requires Winamp 2.9+)

+** writes all the metadata set thru IPC_SET_EXTENDED_FILE_INFO to the file

+** returns 1 if the file has been successfully updated, 0 if error

+*/

+

+

+#define IPC_FORMAT_TITLE 297

+typedef struct

+{

+  char *spec; // NULL=default winamp spec

+  void *p;

+

+  char *out;

+  int out_len;

+

+  char * (*TAGFUNC)(const char * tag, void * p); //return 0 if not found

+  void (*TAGFREEFUNC)(char * tag,void * p);

+} waFormatTitle;

+

+

+#define IPC_FORMAT_TITLE_EXTENDED 298 // similiar to IPC_FORMAT_TITLE, but falls back to Winamp's %tags% if your passed tag function doesn't handle it

+typedef struct

+{

+  const wchar_t *filename;

+  int useExtendedInfo; // set to 1 if you want the Title Formatter to query the input plugins for any tags that your tag function fails on

+  const wchar_t *spec; // NULL=default winamp spec

+  void *p;

+

+  wchar_t *out;

+  int out_len;

+

+  wchar_t * (*TAGFUNC)(const wchar_t * tag, void * p); //return 0 if not found, -1 for empty tag

+  void (*TAGFREEFUNC)(wchar_t *tag, void *p);

+} waFormatTitleExtended;

+

+

+#define IPC_COPY_EXTENDED_FILE_INFO 299

+typedef struct

+{

+  const char *source;

+  const char *dest;

+} copyFileInfoStruct;

+

+

+#define IPC_COPY_EXTENDED_FILE_INFOW 1299

+typedef struct

+{

+  const wchar_t *source;

+  const wchar_t *dest;

+} copyFileInfoStructW;

+

+

+typedef struct {

+  int (*inflateReset)(void *strm);

+  int (*inflateInit_)(void *strm,const char *version, int stream_size);

+  int (*inflate)(void *strm, int flush);

+  int (*inflateEnd)(void *strm);

+  unsigned long (*crc32)(unsigned long crc, const unsigned  char *buf, unsigned int len);

+} wa_inflate_struct;

+

+#define IPC_GETUNCOMPRESSINTERFACE 331

+/* returns a function pointer to uncompress().

+** int (*uncompress)(unsigned char *dest, unsigned long *destLen, const unsigned char *source, unsigned long sourceLen);

+** right out of zlib, useful for decompressing zlibbed data.

+** if you pass the parm of 0x10100000, it will return a wa_inflate_struct * to an inflate API.

+*/

+

+

+typedef struct _prefsDlgRec {

+  HINSTANCE hInst;  // dll instance containing the dialog resource

+  int dlgID;        // resource identifier of the dialog

+  void *proc;       // window proceedure for handling the dialog defined as

+                    // LRESULT CALLBACK PrefsPage(HWND,UINT,WPARAM,LPARAM)

+

+  char *name;       // name shown for the prefs page in the treelist

+  intptr_t where;   // section in the treelist the prefs page is to be added to

+                    // 0 for General Preferences

+                    // 1 for Plugins

+                    // 2 for Skins

+                    // 3 for Bookmarks (no longer in the 5.0+ prefs)

+                    // 4 for Prefs     (the old 'Setup' section - no longer in 5.0+)

+

+  intptr_t _id;

+  struct _prefsDlgRec *next; // no longer implemented as a linked list, now used by Winamp for other means

+} prefsDlgRec;

+

+typedef struct _prefsDlgRecW {

+  HINSTANCE hInst;  // dll instance containing the dialog resource

+  int dlgID;        // resource identifier of the dialog

+  void *proc;       // window proceedure for handling the dialog defined as

+                    // LRESULT CALLBACK PrefsPage(HWND,UINT,WPARAM,LPARAM)

+

+  wchar_t *name;    // name shown for the prefs page in the treelist

+  intptr_t where;   // section in the treelist the prefs page is to be added to

+                    // 0 for General Preferences

+                    // 1 for Plugins

+                    // 2 for Skins

+                    // 3 for Bookmarks (no longer in the 5.0+ prefs)

+                    // 4 for Prefs     (the old 'Setup' section - no longer in 5.0+)

+

+  intptr_t _id;

+  struct _prefsDlgRec *next; // no longer implemented as a linked list, now used by Winamp for other means

+} prefsDlgRecW;

+

+#define IPC_ADD_PREFS_DLG 332

+#define IPC_ADD_PREFS_DLGW 1332

+#define IPC_REMOVE_PREFS_DLG 333

+/* (requires Winamp 2.9+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&prefsRec,IPC_ADD_PREFS_DLG);

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&prefsRec,IPC_REMOVE_PREFS_DLG);

+**

+** IPC_ADD_PREFS_DLG:

+** To use this you need to allocate a prefsDlgRec structure (either on the heap or with

+** some global data but NOT on the stack) and then initialise the members of the structure

+** (see the definition of the prefsDlgRec structure above).

+**

+**   hInst  -  dll instance of where the dialog resource is located.

+**   dlgID  -  id of the dialog resource.

+**   proc   -  dialog window procedure for the prefs dialog.

+**   name   -  name of the prefs page as shown in the preferences list.

+**   where  -  see above for the valid locations the page can be added.

+**

+** Then you do SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&prefsRec,IPC_ADD_PREFS_DLG);

+**

+** example:

+**

+** prefsDlgRec* prefsRec = 0;

+**   prefsRec = GlobalAlloc(GPTR,sizeof(prefsDlgRec));

+**   prefsRec->hInst = hInst;

+**   prefsRec->dlgID = IDD_PREFDIALOG;

+**   prefsRec->name = "Pref Page";

+**   prefsRec->where = 0;

+**   prefsRec->proc = PrefsPage;

+**   SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&prefsRec,IPC_ADD_PREFS_DLG);

+**

+**

+** IPC_REMOVE_PREFS_DLG:

+** To use you pass the address of the same prefsRec you used when adding the prefs page

+** though you shouldn't really ever have to do this but it's good to clean up after you

+** when you're plugin is being unloaded.

+**

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&prefsRec,IPC_REMOVE_PREFS_DLG);

+**

+** IPC_ADD_PREFS_DLGW

+** requires Winamp 5.53+

+*/

+

+

+#define IPC_OPENPREFSTOPAGE 380

+/* SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&prefsRec,IPC_OPENPREFSTOPAGE);

+**

+** There are two ways of opening a preferences page.

+**

+** The first is to pass an id of a builtin preferences page (see below for ids) or a

+** &prefsDlgRec of the preferences page to open and this is normally done if you are

+** opening a prefs page you added yourself.

+**

+** If the page id does not or the &prefsRec is not valid then the prefs dialog will be

+** opened to the first page available (usually the Winamp Pro page).

+**

+** (requires Winamp 5.04+)

+** Passing -1 for param will open the preferences dialog to the last page viewed.

+**

+** Note: v5.0 to 5.03 had a bug in this api

+**

+** On the first call then the correct prefs page would be opened to but on the next call

+** the prefs dialog would be brought to the front but the page would not be changed to the

+** specified.

+** In 5.04+ it will change to the prefs page specified if the prefs dialog is already open.

+*/

+

+/* Builtin Preference page ids (valid for 5.0+)

+** (stored in the lParam member of the TVITEM structure from the tree item)

+**

+** These can be useful if you want to detect a specific prefs page and add things to it

+** yourself or something like that ;)

+**

+** Winamp Pro           20

+** General Preferences  0

+** File Types           1

+** Playlist             23

+** Titles               21

+** Playback             42 (added in 5.25)

+** Station Info         41 (added in 5.11 & removed in 5.5)

+** Video                24

+** Localization         25 (added in 5.5)

+** Skins                40

+** Classic Skins        22

+** Plugins              30

+** Input                31

+** Output               32

+** Visualisation        33

+** DSP/Effect           34

+** General Purpose      35

+**

+** Note:

+** Custom page ids begin from 60

+** The value of the normal custom pages (Global Hotkeys, Jump To File, etc) is not

+** guaranteed since it depends on the order in which the plugins are loaded which can

+** change on different systems.

+**

+** Global Hotkeys, Jump To File, Media Library (under General Preferences and child pages),

+** Media Library (under Plugins), Portables, CD Ripping and Modern Skins are custom pages

+** created by the plugins shipped with Winamp.

+*/

+

+

+#define IPC_GETINIFILE 334

+/* (requires Winamp 2.9+)

+** char *ini=(char*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETINIFILE);

+** This returns a pointer to the full file path of winamp.ini.

+**

+** char ini_path[MAX_PATH] = {0};

+**

+** void GetIniFilePath(HWND hwnd){

+**   if(SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETVERSION) >= 0x2900){

+**     // this gets the string of the full ini file path

+**     lstrcpyn(ini_path,(char*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETINIFILE),sizeof(ini_path));

+**   }

+**   else{

+**   char* p = ini_path;

+**     p += GetModuleFileName(0,ini_path,sizeof(ini_path)) - 1;

+**     while(p && *p != '.'){p--;}

+**     lstrcpyn(p+1,"ini",sizeof(ini_path));

+**   }

+** }

+*/

+

+

+#define IPC_GETINIDIRECTORY 335

+/* (requires Winamp 2.9+)

+** char *dir=(char*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETINIDIRECTORY);

+** This returns a pointer to the directory where winamp.ini can be found and is

+** useful if you want store config files but you don't want to use winamp.ini.

+*/

+

+

+#define IPC_GETPLUGINDIRECTORY 336

+/* (requires Winamp 5.11+)

+** char *plugdir=(char*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETPLUGINDIRECTORY);

+** This returns a pointer to the directory where Winamp has its plugins stored and is

+** useful if you want store config files in plugins.ini in the plugins folder or for

+** accessing any local files in the plugins folder.

+*/

+

+

+#define IPC_GETM3UDIRECTORY 337

+/* (requires Winamp 5.11+)

+** char *m3udir=(char*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETM3UDIRECTORY);

+** This returns a pointer to the directory where winamp.m3u (and winamp.m3u8 if supported) is stored in.

+*/

+

+

+#define IPC_GETM3UDIRECTORYW 338

+/* (requires Winamp 5.3+)

+** wchar_t *m3udirW=(wchar_t*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETM3UDIRECTORYW);

+** This returns a pointer to the directory where winamp.m3u (and winamp.m3u8 if supported) is stored in.

+*/

+

+

+#define IPC_SPAWNBUTTONPOPUP 361 // param =

+// 0 = eject

+// 1 = previous

+// 2 = next

+// 3 = pause

+// 4 = play

+// 5 = stop

+

+

+#define IPC_OPENURLBOX 360

+/* (requires Winamp 5.0+)

+** HGLOBAL hglobal = (HGLOBAL)SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(HWND)parent,IPC_OPENURLBOX);

+** You pass a hwnd for the dialog to be parented to (which modern skin support uses).

+** This will return a HGLOBAL that needs to be freed with GlobalFree() if this worked.

+*/

+

+

+#define IPC_OPENFILEBOX 362

+/* (requires Winamp 5.0+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(HWND)parent,IPC_OPENFILEBOX);

+** You pass a hwnd for the dialog to be parented to (which modern skin support uses).

+*/

+

+

+#define IPC_OPENDIRBOX 363

+/* (requires Winamp 5.0+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(HWND)parent,IPC_OPENDIRBOX);

+** You pass a hwnd for the dialog to be parented to (which modern skin support uses).

+*/

+

+

+#define IPC_SETDIALOGBOXPARENT 364

+/* (requires Winamp 5.0+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(HWND)parent,IPC_SETDIALOGBOXPARENT);

+** Pass 'parent' as the window which will be used as the parent for a number of the built

+** in Winamp dialogs and is useful when you are taking over the whole of the UI so that

+** the dialogs will not appear at the bottom right of the screen since the main winamp

+** window is located at 3000x3000 by gen_ff when this is used.  Call this again with

+** parent = null to reset the parent back to the orginal Winamp window.

+*/

+

+#define IPC_GETDIALOGBOXPARENT 365

+/* (requires Winamp 5.51+)

+** HWND hwndParent = SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)0, IPC_GETDIALOGBOXPARENT);

+** hwndParent can/must be passed to all modal dialogs (including MessageBox) thats uses winamp as a parent

+*/

+

+#define IPC_UPDATEDIALOGBOXPARENT 366

+/* (requires Winamp 5.53+)

+** if you previous called IPC_SETDIALOGBOXPARENT, call this every time your window resizes

+*/

+

+#define IPC_DRO_MIN 401 // reserved for DrO

+#define IPC_SET_JTF_COMPARATOR 409

+/* pass me an int (__cdecl *)(const char *, const char *) in wParam */

+#define IPC_SET_JTF_COMPARATOR_W 410

+/* pass me an int (__cdecl *)(const wchar_t *, const wchar_t *) in wParam ... maybe someday :) */

+#define IPC_SET_JTF_DRAWTEXT 416

+

+#define IPC_DRO_MAX 499

+

+

+// pass 0 for a copy of the skin HBITMAP

+// pass 1 for name of font to use for playlist editor likeness

+// pass 2 for font charset

+// pass 3 for font size

+#define IPC_GET_GENSKINBITMAP 503

+

+

+typedef struct

+{

+  HWND me; //hwnd of the window

+

+  #define EMBED_FLAGS_NORESIZE 0x1

+  // set this bit to keep window from being resizable

+

+  #define EMBED_FLAGS_NOTRANSPARENCY 0x2

+  // set this bit to make gen_ff turn transparency off for this window

+

+  #define EMBED_FLAGS_NOWINDOWMENU 0x4

+  // set this bit to prevent gen_ff from automatically adding your window to the right-click menu

+

+  #define EMBED_FLAGS_GUID 0x8

+  // (5.31+) call SET_EMBED_GUID(yourEmbedWindowStateStruct, GUID) to define a GUID for this window

+

+  #define SET_EMBED_GUID(windowState, windowGUID) { windowState->flags |= EMBED_FLAGS_GUID; *((GUID *)&windowState->extra_data[4])=windowGUID; }

+  #define GET_EMBED_GUID(windowState) (*((GUID *)&windowState->extra_data[4]))

+

+  int flags;  // see above

+

+  RECT r;

+  void *user_ptr;       // for application use

+  int extra_data[64];   // for internal winamp use

+} embedWindowState;

+

+#define IPC_GET_EMBEDIF 505

+/* (requires Winamp 2.9+)

+** HWND myframe = (HWND)SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&wa_wnd,IPC_GET_EMBEDIF);

+**

+** or

+**

+** HWND myframe = 0;

+** HWND (*embed)(embedWindowState *params)=0;

+**   *(void**)&embed = (void*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GET_EMBEDIF);

+**   myframe = embed(&wa_wnd);

+**

+** You pass an embedWindowState* and it will return a hwnd for the frame window or if you

+** pass wParam as null then it will return a HWND embedWindow(embedWindowState *);

+*/

+

+#define IPC_SKINWINDOW  534

+

+typedef struct __SKINWINDOWPARAM

+{

+    HWND hwndToSkin;

+    GUID windowGuid;

+} SKINWINDOWPARAM;

+

+

+

+#define IPC_EMBED_ENUM 532

+typedef struct embedEnumStruct

+{

+  int (*enumProc)(embedWindowState *ws, struct embedEnumStruct *param); // return 1 to abort

+  int user_data; // or more :)

+} embedEnumStruct;

+  // pass

+

+

+#define IPC_EMBED_ISVALID 533

+/* (requires Winamp 2.9+)

+** int valid = SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)embedhwnd,IPC_EMBED_ISVALID);

+** Pass a hwnd in the wParam to this to check if the hwnd is a valid embed window or not.

+*/

+

+

+#define IPC_CONVERTFILE 506

+/* (requires Winamp 2.92+)

+** Converts a given file to a different format (PCM, MP3, etc...)

+** To use, pass a pointer to a waFileConvertStruct struct

+** This struct can be either on the heap or some global

+** data, but NOT on the stack. At least, until the conversion is done.

+**

+** eg: SendMessage(hwnd_winamp,WM_WA_IPC,&myConvertStruct,IPC_CONVERTFILE);

+**

+** Return value:

+** 0: Can't start the conversion. Look at myConvertStruct->error for details.

+** 1: Conversion started. Status messages will be sent to the specified callbackhwnd.

+**    Be sure to call IPC_CONVERTFILE_END when your callback window receives the

+**    IPC_CB_CONVERT_DONE message.

+*/

+typedef struct

+{

+  char *sourcefile;  // "c:\\source.mp3"

+  char *destfile;    // "c:\\dest.pcm"

+  intptr_t destformat[8]; // like 'PCM ',srate,nch,bps.

+  //hack alert! you can set destformat[6]=mmioFOURCC('I','N','I',' '); and destformat[7]=(int)my_ini_file; (where my_ini_file is a char*)

+  HWND callbackhwnd; // window that will receive the IPC_CB_CONVERT notification messages

+

+  //filled in by winamp.exe

+  char *error;        //if IPC_CONVERTFILE returns 0, the reason will be here

+

+  int bytes_done;     //you can look at both of these values for speed statistics

+  int bytes_total;

+  int bytes_out;

+

+  int killswitch;     // don't set it manually, use IPC_CONVERTFILE_END

+  intptr_t extra_data[64]; // for internal winamp use

+} convertFileStruct;

+

+

+#define IPC_CONVERTFILEW 515

+// (requires Winamp 5.36+)

+typedef struct

+{

+  wchar_t *sourcefile;  // "c:\\source.mp3"

+  wchar_t *destfile;    // "c:\\dest.pcm"

+  intptr_t destformat[8]; // like 'PCM ',srate,nch,bps.

+  //hack alert! you can set destformat[6]=mmioFOURCC('I','N','I',' '); and destformat[7]=(int)my_ini_file; (where my_ini_file is a char*)

+  HWND callbackhwnd; // window that will receive the IPC_CB_CONVERT notification messages

+

+  //filled in by winamp.exe

+  wchar_t *error;        //if IPC_CONVERTFILE returns 0, the reason will be here

+

+  int bytes_done;     //you can look at both of these values for speed statistics

+  int bytes_total;

+  int bytes_out;

+

+  int killswitch;     // don't set it manually, use IPC_CONVERTFILE_END

+  intptr_t extra_data[64]; // for internal winamp use

+} convertFileStructW;

+

+

+#define IPC_CONVERTFILE_END 507

+/* (requires Winamp 2.92+)

+** Stop/ends a convert process started from IPC_CONVERTFILE

+** You need to call this when you receive the IPC_CB_CONVERTDONE message or when you

+** want to abort a conversion process

+**

+** eg: SendMessage(hwnd_winamp,WM_WA_IPC,&myConvertStruct,IPC_CONVERTFILE_END);

+**

+** No return value

+*/

+

+

+#define IPC_CONVERTFILEW_END 516

+// (requires Winamp 5.36+)

+

+typedef struct {

+  HWND hwndParent;

+  int format;

+

+  //filled in by winamp.exe

+  HWND hwndConfig;

+  int extra_data[8];

+  //hack alert! you can set extra_data[6]=mmioFOURCC('I','N','I',' '); and extra_data[7]=(int)my_ini_file; (where my_ini_file is a char*)

+} convertConfigStruct;

+

+

+#define IPC_CONVERT_CONFIG 508

+#define IPC_CONVERT_CONFIG_END 509

+

+typedef struct

+{

+  void (*enumProc)(intptr_t user_data, const char *desc, int fourcc);

+  intptr_t user_data;

+} converterEnumFmtStruct;

+#define IPC_CONVERT_CONFIG_ENUMFMTS 510

+/* (requires Winamp 2.92+)

+*/

+

+typedef struct

+{

+  char cdletter;

+  char *playlist_file;

+  HWND callback_hwnd;

+

+  //filled in by winamp.exe

+  char *error;

+} burnCDStruct;

+#define IPC_BURN_CD 511

+/* (requires Winamp 5.0+)

+*/

+

+typedef struct

+{

+  convertFileStruct *cfs;

+  int priority;

+} convertSetPriority;

+

+

+#define IPC_CONVERT_SET_PRIORITY 512

+

+typedef struct

+{

+  convertFileStructW *cfs;

+  int priority;

+} convertSetPriorityW;

+

+

+#define IPC_CONVERT_SET_PRIORITYW 517

+// (requires Winamp 5.36+)

+

+typedef struct

+{

+  unsigned int format; //fourcc value

+  char *item; // config item, eg "bitrate"

+  char *data; // buffer to recieve, or buffer that contains the data

+  int len; // length of the data buffer (only used when getting a config item)

+  char *configfile; // config file to read from

+} convertConfigItem;

+

+

+#define IPC_CONVERT_CONFIG_SET_ITEM 513 // returns TRUE if successful

+#define IPC_CONVERT_CONFIG_GET_ITEM 514 // returns TRUE if successful

+

+

+typedef struct

+{

+  const char *filename;

+  char *title; // 2048 bytes

+  int length;

+  int force_useformatting; // can set this to 1 if you want to force a url to use title formatting shit

+} waHookTitleStruct;

+

+#define IPC_HOOK_TITLES 850

+/* (requires Winamp 5.0+)

+** If you hook this message and modify the information then make sure to return TRUE.

+** If you don't hook the message then make sure you pass it on through the subclass chain.

+**

+** LRESULT CALLBACK WinampWndProc(HWND hwnd, UINT umsg, WPARAM wParam, LPARAM lParam)

+** {

+**   LRESULT ret = CallWindowProc((WNDPROC)WinampProc,hwnd,umsg,wParam,lParam);

+**

+**   if(message==WM_WA_IPC && lParam==IPC_HOOK_TITLES)

+**   {

+**     waHookTitleStruct *ht = (waHookTitleStruct *) wParam;

+**     // Doing ATF stuff with ht->title, whatever...

+**     return TRUE;

+**   }

+**   return ret;

+** }

+*/

+

+typedef struct

+{

+  const wchar_t *filename;

+  wchar_t *title; // 2048 characters

+  int length;

+  int force_useformatting; // can set this to 1 if you want to force a url to use title formatting shit

+} waHookTitleStructW;

+#define IPC_HOOK_TITLESW 851

+/* (requires Winamp 5.3+)

+** See information on IPC_HOOK_TITLES for how to process this.

+*/

+

+

+#define IPC_GETSADATAFUNC 800

+// 0: returns a char *export_sa_get() that returns 150 bytes of data

+// 1: returns a export_sa_setreq(int want);

+

+

+#define IPC_GETVUDATAFUNC 801

+// 0: returns a int export_vu_get(int channel) that returns 0-255 (or -1 for bad channel)

+

+

+#define IPC_ISMAINWNDVISIBLE 900

+/* (requires Winamp 5.0+)

+** int visible=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_ISMAINWNDVISIBLE);

+** You send this to Winamp to query if the main window is visible or not such as by

+** unchecking the option in the main right-click menu. If the main window is visible then

+** this will return 1 otherwise it returns 0.

+*/

+

+

+typedef struct

+{

+  int numElems;

+  int *elems;

+  HBITMAP bm; // set if you want to override

+} waSetPlColorsStruct;

+

+#define IPC_SETPLEDITCOLORS 920

+/* (requires Winamp 5.0+)

+** This is sent by gen_ff when a modern skin is being loaded to set the colour scheme for

+** the playlist editor. When sent numElems is usually 6 and matches with the 6 possible

+** colours which are provided be pledit.txt from the classic skins. The elems array is

+** defined as follows:

+**

+** elems = 0  =>  normal text

+** elems = 1  =>  current text

+** elems = 2  =>  normal background

+** elems = 3  =>  selected background

+** elems = 4  =>  minibroswer foreground

+** elems = 5  =>  minibroswer background

+**

+** if(uMsg == WM_WA_IPC && lParam == IPC_SETPLEDITCOLORS)

+** {

+**   waSetPlColorsStruct* colStr = (waSetPlColorsStruct*)wp;

+**   if(colStr)

+**   {

+**      // set or inspect the colours being used (basically for gen_ff's benefit)

+**   }

+** }

+*/

+

+

+typedef struct

+{

+  HWND wnd;

+  int xpos; // in screen coordinates

+  int ypos;

+} waSpawnMenuParms;

+

+// waSpawnMenuParms2 is used by the menubar submenus

+typedef struct

+{

+  HWND wnd;

+  int xpos; // in screen coordinates

+  int ypos;

+  int width;

+  int height;

+} waSpawnMenuParms2;

+

+// the following IPC use waSpawnMenuParms as parameter

+#define IPC_SPAWNEQPRESETMENU 933

+#define IPC_SPAWNFILEMENU 934 //menubar

+#define IPC_SPAWNOPTIONSMENU 935 //menubar

+#define IPC_SPAWNWINDOWSMENU 936 //menubar

+#define IPC_SPAWNHELPMENU 937 //menubar

+#define IPC_SPAWNPLAYMENU 938 //menubar

+#define IPC_SPAWNPEFILEMENU 939 //menubar

+#define IPC_SPAWNPEPLAYLISTMENU 940 //menubar

+#define IPC_SPAWNPESORTMENU 941 //menubar

+#define IPC_SPAWNPEHELPMENU 942 //menubar

+#define IPC_SPAWNMLFILEMENU 943 //menubar

+#define IPC_SPAWNMLVIEWMENU 944 //menubar

+#define IPC_SPAWNMLHELPMENU 945 //menubar

+#define IPC_SPAWNPELISTOFPLAYLISTS 946

+

+

+#define WM_WA_SYSTRAY WM_USER+1

+/* This is sent by the system tray when an event happens (you might want to simulate it).

+**

+** if(uMsg == WM_WA_SYSTRAY)

+** {

+**   switch(lParam)

+**   {

+**     // process the messages sent from the tray

+**   }

+** }

+*/

+

+

+#define WM_WA_MPEG_EOF WM_USER+2

+/* Input plugins send this when they are done playing back the current file to inform

+** Winamp or anyother installed plugins that the current

+**

+** if(uMsg == WM_WA_MPEG_EOF)

+** {

+**   // do what is needed here

+** }

+*/

+

+

+//// video stuff

+

+#define IPC_IS_PLAYING_VIDEO 501 // returns >1 if playing, 0 if not, 1 if old version (so who knows):)

+#define IPC_GET_IVIDEOOUTPUT 500 // see below for IVideoOutput interface

+#define VIDEO_MAKETYPE(A,B,C,D) ((A) | ((B)<<8) | ((C)<<16) | ((D)<<24))

+#define VIDUSER_SET_INFOSTRING 0x1000

+#define VIDUSER_GET_VIDEOHWND  0x1001

+#define VIDUSER_SET_VFLIP      0x1002

+#define VIDUSER_SET_TRACKSELINTERFACE 0x1003 // give your ITrackSelector interface as param2

+#define VIDUSER_OPENVIDEORENDERER 0x1004

+#define VIDUSER_CLOSEVIDEORENDERER 0x1005

+#define VIDUSER_GETPOPUPMENU 0x1006

+#define VIDUSER_SET_INFOSTRINGW 0x1007

+

+typedef struct

+{

+  int w;

+  int h;

+  int vflip;

+  double aspectratio;

+  unsigned int fmt;

+} VideoOpenStruct;

+

+#ifndef NO_IVIDEO_DECLARE

+#ifdef __cplusplus

+

+class VideoOutput;

+class SubsItem;

+

+#ifndef _NSV_DEC_IF_H_

+struct YV12_PLANE {

+  unsigned char* baseAddr;

+  long rowBytes;

+} ;

+

+struct YV12_PLANES {

+  YV12_PLANE y;

+  YV12_PLANE u;

+  YV12_PLANE v;

+};

+#endif

+

+class IVideoOutput

+{

+  public:

+    virtual ~IVideoOutput() { }

+    virtual int open(int w, int h, int vflip, double aspectratio, unsigned int fmt)=0;

+    virtual void setcallback(LRESULT (*msgcallback)(void *token, HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam), void *token) { (void)token; (void)msgcallback; /* to eliminate warning C4100 */ }

+    virtual void close()=0;

+    virtual void draw(void *frame)=0;

+    virtual void drawSubtitle(SubsItem *item) {UNREFERENCED_PARAMETER(item);  }

+    virtual void showStatusMsg(const char *text) {UNREFERENCED_PARAMETER(text);  }

+    virtual int get_latency() { return 0; }

+    virtual void notifyBufferState(int bufferstate) { UNREFERENCED_PARAMETER(bufferstate); } /* 0-255*/

+    virtual INT_PTR extended(INT_PTR param1, INT_PTR param2, INT_PTR param3) { UNREFERENCED_PARAMETER(param1); UNREFERENCED_PARAMETER(param2); UNREFERENCED_PARAMETER(param3); return 0; } // Dispatchable, eat this!

+};

+

+class ITrackSelector

+{

+  public:

+    virtual int getNumAudioTracks()=0;

+    virtual void enumAudioTrackName(int n, const char *buf, int size)=0;

+    virtual int getCurAudioTrack()=0;

+    virtual int getNumVideoTracks()=0;

+    virtual void enumVideoTrackName(int n, const char *buf, int size)=0;

+    virtual int getCurVideoTrack()=0;

+

+    virtual void setAudioTrack(int n)=0;

+    virtual void setVideoTrack(int n)=0;

+};

+

+#endif //cplusplus

+#endif//NO_IVIDEO_DECLARE

+

+// these messages are callbacks that you can grab by subclassing the winamp window

+

+// wParam =

+#define IPC_CB_WND_EQ 0 // use one of these for the param

+#define IPC_CB_WND_PE 1

+#define IPC_CB_WND_MB 2

+#define IPC_CB_WND_VIDEO 3

+#define IPC_CB_WND_MAIN 4

+

+#define IPC_CB_ONSHOWWND 600

+#define IPC_CB_ONHIDEWND 601

+

+#define IPC_CB_GETTOOLTIP 602

+

+#define IPC_CB_MISC 603

+    #define IPC_CB_MISC_TITLE 0  // start of playing/stop/pause

+    #define IPC_CB_MISC_VOLUME 1 // volume/pan

+    #define IPC_CB_MISC_STATUS 2 // start playing/stop/pause/ffwd/rwd

+    #define IPC_CB_MISC_EQ 3

+    #define IPC_CB_MISC_INFO 4

+    #define IPC_CB_MISC_VIDEOINFO 5

+    #define IPC_CB_MISC_TITLE_RATING 6 // (5.5+ for when the rating is changed via the songticker menu on current file)

+

+/* Example of using IPC_CB_MISC_STATUS to detect the start of track playback with 5.x

+**

+** if(lParam == IPC_CB_MISC && wParam == IPC_CB_MISC_STATUS)

+** {

+**   if(SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_ISPLAYING) == 1 &&

+**      !SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETOUTPUTTIME))

+**   {

+**     char* file = (char*)SendMessage(hwnd_winamp,WM_WA_IPC,

+**                  SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETLISTPOS),IPC_GETPLAYLISTFILE);

+**     // only output if a valid file was found

+**     if(file)

+**     {

+**       MessageBox(hwnd_winamp,file,"starting",0);

+**       // or do something else that you need to do

+**     }

+**   }

+** }

+*/

+

+

+#define IPC_CB_CONVERT_STATUS 604 // param value goes from 0 to 100 (percent)

+#define IPC_CB_CONVERT_DONE   605

+

+

+#define IPC_ADJUST_FFWINDOWSMENUPOS 606

+/* (requires Winamp 2.9+)

+** int newpos=SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)adjust_offset,IPC_ADJUST_FFWINDOWSMENUPOS);

+** This will move where Winamp expects the freeform windows in the menubar windows main

+** menu. This is useful if you wish to insert a menu item above extra freeform windows.

+*/

+

+

+#define IPC_ISDOUBLESIZE 608

+/* (requires Winamp 5.0+)

+** int dsize=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_ISDOUBLESIZE);

+** You send this to Winamp to query if the double size mode is enabled or not.

+** If it is on then this will return 1 otherwise it will return 0.

+*/

+

+

+#define IPC_ADJUST_FFOPTIONSMENUPOS 609

+/* (requires Winamp 2.9+)

+** int newpos=SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)adjust_offset,IPC_ADJUST_FFOPTIONSMENUPOS);

+** moves where winamp expects the freeform preferences item in the menubar windows main

+** menu. This is useful if you wish to insert a menu item above the preferences item.

+**

+** Note: This setting was ignored by gen_ff until it was fixed in 5.1

+**       gen_ff would assume thatthe menu position was 11 in all cases and so when you

+**       had two plugins attempting to add entries into the main right click menu it

+**       would cause the 'colour themes' submenu to either be incorrectly duplicated or

+**       to just disappear.instead.

+*/

+

+

+#define IPC_GETTIMEDISPLAYMODE 610

+/* (requires Winamp 5.0+)

+** int mode=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETTIMEDISPLAYMODE);

+** This will return the status of the time display i.e. shows time elapsed or remaining.

+** This returns 0 if Winamp is displaying time elapsed or 1 for the time remaining.

+*/

+

+

+#define IPC_SETVISWND 611

+/* (requires Winamp 5.0+)

+** int viswnd=(HWND)SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(HWND)viswnd,IPC_SETVISWND);

+** This allows you to set a window to receive the following message commands (which are

+** used as part of the modern skin integration).

+** When you have finished or your visualisation is closed then send wParam as zero to

+** ensure that things are correctly tidied up.

+*/

+

+/* The following messages are received as the LOWORD(wParam) of the WM_COMMAND message.

+** See %SDK%\winamp\wa5vis.txt for more info about visualisation integration in Winamp.

+*/

+#define ID_VIS_NEXT                     40382

+#define ID_VIS_PREV                     40383

+#define ID_VIS_RANDOM                   40384

+#define ID_VIS_FS                       40389

+#define ID_VIS_CFG                      40390

+#define ID_VIS_MENU                     40391

+

+

+#define IPC_GETVISWND 612

+/* (requires Winamp 5.0+)

+** int viswnd=(HWND)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETVISWND);

+** This returns a HWND to the visualisation command handler window if set by IPC_SETVISWND.

+*/

+

+

+#define IPC_ISVISRUNNING 613

+/* (requires Winamp 5.0+)

+** int visrunning=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_ISVISRUNNING);

+** This will return 1 if a visualisation is currently running and 0 if one is not running.

+*/

+

+

+#define IPC_CB_VISRANDOM 628 // param is status of random

+

+

+#define IPC_SETIDEALVIDEOSIZE 614

+/* (requires Winamp 5.0+)

+** This is sent by Winamp back to itself so it can be trapped and adjusted as needed with

+** the desired width in HIWORD(wParam) and the desired height in LOWORD(wParam).

+**

+** if(uMsg == WM_WA_IPC){

+**   if(lParam == IPC_SETIDEALVIDEOSIZE){

+**      wParam = MAKEWPARAM(height,width);

+**   }

+** }

+*/

+

+

+#define IPC_GETSTOPONVIDEOCLOSE 615

+/* (requires Winamp 5.0+)

+** int sovc=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETSTOPONVIDEOCLOSE);

+** This will return 1 if 'stop on video close' is enabled and 0 if it is disabled.

+*/

+

+

+#define IPC_SETSTOPONVIDEOCLOSE 616

+/* (requires Winamp 5.0+)

+** int sovc=SendMessage(hwnd_winamp,WM_WA_IPC,enabled,IPC_SETSTOPONVIDEOCLOSE);

+** Set enabled to 1 to enable and 0 to disable the 'stop on video close' option.

+*/

+

+

+typedef struct {

+  HWND hwnd;

+  int uMsg;

+  WPARAM wParam;

+  LPARAM lParam;

+} transAccelStruct;

+

+#define IPC_TRANSLATEACCELERATOR 617

+/* (requires Winamp 5.0+)

+** (deprecated as of 5.53x+)

+*/

+

+typedef struct {

+  int cmd;

+  int x;

+  int y;

+  int align;

+} windowCommand; // send this as param to an IPC_PLCMD, IPC_MBCMD, IPC_VIDCMD

+

+

+#define IPC_CB_ONTOGGLEAOT 618

+

+

+#define IPC_GETPREFSWND 619

+/* (requires Winamp 5.0+)

+** HWND prefs = (HWND)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETPREFSWND);

+** This will return a handle to the preferences dialog if it is open otherwise it will

+** return zero. A simple check with the OS api IsWindow(..) is a good test if it's valid.

+**

+** e.g.  this will open (or close if already open) the preferences dialog and show if we

+**       managed to get a valid

+** SendMessage(hwnd_winamp,WM_COMMAND,MAKEWPARAM(WINAMP_OPTIONS_PREFS,0),0);

+** MessageBox(hwnd_winamp,(IsWindow((HWND)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETPREFSWND))?"Valid":"Not Open"),0,MB_OK);

+*/

+

+

+#define IPC_SET_PE_WIDTHHEIGHT 620

+/* (requires Winamp 5.0+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&point,IPC_SET_PE_WIDTHHEIGHT);

+** You pass a pointer to a POINT structure which holds the width and height and Winamp

+** will set the playlist editor to that size (this is used by gen_ff on skin changes).

+** There does not appear to be any bounds limiting with this so it is possible to create

+** a zero size playlist editor window (which is a pretty silly thing to do).

+*/

+

+

+#define IPC_GETLANGUAGEPACKINSTANCE 621

+/* (requires Winamp 5.0+)

+** HINSTANCE hInst = (HINSTANCE)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETLANGUAGEPACKINSTANCE);

+** This will return the HINSTANCE to the currently used language pack file for winamp.exe

+**

+** (5.5+)

+** If you pass 1 in wParam then you will have zero returned if a language pack is in use.

+** if(!SendMessage(hwnd_winamp,WM_WA_IPC,1,IPC_GETLANGUAGEPACKINSTANCE)){

+**   // winamp is currently using a language pack

+** }

+**

+** If you pass 2 in wParam then you will get the path to the language pack folder.

+** wchar_t* lngpackfolder = (wchar_t*)SendMessage(hwnd_winamp,WM_WA_IPC,2,IPC_GETLANGUAGEPACKINSTANCE);

+**

+** If you pass 3 in wParam then you will get the path to the currently extracted language pack.

+** wchar_t* lngpack = (wchar_t*)SendMessage(hwnd_winamp,WM_WA_IPC,3,IPC_GETLANGUAGEPACKINSTANCE);

+**

+** If you pass 4 in wParam then you will get the name of the currently used language pack.

+** wchar_t* lngname = (char*)SendMessage(hwnd_winamp,WM_WA_IPC,4,IPC_GETLANGUAGEPACKINSTANCE);

+*/

+#define LANG_IDENT_STR 0

+#define LANG_LANG_CODE 1

+#define LANG_COUNTRY_CODE 2

+/*

+** (5.51+)

+** If you pass 5 in LOWORD(wParam) then you will get the ident string/code string

+** (based on the param passed in the HIWORD(wParam) of the currently used language pack.

+** The string returned with LANG_IDENT_STR is used to represent the language that the

+** language pack is intended for following ISO naming conventions for consistancy.

+**

+** wchar_t* ident_str = (wchar_t*)SendMessage(hwnd_winamp,WM_WA_IPC,MAKEWPARAM(5,LANG_XXX),IPC_GETLANGUAGEPACKINSTANCE);

+**

+** e.g.

+** For the default language it will return the following for the different LANG_XXX codes

+**    LANG_IDENT_STR ->     "en-US" (max buffer size of this is 9 wchar_t)

+**    LANG_LANG_CODE ->     "en"    (language code)

+**    LANG_COUNTRY_CODE ->  "US"    (country code)

+**

+** On pre 5.51 installs you can get LANG_IDENT_STR using the following method

+** (you'll have to custom process the string returned if you want the langugage or country but that's easy ;) )

+**

+** #define LANG_PACK_LANG_ID 65534 (if you don't have lang.h)

+** HINSTANCE hInst = (HINSTANCE)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETLANGUAGEPACKINSTANCE);

+** TCHAR buffer[9] = {0};

+** LoadString(hInst,LANG_PACK_LANG_ID,buffer,sizeof(buffer));

+**

+**

+**

+** The following example shows how using the basic api will allow you to load the playlist

+** context menu resource from the currently loaded language pack or it will fallback to

+** the default winamp.exe instance.

+**

+** HINSTANCE lang = (HINSTANCE)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETLANGUAGEPACKINSTANCE);

+** HMENU popup = GetSubMenu(GetSubMenu((LoadMenu(lang?lang:GetModuleHandle(0),MAKEINTRESOURCE(101))),2),5);

+**   // do processing as needed on the menu before displaying it

+**   TrackPopupMenuEx(orig,TPM_LEFTALIGN|TPM_LEFTBUTTON|TPM_RIGHTBUTTON,rc.left,rc.bottom,hwnd_owner,0);

+**   DestroyMenu(popup);

+**

+** If you need a specific menu handle then look at IPC_GET_HMENU for more information.

+*/

+

+

+#define IPC_CB_PEINFOTEXT 622 // data is a string, ie: "04:21/45:02"

+

+

+#define IPC_CB_OUTPUTCHANGED 623 // output plugin was changed in config

+

+

+#define IPC_GETOUTPUTPLUGIN 625

+/* (requires Winamp 5.0+)

+** char* outdll = (char*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETOUTPUTPLUGIN);

+** This returns a string of the current output plugin's dll name.

+** e.g. if the directsound plugin was selected then this would return 'out_ds.dll'.

+*/

+

+

+#define IPC_SETDRAWBORDERS 626

+/* (requires Winamp 5.0+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,enabled,IPC_SETDRAWBORDERS);

+** Set enabled to 1 to enable and 0 to disable drawing of the playlist editor and winamp

+** gen class windows (used by gen_ff to allow it to draw its own window borders).

+*/

+

+

+#define IPC_DISABLESKINCURSORS 627

+/* (requires Winamp 5.0+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,enabled,IPC_DISABLESKINCURSORS);

+** Set enabled to 1 to enable and 0 to disable the use of skinned cursors.

+*/

+

+

+#define IPC_GETSKINCURSORS 628

+/* (requires Winamp 5.36+)

+** data = (WACURSOR)cursorId. (check wa_dlg.h for values)

+*/

+

+

+#define IPC_CB_RESETFONT 629

+

+

+#define IPC_IS_FULLSCREEN 630

+/* (requires Winamp 5.0+)

+** int val=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_IS_FULLSCREEN);

+** This will return 1 if the video or visualisation is in fullscreen mode or 0 otherwise.

+*/

+

+

+#define IPC_SET_VIS_FS_FLAG 631

+/* (requires Winamp 5.0+)

+** A vis should send this message with 1/as param to notify winamp that it has gone to or has come back from fullscreen mode

+*/

+

+

+#define IPC_SHOW_NOTIFICATION 632

+

+

+#define IPC_GETSKININFO 633

+#define IPC_GETSKININFOW 1633

+/* (requires Winamp 5.0+)

+** This is a notification message sent to the main Winamp window by itself whenever it

+** needs to get information to be shown about the current skin in the 'Current skin

+** information' box on the main Skins page in the Winamp preferences.

+**

+** When this notification is received and the current skin is one you are providing the

+** support for then you return a valid buffer for Winamp to be able to read from with

+** information about it such as the name of the skin file.

+**

+** if(uMsg == WM_WA_IPC && lParam == IPC_GETSKININFO){

+**   if(is_our_skin()){

+**      return is_our_skin_name();

+**   }

+** }

+*/

+

+

+#define IPC_GET_MANUALPLADVANCE 634

+/* (requires Winamp 5.03+)

+** int val=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GET_MANUALPLADVANCE);

+** IPC_GET_MANUALPLADVANCE returns the status of the Manual Playlist Advance.

+** If enabled this will return 1 otherwise it will return 0.

+*/

+

+

+#define IPC_SET_MANUALPLADVANCE 635

+/* (requires Winamp 5.03+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,value,IPC_SET_MANUALPLADVANCE);

+** IPC_SET_MANUALPLADVANCE sets the status of the Manual Playlist Advance option.

+** Set value = 1 to turn it on and value = 0 to turn it off.

+*/

+

+

+#define IPC_GET_NEXT_PLITEM 636

+/* (requires Winamp 5.04+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_EOF_GET_NEXT_PLITEM);

+**

+** Sent to Winamp's main window when an item has just finished playback or the next

+** button has been pressed and requesting the new playlist item number to go to.

+**

+** Subclass this message in your application to return the new item number.

+** Return -1 for normal Winamp operation (default) or the new item number in

+** the playlist to be played instead of the originally selected next track.

+**

+** This is primarily provided for the JTFE plugin (gen_jumpex.dll).

+*/

+

+

+#define IPC_GET_PREVIOUS_PLITEM 637

+/* (requires Winamp 5.04+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_EOF_GET_PREVIOUS_PLITEM);

+**

+** Sent to Winamp's main window when the previous button has been pressed and Winamp is

+** requesting the new playlist item number to go to.

+**

+** Return -1 for normal Winamp operation (default) or the new item number in

+** the playlist to be played instead of the originally selected previous track.

+**

+** This is primarily provided for the JTFE plugin (gen_jumpex.dll).

+*/

+

+

+#define IPC_IS_WNDSHADE 638

+/* (requires Winamp 5.04+)

+** int is_shaded=SendMessage(hwnd_winamp,WM_WA_IPC,wnd,IPC_IS_WNDSHADE);

+** Pass 'wnd' as an id as defined for IPC_GETWND or pass -1 to query the status of the

+** main window. This returns 1 if the window is in winshade mode and 0 if it is not.

+** Make sure you only test for this on a 5.04+ install otherwise you get a false result.

+** (See the notes about unhandled WM_WA_IPC messages).

+*/

+

+

+#define IPC_SETRATING 639

+/* (requires Winamp 5.04+ with ML)

+** int rating=SendMessage(hwnd_winamp,WM_WA_IPC,rating,IPC_SETRATING);

+** This will allow you to set the 'rating' on the current playlist entry where 'rating'

+** is an integer value from 0 (no rating) to 5 (5 stars).

+**

+** The following example should correctly allow you to set the rating for any specified

+** playlist entry assuming of course that you're trying to get a valid playlist entry.

+**

+** void SetPlaylistItemRating(int item_to_set, int rating_to_set){

+** int cur_pos=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETLISTPOS);

+**   SendMessage(hwnd_winamp,WM_WA_IPC,item_to_set,IPC_SETPLAYLISTPOS);

+**   SendMessage(hwnd_winamp,WM_WA_IPC,rating_to_set,IPC_SETRATING);

+**   SendMessage(hwnd_winamp,WM_WA_IPC,cur_pos,IPC_SETPLAYLISTPOS);

+** }

+*/

+

+

+#define IPC_GETRATING 640

+/* (requires Winamp 5.04+ with ML)

+** int rating=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETRATING);

+** This returns the current playlist entry's rating between 0 (no rating) to 5 (5 stars).

+**

+** The following example should correctly allow you to get the rating for any specified

+** playlist entry assuming of course that you're trying to get a valid playlist entry.

+**

+** int GetPlaylistItemRating(int item_to_get, int rating_to_set){

+** int cur_pos=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETLISTPOS), rating = 0;

+**   SendMessage(hwnd_winamp,WM_WA_IPC,item_to_get,IPC_SETPLAYLISTPOS);

+**   rating = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETRATING);

+**   SendMessage(hwnd_winamp,WM_WA_IPC,cur_pos,IPC_SETPLAYLISTPOS);

+**   return rating;

+** }

+*/

+

+

+#define IPC_GETNUMAUDIOTRACKS 641

+/* (requires Winamp 5.04+)

+** int n = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETNUMAUDIOTRACKS);

+** This will return the number of audio tracks available from the currently playing item.

+*/

+

+

+#define IPC_GETNUMVIDEOTRACKS 642

+/* (requires Winamp 5.04+)

+** int n = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETNUMVIDEOTRACKS);

+** This will return the number of video tracks available from the currently playing item.

+*/

+

+

+#define IPC_GETAUDIOTRACK 643

+/* (requires Winamp 5.04+)

+** int cur = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETAUDIOTRACK);

+** This will return the id of the current audio track for the currently playing item.

+*/

+

+

+#define IPC_GETVIDEOTRACK 644

+/* (requires Winamp 5.04+)

+** int cur = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETVIDEOTRACK);

+** This will return the id of the current video track for the currently playing item.

+*/

+

+

+#define IPC_SETAUDIOTRACK 645

+/* (requires Winamp 5.04+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,track,IPC_SETAUDIOTRACK);

+** This allows you to switch to a new audio track (if supported) in the current playing file.

+*/

+

+

+#define IPC_SETVIDEOTRACK 646

+/* (requires Winamp 5.04+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,track,IPC_SETVIDEOTRACK);

+** This allows you to switch to a new video track (if supported) in the current playing file.

+*/

+

+

+#define IPC_PUSH_DISABLE_EXIT 647

+/* (requires Winamp 5.04+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_PUSH_DISABLE_EXIT);

+** This will let you disable or re-enable the UI exit functions (close button, context

+** menu, alt-f4). Remember to call IPC_POP_DISABLE_EXIT when you are done doing whatever

+** was required that needed to prevent exit otherwise you have to kill the Winamp process.

+*/

+

+

+#define IPC_POP_DISABLE_EXIT  648

+/* (requires Winamp 5.04+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_POP_DISABLE_EXIT);

+** See IPC_PUSH_DISABLE_EXIT

+*/

+

+

+#define IPC_IS_EXIT_ENABLED 649

+/* (requires Winamp 5.04+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_IS_EXIT_ENABLED);

+** This will return 0 if the 'exit' option of Winamp's menu is disabled and 1 otherwise.

+*/

+

+

+#define IPC_IS_AOT 650

+/* (requires Winamp 5.04+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_IS_AOT);

+** This will return the status of the always on top flag.

+** Note: This may not match the actual TOPMOST window flag while another fullscreen

+** application is focused if the user has the 'Disable always on top while fullscreen

+** applications are focused' option under the  General Preferences page is checked.

+*/

+

+

+#define IPC_USES_RECYCLEBIN 651

+/* (requires Winamp 5.09+)

+** int use_bin=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_USES_RECYCLEBIN);

+** This will return 1 if the deleted file should be sent to the recycle bin or

+** 0 if deleted files should be deleted permanently (default action for < 5.09).

+**

+** Note: if you use this on pre 5.09 installs of Winamp then it will return 1 which is

+** not correct but is due to the way that SendMessage(..) handles un-processed messages.

+** Below is a quick case for checking if the returned value is correct.

+**

+** if(SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_USES_RECYCLEBIN) &&

+**    SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETVERSION)>=0x5009)

+** {

+**   // can safely follow the option to recycle the file

+** }

+** else

+*  {

+**   // need to do a permanent delete of the file

+** }

+*/

+

+

+#define IPC_FLUSHAUDITS 652

+/*

+** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_FLUSHAUDITS);

+**

+** Will flush any pending audits in the global audits queue

+**

+*/

+

+#define IPC_GETPLAYITEM_START 653

+#define IPC_GETPLAYITEM_END   654

+

+

+#define IPC_GETVIDEORESIZE 655

+#define IPC_SETVIDEORESIZE 656

+

+

+#define IPC_INITIAL_SHOW_STATE 657

+/* (requires Winamp 5.36+)

+** int show_state = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_INITIAL_SHOW_STATE);

+** returns the processed value of nCmdShow when Winamp was started

+** (see MSDN documentation the values passed to WinMain(..) for what this should be)

+**

+** e.g.

+** if(SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_INITIAL_SHOW_STATE) == SW_SHOWMINIMIZED){

+**   // we are starting minimised so process as needed (keep our window hidden)

+** }

+**

+** Useful for seeing if winamp was run minimised on startup so you can act accordingly.

+** On pre-5.36 versions this will effectively return SW_NORMAL/SW_SHOWNORMAL due to the

+** handling of unknown apis returning 1 from Winamp.

+*/

+

+// >>>>>>>>>>> Next is 658

+

+#define IPC_PLCMD  1000

+

+#define PLCMD_ADD  0

+#define PLCMD_REM  1

+#define PLCMD_SEL  2

+#define PLCMD_MISC 3

+#define PLCMD_LIST 4

+

+//#define IPC_MBCMD  1001

+

+#define MBCMD_BACK    0

+#define MBCMD_FORWARD 1

+#define MBCMD_STOP    2

+#define MBCMD_RELOAD  3

+#define MBCMD_MISC  4

+

+#define IPC_VIDCMD 1002

+

+#define VIDCMD_FULLSCREEN 0

+#define VIDCMD_1X         1

+#define VIDCMD_2X         2

+#define VIDCMD_LIB        3

+#define VIDPOPUP_MISC     4

+

+//#define IPC_MBURL       1003 //sets the URL

+//#define IPC_MBGETCURURL 1004 //copies the current URL into wParam (have a 4096 buffer ready)

+//#define IPC_MBGETDESC   1005 //copies the current URL description into wParam (have a 4096 buffer ready)

+//#define IPC_MBCHECKLOCFILE 1006 //checks that the link file is up to date (otherwise updates it). wParam=parent HWND

+//#define IPC_MBREFRESH   1007 //refreshes the "now playing" view in the library

+//#define IPC_MBGETDEFURL 1008 //copies the default URL into wParam (have a 4096 buffer ready)

+

+#define IPC_STATS_LIBRARY_ITEMCNT 1300 // updates library count status

+

+/*

+** IPC's in the message range 2000 - 3000 are reserved internally for freeform messages.

+** These messages are taken from ff_ipc.h which is part of the Modern skin integration.

+*/

+

+#define IPC_FF_FIRST 2000

+

+#define IPC_FF_COLOURTHEME_CHANGE IPC_FF_ONCOLORTHEMECHANGED

+#define IPC_FF_ONCOLORTHEMECHANGED IPC_FF_FIRST + 3

+/*

+** This is a notification message sent when the user changes the colour theme in a Modern

+** skin and can also be detected when the Modern skin is first loaded as the gen_ff plugin

+** applies relevant settings and styles (like the colour theme).

+**

+** The value of wParam is the name of the new color theme being switched to.

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(const char*)colour_theme_name,IPC_FF_ONCOLORTHEMECHANGED);

+**

+** (IPC_FF_COLOURTHEME_CHANGE is the name i (DrO) was using before getting a copy of

+** ff_ipc.h with the proper name in it).

+*/

+

+

+#define IPC_FF_ISMAINWND IPC_FF_FIRST + 4

+/*

+** int ismainwnd = (HWND)SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(HWND)test_wnd,IPC_FF_ISMAINWND);

+**

+** This allows you to determine if the window handle passed to it is a modern skin main

+** window or not. If it is a main window or any of its windowshade variants then it will

+** return 1.

+**

+** Because of the way modern skins are implemented, it is possible for this message to

+** return a positive test result for a number of window handles within the current Winamp

+** process. This appears to be because you can have a visible main window, a compact main

+** window and also a winshaded version.

+**

+** The following code example below is one way of seeing how this api works since it will

+** enumerate all windows related to Winamp at the time and allows you to process as

+** required when a detection happens.

+**

+**

+** EnumThreadWindows(GetCurrentThreadId(),enumWndProc,0);

+**

+** BOOL CALLBACK enumWndProc(HWND hwnd, LPARAM lParam){

+**

+**   if(SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)hwnd,IPC_FF_ISMAINWND)){

+**     // do processing in here

+**     // or continue the enum for other main windows (if they exist)

+**     // and just comment out the line below

+**     return 0;

+**   }

+**   return 1;

+** }

+*/

+

+

+#define IPC_FF_GETCONTENTWND IPC_FF_FIRST + 5

+/*

+** HWND wa2embed = (HWND)SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(HWND)test_wnd,IPC_FF_GETCONTENTWND);

+**

+** This will return the Winamp 2 window that is embedded in the window's container

+** i.e. if hwnd is the playlist editor windowshade hwnd then it will return the Winamp 2

+**      playlist editor hwnd.

+**

+** If no content is found such as the window has nothing embedded then this will return

+** the hwnd passed to it.

+*/

+

+

+#define IPC_FF_NOTIFYHOTKEY IPC_FF_FIRST + 6

+/*

+** This is a notification message sent when the user uses a global hotkey combination

+** which had been registered with the gen_hotkeys plugin.

+**

+** The value of wParam is the description of the hotkey as passed to gen_hotkeys.

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(const char*)hotkey_desc,IPC_FF_NOTIFYHOTKEY);

+*/

+

+#define IPC_FF_LAST  3000

+

+

+/*

+** General IPC messages in Winamp

+**

+** All notification messages appear in the lParam of the main window message proceedure.

+*/

+

+

+#define IPC_GETDROPTARGET 3001

+/* (requires Winamp 5.0+)

+** IDropTarget* IDrop = (IDropTarget*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETDROPTARGET);

+**

+** You call this to retrieve a copy of the IDropTarget interface which Winamp created for

+** handling external drag and drop operations on to it's Windows. This is only really

+** useful if you're providing an alternate interface and want your Windows to provide the

+** same drag and drop support as Winamp normally provides the user. Check out MSDN or

+** your prefered search facility for more information about the IDropTarget interface and

+** what's needed to handle it in your own instance.

+*/

+

+

+#define IPC_PLAYLIST_MODIFIED 3002

+/* (requires Winamp 5.0+)

+** This is a notification message sent to the main Winamp window whenever the playlist is

+** modified in any way e.g. the addition/removal of a playlist entry.

+**

+** It is not a good idea to do large amounts of processing in this notification since it

+** will slow down Winamp as playlist entries are modified (especially when you're adding

+** in a large playlist).

+**

+** if(uMsg == WM_WA_IPC && lParam == IPC_PLAYLIST_MODIFIED)

+** {

+**   // do what you need to do here

+** }

+*/

+

+

+#define IPC_PLAYING_FILE 3003

+/* (requires Winamp 5.0+)

+** This is a notification message sent to the main Winamp window when playback begins for

+** a file. This passes the full filepath in the wParam of the message received.

+**

+** if(uMsg == WM_WA_IPC && lParam == IPC_PLAYING_FILE)

+** {

+**   // do what you need to do here, e.g.

+**   process_file((char*)wParam);

+** }

+*/

+

+

+#define IPC_PLAYING_FILEW 13003

+/* (requires Winamp 5.0+)

+** This is a notification message sent to the main Winamp window when playback begins for

+** a file. This passes the full filepath in the wParam of the message received.

+**

+** if(uMsg == WM_WA_IPC && lParam == IPC_PLAYING_FILEW)

+** {

+**   // do what you need to do here, e.g.

+**   process_file((wchar_t*)wParam);

+** }

+*/

+

+

+#define IPC_FILE_TAG_MAY_HAVE_UPDATED 3004

+#define IPC_FILE_TAG_MAY_HAVE_UPDATEDW 3005

+/* (requires Winamp 5.0+)

+** This is a notification message sent to the main Winamp window when a file's tag

+** (e.g. id3) may have been updated. This appears to be sent when the InfoBox(..) function

+** of the associated input plugin returns a 1 (which is the file information dialog/editor

+** call normally).

+**

+** if(uMsg == WM_WA_IPC && lParam == IPC_FILE_TAG_MAY_HAVE_UPDATED)

+** {

+**   // do what you need to do here, e.g.

+**   update_info_on_file_update((char*)wParam);

+** }

+*/

+

+

+#define IPC_ALLOW_PLAYTRACKING 3007

+/* (requires Winamp 5.0+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,allow,IPC_ALLOW_PLAYTRACKING);

+** Send allow as nonzero to allow play tracking and zero to disable the mode.

+*/

+

+

+#define IPC_HOOK_OKTOQUIT 3010

+/* (requires Winamp 5.0+)

+** This is a notification message sent to the main Winamp window asking if it's okay to

+** close or not. Return zero to prevent Winamp from closing or return anything non-zero

+** to allow Winamp to close.

+**

+** The best implementation of this option is to let the message pass through to the

+** original window proceedure since another plugin may want to have a say in the matter

+** with regards to Winamp closing.

+**

+** if(uMsg == WM_WA_IPC && lParam == IPC_HOOK_OKTOQUIT)

+** {

+**   // do what you need to do here, e.g.

+**   if(no_shut_down())

+**   {

+**     return 1;

+**   }

+** }

+*/

+

+

+#define IPC_WRITECONFIG 3011

+/* (requires Winamp 5.0+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,write_type,IPC_WRITECONFIG);

+**

+** Send write_type as 2 to write all config settings and the current playlist.

+**

+** Send write_type as 1 to write the playlist and common settings.

+** This won't save the following ini settings::

+**

+**   defext, titlefmt, proxy, visplugin_name, dspplugin_name, check_ft_startup,

+**   visplugin_num, pe_fontsize, visplugin_priority, visplugin_autoexec, dspplugin_num,

+**   sticon, splash, taskbar, dropaotfs, ascb_new, ttips, riol, minst, whichicon,

+**   whichicon2, addtolist, snap, snaplen, parent, hilite, disvis, rofiob, shownumsinpl,

+**   keeponscreen, eqdsize, usecursors, fixtitles, priority, shuffle_morph_rate,

+**   useexttitles, bifont, inet_mode, ospb, embedwnd_freesize, no_visseh

+** (the above was valid for 5.1)

+**

+** Send write_type as 0 to write the common and less common settings and no playlist.

+*/

+

+

+#define IPC_UPDATE_URL 3012

+// pass the URL (char *) in lparam, will be free()'d on done.

+

+

+#define IPC_GET_RANDFUNC 3015 // returns a function to get a random number

+/* (requires Winamp 5.1+)

+** int (*randfunc)(void) = (int(*)(void))SendMessage(plugin.hwndParent,WM_WA_IPC,0,IPC_GET_RANDFUNC);

+** if(randfunc && randfunc != 1){

+**   randfunc();

+** }

+**

+** This will return a positive 32-bit number (essentially 31-bit).

+** The check for a returned value of 1 is because that's the default return value from

+** SendMessage(..) when it is not handled so is good to check for it in this situation.

+*/

+

+

+#define IPC_METADATA_CHANGED 3017

+/* (requires Winamp 5.1+)

+** int changed=SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(char*)field,IPC_METADATA_CHANGED);

+** a plugin can SendMessage this to winamp if internal metadata has changes.

+** wParam should be a char * of what field changed

+**

+** Currently used for internal actions (and very few at that) the intent of this api is

+** to allow a plugin to call it when metadata has changed in the current playlist entry

+** e.g.a new id3v2 tag was found in a stream

+**

+** The wparam value can either be NULL or a pointer to an ansi string for the metadata

+** which has changed. This can be thought of as an advanced version of IPC_UPDTITLE and

+** could be used to allow for update of the current title when a specific tag changed.

+**

+** Not recommended to be used since there is not the complete handling implemented in

+** Winamp for it at the moment.

+*/

+

+

+#define IPC_SKIN_CHANGED 3018

+/* (requires Winamp 5.1+)

+** This is a notification message sent to the main Winamp window by itself whenever

+** the skin in use is changed. There is no information sent by the wParam for this.

+**

+** if(message == WM_WA_IPC && lparam == IPC_SKIN_CHANGED)

+** {

+**   // do what you need to do to handle skin changes, e.g. call WADlg_init(hwnd_winamp);

+** }

+*/

+

+

+#define IPC_REGISTER_LOWORD_COMMAND 3019

+/* (requires Winamp 5.1+)

+** WORD id = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_REGISTER_LOWORD_COMMAND);

+** This will assign you a unique id for making your own commands such as for extra menu

+** entries. The starting value returned by this message will potentially change as and

+** when the main resource file of Winamp is updated with extra data so assumptions cannot

+** be made on what will be returned and plugin loading order will affect things as well.

+

+** 5.33+

+** If you want to reserve more than one id, you can pass the number of ids required in wParam

+*/

+

+

+#define IPC_GET_DISPATCH_OBJECT 3020  // gets winamp main IDispatch * (for embedded webpages)

+#define IPC_GET_UNIQUE_DISPATCH_ID 3021 // gives you a unique dispatch ID that won't conflict with anything in winamp's IDispatch *

+#define IPC_ADD_DISPATCH_OBJECT 3022 // add your own dispatch object into winamp's.  This lets embedded webpages access your functions

+// pass a pointer to DispatchInfo (see below).  Winamp makes a copy of all this data so you can safely delete it later

+typedef struct

+{

+  wchar_t *name; // filled in by plugin, make sure it's a unicode string!! (i.e. L"myObject" instead of "myObject).

+  struct IDispatch *dispatch; // filled in by plugin

+  DWORD id; // filled in by winamp on return

+} DispatchInfo;

+

+// see IPC_JSAPI2_GET_DISPATCH_OBJECT for version 2 of the Dispatchable scripting interface

+

+#define IPC_GET_PROXY_STRING 3023

+/* (requires Winamp 5.11+)

+** char* proxy_string=(char*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GET_PROXY_STRING);

+** This will return the same string as is shown on the General Preferences page.

+*/

+

+

+#define IPC_USE_REGISTRY 3024

+/* (requires Winamp 5.11+)

+** int reg_enabled=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_USE_REGISTRY);

+** This will return 0 if you should leave your grubby hands off the registry (i.e. for

+** lockdown mode). This is useful if Winamp is run from a USB drive and you can't alter

+** system settings, etc.

+*/

+

+

+#define IPC_GET_API_SERVICE 3025

+/* (requires Winamp 5.12+)

+** api_service* api_service = (api_service)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GET_API_SERVICE);

+** This api will return Winamp's api_service pointer (which is what Winamp3 used, heh).

+** If this api is not supported in the Winamp version that is being used at the time then

+** the returned value from this api will be 1 which is a good version check.

+**

+** As of 5.12 there is support for .w5s plugins which reside in %WinampDir%\System and

+** are intended for common code that can be shared amongst other plugins e.g. jnetlib.w5s

+** which contains jnetlib in one instance instead of being duplicated multiple times in

+** all of the plugins which need internet access.

+**

+** Details on the .w5s specifications will come at some stage (possibly).

+*/

+

+

+typedef struct {

+  const wchar_t *filename;

+  const wchar_t *metadata;

+  wchar_t *ret;

+  size_t retlen;

+} extendedFileInfoStructW;

+

+#define IPC_GET_EXTENDED_FILE_INFOW 3026

+/* (requires Winamp 5.13+)

+** Pass a pointer to the above struct in wParam

+*/

+

+

+#define IPC_GET_EXTENDED_FILE_INFOW_HOOKABLE 3027

+#define IPC_SET_EXTENDED_FILE_INFOW 3028

+/* (requires Winamp 5.13+)

+** Pass a pointer to the above struct in wParam

+*/

+

+

+#define IPC_PLAYLIST_GET_NEXT_SELECTED 3029

+/* (requires 5.2+)

+** int pl_item = SendMessage(hwnd_winamp,WM_WA_IPC,start,IPC_PLAYLIST_GET_NEXT_SELECTED);

+**

+** This works just like the ListView_GetNextItem(..) macro for ListView controls.

+** 'start' is the index of the playlist item that you want to begin the search after or

+** set this as -1 for the search to begin with the first item of the current playlist.

+**

+** This will return the index of the selected playlist according to the 'start' value or

+** it returns -1 if there is no selection or no more selected items according to 'start'.

+**

+** Quick example:

+**

+** int sel = -1;

+** // keep incrementing the start of the search so we get all of the selected entries

+** while((sel = SendMessage(hwnd_winamp,WM_WA_IPC,sel,IPC_PLAYLIST_GET_NEXT_SELECTED))!=-1){

+**   // show the playlist file entry of the selected item(s) if there were any

+**   MessageBox(hwnd_winamp,(char*)SendMessage(hwnd_winamp,WM_WA_IPC,sel,IPC_GETPLAYLISTFILE),0,0);

+** }

+*/

+

+

+#define IPC_PLAYLIST_GET_SELECTED_COUNT 3030

+/* (requires 5.2+)

+** int selcnt = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_PLAYLIST_GET_SELECTED_COUNT);

+** This will return the number of selected playlist entries.

+*/

+

+

+#define IPC_GET_PLAYING_FILENAME 3031

+// returns wchar_t * of the currently playing filename

+

+#define IPC_OPEN_URL 3032

+// send either ANSI or Unicode string (it'll figure it out, but it MUST start with "h"!, so don't send ftp:// or anything funny)

+// you can also send this one from another process via WM_COPYDATA (unicode only)

+

+

+#define IPC_USE_UXTHEME_FUNC 3033

+/* (requires Winamp 5.35+)

+** int ret = SendMessage(hwnd_winamp,WM_WA_IPC,param,IPC_USE_UXTHEME_FUNC);

+** param can be IPC_ISWINTHEMEPRESENT or IPC_ISAEROCOMPOSITIONACTIVE or a valid hwnd.

+**

+** If you pass a hwnd then it will apply EnableThemeDialogTexture(ETDT_ENABLETAB)

+** so your tabbed dialogs can use the correct theme (on supporting OSes ie XP+).

+**

+** Otherwise this will return a value based on the param passed (as defined below).

+** For compatability, the return value will be zero on success (as 1 is returned

+** for unsupported ipc calls on older Winamp versions)

+*/

+  #define IPC_ISWINTHEMEPRESENT 0

+/* This will return 0 if uxtheme.dll is present

+** int isthemethere = !SendMessage(hwnd_winamp,WM_WA_IPC,IPC_ISWINTHEMEPRESENT,IPC_USE_UXTHEME_FUNC);

+*/

+  #define IPC_ISAEROCOMPOSITIONACTIVE 1

+/* This will return 0 if aero composition is active

+** int isaero = !SendMessage(hwnd_winamp,WM_WA_IPC,IPC_ISAEROCOMPOSITIONACTIVE,IPC_USE_UXTHEME_FUNC);

+*/

+

+

+#define IPC_GET_PLAYING_TITLE 3034

+// returns wchar_t * of the current title

+

+

+#define IPC_CANPLAY 3035

+// pass const wchar_t *, returns an in_mod * or 0

+

+

+typedef struct {

+  // fill these in...

+  size_t size; // init to sizeof(artFetchData)

+  HWND parent; // parent window of the dialogue

+

+  // fill as much of these in as you can, otherwise leave them 0

+  const wchar_t *artist;

+  const wchar_t *album;

+  int year, amgArtistId, amgAlbumId;

+

+  int showCancelAll; // if set to 1, this shows a "Cancel All" button on the dialogue

+

+  // winamp will fill these in if the call returns successfully:

+  void* imgData; // a buffer filled with compressed image data. free with WASABI_API_MEMMGR->sysFree()

+  int imgDataLen; // the size of the buffer

+  wchar_t type[10]; // eg: "jpg"

+  const wchar_t *gracenoteFileId; // if you know it

+} artFetchData;

+

+#define IPC_FETCH_ALBUMART 3036

+/* pass an artFetchData*. This will show a dialog guiding the use through choosing art, and return when it's finished

+** return values:

+** 1: error showing dialog

+** 0: success

+** -1: cancel was pressed

+** -2: cancel all was pressed

+*/

+

+#define IPC_JSAPI2_GET_DISPATCH_OBJECT 3037

+/* pass your service's unique ID, as a wchar_t * string, in wParam

+** Winamp will copy the string, so don't worry about keeping it around

+** An IDispatch * object will be returned (cast the return value from SendMessage)

+** This IDispatch can be used for scripting/automation/VB interaction

+** Pass to IE via IDocHostUIHandler::GetExternal and it will become window.external in javscript

+*/

+

+#define IPC_REGISTER_WINAMP_IPCMESSAGE 65536

+/* (requires Winamp 5.0+)

+** DWORD id = SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)name,IPC_REGISTER_WINAMP_IPCMESSAGE);

+** The value 'id' returned is > 65536 and is incremented on subsequent calls for unique

+** 'name' values passed to it. By using the same 'name' in different plugins will allow a

+** common runtime api to be provided for the currently running instance of Winamp

+** e.g.

+**   PostMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)my_param,registered_ipc);

+** Have a look at wa_hotkeys.h for an example on how this api is used in practice for a

+** custom WM_WA_IPC message.

+**

+** if(uMsg == WM_WA_IPC && lParam == id_from_register_winamp_ipcmessage){

+**   // do things

+** }

+*/

+

+#endif//_WA_IPC_H_

 

--- /dev/null
+++ b/src/in_xsf_framework/zlib/adler32.c
@@ -1,1 +1,187 @@
+/* adler32.c -- compute the Adler-32 checksum of a data stream
+ * Copyright (C) 1995-2011, 2016 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
 
+/* @(#) $Id$ */
+
+#include "zutil.h"
+
+local uLong adler32_combine_ OF((uLong adler1, uLong adler2, z_off64_t len2));
+
+#define BASE 65521U     /* largest prime smaller than 65536 */
+#define NMAX 5552
+/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
+
+#define DO1(buf,i)  {adler += (buf)[i]; sum2 += adler;}
+#define DO2(buf,i)  DO1(buf,i); DO1(buf,i+1);
+#define DO4(buf,i)  DO2(buf,i); DO2(buf,i+2);
+#define DO8(buf,i)  DO4(buf,i); DO4(buf,i+4);
+#define DO16(buf)   DO8(buf,0); DO8(buf,8);
+
+/* use NO_DIVIDE if your processor does not do division in hardware --
+   try it both ways to see which is faster */
+#ifdef NO_DIVIDE
+/* note that this assumes BASE is 65521, where 65536 % 65521 == 15
+   (thank you to John Reiser for pointing this out) */
+#  define CHOP(a) \
+    do { \
+        unsigned long tmp = a >> 16; \
+        a &= 0xffffUL; \
+        a += (tmp << 4) - tmp; \
+    } while (0)
+#  define MOD28(a) \
+    do { \
+        CHOP(a); \
+        if (a >= BASE) a -= BASE; \
+    } while (0)
+#  define MOD(a) \
+    do { \
+        CHOP(a); \
+        MOD28(a); \
+    } while (0)
+#  define MOD63(a) \
+    do { /* this assumes a is not negative */ \
+        z_off64_t tmp = a >> 32; \
+        a &= 0xffffffffL; \
+        a += (tmp << 8) - (tmp << 5) + tmp; \
+        tmp = a >> 16; \
+        a &= 0xffffL; \
+        a += (tmp << 4) - tmp; \
+        tmp = a >> 16; \
+        a &= 0xffffL; \
+        a += (tmp << 4) - tmp; \
+        if (a >= BASE) a -= BASE; \
+    } while (0)
+#else
+#  define MOD(a) a %= BASE
+#  define MOD28(a) a %= BASE
+#  define MOD63(a) a %= BASE
+#endif
+
+/* ========================================================================= */
+uLong ZEXPORT adler32_z(adler, buf, len)
+    uLong adler;
+    const Bytef *buf;
+    z_size_t len;
+{
+    unsigned long sum2;
+    unsigned n;
+
+    /* split Adler-32 into component sums */
+    sum2 = (adler >> 16) & 0xffff;
+    adler &= 0xffff;
+
+    /* in case user likes doing a byte at a time, keep it fast */
+    if (len == 1) {
+        adler += buf[0];
+        if (adler >= BASE)
+            adler -= BASE;
+        sum2 += adler;
+        if (sum2 >= BASE)
+            sum2 -= BASE;
+        return adler | (sum2 << 16);
+    }
+
+    /* initial Adler-32 value (deferred check for len == 1 speed) */
+    if (buf == Z_NULL)
+        return 1L;
+
+    /* in case short lengths are provided, keep it somewhat fast */
+    if (len < 16) {
+        while (len--) {
+            adler += *buf++;
+            sum2 += adler;
+        }
+        if (adler >= BASE)
+            adler -= BASE;
+        MOD28(sum2);            /* only added so many BASE's */
+        return adler | (sum2 << 16);
+    }
+
+    /* do length NMAX blocks -- requires just one modulo operation */
+    while (len >= NMAX) {
+        len -= NMAX;
+        n = NMAX / 16;          /* NMAX is divisible by 16 */
+        do {
+            DO16(buf);          /* 16 sums unrolled */
+            buf += 16;
+        } while (--n);
+        MOD(adler);
+        MOD(sum2);
+    }
+
+    /* do remaining bytes (less than NMAX, still just one modulo) */
+    if (len) {                  /* avoid modulos if none remaining */
+        while (len >= 16) {
+            len -= 16;
+            DO16(buf);
+            buf += 16;
+        }
+        while (len--) {
+            adler += *buf++;
+            sum2 += adler;
+        }
+        MOD(adler);
+        MOD(sum2);
+    }
+
+    /* return recombined sums */
+    return adler | (sum2 << 16);
+}
+
+/* ========================================================================= */
+uLong ZEXPORT adler32(adler, buf, len)
+    uLong adler;
+    const Bytef *buf;
+    uInt len;
+{
+    return adler32_z(adler, buf, len);
+}
+
+/* ========================================================================= */
+local uLong adler32_combine_(adler1, adler2, len2)
+    uLong adler1;
+    uLong adler2;
+    z_off64_t len2;
+{
+    unsigned long sum1;
+    unsigned long sum2;
+    unsigned rem;
+
+    /* for negative len, return invalid adler32 as a clue for debugging */
+    if (len2 < 0)
+        return 0xffffffffUL;
+
+    /* the derivation of this formula is left as an exercise for the reader */
+    MOD63(len2);                /* assumes len2 >= 0 */
+    rem = (unsigned)len2;
+    sum1 = adler1 & 0xffff;
+    sum2 = rem * sum1;
+    MOD(sum2);
+    sum1 += (adler2 & 0xffff) + BASE - 1;
+    sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
+    if (sum1 >= BASE) sum1 -= BASE;
+    if (sum1 >= BASE) sum1 -= BASE;
+    if (sum2 >= ((unsigned long)BASE << 1)) sum2 -= ((unsigned long)BASE << 1);
+    if (sum2 >= BASE) sum2 -= BASE;
+    return sum1 | (sum2 << 16);
+}
+
+/* ========================================================================= */
+uLong ZEXPORT adler32_combine(adler1, adler2, len2)
+    uLong adler1;
+    uLong adler2;
+    z_off_t len2;
+{
+    return adler32_combine_(adler1, adler2, len2);
+}
+
+uLong ZEXPORT adler32_combine64(adler1, adler2, len2)
+    uLong adler1;
+    uLong adler2;
+    z_off64_t len2;
+{
+    return adler32_combine_(adler1, adler2, len2);
+}
+

--- /dev/null
+++ b/src/in_xsf_framework/zlib/crc32.c
@@ -1,1 +1,443 @@
-
+/* crc32.c -- compute the CRC-32 of a data stream
+ * Copyright (C) 1995-2006, 2010, 2011, 2012, 2016 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ *
+ * Thanks to Rodney Brown <rbrown64@csc.com.au> for his contribution of faster
+ * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing
+ * tables for updating the shift register in one step with three exclusive-ors
+ * instead of four steps with four exclusive-ors.  This results in about a
+ * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3.
+ */
+
+/* @(#) $Id$ */
+
+/*
+  Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
+  protection on the static variables used to control the first-use generation
+  of the crc tables.  Therefore, if you #define DYNAMIC_CRC_TABLE, you should
+  first call get_crc_table() to initialize the tables before allowing more than
+  one thread to use crc32().
+
+  DYNAMIC_CRC_TABLE and MAKECRCH can be #defined to write out crc32.h.
+ */
+
+#ifdef MAKECRCH
+#  include <stdio.h>
+#  ifndef DYNAMIC_CRC_TABLE
+#    define DYNAMIC_CRC_TABLE
+#  endif /* !DYNAMIC_CRC_TABLE */
+#endif /* MAKECRCH */
+
+#include "zutil.h"      /* for STDC and FAR definitions */
+
+/* Definitions for doing the crc four data bytes at a time. */
+#if !defined(NOBYFOUR) && defined(Z_U4)
+#  define BYFOUR
+#endif
+#ifdef BYFOUR
+   local unsigned long crc32_little OF((unsigned long,
+                        const unsigned char FAR *, z_size_t));
+   local unsigned long crc32_big OF((unsigned long,
+                        const unsigned char FAR *, z_size_t));
+#  define TBLS 8
+#else
+#  define TBLS 1
+#endif /* BYFOUR */
+
+/* Local functions for crc concatenation */
+local unsigned long gf2_matrix_times OF((unsigned long *mat,
+                                         unsigned long vec));
+local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
+local uLong crc32_combine_ OF((uLong crc1, uLong crc2, z_off64_t len2));
+
+
+#ifdef DYNAMIC_CRC_TABLE
+
+local volatile int crc_table_empty = 1;
+local z_crc_t FAR crc_table[TBLS][256];
+local void make_crc_table OF((void));
+#ifdef MAKECRCH
+   local void write_table OF((FILE *, const z_crc_t FAR *));
+#endif /* MAKECRCH */
+/*
+  Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
+  x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
+
+  Polynomials over GF(2) are represented in binary, one bit per coefficient,
+  with the lowest powers in the most significant bit.  Then adding polynomials
+  is just exclusive-or, and multiplying a polynomial by x is a right shift by
+  one.  If we call the above polynomial p, and represent a byte as the
+  polynomial q, also with the lowest power in the most significant bit (so the
+  byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
+  where a mod b means the remainder after dividing a by b.
+
+  This calculation is done using the shift-register method of multiplying and
+  taking the remainder.  The register is initialized to zero, and for each
+  incoming bit, x^32 is added mod p to the register if the bit is a one (where
+  x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
+  x (which is shifting right by one and adding x^32 mod p if the bit shifted
+  out is a one).  We start with the highest power (least significant bit) of
+  q and repeat for all eight bits of q.
+
+  The first table is simply the CRC of all possible eight bit values.  This is
+  all the information needed to generate CRCs on data a byte at a time for all
+  combinations of CRC register values and incoming bytes.  The remaining tables
+  allow for word-at-a-time CRC calculation for both big-endian and little-
+  endian machines, where a word is four bytes.
+*/
+local void make_crc_table()
+{
+    z_crc_t c;
+    int n, k;
+    z_crc_t poly;                       /* polynomial exclusive-or pattern */
+    /* terms of polynomial defining this crc (except x^32): */
+    static volatile int first = 1;      /* flag to limit concurrent making */
+    static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
+
+    /* See if another task is already doing this (not thread-safe, but better
+       than nothing -- significantly reduces duration of vulnerability in
+       case the advice about DYNAMIC_CRC_TABLE is ignored) */
+    if (first) {
+        first = 0;
+
+        /* make exclusive-or pattern from polynomial (0xedb88320UL) */
+        poly = 0;
+        for (n = 0; n < (int)(sizeof(p)/sizeof(unsigned char)); n++)
+            poly |= (z_crc_t)1 << (31 - p[n]);
+
+        /* generate a crc for every 8-bit value */
+        for (n = 0; n < 256; n++) {
+            c = (z_crc_t)n;
+            for (k = 0; k < 8; k++)
+                c = c & 1 ? poly ^ (c >> 1) : c >> 1;
+            crc_table[0][n] = c;
+        }
+
+#ifdef BYFOUR
+        /* generate crc for each value followed by one, two, and three zeros,
+           and then the byte reversal of those as well as the first table */
+        for (n = 0; n < 256; n++) {
+            c = crc_table[0][n];
+            crc_table[4][n] = ZSWAP32(c);
+            for (k = 1; k < 4; k++) {
+                c = crc_table[0][c & 0xff] ^ (c >> 8);
+                crc_table[k][n] = c;
+                crc_table[k + 4][n] = ZSWAP32(c);
+            }
+        }
+#endif /* BYFOUR */
+
+        crc_table_empty = 0;
+    }
+    else {      /* not first */
+        /* wait for the other guy to finish (not efficient, but rare) */
+        while (crc_table_empty)
+            ;
+    }
+
+#ifdef MAKECRCH
+    /* write out CRC tables to crc32.h */
+    {
+        FILE *out;
+
+        out = fopen("crc32.h", "w");
+        if (out == NULL) return;
+        fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
+        fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
+        fprintf(out, "local const z_crc_t FAR ");
+        fprintf(out, "crc_table[TBLS][256] =\n{\n  {\n");
+        write_table(out, crc_table[0]);
+#  ifdef BYFOUR
+        fprintf(out, "#ifdef BYFOUR\n");
+        for (k = 1; k < 8; k++) {
+            fprintf(out, "  },\n  {\n");
+            write_table(out, crc_table[k]);
+        }
+        fprintf(out, "#endif\n");
+#  endif /* BYFOUR */
+        fprintf(out, "  }\n};\n");
+        fclose(out);
+    }
+#endif /* MAKECRCH */
+}
+
+#ifdef MAKECRCH
+local void write_table(out, table)
+    FILE *out;
+    const z_crc_t FAR *table;
+{
+    int n;
+
+    for (n = 0; n < 256; n++)
+        fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : "    ",
+                (unsigned long)(table[n]),
+                n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
+}
+#endif /* MAKECRCH */
+
+#else /* !DYNAMIC_CRC_TABLE */
+/* ========================================================================
+ * Tables of CRC-32s of all single-byte values, made by make_crc_table().
+ */
+#include "crc32.h"
+#endif /* DYNAMIC_CRC_TABLE */
+
+/* =========================================================================
+ * This function can be used by asm versions of crc32()
+ */
+const z_crc_t FAR * ZEXPORT get_crc_table()
+{
+#ifdef DYNAMIC_CRC_TABLE
+    if (crc_table_empty)
+        make_crc_table();
+#endif /* DYNAMIC_CRC_TABLE */
+    return (const z_crc_t FAR *)crc_table;
+}
+
+/* ========================================================================= */
+#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
+#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
+
+/* ========================================================================= */
+unsigned long ZEXPORT crc32_z(crc, buf, len)
+    unsigned long crc;
+    const unsigned char FAR *buf;
+    z_size_t len;
+{
+    if (buf == Z_NULL) return 0UL;
+
+#ifdef DYNAMIC_CRC_TABLE
+    if (crc_table_empty)
+        make_crc_table();
+#endif /* DYNAMIC_CRC_TABLE */
+
+#ifdef BYFOUR
+    if (sizeof(void *) == sizeof(ptrdiff_t)) {
+        z_crc_t endian;
+
+        endian = 1;
+        if (*((unsigned char *)(&endian)))
+            return crc32_little(crc, buf, len);
+        else
+            return crc32_big(crc, buf, len);
+    }
+#endif /* BYFOUR */
+    crc = crc ^ 0xffffffffUL;
+    while (len >= 8) {
+        DO8;
+        len -= 8;
+    }
+    if (len) do {
+        DO1;
+    } while (--len);
+    return crc ^ 0xffffffffUL;
+}
+
+/* ========================================================================= */
+unsigned long ZEXPORT crc32(crc, buf, len)
+    unsigned long crc;
+    const unsigned char FAR *buf;
+    uInt len;
+{
+    return crc32_z(crc, buf, len);
+}
+
+#ifdef BYFOUR
+
+/*
+   This BYFOUR code accesses the passed unsigned char * buffer with a 32-bit
+   integer pointer type. This violates the strict aliasing rule, where a
+   compiler can assume, for optimization purposes, that two pointers to
+   fundamentally different types won't ever point to the same memory. This can
+   manifest as a problem only if one of the pointers is written to. This code
+   only reads from those pointers. So long as this code remains isolated in
+   this compilation unit, there won't be a problem. For this reason, this code
+   should not be copied and pasted into a compilation unit in which other code
+   writes to the buffer that is passed to these routines.
+ */
+
+/* ========================================================================= */
+#define DOLIT4 c ^= *buf4++; \
+        c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
+            crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
+#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
+
+/* ========================================================================= */
+local unsigned long crc32_little(crc, buf, len)
+    unsigned long crc;
+    const unsigned char FAR *buf;
+    z_size_t len;
+{
+    register z_crc_t c;
+    register const z_crc_t FAR *buf4;
+
+    c = (z_crc_t)crc;
+    c = ~c;
+    while (len && ((ptrdiff_t)buf & 3)) {
+        c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
+        len--;
+    }
+
+    buf4 = (const z_crc_t FAR *)(const void FAR *)buf;
+    while (len >= 32) {
+        DOLIT32;
+        len -= 32;
+    }
+    while (len >= 4) {
+        DOLIT4;
+        len -= 4;
+    }
+    buf = (const unsigned char FAR *)buf4;
+
+    if (len) do {
+        c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
+    } while (--len);
+    c = ~c;
+    return (unsigned long)c;
+}
+
+/* ========================================================================= */
+#define DOBIG4 c ^= *buf4++; \
+        c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
+            crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
+#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
+
+/* ========================================================================= */
+local unsigned long crc32_big(crc, buf, len)
+    unsigned long crc;
+    const unsigned char FAR *buf;
+    z_size_t len;
+{
+    register z_crc_t c;
+    register const z_crc_t FAR *buf4;
+
+    c = ZSWAP32((z_crc_t)crc);
+    c = ~c;
+    while (len && ((ptrdiff_t)buf & 3)) {
+        c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
+        len--;
+    }
+
+    buf4 = (const z_crc_t FAR *)(const void FAR *)buf;
+    while (len >= 32) {
+        DOBIG32;
+        len -= 32;
+    }
+    while (len >= 4) {
+        DOBIG4;
+        len -= 4;
+    }
+    buf = (const unsigned char FAR *)buf4;
+
+    if (len) do {
+        c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
+    } while (--len);
+    c = ~c;
+    return (unsigned long)(ZSWAP32(c));
+}
+
+#endif /* BYFOUR */
+
+#define GF2_DIM 32      /* dimension of GF(2) vectors (length of CRC) */
+
+/* ========================================================================= */
+local unsigned long gf2_matrix_times(mat, vec)
+    unsigned long *mat;
+    unsigned long vec;
+{
+    unsigned long sum;
+
+    sum = 0;
+    while (vec) {
+        if (vec & 1)
+            sum ^= *mat;
+        vec >>= 1;
+        mat++;
+    }
+    return sum;
+}
+
+/* ========================================================================= */
+local void gf2_matrix_square(square, mat)
+    unsigned long *square;
+    unsigned long *mat;
+{
+    int n;
+
+    for (n = 0; n < GF2_DIM; n++)
+        square[n] = gf2_matrix_times(mat, mat[n]);
+}
+
+/* ========================================================================= */
+local uLong crc32_combine_(crc1, crc2, len2)
+    uLong crc1;
+    uLong crc2;
+    z_off64_t len2;
+{
+    int n;
+    unsigned long row;
+    unsigned long even[GF2_DIM];    /* even-power-of-two zeros operator */
+    unsigned long odd[GF2_DIM];     /* odd-power-of-two zeros operator */
+
+    /* degenerate case (also disallow negative lengths) */
+    if (len2 <= 0)
+        return crc1;
+
+    /* put operator for one zero bit in odd */
+    odd[0] = 0xedb88320UL;          /* CRC-32 polynomial */
+    row = 1;
+    for (n = 1; n < GF2_DIM; n++) {
+        odd[n] = row;
+        row <<= 1;
+    }
+
+    /* put operator for two zero bits in even */
+    gf2_matrix_square(even, odd);
+
+    /* put operator for four zero bits in odd */
+    gf2_matrix_square(odd, even);
+
+    /* apply len2 zeros to crc1 (first square will put the operator for one
+       zero byte, eight zero bits, in even) */
+    do {
+        /* apply zeros operator for this bit of len2 */
+        gf2_matrix_square(even, odd);
+        if (len2 & 1)
+            crc1 = gf2_matrix_times(even, crc1);
+        len2 >>= 1;
+
+        /* if no more bits set, then done */
+        if (len2 == 0)
+            break;
+
+        /* another iteration of the loop with odd and even swapped */
+        gf2_matrix_square(odd, even);
+        if (len2 & 1)
+            crc1 = gf2_matrix_times(odd, crc1);
+        len2 >>= 1;
+
+        /* if no more bits set, then done */
+    } while (len2 != 0);
+
+    /* return combined crc */
+    crc1 ^= crc2;
+    return crc1;
+}
+
+/* ========================================================================= */
+uLong ZEXPORT crc32_combine(crc1, crc2, len2)
+    uLong crc1;
+    uLong crc2;
+    z_off_t len2;
+{
+    return crc32_combine_(crc1, crc2, len2);
+}
+
+uLong ZEXPORT crc32_combine64(crc1, crc2, len2)
+    uLong crc1;
+    uLong crc2;
+    z_off64_t len2;
+{
+    return crc32_combine_(crc1, crc2, len2);
+}
+

--- /dev/null
+++ b/src/in_xsf_framework/zlib/crc32.h
@@ -1,1 +1,442 @@
+/* crc32.h -- tables for rapid CRC calculation
+ * Generated automatically by crc32.c
+ */
 
+local const z_crc_t FAR crc_table[TBLS][256] =
+{
+  {
+    0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
+    0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
+    0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
+    0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
+    0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
+    0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
+    0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
+    0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
+    0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
+    0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
+    0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
+    0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
+    0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
+    0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
+    0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
+    0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
+    0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
+    0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
+    0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
+    0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
+    0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
+    0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
+    0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
+    0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
+    0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
+    0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
+    0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
+    0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
+    0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
+    0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
+    0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
+    0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
+    0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
+    0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
+    0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
+    0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
+    0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
+    0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
+    0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
+    0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
+    0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
+    0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
+    0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
+    0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
+    0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
+    0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
+    0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
+    0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
+    0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
+    0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
+    0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
+    0x2d02ef8dUL
+#ifdef BYFOUR
+  },
+  {
+    0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
+    0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
+    0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
+    0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
+    0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
+    0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
+    0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
+    0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
+    0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
+    0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
+    0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
+    0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
+    0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
+    0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
+    0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
+    0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
+    0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
+    0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
+    0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
+    0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
+    0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
+    0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
+    0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
+    0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
+    0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
+    0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
+    0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
+    0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
+    0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
+    0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
+    0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
+    0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
+    0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
+    0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
+    0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
+    0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
+    0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
+    0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
+    0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
+    0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
+    0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
+    0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
+    0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
+    0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
+    0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
+    0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
+    0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
+    0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
+    0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
+    0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
+    0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
+    0x9324fd72UL
+  },
+  {
+    0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
+    0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
+    0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
+    0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
+    0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
+    0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
+    0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
+    0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
+    0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
+    0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
+    0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
+    0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
+    0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
+    0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
+    0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
+    0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
+    0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
+    0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
+    0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
+    0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
+    0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
+    0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
+    0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
+    0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
+    0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
+    0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
+    0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
+    0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
+    0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
+    0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
+    0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
+    0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
+    0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
+    0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
+    0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
+    0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
+    0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
+    0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
+    0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
+    0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
+    0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
+    0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
+    0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
+    0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
+    0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
+    0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
+    0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
+    0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
+    0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
+    0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
+    0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
+    0xbe9834edUL
+  },
+  {
+    0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
+    0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
+    0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
+    0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
+    0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
+    0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
+    0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
+    0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
+    0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
+    0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
+    0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
+    0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
+    0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
+    0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
+    0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
+    0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
+    0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
+    0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
+    0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
+    0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
+    0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
+    0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
+    0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
+    0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
+    0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
+    0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
+    0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
+    0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
+    0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
+    0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
+    0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
+    0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
+    0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
+    0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
+    0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
+    0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
+    0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
+    0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
+    0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
+    0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
+    0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
+    0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
+    0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
+    0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
+    0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
+    0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
+    0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
+    0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
+    0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
+    0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
+    0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
+    0xde0506f1UL
+  },
+  {
+    0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
+    0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
+    0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
+    0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
+    0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
+    0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
+    0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
+    0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
+    0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
+    0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
+    0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
+    0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
+    0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
+    0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
+    0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
+    0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
+    0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
+    0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
+    0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
+    0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
+    0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
+    0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
+    0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
+    0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
+    0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
+    0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
+    0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
+    0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
+    0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
+    0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
+    0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
+    0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
+    0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
+    0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
+    0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
+    0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
+    0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
+    0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
+    0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
+    0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
+    0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
+    0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
+    0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
+    0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
+    0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
+    0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
+    0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
+    0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
+    0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
+    0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
+    0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
+    0x8def022dUL
+  },
+  {
+    0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
+    0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
+    0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
+    0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
+    0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
+    0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
+    0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
+    0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
+    0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
+    0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
+    0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
+    0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
+    0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
+    0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
+    0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
+    0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
+    0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
+    0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
+    0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
+    0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
+    0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
+    0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
+    0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
+    0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
+    0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
+    0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
+    0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
+    0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
+    0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
+    0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
+    0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
+    0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
+    0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
+    0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
+    0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
+    0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
+    0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
+    0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
+    0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
+    0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
+    0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
+    0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
+    0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
+    0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
+    0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
+    0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
+    0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
+    0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
+    0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
+    0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
+    0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
+    0x72fd2493UL
+  },
+  {
+    0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
+    0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
+    0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
+    0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
+    0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
+    0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
+    0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
+    0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
+    0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
+    0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
+    0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
+    0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
+    0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
+    0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
+    0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
+    0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
+    0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
+    0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
+    0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
+    0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
+    0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
+    0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
+    0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
+    0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
+    0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
+    0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
+    0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
+    0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
+    0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
+    0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
+    0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
+    0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
+    0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
+    0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
+    0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
+    0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
+    0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
+    0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
+    0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
+    0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
+    0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
+    0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
+    0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
+    0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
+    0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
+    0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
+    0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
+    0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
+    0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
+    0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
+    0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
+    0xed3498beUL
+  },
+  {
+    0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
+    0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
+    0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
+    0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
+    0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
+    0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
+    0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
+    0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
+    0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
+    0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
+    0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
+    0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
+    0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
+    0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
+    0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
+    0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
+    0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
+    0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
+    0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
+    0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
+    0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
+    0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
+    0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
+    0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
+    0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
+    0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
+    0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
+    0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
+    0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
+    0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
+    0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
+    0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
+    0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
+    0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
+    0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
+    0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
+    0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
+    0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
+    0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
+    0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
+    0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
+    0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
+    0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
+    0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
+    0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
+    0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
+    0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
+    0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
+    0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
+    0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
+    0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
+    0xf10605deUL
+#endif
+  }
+};
+

--- /dev/null
+++ b/src/in_xsf_framework/zlib/gzguts.h
@@ -1,1 +1,219 @@
-
+/* gzguts.h -- zlib internal header definitions for gz* operations
+ * Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013, 2016 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+#ifdef _LARGEFILE64_SOURCE
+#  ifndef _LARGEFILE_SOURCE
+#    define _LARGEFILE_SOURCE 1
+#  endif
+#  ifdef _FILE_OFFSET_BITS
+#    undef _FILE_OFFSET_BITS
+#  endif
+#endif
+
+#ifdef HAVE_HIDDEN
+#  define ZLIB_INTERNAL __attribute__((visibility ("hidden")))
+#else
+#  define ZLIB_INTERNAL
+#endif
+
+#include <stdio.h>
+#include "zlib.h"
+#ifdef STDC
+#  include <string.h>
+#  include <stdlib.h>
+#  include <limits.h>
+#endif
+
+#ifndef _POSIX_SOURCE
+#  define _POSIX_SOURCE
+#endif
+#include <fcntl.h>
+
+#ifdef _WIN32
+#  include <stddef.h>
+#endif
+
+#if defined(__TURBOC__) || defined(_MSC_VER) || defined(_WIN32)
+#  include <io.h>
+#endif
+
+#if defined(_WIN32) || defined(__CYGWIN__)
+#  define WIDECHAR
+#endif
+
+#ifdef WINAPI_FAMILY
+#  define open _open
+#  define read _read
+#  define write _write
+#  define close _close
+#endif
+
+#ifdef NO_DEFLATE       /* for compatibility with old definition */
+#  define NO_GZCOMPRESS
+#endif
+
+#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
+#  ifndef HAVE_VSNPRINTF
+#    define HAVE_VSNPRINTF
+#  endif
+#endif
+
+#if defined(__CYGWIN__)
+#  ifndef HAVE_VSNPRINTF
+#    define HAVE_VSNPRINTF
+#  endif
+#endif
+
+#if defined(MSDOS) && defined(__BORLANDC__) && (BORLANDC > 0x410)
+#  ifndef HAVE_VSNPRINTF
+#    define HAVE_VSNPRINTF
+#  endif
+#endif
+
+#ifndef HAVE_VSNPRINTF
+#  ifdef MSDOS
+/* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
+   but for now we just assume it doesn't. */
+#    define NO_vsnprintf
+#  endif
+#  ifdef __TURBOC__
+#    define NO_vsnprintf
+#  endif
+#  ifdef WIN32
+/* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
+#    if !defined(vsnprintf) && !defined(NO_vsnprintf)
+#      if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 )
+#         define vsnprintf _vsnprintf
+#      endif
+#    endif
+#  endif
+#  ifdef __SASC
+#    define NO_vsnprintf
+#  endif
+#  ifdef VMS
+#    define NO_vsnprintf
+#  endif
+#  ifdef __OS400__
+#    define NO_vsnprintf
+#  endif
+#  ifdef __MVS__
+#    define NO_vsnprintf
+#  endif
+#endif
+
+/* unlike snprintf (which is required in C99), _snprintf does not guarantee
+   null termination of the result -- however this is only used in gzlib.c where
+   the result is assured to fit in the space provided */
+#if defined(_MSC_VER) && _MSC_VER < 1900
+#  define snprintf _snprintf
+#endif
+
+#ifndef local
+#  define local static
+#endif
+/* since "static" is used to mean two completely different things in C, we
+   define "local" for the non-static meaning of "static", for readability
+   (compile with -Dlocal if your debugger can't find static symbols) */
+
+/* gz* functions always use library allocation functions */
+#ifndef STDC
+  extern voidp  malloc OF((uInt size));
+  extern void   free   OF((voidpf ptr));
+#endif
+
+/* get errno and strerror definition */
+#if defined UNDER_CE
+#  include <windows.h>
+#  define zstrerror() gz_strwinerror((DWORD)GetLastError())
+#else
+#  ifndef NO_STRERROR
+#    include <errno.h>
+#    define zstrerror() strerror(errno)
+#  else
+#    define zstrerror() "stdio error (consult errno)"
+#  endif
+#endif
+
+/* provide prototypes for these when building zlib without LFS */
+#if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0
+    ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));
+    ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));
+    ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile));
+    ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile));
+#endif
+
+/* default memLevel */
+#if MAX_MEM_LEVEL >= 8
+#  define DEF_MEM_LEVEL 8
+#else
+#  define DEF_MEM_LEVEL  MAX_MEM_LEVEL
+#endif
+
+/* default i/o buffer size -- double this for output when reading (this and
+   twice this must be able to fit in an unsigned type) */
+#define GZBUFSIZE 8192
+
+/* gzip modes, also provide a little integrity check on the passed structure */
+#define GZ_NONE 0
+#define GZ_READ 7247
+#define GZ_WRITE 31153
+#define GZ_APPEND 1     /* mode set to GZ_WRITE after the file is opened */
+
+/* values for gz_state how */
+#define LOOK 0      /* look for a gzip header */
+#define COPY 1      /* copy input directly */
+#define GZIP 2      /* decompress a gzip stream */
+
+/* internal gzip file state data structure */
+typedef struct {
+        /* exposed contents for gzgetc() macro */
+    struct gzFile_s x;      /* "x" for exposed */
+                            /* x.have: number of bytes available at x.next */
+                            /* x.next: next output data to deliver or write */
+                            /* x.pos: current position in uncompressed data */
+        /* used for both reading and writing */
+    int mode;               /* see gzip modes above */
+    int fd;                 /* file descriptor */
+    char *path;             /* path or fd for error messages */
+    unsigned size;          /* buffer size, zero if not allocated yet */
+    unsigned want;          /* requested buffer size, default is GZBUFSIZE */
+    unsigned char *in;      /* input buffer (double-sized when writing) */
+    unsigned char *out;     /* output buffer (double-sized when reading) */
+    int direct;             /* 0 if processing gzip, 1 if transparent */
+        /* just for reading */
+    int how;                /* 0: get header, 1: copy, 2: decompress */
+    z_off64_t start;        /* where the gzip data started, for rewinding */
+    int eof;                /* true if end of input file reached */
+    int past;               /* true if read requested past end */
+        /* just for writing */
+    int level;              /* compression level */
+    int strategy;           /* compression strategy */
+        /* seek request */
+    z_off64_t skip;         /* amount to skip (already rewound if backwards) */
+    int seek;               /* true if seek request pending */
+        /* error information */
+    int err;                /* error code */
+    char *msg;              /* error message */
+        /* zlib inflate or deflate stream */
+    z_stream strm;          /* stream structure in-place (not a pointer) */
+} gz_state;
+typedef gz_state FAR *gz_statep;
+
+/* shared functions */
+void ZLIB_INTERNAL gz_error OF((gz_statep, int, const char *));
+#if defined UNDER_CE
+char ZLIB_INTERNAL *gz_strwinerror OF((DWORD error));
+#endif
+
+/* GT_OFF(x), where x is an unsigned value, is true if x > maximum z_off64_t
+   value -- needed when comparing unsigned to z_off64_t, which is signed
+   (possible z_off64_t types off_t, off64_t, and long are all signed) */
+#ifdef INT_MAX
+#  define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > INT_MAX)
+#else
+unsigned ZLIB_INTERNAL gz_intmax OF((void));
+#  define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > gz_intmax())
+#endif
+

--- /dev/null
+++ b/src/in_xsf_framework/zlib/inffast.c
@@ -1,1 +1,324 @@
-
+/* inffast.c -- fast decoding
+ * Copyright (C) 1995-2017 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+#include "zutil.h"
+#include "inftrees.h"
+#include "inflate.h"
+#include "inffast.h"
+
+#ifdef ASMINF
+#  pragma message("Assembler code may have bugs -- use at your own risk")
+#else
+
+/*
+   Decode literal, length, and distance codes and write out the resulting
+   literal and match bytes until either not enough input or output is
+   available, an end-of-block is encountered, or a data error is encountered.
+   When large enough input and output buffers are supplied to inflate(), for
+   example, a 16K input buffer and a 64K output buffer, more than 95% of the
+   inflate execution time is spent in this routine.
+
+   Entry assumptions:
+
+        state->mode == LEN
+        strm->avail_in >= 6
+        strm->avail_out >= 258
+        start >= strm->avail_out
+        state->bits < 8
+
+   On return, state->mode is one of:
+
+        LEN -- ran out of enough output space or enough available input
+        TYPE -- reached end of block code, inflate() to interpret next block
+        BAD -- error in block data
+
+   Notes:
+
+    - The maximum input bits used by a length/distance pair is 15 bits for the
+      length code, 5 bits for the length extra, 15 bits for the distance code,
+      and 13 bits for the distance extra.  This totals 48 bits, or six bytes.
+      Therefore if strm->avail_in >= 6, then there is enough input to avoid
+      checking for available input while decoding.
+
+    - The maximum bytes that a single length/distance pair can output is 258
+      bytes, which is the maximum length that can be coded.  inflate_fast()
+      requires strm->avail_out >= 258 for each loop to avoid checking for
+      output space.
+ */
+void ZLIB_INTERNAL inflate_fast(strm, start)
+z_streamp strm;
+unsigned start;         /* inflate()'s starting value for strm->avail_out */
+{
+    struct inflate_state FAR *state;
+    z_const unsigned char FAR *in;      /* local strm->next_in */
+    z_const unsigned char FAR *last;    /* have enough input while in < last */
+    unsigned char FAR *out;     /* local strm->next_out */
+    unsigned char FAR *beg;     /* inflate()'s initial strm->next_out */
+    unsigned char FAR *end;     /* while out < end, enough space available */
+#ifdef INFLATE_STRICT
+    unsigned dmax;              /* maximum distance from zlib header */
+#endif
+    unsigned wsize;             /* window size or zero if not using window */
+    unsigned whave;             /* valid bytes in the window */
+    unsigned wnext;             /* window write index */
+    unsigned char FAR *window;  /* allocated sliding window, if wsize != 0 */
+    unsigned long hold;         /* local strm->hold */
+    unsigned bits;              /* local strm->bits */
+    code const FAR *lcode;      /* local strm->lencode */
+    code const FAR *dcode;      /* local strm->distcode */
+    unsigned lmask;             /* mask for first level of length codes */
+    unsigned dmask;             /* mask for first level of distance codes */
+    code here;                  /* retrieved table entry */
+    unsigned op;                /* code bits, operation, extra bits, or */
+                                /*  window position, window bytes to copy */
+    unsigned len;               /* match length, unused bytes */
+    unsigned dist;              /* match distance */
+    unsigned char FAR *from;    /* where to copy match from */
+
+    /* copy state to local variables */
+    state = (struct inflate_state FAR *)strm->state;
+    in = strm->next_in;
+    last = in + (strm->avail_in - 5);
+    out = strm->next_out;
+    beg = out - (start - strm->avail_out);
+    end = out + (strm->avail_out - 257);
+#ifdef INFLATE_STRICT
+    dmax = state->dmax;
+#endif
+    wsize = state->wsize;
+    whave = state->whave;
+    wnext = state->wnext;
+    window = state->window;
+    hold = state->hold;
+    bits = state->bits;
+    lcode = state->lencode;
+    dcode = state->distcode;
+    lmask = (1U << state->lenbits) - 1;
+    dmask = (1U << state->distbits) - 1;
+
+    /* decode literals and length/distances until end-of-block or not enough
+       input data or output space */
+    do {
+        if (bits < 15) {
+            hold += (unsigned long)(*in++) << bits;
+            bits += 8;
+            hold += (unsigned long)(*in++) << bits;
+            bits += 8;
+        }
+        here = lcode[hold & lmask];
+      dolen:
+        op = (unsigned)(here.bits);
+        hold >>= op;
+        bits -= op;
+        op = (unsigned)(here.op);
+        if (op == 0) {                          /* literal */
+            Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
+                    "inflate:         literal '%c'\n" :
+                    "inflate:         literal 0x%02x\n", here.val));
+            *out++ = (unsigned char)(here.val);
+        }
+        else if (op & 16) {                     /* length base */
+            len = (unsigned)(here.val);
+            op &= 15;                           /* number of extra bits */
+            if (op) {
+                if (bits < op) {
+                    hold += (unsigned long)(*in++) << bits;
+                    bits += 8;
+                }
+                len += (unsigned)hold & ((1U << op) - 1);
+                hold >>= op;
+                bits -= op;
+            }
+            Tracevv((stderr, "inflate:         length %u\n", len));
+            if (bits < 15) {
+                hold += (unsigned long)(*in++) << bits;
+                bits += 8;
+                hold += (unsigned long)(*in++) << bits;
+                bits += 8;
+            }
+            here = dcode[hold & dmask];
+          dodist:
+            op = (unsigned)(here.bits);
+            hold >>= op;
+            bits -= op;
+            op = (unsigned)(here.op);
+            if (op & 16) {                      /* distance base */
+                dist = (unsigned)(here.val);
+                op &= 15;                       /* number of extra bits */
+                if (bits < op) {
+                    hold += (unsigned long)(*in++) << bits;
+                    bits += 8;
+                    if (bits < op) {
+                        hold += (unsigned long)(*in++) << bits;
+                        bits += 8;
+                    }
+                }
+                dist += (unsigned)hold & ((1U << op) - 1);
+#ifdef INFLATE_STRICT
+                if (dist > dmax) {
+                    strm->msg = (char *)"invalid distance too far back";
+                    state->mode = BAD;
+                    break;
+                }
+#endif
+                hold >>= op;
+                bits -= op;
+                Tracevv((stderr, "inflate:         distance %u\n", dist));
+                op = (unsigned)(out - beg);     /* max distance in output */
+                if (dist > op) {                /* see if copy from window */
+                    op = dist - op;             /* distance back in window */
+                    if (op > whave) {
+                        if (state->sane) {
+                            strm->msg =
+                                (char *)"invalid distance too far back";
+                            state->mode = BAD;
+                            break;
+                        }
+#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
+                        if (len <= op - whave) {
+                            do {
+                                *out++ = 0;
+                            } while (--len);
+                            continue;
+                        }
+                        len -= op - whave;
+                        do {
+                            *out++ = 0;
+                        } while (--op > whave);
+                        if (op == 0) {
+                            from = out - dist;
+                            do {
+                                *out++ = *from++;
+                            } while (--len);
+                            continue;
+                        }
+#endif
+                    }
+                    from = window;
+                    if (wnext == 0) {           /* very common case */
+                        from += wsize - op;
+                        if (op < len) {         /* some from window */
+                            len -= op;
+                            do {
+                                *out++ = *from++;
+                            } while (--op);
+                            from = out - dist;  /* rest from output */
+                        }
+                    }
+                    else if (wnext < op) {      /* wrap around window */
+                        from += wsize + wnext - op;
+                        op -= wnext;
+                        if (op < len) {         /* some from end of window */
+                            len -= op;
+                            do {
+                                *out++ = *from++;
+                            } while (--op);
+                            from = window;
+                            if (wnext < len) {  /* some from start of window */
+                                op = wnext;
+                                len -= op;
+                                do {
+                                    *out++ = *from++;
+                                } while (--op);
+                                from = out - dist;      /* rest from output */
+                            }
+                        }
+                    }
+                    else {                      /* contiguous in window */
+                        from += wnext - op;
+                        if (op < len) {         /* some from window */
+                            len -= op;
+                            do {
+                                *out++ = *from++;
+                            } while (--op);
+                            from = out - dist;  /* rest from output */
+                        }
+                    }
+                    while (len > 2) {
+                        *out++ = *from++;
+                        *out++ = *from++;
+                        *out++ = *from++;
+                        len -= 3;
+                    }
+                    if (len) {
+                        *out++ = *from++;
+                        if (len > 1)
+                            *out++ = *from++;
+                    }
+                }
+                else {
+                    from = out - dist;          /* copy direct from output */
+                    do {                        /* minimum length is three */
+                        *out++ = *from++;
+                        *out++ = *from++;
+                        *out++ = *from++;
+                        len -= 3;
+                    } while (len > 2);
+                    if (len) {
+                        *out++ = *from++;
+                        if (len > 1)
+                            *out++ = *from++;
+                    }
+                }
+            }
+            else if ((op & 64) == 0) {          /* 2nd level distance code */
+                here = dcode[here.val + (hold & ((1U << op) - 1))];
+                goto dodist;
+            }
+            else {
+                strm->msg = (char *)"invalid distance code";
+                state->mode = BAD;
+                break;
+            }
+        }
+        else if ((op & 64) == 0) {              /* 2nd level length code */
+            here = lcode[here.val + (hold & ((1U << op) - 1))];
+            goto dolen;
+        }
+        else if (op & 32) {                     /* end-of-block */
+            Tracevv((stderr, "inflate:         end of block\n"));
+            state->mode = TYPE;
+            break;
+        }
+        else {
+            strm->msg = (char *)"invalid literal/length code";
+            state->mode = BAD;
+            break;
+        }
+    } while (in < last && out < end);
+
+    /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
+    len = bits >> 3;
+    in -= len;
+    bits -= len << 3;
+    hold &= (1U << bits) - 1;
+
+    /* update state and return */
+    strm->next_in = in;
+    strm->next_out = out;
+    strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
+    strm->avail_out = (unsigned)(out < end ?
+                                 257 + (end - out) : 257 - (out - end));
+    state->hold = hold;
+    state->bits = bits;
+    return;
+}
+
+/*
+   inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
+   - Using bit fields for code structure
+   - Different op definition to avoid & for extra bits (do & for table bits)
+   - Three separate decoding do-loops for direct, window, and wnext == 0
+   - Special case for distance > 1 copies to do overlapped load and store copy
+   - Explicit branch predictions (based on measured branch probabilities)
+   - Deferring match copy and interspersed it with decoding subsequent codes
+   - Swapping literal/length else
+   - Swapping window/direct else
+   - Larger unrolled copy loops (three is about right)
+   - Moving len -= 3 statement into middle of loop
+ */
+
+#endif /* !ASMINF */
+

--- /dev/null
+++ b/src/in_xsf_framework/zlib/inffast.h
@@ -1,1 +1,12 @@
+/* inffast.h -- header to use inffast.c
+ * Copyright (C) 1995-2003, 2010 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
 
+/* WARNING: this file should *not* be used by applications. It is
+   part of the implementation of the compression library and is
+   subject to change. Applications should only use zlib.h.
+ */
+
+void ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start));
+

--- /dev/null
+++ b/src/in_xsf_framework/zlib/inffixed.h
@@ -1,1 +1,95 @@
+    /* inffixed.h -- table for decoding fixed codes
+     * Generated automatically by makefixed().
+     */
 
+    /* WARNING: this file should *not* be used by applications.
+       It is part of the implementation of this library and is
+       subject to change. Applications should only use zlib.h.
+     */
+
+    static const code lenfix[512] = {
+        {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
+        {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
+        {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
+        {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
+        {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
+        {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
+        {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
+        {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
+        {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
+        {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
+        {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
+        {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
+        {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
+        {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
+        {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
+        {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
+        {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
+        {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
+        {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
+        {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
+        {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
+        {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
+        {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
+        {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
+        {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
+        {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
+        {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
+        {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
+        {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
+        {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
+        {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
+        {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
+        {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
+        {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
+        {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
+        {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
+        {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
+        {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
+        {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
+        {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
+        {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
+        {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
+        {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
+        {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
+        {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
+        {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
+        {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
+        {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
+        {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
+        {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
+        {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
+        {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
+        {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
+        {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
+        {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
+        {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
+        {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
+        {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
+        {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
+        {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
+        {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
+        {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
+        {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
+        {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
+        {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
+        {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
+        {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
+        {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
+        {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
+        {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
+        {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
+        {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
+        {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
+        {0,9,255}
+    };
+
+    static const code distfix[32] = {
+        {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
+        {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
+        {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
+        {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
+        {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
+        {22,5,193},{64,5,0}
+    };
+

--- /dev/null
+++ b/src/in_xsf_framework/zlib/inflate.c
@@ -1,1 +1,1562 @@
-
+/* inflate.c -- zlib decompression
+ * Copyright (C) 1995-2016 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/*
+ * Change history:
+ *
+ * 1.2.beta0    24 Nov 2002
+ * - First version -- complete rewrite of inflate to simplify code, avoid
+ *   creation of window when not needed, minimize use of window when it is
+ *   needed, make inffast.c even faster, implement gzip decoding, and to
+ *   improve code readability and style over the previous zlib inflate code
+ *
+ * 1.2.beta1    25 Nov 2002
+ * - Use pointers for available input and output checking in inffast.c
+ * - Remove input and output counters in inffast.c
+ * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
+ * - Remove unnecessary second byte pull from length extra in inffast.c
+ * - Unroll direct copy to three copies per loop in inffast.c
+ *
+ * 1.2.beta2    4 Dec 2002
+ * - Change external routine names to reduce potential conflicts
+ * - Correct filename to inffixed.h for fixed tables in inflate.c
+ * - Make hbuf[] unsigned char to match parameter type in inflate.c
+ * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
+ *   to avoid negation problem on Alphas (64 bit) in inflate.c
+ *
+ * 1.2.beta3    22 Dec 2002
+ * - Add comments on state->bits assertion in inffast.c
+ * - Add comments on op field in inftrees.h
+ * - Fix bug in reuse of allocated window after inflateReset()
+ * - Remove bit fields--back to byte structure for speed
+ * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
+ * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
+ * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
+ * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
+ * - Use local copies of stream next and avail values, as well as local bit
+ *   buffer and bit count in inflate()--for speed when inflate_fast() not used
+ *
+ * 1.2.beta4    1 Jan 2003
+ * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
+ * - Move a comment on output buffer sizes from inffast.c to inflate.c
+ * - Add comments in inffast.c to introduce the inflate_fast() routine
+ * - Rearrange window copies in inflate_fast() for speed and simplification
+ * - Unroll last copy for window match in inflate_fast()
+ * - Use local copies of window variables in inflate_fast() for speed
+ * - Pull out common wnext == 0 case for speed in inflate_fast()
+ * - Make op and len in inflate_fast() unsigned for consistency
+ * - Add FAR to lcode and dcode declarations in inflate_fast()
+ * - Simplified bad distance check in inflate_fast()
+ * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
+ *   source file infback.c to provide a call-back interface to inflate for
+ *   programs like gzip and unzip -- uses window as output buffer to avoid
+ *   window copying
+ *
+ * 1.2.beta5    1 Jan 2003
+ * - Improved inflateBack() interface to allow the caller to provide initial
+ *   input in strm.
+ * - Fixed stored blocks bug in inflateBack()
+ *
+ * 1.2.beta6    4 Jan 2003
+ * - Added comments in inffast.c on effectiveness of POSTINC
+ * - Typecasting all around to reduce compiler warnings
+ * - Changed loops from while (1) or do {} while (1) to for (;;), again to
+ *   make compilers happy
+ * - Changed type of window in inflateBackInit() to unsigned char *
+ *
+ * 1.2.beta7    27 Jan 2003
+ * - Changed many types to unsigned or unsigned short to avoid warnings
+ * - Added inflateCopy() function
+ *
+ * 1.2.0        9 Mar 2003
+ * - Changed inflateBack() interface to provide separate opaque descriptors
+ *   for the in() and out() functions
+ * - Changed inflateBack() argument and in_func typedef to swap the length
+ *   and buffer address return values for the input function
+ * - Check next_in and next_out for Z_NULL on entry to inflate()
+ *
+ * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
+ */
+
+#include "zutil.h"
+#include "inftrees.h"
+#include "inflate.h"
+#include "inffast.h"
+
+#ifdef MAKEFIXED
+#  ifndef BUILDFIXED
+#    define BUILDFIXED
+#  endif
+#endif
+
+/* function prototypes */
+local int inflateStateCheck OF((z_streamp strm));
+local void fixedtables OF((struct inflate_state FAR *state));
+local int updatewindow OF((z_streamp strm, const unsigned char FAR *end,
+                           unsigned copy));
+#ifdef BUILDFIXED
+   void makefixed OF((void));
+#endif
+local unsigned syncsearch OF((unsigned FAR *have, const unsigned char FAR *buf,
+                              unsigned len));
+
+local int inflateStateCheck(strm)
+z_streamp strm;
+{
+    struct inflate_state FAR *state;
+    if (strm == Z_NULL ||
+        strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)
+        return 1;
+    state = (struct inflate_state FAR *)strm->state;
+    if (state == Z_NULL || state->strm != strm ||
+        state->mode < HEAD || state->mode > SYNC)
+        return 1;
+    return 0;
+}
+
+int ZEXPORT inflateResetKeep(strm)
+z_streamp strm;
+{
+    struct inflate_state FAR *state;
+
+    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    strm->total_in = strm->total_out = state->total = 0;
+    strm->msg = Z_NULL;
+    if (state->wrap)        /* to support ill-conceived Java test suite */
+        strm->adler = state->wrap & 1;
+    state->mode = HEAD;
+    state->last = 0;
+    state->havedict = 0;
+    state->dmax = 32768U;
+    state->head = Z_NULL;
+    state->hold = 0;
+    state->bits = 0;
+    state->lencode = state->distcode = state->next = state->codes;
+    state->sane = 1;
+    state->back = -1;
+    Tracev((stderr, "inflate: reset\n"));
+    return Z_OK;
+}
+
+int ZEXPORT inflateReset(strm)
+z_streamp strm;
+{
+    struct inflate_state FAR *state;
+
+    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    state->wsize = 0;
+    state->whave = 0;
+    state->wnext = 0;
+    return inflateResetKeep(strm);
+}
+
+int ZEXPORT inflateReset2(strm, windowBits)
+z_streamp strm;
+int windowBits;
+{
+    int wrap;
+    struct inflate_state FAR *state;
+
+    /* get the state */
+    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+
+    /* extract wrap request from windowBits parameter */
+    if (windowBits < 0) {
+        wrap = 0;
+        windowBits = -windowBits;
+    }
+    else {
+        wrap = (windowBits >> 4) + 5;
+#ifdef GUNZIP
+        if (windowBits < 48)
+            windowBits &= 15;
+#endif
+    }
+
+    /* set number of window bits, free window if different */
+    if (windowBits && (windowBits < 8 || windowBits > 15))
+        return Z_STREAM_ERROR;
+    if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) {
+        ZFREE(strm, state->window);
+        state->window = Z_NULL;
+    }
+
+    /* update state and reset the rest of it */
+    state->wrap = wrap;
+    state->wbits = (unsigned)windowBits;
+    return inflateReset(strm);
+}
+
+int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size)
+z_streamp strm;
+int windowBits;
+const char *version;
+int stream_size;
+{
+    int ret;
+    struct inflate_state FAR *state;
+
+    if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
+        stream_size != (int)(sizeof(z_stream)))
+        return Z_VERSION_ERROR;
+    if (strm == Z_NULL) return Z_STREAM_ERROR;
+    strm->msg = Z_NULL;                 /* in case we return an error */
+    if (strm->zalloc == (alloc_func)0) {
+#ifdef Z_SOLO
+        return Z_STREAM_ERROR;
+#else
+        strm->zalloc = zcalloc;
+        strm->opaque = (voidpf)0;
+#endif
+    }
+    if (strm->zfree == (free_func)0)
+#ifdef Z_SOLO
+        return Z_STREAM_ERROR;
+#else
+        strm->zfree = zcfree;
+#endif
+    state = (struct inflate_state FAR *)
+            ZALLOC(strm, 1, sizeof(struct inflate_state));
+    if (state == Z_NULL) return Z_MEM_ERROR;
+    Tracev((stderr, "inflate: allocated\n"));
+    strm->state = (struct internal_state FAR *)state;
+    state->strm = strm;
+    state->window = Z_NULL;
+    state->mode = HEAD;     /* to pass state test in inflateReset2() */
+    ret = inflateReset2(strm, windowBits);
+    if (ret != Z_OK) {
+        ZFREE(strm, state);
+        strm->state = Z_NULL;
+    }
+    return ret;
+}
+
+int ZEXPORT inflateInit_(strm, version, stream_size)
+z_streamp strm;
+const char *version;
+int stream_size;
+{
+    return inflateInit2_(strm, DEF_WBITS, version, stream_size);
+}
+
+int ZEXPORT inflatePrime(strm, bits, value)
+z_streamp strm;
+int bits;
+int value;
+{
+    struct inflate_state FAR *state;
+
+    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    if (bits < 0) {
+        state->hold = 0;
+        state->bits = 0;
+        return Z_OK;
+    }
+    if (bits > 16 || state->bits + (uInt)bits > 32) return Z_STREAM_ERROR;
+    value &= (1L << bits) - 1;
+    state->hold += (unsigned)value << state->bits;
+    state->bits += (uInt)bits;
+    return Z_OK;
+}
+
+/*
+   Return state with length and distance decoding tables and index sizes set to
+   fixed code decoding.  Normally this returns fixed tables from inffixed.h.
+   If BUILDFIXED is defined, then instead this routine builds the tables the
+   first time it's called, and returns those tables the first time and
+   thereafter.  This reduces the size of the code by about 2K bytes, in
+   exchange for a little execution time.  However, BUILDFIXED should not be
+   used for threaded applications, since the rewriting of the tables and virgin
+   may not be thread-safe.
+ */
+local void fixedtables(state)
+struct inflate_state FAR *state;
+{
+#ifdef BUILDFIXED
+    static int virgin = 1;
+    static code *lenfix, *distfix;
+    static code fixed[544];
+
+    /* build fixed huffman tables if first call (may not be thread safe) */
+    if (virgin) {
+        unsigned sym, bits;
+        static code *next;
+
+        /* literal/length table */
+        sym = 0;
+        while (sym < 144) state->lens[sym++] = 8;
+        while (sym < 256) state->lens[sym++] = 9;
+        while (sym < 280) state->lens[sym++] = 7;
+        while (sym < 288) state->lens[sym++] = 8;
+        next = fixed;
+        lenfix = next;
+        bits = 9;
+        inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
+
+        /* distance table */
+        sym = 0;
+        while (sym < 32) state->lens[sym++] = 5;
+        distfix = next;
+        bits = 5;
+        inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
+
+        /* do this just once */
+        virgin = 0;
+    }
+#else /* !BUILDFIXED */
+#   include "inffixed.h"
+#endif /* BUILDFIXED */
+    state->lencode = lenfix;
+    state->lenbits = 9;
+    state->distcode = distfix;
+    state->distbits = 5;
+}
+
+#ifdef MAKEFIXED
+#include <stdio.h>
+
+/*
+   Write out the inffixed.h that is #include'd above.  Defining MAKEFIXED also
+   defines BUILDFIXED, so the tables are built on the fly.  makefixed() writes
+   those tables to stdout, which would be piped to inffixed.h.  A small program
+   can simply call makefixed to do this:
+
+    void makefixed(void);
+
+    int main(void)
+    {
+        makefixed();
+        return 0;
+    }
+
+   Then that can be linked with zlib built with MAKEFIXED defined and run:
+
+    a.out > inffixed.h
+ */
+void makefixed()
+{
+    unsigned low, size;
+    struct inflate_state state;
+
+    fixedtables(&state);
+    puts("    /* inffixed.h -- table for decoding fixed codes");
+    puts("     * Generated automatically by makefixed().");
+    puts("     */");
+    puts("");
+    puts("    /* WARNING: this file should *not* be used by applications.");
+    puts("       It is part of the implementation of this library and is");
+    puts("       subject to change. Applications should only use zlib.h.");
+    puts("     */");
+    puts("");
+    size = 1U << 9;
+    printf("    static const code lenfix[%u] = {", size);
+    low = 0;
+    for (;;) {
+        if ((low % 7) == 0) printf("\n        ");
+        printf("{%u,%u,%d}", (low & 127) == 99 ? 64 : state.lencode[low].op,
+               state.lencode[low].bits, state.lencode[low].val);
+        if (++low == size) break;
+        putchar(',');
+    }
+    puts("\n    };");
+    size = 1U << 5;
+    printf("\n    static const code distfix[%u] = {", size);
+    low = 0;
+    for (;;) {
+        if ((low % 6) == 0) printf("\n        ");
+        printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
+               state.distcode[low].val);
+        if (++low == size) break;
+        putchar(',');
+    }
+    puts("\n    };");
+}
+#endif /* MAKEFIXED */
+
+/*
+   Update the window with the last wsize (normally 32K) bytes written before
+   returning.  If window does not exist yet, create it.  This is only called
+   when a window is already in use, or when output has been written during this
+   inflate call, but the end of the deflate stream has not been reached yet.
+   It is also called to create a window for dictionary data when a dictionary
+   is loaded.
+
+   Providing output buffers larger than 32K to inflate() should provide a speed
+   advantage, since only the last 32K of output is copied to the sliding window
+   upon return from inflate(), and since all distances after the first 32K of
+   output will fall in the output data, making match copies simpler and faster.
+   The advantage may be dependent on the size of the processor's data caches.
+ */
+local int updatewindow(strm, end, copy)
+z_streamp strm;
+const Bytef *end;
+unsigned copy;
+{
+    struct inflate_state FAR *state;
+    unsigned dist;
+
+    state = (struct inflate_state FAR *)strm->state;
+
+    /* if it hasn't been done already, allocate space for the window */
+    if (state->window == Z_NULL) {
+        state->window = (unsigned char FAR *)
+                        ZALLOC(strm, 1U << state->wbits,
+                               sizeof(unsigned char));
+        if (state->window == Z_NULL) return 1;
+    }
+
+    /* if window not in use yet, initialize */
+    if (state->wsize == 0) {
+        state->wsize = 1U << state->wbits;
+        state->wnext = 0;
+        state->whave = 0;
+    }
+
+    /* copy state->wsize or less output bytes into the circular window */
+    if (copy >= state->wsize) {
+        zmemcpy(state->window, end - state->wsize, state->wsize);
+        state->wnext = 0;
+        state->whave = state->wsize;
+    }
+    else {
+        dist = state->wsize - state->wnext;
+        if (dist > copy) dist = copy;
+        zmemcpy(state->window + state->wnext, end - copy, dist);
+        copy -= dist;
+        if (copy) {
+            zmemcpy(state->window, end - copy, copy);
+            state->wnext = copy;
+            state->whave = state->wsize;
+        }
+        else {
+            state->wnext += dist;
+            if (state->wnext == state->wsize) state->wnext = 0;
+            if (state->whave < state->wsize) state->whave += dist;
+        }
+    }
+    return 0;
+}
+
+/* Macros for inflate(): */
+
+/* check function to use adler32() for zlib or crc32() for gzip */
+#ifdef GUNZIP
+#  define UPDATE(check, buf, len) \
+    (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
+#else
+#  define UPDATE(check, buf, len) adler32(check, buf, len)
+#endif
+
+/* check macros for header crc */
+#ifdef GUNZIP
+#  define CRC2(check, word) \
+    do { \
+        hbuf[0] = (unsigned char)(word); \
+        hbuf[1] = (unsigned char)((word) >> 8); \
+        check = crc32(check, hbuf, 2); \
+    } while (0)
+
+#  define CRC4(check, word) \
+    do { \
+        hbuf[0] = (unsigned char)(word); \
+        hbuf[1] = (unsigned char)((word) >> 8); \
+        hbuf[2] = (unsigned char)((word) >> 16); \
+        hbuf[3] = (unsigned char)((word) >> 24); \
+        check = crc32(check, hbuf, 4); \
+    } while (0)
+#endif
+
+/* Load registers with state in inflate() for speed */
+#define LOAD() \
+    do { \
+        put = strm->next_out; \
+        left = strm->avail_out; \
+        next = strm->next_in; \
+        have = strm->avail_in; \
+        hold = state->hold; \
+        bits = state->bits; \
+    } while (0)
+
+/* Restore state from registers in inflate() */
+#define RESTORE() \
+    do { \
+        strm->next_out = put; \
+        strm->avail_out = left; \
+        strm->next_in = next; \
+        strm->avail_in = have; \
+        state->hold = hold; \
+        state->bits = bits; \
+    } while (0)
+
+/* Clear the input bit accumulator */
+#define INITBITS() \
+    do { \
+        hold = 0; \
+        bits = 0; \
+    } while (0)
+
+/* Get a byte of input into the bit accumulator, or return from inflate()
+   if there is no input available. */
+#define PULLBYTE() \
+    do { \
+        if (have == 0) goto inf_leave; \
+        have--; \
+        hold += (unsigned long)(*next++) << bits; \
+        bits += 8; \
+    } while (0)
+
+/* Assure that there are at least n bits in the bit accumulator.  If there is
+   not enough available input to do that, then return from inflate(). */
+#define NEEDBITS(n) \
+    do { \
+        while (bits < (unsigned)(n)) \
+            PULLBYTE(); \
+    } while (0)
+
+/* Return the low n bits of the bit accumulator (n < 16) */
+#define BITS(n) \
+    ((unsigned)hold & ((1U << (n)) - 1))
+
+/* Remove n bits from the bit accumulator */
+#define DROPBITS(n) \
+    do { \
+        hold >>= (n); \
+        bits -= (unsigned)(n); \
+    } while (0)
+
+/* Remove zero to seven bits as needed to go to a byte boundary */
+#define BYTEBITS() \
+    do { \
+        hold >>= bits & 7; \
+        bits -= bits & 7; \
+    } while (0)
+
+/*
+   inflate() uses a state machine to process as much input data and generate as
+   much output data as possible before returning.  The state machine is
+   structured roughly as follows:
+
+    for (;;) switch (state) {
+    ...
+    case STATEn:
+        if (not enough input data or output space to make progress)
+            return;
+        ... make progress ...
+        state = STATEm;
+        break;
+    ...
+    }
+
+   so when inflate() is called again, the same case is attempted again, and
+   if the appropriate resources are provided, the machine proceeds to the
+   next state.  The NEEDBITS() macro is usually the way the state evaluates
+   whether it can proceed or should return.  NEEDBITS() does the return if
+   the requested bits are not available.  The typical use of the BITS macros
+   is:
+
+        NEEDBITS(n);
+        ... do something with BITS(n) ...
+        DROPBITS(n);
+
+   where NEEDBITS(n) either returns from inflate() if there isn't enough
+   input left to load n bits into the accumulator, or it continues.  BITS(n)
+   gives the low n bits in the accumulator.  When done, DROPBITS(n) drops
+   the low n bits off the accumulator.  INITBITS() clears the accumulator
+   and sets the number of available bits to zero.  BYTEBITS() discards just
+   enough bits to put the accumulator on a byte boundary.  After BYTEBITS()
+   and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
+
+   NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
+   if there is no input available.  The decoding of variable length codes uses
+   PULLBYTE() directly in order to pull just enough bytes to decode the next
+   code, and no more.
+
+   Some states loop until they get enough input, making sure that enough
+   state information is maintained to continue the loop where it left off
+   if NEEDBITS() returns in the loop.  For example, want, need, and keep
+   would all have to actually be part of the saved state in case NEEDBITS()
+   returns:
+
+    case STATEw:
+        while (want < need) {
+            NEEDBITS(n);
+            keep[want++] = BITS(n);
+            DROPBITS(n);
+        }
+        state = STATEx;
+    case STATEx:
+
+   As shown above, if the next state is also the next case, then the break
+   is omitted.
+
+   A state may also return if there is not enough output space available to
+   complete that state.  Those states are copying stored data, writing a
+   literal byte, and copying a matching string.
+
+   When returning, a "goto inf_leave" is used to update the total counters,
+   update the check value, and determine whether any progress has been made
+   during that inflate() call in order to return the proper return code.
+   Progress is defined as a change in either strm->avail_in or strm->avail_out.
+   When there is a window, goto inf_leave will update the window with the last
+   output written.  If a goto inf_leave occurs in the middle of decompression
+   and there is no window currently, goto inf_leave will create one and copy
+   output to the window for the next call of inflate().
+
+   In this implementation, the flush parameter of inflate() only affects the
+   return code (per zlib.h).  inflate() always writes as much as possible to
+   strm->next_out, given the space available and the provided input--the effect
+   documented in zlib.h of Z_SYNC_FLUSH.  Furthermore, inflate() always defers
+   the allocation of and copying into a sliding window until necessary, which
+   provides the effect documented in zlib.h for Z_FINISH when the entire input
+   stream available.  So the only thing the flush parameter actually does is:
+   when flush is set to Z_FINISH, inflate() cannot return Z_OK.  Instead it
+   will return Z_BUF_ERROR if it has not reached the end of the stream.
+ */
+
+int ZEXPORT inflate(strm, flush)
+z_streamp strm;
+int flush;
+{
+    struct inflate_state FAR *state;
+    z_const unsigned char FAR *next;    /* next input */
+    unsigned char FAR *put;     /* next output */
+    unsigned have, left;        /* available input and output */
+    unsigned long hold;         /* bit buffer */
+    unsigned bits;              /* bits in bit buffer */
+    unsigned in, out;           /* save starting available input and output */
+    unsigned copy;              /* number of stored or match bytes to copy */
+    unsigned char FAR *from;    /* where to copy match bytes from */
+    code here;                  /* current decoding table entry */
+    code last;                  /* parent table entry */
+    unsigned len;               /* length to copy for repeats, bits to drop */
+    int ret;                    /* return code */
+#ifdef GUNZIP
+    unsigned char hbuf[4];      /* buffer for gzip header crc calculation */
+#endif
+    static const unsigned short order[19] = /* permutation of code lengths */
+        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
+
+    if (inflateStateCheck(strm) || strm->next_out == Z_NULL ||
+        (strm->next_in == Z_NULL && strm->avail_in != 0))
+        return Z_STREAM_ERROR;
+
+    state = (struct inflate_state FAR *)strm->state;
+    if (state->mode == TYPE) state->mode = TYPEDO;      /* skip check */
+    LOAD();
+    in = have;
+    out = left;
+    ret = Z_OK;
+    for (;;)
+        switch (state->mode) {
+        case HEAD:
+            if (state->wrap == 0) {
+                state->mode = TYPEDO;
+                break;
+            }
+            NEEDBITS(16);
+#ifdef GUNZIP
+            if ((state->wrap & 2) && hold == 0x8b1f) {  /* gzip header */
+                if (state->wbits == 0)
+                    state->wbits = 15;
+                state->check = crc32(0L, Z_NULL, 0);
+                CRC2(state->check, hold);
+                INITBITS();
+                state->mode = FLAGS;
+                break;
+            }
+            state->flags = 0;           /* expect zlib header */
+            if (state->head != Z_NULL)
+                state->head->done = -1;
+            if (!(state->wrap & 1) ||   /* check if zlib header allowed */
+#else
+            if (
+#endif
+                ((BITS(8) << 8) + (hold >> 8)) % 31) {
+                strm->msg = (char *)"incorrect header check";
+                state->mode = BAD;
+                break;
+            }
+            if (BITS(4) != Z_DEFLATED) {
+                strm->msg = (char *)"unknown compression method";
+                state->mode = BAD;
+                break;
+            }
+            DROPBITS(4);
+            len = BITS(4) + 8;
+            if (state->wbits == 0)
+                state->wbits = len;
+            if (len > 15 || len > state->wbits) {
+                strm->msg = (char *)"invalid window size";
+                state->mode = BAD;
+                break;
+            }
+            state->dmax = 1U << len;
+            Tracev((stderr, "inflate:   zlib header ok\n"));
+            strm->adler = state->check = adler32(0L, Z_NULL, 0);
+            state->mode = hold & 0x200 ? DICTID : TYPE;
+            INITBITS();
+            break;
+#ifdef GUNZIP
+        case FLAGS:
+            NEEDBITS(16);
+            state->flags = (int)(hold);
+            if ((state->flags & 0xff) != Z_DEFLATED) {
+                strm->msg = (char *)"unknown compression method";
+                state->mode = BAD;
+                break;
+            }
+            if (state->flags & 0xe000) {
+                strm->msg = (char *)"unknown header flags set";
+                state->mode = BAD;
+                break;
+            }
+            if (state->head != Z_NULL)
+                state->head->text = (int)((hold >> 8) & 1);
+            if ((state->flags & 0x0200) && (state->wrap & 4))
+                CRC2(state->check, hold);
+            INITBITS();
+            state->mode = TIME;
+        case TIME:
+            NEEDBITS(32);
+            if (state->head != Z_NULL)
+                state->head->time = hold;
+            if ((state->flags & 0x0200) && (state->wrap & 4))
+                CRC4(state->check, hold);
+            INITBITS();
+            state->mode = OS;
+        case OS:
+            NEEDBITS(16);
+            if (state->head != Z_NULL) {
+                state->head->xflags = (int)(hold & 0xff);
+                state->head->os = (int)(hold >> 8);
+            }
+            if ((state->flags & 0x0200) && (state->wrap & 4))
+                CRC2(state->check, hold);
+            INITBITS();
+            state->mode = EXLEN;
+        case EXLEN:
+            if (state->flags & 0x0400) {
+                NEEDBITS(16);
+                state->length = (unsigned)(hold);
+                if (state->head != Z_NULL)
+                    state->head->extra_len = (unsigned)hold;
+                if ((state->flags & 0x0200) && (state->wrap & 4))
+                    CRC2(state->check, hold);
+                INITBITS();
+            }
+            else if (state->head != Z_NULL)
+                state->head->extra = Z_NULL;
+            state->mode = EXTRA;
+        case EXTRA:
+            if (state->flags & 0x0400) {
+                copy = state->length;
+                if (copy > have) copy = have;
+                if (copy) {
+                    if (state->head != Z_NULL &&
+                        state->head->extra != Z_NULL) {
+                        len = state->head->extra_len - state->length;
+                        zmemcpy(state->head->extra + len, next,
+                                len + copy > state->head->extra_max ?
+                                state->head->extra_max - len : copy);
+                    }
+                    if ((state->flags & 0x0200) && (state->wrap & 4))
+                        state->check = crc32(state->check, next, copy);
+                    have -= copy;
+                    next += copy;
+                    state->length -= copy;
+                }
+                if (state->length) goto inf_leave;
+            }
+            state->length = 0;
+            state->mode = NAME;
+        case NAME:
+            if (state->flags & 0x0800) {
+                if (have == 0) goto inf_leave;
+                copy = 0;
+                do {
+                    len = (unsigned)(next[copy++]);
+                    if (state->head != Z_NULL &&
+                            state->head->name != Z_NULL &&
+                            state->length < state->head->name_max)
+                        state->head->name[state->length++] = (Bytef)len;
+                } while (len && copy < have);
+                if ((state->flags & 0x0200) && (state->wrap & 4))
+                    state->check = crc32(state->check, next, copy);
+                have -= copy;
+                next += copy;
+                if (len) goto inf_leave;
+            }
+            else if (state->head != Z_NULL)
+                state->head->name = Z_NULL;
+            state->length = 0;
+            state->mode = COMMENT;
+        case COMMENT:
+            if (state->flags & 0x1000) {
+                if (have == 0) goto inf_leave;
+                copy = 0;
+                do {
+                    len = (unsigned)(next[copy++]);
+                    if (state->head != Z_NULL &&
+                            state->head->comment != Z_NULL &&
+                            state->length < state->head->comm_max)
+                        state->head->comment[state->length++] = (Bytef)len;
+                } while (len && copy < have);
+                if ((state->flags & 0x0200) && (state->wrap & 4))
+                    state->check = crc32(state->check, next, copy);
+                have -= copy;
+                next += copy;
+                if (len) goto inf_leave;
+            }
+            else if (state->head != Z_NULL)
+                state->head->comment = Z_NULL;
+            state->mode = HCRC;
+        case HCRC:
+            if (state->flags & 0x0200) {
+                NEEDBITS(16);
+                if ((state->wrap & 4) && hold != (state->check & 0xffff)) {
+                    strm->msg = (char *)"header crc mismatch";
+                    state->mode = BAD;
+                    break;
+                }
+                INITBITS();
+            }
+            if (state->head != Z_NULL) {
+                state->head->hcrc = (int)((state->flags >> 9) & 1);
+                state->head->done = 1;
+            }
+            strm->adler = state->check = crc32(0L, Z_NULL, 0);
+            state->mode = TYPE;
+            break;
+#endif
+        case DICTID:
+            NEEDBITS(32);
+            strm->adler = state->check = ZSWAP32(hold);
+            INITBITS();
+            state->mode = DICT;
+        case DICT:
+            if (state->havedict == 0) {
+                RESTORE();
+                return Z_NEED_DICT;
+            }
+            strm->adler = state->check = adler32(0L, Z_NULL, 0);
+            state->mode = TYPE;
+        case TYPE:
+            if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave;
+        case TYPEDO:
+            if (state->last) {
+                BYTEBITS();
+                state->mode = CHECK;
+                break;
+            }
+            NEEDBITS(3);
+            state->last = BITS(1);
+            DROPBITS(1);
+            switch (BITS(2)) {
+            case 0:                             /* stored block */
+                Tracev((stderr, "inflate:     stored block%s\n",
+                        state->last ? " (last)" : ""));
+                state->mode = STORED;
+                break;
+            case 1:                             /* fixed block */
+                fixedtables(state);
+                Tracev((stderr, "inflate:     fixed codes block%s\n",
+                        state->last ? " (last)" : ""));
+                state->mode = LEN_;             /* decode codes */
+                if (flush == Z_TREES) {
+                    DROPBITS(2);
+                    goto inf_leave;
+                }
+                break;
+            case 2:                             /* dynamic block */
+                Tracev((stderr, "inflate:     dynamic codes block%s\n",
+                        state->last ? " (last)" : ""));
+                state->mode = TABLE;
+                break;
+            case 3:
+                strm->msg = (char *)"invalid block type";
+                state->mode = BAD;
+            }
+            DROPBITS(2);
+            break;
+        case STORED:
+            BYTEBITS();                         /* go to byte boundary */
+            NEEDBITS(32);
+            if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
+                strm->msg = (char *)"invalid stored block lengths";
+                state->mode = BAD;
+                break;
+            }
+            state->length = (unsigned)hold & 0xffff;
+            Tracev((stderr, "inflate:       stored length %u\n",
+                    state->length));
+            INITBITS();
+            state->mode = COPY_;
+            if (flush == Z_TREES) goto inf_leave;
+        case COPY_:
+            state->mode = COPY;
+        case COPY:
+            copy = state->length;
+            if (copy) {
+                if (copy > have) copy = have;
+                if (copy > left) copy = left;
+                if (copy == 0) goto inf_leave;
+                zmemcpy(put, next, copy);
+                have -= copy;
+                next += copy;
+                left -= copy;
+                put += copy;
+                state->length -= copy;
+                break;
+            }
+            Tracev((stderr, "inflate:       stored end\n"));
+            state->mode = TYPE;
+            break;
+        case TABLE:
+            NEEDBITS(14);
+            state->nlen = BITS(5) + 257;
+            DROPBITS(5);
+            state->ndist = BITS(5) + 1;
+            DROPBITS(5);
+            state->ncode = BITS(4) + 4;
+            DROPBITS(4);
+#ifndef PKZIP_BUG_WORKAROUND
+            if (state->nlen > 286 || state->ndist > 30) {
+                strm->msg = (char *)"too many length or distance symbols";
+                state->mode = BAD;
+                break;
+            }
+#endif
+            Tracev((stderr, "inflate:       table sizes ok\n"));
+            state->have = 0;
+            state->mode = LENLENS;
+        case LENLENS:
+            while (state->have < state->ncode) {
+                NEEDBITS(3);
+                state->lens[order[state->have++]] = (unsigned short)BITS(3);
+                DROPBITS(3);
+            }
+            while (state->have < 19)
+                state->lens[order[state->have++]] = 0;
+            state->next = state->codes;
+            state->lencode = (const code FAR *)(state->next);
+            state->lenbits = 7;
+            ret = inflate_table(CODES, state->lens, 19, &(state->next),
+                                &(state->lenbits), state->work);
+            if (ret) {
+                strm->msg = (char *)"invalid code lengths set";
+                state->mode = BAD;
+                break;
+            }
+            Tracev((stderr, "inflate:       code lengths ok\n"));
+            state->have = 0;
+            state->mode = CODELENS;
+        case CODELENS:
+            while (state->have < state->nlen + state->ndist) {
+                for (;;) {
+                    here = state->lencode[BITS(state->lenbits)];
+                    if ((unsigned)(here.bits) <= bits) break;
+                    PULLBYTE();
+                }
+                if (here.val < 16) {
+                    DROPBITS(here.bits);
+                    state->lens[state->have++] = here.val;
+                }
+                else {
+                    if (here.val == 16) {
+                        NEEDBITS(here.bits + 2);
+                        DROPBITS(here.bits);
+                        if (state->have == 0) {
+                            strm->msg = (char *)"invalid bit length repeat";
+                            state->mode = BAD;
+                            break;
+                        }
+                        len = state->lens[state->have - 1];
+                        copy = 3 + BITS(2);
+                        DROPBITS(2);
+                    }
+                    else if (here.val == 17) {
+                        NEEDBITS(here.bits + 3);
+                        DROPBITS(here.bits);
+                        len = 0;
+                        copy = 3 + BITS(3);
+                        DROPBITS(3);
+                    }
+                    else {
+                        NEEDBITS(here.bits + 7);
+                        DROPBITS(here.bits);
+                        len = 0;
+                        copy = 11 + BITS(7);
+                        DROPBITS(7);
+                    }
+                    if (state->have + copy > state->nlen + state->ndist) {
+                        strm->msg = (char *)"invalid bit length repeat";
+                        state->mode = BAD;
+                        break;
+                    }
+                    while (copy--)
+                        state->lens[state->have++] = (unsigned short)len;
+                }
+            }
+
+            /* handle error breaks in while */
+            if (state->mode == BAD) break;
+
+            /* check for end-of-block code (better have one) */
+            if (state->lens[256] == 0) {
+                strm->msg = (char *)"invalid code -- missing end-of-block";
+                state->mode = BAD;
+                break;
+            }
+
+            /* build code tables -- note: do not change the lenbits or distbits
+               values here (9 and 6) without reading the comments in inftrees.h
+               concerning the ENOUGH constants, which depend on those values */
+            state->next = state->codes;
+            state->lencode = (const code FAR *)(state->next);
+            state->lenbits = 9;
+            ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
+                                &(state->lenbits), state->work);
+            if (ret) {
+                strm->msg = (char *)"invalid literal/lengths set";
+                state->mode = BAD;
+                break;
+            }
+            state->distcode = (const code FAR *)(state->next);
+            state->distbits = 6;
+            ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
+                            &(state->next), &(state->distbits), state->work);
+            if (ret) {
+                strm->msg = (char *)"invalid distances set";
+                state->mode = BAD;
+                break;
+            }
+            Tracev((stderr, "inflate:       codes ok\n"));
+            state->mode = LEN_;
+            if (flush == Z_TREES) goto inf_leave;
+        case LEN_:
+            state->mode = LEN;
+        case LEN:
+            if (have >= 6 && left >= 258) {
+                RESTORE();
+                inflate_fast(strm, out);
+                LOAD();
+                if (state->mode == TYPE)
+                    state->back = -1;
+                break;
+            }
+            state->back = 0;
+            for (;;) {
+                here = state->lencode[BITS(state->lenbits)];
+                if ((unsigned)(here.bits) <= bits) break;
+                PULLBYTE();
+            }
+            if (here.op && (here.op & 0xf0) == 0) {
+                last = here;
+                for (;;) {
+                    here = state->lencode[last.val +
+                            (BITS(last.bits + last.op) >> last.bits)];
+                    if ((unsigned)(last.bits + here.bits) <= bits) break;
+                    PULLBYTE();
+                }
+                DROPBITS(last.bits);
+                state->back += last.bits;
+            }
+            DROPBITS(here.bits);
+            state->back += here.bits;
+            state->length = (unsigned)here.val;
+            if ((int)(here.op) == 0) {
+                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
+                        "inflate:         literal '%c'\n" :
+                        "inflate:         literal 0x%02x\n", here.val));
+                state->mode = LIT;
+                break;
+            }
+            if (here.op & 32) {
+                Tracevv((stderr, "inflate:         end of block\n"));
+                state->back = -1;
+                state->mode = TYPE;
+                break;
+            }
+            if (here.op & 64) {
+                strm->msg = (char *)"invalid literal/length code";
+                state->mode = BAD;
+                break;
+            }
+            state->extra = (unsigned)(here.op) & 15;
+            state->mode = LENEXT;
+        case LENEXT:
+            if (state->extra) {
+                NEEDBITS(state->extra);
+                state->length += BITS(state->extra);
+                DROPBITS(state->extra);
+                state->back += state->extra;
+            }
+            Tracevv((stderr, "inflate:         length %u\n", state->length));
+            state->was = state->length;
+            state->mode = DIST;
+        case DIST:
+            for (;;) {
+                here = state->distcode[BITS(state->distbits)];
+                if ((unsigned)(here.bits) <= bits) break;
+                PULLBYTE();
+            }
+            if ((here.op & 0xf0) == 0) {
+                last = here;
+                for (;;) {
+                    here = state->distcode[last.val +
+                            (BITS(last.bits + last.op) >> last.bits)];
+                    if ((unsigned)(last.bits + here.bits) <= bits) break;
+                    PULLBYTE();
+                }
+                DROPBITS(last.bits);
+                state->back += last.bits;
+            }
+            DROPBITS(here.bits);
+            state->back += here.bits;
+            if (here.op & 64) {
+                strm->msg = (char *)"invalid distance code";
+                state->mode = BAD;
+                break;
+            }
+            state->offset = (unsigned)here.val;
+            state->extra = (unsigned)(here.op) & 15;
+            state->mode = DISTEXT;
+        case DISTEXT:
+            if (state->extra) {
+                NEEDBITS(state->extra);
+                state->offset += BITS(state->extra);
+                DROPBITS(state->extra);
+                state->back += state->extra;
+            }
+#ifdef INFLATE_STRICT
+            if (state->offset > state->dmax) {
+                strm->msg = (char *)"invalid distance too far back";
+                state->mode = BAD;
+                break;
+            }
+#endif
+            Tracevv((stderr, "inflate:         distance %u\n", state->offset));
+            state->mode = MATCH;
+        case MATCH:
+            if (left == 0) goto inf_leave;
+            copy = out - left;
+            if (state->offset > copy) {         /* copy from window */
+                copy = state->offset - copy;
+                if (copy > state->whave) {
+                    if (state->sane) {
+                        strm->msg = (char *)"invalid distance too far back";
+                        state->mode = BAD;
+                        break;
+                    }
+#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
+                    Trace((stderr, "inflate.c too far\n"));
+                    copy -= state->whave;
+                    if (copy > state->length) copy = state->length;
+                    if (copy > left) copy = left;
+                    left -= copy;
+                    state->length -= copy;
+                    do {
+                        *put++ = 0;
+                    } while (--copy);
+                    if (state->length == 0) state->mode = LEN;
+                    break;
+#endif
+                }
+                if (copy > state->wnext) {
+                    copy -= state->wnext;
+                    from = state->window + (state->wsize - copy);
+                }
+                else
+                    from = state->window + (state->wnext - copy);
+                if (copy > state->length) copy = state->length;
+            }
+            else {                              /* copy from output */
+                from = put - state->offset;
+                copy = state->length;
+            }
+            if (copy > left) copy = left;
+            left -= copy;
+            state->length -= copy;
+            do {
+                *put++ = *from++;
+            } while (--copy);
+            if (state->length == 0) state->mode = LEN;
+            break;
+        case LIT:
+            if (left == 0) goto inf_leave;
+            *put++ = (unsigned char)(state->length);
+            left--;
+            state->mode = LEN;
+            break;
+        case CHECK:
+            if (state->wrap) {
+                NEEDBITS(32);
+                out -= left;
+                strm->total_out += out;
+                state->total += out;
+                if ((state->wrap & 4) && out)
+                    strm->adler = state->check =
+                        UPDATE(state->check, put - out, out);
+                out = left;
+                if ((state->wrap & 4) && (
+#ifdef GUNZIP
+                     state->flags ? hold :
+#endif
+                     ZSWAP32(hold)) != state->check) {
+                    strm->msg = (char *)"incorrect data check";
+                    state->mode = BAD;
+                    break;
+                }
+                INITBITS();
+                Tracev((stderr, "inflate:   check matches trailer\n"));
+            }
+#ifdef GUNZIP
+            state->mode = LENGTH;
+        case LENGTH:
+            if (state->wrap && state->flags) {
+                NEEDBITS(32);
+                if (hold != (state->total & 0xffffffffUL)) {
+                    strm->msg = (char *)"incorrect length check";
+                    state->mode = BAD;
+                    break;
+                }
+                INITBITS();
+                Tracev((stderr, "inflate:   length matches trailer\n"));
+            }
+#endif
+            state->mode = DONE;
+        case DONE:
+            ret = Z_STREAM_END;
+            goto inf_leave;
+        case BAD:
+            ret = Z_DATA_ERROR;
+            goto inf_leave;
+        case MEM:
+            return Z_MEM_ERROR;
+        case SYNC:
+        default:
+            return Z_STREAM_ERROR;
+        }
+
+    /*
+       Return from inflate(), updating the total counts and the check value.
+       If there was no progress during the inflate() call, return a buffer
+       error.  Call updatewindow() to create and/or update the window state.
+       Note: a memory error from inflate() is non-recoverable.
+     */
+  inf_leave:
+    RESTORE();
+    if (state->wsize || (out != strm->avail_out && state->mode < BAD &&
+            (state->mode < CHECK || flush != Z_FINISH)))
+        if (updatewindow(strm, strm->next_out, out - strm->avail_out)) {
+            state->mode = MEM;
+            return Z_MEM_ERROR;
+        }
+    in -= strm->avail_in;
+    out -= strm->avail_out;
+    strm->total_in += in;
+    strm->total_out += out;
+    state->total += out;
+    if ((state->wrap & 4) && out)
+        strm->adler = state->check =
+            UPDATE(state->check, strm->next_out - out, out);
+    strm->data_type = (int)state->bits + (state->last ? 64 : 0) +
+                      (state->mode == TYPE ? 128 : 0) +
+                      (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0);
+    if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
+        ret = Z_BUF_ERROR;
+    return ret;
+}
+
+int ZEXPORT inflateEnd(strm)
+z_streamp strm;
+{
+    struct inflate_state FAR *state;
+    if (inflateStateCheck(strm))
+        return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    if (state->window != Z_NULL) ZFREE(strm, state->window);
+    ZFREE(strm, strm->state);
+    strm->state = Z_NULL;
+    Tracev((stderr, "inflate: end\n"));
+    return Z_OK;
+}
+
+int ZEXPORT inflateGetDictionary(strm, dictionary, dictLength)
+z_streamp strm;
+Bytef *dictionary;
+uInt *dictLength;
+{
+    struct inflate_state FAR *state;
+
+    /* check state */
+    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+
+    /* copy dictionary */
+    if (state->whave && dictionary != Z_NULL) {
+        zmemcpy(dictionary, state->window + state->wnext,
+                state->whave - state->wnext);
+        zmemcpy(dictionary + state->whave - state->wnext,
+                state->window, state->wnext);
+    }
+    if (dictLength != Z_NULL)
+        *dictLength = state->whave;
+    return Z_OK;
+}
+
+int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength)
+z_streamp strm;
+const Bytef *dictionary;
+uInt dictLength;
+{
+    struct inflate_state FAR *state;
+    unsigned long dictid;
+    int ret;
+
+    /* check state */
+    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    if (state->wrap != 0 && state->mode != DICT)
+        return Z_STREAM_ERROR;
+
+    /* check for correct dictionary identifier */
+    if (state->mode == DICT) {
+        dictid = adler32(0L, Z_NULL, 0);
+        dictid = adler32(dictid, dictionary, dictLength);
+        if (dictid != state->check)
+            return Z_DATA_ERROR;
+    }
+
+    /* copy dictionary to window using updatewindow(), which will amend the
+       existing dictionary if appropriate */
+    ret = updatewindow(strm, dictionary + dictLength, dictLength);
+    if (ret) {
+        state->mode = MEM;
+        return Z_MEM_ERROR;
+    }
+    state->havedict = 1;
+    Tracev((stderr, "inflate:   dictionary set\n"));
+    return Z_OK;
+}
+
+int ZEXPORT inflateGetHeader(strm, head)
+z_streamp strm;
+gz_headerp head;
+{
+    struct inflate_state FAR *state;
+
+    /* check state */
+    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
+
+    /* save header structure */
+    state->head = head;
+    head->done = 0;
+    return Z_OK;
+}
+
+/*
+   Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff.  Return when found
+   or when out of input.  When called, *have is the number of pattern bytes
+   found in order so far, in 0..3.  On return *have is updated to the new
+   state.  If on return *have equals four, then the pattern was found and the
+   return value is how many bytes were read including the last byte of the
+   pattern.  If *have is less than four, then the pattern has not been found
+   yet and the return value is len.  In the latter case, syncsearch() can be
+   called again with more data and the *have state.  *have is initialized to
+   zero for the first call.
+ */
+local unsigned syncsearch(have, buf, len)
+unsigned FAR *have;
+const unsigned char FAR *buf;
+unsigned len;
+{
+    unsigned got;
+    unsigned next;
+
+    got = *have;
+    next = 0;
+    while (next < len && got < 4) {
+        if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
+            got++;
+        else if (buf[next])
+            got = 0;
+        else
+            got = 4 - got;
+        next++;
+    }
+    *have = got;
+    return next;
+}
+
+int ZEXPORT inflateSync(strm)
+z_streamp strm;
+{
+    unsigned len;               /* number of bytes to look at or looked at */
+    unsigned long in, out;      /* temporary to save total_in and total_out */
+    unsigned char buf[4];       /* to restore bit buffer to byte string */
+    struct inflate_state FAR *state;
+
+    /* check parameters */
+    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
+
+    /* if first time, start search in bit buffer */
+    if (state->mode != SYNC) {
+        state->mode = SYNC;
+        state->hold <<= state->bits & 7;
+        state->bits -= state->bits & 7;
+        len = 0;
+        while (state->bits >= 8) {
+            buf[len++] = (unsigned char)(state->hold);
+            state->hold >>= 8;
+            state->bits -= 8;
+        }
+        state->have = 0;
+        syncsearch(&(state->have), buf, len);
+    }
+
+    /* search available input */
+    len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
+    strm->avail_in -= len;
+    strm->next_in += len;
+    strm->total_in += len;
+
+    /* return no joy or set up to restart inflate() on a new block */
+    if (state->have != 4) return Z_DATA_ERROR;
+    in = strm->total_in;  out = strm->total_out;
+    inflateReset(strm);
+    strm->total_in = in;  strm->total_out = out;
+    state->mode = TYPE;
+    return Z_OK;
+}
+
+/*
+   Returns true if inflate is currently at the end of a block generated by
+   Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
+   implementation to provide an additional safety check. PPP uses
+   Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
+   block. When decompressing, PPP checks that at the end of input packet,
+   inflate is waiting for these length bytes.
+ */
+int ZEXPORT inflateSyncPoint(strm)
+z_streamp strm;
+{
+    struct inflate_state FAR *state;
+
+    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    return state->mode == STORED && state->bits == 0;
+}
+
+int ZEXPORT inflateCopy(dest, source)
+z_streamp dest;
+z_streamp source;
+{
+    struct inflate_state FAR *state;
+    struct inflate_state FAR *copy;
+    unsigned char FAR *window;
+    unsigned wsize;
+
+    /* check input */
+    if (inflateStateCheck(source) || dest == Z_NULL)
+        return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)source->state;
+
+    /* allocate space */
+    copy = (struct inflate_state FAR *)
+           ZALLOC(source, 1, sizeof(struct inflate_state));
+    if (copy == Z_NULL) return Z_MEM_ERROR;
+    window = Z_NULL;
+    if (state->window != Z_NULL) {
+        window = (unsigned char FAR *)
+                 ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
+        if (window == Z_NULL) {
+            ZFREE(source, copy);
+            return Z_MEM_ERROR;
+        }
+    }
+
+    /* copy state */
+    zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
+    zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state));
+    copy->strm = dest;
+    if (state->lencode >= state->codes &&
+        state->lencode <= state->codes + ENOUGH - 1) {
+        copy->lencode = copy->codes + (state->lencode - state->codes);
+        copy->distcode = copy->codes + (state->distcode - state->codes);
+    }
+    copy->next = copy->codes + (state->next - state->codes);
+    if (window != Z_NULL) {
+        wsize = 1U << state->wbits;
+        zmemcpy(window, state->window, wsize);
+    }
+    copy->window = window;
+    dest->state = (struct internal_state FAR *)copy;
+    return Z_OK;
+}
+
+int ZEXPORT inflateUndermine(strm, subvert)
+z_streamp strm;
+int subvert;
+{
+    struct inflate_state FAR *state;
+
+    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
+    state->sane = !subvert;
+    return Z_OK;
+#else
+    (void)subvert;
+    state->sane = 1;
+    return Z_DATA_ERROR;
+#endif
+}
+
+int ZEXPORT inflateValidate(strm, check)
+z_streamp strm;
+int check;
+{
+    struct inflate_state FAR *state;
+
+    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    if (check)
+        state->wrap |= 4;
+    else
+        state->wrap &= ~4;
+    return Z_OK;
+}
+
+long ZEXPORT inflateMark(strm)
+z_streamp strm;
+{
+    struct inflate_state FAR *state;
+
+    if (inflateStateCheck(strm))
+        return -(1L << 16);
+    state = (struct inflate_state FAR *)strm->state;
+    return (long)(((unsigned long)((long)state->back)) << 16) +
+        (state->mode == COPY ? state->length :
+            (state->mode == MATCH ? state->was - state->length : 0));
+}
+
+unsigned long ZEXPORT inflateCodesUsed(strm)
+z_streamp strm;
+{
+    struct inflate_state FAR *state;
+    if (inflateStateCheck(strm)) return (unsigned long)-1;
+    state = (struct inflate_state FAR *)strm->state;
+    return (unsigned long)(state->next - state->codes);
+}
+

--- /dev/null
+++ b/src/in_xsf_framework/zlib/inflate.h
@@ -1,1 +1,126 @@
+/* inflate.h -- internal inflate state definition
+ * Copyright (C) 1995-2016 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
 
+/* WARNING: this file should *not* be used by applications. It is
+   part of the implementation of the compression library and is
+   subject to change. Applications should only use zlib.h.
+ */
+
+/* define NO_GZIP when compiling if you want to disable gzip header and
+   trailer decoding by inflate().  NO_GZIP would be used to avoid linking in
+   the crc code when it is not needed.  For shared libraries, gzip decoding
+   should be left enabled. */
+#ifndef NO_GZIP
+#  define GUNZIP
+#endif
+
+/* Possible inflate modes between inflate() calls */
+typedef enum {
+    HEAD = 16180,   /* i: waiting for magic header */
+    FLAGS,      /* i: waiting for method and flags (gzip) */
+    TIME,       /* i: waiting for modification time (gzip) */
+    OS,         /* i: waiting for extra flags and operating system (gzip) */
+    EXLEN,      /* i: waiting for extra length (gzip) */
+    EXTRA,      /* i: waiting for extra bytes (gzip) */
+    NAME,       /* i: waiting for end of file name (gzip) */
+    COMMENT,    /* i: waiting for end of comment (gzip) */
+    HCRC,       /* i: waiting for header crc (gzip) */
+    DICTID,     /* i: waiting for dictionary check value */
+    DICT,       /* waiting for inflateSetDictionary() call */
+        TYPE,       /* i: waiting for type bits, including last-flag bit */
+        TYPEDO,     /* i: same, but skip check to exit inflate on new block */
+        STORED,     /* i: waiting for stored size (length and complement) */
+        COPY_,      /* i/o: same as COPY below, but only first time in */
+        COPY,       /* i/o: waiting for input or output to copy stored block */
+        TABLE,      /* i: waiting for dynamic block table lengths */
+        LENLENS,    /* i: waiting for code length code lengths */
+        CODELENS,   /* i: waiting for length/lit and distance code lengths */
+            LEN_,       /* i: same as LEN below, but only first time in */
+            LEN,        /* i: waiting for length/lit/eob code */
+            LENEXT,     /* i: waiting for length extra bits */
+            DIST,       /* i: waiting for distance code */
+            DISTEXT,    /* i: waiting for distance extra bits */
+            MATCH,      /* o: waiting for output space to copy string */
+            LIT,        /* o: waiting for output space to write literal */
+    CHECK,      /* i: waiting for 32-bit check value */
+    LENGTH,     /* i: waiting for 32-bit length (gzip) */
+    DONE,       /* finished check, done -- remain here until reset */
+    BAD,        /* got a data error -- remain here until reset */
+    MEM,        /* got an inflate() memory error -- remain here until reset */
+    SYNC        /* looking for synchronization bytes to restart inflate() */
+} inflate_mode;
+
+/*
+    State transitions between above modes -
+
+    (most modes can go to BAD or MEM on error -- not shown for clarity)
+
+    Process header:
+        HEAD -> (gzip) or (zlib) or (raw)
+        (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME -> COMMENT ->
+                  HCRC -> TYPE
+        (zlib) -> DICTID or TYPE
+        DICTID -> DICT -> TYPE
+        (raw) -> TYPEDO
+    Read deflate blocks:
+            TYPE -> TYPEDO -> STORED or TABLE or LEN_ or CHECK
+            STORED -> COPY_ -> COPY -> TYPE
+            TABLE -> LENLENS -> CODELENS -> LEN_
+            LEN_ -> LEN
+    Read deflate codes in fixed or dynamic block:
+                LEN -> LENEXT or LIT or TYPE
+                LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
+                LIT -> LEN
+    Process trailer:
+        CHECK -> LENGTH -> DONE
+ */
+
+/* State maintained between inflate() calls -- approximately 7K bytes, not
+   including the allocated sliding window, which is up to 32K bytes. */
+struct inflate_state {
+    z_streamp strm;             /* pointer back to this zlib stream */
+    inflate_mode mode;          /* current inflate mode */
+    int last;                   /* true if processing last block */
+    int wrap;                   /* bit 0 true for zlib, bit 1 true for gzip,
+                                   bit 2 true to validate check value */
+    int havedict;               /* true if dictionary provided */
+    int flags;                  /* gzip header method and flags (0 if zlib) */
+    unsigned dmax;              /* zlib header max distance (INFLATE_STRICT) */
+    unsigned long check;        /* protected copy of check value */
+    unsigned long total;        /* protected copy of output count */
+    gz_headerp head;            /* where to save gzip header information */
+        /* sliding window */
+    unsigned wbits;             /* log base 2 of requested window size */
+    unsigned wsize;             /* window size or zero if not using window */
+    unsigned whave;             /* valid bytes in the window */
+    unsigned wnext;             /* window write index */
+    unsigned char FAR *window;  /* allocated sliding window, if needed */
+        /* bit accumulator */
+    unsigned long hold;         /* input bit accumulator */
+    unsigned bits;              /* number of bits in "in" */
+        /* for string and stored block copying */
+    unsigned length;            /* literal or length of data to copy */
+    unsigned offset;            /* distance back to copy string from */
+        /* for table and code decoding */
+    unsigned extra;             /* extra bits needed */
+        /* fixed and dynamic code tables */
+    code const FAR *lencode;    /* starting table for length/literal codes */
+    code const FAR *distcode;   /* starting table for distance codes */
+    unsigned lenbits;           /* index bits for lencode */
+    unsigned distbits;          /* index bits for distcode */
+        /* dynamic table building */
+    unsigned ncode;             /* number of code length code lengths */
+    unsigned nlen;              /* number of length code lengths */
+    unsigned ndist;             /* number of distance code lengths */
+    unsigned have;              /* number of code lengths in lens[] */
+    code FAR *next;             /* next available space in codes[] */
+    unsigned short lens[320];   /* temporary storage for code lengths */
+    unsigned short work[288];   /* work area for code table building */
+    code codes[ENOUGH];         /* space for code tables */
+    int sane;                   /* if false, allow invalid distance too far */
+    int back;                   /* bits back of last unprocessed length/lit */
+    unsigned was;               /* initial length of match */
+};
+

--- /dev/null
+++ b/src/in_xsf_framework/zlib/inftrees.c
@@ -1,1 +1,305 @@
-
+/* inftrees.c -- generate Huffman trees for efficient decoding
+ * Copyright (C) 1995-2017 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+#include "zutil.h"
+#include "inftrees.h"
+
+#define MAXBITS 15
+
+const char inflate_copyright[] =
+   " inflate 1.2.11 Copyright 1995-2017 Mark Adler ";
+/*
+  If you use the zlib library in a product, an acknowledgment is welcome
+  in the documentation of your product. If for some reason you cannot
+  include such an acknowledgment, I would appreciate that you keep this
+  copyright string in the executable of your product.
+ */
+
+/*
+   Build a set of tables to decode the provided canonical Huffman code.
+   The code lengths are lens[0..codes-1].  The result starts at *table,
+   whose indices are 0..2^bits-1.  work is a writable array of at least
+   lens shorts, which is used as a work area.  type is the type of code
+   to be generated, CODES, LENS, or DISTS.  On return, zero is success,
+   -1 is an invalid code, and +1 means that ENOUGH isn't enough.  table
+   on return points to the next available entry's address.  bits is the
+   requested root table index bits, and on return it is the actual root
+   table index bits.  It will differ if the request is greater than the
+   longest code or if it is less than the shortest code.
+ */
+int ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work)
+codetype type;
+unsigned short FAR *lens;
+unsigned codes;
+code FAR * FAR *table;
+unsigned FAR *bits;
+unsigned short FAR *work;
+{
+    unsigned len;               /* a code's length in bits */
+    unsigned sym;               /* index of code symbols */
+    unsigned min, max;          /* minimum and maximum code lengths */
+    unsigned root;              /* number of index bits for root table */
+    unsigned curr;              /* number of index bits for current table */
+    unsigned drop;              /* code bits to drop for sub-table */
+    int left;                   /* number of prefix codes available */
+    unsigned used;              /* code entries in table used */
+    unsigned huff;              /* Huffman code */
+    unsigned incr;              /* for incrementing code, index */
+    unsigned fill;              /* index for replicating entries */
+    unsigned low;               /* low bits for current root entry */
+    unsigned mask;              /* mask for low root bits */
+    code here;                  /* table entry for duplication */
+    code FAR *next;             /* next available space in table */
+    const unsigned short FAR *base;     /* base value table to use */
+    const unsigned short FAR *extra;    /* extra bits table to use */
+    unsigned match;             /* use base and extra for symbol >= match */
+    unsigned short count[MAXBITS+1];    /* number of codes of each length */
+    unsigned short offs[MAXBITS+1];     /* offsets in table for each length */
+    static const unsigned short lbase[31] = { /* Length codes 257..285 base */
+        3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
+        35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
+    static const unsigned short lext[31] = { /* Length codes 257..285 extra */
+        16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
+        19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 77, 202};
+    static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
+        1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
+        257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
+        8193, 12289, 16385, 24577, 0, 0};
+    static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
+        16, 16, 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, 64, 64};
+
+    /*
+       Process a set of code lengths to create a canonical Huffman code.  The
+       code lengths are lens[0..codes-1].  Each length corresponds to the
+       symbols 0..codes-1.  The Huffman code is generated by first sorting the
+       symbols by length from short to long, and retaining the symbol order
+       for codes with equal lengths.  Then the code starts with all zero bits
+       for the first code of the shortest length, and the codes are integer
+       increments for the same length, and zeros are appended as the length
+       increases.  For the deflate format, these bits are stored backwards
+       from their more natural integer increment ordering, and so when the
+       decoding tables are built in the large loop below, the integer codes
+       are incremented backwards.
+
+       This routine assumes, but does not check, that all of the entries in
+       lens[] are in the range 0..MAXBITS.  The caller must assure this.
+       1..MAXBITS is interpreted as that code length.  zero means that that
+       symbol does not occur in this code.
+
+       The codes are sorted by computing a count of codes for each length,
+       creating from that a table of starting indices for each length in the
+       sorted table, and then entering the symbols in order in the sorted
+       table.  The sorted table is work[], with that space being provided by
+       the caller.
+
+       The length counts are used for other purposes as well, i.e. finding
+       the minimum and maximum length codes, determining if there are any
+       codes at all, checking for a valid set of lengths, and looking ahead
+       at length counts to determine sub-table sizes when building the
+       decoding tables.
+     */
+
+    /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
+    for (len = 0; len <= MAXBITS; len++)
+        count[len] = 0;
+    for (sym = 0; sym < codes; sym++)
+        count[lens[sym]]++;
+
+    /* bound code lengths, force root to be within code lengths */
+    root = *bits;
+    for (max = MAXBITS; max >= 1; max--)
+        if (count[max] != 0) break;
+    if (root > max) root = max;
+    if (max == 0) {                     /* no symbols to code at all */
+        here.op = (unsigned char)64;    /* invalid code marker */
+        here.bits = (unsigned char)1;
+        here.val = (unsigned short)0;
+        *(*table)++ = here;             /* make a table to force an error */
+        *(*table)++ = here;
+        *bits = 1;
+        return 0;     /* no symbols, but wait for decoding to report error */
+    }
+    for (min = 1; min < max; min++)
+        if (count[min] != 0) break;
+    if (root < min) root = min;
+
+    /* check for an over-subscribed or incomplete set of lengths */
+    left = 1;
+    for (len = 1; len <= MAXBITS; len++) {
+        left <<= 1;
+        left -= count[len];
+        if (left < 0) return -1;        /* over-subscribed */
+    }
+    if (left > 0 && (type == CODES || max != 1))
+        return -1;                      /* incomplete set */
+
+    /* generate offsets into symbol table for each length for sorting */
+    offs[1] = 0;
+    for (len = 1; len < MAXBITS; len++)
+        offs[len + 1] = offs[len] + count[len];
+
+    /* sort symbols by length, by symbol order within each length */
+    for (sym = 0; sym < codes; sym++)
+        if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
+
+    /*
+       Create and fill in decoding tables.  In this loop, the table being
+       filled is at next and has curr index bits.  The code being used is huff
+       with length len.  That code is converted to an index by dropping drop
+       bits off of the bottom.  For codes where len is less than drop + curr,
+       those top drop + curr - len bits are incremented through all values to
+       fill the table with replicated entries.
+
+       root is the number of index bits for the root table.  When len exceeds
+       root, sub-tables are created pointed to by the root entry with an index
+       of the low root bits of huff.  This is saved in low to check for when a
+       new sub-table should be started.  drop is zero when the root table is
+       being filled, and drop is root when sub-tables are being filled.
+
+       When a new sub-table is needed, it is necessary to look ahead in the
+       code lengths to determine what size sub-table is needed.  The length
+       counts are used for this, and so count[] is decremented as codes are
+       entered in the tables.
+
+       used keeps track of how many table entries have been allocated from the
+       provided *table space.  It is checked for LENS and DIST tables against
+       the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
+       the initial root table size constants.  See the comments in inftrees.h
+       for more information.
+
+       sym increments through all symbols, and the loop terminates when
+       all codes of length max, i.e. all codes, have been processed.  This
+       routine permits incomplete codes, so another loop after this one fills
+       in the rest of the decoding tables with invalid code markers.
+     */
+
+    /* set up for code type */
+    switch (type) {
+    case CODES:
+        base = extra = work;    /* dummy value--not used */
+        match = 20;
+        break;
+    case LENS:
+        base = lbase;
+        extra = lext;
+        match = 257;
+        break;
+    default:    /* DISTS */
+        base = dbase;
+        extra = dext;
+        match = 0;
+    }
+
+    /* initialize state for loop */
+    huff = 0;                   /* starting code */
+    sym = 0;                    /* starting code symbol */
+    len = min;                  /* starting code length */
+    next = *table;              /* current table to fill in */
+    curr = root;                /* current table index bits */
+    drop = 0;                   /* current bits to drop from code for index */
+    low = (unsigned)(-1);       /* trigger new sub-table when len > root */
+    used = 1U << root;          /* use root table entries */
+    mask = used - 1;            /* mask for comparing low */
+
+    /* check available table space */
+    if ((type == LENS && used > ENOUGH_LENS) ||
+        (type == DISTS && used > ENOUGH_DISTS))
+        return 1;
+
+    /* process all codes and make table entries */
+    for (;;) {
+        /* create table entry */
+        here.bits = (unsigned char)(len - drop);
+        if (work[sym] + 1U < match) {
+            here.op = (unsigned char)0;
+            here.val = work[sym];
+        }
+        else if (work[sym] >= match) {
+            here.op = (unsigned char)(extra[work[sym] - match]);
+            here.val = base[work[sym] - match];
+        }
+        else {
+            here.op = (unsigned char)(32 + 64);         /* end of block */
+            here.val = 0;
+        }
+
+        /* replicate for those indices with low len bits equal to huff */
+        incr = 1U << (len - drop);
+        fill = 1U << curr;
+        min = fill;                 /* save offset to next table */
+        do {
+            fill -= incr;
+            next[(huff >> drop) + fill] = here;
+        } while (fill != 0);
+
+        /* backwards increment the len-bit code huff */
+        incr = 1U << (len - 1);
+        while (huff & incr)
+            incr >>= 1;
+        if (incr != 0) {
+            huff &= incr - 1;
+            huff += incr;
+        }
+        else
+            huff = 0;
+
+        /* go to next symbol, update count, len */
+        sym++;
+        if (--(count[len]) == 0) {
+            if (len == max) break;
+            len = lens[work[sym]];
+        }
+
+        /* create new sub-table if needed */
+        if (len > root && (huff & mask) != low) {
+            /* if first time, transition to sub-tables */
+            if (drop == 0)
+                drop = root;
+
+            /* increment past last table */
+            next += min;            /* here min is 1 << curr */
+
+            /* determine length of next table */
+            curr = len - drop;
+            left = (int)(1 << curr);
+            while (curr + drop < max) {
+                left -= count[curr + drop];
+                if (left <= 0) break;
+                curr++;
+                left <<= 1;
+            }
+
+            /* check for enough space */
+            used += 1U << curr;
+            if ((type == LENS && used > ENOUGH_LENS) ||
+                (type == DISTS && used > ENOUGH_DISTS))
+                return 1;
+
+            /* point entry in root table to sub-table */
+            low = huff & mask;
+            (*table)[low].op = (unsigned char)curr;
+            (*table)[low].bits = (unsigned char)root;
+            (*table)[low].val = (unsigned short)(next - *table);
+        }
+    }
+
+    /* fill in remaining table entry if code is incomplete (guaranteed to have
+       at most one remaining entry, since if the code is incomplete, the
+       maximum code length that was allowed to get this far is one bit) */
+    if (huff != 0) {
+        here.op = (unsigned char)64;            /* invalid code marker */
+        here.bits = (unsigned char)(len - drop);
+        here.val = (unsigned short)0;
+        next[huff] = here;
+    }
+
+    /* set return parameters */
+    *table += used;
+    *bits = root;
+    return 0;
+}
+

--- /dev/null
+++ b/src/in_xsf_framework/zlib/inftrees.h
@@ -1,1 +1,63 @@
+/* inftrees.h -- header to use inftrees.c
+ * Copyright (C) 1995-2005, 2010 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
 
+/* WARNING: this file should *not* be used by applications. It is
+   part of the implementation of the compression library and is
+   subject to change. Applications should only use zlib.h.
+ */
+
+/* Structure for decoding tables.  Each entry provides either the
+   information needed to do the operation requested by the code that
+   indexed that table entry, or it provides a pointer to another
+   table that indexes more bits of the code.  op indicates whether
+   the entry is a pointer to another table, a literal, a length or
+   distance, an end-of-block, or an invalid code.  For a table
+   pointer, the low four bits of op is the number of index bits of
+   that table.  For a length or distance, the low four bits of op
+   is the number of extra bits to get after the code.  bits is
+   the number of bits in this code or part of the code to drop off
+   of the bit buffer.  val is the actual byte to output in the case
+   of a literal, the base length or distance, or the offset from
+   the current table to the next table.  Each entry is four bytes. */
+typedef struct {
+    unsigned char op;           /* operation, extra bits, table bits */
+    unsigned char bits;         /* bits in this part of the code */
+    unsigned short val;         /* offset in table or code value */
+} code;
+
+/* op values as set by inflate_table():
+    00000000 - literal
+    0000tttt - table link, tttt != 0 is the number of table index bits
+    0001eeee - length or distance, eeee is the number of extra bits
+    01100000 - end of block
+    01000000 - invalid code
+ */
+
+/* Maximum size of the dynamic table.  The maximum number of code structures is
+   1444, which is the sum of 852 for literal/length codes and 592 for distance
+   codes.  These values were found by exhaustive searches using the program
+   examples/enough.c found in the zlib distribtution.  The arguments to that
+   program are the number of symbols, the initial root table size, and the
+   maximum bit length of a code.  "enough 286 9 15" for literal/length codes
+   returns returns 852, and "enough 30 6 15" for distance codes returns 592.
+   The initial root table size (9 or 6) is found in the fifth argument of the
+   inflate_table() calls in inflate.c and infback.c.  If the root table size is
+   changed, then these maximum sizes would be need to be recalculated and
+   updated. */
+#define ENOUGH_LENS 852
+#define ENOUGH_DISTS 592
+#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS)
+
+/* Type of code to build for inflate_table() */
+typedef enum {
+    CODES,
+    LENS,
+    DISTS
+} codetype;
+
+int ZLIB_INTERNAL inflate_table OF((codetype type, unsigned short FAR *lens,
+                             unsigned codes, code FAR * FAR *table,
+                             unsigned FAR *bits, unsigned short FAR *work));
+

--- /dev/null
+++ b/src/in_xsf_framework/zlib/uncompr.c
@@ -1,1 +1,94 @@
+/* uncompr.c -- decompress a memory buffer
+ * Copyright (C) 1995-2003, 2010, 2014, 2016 Jean-loup Gailly, Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
 
+/* @(#) $Id$ */
+
+#define ZLIB_INTERNAL
+#include "zlib.h"
+
+/* ===========================================================================
+     Decompresses the source buffer into the destination buffer.  *sourceLen is
+   the byte length of the source buffer. Upon entry, *destLen is the total size
+   of the destination buffer, which must be large enough to hold the entire
+   uncompressed data. (The size of the uncompressed data must have been saved
+   previously by the compressor and transmitted to the decompressor by some
+   mechanism outside the scope of this compression library.) Upon exit,
+   *destLen is the size of the decompressed data and *sourceLen is the number
+   of source bytes consumed. Upon return, source + *sourceLen points to the
+   first unused input byte.
+
+     uncompress returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_BUF_ERROR if there was not enough room in the output buffer, or
+   Z_DATA_ERROR if the input data was corrupted, including if the input data is
+   an incomplete zlib stream.
+*/
+int ZEXPORT uncompress2 (dest, destLen, source, sourceLen)
+    Bytef *dest;
+    uLongf *destLen;
+    const Bytef *source;
+    uLong *sourceLen;
+{
+    z_stream stream;
+    int err;
+    const uInt max = (uInt)-1;
+    uLong len, left;
+    Byte buf[1];    /* for detection of incomplete stream when *destLen == 0 */
+
+    len = *sourceLen;
+    if (*destLen) {
+        left = *destLen;
+        *destLen = 0;
+    }
+    else {
+        left = 1;
+        dest = buf;
+    }
+
+    stream.next_in = (z_const Bytef *)source;
+    stream.avail_in = 0;
+    stream.zalloc = (alloc_func)0;
+    stream.zfree = (free_func)0;
+    stream.opaque = (voidpf)0;
+
+    err = inflateInit(&stream);
+    if (err != Z_OK) return err;
+
+    stream.next_out = dest;
+    stream.avail_out = 0;
+
+    do {
+        if (stream.avail_out == 0) {
+            stream.avail_out = left > (uLong)max ? max : (uInt)left;
+            left -= stream.avail_out;
+        }
+        if (stream.avail_in == 0) {
+            stream.avail_in = len > (uLong)max ? max : (uInt)len;
+            len -= stream.avail_in;
+        }
+        err = inflate(&stream, Z_NO_FLUSH);
+    } while (err == Z_OK);
+
+    *sourceLen -= len + stream.avail_in;
+    if (dest != buf)
+        *destLen = stream.total_out;
+    else if (stream.total_out && err == Z_BUF_ERROR)
+        left = 1;
+
+    inflateEnd(&stream);
+    return err == Z_STREAM_END ? Z_OK :
+           err == Z_NEED_DICT ? Z_DATA_ERROR  :
+           err == Z_BUF_ERROR && left + stream.avail_out ? Z_DATA_ERROR :
+           err;
+}
+
+int ZEXPORT uncompress (dest, destLen, source, sourceLen)
+    Bytef *dest;
+    uLongf *destLen;
+    const Bytef *source;
+    uLong sourceLen;
+{
+    return uncompress2(dest, destLen, source, &sourceLen);
+}
+

--- /dev/null
+++ b/src/in_xsf_framework/zlib/zconf.h
@@ -1,1 +1,535 @@
-
+/* zconf.h -- configuration of the zlib compression library
+ * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* @(#) $Id$ */
+
+#ifndef ZCONF_H
+#define ZCONF_H
+
+/*
+ * If you *really* need a unique prefix for all types and library functions,
+ * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
+ * Even better than compiling with -DZ_PREFIX would be to use configure to set
+ * this permanently in zconf.h using "./configure --zprefix".
+ */
+#ifdef Z_PREFIX     /* may be set to #if 1 by ./configure */
+#  define Z_PREFIX_SET
+
+/* all linked symbols and init macros */
+#  define _dist_code            z__dist_code
+#  define _length_code          z__length_code
+#  define _tr_align             z__tr_align
+#  define _tr_flush_bits        z__tr_flush_bits
+#  define _tr_flush_block       z__tr_flush_block
+#  define _tr_init              z__tr_init
+#  define _tr_stored_block      z__tr_stored_block
+#  define _tr_tally             z__tr_tally
+#  define adler32               z_adler32
+#  define adler32_combine       z_adler32_combine
+#  define adler32_combine64     z_adler32_combine64
+#  define adler32_z             z_adler32_z
+#  ifndef Z_SOLO
+#    define compress              z_compress
+#    define compress2             z_compress2
+#    define compressBound         z_compressBound
+#  endif
+#  define crc32                 z_crc32
+#  define crc32_combine         z_crc32_combine
+#  define crc32_combine64       z_crc32_combine64
+#  define crc32_z               z_crc32_z
+#  define deflate               z_deflate
+#  define deflateBound          z_deflateBound
+#  define deflateCopy           z_deflateCopy
+#  define deflateEnd            z_deflateEnd
+#  define deflateGetDictionary  z_deflateGetDictionary
+#  define deflateInit           z_deflateInit
+#  define deflateInit2          z_deflateInit2
+#  define deflateInit2_         z_deflateInit2_
+#  define deflateInit_          z_deflateInit_
+#  define deflateParams         z_deflateParams
+#  define deflatePending        z_deflatePending
+#  define deflatePrime          z_deflatePrime
+#  define deflateReset          z_deflateReset
+#  define deflateResetKeep      z_deflateResetKeep
+#  define deflateSetDictionary  z_deflateSetDictionary
+#  define deflateSetHeader      z_deflateSetHeader
+#  define deflateTune           z_deflateTune
+#  define deflate_copyright     z_deflate_copyright
+#  define get_crc_table         z_get_crc_table
+#  ifndef Z_SOLO
+#    define gz_error              z_gz_error
+#    define gz_intmax             z_gz_intmax
+#    define gz_strwinerror        z_gz_strwinerror
+#    define gzbuffer              z_gzbuffer
+#    define gzclearerr            z_gzclearerr
+#    define gzclose               z_gzclose
+#    define gzclose_r             z_gzclose_r
+#    define gzclose_w             z_gzclose_w
+#    define gzdirect              z_gzdirect
+#    define gzdopen               z_gzdopen
+#    define gzeof                 z_gzeof
+#    define gzerror               z_gzerror
+#    define gzflush               z_gzflush
+#    define gzfread               z_gzfread
+#    define gzfwrite              z_gzfwrite
+#    define gzgetc                z_gzgetc
+#    define gzgetc_               z_gzgetc_
+#    define gzgets                z_gzgets
+#    define gzoffset              z_gzoffset
+#    define gzoffset64            z_gzoffset64
+#    define gzopen                z_gzopen
+#    define gzopen64              z_gzopen64
+#    ifdef _WIN32
+#      define gzopen_w              z_gzopen_w
+#    endif
+#    define gzprintf              z_gzprintf
+#    define gzputc                z_gzputc
+#    define gzputs                z_gzputs
+#    define gzread                z_gzread
+#    define gzrewind              z_gzrewind
+#    define gzseek                z_gzseek
+#    define gzseek64              z_gzseek64
+#    define gzsetparams           z_gzsetparams
+#    define gztell                z_gztell
+#    define gztell64              z_gztell64
+#    define gzungetc              z_gzungetc
+#    define gzvprintf             z_gzvprintf
+#    define gzwrite               z_gzwrite
+#  endif
+#  define inflate               z_inflate
+#  define inflateBack           z_inflateBack
+#  define inflateBackEnd        z_inflateBackEnd
+#  define inflateBackInit       z_inflateBackInit
+#  define inflateBackInit_      z_inflateBackInit_
+#  define inflateCodesUsed      z_inflateCodesUsed
+#  define inflateCopy           z_inflateCopy
+#  define inflateEnd            z_inflateEnd
+#  define inflateGetDictionary  z_inflateGetDictionary
+#  define inflateGetHeader      z_inflateGetHeader
+#  define inflateInit           z_inflateInit
+#  define inflateInit2          z_inflateInit2
+#  define inflateInit2_         z_inflateInit2_
+#  define inflateInit_          z_inflateInit_
+#  define inflateMark           z_inflateMark
+#  define inflatePrime          z_inflatePrime
+#  define inflateReset          z_inflateReset
+#  define inflateReset2         z_inflateReset2
+#  define inflateResetKeep      z_inflateResetKeep
+#  define inflateSetDictionary  z_inflateSetDictionary
+#  define inflateSync           z_inflateSync
+#  define inflateSyncPoint      z_inflateSyncPoint
+#  define inflateUndermine      z_inflateUndermine
+#  define inflateValidate       z_inflateValidate
+#  define inflate_copyright     z_inflate_copyright
+#  define inflate_fast          z_inflate_fast
+#  define inflate_table         z_inflate_table
+#  ifndef Z_SOLO
+#    define uncompress            z_uncompress
+#    define uncompress2           z_uncompress2
+#  endif
+#  define zError                z_zError
+#  ifndef Z_SOLO
+#    define zcalloc               z_zcalloc
+#    define zcfree                z_zcfree
+#  endif
+#  define zlibCompileFlags      z_zlibCompileFlags
+#  define zlibVersion           z_zlibVersion
+
+/* all zlib typedefs in zlib.h and zconf.h */
+#  define Byte                  z_Byte
+#  define Bytef                 z_Bytef
+#  define alloc_func            z_alloc_func
+#  define charf                 z_charf
+#  define free_func             z_free_func
+#  ifndef Z_SOLO
+#    define gzFile                z_gzFile
+#  endif
+#  define gz_header             z_gz_header
+#  define gz_headerp            z_gz_headerp
+#  define in_func               z_in_func
+#  define intf                  z_intf
+#  define out_func              z_out_func
+#  define uInt                  z_uInt
+#  define uIntf                 z_uIntf
+#  define uLong                 z_uLong
+#  define uLongf                z_uLongf
+#  define voidp                 z_voidp
+#  define voidpc                z_voidpc
+#  define voidpf                z_voidpf
+
+/* all zlib structs in zlib.h and zconf.h */
+#  define gz_header_s           z_gz_header_s
+#  define internal_state        z_internal_state
+
+#endif
+
+#if defined(__MSDOS__) && !defined(MSDOS)
+#  define MSDOS
+#endif
+#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
+#  define OS2
+#endif
+#if defined(_WINDOWS) && !defined(WINDOWS)
+#  define WINDOWS
+#endif
+#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
+#  ifndef WIN32
+#    define WIN32
+#  endif
+#endif
+#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
+#  if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
+#    ifndef SYS16BIT
+#      define SYS16BIT
+#    endif
+#  endif
+#endif
+
+/*
+ * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
+ * than 64k bytes at a time (needed on systems with 16-bit int).
+ */
+#ifdef SYS16BIT
+#  define MAXSEG_64K
+#endif
+#ifdef MSDOS
+#  define UNALIGNED_OK
+#endif
+
+#ifdef __STDC_VERSION__
+#  ifndef STDC
+#    define STDC
+#  endif
+#  if __STDC_VERSION__ >= 199901L
+#    ifndef STDC99
+#      define STDC99
+#    endif
+#  endif
+#endif
+#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
+#  define STDC
+#endif
+#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
+#  define STDC
+#endif
+#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
+#  define STDC
+#endif
+#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
+#  define STDC
+#endif
+
+#if defined(__OS400__) && !defined(STDC)    /* iSeries (formerly AS/400). */
+#  define STDC
+#endif
+
+#ifndef STDC
+#  ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
+#    define const       /* note: need a more gentle solution here */
+#  endif
+#endif
+
+#if defined(ZLIB_CONST) && !defined(z_const)
+#  define z_const const
+#else
+#  define z_const
+#endif
+
+#ifdef Z_SOLO
+   typedef unsigned long z_size_t;
+#else
+#  define z_longlong long long
+#  if defined(NO_SIZE_T)
+     typedef unsigned NO_SIZE_T z_size_t;
+#  elif defined(STDC)
+#    include <stddef.h>
+     typedef size_t z_size_t;
+#  else
+     typedef unsigned long z_size_t;
+#  endif
+#  undef z_longlong
+#endif
+
+/* Maximum value for memLevel in deflateInit2 */
+#ifndef MAX_MEM_LEVEL
+#  ifdef MAXSEG_64K
+#    define MAX_MEM_LEVEL 8
+#  else
+#    define MAX_MEM_LEVEL 9
+#  endif
+#endif
+
+/* Maximum value for windowBits in deflateInit2 and inflateInit2.
+ * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
+ * created by gzip. (Files created by minigzip can still be extracted by
+ * gzip.)
+ */
+#ifndef MAX_WBITS
+#  define MAX_WBITS   15 /* 32K LZ77 window */
+#endif
+
+/* The memory requirements for deflate are (in bytes):
+            (1 << (windowBits+2)) +  (1 << (memLevel+9))
+ that is: 128K for windowBits=15  +  128K for memLevel = 8  (default values)
+ plus a few kilobytes for small objects. For example, if you want to reduce
+ the default memory requirements from 256K to 128K, compile with
+     make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
+ Of course this will generally degrade compression (there's no free lunch).
+
+   The memory requirements for inflate are (in bytes) 1 << windowBits
+ that is, 32K for windowBits=15 (default value) plus about 7 kilobytes
+ for small objects.
+*/
+
+                        /* Type declarations */
+
+#ifndef OF /* function prototypes */
+#  ifdef STDC
+#    define OF(args)  args
+#  else
+#    define OF(args)  ()
+#  endif
+#endif
+
+#ifndef Z_ARG /* function prototypes for stdarg */
+#  if defined(STDC) || defined(Z_HAVE_STDARG_H)
+#    define Z_ARG(args)  args
+#  else
+#    define Z_ARG(args)  ()
+#  endif
+#endif
+
+/* The following definitions for FAR are needed only for MSDOS mixed
+ * model programming (small or medium model with some far allocations).
+ * This was tested only with MSC; for other MSDOS compilers you may have
+ * to define NO_MEMCPY in zutil.h.  If you don't need the mixed model,
+ * just define FAR to be empty.
+ */
+#ifdef SYS16BIT
+#  if defined(M_I86SM) || defined(M_I86MM)
+     /* MSC small or medium model */
+#    define SMALL_MEDIUM
+#    ifdef _MSC_VER
+#      define FAR _far
+#    else
+#      define FAR far
+#    endif
+#  endif
+#  if (defined(__SMALL__) || defined(__MEDIUM__))
+     /* Turbo C small or medium model */
+#    define SMALL_MEDIUM
+#    ifdef __BORLANDC__
+#      define FAR _far
+#    else
+#      define FAR far
+#    endif
+#  endif
+#endif
+
+#if defined(WINDOWS) || defined(WIN32)
+   /* If building or using zlib as a DLL, define ZLIB_DLL.
+    * This is not mandatory, but it offers a little performance increase.
+    */
+#  ifdef ZLIB_DLL
+#    if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
+#      ifdef ZLIB_INTERNAL
+#        define ZEXTERN extern __declspec(dllexport)
+#      else
+#        define ZEXTERN extern __declspec(dllimport)
+#      endif
+#    endif
+#  endif  /* ZLIB_DLL */
+   /* If building or using zlib with the WINAPI/WINAPIV calling convention,
+    * define ZLIB_WINAPI.
+    * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
+    */
+#  ifdef ZLIB_WINAPI
+#    ifdef FAR
+#      undef FAR
+#    endif
+#    include <windows.h>
+     /* No need for _export, use ZLIB.DEF instead. */
+     /* For complete Windows compatibility, use WINAPI, not __stdcall. */
+#    define ZEXPORT WINAPI
+#    ifdef WIN32
+#      define ZEXPORTVA WINAPIV
+#    else
+#      define ZEXPORTVA FAR CDECL
+#    endif
+#  endif
+#endif
+
+#if defined (__BEOS__)
+#  ifdef ZLIB_DLL
+#    ifdef ZLIB_INTERNAL
+#      define ZEXPORT   __declspec(dllexport)
+#      define ZEXPORTVA __declspec(dllexport)
+#    else
+#      define ZEXPORT   __declspec(dllimport)
+#      define ZEXPORTVA __declspec(dllimport)
+#    endif
+#  endif
+#endif
+
+#ifndef ZEXTERN
+#  define ZEXTERN extern
+#endif
+#ifndef ZEXPORT
+#  define ZEXPORT
+#endif
+#ifndef ZEXPORTVA
+#  define ZEXPORTVA
+#endif
+
+#ifndef FAR
+#  define FAR
+#endif
+
+#if !defined(__MACTYPES__)
+typedef unsigned char  Byte;  /* 8 bits */
+#endif
+typedef unsigned int   uInt;  /* 16 bits or more */
+typedef unsigned long  uLong; /* 32 bits or more */
+
+#ifdef SMALL_MEDIUM
+   /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
+#  define Bytef Byte FAR
+#else
+   typedef Byte  FAR Bytef;
+#endif
+typedef char  FAR charf;
+typedef int   FAR intf;
+typedef uInt  FAR uIntf;
+typedef uLong FAR uLongf;
+
+#ifdef STDC
+   typedef void const *voidpc;
+   typedef void FAR   *voidpf;
+   typedef void       *voidp;
+#else
+   typedef Byte const *voidpc;
+   typedef Byte FAR   *voidpf;
+   typedef Byte       *voidp;
+#endif
+
+#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC)
+#  include <limits.h>
+#  if (UINT_MAX == 0xffffffffUL)
+#    define Z_U4 unsigned
+#  elif (ULONG_MAX == 0xffffffffUL)
+#    define Z_U4 unsigned long
+#  elif (USHRT_MAX == 0xffffffffUL)
+#    define Z_U4 unsigned short
+#  endif
+#endif
+
+#ifdef Z_U4
+   typedef Z_U4 z_crc_t;
+#else
+   typedef unsigned long z_crc_t;
+#endif
+
+#ifdef HAVE_UNISTD_H    /* may be set to #if 1 by ./configure */
+#  define Z_HAVE_UNISTD_H
+#endif
+
+#ifdef HAVE_STDARG_H    /* may be set to #if 1 by ./configure */
+#  define Z_HAVE_STDARG_H
+#endif
+
+#ifdef STDC
+#  ifndef Z_SOLO
+#    include <sys/types.h>      /* for off_t */
+#  endif
+#endif
+
+#if defined(STDC) || defined(Z_HAVE_STDARG_H)
+#  ifndef Z_SOLO
+#    include <stdarg.h>         /* for va_list */
+#  endif
+#endif
+
+#ifdef _WIN32
+#  ifndef Z_SOLO
+#    include <stddef.h>         /* for wchar_t */
+#  endif
+#endif
+
+/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and
+ * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even
+ * though the former does not conform to the LFS document), but considering
+ * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as
+ * equivalently requesting no 64-bit operations
+ */
+#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1
+#  undef _LARGEFILE64_SOURCE
+#endif
+
+#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H)
+#  define Z_HAVE_UNISTD_H
+#endif
+#ifndef Z_SOLO
+#  if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE)
+#    include <unistd.h>         /* for SEEK_*, off_t, and _LFS64_LARGEFILE */
+#    ifdef VMS
+#      include <unixio.h>       /* for off_t */
+#    endif
+#    ifndef z_off_t
+#      define z_off_t off_t
+#    endif
+#  endif
+#endif
+
+#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0
+#  define Z_LFS64
+#endif
+
+#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64)
+#  define Z_LARGE64
+#endif
+
+#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64)
+#  define Z_WANT64
+#endif
+
+#if !defined(SEEK_SET) && !defined(Z_SOLO)
+#  define SEEK_SET        0       /* Seek from beginning of file.  */
+#  define SEEK_CUR        1       /* Seek from current position.  */
+#  define SEEK_END        2       /* Set file pointer to EOF plus "offset" */
+#endif
+
+#ifndef z_off_t
+#  define z_off_t long
+#endif
+
+#if !defined(_WIN32) && defined(Z_LARGE64)
+#  define z_off64_t off64_t
+#else
+#  if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO)
+#    define z_off64_t __int64
+#  else
+#    define z_off64_t z_off_t
+#  endif
+#endif
+
+/* MVS linker does not support external names larger than 8 bytes */
+#if defined(__MVS__)
+  #pragma map(deflateInit_,"DEIN")
+  #pragma map(deflateInit2_,"DEIN2")
+  #pragma map(deflateEnd,"DEEND")
+  #pragma map(deflateBound,"DEBND")
+  #pragma map(inflateInit_,"ININ")
+  #pragma map(inflateInit2_,"ININ2")
+  #pragma map(inflateEnd,"INEND")
+  #pragma map(inflateSync,"INSY")
+  #pragma map(inflateSetDictionary,"INSEDI")
+  #pragma map(compressBound,"CMBND")
+  #pragma map(inflate_table,"INTABL")
+  #pragma map(inflate_fast,"INFA")
+  #pragma map(inflate_copyright,"INCOPY")
+#endif
+
+#endif /* ZCONF_H */
+

--- /dev/null
+++ b/src/in_xsf_framework/zlib/zlib.h
@@ -1,1 +1,1913 @@
-
+/* zlib.h -- interface of the 'zlib' general purpose compression library
+  version 1.2.11, January 15th, 2017
+
+  Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+
+  Jean-loup Gailly        Mark Adler
+  jloup@gzip.org          madler@alumni.caltech.edu
+
+
+  The data format used by the zlib library is described by RFCs (Request for
+  Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950
+  (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format).
+*/
+
+#ifndef ZLIB_H
+#define ZLIB_H
+
+#include "zconf.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define ZLIB_VERSION "1.2.11"
+#define ZLIB_VERNUM 0x12b0
+#define ZLIB_VER_MAJOR 1
+#define ZLIB_VER_MINOR 2
+#define ZLIB_VER_REVISION 11
+#define ZLIB_VER_SUBREVISION 0
+
+/*
+    The 'zlib' compression library provides in-memory compression and
+  decompression functions, including integrity checks of the uncompressed data.
+  This version of the library supports only one compression method (deflation)
+  but other algorithms will be added later and will have the same stream
+  interface.
+
+    Compression can be done in a single step if the buffers are large enough,
+  or can be done by repeated calls of the compression function.  In the latter
+  case, the application must provide more input and/or consume the output
+  (providing more output space) before each call.
+
+    The compressed data format used by default by the in-memory functions is
+  the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
+  around a deflate stream, which is itself documented in RFC 1951.
+
+    The library also supports reading and writing files in gzip (.gz) format
+  with an interface similar to that of stdio using the functions that start
+  with "gz".  The gzip format is different from the zlib format.  gzip is a
+  gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
+
+    This library can optionally read and write gzip and raw deflate streams in
+  memory as well.
+
+    The zlib format was designed to be compact and fast for use in memory
+  and on communications channels.  The gzip format was designed for single-
+  file compression on file systems, has a larger header than zlib to maintain
+  directory information, and uses a different, slower check method than zlib.
+
+    The library does not install any signal handler.  The decoder checks
+  the consistency of the compressed data, so the library should never crash
+  even in the case of corrupted input.
+*/
+
+typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
+typedef void   (*free_func)  OF((voidpf opaque, voidpf address));
+
+struct internal_state;
+
+typedef struct z_stream_s {
+    z_const Bytef *next_in;     /* next input byte */
+    uInt     avail_in;  /* number of bytes available at next_in */
+    uLong    total_in;  /* total number of input bytes read so far */
+
+    Bytef    *next_out; /* next output byte will go here */
+    uInt     avail_out; /* remaining free space at next_out */
+    uLong    total_out; /* total number of bytes output so far */
+
+    z_const char *msg;  /* last error message, NULL if no error */
+    struct internal_state FAR *state; /* not visible by applications */
+
+    alloc_func zalloc;  /* used to allocate the internal state */
+    free_func  zfree;   /* used to free the internal state */
+    voidpf     opaque;  /* private data object passed to zalloc and zfree */
+
+    int     data_type;  /* best guess about the data type: binary or text
+                           for deflate, or the decoding state for inflate */
+    uLong   adler;      /* Adler-32 or CRC-32 value of the uncompressed data */
+    uLong   reserved;   /* reserved for future use */
+} z_stream;
+
+typedef z_stream FAR *z_streamp;
+
+/*
+     gzip header information passed to and from zlib routines.  See RFC 1952
+  for more details on the meanings of these fields.
+*/
+typedef struct gz_header_s {
+    int     text;       /* true if compressed data believed to be text */
+    uLong   time;       /* modification time */
+    int     xflags;     /* extra flags (not used when writing a gzip file) */
+    int     os;         /* operating system */
+    Bytef   *extra;     /* pointer to extra field or Z_NULL if none */
+    uInt    extra_len;  /* extra field length (valid if extra != Z_NULL) */
+    uInt    extra_max;  /* space at extra (only when reading header) */
+    Bytef   *name;      /* pointer to zero-terminated file name or Z_NULL */
+    uInt    name_max;   /* space at name (only when reading header) */
+    Bytef   *comment;   /* pointer to zero-terminated comment or Z_NULL */
+    uInt    comm_max;   /* space at comment (only when reading header) */
+    int     hcrc;       /* true if there was or will be a header crc */
+    int     done;       /* true when done reading gzip header (not used
+                           when writing a gzip file) */
+} gz_header;
+
+typedef gz_header FAR *gz_headerp;
+
+/*
+     The application must update next_in and avail_in when avail_in has dropped
+   to zero.  It must update next_out and avail_out when avail_out has dropped
+   to zero.  The application must initialize zalloc, zfree and opaque before
+   calling the init function.  All other fields are set by the compression
+   library and must not be updated by the application.
+
+     The opaque value provided by the application will be passed as the first
+   parameter for calls of zalloc and zfree.  This can be useful for custom
+   memory management.  The compression library attaches no meaning to the
+   opaque value.
+
+     zalloc must return Z_NULL if there is not enough memory for the object.
+   If zlib is used in a multi-threaded application, zalloc and zfree must be
+   thread safe.  In that case, zlib is thread-safe.  When zalloc and zfree are
+   Z_NULL on entry to the initialization function, they are set to internal
+   routines that use the standard library functions malloc() and free().
+
+     On 16-bit systems, the functions zalloc and zfree must be able to allocate
+   exactly 65536 bytes, but will not be required to allocate more than this if
+   the symbol MAXSEG_64K is defined (see zconf.h).  WARNING: On MSDOS, pointers
+   returned by zalloc for objects of exactly 65536 bytes *must* have their
+   offset normalized to zero.  The default allocation function provided by this
+   library ensures this (see zutil.c).  To reduce memory requirements and avoid
+   any allocation of 64K objects, at the expense of compression ratio, compile
+   the library with -DMAX_WBITS=14 (see zconf.h).
+
+     The fields total_in and total_out can be used for statistics or progress
+   reports.  After compression, total_in holds the total size of the
+   uncompressed data and may be saved for use by the decompressor (particularly
+   if the decompressor wants to decompress everything in a single step).
+*/
+
+                        /* constants */
+
+#define Z_NO_FLUSH      0
+#define Z_PARTIAL_FLUSH 1
+#define Z_SYNC_FLUSH    2
+#define Z_FULL_FLUSH    3
+#define Z_FINISH        4
+#define Z_BLOCK         5
+#define Z_TREES         6
+/* Allowed flush values; see deflate() and inflate() below for details */
+
+#define Z_OK            0
+#define Z_STREAM_END    1
+#define Z_NEED_DICT     2
+#define Z_ERRNO        (-1)
+#define Z_STREAM_ERROR (-2)
+#define Z_DATA_ERROR   (-3)
+#define Z_MEM_ERROR    (-4)
+#define Z_BUF_ERROR    (-5)
+#define Z_VERSION_ERROR (-6)
+/* Return codes for the compression/decompression functions. Negative values
+ * are errors, positive values are used for special but normal events.
+ */
+
+#define Z_NO_COMPRESSION         0
+#define Z_BEST_SPEED             1
+#define Z_BEST_COMPRESSION       9
+#define Z_DEFAULT_COMPRESSION  (-1)
+/* compression levels */
+
+#define Z_FILTERED            1
+#define Z_HUFFMAN_ONLY        2
+#define Z_RLE                 3
+#define Z_FIXED               4
+#define Z_DEFAULT_STRATEGY    0
+/* compression strategy; see deflateInit2() below for details */
+
+#define Z_BINARY   0
+#define Z_TEXT     1
+#define Z_ASCII    Z_TEXT   /* for compatibility with 1.2.2 and earlier */
+#define Z_UNKNOWN  2
+/* Possible values of the data_type field for deflate() */
+
+#define Z_DEFLATED   8
+/* The deflate compression method (the only one supported in this version) */
+
+#define Z_NULL  0  /* for initializing zalloc, zfree, opaque */
+
+#define zlib_version zlibVersion()
+/* for compatibility with versions < 1.0.2 */
+
+
+                        /* basic functions */
+
+ZEXTERN const char * ZEXPORT zlibVersion OF((void));
+/* The application can compare zlibVersion and ZLIB_VERSION for consistency.
+   If the first character differs, the library code actually used is not
+   compatible with the zlib.h header file used by the application.  This check
+   is automatically made by deflateInit and inflateInit.
+ */
+
+/*
+ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
+
+     Initializes the internal stream state for compression.  The fields
+   zalloc, zfree and opaque must be initialized before by the caller.  If
+   zalloc and zfree are set to Z_NULL, deflateInit updates them to use default
+   allocation functions.
+
+     The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
+   1 gives best speed, 9 gives best compression, 0 gives no compression at all
+   (the input data is simply copied a block at a time).  Z_DEFAULT_COMPRESSION
+   requests a default compromise between speed and compression (currently
+   equivalent to level 6).
+
+     deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_STREAM_ERROR if level is not a valid compression level, or
+   Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
+   with the version assumed by the caller (ZLIB_VERSION).  msg is set to null
+   if there is no error message.  deflateInit does not perform any compression:
+   this will be done by deflate().
+*/
+
+
+ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
+/*
+    deflate compresses as much data as possible, and stops when the input
+  buffer becomes empty or the output buffer becomes full.  It may introduce
+  some output latency (reading input without producing any output) except when
+  forced to flush.
+
+    The detailed semantics are as follows.  deflate performs one or both of the
+  following actions:
+
+  - Compress more input starting at next_in and update next_in and avail_in
+    accordingly.  If not all input can be processed (because there is not
+    enough room in the output buffer), next_in and avail_in are updated and
+    processing will resume at this point for the next call of deflate().
+
+  - Generate more output starting at next_out and update next_out and avail_out
+    accordingly.  This action is forced if the parameter flush is non zero.
+    Forcing flush frequently degrades the compression ratio, so this parameter
+    should be set only when necessary.  Some output may be provided even if
+    flush is zero.
+
+    Before the call of deflate(), the application should ensure that at least
+  one of the actions is possible, by providing more input and/or consuming more
+  output, and updating avail_in or avail_out accordingly; avail_out should
+  never be zero before the call.  The application can consume the compressed
+  output when it wants, for example when the output buffer is full (avail_out
+  == 0), or after each call of deflate().  If deflate returns Z_OK and with
+  zero avail_out, it must be called again after making room in the output
+  buffer because there might be more output pending. See deflatePending(),
+  which can be used if desired to determine whether or not there is more ouput
+  in that case.
+
+    Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
+  decide how much data to accumulate before producing output, in order to
+  maximize compression.
+
+    If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
+  flushed to the output buffer and the output is aligned on a byte boundary, so
+  that the decompressor can get all input data available so far.  (In
+  particular avail_in is zero after the call if enough output space has been
+  provided before the call.) Flushing may degrade compression for some
+  compression algorithms and so it should be used only when necessary.  This
+  completes the current deflate block and follows it with an empty stored block
+  that is three bits plus filler bits to the next byte, followed by four bytes
+  (00 00 ff ff).
+
+    If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the
+  output buffer, but the output is not aligned to a byte boundary.  All of the
+  input data so far will be available to the decompressor, as for Z_SYNC_FLUSH.
+  This completes the current deflate block and follows it with an empty fixed
+  codes block that is 10 bits long.  This assures that enough bytes are output
+  in order for the decompressor to finish the block before the empty fixed
+  codes block.
+
+    If flush is set to Z_BLOCK, a deflate block is completed and emitted, as
+  for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to
+  seven bits of the current block are held to be written as the next byte after
+  the next deflate block is completed.  In this case, the decompressor may not
+  be provided enough bits at this point in order to complete decompression of
+  the data provided so far to the compressor.  It may need to wait for the next
+  block to be emitted.  This is for advanced applications that need to control
+  the emission of deflate blocks.
+
+    If flush is set to Z_FULL_FLUSH, all output is flushed as with
+  Z_SYNC_FLUSH, and the compression state is reset so that decompression can
+  restart from this point if previous compressed data has been damaged or if
+  random access is desired.  Using Z_FULL_FLUSH too often can seriously degrade
+  compression.
+
+    If deflate returns with avail_out == 0, this function must be called again
+  with the same value of the flush parameter and more output space (updated
+  avail_out), until the flush is complete (deflate returns with non-zero
+  avail_out).  In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
+  avail_out is greater than six to avoid repeated flush markers due to
+  avail_out == 0 on return.
+
+    If the parameter flush is set to Z_FINISH, pending input is processed,
+  pending output is flushed and deflate returns with Z_STREAM_END if there was
+  enough output space.  If deflate returns with Z_OK or Z_BUF_ERROR, this
+  function must be called again with Z_FINISH and more output space (updated
+  avail_out) but no more input data, until it returns with Z_STREAM_END or an
+  error.  After deflate has returned Z_STREAM_END, the only possible operations
+  on the stream are deflateReset or deflateEnd.
+
+    Z_FINISH can be used in the first deflate call after deflateInit if all the
+  compression is to be done in a single step.  In order to complete in one
+  call, avail_out must be at least the value returned by deflateBound (see
+  below).  Then deflate is guaranteed to return Z_STREAM_END.  If not enough
+  output space is provided, deflate will not return Z_STREAM_END, and it must
+  be called again as described above.
+
+    deflate() sets strm->adler to the Adler-32 checksum of all input read
+  so far (that is, total_in bytes).  If a gzip stream is being generated, then
+  strm->adler will be the CRC-32 checksum of the input read so far.  (See
+  deflateInit2 below.)
+
+    deflate() may update strm->data_type if it can make a good guess about
+  the input data type (Z_BINARY or Z_TEXT).  If in doubt, the data is
+  considered binary.  This field is only for information purposes and does not
+  affect the compression algorithm in any manner.
+
+    deflate() returns Z_OK if some progress has been made (more input
+  processed or more output produced), Z_STREAM_END if all input has been
+  consumed and all output has been produced (only when flush is set to
+  Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
+  if next_in or next_out was Z_NULL or the state was inadvertently written over
+  by the application), or Z_BUF_ERROR if no progress is possible (for example
+  avail_in or avail_out was zero).  Note that Z_BUF_ERROR is not fatal, and
+  deflate() can be called again with more input and more output space to
+  continue compressing.
+*/
+
+
+ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
+/*
+     All dynamically allocated data structures for this stream are freed.
+   This function discards any unprocessed input and does not flush any pending
+   output.
+
+     deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
+   stream state was inconsistent, Z_DATA_ERROR if the stream was freed
+   prematurely (some input or output was discarded).  In the error case, msg
+   may be set but then points to a static string (which must not be
+   deallocated).
+*/
+
+
+/*
+ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
+
+     Initializes the internal stream state for decompression.  The fields
+   next_in, avail_in, zalloc, zfree and opaque must be initialized before by
+   the caller.  In the current version of inflate, the provided input is not
+   read or consumed.  The allocation of a sliding window will be deferred to
+   the first call of inflate (if the decompression does not complete on the
+   first call).  If zalloc and zfree are set to Z_NULL, inflateInit updates
+   them to use default allocation functions.
+
+     inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
+   version assumed by the caller, or Z_STREAM_ERROR if the parameters are
+   invalid, such as a null pointer to the structure.  msg is set to null if
+   there is no error message.  inflateInit does not perform any decompression.
+   Actual decompression will be done by inflate().  So next_in, and avail_in,
+   next_out, and avail_out are unused and unchanged.  The current
+   implementation of inflateInit() does not process any header information --
+   that is deferred until inflate() is called.
+*/
+
+
+ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
+/*
+    inflate decompresses as much data as possible, and stops when the input
+  buffer becomes empty or the output buffer becomes full.  It may introduce
+  some output latency (reading input without producing any output) except when
+  forced to flush.
+
+  The detailed semantics are as follows.  inflate performs one or both of the
+  following actions:
+
+  - Decompress more input starting at next_in and update next_in and avail_in
+    accordingly.  If not all input can be processed (because there is not
+    enough room in the output buffer), then next_in and avail_in are updated
+    accordingly, and processing will resume at this point for the next call of
+    inflate().
+
+  - Generate more output starting at next_out and update next_out and avail_out
+    accordingly.  inflate() provides as much output as possible, until there is
+    no more input data or no more space in the output buffer (see below about
+    the flush parameter).
+
+    Before the call of inflate(), the application should ensure that at least
+  one of the actions is possible, by providing more input and/or consuming more
+  output, and updating the next_* and avail_* values accordingly.  If the
+  caller of inflate() does not provide both available input and available
+  output space, it is possible that there will be no progress made.  The
+  application can consume the uncompressed output when it wants, for example
+  when the output buffer is full (avail_out == 0), or after each call of
+  inflate().  If inflate returns Z_OK and with zero avail_out, it must be
+  called again after making room in the output buffer because there might be
+  more output pending.
+
+    The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH,
+  Z_BLOCK, or Z_TREES.  Z_SYNC_FLUSH requests that inflate() flush as much
+  output as possible to the output buffer.  Z_BLOCK requests that inflate()
+  stop if and when it gets to the next deflate block boundary.  When decoding
+  the zlib or gzip format, this will cause inflate() to return immediately
+  after the header and before the first block.  When doing a raw inflate,
+  inflate() will go ahead and process the first block, and will return when it
+  gets to the end of that block, or when it runs out of data.
+
+    The Z_BLOCK option assists in appending to or combining deflate streams.
+  To assist in this, on return inflate() always sets strm->data_type to the
+  number of unused bits in the last byte taken from strm->next_in, plus 64 if
+  inflate() is currently decoding the last block in the deflate stream, plus
+  128 if inflate() returned immediately after decoding an end-of-block code or
+  decoding the complete header up to just before the first byte of the deflate
+  stream.  The end-of-block will not be indicated until all of the uncompressed
+  data from that block has been written to strm->next_out.  The number of
+  unused bits may in general be greater than seven, except when bit 7 of
+  data_type is set, in which case the number of unused bits will be less than
+  eight.  data_type is set as noted here every time inflate() returns for all
+  flush options, and so can be used to determine the amount of currently
+  consumed input in bits.
+
+    The Z_TREES option behaves as Z_BLOCK does, but it also returns when the
+  end of each deflate block header is reached, before any actual data in that
+  block is decoded.  This allows the caller to determine the length of the
+  deflate block header for later use in random access within a deflate block.
+  256 is added to the value of strm->data_type when inflate() returns
+  immediately after reaching the end of the deflate block header.
+
+    inflate() should normally be called until it returns Z_STREAM_END or an
+  error.  However if all decompression is to be performed in a single step (a
+  single call of inflate), the parameter flush should be set to Z_FINISH.  In
+  this case all pending input is processed and all pending output is flushed;
+  avail_out must be large enough to hold all of the uncompressed data for the
+  operation to complete.  (The size of the uncompressed data may have been
+  saved by the compressor for this purpose.)  The use of Z_FINISH is not
+  required to perform an inflation in one step.  However it may be used to
+  inform inflate that a faster approach can be used for the single inflate()
+  call.  Z_FINISH also informs inflate to not maintain a sliding window if the
+  stream completes, which reduces inflate's memory footprint.  If the stream
+  does not complete, either because not all of the stream is provided or not
+  enough output space is provided, then a sliding window will be allocated and
+  inflate() can be called again to continue the operation as if Z_NO_FLUSH had
+  been used.
+
+     In this implementation, inflate() always flushes as much output as
+  possible to the output buffer, and always uses the faster approach on the
+  first call.  So the effects of the flush parameter in this implementation are
+  on the return value of inflate() as noted below, when inflate() returns early
+  when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of
+  memory for a sliding window when Z_FINISH is used.
+
+     If a preset dictionary is needed after this call (see inflateSetDictionary
+  below), inflate sets strm->adler to the Adler-32 checksum of the dictionary
+  chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
+  strm->adler to the Adler-32 checksum of all output produced so far (that is,
+  total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
+  below.  At the end of the stream, inflate() checks that its computed Adler-32
+  checksum is equal to that saved by the compressor and returns Z_STREAM_END
+  only if the checksum is correct.
+
+    inflate() can decompress and check either zlib-wrapped or gzip-wrapped
+  deflate data.  The header type is detected automatically, if requested when
+  initializing with inflateInit2().  Any information contained in the gzip
+  header is not retained unless inflateGetHeader() is used.  When processing
+  gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output
+  produced so far.  The CRC-32 is checked against the gzip trailer, as is the
+  uncompressed length, modulo 2^32.
+
+    inflate() returns Z_OK if some progress has been made (more input processed
+  or more output produced), Z_STREAM_END if the end of the compressed data has
+  been reached and all uncompressed output has been produced, Z_NEED_DICT if a
+  preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
+  corrupted (input stream not conforming to the zlib format or incorrect check
+  value, in which case strm->msg points to a string with a more specific
+  error), Z_STREAM_ERROR if the stream structure was inconsistent (for example
+  next_in or next_out was Z_NULL, or the state was inadvertently written over
+  by the application), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR
+  if no progress was possible or if there was not enough room in the output
+  buffer when Z_FINISH is used.  Note that Z_BUF_ERROR is not fatal, and
+  inflate() can be called again with more input and more output space to
+  continue decompressing.  If Z_DATA_ERROR is returned, the application may
+  then call inflateSync() to look for a good compression block if a partial
+  recovery of the data is to be attempted.
+*/
+
+
+ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
+/*
+     All dynamically allocated data structures for this stream are freed.
+   This function discards any unprocessed input and does not flush any pending
+   output.
+
+     inflateEnd returns Z_OK if success, or Z_STREAM_ERROR if the stream state
+   was inconsistent.
+*/
+
+
+                        /* Advanced functions */
+
+/*
+    The following functions are needed only in some special applications.
+*/
+
+/*
+ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
+                                     int  level,
+                                     int  method,
+                                     int  windowBits,
+                                     int  memLevel,
+                                     int  strategy));
+
+     This is another version of deflateInit with more compression options.  The
+   fields next_in, zalloc, zfree and opaque must be initialized before by the
+   caller.
+
+     The method parameter is the compression method.  It must be Z_DEFLATED in
+   this version of the library.
+
+     The windowBits parameter is the base two logarithm of the window size
+   (the size of the history buffer).  It should be in the range 8..15 for this
+   version of the library.  Larger values of this parameter result in better
+   compression at the expense of memory usage.  The default value is 15 if
+   deflateInit is used instead.
+
+     For the current implementation of deflate(), a windowBits value of 8 (a
+   window size of 256 bytes) is not supported.  As a result, a request for 8
+   will result in 9 (a 512-byte window).  In that case, providing 8 to
+   inflateInit2() will result in an error when the zlib header with 9 is
+   checked against the initialization of inflate().  The remedy is to not use 8
+   with deflateInit2() with this initialization, or at least in that case use 9
+   with inflateInit2().
+
+     windowBits can also be -8..-15 for raw deflate.  In this case, -windowBits
+   determines the window size.  deflate() will then generate raw deflate data
+   with no zlib header or trailer, and will not compute a check value.
+
+     windowBits can also be greater than 15 for optional gzip encoding.  Add
+   16 to windowBits to write a simple gzip header and trailer around the
+   compressed data instead of a zlib wrapper.  The gzip header will have no
+   file name, no extra data, no comment, no modification time (set to zero), no
+   header crc, and the operating system will be set to the appropriate value,
+   if the operating system was determined at compile time.  If a gzip stream is
+   being written, strm->adler is a CRC-32 instead of an Adler-32.
+
+     For raw deflate or gzip encoding, a request for a 256-byte window is
+   rejected as invalid, since only the zlib header provides a means of
+   transmitting the window size to the decompressor.
+
+     The memLevel parameter specifies how much memory should be allocated
+   for the internal compression state.  memLevel=1 uses minimum memory but is
+   slow and reduces compression ratio; memLevel=9 uses maximum memory for
+   optimal speed.  The default value is 8.  See zconf.h for total memory usage
+   as a function of windowBits and memLevel.
+
+     The strategy parameter is used to tune the compression algorithm.  Use the
+   value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
+   filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
+   string match), or Z_RLE to limit match distances to one (run-length
+   encoding).  Filtered data consists mostly of small values with a somewhat
+   random distribution.  In this case, the compression algorithm is tuned to
+   compress them better.  The effect of Z_FILTERED is to force more Huffman
+   coding and less string matching; it is somewhat intermediate between
+   Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY.  Z_RLE is designed to be almost as
+   fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data.  The
+   strategy parameter only affects the compression ratio but not the
+   correctness of the compressed output even if it is not set appropriately.
+   Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler
+   decoder for special applications.
+
+     deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid
+   method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is
+   incompatible with the version assumed by the caller (ZLIB_VERSION).  msg is
+   set to null if there is no error message.  deflateInit2 does not perform any
+   compression: this will be done by deflate().
+*/
+
+ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
+                                             const Bytef *dictionary,
+                                             uInt  dictLength));
+/*
+     Initializes the compression dictionary from the given byte sequence
+   without producing any compressed output.  When using the zlib format, this
+   function must be called immediately after deflateInit, deflateInit2 or
+   deflateReset, and before any call of deflate.  When doing raw deflate, this
+   function must be called either before any call of deflate, or immediately
+   after the completion of a deflate block, i.e. after all input has been
+   consumed and all output has been delivered when using any of the flush
+   options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH.  The
+   compressor and decompressor must use exactly the same dictionary (see
+   inflateSetDictionary).
+
+     The dictionary should consist of strings (byte sequences) that are likely
+   to be encountered later in the data to be compressed, with the most commonly
+   used strings preferably put towards the end of the dictionary.  Using a
+   dictionary is most useful when the data to be compressed is short and can be
+   predicted with good accuracy; the data can then be compressed better than
+   with the default empty dictionary.
+
+     Depending on the size of the compression data structures selected by
+   deflateInit or deflateInit2, a part of the dictionary may in effect be
+   discarded, for example if the dictionary is larger than the window size
+   provided in deflateInit or deflateInit2.  Thus the strings most likely to be
+   useful should be put at the end of the dictionary, not at the front.  In
+   addition, the current implementation of deflate will use at most the window
+   size minus 262 bytes of the provided dictionary.
+
+     Upon return of this function, strm->adler is set to the Adler-32 value
+   of the dictionary; the decompressor may later use this value to determine
+   which dictionary has been used by the compressor.  (The Adler-32 value
+   applies to the whole dictionary even if only a subset of the dictionary is
+   actually used by the compressor.) If a raw deflate was requested, then the
+   Adler-32 value is not computed and strm->adler is not set.
+
+     deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
+   parameter is invalid (e.g.  dictionary being Z_NULL) or the stream state is
+   inconsistent (for example if deflate has already been called for this stream
+   or if not at a block boundary for raw deflate).  deflateSetDictionary does
+   not perform any compression: this will be done by deflate().
+*/
+
+ZEXTERN int ZEXPORT deflateGetDictionary OF((z_streamp strm,
+                                             Bytef *dictionary,
+                                             uInt  *dictLength));
+/*
+     Returns the sliding dictionary being maintained by deflate.  dictLength is
+   set to the number of bytes in the dictionary, and that many bytes are copied
+   to dictionary.  dictionary must have enough space, where 32768 bytes is
+   always enough.  If deflateGetDictionary() is called with dictionary equal to
+   Z_NULL, then only the dictionary length is returned, and nothing is copied.
+   Similary, if dictLength is Z_NULL, then it is not set.
+
+     deflateGetDictionary() may return a length less than the window size, even
+   when more than the window size in input has been provided. It may return up
+   to 258 bytes less in that case, due to how zlib's implementation of deflate
+   manages the sliding window and lookahead for matches, where matches can be
+   up to 258 bytes long. If the application needs the last window-size bytes of
+   input, then that would need to be saved by the application outside of zlib.
+
+     deflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the
+   stream state is inconsistent.
+*/
+
+ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
+                                    z_streamp source));
+/*
+     Sets the destination stream as a complete copy of the source stream.
+
+     This function can be useful when several compression strategies will be
+   tried, for example when there are several ways of pre-processing the input
+   data with a filter.  The streams that will be discarded should then be freed
+   by calling deflateEnd.  Note that deflateCopy duplicates the internal
+   compression state which can be quite large, so this strategy is slow and can
+   consume lots of memory.
+
+     deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
+   enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
+   (such as zalloc being Z_NULL).  msg is left unchanged in both source and
+   destination.
+*/
+
+ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
+/*
+     This function is equivalent to deflateEnd followed by deflateInit, but
+   does not free and reallocate the internal compression state.  The stream
+   will leave the compression level and any other attributes that may have been
+   set unchanged.
+
+     deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent (such as zalloc or state being Z_NULL).
+*/
+
+ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
+                                      int level,
+                                      int strategy));
+/*
+     Dynamically update the compression level and compression strategy.  The
+   interpretation of level and strategy is as in deflateInit2().  This can be
+   used to switch between compression and straight copy of the input data, or
+   to switch to a different kind of input data requiring a different strategy.
+   If the compression approach (which is a function of the level) or the
+   strategy is changed, and if any input has been consumed in a previous
+   deflate() call, then the input available so far is compressed with the old
+   level and strategy using deflate(strm, Z_BLOCK).  There are three approaches
+   for the compression levels 0, 1..3, and 4..9 respectively.  The new level
+   and strategy will take effect at the next call of deflate().
+
+     If a deflate(strm, Z_BLOCK) is performed by deflateParams(), and it does
+   not have enough output space to complete, then the parameter change will not
+   take effect.  In this case, deflateParams() can be called again with the
+   same parameters and more output space to try again.
+
+     In order to assure a change in the parameters on the first try, the
+   deflate stream should be flushed using deflate() with Z_BLOCK or other flush
+   request until strm.avail_out is not zero, before calling deflateParams().
+   Then no more input data should be provided before the deflateParams() call.
+   If this is done, the old level and strategy will be applied to the data
+   compressed before deflateParams(), and the new level and strategy will be
+   applied to the the data compressed after deflateParams().
+
+     deflateParams returns Z_OK on success, Z_STREAM_ERROR if the source stream
+   state was inconsistent or if a parameter was invalid, or Z_BUF_ERROR if
+   there was not enough output space to complete the compression of the
+   available input data before a change in the strategy or approach.  Note that
+   in the case of a Z_BUF_ERROR, the parameters are not changed.  A return
+   value of Z_BUF_ERROR is not fatal, in which case deflateParams() can be
+   retried with more output space.
+*/
+
+ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
+                                    int good_length,
+                                    int max_lazy,
+                                    int nice_length,
+                                    int max_chain));
+/*
+     Fine tune deflate's internal compression parameters.  This should only be
+   used by someone who understands the algorithm used by zlib's deflate for
+   searching for the best matching string, and even then only by the most
+   fanatic optimizer trying to squeeze out the last compressed bit for their
+   specific input data.  Read the deflate.c source code for the meaning of the
+   max_lazy, good_length, nice_length, and max_chain parameters.
+
+     deflateTune() can be called after deflateInit() or deflateInit2(), and
+   returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
+ */
+
+ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
+                                       uLong sourceLen));
+/*
+     deflateBound() returns an upper bound on the compressed size after
+   deflation of sourceLen bytes.  It must be called after deflateInit() or
+   deflateInit2(), and after deflateSetHeader(), if used.  This would be used
+   to allocate an output buffer for deflation in a single pass, and so would be
+   called before deflate().  If that first deflate() call is provided the
+   sourceLen input bytes, an output buffer allocated to the size returned by
+   deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed
+   to return Z_STREAM_END.  Note that it is possible for the compressed size to
+   be larger than the value returned by deflateBound() if flush options other
+   than Z_FINISH or Z_NO_FLUSH are used.
+*/
+
+ZEXTERN int ZEXPORT deflatePending OF((z_streamp strm,
+                                       unsigned *pending,
+                                       int *bits));
+/*
+     deflatePending() returns the number of bytes and bits of output that have
+   been generated, but not yet provided in the available output.  The bytes not
+   provided would be due to the available output space having being consumed.
+   The number of bits of output not provided are between 0 and 7, where they
+   await more bits to join them in order to fill out a full byte.  If pending
+   or bits are Z_NULL, then those values are not set.
+
+     deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent.
+ */
+
+ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
+                                     int bits,
+                                     int value));
+/*
+     deflatePrime() inserts bits in the deflate output stream.  The intent
+   is that this function is used to start off the deflate output with the bits
+   leftover from a previous deflate stream when appending to it.  As such, this
+   function can only be used for raw deflate, and must be used before the first
+   deflate() call after a deflateInit2() or deflateReset().  bits must be less
+   than or equal to 16, and that many of the least significant bits of value
+   will be inserted in the output.
+
+     deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough
+   room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the
+   source stream state was inconsistent.
+*/
+
+ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
+                                         gz_headerp head));
+/*
+     deflateSetHeader() provides gzip header information for when a gzip
+   stream is requested by deflateInit2().  deflateSetHeader() may be called
+   after deflateInit2() or deflateReset() and before the first call of
+   deflate().  The text, time, os, extra field, name, and comment information
+   in the provided gz_header structure are written to the gzip header (xflag is
+   ignored -- the extra flags are set according to the compression level).  The
+   caller must assure that, if not Z_NULL, name and comment are terminated with
+   a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
+   available there.  If hcrc is true, a gzip header crc is included.  Note that
+   the current versions of the command-line version of gzip (up through version
+   1.3.x) do not support header crc's, and will report that it is a "multi-part
+   gzip file" and give up.
+
+     If deflateSetHeader is not used, the default gzip header has text false,
+   the time set to zero, and os set to 255, with no extra, name, or comment
+   fields.  The gzip header is returned to the default state by deflateReset().
+
+     deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent.
+*/
+
+/*
+ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
+                                     int  windowBits));
+
+     This is another version of inflateInit with an extra parameter.  The
+   fields next_in, avail_in, zalloc, zfree and opaque must be initialized
+   before by the caller.
+
+     The windowBits parameter is the base two logarithm of the maximum window
+   size (the size of the history buffer).  It should be in the range 8..15 for
+   this version of the library.  The default value is 15 if inflateInit is used
+   instead.  windowBits must be greater than or equal to the windowBits value
+   provided to deflateInit2() while compressing, or it must be equal to 15 if
+   deflateInit2() was not used.  If a compressed stream with a larger window
+   size is given as input, inflate() will return with the error code
+   Z_DATA_ERROR instead of trying to allocate a larger window.
+
+     windowBits can also be zero to request that inflate use the window size in
+   the zlib header of the compressed stream.
+
+     windowBits can also be -8..-15 for raw inflate.  In this case, -windowBits
+   determines the window size.  inflate() will then process raw deflate data,
+   not looking for a zlib or gzip header, not generating a check value, and not
+   looking for any check values for comparison at the end of the stream.  This
+   is for use with other formats that use the deflate compressed data format
+   such as zip.  Those formats provide their own check values.  If a custom
+   format is developed using the raw deflate format for compressed data, it is
+   recommended that a check value such as an Adler-32 or a CRC-32 be applied to
+   the uncompressed data as is done in the zlib, gzip, and zip formats.  For
+   most applications, the zlib format should be used as is.  Note that comments
+   above on the use in deflateInit2() applies to the magnitude of windowBits.
+
+     windowBits can also be greater than 15 for optional gzip decoding.  Add
+   32 to windowBits to enable zlib and gzip decoding with automatic header
+   detection, or add 16 to decode only the gzip format (the zlib format will
+   return a Z_DATA_ERROR).  If a gzip stream is being decoded, strm->adler is a
+   CRC-32 instead of an Adler-32.  Unlike the gunzip utility and gzread() (see
+   below), inflate() will not automatically decode concatenated gzip streams.
+   inflate() will return Z_STREAM_END at the end of the gzip stream.  The state
+   would need to be reset to continue decoding a subsequent gzip stream.
+
+     inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
+   version assumed by the caller, or Z_STREAM_ERROR if the parameters are
+   invalid, such as a null pointer to the structure.  msg is set to null if
+   there is no error message.  inflateInit2 does not perform any decompression
+   apart from possibly reading the zlib header if present: actual decompression
+   will be done by inflate().  (So next_in and avail_in may be modified, but
+   next_out and avail_out are unused and unchanged.) The current implementation
+   of inflateInit2() does not process any header information -- that is
+   deferred until inflate() is called.
+*/
+
+ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
+                                             const Bytef *dictionary,
+                                             uInt  dictLength));
+/*
+     Initializes the decompression dictionary from the given uncompressed byte
+   sequence.  This function must be called immediately after a call of inflate,
+   if that call returned Z_NEED_DICT.  The dictionary chosen by the compressor
+   can be determined from the Adler-32 value returned by that call of inflate.
+   The compressor and decompressor must use exactly the same dictionary (see
+   deflateSetDictionary).  For raw inflate, this function can be called at any
+   time to set the dictionary.  If the provided dictionary is smaller than the
+   window and there is already data in the window, then the provided dictionary
+   will amend what's there.  The application must insure that the dictionary
+   that was used for compression is provided.
+
+     inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
+   parameter is invalid (e.g.  dictionary being Z_NULL) or the stream state is
+   inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
+   expected one (incorrect Adler-32 value).  inflateSetDictionary does not
+   perform any decompression: this will be done by subsequent calls of
+   inflate().
+*/
+
+ZEXTERN int ZEXPORT inflateGetDictionary OF((z_streamp strm,
+                                             Bytef *dictionary,
+                                             uInt  *dictLength));
+/*
+     Returns the sliding dictionary being maintained by inflate.  dictLength is
+   set to the number of bytes in the dictionary, and that many bytes are copied
+   to dictionary.  dictionary must have enough space, where 32768 bytes is
+   always enough.  If inflateGetDictionary() is called with dictionary equal to
+   Z_NULL, then only the dictionary length is returned, and nothing is copied.
+   Similary, if dictLength is Z_NULL, then it is not set.
+
+     inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the
+   stream state is inconsistent.
+*/
+
+ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
+/*
+     Skips invalid compressed data until a possible full flush point (see above
+   for the description of deflate with Z_FULL_FLUSH) can be found, or until all
+   available input is skipped.  No output is provided.
+
+     inflateSync searches for a 00 00 FF FF pattern in the compressed data.
+   All full flush points have this pattern, but not all occurrences of this
+   pattern are full flush points.
+
+     inflateSync returns Z_OK if a possible full flush point has been found,
+   Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point
+   has been found, or Z_STREAM_ERROR if the stream structure was inconsistent.
+   In the success case, the application may save the current current value of
+   total_in which indicates where valid compressed data was found.  In the
+   error case, the application may repeatedly call inflateSync, providing more
+   input each time, until success or end of the input data.
+*/
+
+ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
+                                    z_streamp source));
+/*
+     Sets the destination stream as a complete copy of the source stream.
+
+     This function can be useful when randomly accessing a large stream.  The
+   first pass through the stream can periodically record the inflate state,
+   allowing restarting inflate at those points when randomly accessing the
+   stream.
+
+     inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
+   enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
+   (such as zalloc being Z_NULL).  msg is left unchanged in both source and
+   destination.
+*/
+
+ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
+/*
+     This function is equivalent to inflateEnd followed by inflateInit,
+   but does not free and reallocate the internal decompression state.  The
+   stream will keep attributes that may have been set by inflateInit2.
+
+     inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent (such as zalloc or state being Z_NULL).
+*/
+
+ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm,
+                                      int windowBits));
+/*
+     This function is the same as inflateReset, but it also permits changing
+   the wrap and window size requests.  The windowBits parameter is interpreted
+   the same as it is for inflateInit2.  If the window size is changed, then the
+   memory allocated for the window is freed, and the window will be reallocated
+   by inflate() if needed.
+
+     inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent (such as zalloc or state being Z_NULL), or if
+   the windowBits parameter is invalid.
+*/
+
+ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
+                                     int bits,
+                                     int value));
+/*
+     This function inserts bits in the inflate input stream.  The intent is
+   that this function is used to start inflating at a bit position in the
+   middle of a byte.  The provided bits will be used before any bytes are used
+   from next_in.  This function should only be used with raw inflate, and
+   should be used before the first inflate() call after inflateInit2() or
+   inflateReset().  bits must be less than or equal to 16, and that many of the
+   least significant bits of value will be inserted in the input.
+
+     If bits is negative, then the input stream bit buffer is emptied.  Then
+   inflatePrime() can be called again to put bits in the buffer.  This is used
+   to clear out bits leftover after feeding inflate a block description prior
+   to feeding inflate codes.
+
+     inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent.
+*/
+
+ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm));
+/*
+     This function returns two values, one in the lower 16 bits of the return
+   value, and the other in the remaining upper bits, obtained by shifting the
+   return value down 16 bits.  If the upper value is -1 and the lower value is
+   zero, then inflate() is currently decoding information outside of a block.
+   If the upper value is -1 and the lower value is non-zero, then inflate is in
+   the middle of a stored block, with the lower value equaling the number of
+   bytes from the input remaining to copy.  If the upper value is not -1, then
+   it is the number of bits back from the current bit position in the input of
+   the code (literal or length/distance pair) currently being processed.  In
+   that case the lower value is the number of bytes already emitted for that
+   code.
+
+     A code is being processed if inflate is waiting for more input to complete
+   decoding of the code, or if it has completed decoding but is waiting for
+   more output space to write the literal or match data.
+
+     inflateMark() is used to mark locations in the input data for random
+   access, which may be at bit positions, and to note those cases where the
+   output of a code may span boundaries of random access blocks.  The current
+   location in the input stream can be determined from avail_in and data_type
+   as noted in the description for the Z_BLOCK flush parameter for inflate.
+
+     inflateMark returns the value noted above, or -65536 if the provided
+   source stream state was inconsistent.
+*/
+
+ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
+                                         gz_headerp head));
+/*
+     inflateGetHeader() requests that gzip header information be stored in the
+   provided gz_header structure.  inflateGetHeader() may be called after
+   inflateInit2() or inflateReset(), and before the first call of inflate().
+   As inflate() processes the gzip stream, head->done is zero until the header
+   is completed, at which time head->done is set to one.  If a zlib stream is
+   being decoded, then head->done is set to -1 to indicate that there will be
+   no gzip header information forthcoming.  Note that Z_BLOCK or Z_TREES can be
+   used to force inflate() to return immediately after header processing is
+   complete and before any actual data is decompressed.
+
+     The text, time, xflags, and os fields are filled in with the gzip header
+   contents.  hcrc is set to true if there is a header CRC.  (The header CRC
+   was valid if done is set to one.) If extra is not Z_NULL, then extra_max
+   contains the maximum number of bytes to write to extra.  Once done is true,
+   extra_len contains the actual extra field length, and extra contains the
+   extra field, or that field truncated if extra_max is less than extra_len.
+   If name is not Z_NULL, then up to name_max characters are written there,
+   terminated with a zero unless the length is greater than name_max.  If
+   comment is not Z_NULL, then up to comm_max characters are written there,
+   terminated with a zero unless the length is greater than comm_max.  When any
+   of extra, name, or comment are not Z_NULL and the respective field is not
+   present in the header, then that field is set to Z_NULL to signal its
+   absence.  This allows the use of deflateSetHeader() with the returned
+   structure to duplicate the header.  However if those fields are set to
+   allocated memory, then the application will need to save those pointers
+   elsewhere so that they can be eventually freed.
+
+     If inflateGetHeader is not used, then the header information is simply
+   discarded.  The header is always checked for validity, including the header
+   CRC if present.  inflateReset() will reset the process to discard the header
+   information.  The application would need to call inflateGetHeader() again to
+   retrieve the header from the next gzip stream.
+
+     inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent.
+*/
+
+/*
+ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
+                                        unsigned char FAR *window));
+
+     Initialize the internal stream state for decompression using inflateBack()
+   calls.  The fields zalloc, zfree and opaque in strm must be initialized
+   before the call.  If zalloc and zfree are Z_NULL, then the default library-
+   derived memory allocation routines are used.  windowBits is the base two
+   logarithm of the window size, in the range 8..15.  window is a caller
+   supplied buffer of that size.  Except for special applications where it is
+   assured that deflate was used with small window sizes, windowBits must be 15
+   and a 32K byte window must be supplied to be able to decompress general
+   deflate streams.
+
+     See inflateBack() for the usage of these routines.
+
+     inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
+   the parameters are invalid, Z_MEM_ERROR if the internal state could not be
+   allocated, or Z_VERSION_ERROR if the version of the library does not match
+   the version of the header file.
+*/
+
+typedef unsigned (*in_func) OF((void FAR *,
+                                z_const unsigned char FAR * FAR *));
+typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
+
+ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
+                                    in_func in, void FAR *in_desc,
+                                    out_func out, void FAR *out_desc));
+/*
+     inflateBack() does a raw inflate with a single call using a call-back
+   interface for input and output.  This is potentially more efficient than
+   inflate() for file i/o applications, in that it avoids copying between the
+   output and the sliding window by simply making the window itself the output
+   buffer.  inflate() can be faster on modern CPUs when used with large
+   buffers.  inflateBack() trusts the application to not change the output
+   buffer passed by the output function, at least until inflateBack() returns.
+
+     inflateBackInit() must be called first to allocate the internal state
+   and to initialize the state with the user-provided window buffer.
+   inflateBack() may then be used multiple times to inflate a complete, raw
+   deflate stream with each call.  inflateBackEnd() is then called to free the
+   allocated state.
+
+     A raw deflate stream is one with no zlib or gzip header or trailer.
+   This routine would normally be used in a utility that reads zip or gzip
+   files and writes out uncompressed files.  The utility would decode the
+   header and process the trailer on its own, hence this routine expects only
+   the raw deflate stream to decompress.  This is different from the default
+   behavior of inflate(), which expects a zlib header and trailer around the
+   deflate stream.
+
+     inflateBack() uses two subroutines supplied by the caller that are then
+   called by inflateBack() for input and output.  inflateBack() calls those
+   routines until it reads a complete deflate stream and writes out all of the
+   uncompressed data, or until it encounters an error.  The function's
+   parameters and return types are defined above in the in_func and out_func
+   typedefs.  inflateBack() will call in(in_desc, &buf) which should return the
+   number of bytes of provided input, and a pointer to that input in buf.  If
+   there is no input available, in() must return zero -- buf is ignored in that
+   case -- and inflateBack() will return a buffer error.  inflateBack() will
+   call out(out_desc, buf, len) to write the uncompressed data buf[0..len-1].
+   out() should return zero on success, or non-zero on failure.  If out()
+   returns non-zero, inflateBack() will return with an error.  Neither in() nor
+   out() are permitted to change the contents of the window provided to
+   inflateBackInit(), which is also the buffer that out() uses to write from.
+   The length written by out() will be at most the window size.  Any non-zero
+   amount of input may be provided by in().
+
+     For convenience, inflateBack() can be provided input on the first call by
+   setting strm->next_in and strm->avail_in.  If that input is exhausted, then
+   in() will be called.  Therefore strm->next_in must be initialized before
+   calling inflateBack().  If strm->next_in is Z_NULL, then in() will be called
+   immediately for input.  If strm->next_in is not Z_NULL, then strm->avail_in
+   must also be initialized, and then if strm->avail_in is not zero, input will
+   initially be taken from strm->next_in[0 ..  strm->avail_in - 1].
+
+     The in_desc and out_desc parameters of inflateBack() is passed as the
+   first parameter of in() and out() respectively when they are called.  These
+   descriptors can be optionally used to pass any information that the caller-
+   supplied in() and out() functions need to do their job.
+
+     On return, inflateBack() will set strm->next_in and strm->avail_in to
+   pass back any unused input that was provided by the last in() call.  The
+   return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
+   if in() or out() returned an error, Z_DATA_ERROR if there was a format error
+   in the deflate stream (in which case strm->msg is set to indicate the nature
+   of the error), or Z_STREAM_ERROR if the stream was not properly initialized.
+   In the case of Z_BUF_ERROR, an input or output error can be distinguished
+   using strm->next_in which will be Z_NULL only if in() returned an error.  If
+   strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning
+   non-zero.  (in() will always be called before out(), so strm->next_in is
+   assured to be defined if out() returns non-zero.)  Note that inflateBack()
+   cannot return Z_OK.
+*/
+
+ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
+/*
+     All memory allocated by inflateBackInit() is freed.
+
+     inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
+   state was inconsistent.
+*/
+
+ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
+/* Return flags indicating compile-time options.
+
+    Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
+     1.0: size of uInt
+     3.2: size of uLong
+     5.4: size of voidpf (pointer)
+     7.6: size of z_off_t
+
+    Compiler, assembler, and debug options:
+     8: ZLIB_DEBUG
+     9: ASMV or ASMINF -- use ASM code
+     10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
+     11: 0 (reserved)
+
+    One-time table building (smaller code, but not thread-safe if true):
+     12: BUILDFIXED -- build static block decoding tables when needed
+     13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
+     14,15: 0 (reserved)
+
+    Library content (indicates missing functionality):
+     16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
+                          deflate code when not needed)
+     17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
+                    and decode gzip streams (to avoid linking crc code)
+     18-19: 0 (reserved)
+
+    Operation variations (changes in library functionality):
+     20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
+     21: FASTEST -- deflate algorithm with only one, lowest compression level
+     22,23: 0 (reserved)
+
+    The sprintf variant used by gzprintf (zero is best):
+     24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
+     25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
+     26: 0 = returns value, 1 = void -- 1 means inferred string length returned
+
+    Remainder:
+     27-31: 0 (reserved)
+ */
+
+#ifndef Z_SOLO
+
+                        /* utility functions */
+
+/*
+     The following utility functions are implemented on top of the basic
+   stream-oriented functions.  To simplify the interface, some default options
+   are assumed (compression level and memory usage, standard memory allocation
+   functions).  The source code of these utility functions can be modified if
+   you need special options.
+*/
+
+ZEXTERN int ZEXPORT compress OF((Bytef *dest,   uLongf *destLen,
+                                 const Bytef *source, uLong sourceLen));
+/*
+     Compresses the source buffer into the destination buffer.  sourceLen is
+   the byte length of the source buffer.  Upon entry, destLen is the total size
+   of the destination buffer, which must be at least the value returned by
+   compressBound(sourceLen).  Upon exit, destLen is the actual size of the
+   compressed data.  compress() is equivalent to compress2() with a level
+   parameter of Z_DEFAULT_COMPRESSION.
+
+     compress returns Z_OK if success, Z_MEM_ERROR if there was not
+   enough memory, Z_BUF_ERROR if there was not enough room in the output
+   buffer.
+*/
+
+ZEXTERN int ZEXPORT compress2 OF((Bytef *dest,   uLongf *destLen,
+                                  const Bytef *source, uLong sourceLen,
+                                  int level));
+/*
+     Compresses the source buffer into the destination buffer.  The level
+   parameter has the same meaning as in deflateInit.  sourceLen is the byte
+   length of the source buffer.  Upon entry, destLen is the total size of the
+   destination buffer, which must be at least the value returned by
+   compressBound(sourceLen).  Upon exit, destLen is the actual size of the
+   compressed data.
+
+     compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_BUF_ERROR if there was not enough room in the output buffer,
+   Z_STREAM_ERROR if the level parameter is invalid.
+*/
+
+ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
+/*
+     compressBound() returns an upper bound on the compressed size after
+   compress() or compress2() on sourceLen bytes.  It would be used before a
+   compress() or compress2() call to allocate the destination buffer.
+*/
+
+ZEXTERN int ZEXPORT uncompress OF((Bytef *dest,   uLongf *destLen,
+                                   const Bytef *source, uLong sourceLen));
+/*
+     Decompresses the source buffer into the destination buffer.  sourceLen is
+   the byte length of the source buffer.  Upon entry, destLen is the total size
+   of the destination buffer, which must be large enough to hold the entire
+   uncompressed data.  (The size of the uncompressed data must have been saved
+   previously by the compressor and transmitted to the decompressor by some
+   mechanism outside the scope of this compression library.) Upon exit, destLen
+   is the actual size of the uncompressed data.
+
+     uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
+   enough memory, Z_BUF_ERROR if there was not enough room in the output
+   buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.  In
+   the case where there is not enough room, uncompress() will fill the output
+   buffer with the uncompressed data up to that point.
+*/
+
+ZEXTERN int ZEXPORT uncompress2 OF((Bytef *dest,   uLongf *destLen,
+                                    const Bytef *source, uLong *sourceLen));
+/*
+     Same as uncompress, except that sourceLen is a pointer, where the
+   length of the source is *sourceLen.  On return, *sourceLen is the number of
+   source bytes consumed.
+*/
+
+                        /* gzip file access functions */
+
+/*
+     This library supports reading and writing files in gzip (.gz) format with
+   an interface similar to that of stdio, using the functions that start with
+   "gz".  The gzip format is different from the zlib format.  gzip is a gzip
+   wrapper, documented in RFC 1952, wrapped around a deflate stream.
+*/
+
+typedef struct gzFile_s *gzFile;    /* semi-opaque gzip file descriptor */
+
+/*
+ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
+
+     Opens a gzip (.gz) file for reading or writing.  The mode parameter is as
+   in fopen ("rb" or "wb") but can also include a compression level ("wb9") or
+   a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only
+   compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F'
+   for fixed code compression as in "wb9F".  (See the description of
+   deflateInit2 for more information about the strategy parameter.)  'T' will
+   request transparent writing or appending with no compression and not using
+   the gzip format.
+
+     "a" can be used instead of "w" to request that the gzip stream that will
+   be written be appended to the file.  "+" will result in an error, since
+   reading and writing to the same gzip file is not supported.  The addition of
+   "x" when writing will create the file exclusively, which fails if the file
+   already exists.  On systems that support it, the addition of "e" when
+   reading or writing will set the flag to close the file on an execve() call.
+
+     These functions, as well as gzip, will read and decode a sequence of gzip
+   streams in a file.  The append function of gzopen() can be used to create
+   such a file.  (Also see gzflush() for another way to do this.)  When
+   appending, gzopen does not test whether the file begins with a gzip stream,
+   nor does it look for the end of the gzip streams to begin appending.  gzopen
+   will simply append a gzip stream to the existing file.
+
+     gzopen can be used to read a file which is not in gzip format; in this
+   case gzread will directly read from the file without decompression.  When
+   reading, this will be detected automatically by looking for the magic two-
+   byte gzip header.
+
+     gzopen returns NULL if the file could not be opened, if there was
+   insufficient memory to allocate the gzFile state, or if an invalid mode was
+   specified (an 'r', 'w', or 'a' was not provided, or '+' was provided).
+   errno can be checked to determine if the reason gzopen failed was that the
+   file could not be opened.
+*/
+
+ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
+/*
+     gzdopen associates a gzFile with the file descriptor fd.  File descriptors
+   are obtained from calls like open, dup, creat, pipe or fileno (if the file
+   has been previously opened with fopen).  The mode parameter is as in gzopen.
+
+     The next call of gzclose on the returned gzFile will also close the file
+   descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor
+   fd.  If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd,
+   mode);.  The duplicated descriptor should be saved to avoid a leak, since
+   gzdopen does not close fd if it fails.  If you are using fileno() to get the
+   file descriptor from a FILE *, then you will have to use dup() to avoid
+   double-close()ing the file descriptor.  Both gzclose() and fclose() will
+   close the associated file descriptor, so they need to have different file
+   descriptors.
+
+     gzdopen returns NULL if there was insufficient memory to allocate the
+   gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not
+   provided, or '+' was provided), or if fd is -1.  The file descriptor is not
+   used until the next gz* read, write, seek, or close operation, so gzdopen
+   will not detect if fd is invalid (unless fd is -1).
+*/
+
+ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size));
+/*
+     Set the internal buffer size used by this library's functions.  The
+   default buffer size is 8192 bytes.  This function must be called after
+   gzopen() or gzdopen(), and before any other calls that read or write the
+   file.  The buffer memory allocation is always deferred to the first read or
+   write.  Three times that size in buffer space is allocated.  A larger buffer
+   size of, for example, 64K or 128K bytes will noticeably increase the speed
+   of decompression (reading).
+
+     The new buffer size also affects the maximum length for gzprintf().
+
+     gzbuffer() returns 0 on success, or -1 on failure, such as being called
+   too late.
+*/
+
+ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
+/*
+     Dynamically update the compression level or strategy.  See the description
+   of deflateInit2 for the meaning of these parameters.  Previously provided
+   data is flushed before the parameter change.
+
+     gzsetparams returns Z_OK if success, Z_STREAM_ERROR if the file was not
+   opened for writing, Z_ERRNO if there is an error writing the flushed data,
+   or Z_MEM_ERROR if there is a memory allocation error.
+*/
+
+ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
+/*
+     Reads the given number of uncompressed bytes from the compressed file.  If
+   the input file is not in gzip format, gzread copies the given number of
+   bytes into the buffer directly from the file.
+
+     After reaching the end of a gzip stream in the input, gzread will continue
+   to read, looking for another gzip stream.  Any number of gzip streams may be
+   concatenated in the input file, and will all be decompressed by gzread().
+   If something other than a gzip stream is encountered after a gzip stream,
+   that remaining trailing garbage is ignored (and no error is returned).
+
+     gzread can be used to read a gzip file that is being concurrently written.
+   Upon reaching the end of the input, gzread will return with the available
+   data.  If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then
+   gzclearerr can be used to clear the end of file indicator in order to permit
+   gzread to be tried again.  Z_OK indicates that a gzip stream was completed
+   on the last gzread.  Z_BUF_ERROR indicates that the input file ended in the
+   middle of a gzip stream.  Note that gzread does not return -1 in the event
+   of an incomplete gzip stream.  This error is deferred until gzclose(), which
+   will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip
+   stream.  Alternatively, gzerror can be used before gzclose to detect this
+   case.
+
+     gzread returns the number of uncompressed bytes actually read, less than
+   len for end of file, or -1 for error.  If len is too large to fit in an int,
+   then nothing is read, -1 is returned, and the error state is set to
+   Z_STREAM_ERROR.
+*/
+
+ZEXTERN z_size_t ZEXPORT gzfread OF((voidp buf, z_size_t size, z_size_t nitems,
+                                     gzFile file));
+/*
+     Read up to nitems items of size size from file to buf, otherwise operating
+   as gzread() does.  This duplicates the interface of stdio's fread(), with
+   size_t request and return types.  If the library defines size_t, then
+   z_size_t is identical to size_t.  If not, then z_size_t is an unsigned
+   integer type that can contain a pointer.
+
+     gzfread() returns the number of full items read of size size, or zero if
+   the end of the file was reached and a full item could not be read, or if
+   there was an error.  gzerror() must be consulted if zero is returned in
+   order to determine if there was an error.  If the multiplication of size and
+   nitems overflows, i.e. the product does not fit in a z_size_t, then nothing
+   is read, zero is returned, and the error state is set to Z_STREAM_ERROR.
+
+     In the event that the end of file is reached and only a partial item is
+   available at the end, i.e. the remaining uncompressed data length is not a
+   multiple of size, then the final partial item is nevetheless read into buf
+   and the end-of-file flag is set.  The length of the partial item read is not
+   provided, but could be inferred from the result of gztell().  This behavior
+   is the same as the behavior of fread() implementations in common libraries,
+   but it prevents the direct use of gzfread() to read a concurrently written
+   file, reseting and retrying on end-of-file, when size is not 1.
+*/
+
+ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
+                                voidpc buf, unsigned len));
+/*
+     Writes the given number of uncompressed bytes into the compressed file.
+   gzwrite returns the number of uncompressed bytes written or 0 in case of
+   error.
+*/
+
+ZEXTERN z_size_t ZEXPORT gzfwrite OF((voidpc buf, z_size_t size,
+                                      z_size_t nitems, gzFile file));
+/*
+     gzfwrite() writes nitems items of size size from buf to file, duplicating
+   the interface of stdio's fwrite(), with size_t request and return types.  If
+   the library defines size_t, then z_size_t is identical to size_t.  If not,
+   then z_size_t is an unsigned integer type that can contain a pointer.
+
+     gzfwrite() returns the number of full items written of size size, or zero
+   if there was an error.  If the multiplication of size and nitems overflows,
+   i.e. the product does not fit in a z_size_t, then nothing is written, zero
+   is returned, and the error state is set to Z_STREAM_ERROR.
+*/
+
+ZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...));
+/*
+     Converts, formats, and writes the arguments to the compressed file under
+   control of the format string, as in fprintf.  gzprintf returns the number of
+   uncompressed bytes actually written, or a negative zlib error code in case
+   of error.  The number of uncompressed bytes written is limited to 8191, or
+   one less than the buffer size given to gzbuffer().  The caller should assure
+   that this limit is not exceeded.  If it is exceeded, then gzprintf() will
+   return an error (0) with nothing written.  In this case, there may also be a
+   buffer overflow with unpredictable consequences, which is possible only if
+   zlib was compiled with the insecure functions sprintf() or vsprintf()
+   because the secure snprintf() or vsnprintf() functions were not available.
+   This can be determined using zlibCompileFlags().
+*/
+
+ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
+/*
+     Writes the given null-terminated string to the compressed file, excluding
+   the terminating null character.
+
+     gzputs returns the number of characters written, or -1 in case of error.
+*/
+
+ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
+/*
+     Reads bytes from the compressed file until len-1 characters are read, or a
+   newline character is read and transferred to buf, or an end-of-file
+   condition is encountered.  If any characters are read or if len == 1, the
+   string is terminated with a null character.  If no characters are read due
+   to an end-of-file or len < 1, then the buffer is left untouched.
+
+     gzgets returns buf which is a null-terminated string, or it returns NULL
+   for end-of-file or in case of error.  If there was an error, the contents at
+   buf are indeterminate.
+*/
+
+ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
+/*
+     Writes c, converted to an unsigned char, into the compressed file.  gzputc
+   returns the value that was written, or -1 in case of error.
+*/
+
+ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
+/*
+     Reads one byte from the compressed file.  gzgetc returns this byte or -1
+   in case of end of file or error.  This is implemented as a macro for speed.
+   As such, it does not do all of the checking the other functions do.  I.e.
+   it does not check to see if file is NULL, nor whether the structure file
+   points to has been clobbered or not.
+*/
+
+ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
+/*
+     Push one character back onto the stream to be read as the first character
+   on the next read.  At least one character of push-back is allowed.
+   gzungetc() returns the character pushed, or -1 on failure.  gzungetc() will
+   fail if c is -1, and may fail if a character has been pushed but not read
+   yet.  If gzungetc is used immediately after gzopen or gzdopen, at least the
+   output buffer size of pushed characters is allowed.  (See gzbuffer above.)
+   The pushed character will be discarded if the stream is repositioned with
+   gzseek() or gzrewind().
+*/
+
+ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
+/*
+     Flushes all pending output into the compressed file.  The parameter flush
+   is as in the deflate() function.  The return value is the zlib error number
+   (see function gzerror below).  gzflush is only permitted when writing.
+
+     If the flush parameter is Z_FINISH, the remaining data is written and the
+   gzip stream is completed in the output.  If gzwrite() is called again, a new
+   gzip stream will be started in the output.  gzread() is able to read such
+   concatenated gzip streams.
+
+     gzflush should be called only when strictly necessary because it will
+   degrade compression if called too often.
+*/
+
+/*
+ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
+                                   z_off_t offset, int whence));
+
+     Sets the starting position for the next gzread or gzwrite on the given
+   compressed file.  The offset represents a number of bytes in the
+   uncompressed data stream.  The whence parameter is defined as in lseek(2);
+   the value SEEK_END is not supported.
+
+     If the file is opened for reading, this function is emulated but can be
+   extremely slow.  If the file is opened for writing, only forward seeks are
+   supported; gzseek then compresses a sequence of zeroes up to the new
+   starting position.
+
+     gzseek returns the resulting offset location as measured in bytes from
+   the beginning of the uncompressed stream, or -1 in case of error, in
+   particular if the file is opened for writing and the new starting position
+   would be before the current position.
+*/
+
+ZEXTERN int ZEXPORT    gzrewind OF((gzFile file));
+/*
+     Rewinds the given file. This function is supported only for reading.
+
+     gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
+*/
+
+/*
+ZEXTERN z_off_t ZEXPORT    gztell OF((gzFile file));
+
+     Returns the starting position for the next gzread or gzwrite on the given
+   compressed file.  This position represents a number of bytes in the
+   uncompressed data stream, and is zero when starting, even if appending or
+   reading a gzip stream from the middle of a file using gzdopen().
+
+     gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
+*/
+
+/*
+ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file));
+
+     Returns the current offset in the file being read or written.  This offset
+   includes the count of bytes that precede the gzip stream, for example when
+   appending or when using gzdopen() for reading.  When reading, the offset
+   does not include as yet unused buffered input.  This information can be used
+   for a progress indicator.  On error, gzoffset() returns -1.
+*/
+
+ZEXTERN int ZEXPORT gzeof OF((gzFile file));
+/*
+     Returns true (1) if the end-of-file indicator has been set while reading,
+   false (0) otherwise.  Note that the end-of-file indicator is set only if the
+   read tried to go past the end of the input, but came up short.  Therefore,
+   just like feof(), gzeof() may return false even if there is no more data to
+   read, in the event that the last read request was for the exact number of
+   bytes remaining in the input file.  This will happen if the input file size
+   is an exact multiple of the buffer size.
+
+     If gzeof() returns true, then the read functions will return no more data,
+   unless the end-of-file indicator is reset by gzclearerr() and the input file
+   has grown since the previous end of file was detected.
+*/
+
+ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
+/*
+     Returns true (1) if file is being copied directly while reading, or false
+   (0) if file is a gzip stream being decompressed.
+
+     If the input file is empty, gzdirect() will return true, since the input
+   does not contain a gzip stream.
+
+     If gzdirect() is used immediately after gzopen() or gzdopen() it will
+   cause buffers to be allocated to allow reading the file to determine if it
+   is a gzip file.  Therefore if gzbuffer() is used, it should be called before
+   gzdirect().
+
+     When writing, gzdirect() returns true (1) if transparent writing was
+   requested ("wT" for the gzopen() mode), or false (0) otherwise.  (Note:
+   gzdirect() is not needed when writing.  Transparent writing must be
+   explicitly requested, so the application already knows the answer.  When
+   linking statically, using gzdirect() will include all of the zlib code for
+   gzip file reading and decompression, which may not be desired.)
+*/
+
+ZEXTERN int ZEXPORT    gzclose OF((gzFile file));
+/*
+     Flushes all pending output if necessary, closes the compressed file and
+   deallocates the (de)compression state.  Note that once file is closed, you
+   cannot call gzerror with file, since its structures have been deallocated.
+   gzclose must not be called more than once on the same file, just as free
+   must not be called more than once on the same allocation.
+
+     gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a
+   file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the
+   last read ended in the middle of a gzip stream, or Z_OK on success.
+*/
+
+ZEXTERN int ZEXPORT gzclose_r OF((gzFile file));
+ZEXTERN int ZEXPORT gzclose_w OF((gzFile file));
+/*
+     Same as gzclose(), but gzclose_r() is only for use when reading, and
+   gzclose_w() is only for use when writing or appending.  The advantage to
+   using these instead of gzclose() is that they avoid linking in zlib
+   compression or decompression code that is not used when only reading or only
+   writing respectively.  If gzclose() is used, then both compression and
+   decompression code will be included the application when linking to a static
+   zlib library.
+*/
+
+ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
+/*
+     Returns the error message for the last error which occurred on the given
+   compressed file.  errnum is set to zlib error number.  If an error occurred
+   in the file system and not in the compression library, errnum is set to
+   Z_ERRNO and the application may consult errno to get the exact error code.
+
+     The application must not modify the returned string.  Future calls to
+   this function may invalidate the previously returned string.  If file is
+   closed, then the string previously returned by gzerror will no longer be
+   available.
+
+     gzerror() should be used to distinguish errors from end-of-file for those
+   functions above that do not distinguish those cases in their return values.
+*/
+
+ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
+/*
+     Clears the error and end-of-file flags for file.  This is analogous to the
+   clearerr() function in stdio.  This is useful for continuing to read a gzip
+   file that is being written concurrently.
+*/
+
+#endif /* !Z_SOLO */
+
+                        /* checksum functions */
+
+/*
+     These functions are not related to compression but are exported
+   anyway because they might be useful in applications using the compression
+   library.
+*/
+
+ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
+/*
+     Update a running Adler-32 checksum with the bytes buf[0..len-1] and
+   return the updated checksum.  If buf is Z_NULL, this function returns the
+   required initial value for the checksum.
+
+     An Adler-32 checksum is almost as reliable as a CRC-32 but can be computed
+   much faster.
+
+   Usage example:
+
+     uLong adler = adler32(0L, Z_NULL, 0);
+
+     while (read_buffer(buffer, length) != EOF) {
+       adler = adler32(adler, buffer, length);
+     }
+     if (adler != original_adler) error();
+*/
+
+ZEXTERN uLong ZEXPORT adler32_z OF((uLong adler, const Bytef *buf,
+                                    z_size_t len));
+/*
+     Same as adler32(), but with a size_t length.
+*/
+
+/*
+ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
+                                          z_off_t len2));
+
+     Combine two Adler-32 checksums into one.  For two sequences of bytes, seq1
+   and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
+   each, adler1 and adler2.  adler32_combine() returns the Adler-32 checksum of
+   seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.  Note
+   that the z_off_t type (like off_t) is a signed integer.  If len2 is
+   negative, the result has no meaning or utility.
+*/
+
+ZEXTERN uLong ZEXPORT crc32   OF((uLong crc, const Bytef *buf, uInt len));
+/*
+     Update a running CRC-32 with the bytes buf[0..len-1] and return the
+   updated CRC-32.  If buf is Z_NULL, this function returns the required
+   initial value for the crc.  Pre- and post-conditioning (one's complement) is
+   performed within this function so it shouldn't be done by the application.
+
+   Usage example:
+
+     uLong crc = crc32(0L, Z_NULL, 0);
+
+     while (read_buffer(buffer, length) != EOF) {
+       crc = crc32(crc, buffer, length);
+     }
+     if (crc != original_crc) error();
+*/
+
+ZEXTERN uLong ZEXPORT crc32_z OF((uLong adler, const Bytef *buf,
+                                  z_size_t len));
+/*
+     Same as crc32(), but with a size_t length.
+*/
+
+/*
+ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
+
+     Combine two CRC-32 check values into one.  For two sequences of bytes,
+   seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
+   calculated for each, crc1 and crc2.  crc32_combine() returns the CRC-32
+   check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
+   len2.
+*/
+
+
+                        /* various hacks, don't look :) */
+
+/* deflateInit and inflateInit are macros to allow checking the zlib version
+ * and the compiler's view of z_stream:
+ */
+ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
+                                     const char *version, int stream_size));
+ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
+                                     const char *version, int stream_size));
+ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int  level, int  method,
+                                      int windowBits, int memLevel,
+                                      int strategy, const char *version,
+                                      int stream_size));
+ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int  windowBits,
+                                      const char *version, int stream_size));
+ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
+                                         unsigned char FAR *window,
+                                         const char *version,
+                                         int stream_size));
+#ifdef Z_PREFIX_SET
+#  define z_deflateInit(strm, level) \
+          deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream))
+#  define z_inflateInit(strm) \
+          inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream))
+#  define z_deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
+          deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
+                        (strategy), ZLIB_VERSION, (int)sizeof(z_stream))
+#  define z_inflateInit2(strm, windowBits) \
+          inflateInit2_((strm), (windowBits), ZLIB_VERSION, \
+                        (int)sizeof(z_stream))
+#  define z_inflateBackInit(strm, windowBits, window) \
+          inflateBackInit_((strm), (windowBits), (window), \
+                           ZLIB_VERSION, (int)sizeof(z_stream))
+#else
+#  define deflateInit(strm, level) \
+          deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream))
+#  define inflateInit(strm) \
+          inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream))
+#  define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
+          deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
+                        (strategy), ZLIB_VERSION, (int)sizeof(z_stream))
+#  define inflateInit2(strm, windowBits) \
+          inflateInit2_((strm), (windowBits), ZLIB_VERSION, \
+                        (int)sizeof(z_stream))
+#  define inflateBackInit(strm, windowBits, window) \
+          inflateBackInit_((strm), (windowBits), (window), \
+                           ZLIB_VERSION, (int)sizeof(z_stream))
+#endif
+
+#ifndef Z_SOLO
+
+/* gzgetc() macro and its supporting function and exposed data structure.  Note
+ * that the real internal state is much larger than the exposed structure.
+ * This abbreviated structure exposes just enough for the gzgetc() macro.  The
+ * user should not mess with these exposed elements, since their names or
+ * behavior could change in the future, perhaps even capriciously.  They can
+ * only be used by the gzgetc() macro.  You have been warned.
+ */
+struct gzFile_s {
+    unsigned have;
+    unsigned char *next;
+    z_off64_t pos;
+};
+ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file));  /* backward compatibility */
+#ifdef Z_PREFIX_SET
+#  undef z_gzgetc
+#  define z_gzgetc(g) \
+          ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g))
+#else
+#  define gzgetc(g) \
+          ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g))
+#endif
+
+/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or
+ * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if
+ * both are true, the application gets the *64 functions, and the regular
+ * functions are changed to 64 bits) -- in case these are set on systems
+ * without large file support, _LFS64_LARGEFILE must also be true
+ */
+#ifdef Z_LARGE64
+   ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));
+   ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));
+   ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile));
+   ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile));
+   ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t));
+   ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t));
+#endif
+
+#if !defined(ZLIB_INTERNAL) && defined(Z_WANT64)
+#  ifdef Z_PREFIX_SET
+#    define z_gzopen z_gzopen64
+#    define z_gzseek z_gzseek64
+#    define z_gztell z_gztell64
+#    define z_gzoffset z_gzoffset64
+#    define z_adler32_combine z_adler32_combine64
+#    define z_crc32_combine z_crc32_combine64
+#  else
+#    define gzopen gzopen64
+#    define gzseek gzseek64
+#    define gztell gztell64
+#    define gzoffset gzoffset64
+#    define adler32_combine adler32_combine64
+#    define crc32_combine crc32_combine64
+#  endif
+#  ifndef Z_LARGE64
+     ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));
+     ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int));
+     ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile));
+     ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile));
+     ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t));
+     ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t));
+#  endif
+#else
+   ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *));
+   ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int));
+   ZEXTERN z_off_t ZEXPORT gztell OF((gzFile));
+   ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile));
+   ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t));
+   ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t));
+#endif
+
+#else /* Z_SOLO */
+
+   ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t));
+   ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t));
+
+#endif /* !Z_SOLO */
+
+/* undocumented functions */
+ZEXTERN const char   * ZEXPORT zError           OF((int));
+ZEXTERN int            ZEXPORT inflateSyncPoint OF((z_streamp));
+ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table    OF((void));
+ZEXTERN int            ZEXPORT inflateUndermine OF((z_streamp, int));
+ZEXTERN int            ZEXPORT inflateValidate OF((z_streamp, int));
+ZEXTERN unsigned long  ZEXPORT inflateCodesUsed OF ((z_streamp));
+ZEXTERN int            ZEXPORT inflateResetKeep OF((z_streamp));
+ZEXTERN int            ZEXPORT deflateResetKeep OF((z_streamp));
+#if (defined(_WIN32) || defined(__CYGWIN__)) && !defined(Z_SOLO)
+ZEXTERN gzFile         ZEXPORT gzopen_w OF((const wchar_t *path,
+                                            const char *mode));
+#endif
+#if defined(STDC) || defined(Z_HAVE_STDARG_H)
+#  ifndef Z_SOLO
+ZEXTERN int            ZEXPORTVA gzvprintf Z_ARG((gzFile file,
+                                                  const char *format,
+                                                  va_list va));
+#  endif
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ZLIB_H */
+

--- /dev/null
+++ b/src/in_xsf_framework/zlib/zutil.c
@@ -1,1 +1,326 @@
-
+/* zutil.c -- target dependent utility functions for the compression library
+ * Copyright (C) 1995-2017 Jean-loup Gailly
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* @(#) $Id$ */
+
+#include "zutil.h"
+#ifndef Z_SOLO
+#  include "gzguts.h"
+#endif
+
+z_const char * const z_errmsg[10] = {
+    (z_const char *)"need dictionary",     /* Z_NEED_DICT       2  */
+    (z_const char *)"stream end",          /* Z_STREAM_END      1  */
+    (z_const char *)"",                    /* Z_OK              0  */
+    (z_const char *)"file error",          /* Z_ERRNO         (-1) */
+    (z_const char *)"stream error",        /* Z_STREAM_ERROR  (-2) */
+    (z_const char *)"data error",          /* Z_DATA_ERROR    (-3) */
+    (z_const char *)"insufficient memory", /* Z_MEM_ERROR     (-4) */
+    (z_const char *)"buffer error",        /* Z_BUF_ERROR     (-5) */
+    (z_const char *)"incompatible version",/* Z_VERSION_ERROR (-6) */
+    (z_const char *)""
+};
+
+
+const char * ZEXPORT zlibVersion()
+{
+    return ZLIB_VERSION;
+}
+
+uLong ZEXPORT zlibCompileFlags()
+{
+    uLong flags;
+
+    flags = 0;
+    switch ((int)(sizeof(uInt))) {
+    case 2:     break;
+    case 4:     flags += 1;     break;
+    case 8:     flags += 2;     break;
+    default:    flags += 3;
+    }
+    switch ((int)(sizeof(uLong))) {
+    case 2:     break;
+    case 4:     flags += 1 << 2;        break;
+    case 8:     flags += 2 << 2;        break;
+    default:    flags += 3 << 2;
+    }
+    switch ((int)(sizeof(voidpf))) {
+    case 2:     break;
+    case 4:     flags += 1 << 4;        break;
+    case 8:     flags += 2 << 4;        break;
+    default:    flags += 3 << 4;
+    }
+    switch ((int)(sizeof(z_off_t))) {
+    case 2:     break;
+    case 4:     flags += 1 << 6;        break;
+    case 8:     flags += 2 << 6;        break;
+    default:    flags += 3 << 6;
+    }
+#ifdef ZLIB_DEBUG
+    flags += 1 << 8;
+#endif
+#if defined(ASMV) || defined(ASMINF)
+    flags += 1 << 9;
+#endif
+#ifdef ZLIB_WINAPI
+    flags += 1 << 10;
+#endif
+#ifdef BUILDFIXED
+    flags += 1 << 12;
+#endif
+#ifdef DYNAMIC_CRC_TABLE
+    flags += 1 << 13;
+#endif
+#ifdef NO_GZCOMPRESS
+    flags += 1L << 16;
+#endif
+#ifdef NO_GZIP
+    flags += 1L << 17;
+#endif
+#ifdef PKZIP_BUG_WORKAROUND
+    flags += 1L << 20;
+#endif
+#ifdef FASTEST
+    flags += 1L << 21;
+#endif
+#if defined(STDC) || defined(Z_HAVE_STDARG_H)
+#  ifdef NO_vsnprintf
+    flags += 1L << 25;
+#    ifdef HAS_vsprintf_void
+    flags += 1L << 26;
+#    endif
+#  else
+#    ifdef HAS_vsnprintf_void
+    flags += 1L << 26;
+#    endif
+#  endif
+#else
+    flags += 1L << 24;
+#  ifdef NO_snprintf
+    flags += 1L << 25;
+#    ifdef HAS_sprintf_void
+    flags += 1L << 26;
+#    endif
+#  else
+#    ifdef HAS_snprintf_void
+    flags += 1L << 26;
+#    endif
+#  endif
+#endif
+    return flags;
+}
+
+#ifdef ZLIB_DEBUG
+#include <stdlib.h>
+#  ifndef verbose
+#    define verbose 0
+#  endif
+int ZLIB_INTERNAL z_verbose = verbose;
+
+void ZLIB_INTERNAL z_error (m)
+    char *m;
+{
+    fprintf(stderr, "%s\n", m);
+    exit(1);
+}
+#endif
+
+/* exported to allow conversion of error code to string for compress() and
+ * uncompress()
+ */
+const char * ZEXPORT zError(err)
+    int err;
+{
+    return ERR_MSG(err);
+}
+
+#if defined(_WIN32_WCE)
+    /* The Microsoft C Run-Time Library for Windows CE doesn't have
+     * errno.  We define it as a global variable to simplify porting.
+     * Its value is always 0 and should not be used.
+     */
+    int errno = 0;
+#endif
+
+#ifndef HAVE_MEMCPY
+
+void ZLIB_INTERNAL zmemcpy(dest, source, len)
+    Bytef* dest;
+    const Bytef* source;
+    uInt  len;
+{
+    if (len == 0) return;
+    do {
+        *dest++ = *source++; /* ??? to be unrolled */
+    } while (--len != 0);
+}
+
+int ZLIB_INTERNAL zmemcmp(s1, s2, len)
+    const Bytef* s1;
+    const Bytef* s2;
+    uInt  len;
+{
+    uInt j;
+
+    for (j = 0; j < len; j++) {
+        if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
+    }
+    return 0;
+}
+
+void ZLIB_INTERNAL zmemzero(dest, len)
+    Bytef* dest;
+    uInt  len;
+{
+    if (len == 0) return;
+    do {
+        *dest++ = 0;  /* ??? to be unrolled */
+    } while (--len != 0);
+}
+#endif
+
+#ifndef Z_SOLO
+
+#ifdef SYS16BIT
+
+#ifdef __TURBOC__
+/* Turbo C in 16-bit mode */
+
+#  define MY_ZCALLOC
+
+/* Turbo C malloc() does not allow dynamic allocation of 64K bytes
+ * and farmalloc(64K) returns a pointer with an offset of 8, so we
+ * must fix the pointer. Warning: the pointer must be put back to its
+ * original form in order to free it, use zcfree().
+ */
+
+#define MAX_PTR 10
+/* 10*64K = 640K */
+
+local int next_ptr = 0;
+
+typedef struct ptr_table_s {
+    voidpf org_ptr;
+    voidpf new_ptr;
+} ptr_table;
+
+local ptr_table table[MAX_PTR];
+/* This table is used to remember the original form of pointers
+ * to large buffers (64K). Such pointers are normalized with a zero offset.
+ * Since MSDOS is not a preemptive multitasking OS, this table is not
+ * protected from concurrent access. This hack doesn't work anyway on
+ * a protected system like OS/2. Use Microsoft C instead.
+ */
+
+voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size)
+{
+    voidpf buf;
+    ulg bsize = (ulg)items*size;
+
+    (void)opaque;
+
+    /* If we allocate less than 65520 bytes, we assume that farmalloc
+     * will return a usable pointer which doesn't have to be normalized.
+     */
+    if (bsize < 65520L) {
+        buf = farmalloc(bsize);
+        if (*(ush*)&buf != 0) return buf;
+    } else {
+        buf = farmalloc(bsize + 16L);
+    }
+    if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
+    table[next_ptr].org_ptr = buf;
+
+    /* Normalize the pointer to seg:0 */
+    *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
+    *(ush*)&buf = 0;
+    table[next_ptr++].new_ptr = buf;
+    return buf;
+}
+
+void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr)
+{
+    int n;
+
+    (void)opaque;
+
+    if (*(ush*)&ptr != 0) { /* object < 64K */
+        farfree(ptr);
+        return;
+    }
+    /* Find the original pointer */
+    for (n = 0; n < next_ptr; n++) {
+        if (ptr != table[n].new_ptr) continue;
+
+        farfree(table[n].org_ptr);
+        while (++n < next_ptr) {
+            table[n-1] = table[n];
+        }
+        next_ptr--;
+        return;
+    }
+    Assert(0, "zcfree: ptr not found");
+}
+
+#endif /* __TURBOC__ */
+
+
+#ifdef M_I86
+/* Microsoft C in 16-bit mode */
+
+#  define MY_ZCALLOC
+
+#if (!defined(_MSC_VER) || (_MSC_VER <= 600))
+#  define _halloc  halloc
+#  define _hfree   hfree
+#endif
+
+voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, uInt items, uInt size)
+{
+    (void)opaque;
+    return _halloc((long)items, size);
+}
+
+void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr)
+{
+    (void)opaque;
+    _hfree(ptr);
+}
+
+#endif /* M_I86 */
+
+#endif /* SYS16BIT */
+
+
+#ifndef MY_ZCALLOC /* Any system without a special alloc function */
+
+#ifndef STDC
+extern voidp  malloc OF((uInt size));
+extern voidp  calloc OF((uInt items, uInt size));
+extern void   free   OF((voidpf ptr));
+#endif
+
+voidpf ZLIB_INTERNAL zcalloc (opaque, items, size)
+    voidpf opaque;
+    unsigned items;
+    unsigned size;
+{
+    (void)opaque;
+    return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
+                              (voidpf)calloc(items, size);
+}
+
+void ZLIB_INTERNAL zcfree (opaque, ptr)
+    voidpf opaque;
+    voidpf ptr;
+{
+    (void)opaque;
+    free(ptr);
+}
+
+#endif /* MY_ZCALLOC */
+
+#endif /* !Z_SOLO */
+

--- /dev/null
+++ b/src/in_xsf_framework/zlib/zutil.h
@@ -1,1 +1,272 @@
-
+/* zutil.h -- internal interface and configuration of the compression library
+ * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+   part of the implementation of the compression library and is
+   subject to change. Applications should only use zlib.h.
+ */
+
+/* @(#) $Id$ */
+
+#ifndef ZUTIL_H
+#define ZUTIL_H
+
+#ifdef HAVE_HIDDEN
+#  define ZLIB_INTERNAL __attribute__((visibility ("hidden")))
+#else
+#  define ZLIB_INTERNAL
+#endif
+
+#include "zlib.h"
+
+#if defined(STDC) && !defined(Z_SOLO)
+#  if !(defined(_WIN32_WCE) && defined(_MSC_VER))
+#    include <stddef.h>
+#  endif
+#  include <string.h>
+#  include <stdlib.h>
+#endif
+
+#ifdef Z_SOLO
+   typedef long ptrdiff_t;  /* guess -- will be caught if guess is wrong */
+#endif
+
+#ifndef local
+#  define local static
+#endif
+/* since "static" is used to mean two completely different things in C, we
+   define "local" for the non-static meaning of "static", for readability
+   (compile with -Dlocal if your debugger can't find static symbols) */
+
+typedef unsigned char  uch;
+typedef uch FAR uchf;
+typedef unsigned short ush;
+typedef ush FAR ushf;
+typedef unsigned long  ulg;
+
+extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
+/* (size given to avoid silly warnings with Visual C++) */
+
+#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
+
+#define ERR_RETURN(strm,err) \
+  return (strm->msg = ERR_MSG(err), (err))
+/* To be used only when the state is known to be valid */
+
+        /* common constants */
+
+#ifndef DEF_WBITS
+#  define DEF_WBITS MAX_WBITS
+#endif
+/* default windowBits for decompression. MAX_WBITS is for compression only */
+
+#if MAX_MEM_LEVEL >= 8
+#  define DEF_MEM_LEVEL 8
+#else
+#  define DEF_MEM_LEVEL  MAX_MEM_LEVEL
+#endif
+/* default memLevel */
+
+#define STORED_BLOCK 0
+#define STATIC_TREES 1
+#define DYN_TREES    2
+/* The three kinds of block type */
+
+#define MIN_MATCH  3
+#define MAX_MATCH  258
+/* The minimum and maximum match lengths */
+
+#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
+
+        /* target dependencies */
+
+#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
+#  define OS_CODE  0x00
+#  ifndef Z_SOLO
+#    if defined(__TURBOC__) || defined(__BORLANDC__)
+#      if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
+         /* Allow compilation with ANSI keywords only enabled */
+         void _Cdecl farfree( void *block );
+         void *_Cdecl farmalloc( unsigned long nbytes );
+#      else
+#        include <alloc.h>
+#      endif
+#    else /* MSC or DJGPP */
+#      include <malloc.h>
+#    endif
+#  endif
+#endif
+
+#ifdef AMIGA
+#  define OS_CODE  1
+#endif
+
+#if defined(VAXC) || defined(VMS)
+#  define OS_CODE  2
+#  define F_OPEN(name, mode) \
+     fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
+#endif
+
+#ifdef __370__
+#  if __TARGET_LIB__ < 0x20000000
+#    define OS_CODE 4
+#  elif __TARGET_LIB__ < 0x40000000
+#    define OS_CODE 11
+#  else
+#    define OS_CODE 8
+#  endif
+#endif
+
+#if defined(ATARI) || defined(atarist)
+#  define OS_CODE  5
+#endif
+
+#ifdef OS2
+#  define OS_CODE  6
+#  if defined(M_I86) && !defined(Z_SOLO)
+#    include <malloc.h>
+#  endif
+#endif
+
+#if defined(MACOS) || defined(TARGET_OS_MAC)
+#  define OS_CODE  7
+#  ifndef Z_SOLO
+#    if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
+#      include <unix.h> /* for fdopen */
+#    else
+#      ifndef fdopen
+#        define fdopen(fd,mode) NULL /* No fdopen() */
+#      endif
+#    endif
+#  endif
+#endif
+
+#ifdef __acorn
+#  define OS_CODE 13
+#endif
+
+#if defined(WIN32) && !defined(__CYGWIN__)
+#  define OS_CODE  10
+#endif
+
+#ifdef _BEOS_
+#  define OS_CODE  16
+#endif
+
+#ifdef __TOS_OS400__
+#  define OS_CODE 18
+#endif
+
+#ifdef __APPLE__
+#  define OS_CODE 19
+#endif
+
+#if defined(_BEOS_) || defined(RISCOS)
+#  define fdopen(fd,mode) NULL /* No fdopen() */
+#endif
+
+#if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX
+#  if defined(_WIN32_WCE)
+#    define fdopen(fd,mode) NULL /* No fdopen() */
+#    ifndef _PTRDIFF_T_DEFINED
+       typedef int ptrdiff_t;
+#      define _PTRDIFF_T_DEFINED
+#    endif
+#  else
+#    define fdopen(fd,type)  _fdopen(fd,type)
+#  endif
+#endif
+
+#if defined(__BORLANDC__) && !defined(MSDOS)
+  #pragma warn -8004
+  #pragma warn -8008
+  #pragma warn -8066
+#endif
+
+/* provide prototypes for these when building zlib without LFS */
+#if !defined(_WIN32) && \
+    (!defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0)
+    ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t));
+    ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t));
+#endif
+
+        /* common defaults */
+
+#ifndef OS_CODE
+#  define OS_CODE  3     /* assume Unix */
+#endif
+
+#ifndef F_OPEN
+#  define F_OPEN(name, mode) fopen((name), (mode))
+#endif
+
+         /* functions */
+
+#if defined(pyr) || defined(Z_SOLO)
+#  define NO_MEMCPY
+#endif
+#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
+ /* Use our own functions for small and medium model with MSC <= 5.0.
+  * You may have to use the same strategy for Borland C (untested).
+  * The __SC__ check is for Symantec.
+  */
+#  define NO_MEMCPY
+#endif
+#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
+#  define HAVE_MEMCPY
+#endif
+#ifdef HAVE_MEMCPY
+#  ifdef SMALL_MEDIUM /* MSDOS small or medium model */
+#    define zmemcpy _fmemcpy
+#    define zmemcmp _fmemcmp
+#    define zmemzero(dest, len) _fmemset(dest, 0, len)
+#  else
+#    define zmemcpy memcpy
+#    define zmemcmp memcmp
+#    define zmemzero(dest, len) memset(dest, 0, len)
+#  endif
+#else
+   void ZLIB_INTERNAL zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
+   int ZLIB_INTERNAL zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
+   void ZLIB_INTERNAL zmemzero OF((Bytef* dest, uInt len));
+#endif
+
+/* Diagnostic functions */
+#ifdef ZLIB_DEBUG
+#  include <stdio.h>
+   extern int ZLIB_INTERNAL z_verbose;
+   extern void ZLIB_INTERNAL z_error OF((char *m));
+#  define Assert(cond,msg) {if(!(cond)) z_error(msg);}
+#  define Trace(x) {if (z_verbose>=0) fprintf x ;}
+#  define Tracev(x) {if (z_verbose>0) fprintf x ;}
+#  define Tracevv(x) {if (z_verbose>1) fprintf x ;}
+#  define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
+#  define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
+#else
+#  define Assert(cond,msg)
+#  define Trace(x)
+#  define Tracev(x)
+#  define Tracevv(x)
+#  define Tracec(c,x)
+#  define Tracecv(c,x)
+#endif
+
+#ifndef Z_SOLO
+   voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items,
+                                    unsigned size));
+   void ZLIB_INTERNAL zcfree  OF((voidpf opaque, voidpf ptr));
+#endif
+
+#define ZALLOC(strm, items, size) \
+           (*((strm)->zalloc))((strm)->opaque, (items), (size))
+#define ZFREE(strm, addr)  (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
+#define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
+
+/* Reverse the bytes in a 32-bit value */
+#define ZSWAP32(q) ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
+                    (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
+
+#endif /* ZUTIL_H */
+